File size: 69,568 Bytes
8e4085d
9305a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361120d
9305a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88a1fc6
 
 
 
 
361120d
 
 
 
 
 
9305a6d
 
044ac85
361120d
044ac85
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
 
 
 
 
 
 
 
 
 
361120d
 
044ac85
9305a6d
 
 
 
 
 
361120d
9305a6d
 
 
 
 
 
 
 
 
361120d
 
 
 
9305a6d
 
88a1fc6
9305a6d
 
88a1fc6
 
 
9305a6d
 
 
 
 
 
 
 
 
 
361120d
9305a6d
044ac85
361120d
 
 
 
 
 
 
 
9305a6d
 
 
 
 
 
 
 
 
 
361120d
 
 
 
 
 
 
9305a6d
 
 
 
 
 
 
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
361120d
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
 
 
 
 
 
 
 
 
 
 
 
361120d
9305a6d
044ac85
 
 
 
361120d
044ac85
 
361120d
 
044ac85
 
 
 
361120d
044ac85
361120d
044ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361120d
044ac85
 
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
044ac85
361120d
044ac85
 
361120d
 
 
 
 
044ac85
 
 
 
 
 
361120d
044ac85
361120d
 
 
044ac85
 
 
 
 
361120d
 
 
 
 
 
 
 
 
 
 
 
 
044ac85
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
044ac85
361120d
044ac85
 
 
 
 
361120d
044ac85
 
 
361120d
044ac85
 
 
 
 
 
88a1fc6
044ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
044ac85
 
9305a6d
 
361120d
 
 
7eb996b
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eb996b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
 
 
 
 
7eb996b
 
 
 
 
044ac85
 
7eb996b
044ac85
7eb996b
044ac85
 
9305a6d
 
 
044ac85
 
9305a6d
 
 
 
 
 
 
 
 
7eb996b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361120d
 
7eb996b
361120d
7eb996b
 
 
 
 
 
 
 
361120d
 
 
 
9305a6d
 
 
 
 
 
 
 
 
 
044ac85
 
 
 
 
 
 
 
361120d
044ac85
 
 
361120d
044ac85
 
 
 
 
 
 
9305a6d
 
 
361120d
 
 
9305a6d
361120d
 
9305a6d
 
 
361120d
9305a6d
 
 
361120d
9305a6d
 
 
 
361120d
9305a6d
 
 
 
 
 
 
 
 
 
 
 
361120d
9305a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7eb996b
9305a6d
 
 
7eb996b
 
 
 
 
9305a6d
7eb996b
9305a6d
 
 
 
 
 
 
 
 
 
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
361120d
9305a6d
 
361120d
 
 
9305a6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361120d
 
 
 
 
 
 
9305a6d
88a1fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
 
 
 
044ac85
 
 
9305a6d
 
 
 
 
 
 
361120d
9305a6d
 
361120d
 
 
9305a6d
 
 
 
361120d
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
361120d
9305a6d
 
361120d
9305a6d
 
 
 
361120d
 
 
9305a6d
361120d
 
 
 
 
9305a6d
361120d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9305a6d
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ルビメーカー | MOSS-Image</title>
<style>
:root{color-scheme:light;--bg:#f4f1eb;--ink:#26231f;--sub:#666158;--line:#cfc7bc;--surface:#fffdf9;--accent:#863b35;--button:#853931;--on:#fff;--chip:#eee8df}
:root[data-theme=dark]{color-scheme:dark;--bg:#202121;--ink:#f4ede3;--sub:#c3bbb0;--line:#56524e;--surface:#2a2a29;--accent:#f0a798;--button:#dc9a87;--on:#261a16;--chip:#383634}
*{box-sizing:border-box} [hidden]{display:none!important}
body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 "Yu Gothic UI",Meiryo,sans-serif}
main{max-width:1360px;margin:auto;padding:24px clamp(16px,4vw,64px) 48px}
header,.bar,.tools,.symbols,.row,.checks,.pal,.actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
header,.bar{justify-content:space-between}
header{padding-bottom:16px;border-bottom:2px solid var(--ink)}
.brand{display:flex;align-items:baseline;gap:16px;flex-wrap:wrap}
.brand span{font:650 14px/1.2 "Segoe UI",sans-serif;letter-spacing:.04em;color:var(--accent)}
h1{margin:0;font:700 clamp(28px,3.4vw,44px)/1.2 "Yu Mincho",serif}
h2,legend,summary{font-size:16px;font-weight:700;margin:0;padding:0}
.presets{padding:16px 0 20px;border-bottom:1px solid var(--line)}
.preset-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:8px;margin-top:8px}
button,input,select,textarea{color:inherit;font:inherit}
button,select,input[type=range],summary{cursor:pointer}
button,.chip{background:var(--surface);border:1px solid var(--line);border-radius:6px}
button{padding:6px 12px;font-weight:600}
button:hover,.chip:hover{border-color:var(--accent)}
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
.preset{padding:0;overflow:hidden;text-align:left}
.preset[aria-pressed=true]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}
.preset span{display:block;padding:5px 8px;font-size:12px}
.preset[aria-pressed=true] span::after{content:" ✓";color:var(--accent)}
.preset canvas{display:block;width:100%;height:53px}
.workspace{display:grid;grid-template-columns:minmax(300px,.86fr) minmax(0,1.4fr);gap:clamp(18px,3vw,44px);align-items:start;padding-top:18px}
fieldset,details{min-width:0;margin:0 0 17px;padding:0 0 16px;border:0;border-bottom:1px solid var(--line)}
legend,summary{margin-bottom:9px}
.fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 12px}
label,.field{display:grid;align-content:start;gap:4px;font-size:13px;font-weight:650}
.full{grid-column:1/-1}.results{min-width:0;position:sticky;top:10px}
input[type=text],input[type=number],select,textarea{min-width:0;width:100%;padding:7px 9px;background:var(--surface);border:1px solid var(--line);border-radius:5px}
input,select{accent-color:var(--button)} input[type=range]{margin:3px 0;width:100%}
.tools label,.row label,.checks label,.check,.range-label{display:flex;align-items:center;gap:5px}
.tools select,.row select{width:auto}.tools label,.hint{color:var(--sub);font-weight:450;font-size:12px}
.range-label{justify-content:space-between} output{color:var(--accent);font:600 13px Consolas,monospace}
.chip{padding:5px 8px}.chip:has(input:checked){border-color:var(--accent);color:var(--accent)}
.checks{gap:6px}.checks input,.check input{margin:0}
.bar{margin-bottom:9px}.stage{border:1px solid var(--line);overflow:hidden;border-radius:8px;background:var(--chip)}
#preview{display:block;width:100%;height:clamp(220px,24vw,315px)}
.hint,.error{margin:6px 0}.error{color:var(--accent);font-size:13px;font-weight:650}
.prompt{margin-top:18px}.actions{margin-top:8px}
.primary{background:var(--button);color:var(--on);border-color:var(--button);padding:8px 16px}
button:disabled{opacity:.45;cursor:default} textarea{resize:vertical;min-height:118px;font:14px/1.6 "Segoe UI",Meiryo,sans-serif}
#notice{font-size:13px}.symbols{gap:5px}.symbols button{min-width:34px;padding:3px 6px;font-size:17px}
#emojiList{margin:0;padding:0;border:0}
#emojiList summary{width:fit-content;cursor:pointer;font-size:14px}
#emojiList h3{margin:12px 0 5px;font-size:13px;color:var(--sub)}
#emojiList .symbols{display:grid;grid-template-columns:repeat(auto-fill,minmax(34px,1fr))}
#emojiList button{padding:3px 0}
.color-choice summary{display:flex;align-items:center;gap:6px;font-size:12px;padding:5px 7px;text-align:left}
.color-choice summary::before{content:"";display:inline-block;flex:none;width:15px;height:15px;border-radius:50%;background:var(--sample);border:1px solid #8889}
.color-choice,.more-colors{padding:4px 0;margin:0;border:0}.color-choice summary,.more-colors summary{font-size:13px;margin:4px 0}.color-choice summary{width:fit-content;border:1px solid var(--line);border-radius:5px}.color-choice summary::after{content:"▾"}
.color-choice[open]{grid-column:1/-1}.more-colors h4{font-size:12px;margin:10px 0 4px}.full button{overflow-wrap:anywhere}
#gradientControls{display:grid;grid-template-columns:1fr 1fr;gap:8px}.color-presets{display:flex;gap:5px;flex-wrap:wrap}.color-presets button{font-size:12px}
#styleSamples canvas{width:100%;height:48px;display:block;background:white;border-radius:4px}#styleSamples button{padding:4px}.style-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px}
@media(max-width:800px){.workspace{grid-template-columns:minmax(0,1fr)}.results{position:static}.preset-grid{grid-template-columns:repeat(3,minmax(0,1fr))}main{padding-top:15px}.brand{gap:7px}.tools{gap:4px}}
@media(max-height:650px){.results{position:static}}
#editor{padding:18px 16px;min-height:118px;margin:6px 0;white-space:pre-wrap;overflow-wrap:anywhere;background:var(--surface);border:1px solid var(--line);border-radius:6px;font:500 23px/2 Meiryo,sans-serif}
#editor{cursor:text} #editor ruby{white-space:nowrap;ruby-align:space-between} #editor.center ruby{ruby-align:center}
#editor rt{font-size:var(--ruby-size, .5em);line-height:1;user-select:none}
#rubyBox{position:fixed;z-index:5;width:min(650px,calc(100vw - 16px));height:min(408px,calc(100dvh - 16px));display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--line);border-radius:9px;box-shadow:0 6px 26px #0003;overflow:hidden}
.edit-head,.edit-line,.edit-sections,.edit-body{padding:8px 12px}
.edit-head,.edit-line,.edit-sections{flex:none;display:flex;align-items:center;gap:8px;border-bottom:1px solid var(--line)}
.edit-head strong{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.edit-head button,.edit-line button,.edit-sections button{white-space:nowrap}
.edit-line label{flex:1;min-width:0}.edit-line #removeRuby{font-size:12px;padding:5px}.edit-line #localSample{width:18%;height:48px;border:1px solid var(--line);border-radius:5px}
.edit-sections{gap:4px;padding-block:5px}.edit-sections button{flex:1;padding:5px 4px;border-color:transparent;background:transparent}
.edit-sections button[aria-pressed=true]{background:var(--chip);border-color:var(--line);color:var(--accent)}
.edit-body{flex:1;min-height:0;overflow:auto;overscroll-behavior:contain}
.edit-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px 12px}
.edit-color-line{display:flex;align-items:center;gap:8px;margin-bottom:5px}.edit-color-line select{width:auto}.edit-color-line button,.edit-ops button{padding:4px 8px;font-size:12px}
.edit-ops{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}
.swatch-groups{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:6px 10px}.swatch-groups h4{margin:0 0 3px;font-size:12px;color:var(--sub)}
.pal{display:flex;flex-wrap:wrap;gap:3px;align-content:start}
.pal button{position:relative;display:grid;place-items:center;width:25px;height:25px;padding:0;border-radius:5px;background:var(--sample);border:1px solid #80808088}
.pal button[aria-pressed=true]{outline:2px solid var(--accent);outline-offset:0}
.pal button[aria-pressed=true]::after{margin:0;content:"✓";color:white;text-shadow:0 1px 2px black,0 0 3px black;font-size:16px}
#swatchTip{position:fixed;z-index:8;pointer-events:none;background:var(--ink);color:var(--surface);border-radius:4px;padding:3px 8px;font-size:12px}
@media(max-width:620px){.swatch-groups{grid-template-columns:repeat(2,minmax(0,1fr))}#rubyBox{height:min(480px,calc(100dvh - 16px))}.edit-fields{gap:6px}.edit-line #localSample{width:15%}}
@media(max-width:400px){.edit-head,.edit-line,.edit-body{padding-inline:8px}.edit-color-line{gap:4px}.edit-fields{grid-template-columns:repeat(2,minmax(0,1fr))}.edit-line{gap:4px}}
@media(max-width:350px){#rubyBox{height:min(524px,calc(100dvh - 16px))}}
@media(max-height:420px){.edit-line,.edit-head,.edit-sections{padding-block:3px}.edit-line #localSample{height:34px}}
@media(min-width:621px) and (max-height:420px){.edit-line label{display:flex;align-items:center;white-space:nowrap}.edit-body{padding-block:4px}.edit-color-line select,.edit-fields select{padding-block:4px}.edit-fields,.swatch-groups{row-gap:4px}}
</style>
</head>
<body><main>
<header><div class="brand"><h1>ルビメーカー</h1><span lang="en">MOSS-Image</span></div>
<div class="tools"><label>画面テーマ<select id="theme"><option value="light">ライト</option><option value="dark">ダーク</option></select></label></div></header>
<section class="presets" aria-labelledby="presetTitle"><h2 id="presetTitle">装飾見本</h2><div id="presets" class="preset-grid"></div></section>
<div class="workspace">
<section aria-label="文字の設定">
<fieldset><legend>文字と配置</legend>
<div class="fields">
<div class="full"><label id="bodyLabel">本文</label><div id="editor" role="textbox" aria-multiline="true" aria-labelledby="bodyLabel" aria-describedby="editorHelp" contenteditable="true" spellcheck="false">こんにちは、<ruby>今日<rt contenteditable="false">きょう</rt></ruby>はいい<ruby>天気<rt contenteditable="false">てんき</rt></ruby>ですね。</div>
<p id="editorHelp" class="hint">読みや装飾を付ける文字をドラッグします。設定した部分はクリックして編集できます。</p></div>
<label>ルビの配置<select id="align"><option value="spread">親文字の幅に均等配置</option><option value="center">中央にまとめる</option></select></label>
<label><span class="range-label">ルビの大きさ <output id="sizeValue" for="size">20%</output></span><input id="size" type="range" min="10" max="50" value="20"></label>
</div></fieldset>
<fieldset><legend>書体と装飾</legend>
<div class="fields">
<label>書体スタイル<select id="style"></select></label>
<label>仕上げ<select id="effect"><option value="flat">平面</option><option value="shadow">ずらし影</option><option value="depth">押し出し3D</option><option value="foil">箔押し</option><option value="emboss">型押し</option><option value="neon">ネオン</option></select></label>
<details id="styleSamples" class="full"><summary>本文で書体を見比べる</summary><div class="style-grid"></div></details>
<div class="checks full" aria-label="文字修飾">
<label class="chip"><input type="checkbox" id="bold">太字</label><label class="chip"><input type="checkbox" id="italic">斜体</label>
<label class="chip"><input type="checkbox" id="underline">下線</label><label class="chip"><input type="checkbox" id="strike">取り消し線</label>
</div>
<label>縁取り<select id="outline"><option value="none">なし</option><option value="thin">細め</option><option value="bold">太め</option><option value="double">二重</option></select></label>
<label class="check"><input id="includeRuby" type="checkbox">装飾をルビにも適用</label>
</div></fieldset>
<fieldset><legend>配色</legend><div class="fields">
<label>変更する色<select id="target"><option value="ink">親文字</option><option value="ruby">ルビ</option><option value="edge">縁取り・内縁</option><option value="outer">外縁</option><option value="side">影・側面・発光</option></select></label>
<div class="field">選択色<span id="colorName"></span></div>
<div id="palette" class="full" role="group" aria-label="色見本"></div>
<label>塗り<select id="fill"><option value="solid">単色</option><option value="gradient">2色グラデーション</option><option value="halftone">漫画の網点</option></select></label>
<div id="gradientControls" class="full" hidden><div class="field">開始色(親文字)<div id="startPicker"></div></div><div class="field">終了色<div id="endPicker"></div></div><label>向き<select id="direction"><option value="down">上から下</option><option value="across">左から右</option><option value="diagonal">左上から右下</option></select></label><div id="gradientPresets" class="color-presets full"></div></div>
<label class="check full"><input type="checkbox" id="linked" checked>ルビは親文字と同じ色</label>
</div></fieldset>
<details id="symbolPicker"><summary>記号・絵文字</summary><div class="fields">
<label>挿入先<select id="symbolTarget"><option value="base">親文字の中</option><option value="reading">ルビの中</option><option value="ornament">右側の飾り</option></select></label>
<label>右側の飾り<input type="text" id="ornament" placeholder="例:🔥"></label>
<div class="symbols full" id="symbols"></div>
<details class="full" id="emojiList"><summary>絵文字一覧</summary><div id="emojiGroups"></div></details>
</div></details>
</section>
<section class="results" aria-label="確認とコピー">
<div class="bar"><h2>組版プレビュー</h2><div class="tools"><label>確認用の背景<select id="paper"><option value="#ffffff">白</option><option value="#262626">墨色</option></select></label></div></div>
<div class="stage"><canvas id="preview" role="img" aria-label="文字の配置"></canvas></div>
<p class="hint">配置・配色・装飾の確認用です。MOSS-Imageで生成した画像では、文字や効果の見え方が変わります。</p>
<section class="prompt"><div class="bar"><h2 id="promptTitle">MOSS用プロンプト</h2><div class="tools"><label>出力形式<select id="format"><option value="caption">英文</option><option value="layout">Layout JSON(実験)</option></select></label></div></div>
<div id="dimensions" hidden><div class="fields"><label>生成幅(px)<input type="number" min="16" step="16" id="width" value="1024"></label><label>生成高さ(px)<input type="number" min="16" step="16" id="height" value="1024"></label></div>
<p class="hint">生成側も同じ幅・高さに設定し、JSON全体をポジティブプロンプトに貼り付けます。</p></div>
<p id="error" role="status" class="error" hidden></p>
<textarea id="prompt" lang="en" aria-labelledby="promptTitle" readonly placeholder="親文字を入力してください"></textarea>
<div class="actions"><button class="primary" id="copy" type="button">プロンプトをコピー</button><button id="copyPlain" type="button">プレーンな英文をコピー</button><span role="status" id="notice"></span></div>
</section></section></div></main>
<div id="rubyBox" role="dialog" aria-labelledby="rubyTarget" hidden>
<div class="edit-head"><strong id="rubyTarget"></strong><button type="button" id="applyRuby" class="primary">適用</button><button type="button" id="cancelRuby">閉じる</button></div>
<div class="edit-line"><label id="readingField">読み<input id="reading" type="text" placeholder="例:きょう" autocomplete="off"></label><button type="button" id="removeRuby">ルビを外す</button>
<label>装飾対象<select id="localPart"><option value="base">親文字</option><option value="ruby">ルビ</option></select></label><canvas id="localSample" aria-label="選択部分の装飾見本"></canvas></div>
<div class="edit-sections" role="group" aria-label="設定項目"><button data-pane="localPaint">配色</button><button data-pane="localType">書体・塗り</button><button data-pane="localFinish">仕上げ・操作</button></div>
<div class="edit-body"><section id="localPaint"><div class="edit-color-line"><label for="colorRole">変更する色</label><select id="colorRole"></select><button id="inheritColor">全体に戻す</button></div><div id="localSwatches" class="swatch-groups"></div></section>
<section id="localType" hidden><div class="edit-fields"></div></section>
<section id="localFinish" hidden><div class="edit-fields"></div><div class="edit-ops"><button type="button" id="copyStyle">装飾をコピー</button><button type="button" id="pasteStyle" disabled>装飾を貼り付け</button><button type="button" id="localReset">この部分を全体設定に戻す</button></div></section></div></div>
<div id="swatchTip" role="tooltip" hidden></div>
<script>
"use strict";
const el = id => document.getElementById(id);
const styles = {
  plain: ["指定なし", "", '400', 'sans-serif'],
  mincho: ["明朝", "traditional Japanese Mincho lettering with fine horizontal strokes and tapered serifs", '700', '"Yu Mincho", "MS PMincho", serif'],
  gothic: ["ゴシック", "bold Japanese Gothic lettering with clean, even strokes", '500', '"Yu Gothic", Meiryo, sans-serif'],
  round: ["丸ゴシック", "rounded Japanese Gothic lettering with soft terminals", '400', '"Hiragino Maru Gothic ProN", "BIZ UDPGothic", Meiryo, sans-serif'],
  pop: ["ポップ", "playful, chunky Japanese display lettering with plump rounded shapes", '700', '"M PLUS Rounded 1c", "Hiragino Maru Gothic ProN", Meiryo, sans-serif'],
  brush: ["筆文字", "expressive Japanese brush lettering with sweeping tapered strokes", '400', '"HGS行書体", "HG行書体", "Yu Mincho", serif'],
  pixel:["ピクセル文字","blocky pixel lettering with crisp stair-step edges","700","Meiryo, monospace"],
  led:["LED電光掲示板","dot-matrix lettering made of evenly spaced round LED lights","700","Meiryo, monospace"],
  digital:["角型デジタル","angular digital lettering with straight strokes and clipped corners","700","Meiryo, monospace"],
  segments:["液晶時計風","seven-segment display lettering with straight separated bars","600","Consolas, monospace"],
  stencil:["ステンシル","stencil lettering with narrow breaks in the strokes","700","Meiryo, sans-serif"],
  hollow:["袋文字","hollow letters drawn as clear outlines","700","Meiryo, sans-serif"],
  balloon:["バルーン文字","inflated balloon lettering with soft rounded highlights","900","Meiryo, sans-serif"],
  pen: ["手書き", "casual handwritten Japanese lettering with light, gently irregular pen strokes", '400', '"HGP教科書体", "Yu Kyokasho", "UD Digi Kyokasho N-R", "Yu Gothic", sans-serif']
};
for (const [key, spec] of Object.entries(styles)) el("style").add(new Option(spec[0], key));
const segmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter("ja", {granularity: "grapheme"}) : null;
function characters(text) {
  return segmenter ? Array.from(segmenter.segment(text), part => part.segment) : Array.from(text);
}
const colorGroups = [
  ["基本の12色", [
    ["#000000","黒","black"],
    ["#ffffff","白","white"],
    ["#ff0000","赤","red"],
    ["#ff8000","オレンジ","orange"],
    ["#ffdf00","黄","yellow"],
    ["#00a024","緑","green"],
    ["#004cff","青","blue"],
    ["#00e9ee","シアン","cyan"],
    ["#8000c8","紫","purple"],
    ["#ff00ba","マゼンタ","magenta"],
    ["#ff94bc","ピンク","pink"],
    ["#865032","茶","brown"]
  ]],
  ["鮮やか・明るい色", [
    ["#a2ef00","黄緑","lime green"],
    ["#76c8ff","空色","sky blue"],
    ["#41bcca","ターコイズ","turquoise"],
    ["#ff7967","コーラル","coral"],
    ["#ff4099","ホットピンク","hot pink"],
    ["#fff54c","レモンイエロー","lemon yellow"],
    ["#db503d","朱","vermilion"],
    ["#eaa439","山吹","amber"]
  ]],
  ["パステル", [
    ["#ffd1dc","パステルピンク","pastel pink"],
    ["#aecbfa","パステルブルー","pastel blue"],
    ["#b7edcf","ミント","mint green"],
    ["#dfc8fa","ラベンダー","lavender"],
    ["#ffcfad","ピーチ","peach"],
    ["#fff3ad","淡い黄","pale yellow"],
    ["#c7f1ea","淡い青緑","pale aqua"]
  ]],
  ["深い色", [
    ["#a41936","深紅","crimson"],
    ["#8b293e","臙脂","burgundy"],
    ["#162749","紺","navy blue"],
    ["#366b54","深緑","forest green"],
    ["#4e245d","濃紫","deep purple"],
    ["#513323","こげ茶","dark brown"],
    ["#386eac","深青","deep blue"],
    ["#714e93","菫色","violet"]
  ]],
  ["くすみ・アースカラー", [
    ["#bd5040","レンガ色","brick red"],
    ["#c67453","テラコッタ","terracotta"],
    ["#778239","オリーブ","olive green"],
    ["#9bac8a","セージ","sage green"],
    ["#e57d93","桃","rose pink"],
    ["#bf8b92","くすみローズ","dusty rose"],
    ["#b8893c","金","warm gold"],
    ["#ab792f","黄土","ochre"]
  ]],
  ["ニュートラル", [
    ["#171717","墨","near-black"],
    ["#fffff0","アイボリー","ivory"],
    ["#fff1d1","クリーム","cream"],
    ["#dfcfb8","ベージュ","beige"],
    ["#c7ccd0","薄灰","light gray"],
    ["#888888","灰","gray"],
    ["#6c7077","青灰","slate gray"],
    ["#424348","チャコール","charcoal gray"]
  ]]
];
const palette=colorGroups.flatMap(([,entries])=>entries);
const colorByHex=new Map(palette.map(entry=>[entry[0],entry]));
function namedColor(hex){
  const exact=colorByHex.get(hex.toLowerCase());
  if(exact) return exact;
  // Older selections could contain arbitrary colors. Describe the nearest swatch.
  const channels=value=>[1,3,5].map(i=>parseInt(value.slice(i,i+2),16));
  const rgb=channels(hex);
  const distance=entry=>channels(entry[0]).reduce((d,n,i)=>d+(n-rgb[i])**2,0);
  return palette.reduce((best,item)=>distance(item)<distance(best)?item:best);
}
const colorText=hex=>namedColor(hex)[2];
const defaults = {fill:"solid",gradientEnd:"#ff8000",direction:"down",style:"mincho", effect:"flat", outline:"none", ink:"#171717", ruby:"#171717", edge:"#ffffff", outer:"#171717", side:"#8b293e",
  bold:false, italic:false, underline:false, strike:false, includeRuby:false, linked:true};
const presets = [
  ["プレーン", {style:"plain"}, "#ffffff"],
  ["和文タイトル", {}, "#f7f3e9"],
  ["漫画の決め文字", {style:"brush", italic:true, bold:true, outline:"double", ink:"#db503d"}, "#f7e3c4"],
  ["ポップステッカー", {style:"pop", effect:"shadow", outline:"bold", ink:"#e57d93", side:"#714e93"}, "#f1deec"],
  ["レトロ立体ロゴ", {style:"round", bold:true, ink:"#db503d", side:"#8b293e", effect:"depth"}, "#f6deb1"],
  ["箔押し", {ink:"#b8893c", effect:"foil"}, "#312b28"],
  ["ネオンサイン", {style:"round", ink:"#41bcca", side:"#41bcca", effect:"neon"}, "#202c36"]
];
const design = {...defaults};
const flags = ["bold","italic","underline","strike","includeRuby","linked"];
const designFields = ["style","effect","outline","fill","direction",...flags];
const symbolNames = {"★":"a five-pointed star","♡":"an outline heart","♪":"a musical note","✦":"a four-pointed sparkle","→":"a right arrow","🔥":"a flame","🌸":"a cherry blossom","✨":"sparkles","🎵":"musical notes","❤️":"a red heart"};
const editor = el("editor"), rubyBox = el("rubyBox"), readingInput = el("reading");
let editing = null, lastCaret = null;
function readGroups(root) {
  const groups = [];
  function append(text, reading = "", format = null) {
    if (!text) return;
    const last = groups.at(-1);
    if (!format && !reading && last && !last.reading && !last.format) last.text += text;
    else groups.push({text, reading, format});
  }
  function visit(node) {
    if (node.nodeType === Node.TEXT_NODE) return append(node.data);
    if (node.nodeName === "RT") return;
    if (node.nodeName === "RUBY" || node.dataset?.format) {
      const base = Array.from(node.childNodes).filter(n => n.nodeName !== "RT").map(n => n.textContent).join("");
      return append(base, node.querySelector("rt")?.textContent || "", node.dataset.format ? JSON.parse(node.dataset.format) : null);
    }
    if (node.nodeName === "BR") {
      if (node.parentNode.childNodes.length > 1 || node.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) append("\n");
      return;
    }
    if (["DIV","P"].includes(node.nodeName) && node.previousSibling) append("\n");
    node.childNodes.forEach(visit);
  }
  root.childNodes.forEach(visit);
  return groups;
}
function editorRange() {
  const sel = window.getSelection();
  if (!sel.rangeCount) return null;
  const range = sel.getRangeAt(0);
  return editor.contains(range.commonAncestorContainer) ? range.cloneRange() : null;
}
function selectRange(range) {
  editor.focus({preventScroll:true});
  const sel = window.getSelection();
  sel.removeAllRanges(); sel.addRange(range);
}
function closeEditor() {
  editing = null;
  rubyBox.hidden = true;
  el("swatchTip").hidden=true;
}
function positionBox() {
  if (!editing || rubyBox.hidden) return;
  const rect=editing.selected.getBoundingClientRect(), area=editor.getBoundingClientRect();
  const w=rubyBox.offsetWidth,h=rubyBox.offsetHeight;
  const beside=area.right+8+w<=innerWidth-8;
  const x=beside?area.right+8:rect.left;
  const y=beside?area.top:rect.bottom+8+h<=innerHeight-8?rect.bottom+8:rect.top-h-8>=8?rect.top-h-8:innerHeight-h-8;
  rubyBox.style.left=Math.max(8,Math.min(x,innerWidth-w-8))+"px";
  rubyBox.style.top=Math.max(8,Math.min(y,innerHeight-h-8))+"px";
}
const wordSelector="ruby,[data-format]";
function openEditor(range, word = null) {
  const selected=range.cloneRange();
  let prefix=null, suffix=null;
  if (word) range.selectNode(word);
  else {
    for (const boundary of ["start","end"]) {
      const node=range[boundary+"Container"];
      const parent=(node.nodeType===Node.TEXT_NODE ? node.parentElement : node).closest?.(wordSelector);
      if (parent && editor.contains(parent)) {
        const outside=document.createRange();
        outside.selectNodeContents(parent);
        if(boundary==="start") outside.setEnd(node,range.startOffset);
        else outside.setStart(node,range.endOffset);
        const remainder=readGroups(outside.cloneContents()).map(g=>g.text).join("");
        const whole=readGroups(parent).map(g=>g.text).join("");
        if(remainder && remainder===whole){
          if(boundary==="start") range.setStartAfter(parent);
          else range.setEndBefore(parent);
          continue;
        }
        if(remainder && parent.tagName!=="RUBY"){
          const piece={text:remainder,format:JSON.parse(parent.dataset.format)};
          if(boundary==="start") prefix=piece;
          else suffix=piece;
        }
        if (boundary==="start") range.setStartBefore(parent);
        else range.setEndAfter(parent);
      }
    }
  }
  const groups=readGroups(range.cloneContents());
  if(prefix) groups[0].text=groups[0].text.slice(prefix.text.length);
  if(suffix) groups.at(-1).text=groups.at(-1).text.slice(0,-suffix.text.length);
  const text=groups.map(g=>g.text).join("");
  if (!text.trim() || /[\r\n]/.test(text)) return closeEditor();
  const single=groups.length===1;
  editing={range,selected,text,groups,prefix,suffix};
  el("rubyTarget").textContent="「"+text+"」を編集";
  el("rubyTarget").title=text;
  readingInput.disabled=!single;
  el("readingField").hidden=!single;
  readingInput.value=single ? groups[0].reading : "";
  el("removeRuby").hidden=!single || !groups[0].reading;
  el("applyRuby").disabled=false;
  el("localPart").value="base";
  el("colorRole").value="ink";
  rubyBox.hidden=false;
  showPane("localPaint");
  positionBox();
  syncLocalFields();
}
function pickRange(event) {
  const range=editorRange();
  if (range) lastCaret=range;
  const word=event.target.closest?.(wordSelector);
  if (range && !range.collapsed) openEditor(range);
  else if (word) openEditor(range||document.createRange(),word);
  else closeEditor();
}
editor.addEventListener("pointerup", pickRange);
editor.addEventListener("click", e => { if (e.detail===0) pickRange(e); });
editor.addEventListener("keyup", e => { if(e.shiftKey && e.key.startsWith("Arrow")) pickRange(e); });
editor.addEventListener("keydown", e => {
  if (e.isComposing || e.keyCode===229 || e.key!=="F2") return;
  const range=editorRange();
  if (!range || range.collapsed) return;
  e.preventDefault(); openEditor(range);
  if (editing) readingInput.focus();
});
editor.addEventListener("focusout", () => {
  const range = editorRange();
  if (range) lastCaret = range;
});
editor.addEventListener("beforeinput", e => {
  if (e.isComposing || !e.cancelable || !e.inputType.startsWith("delete")) return;
  const target=e.getTargetRanges?.()[0];
  if (!target) return;
  const node=target.startContainer, ruby=node.parentElement;
  if (node.nodeType!==Node.TEXT_NODE || ruby?.tagName!=="RUBY" || ruby.firstChild!==node ||
      node.nextSibling?.nodeName!=="RT" || target.endContainer!==node ||
      target.startOffset!==0 || target.endOffset!==node.length) return;
  // Remove the reading together with the last base character in the same undo step.
  e.preventDefault();
  const range=document.createRange(); range.selectNode(ruby); selectRange(range);
  document.execCommand("delete");
});
function applyReading(remove = false) {
  if (!editing) return;
  const {range,groups,prefix,suffix}=editing;
  if(groups.length===1) groups[0].reading=remove?"":readingInput.value.trim();
  const fragment=document.createElement("div");
  for(const g of [prefix,...groups,suffix].filter(Boolean)){
    const format={};
    for(const part of ["base","ruby"]){
      if(part==="ruby" && !g.reading) continue;
      if(Object.keys(g.format?.[part] || {}).length) format[part]=g.format[part];
    }
    if(!g.reading && !Object.keys(format).length){fragment.append(g.text);continue;}
    const word=document.createElement(g.reading?"ruby":"span");
    word.append(g.text);
    if(Object.keys(format).length) word.dataset.format=JSON.stringify(format);
    if(g.reading){
      const rt=document.createElement("rt"); rt.contentEditable="false"; rt.textContent=g.reading; word.append(rt);
    }
    fragment.append(word);
  }
  closeEditor(); selectRange(range);
  document.execCommand("insertHTML",false,fragment.innerHTML);
}
el("applyRuby").onclick = () => applyReading();
el("removeRuby").onclick = () => applyReading(true);
function cancelReading() {
  if (!editing) return;
  const range = editing.selected;
  closeEditor(); selectRange(range);
}
el("cancelRuby").onclick = cancelReading;
readingInput.oninput = syncLocalFields;
document.addEventListener("keydown", e => {
  if (!editing || e.isComposing || e.keyCode===229) return;
  if (e.key==="Escape") { e.preventDefault(); cancelReading(); }
  if (e.key==="Enter" && e.target===readingInput) { e.preventDefault(); applyReading(); }
});
document.addEventListener("pointerdown", e => {
  if (!rubyBox.contains(e.target) && !editor.contains(e.target) && !e.target.closest("#symbolPicker")) closeEditor();
});
window.addEventListener("scroll", e => {
  if (e.target===document || e.target.contains?.(editor)) positionBox();
},true);
window.addEventListener("resize",positionBox);
editor.oninput = closeEditor;
editor.oncopy = e => {
  const range = editorRange();
  if (!range || range.collapsed) return;
  e.preventDefault();
  e.clipboardData.setData("text/plain",readGroups(range.cloneContents()).map(g=>g.text).join(""));
};
function insertPlain(text) {
  if (!text.includes("\n")) return document.execCommand("insertText",false,text);
  const span=document.createElement("span");
  span.textContent=text;
  document.execCommand("insertHTML",false,span.innerHTML.replaceAll("\n","<br>"));
}
editor.onpaste = e => {
  e.preventDefault(); insertPlain(e.clipboardData.getData("text/plain").replace(/\r\n?/g,"\n"));
};
function settings() {
  const groups=readGroups(editor), base=groups.map(g=>g.text).join(""), reading=groups.map(g=>g.reading).join("");
  return {...design, styleSpec:styles[design.style], base, reading, groups, align:el("align").value,
    ratio:Number(el("size").value)/100, rubyInk:design.linked ? design.ink : design.ruby, ornament:el("ornament").value.trim()};
}
function partStyle(s,g,part) {
  const result={...s};
  if(part==="ruby"){
    result.ink=s.linked ? (g.format?.base?.ink ?? s.ink) : s.rubyInk;
    if(!s.includeRuby) Object.assign(result,{fill:"solid",effect:"flat",outline:"none",bold:false,italic:false,underline:false,strike:false});
  }
  Object.assign(result,g.format?.[part]);
  result.styleSpec=styles[result.style];
  return result;
}
const localOptions=[
  ["ink","文字色","color"],["style","書体"],["fill","塗り"],["gradientEnd","終了色","color"],["direction","グラデーションの向き"],["effect","仕上げ"],["outline","縁取り"],
  ["edge","縁取り・内縁の色","color"],["outer","外縁の色","color"],["side","影・側面・発光色","color"],
  ["bold","太字","flag"],["italic","斜体","flag"],["underline","下線","flag"],["strike","取り消し線","flag"],
  ["align","ルビの配置"],["ratio","ルビの大きさ"]
];
function changeLocal(key,value){
  const part=el("localPart").value;
  for(const group of editing.groups){
    group.format ||= {};
    group.format[part] ||= {};
    if(value===undefined) delete group.format[part][key];
    else group.format[part][key]=value;
  }
  syncLocalFields();
}
function swatchGrid(entries,container,selected){
  const grid=document.createElement("div");grid.className="pal";
  for(const [hex,name] of entries){
    const b=document.createElement("button");b.type="button";b.setAttribute("aria-label",name);
    b.style.setProperty("--sample",hex);b.dataset.hex=hex;b.setAttribute("aria-pressed",String(hex===selected));
    grid.append(b);
  }
  container.append(grid);
}
function swatchGroup(container,[name,entries],selected){
  const section=document.createElement("div"),heading=document.createElement("h4");
  heading.textContent=name;section.append(heading);swatchGrid(entries,section,selected);container.append(section);
}
function swatchHint(e){
  const tip=el("swatchTip"),b=e.target.closest?.(".pal button");
  if(!b || e.type==="focusout" || e.type==="pointerout"){tip.hidden=true;return;}
  tip.textContent=b.getAttribute("aria-label");tip.hidden=false;
  const r=b.getBoundingClientRect();
  tip.style.left=Math.max(4,Math.min(r.left,innerWidth-tip.offsetWidth-4))+"px";
  tip.style.top=(r.top>tip.offsetHeight+5?r.top-tip.offsetHeight-4:r.bottom+4)+"px";
}
for(const event of ["pointerover","pointerout","focusin","focusout"])document.addEventListener(event,swatchHint);
function makePalette(host,choose,compact){
  const details=document.createElement("details"), summary=document.createElement("summary");
  let selected="", marked=[], built=false;
  function build(){
    if(built) return;
    built=true;
    swatchGrid(colorGroups[0][1],host,selected);
    marked=[...host.querySelectorAll('[aria-pressed="true"]')];
    const more=document.createElement("details"), title=document.createElement("summary");
    more.className="more-colors";title.textContent="すべての色";more.append(title);host.append(more);
    more.addEventListener("toggle",()=>{
      if(!more.open || more.childElementCount>1) return;
      const groups=document.createElement("div");groups.className="swatch-groups";more.append(groups);
      for(const group of colorGroups.slice(1))swatchGroup(groups,group,selected);
      marked=[...host.querySelectorAll('[aria-pressed="true"]')];
    });
  }
  if(compact){
    details.className="color-choice";details.append(summary);host.append(details);host=details;
    details.ontoggle=()=>{if(details.open) build()};
  }else build();
  host.addEventListener("click",event=>{
    const b=event.target.closest("button[data-hex]");
    if(b){choose(b.dataset.hex);if(compact) details.open=false;}
  });
  return hex=>{
    if(hex===selected) return;
    selected=hex;
    for(const b of marked)b.setAttribute("aria-pressed","false");
    marked=[...host.querySelectorAll('[data-hex="'+hex+'"]')];
    for(const b of marked)b.setAttribute("aria-pressed","true");
    if(compact){summary.textContent=namedColor(hex)[1];summary.style.setProperty("--sample",hex);}
  };
}
function showPane(id){
  for(const button of rubyBox.querySelectorAll("[data-pane]")){
    const active=button.dataset.pane===id;
    button.setAttribute("aria-pressed",String(active));el(button.dataset.pane).hidden=!active;
  }
  rubyBox.querySelector(".edit-body").scrollTop=0;
  el("swatchTip").hidden=true;
}
for(const button of rubyBox.querySelectorAll("[data-pane]"))button.onclick=()=>showPane(button.dataset.pane);
for(const group of colorGroups)swatchGroup(el("localSwatches"),group,"");
el("localSwatches").onclick=e=>{
  const b=e.target.closest("button[data-hex]");
  if(b)changeLocal(el("colorRole").value,b.dataset.hex);
};
el("colorRole").onchange=syncLocalFields;
el("inheritColor").onclick=()=>changeLocal(el("colorRole").value,undefined);
for(const [key,label,kind] of localOptions){
  if(kind==="color"){el("colorRole").add(new Option(label,key));continue;}
  const row=document.createElement("div"), caption=document.createElement("label");
  row.className="field"; row.append(caption);caption.textContent=label;
  const input=document.createElement("select");
  input.id="local-"+key; caption.htmlFor=input.id;
  input.add(new Option("全体に従う",""));
    if(kind==="flag"){
      input.add(new Option("あり","true"));input.add(new Option("なし","false"));
    }else if(key==="ratio"){
      for(let i=Number(el("size").min);i<=Number(el("size").max);i++) input.add(new Option(i+"%",String(i/100)));
    }else for(const opt of el(key).options) input.add(new Option(opt.text,opt.value));
  row.append(input);
  input.oninput=()=>{
    let value=input.value;
    if(value==="") value=undefined;
    else if(kind==="flag") value=value==="true";
    else if(key==="ratio") value=Number(value);
    changeLocal(key,value);
  };
  const pane=["effect","outline"].includes(key)?"localFinish":"localType";
  el(pane).querySelector(".edit-fields").append(row);
}
function syncLocalFields(){
  if(!editing) return;
  const groups=editing.groups.map(g=>({...g,reading:editing.groups.length===1?readingInput.value.trim():g.reading}));
  const part=el("localPart").value, global=settings(), effective=partStyle(global,groups[0],part);
  const role=el("colorRole");
  const gradient=effective.fill==="gradient";
  role.querySelector('[value="gradientEnd"]').disabled=!gradient;
  if(!gradient && role.value==="gradientEnd")role.value="ink";
  const hex=effective[role.value];
  const paletteHost=el("localSwatches");
  if(paletteHost.dataset.selected!==hex){
    paletteHost.querySelector('[aria-pressed="true"]')?.setAttribute("aria-pressed","false");
    paletteHost.querySelector('[data-hex="'+hex+'"]')?.setAttribute("aria-pressed","true");
    paletteHost.dataset.selected=hex;
  }
  el("inheritColor").disabled=!groups.some(g=>g.format?.[part]?.[role.value]!==undefined);
  for(const [key,,kind] of localOptions){
    if(kind==="color")continue;
    const input=el("local-"+key), value=groups[0].format?.[part]?.[key];
    input.parentElement.hidden=(part==="base" && (key==="ratio" || key==="align")) || (key==="direction" && effective.fill!=="gradient");
    input.value=groups.every(g=>g.format?.[part]?.[key]===value) ? String(value??"") : "";
  }
  const view=surface(el("localSample"));
  if(!view.w || !view.h) return;
  view.c.fillStyle=el("paper").value;view.c.fillRect(0,0,view.w,view.h);
  const scene=composition({...global,groups,ornament:""});
  paintScene(view.c,scene,frame(scene.box,view.w,view.h),global,view.dpr);
}
el("localPart").onchange=syncLocalFields;
let copiedStyle;
el("copyStyle").onclick=()=>{
  const part=el("localPart").value, st=partStyle(settings(),editing.groups[0],part);
  copiedStyle=Object.fromEntries(localOptions.filter(([k])=>part==="ruby" || !["align","ratio"].includes(k)).map(([k])=>[k,st[k]]));
  el("pasteStyle").disabled=false;
};
el("pasteStyle").onclick=()=>{
  const part=el("localPart").value, values={...copiedStyle};
  if(part==="base"){delete values.align;delete values.ratio}
  for(const g of editing.groups){g.format||={};g.format[part]={...g.format[part],...values};}
  syncLocalFields();
};
el("localReset").onclick=()=>{for(const group of editing.groups) group.format=null;syncLocalFields();};
// Describe visible differences only. Colors belonging to inactive effects are omitted.
function appearance(s, ruby=false){
  const color=colorText(s.ink);
  const direction={down:"top to bottom",across:"left to right",diagonal:"upper left to lower right"};
  const fill=s.fill==="gradient" ? color+" to "+colorText(s.gradientEnd)+" gradient ("+direction[s.direction]+")"
    : s.fill==="halftone" ? color+" halftone dots" : color;
  const face={plain:"",mincho:"Mincho",gothic:"Japanese Gothic",round:"rounded Gothic",pop:"chunky pop",brush:"brush lettering",
    pixel:"pixel lettering",led:"LED dot-matrix",digital:"angular digital",segments:"seven-segment",stencil:"stencil",
    hollow:"hollow lettering",balloon:"inflated balloon lettering",pen:"handwritten"};
  const outline=s.outline==="double" ? colorText(s.edge)+" inner and "+colorText(s.outer)+" outer outlines"
    : s.outline==="none" ? "" : (s.outline==="thin"?"thin ":"thick ")+colorText(s.edge)+" outline";
  const side=colorText(s.side);
  return {fill,style:face[s.style],outline,
    effect:{flat:"",depth:side+" 3D extrusion",shadow:side+" drop shadow",neon:side+" neon glow",foil:"metallic foil",emboss:"embossed"}[s.effect],
    bold:s.bold?"bold":"",italic:s.italic?"italic":"",underline:s.underline?"underlined":"",strike:s.strike?"strikethrough":"",
    align:ruby && s.align==="center"?"centered":"",
    ratio:ruby && s.ratio!==.2?Math.round(s.ratio*100)+"% of the base height":""};
}
const plainAppearance=appearance({...defaults,style:"plain"});
const resetWords={style:"plain lettering",outline:"no outline",effect:"flat finish",bold:"regular weight",italic:"upright",
  underline:"no underline",strike:"no strikethrough",align:"spread across the word",ratio:"20% of the base height"};
function differences(current,inherited){
  return Object.keys(current).filter(k=>current[k]!==inherited[k]);
}
function styleInstruction(target,look,keys){
  if(!keys.length)return "";
  if(keys.length===1 && keys[0]==="fill" && palette.some(c=>c[2]===look.fill))return "Color "+target+" "+look.fill+".";
  return "Use "+keys.map(k=>look[k]||resetWords[k]).join(", ")+" for "+target+".";
}
function ornamentText(s) {
  const desc = symbolNames[s.ornament] || "a decorative mark shaped like “"+s.ornament+"”";
  return "Place "+desc+" to the right of the title as a separate ornament.";
}
function wordTarget(s,g,offset,color=""){
  const repeated=s.base.indexOf(g.text)!==s.base.lastIndexOf(g.text);
  return (repeated?"occurrence "+s.base.slice(0,offset).split(g.text).length+" of ":"")+(color?color+" ":"")+"“"+g.text+"”";
}
function readingPairs(s){
  let offset=0;
  return s.groups.flatMap(g=>{
    const target=wordTarget(s,g,offset);
    offset+=g.text.length;
    return g.reading?["“"+g.reading+"” above "+target]:[];
  });
}
function plainPrompt(s) {
  let text = "Write “"+s.base+"”";
  if (s.reading) {
    if (s.groups.length>1) {
      const pairs=readingPairs(s);
      text+=" with small furigana: "+pairs.join(", ");
    } else {
      const spread=s.align==="spread" && characters(s.reading).length>1;
      text+=" with small furigana “"+s.reading+"” "+(spread ? "above it, spanning its width" : "centered above it");
    }
  }
  if (s.ornament) text+=", with “"+s.ornament+"” on the right";
  return text+".";
}
function scopedColorPrompt(s){
  if(s.fill!=="solid" || !s.groups.some(({format})=>format?.base?.ink || format?.ruby?.ink)) return null;
  const name=ink=>ink===defaults.ink?"black":colorText(ink);
  const wordColors=[], readings=[];
  let hasLocalRubyColor=false, offset=0;
  for(const group of s.groups){
    const start=offset;
    offset+=group.text.length;
    if(!group.reading && !group.format) continue;
    const word=partStyle(s,group,"base"), ruby=partStyle(s,group,"ruby");
    if(word.fill!=="solid" || (group.reading && ruby.fill!=="solid")) return null;
    const wordHasColor=word.ink!==s.ink;
    const target=wordTarget(s,group,start,wordHasColor?"":name(word.ink));
    if(wordHasColor) wordColors.push(target+" in "+name(word.ink));
    if(group.reading){
      hasLocalRubyColor ||= ruby.ink!==s.rubyInk;
      readings.push("small "+name(ruby.ink)+" “"+group.reading+"” above "+target);
    }
  }
  if(!wordColors.length && !hasLocalRubyColor) return null;
  const colors=wordColors.join(" and ");
  let text=plainPrompt({...s,reading:""}).replace(/([。!?.!?]”)\.$/,"$1")+" Set ";
  text+=wordColors.length===s.groups.length ? colors : "the text in "+name(s.ink)+(colors?", with "+colors:"");
  text+=".";
  if(readings.length) text+=" Place "+readings.join(" and ")+".";
  return text;
}
function makePrompt(s){
  const base=appearance(s), ruby=appearance(partStyle(s,{},"ruby"),true);
  const scoped=scopedColorPrompt(s);
  const lines=[scoped ?? plainPrompt(s)];
  const keepKey=k=>!scoped || k!=="fill";
  const mainKeys=differences(base,plainAppearance).filter(keepKey), rubyKeys=s.reading?differences(ruby,plainAppearance).filter(keepKey):[];
  const shared=mainKeys.filter(k=>rubyKeys.includes(k) && base[k]===ruby[k]);
  lines.push(styleInstruction("all lettering",base,shared),
    styleInstruction("the main text",base,mainKeys.filter(k=>!shared.includes(k))),
    styleInstruction("the furigana",ruby,rubyKeys.filter(k=>!shared.includes(k) && !(k==="align" && !scoped && s.groups.length===1))));
  let offset=0;
  for(const group of s.groups){
    const start=offset;
    offset+=group.text.length;
    if(!group.format) continue;
    const target=wordTarget(s,group,start);
    const word=partStyle(s,group,"base"), reading=partStyle(s,group,"ruby");
    const wordLook=appearance(word);
    lines.push(styleInstruction(target,wordLook,differences(wordLook,base).filter(keepKey)));
    if(group.reading){
      const readingLook=appearance(reading,true);
      lines.push(styleInstruction("the furigana “"+group.reading+"” above "+target,readingLook,differences(readingLook,ruby).filter(keepKey)));
    }
  }
  return lines.filter(Boolean).join(" ");
}
const canvas=el("preview"), ctx=canvas.getContext("2d");
function measure(text,size,s,decorated) {
  // Keep the native face. paintRun adds bold once, including for single-weight script fonts.
  const font = (decorated && s.italic ? "italic " : "")+s.styleSpec[2]+" "+size+"px "+s.styleSpec[3];
  ctx.font=font;
  const m=ctx.measureText(text), left=text.trim() ? -m.actualBoundingBoxLeft : 0;
  return {text,font,size,left,width:text.trim()? Math.max(1,m.actualBoundingBoxRight-left) : m.width, top:m.actualBoundingBoxAscent,bottom:m.actualBoundingBoxDescent};
}
// All geometry is in lettering units, shared by the preview and Layout exporter.
function composition(s) {
  if (!s.groups.some(g=>g.text.includes("\n"))) return composeLine(s);
  const rows=[[]], items=[];
  for(const group of s.groups){
    group.text.split("\n").forEach((text,i)=>{
      if(i) rows.push([]);
      if(text) rows.at(-1).push({...group,text});
    });
  }
  const lineRatio=s.groups.reduce((max,g)=>Math.max(max,g.format?.ruby?.ratio||0),s.ratio);
  rows.forEach((groups,row)=>{
    if(!groups.length && !(row===rows.length-1 && s.ornament)) return;
    const line=composeLine({...s,groups,ornament:row===rows.length-1?s.ornament:""});
    const dy=row*160*(1.4+lineRatio);
    for(const item of line.items){
      item.baseline+=dy; item.box[1]+=dy; item.box[3]+=dy; items.push(item);
    }
  });
  return {items,box:items.reduce((b,i)=>[Math.min(b[0],i.box[0]),Math.min(b[1],i.box[1]),Math.max(b[2],i.box[2]),Math.max(b[3],i.box[3])],[Infinity,Infinity,-Infinity,-Infinity])};
}
function composeLine(s) {
  const size=160, items=[];
  let cursor=0;
  for (const g of s.groups) {
    const baseStyle=partStyle(s,g,"base"), rubyStyle=partStyle(s,g,"ruby");
    const base=measure(g.text,size,baseStyle,true);
    const spread=rubyStyle.align==="spread";
    const letters=spread ? characters(g.reading) : (g.reading ? [g.reading] : []);
    const rubySize=size*rubyStyle.ratio;
    let ruby=letters.map(ch=>measure(ch,rubySize,rubyStyle,true));
    const sumWidth=runs=>runs.reduce((w,r)=>w+r.width,0);
    let rw=sumWidth(ruby);
    if (spread && rw>base.width) {
      ruby=letters.map(ch=>measure(ch,rubySize*base.width/rw,rubyStyle,true));
      rw=sumWidth(ruby);
    }
    const width=Math.max(base.width,rw);
    items.push({type:"base",style:baseStyle,text:g.text, runs:[{...base,x:cursor+(width-base.width)/2}], baseline:0});
    if (ruby.length) {
      const spacing=spread && ruby.length>1 ? (width-rw)/(ruby.length-1) : 0;
      let x=cursor+(spacing ? 0 : (width-rw)/2);
      const runs=ruby.map(r=>{const run={...r,x}; x+=r.width+spacing; return run;});
      items.push({type:"ruby",style:rubyStyle,text:g.reading,runs,baseline:0});
    }
    cursor+=width+(s.groups.length>1 ? size*.045 : 0);
  }
  const bases=items.filter(i=>i.type==="base");
  const baseTop=bases.reduce((a,i)=>Math.max(a,i.runs[0].top),0);
  const rubyDesc=items.filter(i=>i.type==="ruby").reduce((a,i)=>i.runs.reduce((b,r)=>Math.max(b,r.bottom),a),0);
  for (const i of items) if(i.type==="ruby") i.baseline=-baseTop-size*.08-rubyDesc;
  if (s.ornament) {
    const mark=measure(s.ornament,size*.36,s,false);
    items.push({type:"ornament", text:s.ornament,runs:[{...mark,x:cursor+size*.13}],baseline:-baseTop*.45+(mark.top-mark.bottom)/2});
  }
  for(const i of items){
    const pad = i.type==="ornament" ? 0 : extent(i.style,i.runs[0].size);
    i.box=i.runs.reduce((b,r)=>[Math.min(b[0],r.x-pad),Math.min(b[1],i.baseline-r.top-pad),Math.max(b[2],r.x+r.width+pad),Math.max(b[3],i.baseline+r.bottom+pad)],[Infinity,Infinity,-Infinity,-Infinity]);
  }
  const box=items.reduce((b,i)=>[Math.min(b[0],i.box[0]),Math.min(b[1],i.box[1]),Math.max(b[2],i.box[2]),Math.max(b[3],i.box[3])],[Infinity,Infinity,-Infinity,-Infinity]);
  return {items,box};
}
function extent(s,size) {
  const edge={none:0,thin:.02,bold:.05,double:.075}[s.outline];
  const effect={flat:0,shadow:.10,depth:.12,foil:0,emboss:.025,neon:.15}[s.effect];
  return size*Math.max(edge+effect,s.underline ? .12 : 0, s.bold ? .014 : 0);
}
function frame(box,w,h) {
  const bw=Math.max(1,box[2]-box[0]), bh=Math.max(1,box[3]-box[1]);
  const scale=Math.min(w*.82/bw,h*.68/bh);
  return {scale,x:(w-bw*scale)/2-box[0]*scale,y:(h-bh*scale)/2-box[1]*scale};
}
function draftLayout(s,scene,w,h) {
  const f=frame(scene.box,w,h);
  const mixedInk=new Set(scene.items.filter(i=>i.type!=="ornament").map(i=>i.style.ink)).size>1;
  const items=scene.items.map(i=>{
    const box=i.box.map((v,j)=>v*f.scale+(j%2 ? f.y : f.x));
    if (i.type==="ornament") return {label:"object",caption:ornamentText(s),bbox:box};
    const isRuby=i.type==="ruby", look=appearance(i.style,isRuby);
    const keys=differences(look,plainAppearance);
    if(mixedInk && !keys.includes("fill"))keys.unshift("fill");
    const caption=[isRuby?"furigana":"main text",...keys.map(k=>look[k])].join(", ");
    return {label:"text",text:i.text,caption,bbox:box};
  });
  return {width:w,height:h,bbox_coord_space:"abs",bbox_format:"xyxy",summary:{canvas:"single",caption:plainPrompt(s)},items};
}
// Match the official pixel-layout compiler: enclose fractional edges, then center y/x.
function compileLayout(draft) {
  const {width,height,summary}=draft;
  const items=draft.items.map(item=>{
    const [l,t,r,b]=item.bbox.map(edge=>Number(edge.toFixed(9)));
    return {...item,bbox:[Math.floor(t)-height/2, Math.floor(l)-width/2, Math.ceil(b)-height/2, Math.ceil(r)-width/2]};
  });
  return {summary,items,bbox_coord_space:"abs_centralized",bbox_format:"yxyx"};
}
// Sample glyphs on a small grid once, and reuse their vector masks between redraws.
const glyphPaths=new Map();
function displayGlyph(char,style,font){
  const key=style+"/"+font+"/"+char;
  if(glyphPaths.has(key))return glyphPaths.get(key);
  const mask=document.createElement("canvas");mask.width=64;mask.height=48;
  const c=mask.getContext("2d",{willReadFrequently:true});c.font=font.replace(/[\d.]+px/,"32px");
  const advance=c.measureText(char).width, path=new Path2D();
  if(style==="segments" && /^[0-9]$/.test(char)){
    const bars=[[3,2,13,2],[16,3,2,10],[16,15,2,10],[3,25,13,2],[2,15,2,10],[2,3,2,10],[3,13,13,2]];
    for(const id of ["012345","12","01643","01623","5612","05623","056423","012","0123456","012356"][Number(char)]){
      const [x,y,w,h]=bars[id];path.rect(x*advance/20,y-27,w*advance/20,h);
    }
  }else{
    c.fillText(char,2,34);const pixels=c.getImageData(0,0,64,48).data;
    const step=style==="pixel"?2:1.5;
    for(let y=0;y<48;y+=step)for(let x=0;x<Math.min(64,advance+6);x+=step){
      if(pixels[4*(Math.floor(y)*64+Math.floor(x))+3]<90)continue;
      const left=x-2,top=y-34;
      if(style==="led"){path.moveTo(left+step*.88,top+step*.5);path.arc(left+step*.5,top+step*.5,step*.38,0,2*Math.PI);}
      else if(style==="digital" || style==="segments"){
        path.moveTo(left+step*.26,top);path.lineTo(left+step,top);path.lineTo(left+step,top+step*.74);path.lineTo(left+step*.74,top+step);path.lineTo(left,top+step);path.lineTo(left,top+step*.26);path.closePath();
      }else path.rect(left,top,step+.04,step+.04);
    }
  }
  const glyph={path,advance};if(glyphPaths.size>=512)glyphPaths.delete(glyphPaths.keys().next().value);
  glyphPaths.set(key,glyph);return glyph;
}
const dotPatterns=new Map();
function dots(color){
  if(!dotPatterns.has(color)){
    const tile=document.createElement("canvas");tile.width=tile.height=8;
    const c=tile.getContext("2d");c.fillStyle=color;c.beginPath();c.arc(4,4,3.1,0,Math.PI*2);c.fill();
    dotPatterns.set(color,c.createPattern(tile,"repeat"));
  }
  return dotPatterns.get(color);
}
function paintRun(c,r,baseline,ink,s,decorated,scale,runs) {
  const x=r.x-r.left, y=baseline, n=r.size;
  c.save(); c.font=r.font; c.lineJoin="round"; c.fillStyle=ink;
  function stroke(color,width) { c.strokeStyle=color; c.lineWidth=n*width; c.strokeText(r.text,x,y); }
  if (decorated) {
    if(s.effect==="shadow" || s.effect==="depth"){
      c.fillStyle=s.side;
        const steps=s.effect==="depth" ? 8 : 1, depth=n*(s.effect==="depth" ? .035 : .025);
      for(let j=steps;j>0;j--) c.fillText(r.text,x+depth*j/steps,y+depth*j/steps);
    } else if(s.effect==="emboss"){
      c.fillStyle="#574838"; c.fillText(r.text,x+n*.018,y+n*.018);
      c.fillStyle="#fff2d5"; c.fillText(r.text,x-n*.014,y-n*.014);
    } else if(s.effect==="neon"){
      c.shadowColor=s.side; c.shadowBlur=Math.min(64,n*scale*.1);
        stroke(s.side,.018); c.fillStyle=s.side; c.fillText(r.text,x,y); c.shadowBlur=0;
    }
      if (s.outline==="double") stroke(s.outer,.038);
      if (s.outline!=="none") stroke(s.edge,{thin:.012,bold:.027,double:.021}[s.outline]);
      if(s.bold) stroke(ink,.008);
  }
  c.fillStyle=ink;
  if(decorated && (s.effect==="foil" || s.effect==="emboss")){
    const grad=c.createLinearGradient(x,y-r.top,x+n*.15,y+Math.max(r.bottom,1));
    for(const [p,color] of [[0,ink],[.29,ink],[.42,s.effect==="foil"?"#fff4ce":"#dbcdb9"],[.52,ink],[1,ink]]) grad.addColorStop(p,color);
    c.fillStyle=grad;
  }
  if(decorated && s.fill==="gradient"){
    const horizontal=s.direction!=="down",vertical=s.direction!=="across";
    const left=runs[0].x, last=runs.at(-1);
    const grad=c.createLinearGradient(left,y-r.top,horizontal?last.x+last.width:left,vertical?y+Math.max(1,r.bottom):y-r.top);
    grad.addColorStop(0,ink);grad.addColorStop(1,s.gradientEnd);c.fillStyle=grad;
  }else if(decorated && s.fill==="halftone"){
    const pattern=dots(ink);pattern.setTransform(new DOMMatrix().scale(n/160));c.fillStyle=pattern;
  }
  if(decorated && ["pixel","led","digital","segments"].includes(s.style)){
    const path=new Path2D(), factor=n/32;
    let advance=0;
    for(const ch of characters(r.text)){
      const glyph=displayGlyph(ch,s.style,r.font);
      path.addPath(glyph.path,new DOMMatrix([factor,0,0,factor,x+advance*factor,y]));
      advance+=glyph.advance;
    }
    c.fill(path);
  }else if(decorated && s.style==="hollow"){
    c.strokeStyle=c.fillStyle;c.lineWidth=n*.017;c.strokeText(r.text,x,y);
  }else if(decorated && s.style==="stencil"){
    c.beginPath();
    const step=n*.48, end=x+Math.max(n,r.width+n);
    for(let pos=x-n;pos<end;pos+=step)c.rect(pos,y-n*1.5,step-n*.026,n*2);
    c.clip();c.fillText(r.text,x,y);
  }else{
    if(decorated && s.style==="balloon"){c.strokeStyle=c.fillStyle;c.lineWidth=n*.035;c.strokeText(r.text,x,y);}
    c.fillText(r.text,x,y);
  }
  c.restore();
}
function paintScene(c,scene,f,global,deviceScale) {
  c.save(); c.translate(f.x,f.y); c.scale(f.scale,f.scale);
  for (const i of scene.items) {
    const decorated=i.type!=="ornament";
    const s=i.style||global, ink=s.ink;
    for (const r of i.runs) paintRun(c,r,i.baseline,ink,s,decorated,f.scale*deviceScale,i.runs);
    if (decorated && (s.underline || s.strike)){
      const first=i.runs[0], last=i.runs[i.runs.length-1], width=last.x+last.width-first.x;
      const thick=first.size*.035;
      c.fillStyle=ink;
      if(s.underline) c.fillRect(first.x,i.baseline+i.runs.reduce((d,r)=>Math.max(d,r.bottom),0)+first.size*.04,width,thick);
      if(s.strike) c.fillRect(first.x,i.baseline-first.top*.45,width,thick);
    }
  }
  c.restore();
}
function surface(target) {
  const w=target.clientWidth,h=target.clientHeight,dpr=window.devicePixelRatio||1;
  const pixelWidth=Math.round(w*dpr), pixelHeight=Math.round(h*dpr);
  if(target.width!==pixelWidth || target.height!==pixelHeight){target.width=pixelWidth;target.height=pixelHeight;}
  const c=target.getContext("2d"); c.setTransform(dpr,0,0,dpr,0,0);
  return {c,w,h,dpr};
}
function renderPreview(s,scene,w,h,useLayout) {
  const view=surface(canvas),c=view.c;
  c.fillStyle=useLayout ? getComputedStyle(canvas).getPropertyValue("--chip") : el("paper").value;
  c.fillRect(0,0,view.w,view.h);
  if(!scene || !w || !h) return;
  const z=useLayout ? Math.min(view.w/w,view.h/h) : 1;
  c.save(); c.translate((view.w-w*z)/2,(view.h-h*z)/2); c.scale(z,z);
  c.fillStyle=el("paper").value;c.fillRect(0,0,w,h);
  paintScene(c,scene,frame(scene.box,w,h),s,z*view.dpr); c.restore();
}
const presetButtons=[];
function setDesign(key,value) {
  design[key]=value;
  if (flags.includes(key)) el(key).checked=value;
  else if(designFields.includes(key)) el(key).value=value;
}
function applyPreset(index) {
  const spec={...defaults,...presets[index][1]};
  for(const [key,value] of Object.entries(spec)) setDesign(key,value);
  update();
}
for(const [index,[name]] of presets.entries()){
  const b=document.createElement("button"), thumb=document.createElement("canvas"), label=document.createElement("span");
  b.type="button"; b.className="preset"; thumb.setAttribute("aria-hidden","true"); label.textContent=name;
  b.append(thumb,label); el("presets").append(b); b.onclick=()=>applyPreset(index); presetButtons.push(b);
}
function thumbnails(){
  for(const [i,[name,spec,paper]] of presets.entries()){
    const thumb=presetButtons[i].querySelector("canvas"),view=surface(thumb);
    const s={...defaults,...spec,groups:[{text:"紅蓮",reading:spec.style==="plain" ? "グレン" : ""}],align:"spread",ratio:.2,ornament:""};
    s.styleSpec=styles[s.style]; s.rubyInk=s.ink;
    view.c.fillStyle=paper; view.c.fillRect(0,0,view.w,view.h);
    const scene=composition(s); paintScene(view.c,scene,frame(scene.box,view.w,view.h),s,view.dpr);
  }
}
function editColor(hex){
  const target=el("target").value;
  if(target==="ruby" && design.linked) setDesign("linked",false);
  design[target]=hex; update();
}
const showMainColor=makePalette(el("palette"),editColor,false);
const showStartColor=makePalette(el("startPicker"),hex=>{design.ink=hex;update()},true);
const showEndColor=makePalette(el("endPicker"),hex=>{design.gradientEnd=hex;update()},true);
for(const [label,start,end] of [["夕焼け","#ffdf00","#ff8000"],["氷","#ffffff","#76c8ff"],["キャンディ","#ffd1dc","#dfc8fa"]]){
  const button=document.createElement("button");button.type="button";button.textContent=label;
  button.onclick=()=>{design.ink=start;design.gradientEnd=end;el("target").value="ink";update()};
  el("gradientPresets").append(button);
}
const emojiCategories = [
  ["顔・気持ち","😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😋 😜 🤪 🤭 🤫 🤔 🫡 🤐 😐 😏 😒 🙄 😳 🥺 😢 😭 😤 😡 🤯 😱 😴 🥳 😎 🤓 😈 👻 🤖 👽 💀 😺 😻"],
  ["手・人","👋 🤚 🖐️ ✋ 🖖 👌 🤌 ✌️ 🤞 🤟 🤘 🤙 👈 👉 👆 👇 ☝️ 👍 👎 ✊ 👊 👏 🙌 🫶 👐 🤝 🙏 ✍️ 💪 👀 🧑‍🎨 🧑‍🚀 🥷 🧙 🧚 🧜‍♀️ 💃 🕺"],
  ["ハート・効果","❤️ 🧡 💛 💚 💙 💜 🖤 🤍 🤎 🩷 🩵 🩶 💔 ❤️‍🔥 ❤️‍🩹 ❣️ 💕 💞 💓 💗 💖 💘 💝 💟 💋 💯 💢 💥 💫 💦 💨 💬 💭 ✨ 🌟 ⭐ 🔥 🎉 🎊"],
  ["動物","🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼 🐨 🐯 🦁 🐮 🐷 🐸 🐵 🐔 🐧 🐦 🐤 🦆 🦉 🦄 🐝 🦋 🐞 🐢 🐍 🐙 🦑 🐠 🐬 🐳 🦈 🦭 🐘 🦒 🦔 🐾 🐉"],
  ["花・自然・天気","🌸 🌷 🌹 🥀 🌺 🌻 🌼 🪻 🪷 💐 🍀 🌱 🌿 🍃 🍁 🍂 🌾 🌵 🌴 🌲 🍄 🪨 🌍 🌙 🌕 🌛 ☀️ 🌤️ ☁️ 🌧️ ⛈️ 🌩️ ❄️ ☃️ 🌈 ☄️ 🌊 💧 🫧"],
  ["食べ物・飲み物","🍎 🍊 🍋 🍌 🍉 🍇 🍓 🍒 🍑 🥝 🍅 🌽 🍞 🥐 🥞 🍔 🍟 🍕 🍝 🍛 🍜 🍣 🍙 🍱 🍤 🍡 🍥 🍦 🍩 🍪 🎂 🍰 🧁 🍫 🍬 🍭 ☕ 🍵 🧋 🥤 🍹 🥂"],
  ["音楽・遊び・行事","🎵 🎶 🎼 🎤 🎧 🎹 🥁 🎷 🎺 🎸 🎻 🪈 🎨 🖌️ 🎭 🎬 🎥 📷 📚 🖋️ 🎮 🎲 🧩 ♟️ 🧸 🎁 🎈 🎀 🎆 🎇 🎐 🎏 🎎 🎑 🎃 🎄 🏆 🥇 ⚽ ⚾ 🏀 🎾"],
  ["場所・乗り物・道具","🏠 🏯 🏰 ⛩️ 🗼 🗻 🏝️ 🏕️ 🎡 🎢 🌃 🚗 🚕 🚌 🚲 🚃 🚄 🚢 ✈️ 🚁 🚀 🛸 ⚓ 🧳 🗺️ 🧭 ⏰ ⌛ 💡 🔦 🕯️ 🔮 💎 👑 🗝️ 🔑 🔔 📌 ✉️ 📣"],
  ["記号・矢印","⬅️ ➡️ ⬆️ ⬇️ ↗️ ↘️ ↙️ ↖️ ↔️ ↕️ 🔄 ▶️ ⏸️ ⏩ ⏪ ➕ ➖ ✖️ ➗ ♾️ ✔️ ✅ ❌ ⭕ ❗ ❓ ⁉️ ⚠️ ⛔ 🚫 🔴 🟠 🟡 🟢 🔵 🟣 ⚫ ⚪ 🔷 🔶 🔺 🔻 🏁 🚩"]
];
function symbolButton(symbol) {
  const b=document.createElement("button");
  b.type="button"; b.textContent=symbol; b.setAttribute("aria-label",symbol+"を挿入");
  return b;
}
el("symbols").append(...Object.keys(symbolNames).map(symbolButton));
el("emojiList").addEventListener("toggle", () => {
  const groups=el("emojiGroups");
  if (!el("emojiList").open || groups.childElementCount) return;
  for (const [name, symbols] of emojiCategories) {
    const heading=document.createElement("h3"), grid=document.createElement("div");
    heading.textContent=name; grid.className="symbols";
    grid.append(...symbols.split(" ").map(symbolButton));
    groups.append(heading,grid);
  }
});
const picker=el("symbolPicker");
picker.addEventListener("mousedown", e => {
  if (e.target.closest(".symbols button")) e.preventDefault();
});
picker.addEventListener("click", e => {
  const button=e.target.closest(".symbols button");
  if (!button) return;
  const symbol=button.textContent, target=el("symbolTarget").value;
  if(target==="base"){
    const range=editorRange() || lastCaret || document.createRange();
    if(!editor.contains(range.commonAncestorContainer)){range.selectNodeContents(editor);range.collapse(false);}
    closeEditor(); selectRange(range); insertPlain(symbol);
    lastCaret=editorRange();
    return;
  }
  if(target==="reading" && !editing){
    editor.focus(); el("notice").textContent="先に本文の文字を選択してください。"; return;
  }
  const input=el(target);
  input.setRangeText(symbol,input.selectionStart,input.selectionEnd,"end");
  input.focus({preventScroll:true});
  input.dispatchEvent(new Event("input",{bubbles:true}));
});
function update(){
  const s=settings(), format=el("format").value, useLayout=format==="layout";
  const w=useLayout ? el("width").valueAsNumber : canvas.clientWidth, h=useLayout ? el("height").valueAsNumber : canvas.clientHeight;
  const validSize=n=>Number.isSafeInteger(n) && n>0 && n%16===0;
  const error=(useLayout && (!validSize(w)||!validSize(h)) ? "生成幅と高さは16の倍数で入力してください。" : "");
  const scene=s.base.trim() && !error ? composition(s) : null;
  el("dimensions").hidden=!useLayout; editor.classList.toggle("center",s.align==="center"); editor.style.setProperty("--ruby-size", Math.max(.35,s.ratio)+"em");
  el("error").textContent=error; el("error").hidden=!error; el("sizeValue").value=el("size").value+"%";
  let prompt="";
  if (scene) {
    if (useLayout) prompt=JSON.stringify(compileLayout(draftLayout(s,scene,w,h)));
    else prompt=makePrompt(s);
  }
  el("prompt").value=prompt;
  el("copyPlain").disabled=!s.base.trim(); el("copy").disabled=!scene; el("notice").textContent="";
  canvas.setAttribute("aria-label",s.base ? s.base+(s.reading ? "、ルビは"+s.reading : "") : "親文字を入力してください");
  const target=el("target").value,hex=target==="ruby" ? s.rubyInk : design[target];
  el("colorName").textContent=namedColor(hex)[1]; showMainColor(hex); showEndColor(design.gradientEnd);
  el("gradientControls").hidden=design.fill!=="gradient";
  showStartColor(s.ink);
  for(const [i,b] of presetButtons.entries()){
    const spec={...defaults,...presets[i][1]};
    b.setAttribute("aria-pressed",String(Object.keys(defaults).every(k=>design[k]===spec[k])));
  }
  for(const word of editor.querySelectorAll("[data-format]")){
    const group={format:JSON.parse(word.dataset.format)};
    const base=partStyle(s,group,"base"),ruby=partStyle(s,group,"ruby");
    word.style.color=base.ink;
    word.style.fontFamily=base.styleSpec[3];word.style.fontWeight=base.bold?"bold":base.styleSpec[2];
    word.style.fontStyle=base.italic?"italic":"normal";
    const rt=word.querySelector("rt");
    if(rt){
      rt.style.color=ruby.ink;rt.style.fontFamily=ruby.styleSpec[3];rt.style.fontWeight=ruby.bold?"bold":ruby.styleSpec[2];
      rt.style.fontStyle=ruby.italic?"italic":"normal";rt.style.fontSize=Math.max(.35,ruby.ratio)+"em";
      word.style.rubyAlign=ruby.align==="center"?"center":"space-between";
    }
  }
  renderPreview(s,scene,w,h,useLayout);
  if(el("styleSamples").open)styleSamples();
}
for(const key of designFields) el(key).addEventListener("input",()=>{design[key]=flags.includes(key)?el(key).checked:el(key).value;});

document.querySelector(".workspace").addEventListener("input",update);
function setTheme(value) {document.documentElement.dataset.theme=value;el("theme").value=value;}
try{setTheme(localStorage.getItem("moss-ruby-theme")==="dark"?"dark":"light");}catch{setTheme("light");}
el("theme").onchange=()=>{setTheme(el("theme").value);try{localStorage.setItem("moss-ruby-theme",el("theme").value);}catch{} update();};
async function copyPrompt(plain){
  const text=plain?plainPrompt(settings()):el("prompt").value;
  try { await navigator.clipboard.writeText(text); }
  catch {
    const field=document.createElement("textarea");field.value=text;
    document.body.append(field);field.select();
    let copied=false;try{copied=document.execCommand("copy")}catch{}
    if(!copied){field.setAttribute("aria-label","手動コピー用");field.onblur=()=>field.remove();el("notice").textContent="選択した文章を手動でコピーしてください。";return;}
    field.remove();
  }
  el("notice").textContent=plain?"プレーンな英文をコピーしました。":"コピーしました。";
}
el("copy").onclick=()=>copyPrompt(false);
el("copyPlain").onclick=()=>copyPrompt(true);
let sampleKey="";
function styleSamples(){
  const drawer=el("styleSamples");
  if(!drawer.open)return;
  const selection=editorRange()||lastCaret;
  const selected=selection && !selection.collapsed && editor.contains(selection.commonAncestorContainer)?readGroups(selection.cloneContents()).map(g=>g.text).join(""):"";
  const st=settings(), text=characters((selected||st.base||"紅蓮").replace(/\s+/g," ")).slice(0,6).join("");
  if(text===sampleKey)return;
  sampleKey=text;
  const grid=drawer.querySelector(".style-grid");grid.replaceChildren();
  for(const [style,[name]] of Object.entries(styles)){
    const b=document.createElement("button"), thumb=document.createElement("canvas");b.type="button";
    b.append(thumb,name);grid.append(b);b.onclick=()=>{setDesign("style",style);update()};
    const sample={...st,...defaults,style,styleSpec:styles[style],groups:[{text,reading:""}],ornament:""};
    const view=surface(thumb),scene=composition(sample);
    paintScene(view.c,scene,frame(scene.box,view.w,view.h),sample,view.dpr);
  }
}
el("styleSamples").ontoggle=()=>{if(!el("styleSamples").open)sampleKey="";else styleSamples()};
editor.addEventListener("pointerup",styleSamples);
new ResizeObserver(()=>{update();thumbnails();}).observe(canvas);
applyPreset(0); thumbnails();
</script></body></html>