hide1 commited on
Commit
361120d
·
verified ·
1 Parent(s): 88a1fc6

Update ruby editor with compact controls and named color palettes

Browse files
Files changed (2) hide show
  1. README.md +15 -15
  2. index.html +581 -133
README.md CHANGED
@@ -1,15 +1,15 @@
1
- ---
2
- title: MOSS-Image Ruby Maker
3
- emoji: ✍️
4
- colorFrom: pink
5
- colorTo: red
6
- sdk: static
7
- app_file: index.html
8
- short_description: 日本語の親文字とルビからMOSS-Image用のプロンプトを作成
9
- ---
10
-
11
- # MOSS-Image ルビメーカー
12
-
13
- 親文字と読みを入力し、文字の真上にルビを置くための英文プロンプトをコピーできます。書体、配色、縁取り、立体文字などを選べます。Layout JSONも試せます。
14
-
15
- 初期例は「紅蓮」と「グレン」です。レイアウトと文字装飾はブラウザー上でプレビューできます。実際の画像は、コピーしたプロンプトをMOSS-Imageに貼り付けて生成してください。
 
1
+ ---
2
+ title: MOSS-Image Ruby Maker
3
+ emoji: ✍️
4
+ colorFrom: pink
5
+ colorTo: red
6
+ sdk: static
7
+ app_file: index.html
8
+ short_description: 日本語の親文字とルビからMOSS-Image用のプロンプトを作成
9
+ ---
10
+
11
+ # MOSS-Image ルビメーカー
12
+
13
+ 親文字と読みを入力し、文字の真上にルビを置くための英文プロンプトをコピーできます。書体、配色、縁取り、立体文字などを選べます。Layout JSONも試せます。
14
+
15
+ 初期例は「こんにちは、今日はいい天気ですね。」です。「今日」と「天気」に読みが付いています。本文の一部を選ぶと、親文字とルビの配色・書体を個別に編集できます。51色のパレット、2色グラデーション、ドット文字などに対応しています。レイアウトと文字装飾はブラウザー上でプレビューできます。実際の画像は、コピーしたプロンプトをMOSS-Imageに貼り付けて生成してください。
index.html CHANGED
@@ -20,7 +20,7 @@ h2,legend,summary{font-size:16px;font-weight:700;margin:0;padding:0}
20
  .presets{padding:16px 0 20px;border-bottom:1px solid var(--line)}
21
  .preset-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:8px;margin-top:8px}
22
  button,input,select,textarea{color:inherit;font:inherit}
23
- button,select,input[type=color],input[type=range],summary{cursor:pointer}
24
  button,.chip{background:var(--surface);border:1px solid var(--line);border-radius:6px}
25
  button{padding:6px 12px;font-weight:600}
26
  button:hover,.chip:hover{border-color:var(--accent)}
@@ -55,19 +55,40 @@ button:disabled{opacity:.45;cursor:default} textarea{resize:vertical;min-height:
55
  #emojiList h3{margin:12px 0 5px;font-size:13px;color:var(--sub)}
56
  #emojiList .symbols{display:grid;grid-template-columns:repeat(auto-fill,minmax(34px,1fr))}
57
  #emojiList button{padding:3px 0}
58
- .pal{gap:6px}.pal button{width:26px;height:26px;padding:0;border:1px solid #8888;border-radius:50%;background:var(--sample)}
59
- .pal button[aria-pressed=true]{outline:2px solid var(--accent);outline-offset:2px}
60
- .color-slot{display:flex;align-items:center;gap:8px}
61
- input[type=color]{width:39px;height:32px;border:1px solid var(--line);border-radius:4px;background:var(--surface);padding:2px}
62
- #hex{color:var(--sub);font:13px Consolas,monospace}
 
63
  @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}}
64
  @media(max-height:650px){.results{position:static}}
65
  #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}
66
- #editor ruby{white-space:nowrap;cursor:pointer;ruby-align:space-between} #editor.center ruby{ruby-align:center}
67
  #editor rt{font-size:var(--ruby-size, .5em);line-height:1;user-select:none}
68
- #rubyBox{position:fixed;z-index:5;width:min(310px,calc(100vw - 16px));padding:12px;background:var(--surface);border:1px solid var(--line);border-radius:8px;box-shadow:0 4px 18px #0003}
69
- #rubyBox{left:clamp(8px,var(--anchor-x),max(8px,100% - 318px));overflow:auto}
70
- #sampleRuby{font-size:22px;padding:8px 0;line-height:1.4} #rubyTarget{overflow-wrap:anywhere;max-height:55px;overflow:auto} #rubyBox .actions{display:flex;gap:6px;flex-wrap:wrap}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  </style>
72
  </head>
73
  <body><main>
@@ -78,8 +99,8 @@ input[type=color]{width:39px;height:32px;border:1px solid var(--line);border-rad
78
  <section aria-label="文字の設定">
79
  <fieldset><legend>文字と配置</legend>
80
  <div class="fields">
81
- <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 contenteditable="false">今日<rt>きょう</rt></ruby>はいい<ruby contenteditable="false">天気<rt>てんき</rt></ruby>ですね。</div>
82
- <p id="editorHelp" class="hint">本文を入力し、読みを付けたい文字をドラッグしてください。付けたルビはクリックして編集できます。</p></div>
83
  <label>ルビの配置<select id="align"><option value="spread">親文字の幅に均等配置</option><option value="center">中央にまとめる</option></select></label>
84
  <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>
85
  </div></fieldset>
@@ -87,6 +108,7 @@ input[type=color]{width:39px;height:32px;border:1px solid var(--line);border-rad
87
  <div class="fields">
88
  <label>書体スタイル<select id="style"></select></label>
89
  <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>
 
90
  <div class="checks full" aria-label="文字修飾">
91
  <label class="chip"><input type="checkbox" id="bold">太字</label><label class="chip"><input type="checkbox" id="italic">斜体</label>
92
  <label class="chip"><input type="checkbox" id="underline">下線</label><label class="chip"><input type="checkbox" id="strike">取り消し線</label>
@@ -96,8 +118,10 @@ input[type=color]{width:39px;height:32px;border:1px solid var(--line);border-rad
96
  </div></fieldset>
97
  <fieldset><legend>配色</legend><div class="fields">
98
  <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>
99
- <label>自由に選ぶ<span class="color-slot"><input id="picker" type="color" value="#171717"><span id="hex"></span></span></label>
100
- <div id="palette" class="pal full" role="group" aria-label="色見本"></div>
 
 
101
  <label class="check full"><input type="checkbox" id="linked" checked>ルビは親文字と同じ色</label>
102
  </div></fieldset>
103
  <details id="symbolPicker"><summary>記号・絵文字</summary><div class="fields">
@@ -116,11 +140,17 @@ input[type=color]{width:39px;height:32px;border:1px solid var(--line);border-rad
116
  <p class="hint">生成側も同じ幅・高さに設定し、JSON全体をポジティブプロンプトに貼り付けます。</p></div>
117
  <p id="error" role="status" class="error" hidden></p>
118
  <textarea id="prompt" lang="en" aria-labelledby="promptTitle" readonly placeholder="親文字を入力してください"></textarea>
119
- <div class="actions"><button class="primary" id="copy" type="button">プロンプトをコピー</button><span role="status" id="notice"></span></div>
120
  </section></section></div></main>
121
  <div id="rubyBox" role="dialog" aria-labelledby="rubyTarget" hidden>
122
- <label for="reading" id="rubyTarget"></label><div id="sampleRuby" aria-hidden="true"><ruby><span></span><rt></rt></ruby></div><input id="reading" type="text" placeholder="例:きょう" autocomplete="off">
123
- <div class="actions"><button type="button" id="applyRuby" class="primary">適用</button><button type="button" id="removeRuby">ルビを外す</button><button type="button" id="cancelRuby">閉じる</button></div></div>
 
 
 
 
 
 
124
  <script>
125
  "use strict";
126
  const el = id => document.getElementById(id);
@@ -131,6 +161,13 @@ const styles = {
131
  round: ["丸ゴシック", "rounded Japanese Gothic lettering with soft terminals", '400', '"Hiragino Maru Gothic ProN", "BIZ UDPGothic", Meiryo, sans-serif'],
132
  pop: ["ポップ", "playful, chunky Japanese display lettering with plump rounded shapes", '700', '"M PLUS Rounded 1c", "Hiragino Maru Gothic ProN", Meiryo, sans-serif'],
133
  brush: ["筆文字", "expressive Japanese brush lettering with sweeping tapered strokes", '400', '"HGS行書体", "HG行書体", "Yu Mincho", serif'],
 
 
 
 
 
 
 
134
  pen: ["手書き", "casual handwritten Japanese lettering with light, gently irregular pen strokes", '400', '"HGP教科書体", "Yu Kyokasho", "UD Digi Kyokasho N-R", "Yu Gothic", sans-serif']
135
  };
136
  for (const [key, spec] of Object.entries(styles)) el("style").add(new Option(spec[0], key));
@@ -138,13 +175,84 @@ const segmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter("ja"
138
  function characters(text) {
139
  return segmenter ? Array.from(segmenter.segment(text), part => part.segment) : Array.from(text);
140
  }
141
- const palette = [
142
- ["#171717","墨","near-black"],["#ffffff","白","white"],["#db503d","朱","vermilion"],["#8b293e","臙脂","burgundy"],
143
- ["#e57d93","桃","rose pink"],["#eaa439","山吹","amber"],["#b8893c","金","warm gold"],["#366b54","深緑","forest green"],
144
- ["#386eac","藍","deep blue"],["#714e93","紫","violet"],["#41bcca","青緑","turquoise"],["#6c7077","灰","slate gray"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  ];
146
- const colorText = hex => palette.find(c => c[0] === hex)?.[2] || hex.toUpperCase();
147
- const defaults = {style:"mincho", effect:"flat", outline:"none", ink:"#171717", ruby:"#171717", edge:"#ffffff", outer:"#171717", side:"#8b293e",
 
 
 
 
 
 
 
 
 
 
 
148
  bold:false, italic:false, underline:false, strike:false, includeRuby:false, linked:true};
149
  const presets = [
150
  ["プレーン", {style:"plain"}, "#ffffff"],
@@ -157,24 +265,24 @@ const presets = [
157
  ];
158
  const design = {...defaults};
159
  const flags = ["bold","italic","underline","strike","includeRuby","linked"];
160
- const designFields = ["style","effect","outline",...flags];
161
  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"};
162
  const editor = el("editor"), rubyBox = el("rubyBox"), readingInput = el("reading");
163
  let editing = null, lastCaret = null;
164
  function readGroups(root) {
165
  const groups = [];
166
- function append(text, reading = "") {
167
  if (!text) return;
168
  const last = groups.at(-1);
169
- if (!reading && last && !last.reading) last.text += text;
170
- else groups.push({text, reading});
171
  }
172
  function visit(node) {
173
  if (node.nodeType === Node.TEXT_NODE) return append(node.data);
174
  if (node.nodeName === "RT") return;
175
- if (node.nodeName === "RUBY") {
176
  const base = Array.from(node.childNodes).filter(n => n.nodeName !== "RT").map(n => n.textContent).join("");
177
- return append(base, node.querySelector("rt")?.textContent || "");
178
  }
179
  if (node.nodeName === "BR") {
180
  if (node.parentNode.childNodes.length > 1 || node.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) append("\n");
@@ -200,104 +308,137 @@ function selectRange(range) {
200
  function closeEditor() {
201
  editing = null;
202
  rubyBox.hidden = true;
 
203
  }
204
  function positionBox() {
205
- if (!editing) return;
206
- const rect = editing.range.getBoundingClientRect();
207
- const below = innerHeight-rect.bottom >= rect.top;
208
- const inset = Math.max(8, (below ? rect.bottom : innerHeight-rect.top)+5);
209
- const style = rubyBox.style;
210
- style.setProperty("--anchor-x",rect.left+"px");
211
- style.top = below ? inset+"px" : "auto";
212
- style.bottom = below ? "auto" : inset+"px";
213
- style.maxHeight = Math.max(0,innerHeight-inset-8)+"px";
214
- }
215
- function openEditor(range, ruby = null) {
216
- const text = ruby ? Array.from(ruby.childNodes).filter(n=>n.nodeName!=="RT").map(n=>n.textContent).join("") : range.toString();
217
- const crossesNodes = range.startContainer !== range.endContainer || range.startContainer.nodeType!==Node.TEXT_NODE;
218
- if (!text.trim() || /[\r\n]/.test(text) || (!ruby && crossesNodes && range.cloneContents().querySelector("ruby,br,div,p"))) return closeEditor();
219
- editing = {range, text, ruby};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  positionBox();
221
- el("rubyTarget").textContent = "「"+text+"」の読み";
222
- readingInput.value = ruby?.querySelector("rt")?.textContent || "";
223
- el("sampleRuby").querySelector("span").textContent=text;
224
- el("sampleRuby").querySelector("rt").textContent=readingInput.value;
225
- el("removeRuby").hidden = !ruby;
226
- el("applyRuby").disabled = !readingInput.value.trim();
227
- rubyBox.hidden = false;
228
  }
229
  function pickRange(event) {
230
- const range = editorRange();
231
- if (range) lastCaret = range;
232
- const ruby = event.target.closest?.("ruby");
233
- if (ruby) {
234
- const target = document.createRange();
235
- target.selectNode(ruby); openEditor(target, ruby);
236
- } else if (range && !range.collapsed) openEditor(range);
237
  else closeEditor();
238
  }
239
  editor.addEventListener("pointerup", pickRange);
240
  editor.addEventListener("click", e => { if (e.detail===0) pickRange(e); });
241
  editor.addEventListener("keyup", e => { if(e.shiftKey && e.key.startsWith("Arrow")) pickRange(e); });
242
- function enclosingRuby(node) {
243
- return (node.nodeType===Node.TEXT_NODE ? node.parentElement : node)?.closest("ruby");
244
- }
245
  editor.addEventListener("keydown", e => {
246
- if (e.isComposing || e.keyCode===229) return;
247
  const range=editorRange();
248
- if (!range) return;
249
- if (e.key==="F2" && !range.collapsed) {
250
- e.preventDefault(); openEditor(range);
251
- if (editing) readingInput.focus();
252
- return;
253
- }
254
- if (!range.collapsed || !["Backspace","Delete"].includes(e.key)) return;
255
- const node=range.startContainer, offset=range.startOffset, backward=e.key==="Backspace";
256
- let ruby=enclosingRuby(node);
257
- if (!ruby) {
258
- let neighbor;
259
- if (node.nodeType===Node.ELEMENT_NODE) neighbor=node.childNodes[offset-(backward?1:0)];
260
- else if (offset===(backward?0:node.length)) neighbor=backward?node.previousSibling:node.nextSibling;
261
- if (neighbor?.nodeName==="RUBY") ruby=neighbor;
262
- }
263
- if (ruby) {
264
- e.preventDefault(); closeEditor(); range.selectNode(ruby); selectRange(range);
265
- document.execCommand("delete");
266
- }
267
- });
268
- editor.addEventListener("beforeinput", e => {
269
- if (!e.inputType.startsWith("insert")) return;
270
- const range=editorRange();
271
- if (!range?.collapsed) return;
272
- const ruby=enclosingRuby(range.startContainer);
273
- if (ruby) {
274
- if (range.startOffset===0) range.setStartBefore(ruby);
275
- else range.setStartAfter(ruby);
276
- range.collapse(true); selectRange(range);
277
- }
278
  });
279
  editor.addEventListener("focusout", () => {
280
  const range = editorRange();
281
  if (range) lastCaret = range;
282
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  function applyReading(remove = false) {
284
- if (!editing || (!remove && !readingInput.value.trim())) return;
285
- const {range,text} = editing;
286
- const ruby = document.createElement("ruby"), rt = document.createElement("rt");
287
- ruby.contentEditable = "false";
288
- rt.textContent = readingInput.value.trim(); ruby.append(text,rt);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  closeEditor(); selectRange(range);
290
- document.execCommand(remove ? "insertText" : "insertHTML", false, remove ? text : ruby.outerHTML);
291
  }
292
  el("applyRuby").onclick = () => applyReading();
293
  el("removeRuby").onclick = () => applyReading(true);
294
  function cancelReading() {
295
  if (!editing) return;
296
- const range = editing.range;
297
  closeEditor(); selectRange(range);
298
  }
299
  el("cancelRuby").onclick = cancelReading;
300
- readingInput.oninput = () => { el("sampleRuby").querySelector("rt").textContent=readingInput.value; el("applyRuby").disabled = !readingInput.value.trim(); };
301
  document.addEventListener("keydown", e => {
302
  if (!editing || e.isComposing || e.keyCode===229) return;
303
  if (e.key==="Escape") { e.preventDefault(); cancelReading(); }
@@ -331,6 +472,169 @@ function settings() {
331
  return {...design, styleSpec:styles[design.style], base, reading, groups, align:el("align").value,
332
  ratio:Number(el("size").value)/100, rubyInk:design.linked ? design.ink : design.ruby, ornament:el("ornament").value.trim()};
333
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
334
  function finishText(s) {
335
  const side = colorText(s.side);
336
  const phrases = {
@@ -344,6 +648,10 @@ function finishText(s) {
344
  }
345
  function decorations(s) {
346
  const a=[];
 
 
 
 
347
  if (s.bold) a.push("Use extra-heavy strokes.");
348
  if (s.italic) a.push("Slant the letters to the right.");
349
  if (s.underline) a.push("Draw a continuous line just beneath the lettering.");
@@ -387,7 +695,36 @@ function plainPrompt(s) {
387
  if (s.ornament) text+=", with “"+s.ornament+"” on the right";
388
  return text+".";
389
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
  function makePrompt(s) {
 
391
  const d=decorations(s);
392
  if (!s.styleSpec[1] && !d && s.ink===defaults.ink && (!s.reading || (s.rubyInk===defaults.ink && s.ratio===.2))) return plainPrompt(s);
393
  const face=s.styleSpec[1] ? " using "+s.styleSpec[1] : "";
@@ -421,10 +758,11 @@ function composition(s) {
421
  if(text) rows.at(-1).push({...group,text});
422
  });
423
  }
 
424
  rows.forEach((groups,row)=>{
425
  if(!groups.length && !(row===rows.length-1 && s.ornament)) return;
426
  const line=composeLine({...s,groups,ornament:row===rows.length-1?s.ornament:""});
427
- const dy=row*160*(1.4+s.ratio);
428
  for(const item of line.items){
429
  item.baseline+=dy; item.box[1]+=dy; item.box[3]+=dy; items.push(item);
430
  }
@@ -435,24 +773,25 @@ function composeLine(s) {
435
  const size=160, items=[];
436
  let cursor=0;
437
  for (const g of s.groups) {
438
- const base=measure(g.text,size,s,true);
439
- const spread=s.align==="spread";
 
440
  const letters=spread ? characters(g.reading) : (g.reading ? [g.reading] : []);
441
- const rubySize=size*s.ratio;
442
- let ruby=letters.map(ch=>measure(ch,rubySize,s,s.includeRuby));
443
  const sumWidth=runs=>runs.reduce((w,r)=>w+r.width,0);
444
  let rw=sumWidth(ruby);
445
  if (spread && rw>base.width) {
446
- ruby=letters.map(ch=>measure(ch,rubySize*base.width/rw,s,s.includeRuby));
447
  rw=sumWidth(ruby);
448
  }
449
  const width=Math.max(base.width,rw);
450
- items.push({type:"base",text:g.text, runs:[{...base,x:cursor+(width-base.width)/2}], baseline:0});
451
  if (ruby.length) {
452
  const spacing=spread && ruby.length>1 ? (width-rw)/(ruby.length-1) : 0;
453
  let x=cursor+(spacing ? 0 : (width-rw)/2);
454
  const runs=ruby.map(r=>{const run={...r,x}; x+=r.width+spacing; return run;});
455
- items.push({type:"ruby",text:g.reading,runs,baseline:0});
456
  }
457
  cursor+=width+(s.groups.length>1 ? size*.045 : 0);
458
  }
@@ -465,7 +804,7 @@ function composeLine(s) {
465
  items.push({type:"ornament", text:s.ornament,runs:[{...mark,x:cursor+size*.13}],baseline:-baseTop*.45+(mark.top-mark.bottom)/2});
466
  }
467
  for(const i of items){
468
- const pad = i.type==="ornament" ? 0 : ((i.type==="base" || s.includeRuby) ? extent(s,i.runs[0].size) : 0);
469
  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]);
470
  }
471
  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]);
@@ -486,9 +825,10 @@ function draftLayout(s,scene,w,h) {
486
  const items=scene.items.map(i=>{
487
  const box=i.box.map((v,j)=>v*f.scale+(j%2 ? f.y : f.x));
488
  if (i.type==="ornament") return {label:"object",caption:ornamentText(s),bbox:box};
489
- const caption=i.type==="base" ? [colorText(s.ink)+" "+(s.styleSpec[1] || "lettering")+".",decorations(s)].filter(Boolean).join(" ") :
490
- rubyText(s,i.text)+" "+(s.includeRuby ? decorations(s) : "Plain upright lettering.");
491
- return {label:"text",text:i.text,caption,bbox:box};
 
492
  });
493
  return {width:w,height:h,bbox_coord_space:"abs",bbox_format:"xyxy",summary:{canvas:"single",caption:makePrompt(s)},items};
494
  }
@@ -501,7 +841,44 @@ function compileLayout(draft) {
501
  });
502
  return {summary,items,bbox_coord_space:"abs_centralized",bbox_format:"yxyx"};
503
  }
504
- function paintRun(c,r,baseline,ink,s,decorated,scale) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  const x=r.x-r.left, y=baseline, n=r.size;
506
  c.save(); c.font=r.font; c.lineJoin="round"; c.fillStyle=ink;
507
  function stroke(color,width) { c.strokeStyle=color; c.lineWidth=n*width; c.strokeText(r.text,x,y); }
@@ -527,14 +904,42 @@ function paintRun(c,r,baseline,ink,s,decorated,scale) {
527
  for(const [p,color] of [[0,ink],[.29,ink],[.42,s.effect==="foil"?"#fff4ce":"#dbcdb9"],[.52,ink],[1,ink]]) grad.addColorStop(p,color);
528
  c.fillStyle=grad;
529
  }
530
- c.fillText(r.text,x,y); c.restore();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531
  }
532
- function paintScene(c,scene,f,s,deviceScale) {
533
  c.save(); c.translate(f.x,f.y); c.scale(f.scale,f.scale);
534
  for (const i of scene.items) {
535
- const decorated=i.type==="base" || (i.type==="ruby" && s.includeRuby);
536
- const ink=i.type==="ruby" ? s.rubyInk : s.ink;
537
- for (const r of i.runs) paintRun(c,r,i.baseline,ink,s,decorated,f.scale*deviceScale);
538
  if (decorated && (s.underline || s.strike)){
539
  const first=i.runs[0], last=i.runs[i.runs.length-1], width=last.x+last.width-first.x;
540
  const thick=first.size*.035;
@@ -592,9 +997,13 @@ function editColor(hex){
592
  if(target==="ruby" && design.linked) setDesign("linked",false);
593
  design[target]=hex; update();
594
  }
595
- for (const [hex,label] of palette){
596
- const b=document.createElement("button"); b.type="button"; b.title=label; b.setAttribute("aria-label",label); b.dataset.hex=hex;
597
- b.style.setProperty("--sample",hex); b.onclick=()=>editColor(hex); el("palette").append(b);
 
 
 
 
598
  }
599
  const emojiCategories = [
600
  ["顔・気持ち","😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😋 😜 🤪 🤭 🤫 🤔 🫡 🤐 😐 😏 😒 🙄 😳 🥺 😢 😭 😤 😡 🤯 😱 😴 🥳 😎 🤓 😈 👻 🤖 👽 💀 😺 😻"],
@@ -660,33 +1069,72 @@ function update(){
660
  else prompt=makePrompt(s);
661
  }
662
  el("prompt").value=prompt;
663
- el("copy").disabled=!scene; el("notice").textContent="";
664
  canvas.setAttribute("aria-label",s.base ? s.base+(s.reading ? "、ルビは"+s.reading : "") : "親文字を入力してください");
665
  const target=el("target").value,hex=target==="ruby" ? s.rubyInk : design[target];
666
- el("hex").textContent=hex.toUpperCase(); el("picker").value=hex;
667
- for(const b of el("palette").children) b.setAttribute("aria-pressed",String(b.dataset.hex===hex));
 
668
  for(const [i,b] of presetButtons.entries()){
669
  const spec={...defaults,...presets[i][1]};
670
  b.setAttribute("aria-pressed",String(Object.keys(defaults).every(k=>design[k]===spec[k])));
671
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
672
  renderPreview(s,scene,w,h,useLayout);
 
673
  }
674
  for(const key of designFields) el(key).addEventListener("input",()=>{design[key]=flags.includes(key)?el(key).checked:el(key).value;});
675
- el("picker").addEventListener("input",e=>{e.stopPropagation();editColor(e.target.value);});
676
  document.querySelector(".workspace").addEventListener("input",update);
677
  function setTheme(value) {document.documentElement.dataset.theme=value;el("theme").value=value;}
678
  try{setTheme(localStorage.getItem("moss-ruby-theme")==="dark"?"dark":"light");}catch{setTheme("light");}
679
  el("theme").onchange=()=>{setTheme(el("theme").value);try{localStorage.setItem("moss-ruby-theme",el("theme").value);}catch{} update();};
680
- el("copy").addEventListener("click",async()=>{
681
- const box=el("prompt");
682
- try { await navigator.clipboard.writeText(box.value); }
683
  catch {
684
- box.focus();box.select();
685
- let copied=false; try{copied=document.execCommand("copy");}catch{}
686
- if(!copied){el("notice").textContent="選択した文章を手動でコピーしてください。";return;}
 
 
687
  }
688
- el("notice").textContent="コピーしました。";
689
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
690
  new ResizeObserver(()=>{update();thumbnails();}).observe(canvas);
691
  applyPreset(0); thumbnails();
692
  </script></body></html>
 
20
  .presets{padding:16px 0 20px;border-bottom:1px solid var(--line)}
21
  .preset-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));gap:8px;margin-top:8px}
22
  button,input,select,textarea{color:inherit;font:inherit}
23
+ button,select,input[type=range],summary{cursor:pointer}
24
  button,.chip{background:var(--surface);border:1px solid var(--line);border-radius:6px}
25
  button{padding:6px 12px;font-weight:600}
26
  button:hover,.chip:hover{border-color:var(--accent)}
 
55
  #emojiList h3{margin:12px 0 5px;font-size:13px;color:var(--sub)}
56
  #emojiList .symbols{display:grid;grid-template-columns:repeat(auto-fill,minmax(34px,1fr))}
57
  #emojiList button{padding:3px 0}
58
+ .color-choice summary{display:flex;align-items:center;gap:6px;font-size:12px;padding:5px 7px;text-align:left}
59
+ .color-choice summary::before{content:"";display:inline-block;flex:none;width:15px;height:15px;border-radius:50%;background:var(--sample);border:1px solid #8889}
60
+ .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:"▾"}
61
+ .color-choice[open]{grid-column:1/-1}.more-colors h4{font-size:12px;margin:10px 0 4px}.full button{overflow-wrap:anywhere}
62
+ #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}
63
+ #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}
64
  @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}}
65
  @media(max-height:650px){.results{position:static}}
66
  #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}
67
+ #editor{cursor:text} #editor ruby{white-space:nowrap;ruby-align:space-between} #editor.center ruby{ruby-align:center}
68
  #editor rt{font-size:var(--ruby-size, .5em);line-height:1;user-select:none}
69
+ #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}
70
+ .edit-head,.edit-line,.edit-sections,.edit-body{padding:8px 12px}
71
+ .edit-head,.edit-line,.edit-sections{flex:none;display:flex;align-items:center;gap:8px;border-bottom:1px solid var(--line)}
72
+ .edit-head strong{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
73
+ .edit-head button,.edit-line button,.edit-sections button{white-space:nowrap}
74
+ .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}
75
+ .edit-sections{gap:4px;padding-block:5px}.edit-sections button{flex:1;padding:5px 4px;border-color:transparent;background:transparent}
76
+ .edit-sections button[aria-pressed=true]{background:var(--chip);border-color:var(--line);color:var(--accent)}
77
+ .edit-body{flex:1;min-height:0;overflow:auto;overscroll-behavior:contain}
78
+ .edit-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px 12px}
79
+ .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}
80
+ .edit-ops{display:flex;gap:6px;flex-wrap:wrap;margin-top:10px}
81
+ .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)}
82
+ .pal{display:flex;flex-wrap:wrap;gap:3px;align-content:start}
83
+ .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}
84
+ .pal button[aria-pressed=true]{outline:2px solid var(--accent);outline-offset:0}
85
+ .pal button[aria-pressed=true]::after{margin:0;content:"✓";color:white;text-shadow:0 1px 2px black,0 0 3px black;font-size:16px}
86
+ #swatchTip{position:fixed;z-index:8;pointer-events:none;background:var(--ink);color:var(--surface);border-radius:4px;padding:3px 8px;font-size:12px}
87
+ @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%}}
88
+ @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}}
89
+ @media(max-width:350px){#rubyBox{height:min(524px,calc(100dvh - 16px))}}
90
+ @media(max-height:420px){.edit-line,.edit-head,.edit-sections{padding-block:3px}.edit-line #localSample{height:34px}}
91
+ @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}}
92
  </style>
93
  </head>
94
  <body><main>
 
99
  <section aria-label="文字の設定">
100
  <fieldset><legend>文字と配置</legend>
101
  <div class="fields">
102
+ <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>
103
+ <p id="editorHelp" class="hint">読みや装飾を付ける文字をドラッグします。設定した部分はクリックして編集できます。</p></div>
104
  <label>ルビの配置<select id="align"><option value="spread">親文字の幅に均等配置</option><option value="center">中央にまとめる</option></select></label>
105
  <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>
106
  </div></fieldset>
 
108
  <div class="fields">
109
  <label>書体スタイル<select id="style"></select></label>
110
  <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>
111
+ <details id="styleSamples" class="full"><summary>本文で書体を見比べる</summary><div class="style-grid"></div></details>
112
  <div class="checks full" aria-label="文字修飾">
113
  <label class="chip"><input type="checkbox" id="bold">太字</label><label class="chip"><input type="checkbox" id="italic">斜体</label>
114
  <label class="chip"><input type="checkbox" id="underline">下線</label><label class="chip"><input type="checkbox" id="strike">取り消し線</label>
 
118
  </div></fieldset>
119
  <fieldset><legend>配色</legend><div class="fields">
120
  <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>
121
+ <div class="field">選択色<span id="colorName"></span></div>
122
+ <div id="palette" class="full" role="group" aria-label="色見本"></div>
123
+ <label>塗り<select id="fill"><option value="solid">単色</option><option value="gradient">2色グラデーション</option><option value="halftone">漫画の網点</option></select></label>
124
+ <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>
125
  <label class="check full"><input type="checkbox" id="linked" checked>ルビは親文字と同じ色</label>
126
  </div></fieldset>
127
  <details id="symbolPicker"><summary>記号・絵文字</summary><div class="fields">
 
140
  <p class="hint">生成側も同じ幅・高さに設定し、JSON全体をポジティブプロンプトに貼り付けます。</p></div>
141
  <p id="error" role="status" class="error" hidden></p>
142
  <textarea id="prompt" lang="en" aria-labelledby="promptTitle" readonly placeholder="親文字を入力してください"></textarea>
143
+ <div class="actions"><button class="primary" id="copy" type="button">プロンプトをコピー</button><button id="copyPlain" type="button">プレーンな英文をコピー</button><span role="status" id="notice"></span></div>
144
  </section></section></div></main>
145
  <div id="rubyBox" role="dialog" aria-labelledby="rubyTarget" hidden>
146
+ <div class="edit-head"><strong id="rubyTarget"></strong><button type="button" id="applyRuby" class="primary">適用</button><button type="button" id="cancelRuby">閉じる</button></div>
147
+ <div class="edit-line"><label id="readingField">読み<input id="reading" type="text" placeholder="例:きょう" autocomplete="off"></label><button type="button" id="removeRuby">ルビを外す</button>
148
+ <label>装飾対象<select id="localPart"><option value="base">親文字</option><option value="ruby">ルビ</option></select></label><canvas id="localSample" aria-label="選択部分の装飾見本"></canvas></div>
149
+ <div class="edit-sections" role="group" aria-label="設定項目"><button data-pane="localPaint">配色</button><button data-pane="localType">書体・塗り</button><button data-pane="localFinish">仕上げ・操作</button></div>
150
+ <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>
151
+ <section id="localType" hidden><div class="edit-fields"></div></section>
152
+ <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>
153
+ <div id="swatchTip" role="tooltip" hidden></div>
154
  <script>
155
  "use strict";
156
  const el = id => document.getElementById(id);
 
161
  round: ["丸ゴシック", "rounded Japanese Gothic lettering with soft terminals", '400', '"Hiragino Maru Gothic ProN", "BIZ UDPGothic", Meiryo, sans-serif'],
162
  pop: ["ポップ", "playful, chunky Japanese display lettering with plump rounded shapes", '700', '"M PLUS Rounded 1c", "Hiragino Maru Gothic ProN", Meiryo, sans-serif'],
163
  brush: ["筆文字", "expressive Japanese brush lettering with sweeping tapered strokes", '400', '"HGS行書体", "HG行書体", "Yu Mincho", serif'],
164
+ pixel:["ピクセル文字","blocky pixel lettering with crisp stair-step edges","700","Meiryo, monospace"],
165
+ led:["LED電光掲示板","dot-matrix lettering made of evenly spaced round LED lights","700","Meiryo, monospace"],
166
+ digital:["角型デジタル","angular digital lettering with straight strokes and clipped corners","700","Meiryo, monospace"],
167
+ segments:["液晶時計風","seven-segment display lettering with straight separated bars","600","Consolas, monospace"],
168
+ stencil:["ステンシル","stencil lettering with narrow breaks in the strokes","700","Meiryo, sans-serif"],
169
+ hollow:["袋文字","hollow letters drawn as clear outlines","700","Meiryo, sans-serif"],
170
+ balloon:["バルーン文字","inflated balloon lettering with soft rounded highlights","900","Meiryo, sans-serif"],
171
  pen: ["手書き", "casual handwritten Japanese lettering with light, gently irregular pen strokes", '400', '"HGP教科書体", "Yu Kyokasho", "UD Digi Kyokasho N-R", "Yu Gothic", sans-serif']
172
  };
173
  for (const [key, spec] of Object.entries(styles)) el("style").add(new Option(spec[0], key));
 
175
  function characters(text) {
176
  return segmenter ? Array.from(segmenter.segment(text), part => part.segment) : Array.from(text);
177
  }
178
+ const colorGroups = [
179
+ ["基本の12色", [
180
+ ["#000000","黒","black"],
181
+ ["#ffffff","白","white"],
182
+ ["#ff0000","赤","red"],
183
+ ["#ff8000","オレンジ","orange"],
184
+ ["#ffdf00","黄","yellow"],
185
+ ["#00a024","緑","green"],
186
+ ["#004cff","青","blue"],
187
+ ["#00e9ee","シアン","cyan"],
188
+ ["#8000c8","紫","purple"],
189
+ ["#ff00ba","マゼンタ","magenta"],
190
+ ["#ff94bc","ピンク","pink"],
191
+ ["#865032","茶","brown"]
192
+ ]],
193
+ ["鮮やか・明るい色", [
194
+ ["#a2ef00","黄緑","lime green"],
195
+ ["#76c8ff","空色","sky blue"],
196
+ ["#41bcca","ターコイズ","turquoise"],
197
+ ["#ff7967","コーラル","coral"],
198
+ ["#ff4099","ホットピンク","hot pink"],
199
+ ["#fff54c","レモンイエロー","lemon yellow"],
200
+ ["#db503d","朱","vermilion"],
201
+ ["#eaa439","山吹","amber"]
202
+ ]],
203
+ ["パステル", [
204
+ ["#ffd1dc","パステルピンク","pastel pink"],
205
+ ["#aecbfa","パステルブルー","pastel blue"],
206
+ ["#b7edcf","ミント","mint green"],
207
+ ["#dfc8fa","ラベンダー","lavender"],
208
+ ["#ffcfad","ピーチ","peach"],
209
+ ["#fff3ad","淡い黄","pale yellow"],
210
+ ["#c7f1ea","淡い青緑","pale aqua"]
211
+ ]],
212
+ ["深い色", [
213
+ ["#a41936","深紅","crimson"],
214
+ ["#8b293e","臙脂","burgundy"],
215
+ ["#162749","紺","navy blue"],
216
+ ["#366b54","深緑","forest green"],
217
+ ["#4e245d","濃紫","deep purple"],
218
+ ["#513323","こげ茶","dark brown"],
219
+ ["#386eac","深青","deep blue"],
220
+ ["#714e93","菫色","violet"]
221
+ ]],
222
+ ["くすみ・アースカラー", [
223
+ ["#bd5040","レンガ色","brick red"],
224
+ ["#c67453","テラコッタ","terracotta"],
225
+ ["#778239","オリーブ","olive green"],
226
+ ["#9bac8a","セージ","sage green"],
227
+ ["#e57d93","桃","rose pink"],
228
+ ["#bf8b92","くすみローズ","dusty rose"],
229
+ ["#b8893c","金","warm gold"],
230
+ ["#ab792f","黄土","ochre"]
231
+ ]],
232
+ ["ニュートラル", [
233
+ ["#171717","墨","near-black"],
234
+ ["#fffff0","アイボリー","ivory"],
235
+ ["#fff1d1","クリーム","cream"],
236
+ ["#dfcfb8","ベージュ","beige"],
237
+ ["#c7ccd0","薄灰","light gray"],
238
+ ["#888888","灰","gray"],
239
+ ["#6c7077","青灰","slate gray"],
240
+ ["#424348","チャコール","charcoal gray"]
241
+ ]]
242
  ];
243
+ const palette=colorGroups.flatMap(([,entries])=>entries);
244
+ const colorByHex=new Map(palette.map(entry=>[entry[0],entry]));
245
+ function namedColor(hex){
246
+ const exact=colorByHex.get(hex.toLowerCase());
247
+ if(exact) return exact;
248
+ // Older selections could contain arbitrary colors. Describe the nearest swatch.
249
+ const channels=value=>[1,3,5].map(i=>parseInt(value.slice(i,i+2),16));
250
+ const rgb=channels(hex);
251
+ const distance=entry=>channels(entry[0]).reduce((d,n,i)=>d+(n-rgb[i])**2,0);
252
+ return palette.reduce((best,item)=>distance(item)<distance(best)?item:best);
253
+ }
254
+ const colorText=hex=>namedColor(hex)[2];
255
+ const defaults = {fill:"solid",gradientEnd:"#ff8000",direction:"down",style:"mincho", effect:"flat", outline:"none", ink:"#171717", ruby:"#171717", edge:"#ffffff", outer:"#171717", side:"#8b293e",
256
  bold:false, italic:false, underline:false, strike:false, includeRuby:false, linked:true};
257
  const presets = [
258
  ["プレーン", {style:"plain"}, "#ffffff"],
 
265
  ];
266
  const design = {...defaults};
267
  const flags = ["bold","italic","underline","strike","includeRuby","linked"];
268
+ const designFields = ["style","effect","outline","fill","direction",...flags];
269
  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"};
270
  const editor = el("editor"), rubyBox = el("rubyBox"), readingInput = el("reading");
271
  let editing = null, lastCaret = null;
272
  function readGroups(root) {
273
  const groups = [];
274
+ function append(text, reading = "", format = null) {
275
  if (!text) return;
276
  const last = groups.at(-1);
277
+ if (!format && !reading && last && !last.reading && !last.format) last.text += text;
278
+ else groups.push({text, reading, format});
279
  }
280
  function visit(node) {
281
  if (node.nodeType === Node.TEXT_NODE) return append(node.data);
282
  if (node.nodeName === "RT") return;
283
+ if (node.nodeName === "RUBY" || node.dataset?.format) {
284
  const base = Array.from(node.childNodes).filter(n => n.nodeName !== "RT").map(n => n.textContent).join("");
285
+ return append(base, node.querySelector("rt")?.textContent || "", node.dataset.format ? JSON.parse(node.dataset.format) : null);
286
  }
287
  if (node.nodeName === "BR") {
288
  if (node.parentNode.childNodes.length > 1 || node.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) append("\n");
 
308
  function closeEditor() {
309
  editing = null;
310
  rubyBox.hidden = true;
311
+ el("swatchTip").hidden=true;
312
  }
313
  function positionBox() {
314
+ if (!editing || rubyBox.hidden) return;
315
+ const rect=editing.selected.getBoundingClientRect(), area=editor.getBoundingClientRect();
316
+ const w=rubyBox.offsetWidth,h=rubyBox.offsetHeight;
317
+ const beside=area.right+8+w<=innerWidth-8;
318
+ const x=beside?area.right+8:rect.left;
319
+ 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;
320
+ rubyBox.style.left=Math.max(8,Math.min(x,innerWidth-w-8))+"px";
321
+ rubyBox.style.top=Math.max(8,Math.min(y,innerHeight-h-8))+"px";
322
+ }
323
+ const wordSelector="ruby,[data-format]";
324
+ function openEditor(range, word = null) {
325
+ const selected=range.cloneRange();
326
+ let prefix=null, suffix=null;
327
+ if (word) range.selectNode(word);
328
+ else {
329
+ for (const boundary of ["start","end"]) {
330
+ const node=range[boundary+"Container"];
331
+ const parent=(node.nodeType===Node.TEXT_NODE ? node.parentElement : node).closest?.(wordSelector);
332
+ if (parent && editor.contains(parent)) {
333
+ const outside=document.createRange();
334
+ outside.selectNodeContents(parent);
335
+ if(boundary==="start") outside.setEnd(node,range.startOffset);
336
+ else outside.setStart(node,range.endOffset);
337
+ const remainder=readGroups(outside.cloneContents()).map(g=>g.text).join("");
338
+ const whole=readGroups(parent).map(g=>g.text).join("");
339
+ if(remainder && remainder===whole){
340
+ if(boundary==="start") range.setStartAfter(parent);
341
+ else range.setEndBefore(parent);
342
+ continue;
343
+ }
344
+ if(remainder && parent.tagName!=="RUBY"){
345
+ const piece={text:remainder,format:JSON.parse(parent.dataset.format)};
346
+ if(boundary==="start") prefix=piece;
347
+ else suffix=piece;
348
+ }
349
+ if (boundary==="start") range.setStartBefore(parent);
350
+ else range.setEndAfter(parent);
351
+ }
352
+ }
353
+ }
354
+ const groups=readGroups(range.cloneContents());
355
+ if(prefix) groups[0].text=groups[0].text.slice(prefix.text.length);
356
+ if(suffix) groups.at(-1).text=groups.at(-1).text.slice(0,-suffix.text.length);
357
+ const text=groups.map(g=>g.text).join("");
358
+ if (!text.trim() || /[\r\n]/.test(text)) return closeEditor();
359
+ const single=groups.length===1;
360
+ editing={range,selected,text,groups,prefix,suffix};
361
+ el("rubyTarget").textContent="「"+text+"」を編集";
362
+ el("rubyTarget").title=text;
363
+ readingInput.disabled=!single;
364
+ el("readingField").hidden=!single;
365
+ readingInput.value=single ? groups[0].reading : "";
366
+ el("removeRuby").hidden=!single || !groups[0].reading;
367
+ el("applyRuby").disabled=false;
368
+ el("localPart").value="base";
369
+ el("colorRole").value="ink";
370
+ rubyBox.hidden=false;
371
+ showPane("localPaint");
372
  positionBox();
373
+ syncLocalFields();
 
 
 
 
 
 
374
  }
375
  function pickRange(event) {
376
+ const range=editorRange();
377
+ if (range) lastCaret=range;
378
+ const word=event.target.closest?.(wordSelector);
379
+ if (range && !range.collapsed) openEditor(range);
380
+ else if (word) openEditor(range||document.createRange(),word);
 
 
381
  else closeEditor();
382
  }
383
  editor.addEventListener("pointerup", pickRange);
384
  editor.addEventListener("click", e => { if (e.detail===0) pickRange(e); });
385
  editor.addEventListener("keyup", e => { if(e.shiftKey && e.key.startsWith("Arrow")) pickRange(e); });
 
 
 
386
  editor.addEventListener("keydown", e => {
387
+ if (e.isComposing || e.keyCode===229 || e.key!=="F2") return;
388
  const range=editorRange();
389
+ if (!range || range.collapsed) return;
390
+ e.preventDefault(); openEditor(range);
391
+ if (editing) readingInput.focus();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  });
393
  editor.addEventListener("focusout", () => {
394
  const range = editorRange();
395
  if (range) lastCaret = range;
396
  });
397
+ editor.addEventListener("beforeinput", e => {
398
+ if (e.isComposing || !e.cancelable || !e.inputType.startsWith("delete")) return;
399
+ const target=e.getTargetRanges?.()[0];
400
+ if (!target) return;
401
+ const node=target.startContainer, ruby=node.parentElement;
402
+ if (node.nodeType!==Node.TEXT_NODE || ruby?.tagName!=="RUBY" || ruby.firstChild!==node ||
403
+ node.nextSibling?.nodeName!=="RT" || target.endContainer!==node ||
404
+ target.startOffset!==0 || target.endOffset!==node.length) return;
405
+ // Remove the reading together with the last base character in the same undo step.
406
+ e.preventDefault();
407
+ const range=document.createRange(); range.selectNode(ruby); selectRange(range);
408
+ document.execCommand("delete");
409
+ });
410
  function applyReading(remove = false) {
411
+ if (!editing) return;
412
+ const {range,groups,prefix,suffix}=editing;
413
+ if(groups.length===1) groups[0].reading=remove?"":readingInput.value.trim();
414
+ const fragment=document.createElement("div");
415
+ for(const g of [prefix,...groups,suffix].filter(Boolean)){
416
+ const format={};
417
+ for(const part of ["base","ruby"]){
418
+ if(part==="ruby" && !g.reading) continue;
419
+ if(Object.keys(g.format?.[part] || {}).length) format[part]=g.format[part];
420
+ }
421
+ if(!g.reading && !Object.keys(format).length){fragment.append(g.text);continue;}
422
+ const word=document.createElement(g.reading?"ruby":"span");
423
+ word.append(g.text);
424
+ if(Object.keys(format).length) word.dataset.format=JSON.stringify(format);
425
+ if(g.reading){
426
+ const rt=document.createElement("rt"); rt.contentEditable="false"; rt.textContent=g.reading; word.append(rt);
427
+ }
428
+ fragment.append(word);
429
+ }
430
  closeEditor(); selectRange(range);
431
+ document.execCommand("insertHTML",false,fragment.innerHTML);
432
  }
433
  el("applyRuby").onclick = () => applyReading();
434
  el("removeRuby").onclick = () => applyReading(true);
435
  function cancelReading() {
436
  if (!editing) return;
437
+ const range = editing.selected;
438
  closeEditor(); selectRange(range);
439
  }
440
  el("cancelRuby").onclick = cancelReading;
441
+ readingInput.oninput = syncLocalFields;
442
  document.addEventListener("keydown", e => {
443
  if (!editing || e.isComposing || e.keyCode===229) return;
444
  if (e.key==="Escape") { e.preventDefault(); cancelReading(); }
 
472
  return {...design, styleSpec:styles[design.style], base, reading, groups, align:el("align").value,
473
  ratio:Number(el("size").value)/100, rubyInk:design.linked ? design.ink : design.ruby, ornament:el("ornament").value.trim()};
474
  }
475
+ function partStyle(s,g,part) {
476
+ const result={...s};
477
+ if(part==="ruby"){
478
+ result.ink=s.rubyInk;
479
+ if(!s.includeRuby) Object.assign(result,{fill:"solid",effect:"flat",outline:"none",bold:false,italic:false,underline:false,strike:false});
480
+ }
481
+ Object.assign(result,g.format?.[part]);
482
+ result.styleSpec=styles[result.style];
483
+ return result;
484
+ }
485
+ const localOptions=[
486
+ ["ink","文字色","color"],["style","書体"],["fill","塗り"],["gradientEnd","終了色","color"],["direction","グラデーションの向き"],["effect","仕上げ"],["outline","縁取り"],
487
+ ["edge","縁取り・内縁の色","color"],["outer","外縁の色","color"],["side","影・側面・発光色","color"],
488
+ ["bold","太字","flag"],["italic","斜体","flag"],["underline","下線","flag"],["strike","取り消し線","flag"],
489
+ ["align","ルビの配置"],["ratio","ルビの大きさ"]
490
+ ];
491
+ function changeLocal(key,value){
492
+ const part=el("localPart").value;
493
+ for(const group of editing.groups){
494
+ group.format ||= {};
495
+ group.format[part] ||= {};
496
+ if(value===undefined) delete group.format[part][key];
497
+ else group.format[part][key]=value;
498
+ }
499
+ syncLocalFields();
500
+ }
501
+ function swatchGrid(entries,container,selected){
502
+ const grid=document.createElement("div");grid.className="pal";
503
+ for(const [hex,name] of entries){
504
+ const b=document.createElement("button");b.type="button";b.setAttribute("aria-label",name);
505
+ b.style.setProperty("--sample",hex);b.dataset.hex=hex;b.setAttribute("aria-pressed",String(hex===selected));
506
+ grid.append(b);
507
+ }
508
+ container.append(grid);
509
+ }
510
+ function swatchGroup(container,[name,entries],selected){
511
+ const section=document.createElement("div"),heading=document.createElement("h4");
512
+ heading.textContent=name;section.append(heading);swatchGrid(entries,section,selected);container.append(section);
513
+ }
514
+ function swatchHint(e){
515
+ const tip=el("swatchTip"),b=e.target.closest?.(".pal button");
516
+ if(!b || e.type==="focusout" || e.type==="pointerout"){tip.hidden=true;return;}
517
+ tip.textContent=b.getAttribute("aria-label");tip.hidden=false;
518
+ const r=b.getBoundingClientRect();
519
+ tip.style.left=Math.max(4,Math.min(r.left,innerWidth-tip.offsetWidth-4))+"px";
520
+ tip.style.top=(r.top>tip.offsetHeight+5?r.top-tip.offsetHeight-4:r.bottom+4)+"px";
521
+ }
522
+ for(const event of ["pointerover","pointerout","focusin","focusout"])document.addEventListener(event,swatchHint);
523
+ function makePalette(host,choose,compact){
524
+ const details=document.createElement("details"), summary=document.createElement("summary");
525
+ let selected="", marked=[], built=false;
526
+ function build(){
527
+ if(built) return;
528
+ built=true;
529
+ swatchGrid(colorGroups[0][1],host,selected);
530
+ marked=[...host.querySelectorAll('[aria-pressed="true"]')];
531
+ const more=document.createElement("details"), title=document.createElement("summary");
532
+ more.className="more-colors";title.textContent="すべての色";more.append(title);host.append(more);
533
+ more.addEventListener("toggle",()=>{
534
+ if(!more.open || more.childElementCount>1) return;
535
+ const groups=document.createElement("div");groups.className="swatch-groups";more.append(groups);
536
+ for(const group of colorGroups.slice(1))swatchGroup(groups,group,selected);
537
+ marked=[...host.querySelectorAll('[aria-pressed="true"]')];
538
+ });
539
+ }
540
+ if(compact){
541
+ details.className="color-choice";details.append(summary);host.append(details);host=details;
542
+ details.ontoggle=()=>{if(details.open) build()};
543
+ }else build();
544
+ host.addEventListener("click",event=>{
545
+ const b=event.target.closest("button[data-hex]");
546
+ if(b){choose(b.dataset.hex);if(compact) details.open=false;}
547
+ });
548
+ return hex=>{
549
+ if(hex===selected) return;
550
+ selected=hex;
551
+ for(const b of marked)b.setAttribute("aria-pressed","false");
552
+ marked=[...host.querySelectorAll('[data-hex="'+hex+'"]')];
553
+ for(const b of marked)b.setAttribute("aria-pressed","true");
554
+ if(compact){summary.textContent=namedColor(hex)[1];summary.style.setProperty("--sample",hex);}
555
+ };
556
+ }
557
+ function showPane(id){
558
+ for(const button of rubyBox.querySelectorAll("[data-pane]")){
559
+ const active=button.dataset.pane===id;
560
+ button.setAttribute("aria-pressed",String(active));el(button.dataset.pane).hidden=!active;
561
+ }
562
+ rubyBox.querySelector(".edit-body").scrollTop=0;
563
+ el("swatchTip").hidden=true;
564
+ }
565
+ for(const button of rubyBox.querySelectorAll("[data-pane]"))button.onclick=()=>showPane(button.dataset.pane);
566
+ for(const group of colorGroups)swatchGroup(el("localSwatches"),group,"");
567
+ el("localSwatches").onclick=e=>{
568
+ const b=e.target.closest("button[data-hex]");
569
+ if(b)changeLocal(el("colorRole").value,b.dataset.hex);
570
+ };
571
+ el("colorRole").onchange=syncLocalFields;
572
+ el("inheritColor").onclick=()=>changeLocal(el("colorRole").value,undefined);
573
+ for(const [key,label,kind] of localOptions){
574
+ if(kind==="color"){el("colorRole").add(new Option(label,key));continue;}
575
+ const row=document.createElement("div"), caption=document.createElement("label");
576
+ row.className="field"; row.append(caption);caption.textContent=label;
577
+ const input=document.createElement("select");
578
+ input.id="local-"+key; caption.htmlFor=input.id;
579
+ input.add(new Option("全体に従う",""));
580
+ if(kind==="flag"){
581
+ input.add(new Option("あり","true"));input.add(new Option("なし","false"));
582
+ }else if(key==="ratio"){
583
+ for(let i=Number(el("size").min);i<=Number(el("size").max);i++) input.add(new Option(i+"%",String(i/100)));
584
+ }else for(const opt of el(key).options) input.add(new Option(opt.text,opt.value));
585
+ row.append(input);
586
+ input.oninput=()=>{
587
+ let value=input.value;
588
+ if(value==="") value=undefined;
589
+ else if(kind==="flag") value=value==="true";
590
+ else if(key==="ratio") value=Number(value);
591
+ changeLocal(key,value);
592
+ };
593
+ const pane=["effect","outline"].includes(key)?"localFinish":"localType";
594
+ el(pane).querySelector(".edit-fields").append(row);
595
+ }
596
+ function syncLocalFields(){
597
+ if(!editing) return;
598
+ const groups=editing.groups.map(g=>({...g,reading:editing.groups.length===1?readingInput.value.trim():g.reading}));
599
+ const part=el("localPart").value, global=settings(), effective=partStyle(global,groups[0],part);
600
+ const role=el("colorRole");
601
+ const gradient=effective.fill==="gradient";
602
+ role.querySelector('[value="gradientEnd"]').disabled=!gradient;
603
+ if(!gradient && role.value==="gradientEnd")role.value="ink";
604
+ const hex=effective[role.value];
605
+ const paletteHost=el("localSwatches");
606
+ if(paletteHost.dataset.selected!==hex){
607
+ paletteHost.querySelector('[aria-pressed="true"]')?.setAttribute("aria-pressed","false");
608
+ paletteHost.querySelector('[data-hex="'+hex+'"]')?.setAttribute("aria-pressed","true");
609
+ paletteHost.dataset.selected=hex;
610
+ }
611
+ el("inheritColor").disabled=!groups.some(g=>g.format?.[part]?.[role.value]!==undefined);
612
+ for(const [key,,kind] of localOptions){
613
+ if(kind==="color")continue;
614
+ const input=el("local-"+key), value=groups[0].format?.[part]?.[key];
615
+ input.parentElement.hidden=(part==="base" && (key==="ratio" || key==="align")) || (key==="direction" && effective.fill!=="gradient");
616
+ input.value=groups.every(g=>g.format?.[part]?.[key]===value) ? String(value??"") : "";
617
+ }
618
+ const view=surface(el("localSample"));
619
+ if(!view.w || !view.h) return;
620
+ view.c.fillStyle=el("paper").value;view.c.fillRect(0,0,view.w,view.h);
621
+ const scene=composition({...global,groups,ornament:""});
622
+ paintScene(view.c,scene,frame(scene.box,view.w,view.h),global,view.dpr);
623
+ }
624
+ el("localPart").onchange=syncLocalFields;
625
+ let copiedStyle;
626
+ el("copyStyle").onclick=()=>{
627
+ const part=el("localPart").value, st=partStyle(settings(),editing.groups[0],part);
628
+ copiedStyle=Object.fromEntries(localOptions.filter(([k])=>part==="ruby" || !["align","ratio"].includes(k)).map(([k])=>[k,st[k]]));
629
+ el("pasteStyle").disabled=false;
630
+ };
631
+ el("pasteStyle").onclick=()=>{
632
+ const part=el("localPart").value, values={...copiedStyle};
633
+ if(part==="base"){delete values.align;delete values.ratio}
634
+ for(const g of editing.groups){g.format||={};g.format[part]={...g.format[part],...values};}
635
+ syncLocalFields();
636
+ };
637
+ el("localReset").onclick=()=>{for(const group of editing.groups) group.format=null;syncLocalFields();};
638
  function finishText(s) {
639
  const side = colorText(s.side);
640
  const phrases = {
 
648
  }
649
  function decorations(s) {
650
  const a=[];
651
+ if(s.fill==="gradient"){
652
+ const [start,end]={down:["top","bottom"],across:["left","right"],diagonal:["upper left","lower right"]}[s.direction];
653
+ a.push("Fill the letter faces with a smooth gradient from "+colorText(s.ink)+" at the "+start+" to "+colorText(s.gradientEnd)+" at the "+end+".");
654
+ }else if(s.fill==="halftone") a.push("Fill the strokes with a fine comic-book halftone dot pattern.");
655
  if (s.bold) a.push("Use extra-heavy strokes.");
656
  if (s.italic) a.push("Slant the letters to the right.");
657
  if (s.underline) a.push("Draw a continuous line just beneath the lettering.");
 
695
  if (s.ornament) text+=", with “"+s.ornament+"” on the right";
696
  return text+".";
697
  }
698
+ function scopedPrompt(s){
699
+ const lines=["Write “"+s.base+"”.", "Use "+colorText(s.ink)+" "+(s.styleSpec[1]||"lettering")+" by default.",decorations(s)];
700
+ let offset=0;
701
+ for(const group of s.groups){
702
+ const index=s.base.slice(0,offset).split(group.text).length;
703
+ const repeated=s.base.indexOf(group.text)!==s.base.lastIndexOf(group.text);
704
+ const target=(repeated?"occurrence "+index+" of ":"")+"“"+group.text+"”";
705
+ offset+=group.text.length;
706
+ for(const part of ["base","ruby"]){
707
+ if(part==="ruby" && !group.reading) continue;
708
+ const overrides=group.format?.[part]||{};
709
+ if(part==="base" && !Object.keys(overrides).length) continue;
710
+ const st=partStyle(s,group,part);
711
+ const description=colorText(st.ink)+" "+(st.styleSpec[1]||"lettering");
712
+ if(part==="base") lines.push("For "+target+", use "+description+".");
713
+ else {
714
+ const alignment=st.align==="spread"?"spaced across its width":"centered";
715
+ lines.push("Place “"+group.reading+"” directly above "+target+", "+alignment+", in "+description+" at "+Math.round(st.ratio*100)+"% of the base height.");
716
+ }
717
+ lines.push(decorations(st));
718
+ const off={fill:"a solid fill",bold:"regular weight",italic:"upright letters",underline:"no underline",strike:"no strikethrough",outline:"no outline",effect:"a flat finish"};
719
+ const exceptions=Object.keys(overrides).filter(k=>k in off && [false,"none","flat","solid"].includes(st[k]));
720
+ if(exceptions.length) lines.push("Use "+exceptions.map(k=>off[k]).join(", ")+" here.");
721
+ }
722
+ }
723
+ if(s.ornament) lines.push(ornamentText(s));
724
+ return lines.filter(Boolean).join(" ");
725
+ }
726
  function makePrompt(s) {
727
+ if(s.groups.some(g=>g.format)) return scopedPrompt(s);
728
  const d=decorations(s);
729
  if (!s.styleSpec[1] && !d && s.ink===defaults.ink && (!s.reading || (s.rubyInk===defaults.ink && s.ratio===.2))) return plainPrompt(s);
730
  const face=s.styleSpec[1] ? " using "+s.styleSpec[1] : "";
 
758
  if(text) rows.at(-1).push({...group,text});
759
  });
760
  }
761
+ const lineRatio=s.groups.reduce((max,g)=>Math.max(max,g.format?.ruby?.ratio||0),s.ratio);
762
  rows.forEach((groups,row)=>{
763
  if(!groups.length && !(row===rows.length-1 && s.ornament)) return;
764
  const line=composeLine({...s,groups,ornament:row===rows.length-1?s.ornament:""});
765
+ const dy=row*160*(1.4+lineRatio);
766
  for(const item of line.items){
767
  item.baseline+=dy; item.box[1]+=dy; item.box[3]+=dy; items.push(item);
768
  }
 
773
  const size=160, items=[];
774
  let cursor=0;
775
  for (const g of s.groups) {
776
+ const baseStyle=partStyle(s,g,"base"), rubyStyle=partStyle(s,g,"ruby");
777
+ const base=measure(g.text,size,baseStyle,true);
778
+ const spread=rubyStyle.align==="spread";
779
  const letters=spread ? characters(g.reading) : (g.reading ? [g.reading] : []);
780
+ const rubySize=size*rubyStyle.ratio;
781
+ let ruby=letters.map(ch=>measure(ch,rubySize,rubyStyle,true));
782
  const sumWidth=runs=>runs.reduce((w,r)=>w+r.width,0);
783
  let rw=sumWidth(ruby);
784
  if (spread && rw>base.width) {
785
+ ruby=letters.map(ch=>measure(ch,rubySize*base.width/rw,rubyStyle,true));
786
  rw=sumWidth(ruby);
787
  }
788
  const width=Math.max(base.width,rw);
789
+ items.push({type:"base",style:baseStyle,text:g.text, runs:[{...base,x:cursor+(width-base.width)/2}], baseline:0});
790
  if (ruby.length) {
791
  const spacing=spread && ruby.length>1 ? (width-rw)/(ruby.length-1) : 0;
792
  let x=cursor+(spacing ? 0 : (width-rw)/2);
793
  const runs=ruby.map(r=>{const run={...r,x}; x+=r.width+spacing; return run;});
794
+ items.push({type:"ruby",style:rubyStyle,text:g.reading,runs,baseline:0});
795
  }
796
  cursor+=width+(s.groups.length>1 ? size*.045 : 0);
797
  }
 
804
  items.push({type:"ornament", text:s.ornament,runs:[{...mark,x:cursor+size*.13}],baseline:-baseTop*.45+(mark.top-mark.bottom)/2});
805
  }
806
  for(const i of items){
807
+ const pad = i.type==="ornament" ? 0 : extent(i.style,i.runs[0].size);
808
  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]);
809
  }
810
  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]);
 
825
  const items=scene.items.map(i=>{
826
  const box=i.box.map((v,j)=>v*f.scale+(j%2 ? f.y : f.x));
827
  if (i.type==="ornament") return {label:"object",caption:ornamentText(s),bbox:box};
828
+ const style=i.style;
829
+ const caption=[colorText(style.ink)+" "+(style.styleSpec[1]||"lettering")+".",decorations(style)];
830
+ if(i.type==="ruby") caption.push(rubyText({...style,rubyInk:style.ink},i.text));
831
+ return {label:"text",text:i.text,caption:caption.filter(Boolean).join(" "),bbox:box};
832
  });
833
  return {width:w,height:h,bbox_coord_space:"abs",bbox_format:"xyxy",summary:{canvas:"single",caption:makePrompt(s)},items};
834
  }
 
841
  });
842
  return {summary,items,bbox_coord_space:"abs_centralized",bbox_format:"yxyx"};
843
  }
844
+ // Sample glyphs on a small grid once, and reuse their vector masks between redraws.
845
+ const glyphPaths=new Map();
846
+ function displayGlyph(char,style,font){
847
+ const key=style+"/"+font+"/"+char;
848
+ if(glyphPaths.has(key))return glyphPaths.get(key);
849
+ const mask=document.createElement("canvas");mask.width=64;mask.height=48;
850
+ const c=mask.getContext("2d",{willReadFrequently:true});c.font=font.replace(/[\d.]+px/,"32px");
851
+ const advance=c.measureText(char).width, path=new Path2D();
852
+ if(style==="segments" && /^[0-9]$/.test(char)){
853
+ 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]];
854
+ for(const id of ["012345","12","01643","01623","5612","05623","056423","012","0123456","012356"][Number(char)]){
855
+ const [x,y,w,h]=bars[id];path.rect(x*advance/20,y-27,w*advance/20,h);
856
+ }
857
+ }else{
858
+ c.fillText(char,2,34);const pixels=c.getImageData(0,0,64,48).data;
859
+ const step=style==="pixel"?2:1.5;
860
+ for(let y=0;y<48;y+=step)for(let x=0;x<Math.min(64,advance+6);x+=step){
861
+ if(pixels[4*(Math.floor(y)*64+Math.floor(x))+3]<90)continue;
862
+ const left=x-2,top=y-34;
863
+ 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);}
864
+ else if(style==="digital" || style==="segments"){
865
+ 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();
866
+ }else path.rect(left,top,step+.04,step+.04);
867
+ }
868
+ }
869
+ const glyph={path,advance};if(glyphPaths.size>=512)glyphPaths.delete(glyphPaths.keys().next().value);
870
+ glyphPaths.set(key,glyph);return glyph;
871
+ }
872
+ const dotPatterns=new Map();
873
+ function dots(color){
874
+ if(!dotPatterns.has(color)){
875
+ const tile=document.createElement("canvas");tile.width=tile.height=8;
876
+ const c=tile.getContext("2d");c.fillStyle=color;c.beginPath();c.arc(4,4,3.1,0,Math.PI*2);c.fill();
877
+ dotPatterns.set(color,c.createPattern(tile,"repeat"));
878
+ }
879
+ return dotPatterns.get(color);
880
+ }
881
+ function paintRun(c,r,baseline,ink,s,decorated,scale,runs) {
882
  const x=r.x-r.left, y=baseline, n=r.size;
883
  c.save(); c.font=r.font; c.lineJoin="round"; c.fillStyle=ink;
884
  function stroke(color,width) { c.strokeStyle=color; c.lineWidth=n*width; c.strokeText(r.text,x,y); }
 
904
  for(const [p,color] of [[0,ink],[.29,ink],[.42,s.effect==="foil"?"#fff4ce":"#dbcdb9"],[.52,ink],[1,ink]]) grad.addColorStop(p,color);
905
  c.fillStyle=grad;
906
  }
907
+ if(decorated && s.fill==="gradient"){
908
+ const horizontal=s.direction!=="down",vertical=s.direction!=="across";
909
+ const left=runs[0].x, last=runs.at(-1);
910
+ const grad=c.createLinearGradient(left,y-r.top,horizontal?last.x+last.width:left,vertical?y+Math.max(1,r.bottom):y-r.top);
911
+ grad.addColorStop(0,ink);grad.addColorStop(1,s.gradientEnd);c.fillStyle=grad;
912
+ }else if(decorated && s.fill==="halftone"){
913
+ const pattern=dots(ink);pattern.setTransform(new DOMMatrix().scale(n/160));c.fillStyle=pattern;
914
+ }
915
+ if(decorated && ["pixel","led","digital","segments"].includes(s.style)){
916
+ const path=new Path2D(), factor=n/32;
917
+ let advance=0;
918
+ for(const ch of characters(r.text)){
919
+ const glyph=displayGlyph(ch,s.style,r.font);
920
+ path.addPath(glyph.path,new DOMMatrix([factor,0,0,factor,x+advance*factor,y]));
921
+ advance+=glyph.advance;
922
+ }
923
+ c.fill(path);
924
+ }else if(decorated && s.style==="hollow"){
925
+ c.strokeStyle=c.fillStyle;c.lineWidth=n*.017;c.strokeText(r.text,x,y);
926
+ }else if(decorated && s.style==="stencil"){
927
+ c.beginPath();
928
+ const step=n*.48, end=x+Math.max(n,r.width+n);
929
+ for(let pos=x-n;pos<end;pos+=step)c.rect(pos,y-n*1.5,step-n*.026,n*2);
930
+ c.clip();c.fillText(r.text,x,y);
931
+ }else{
932
+ if(decorated && s.style==="balloon"){c.strokeStyle=c.fillStyle;c.lineWidth=n*.035;c.strokeText(r.text,x,y);}
933
+ c.fillText(r.text,x,y);
934
+ }
935
+ c.restore();
936
  }
937
+ function paintScene(c,scene,f,global,deviceScale) {
938
  c.save(); c.translate(f.x,f.y); c.scale(f.scale,f.scale);
939
  for (const i of scene.items) {
940
+ const decorated=i.type!=="ornament";
941
+ const s=i.style||global, ink=s.ink;
942
+ for (const r of i.runs) paintRun(c,r,i.baseline,ink,s,decorated,f.scale*deviceScale,i.runs);
943
  if (decorated && (s.underline || s.strike)){
944
  const first=i.runs[0], last=i.runs[i.runs.length-1], width=last.x+last.width-first.x;
945
  const thick=first.size*.035;
 
997
  if(target==="ruby" && design.linked) setDesign("linked",false);
998
  design[target]=hex; update();
999
  }
1000
+ const showMainColor=makePalette(el("palette"),editColor,false);
1001
+ const showStartColor=makePalette(el("startPicker"),hex=>{design.ink=hex;update()},true);
1002
+ const showEndColor=makePalette(el("endPicker"),hex=>{design.gradientEnd=hex;update()},true);
1003
+ for(const [label,start,end] of [["夕焼け","#ffdf00","#ff8000"],["氷","#ffffff","#76c8ff"],["キャンディ","#ffd1dc","#dfc8fa"]]){
1004
+ const button=document.createElement("button");button.type="button";button.textContent=label;
1005
+ button.onclick=()=>{design.ink=start;design.gradientEnd=end;el("target").value="ink";update()};
1006
+ el("gradientPresets").append(button);
1007
  }
1008
  const emojiCategories = [
1009
  ["顔・気持ち","😀 😃 😄 😁 😆 😅 😂 🤣 😊 😇 🙂 🙃 😉 😌 😍 🥰 😘 😋 😜 🤪 🤭 🤫 🤔 🫡 🤐 😐 😏 😒 🙄 😳 🥺 😢 😭 😤 😡 🤯 😱 😴 🥳 😎 🤓 😈 👻 🤖 👽 💀 😺 😻"],
 
1069
  else prompt=makePrompt(s);
1070
  }
1071
  el("prompt").value=prompt;
1072
+ el("copyPlain").disabled=!s.base.trim(); el("copy").disabled=!scene; el("notice").textContent="";
1073
  canvas.setAttribute("aria-label",s.base ? s.base+(s.reading ? "、ルビは"+s.reading : "") : "親文字を入力してください");
1074
  const target=el("target").value,hex=target==="ruby" ? s.rubyInk : design[target];
1075
+ el("colorName").textContent=namedColor(hex)[1]; showMainColor(hex); showEndColor(design.gradientEnd);
1076
+ el("gradientControls").hidden=design.fill!=="gradient";
1077
+ showStartColor(s.ink);
1078
  for(const [i,b] of presetButtons.entries()){
1079
  const spec={...defaults,...presets[i][1]};
1080
  b.setAttribute("aria-pressed",String(Object.keys(defaults).every(k=>design[k]===spec[k])));
1081
  }
1082
+ for(const word of editor.querySelectorAll("[data-format]")){
1083
+ const group={format:JSON.parse(word.dataset.format)};
1084
+ const base=partStyle(s,group,"base"),ruby=partStyle(s,group,"ruby");
1085
+ word.style.color=base.ink;
1086
+ word.style.fontFamily=base.styleSpec[3];word.style.fontWeight=base.bold?"bold":base.styleSpec[2];
1087
+ word.style.fontStyle=base.italic?"italic":"normal";
1088
+ const rt=word.querySelector("rt");
1089
+ if(rt){
1090
+ rt.style.color=ruby.ink;rt.style.fontFamily=ruby.styleSpec[3];rt.style.fontWeight=ruby.bold?"bold":ruby.styleSpec[2];
1091
+ rt.style.fontStyle=ruby.italic?"italic":"normal";rt.style.fontSize=Math.max(.35,ruby.ratio)+"em";
1092
+ word.style.rubyAlign=ruby.align==="center"?"center":"space-between";
1093
+ }
1094
+ }
1095
  renderPreview(s,scene,w,h,useLayout);
1096
+ if(el("styleSamples").open)styleSamples();
1097
  }
1098
  for(const key of designFields) el(key).addEventListener("input",()=>{design[key]=flags.includes(key)?el(key).checked:el(key).value;});
1099
+
1100
  document.querySelector(".workspace").addEventListener("input",update);
1101
  function setTheme(value) {document.documentElement.dataset.theme=value;el("theme").value=value;}
1102
  try{setTheme(localStorage.getItem("moss-ruby-theme")==="dark"?"dark":"light");}catch{setTheme("light");}
1103
  el("theme").onchange=()=>{setTheme(el("theme").value);try{localStorage.setItem("moss-ruby-theme",el("theme").value);}catch{} update();};
1104
+ async function copyPrompt(plain){
1105
+ const text=plain?plainPrompt(settings()):el("prompt").value;
1106
+ try { await navigator.clipboard.writeText(text); }
1107
  catch {
1108
+ const field=document.createElement("textarea");field.value=text;
1109
+ document.body.append(field);field.select();
1110
+ let copied=false;try{copied=document.execCommand("copy")}catch{}
1111
+ if(!copied){field.setAttribute("aria-label","手動コピー用");field.onblur=()=>field.remove();el("notice").textContent="選択した文章を手動でコピーしてください。";return;}
1112
+ field.remove();
1113
  }
1114
+ el("notice").textContent=plain?"プレーンな英文をコピーしました。":"コピーしました。";
1115
+ }
1116
+ el("copy").onclick=()=>copyPrompt(false);
1117
+ el("copyPlain").onclick=()=>copyPrompt(true);
1118
+ let sampleKey="";
1119
+ function styleSamples(){
1120
+ const drawer=el("styleSamples");
1121
+ if(!drawer.open)return;
1122
+ const selection=editorRange()||lastCaret;
1123
+ const selected=selection && !selection.collapsed && editor.contains(selection.commonAncestorContainer)?readGroups(selection.cloneContents()).map(g=>g.text).join(""):"";
1124
+ const st=settings(), text=characters((selected||st.base||"紅蓮").replace(/\s+/g," ")).slice(0,6).join("");
1125
+ if(text===sampleKey)return;
1126
+ sampleKey=text;
1127
+ const grid=drawer.querySelector(".style-grid");grid.replaceChildren();
1128
+ for(const [style,[name]] of Object.entries(styles)){
1129
+ const b=document.createElement("button"), thumb=document.createElement("canvas");b.type="button";
1130
+ b.append(thumb,name);grid.append(b);b.onclick=()=>{setDesign("style",style);update()};
1131
+ const sample={...st,...defaults,style,styleSpec:styles[style],groups:[{text,reading:""}],ornament:""};
1132
+ const view=surface(thumb),scene=composition(sample);
1133
+ paintScene(view.c,scene,frame(scene.box,view.w,view.h),sample,view.dpr);
1134
+ }
1135
+ }
1136
+ el("styleSamples").ontoggle=()=>{if(!el("styleSamples").open)sampleKey="";else styleSamples()};
1137
+ editor.addEventListener("pointerup",styleSamples);
1138
  new ResizeObserver(()=>{update();thumbnails();}).observe(canvas);
1139
  applyPreset(0); thumbnails();
1140
  </script></body></html>