hide1 commited on
Commit
9305a6d
·
verified ·
1 Parent(s): 8e4085d

Upload 2 files

Browse files
Files changed (2) hide show
  1. README.md +15 -11
  2. index.html +440 -18
README.md CHANGED
@@ -1,11 +1,15 @@
1
- ---
2
- title: Moss Image Ruby Maker
3
- emoji: 🌖
4
- colorFrom: pink
5
- colorTo: indigo
6
- sdk: static
7
- pinned: false
8
- short_description: 日本語の親文字とルビからMOSS-Image用のプロンプトを作成
9
- ---
10
-
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
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に貼り付けて生成してください。
index.html CHANGED
@@ -1,19 +1,441 @@
1
  <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
19
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <!doctype html>
2
+ <html lang="ja">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>ルビメーカー | MOSS-Image</title>
7
+ <style>
8
+ :root{color-scheme:light;--bg:#f4f1eb;--ink:#26231f;--sub:#666158;--line:#cfc7bc;--surface:#fffdf9;--accent:#863b35;--button:#853931;--on:#fff;--chip:#eee8df}
9
+ :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}
10
+ *{box-sizing:border-box} [hidden]{display:none!important}
11
+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 "Yu Gothic UI",Meiryo,sans-serif}
12
+ main{max-width:1360px;margin:auto;padding:24px clamp(16px,4vw,64px) 48px}
13
+ header,.bar,.tools,.symbols,.row,.checks,.pal,.actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
14
+ header,.bar{justify-content:space-between}
15
+ header{padding-bottom:16px;border-bottom:2px solid var(--ink)}
16
+ .brand{display:flex;align-items:baseline;gap:16px;flex-wrap:wrap}
17
+ .brand span{font:650 14px/1.2 "Segoe UI",sans-serif;letter-spacing:.04em;color:var(--accent)}
18
+ h1{margin:0;font:700 clamp(28px,3.4vw,44px)/1.2 "Yu Mincho",serif}
19
+ 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)}
27
+ :focus-visible{outline:2px solid var(--accent);outline-offset:2px}
28
+ .preset{padding:0;overflow:hidden;text-align:left}
29
+ .preset[aria-pressed=true]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}
30
+ .preset span{display:block;padding:5px 8px;font-size:12px}
31
+ .preset[aria-pressed=true] span::after{content:" ✓";color:var(--accent)}
32
+ .preset canvas{display:block;width:100%;height:53px}
33
+ .workspace{display:grid;grid-template-columns:minmax(300px,.86fr) minmax(0,1.4fr);gap:clamp(18px,3vw,44px);align-items:start;padding-top:18px}
34
+ fieldset,details{min-width:0;margin:0 0 17px;padding:0 0 16px;border:0;border-bottom:1px solid var(--line)}
35
+ legend,summary{margin-bottom:9px}
36
+ .fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 12px}
37
+ label,.field{display:grid;align-content:start;gap:4px;font-size:13px;font-weight:650}
38
+ .full{grid-column:1/-1}.results{min-width:0;position:sticky;top:10px}
39
+ 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}
40
+ input,select{accent-color:var(--button)} input[type=range]{margin:3px 0;width:100%}
41
+ .tools label,.row label,.checks label,.check,.range-label{display:flex;align-items:center;gap:5px}
42
+ .tools select,.row select{width:auto}.tools label,.hint{color:var(--sub);font-weight:450;font-size:12px}
43
+ .range-label{justify-content:space-between} output{color:var(--accent);font:600 13px Consolas,monospace}
44
+ .chip{padding:5px 8px}.chip:has(input:checked){border-color:var(--accent);color:var(--accent)}
45
+ .checks{gap:6px}.checks input,.check input{margin:0}
46
+ .bar{margin-bottom:9px}.stage{border:1px solid var(--line);overflow:hidden;border-radius:8px;background:var(--chip)}
47
+ #preview{display:block;width:100%;height:clamp(220px,24vw,315px)}
48
+ .hint,.error{margin:6px 0}.error{color:var(--accent);font-size:13px;font-weight:650}
49
+ .prompt{margin-top:18px}.actions{margin-top:8px}
50
+ .primary{background:var(--button);color:var(--on);border-color:var(--button);padding:8px 16px}
51
+ button:disabled{opacity:.45;cursor:default} textarea{resize:vertical;min-height:118px;font:14px/1.6 "Segoe UI",Meiryo,sans-serif}
52
+ #notice{font-size:13px}.symbols{gap:5px}.symbols button{min-width:34px;padding:3px 6px;font-size:17px}
53
+ .pal{gap:6px}.pal button{width:26px;height:26px;padding:0;border:1px solid #8888;border-radius:50%;background:var(--sample)}
54
+ .pal button[aria-pressed=true]{outline:2px solid var(--accent);outline-offset:2px}
55
+ .color-slot{display:flex;align-items:center;gap:8px}
56
+ input[type=color]{width:39px;height:32px;border:1px solid var(--line);border-radius:4px;background:var(--surface);padding:2px}
57
+ #hex{color:var(--sub);font:13px Consolas,monospace}
58
+ @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}}
59
+ @media(max-height:650px){.results{position:static}}
60
+ </style>
61
+ </head>
62
+ <body><main>
63
+ <header><div class="brand"><h1>ルビメーカー</h1><span lang="en">MOSS-Image</span></div>
64
+ <div class="tools"><label>画面テーマ<select id="theme"><option value="light">ライト</option><option value="dark">ダーク</option></select></label></div></header>
65
+ <section class="presets" aria-labelledby="presetTitle"><h2 id="presetTitle">装飾見本</h2><div id="presets" class="preset-grid"></div></section>
66
+ <div class="workspace">
67
+ <section aria-label="文字の設定">
68
+ <fieldset><legend>文字と配置</legend>
69
+ <div class="fields">
70
+ <label>親文字<input id="base" type="text" value="紅蓮"></label>
71
+ <label>ルビ<input id="reading" type="text" value="グレン" placeholder="ひらがな・カタカナ"></label>
72
+ <label>ルビの配置<select id="align"><option value="spread">親文字の幅に均等配置</option><option value="center">中央にまとめる</option><option value="groups">グループごと</option></select></label>
73
+ <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>
74
+ <p id="groupHint" class="hint full" hidden>同じ位置を「|」で区切ります。例:親文字「紅|蓮」、ルビ「グ|レン」。読みのない組は空欄にできます。</p>
75
+ </div></fieldset>
76
+ <fieldset><legend>書体と装飾</legend>
77
+ <div class="fields">
78
+ <label>書体スタイル<select id="style"></select></label>
79
+ <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>
80
+ <div class="checks full" aria-label="文字修飾">
81
+ <label class="chip"><input type="checkbox" id="bold">太字</label><label class="chip"><input type="checkbox" id="italic">斜体</label>
82
+ <label class="chip"><input type="checkbox" id="underline">下線</label><label class="chip"><input type="checkbox" id="strike">取り消し線</label>
83
+ </div>
84
+ <label>縁取り<select id="outline"><option value="none">なし</option><option value="thin">細め</option><option value="bold">太め</option><option value="double">二重</option></select></label>
85
+ <label class="check"><input id="includeRuby" type="checkbox">装飾をルビにも適用</label>
86
+ </div></fieldset>
87
+ <fieldset><legend>配色</legend><div class="fields">
88
+ <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>
89
+ <label>自由に選ぶ<span class="color-slot"><input id="picker" type="color" value="#171717"><span id="hex"></span></span></label>
90
+ <div id="palette" class="pal full" role="group" aria-label="色見本"></div>
91
+ <label class="check full"><input type="checkbox" id="linked" checked>ルビは親文字と同じ色</label>
92
+ </div></fieldset>
93
+ <details><summary>記号・絵文字</summary><div class="fields">
94
+ <label>挿入先<select id="symbolTarget"><option value="base">親文字の中</option><option value="reading">ルビの中</option><option value="ornament">右側の飾り</option></select></label>
95
+ <label>右側の飾り<input type="text" id="ornament" placeholder="例:🔥"></label>
96
+ <div class="symbols full" id="symbols"></div></div></details>
97
+ </section>
98
+ <section class="results" aria-label="確認とコピー">
99
+ <div class="bar"><h2>組版プレビュー</h2><div class="tools"><label>確認用の背景<select id="paper"><option value="#ffffff">白</option><option value="#262626">墨色</option></select></label></div></div>
100
+ <div class="stage"><canvas id="preview" role="img" aria-label="文字の配置"></canvas></div>
101
+ <p class="hint">配置・配色・装飾の確認用です。MOSS-Imageで生成した画像では、文字や効果の見え方が変わります。</p>
102
+ <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>
103
+ <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>
104
+ <p class="hint">生成側も同じ幅・高さに設定し、JSON全体をポジティブプロンプトに貼り付けます。</p></div>
105
+ <p id="error" role="status" class="error" hidden></p>
106
+ <textarea id="prompt" lang="en" aria-labelledby="promptTitle" readonly placeholder="親文字を入力してください"></textarea>
107
+ <div class="actions"><button class="primary" id="copy" type="button">プロンプトをコピー</button><span role="status" id="notice"></span></div>
108
+ </section></section></div></main>
109
+ <script>
110
+ "use strict";
111
+ const el = id => document.getElementById(id);
112
+ const styles = {
113
+ plain: ["指定なし", "", '400', 'sans-serif'],
114
+ mincho: ["明朝", "traditional Japanese Mincho lettering with fine horizontal strokes and tapered serifs", '700', '"Yu Mincho", "MS PMincho", serif'],
115
+ gothic: ["ゴシック", "bold Japanese Gothic lettering with clean, even strokes", '500', '"Yu Gothic", Meiryo, sans-serif'],
116
+ round: ["丸ゴシック", "rounded Japanese Gothic lettering with soft terminals", '400', '"Hiragino Maru Gothic ProN", "BIZ UDPGothic", Meiryo, sans-serif'],
117
+ pop: ["ポップ", "playful, chunky Japanese display lettering with plump rounded shapes", '700', '"M PLUS Rounded 1c", "Hiragino Maru Gothic ProN", Meiryo, sans-serif'],
118
+ brush: ["筆文字", "expressive Japanese brush lettering with sweeping tapered strokes", '400', '"HGS行書体", "HG行書体", "Yu Mincho", serif'],
119
+ pen: ["手書き", "casual handwritten Japanese lettering with light, gently irregular pen strokes", '400', '"HGP教科書体", "Yu Kyokasho", "UD Digi Kyokasho N-R", "Yu Gothic", sans-serif']
120
+ };
121
+ for (const [key, spec] of Object.entries(styles)) el("style").add(new Option(spec[0], key));
122
+ const segmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter("ja", {granularity: "grapheme"}) : null;
123
+ function characters(text) {
124
+ return segmenter ? Array.from(segmenter.segment(text), part => part.segment) : Array.from(text);
125
+ }
126
+ const palette = [
127
+ ["#171717","墨","near-black"],["#ffffff","白","white"],["#db503d","朱","vermilion"],["#8b293e","臙脂","burgundy"],
128
+ ["#e57d93","桃","rose pink"],["#eaa439","山吹","amber"],["#b8893c","金","warm gold"],["#366b54","深緑","forest green"],
129
+ ["#386eac","藍","deep blue"],["#714e93","紫","violet"],["#41bcca","青緑","turquoise"],["#6c7077","灰","slate gray"]
130
+ ];
131
+ const colorText = hex => palette.find(c => c[0] === hex)?.[2] || hex.toUpperCase();
132
+ const defaults = {style:"mincho", effect:"flat", outline:"none", ink:"#171717", ruby:"#171717", edge:"#ffffff", outer:"#171717", side:"#8b293e",
133
+ bold:false, italic:false, underline:false, strike:false, includeRuby:false, linked:true};
134
+ const presets = [
135
+ ["プレーン", {style:"plain"}, "#ffffff"],
136
+ ["和文タイトル", {}, "#f7f3e9"],
137
+ ["漫画の決め文字", {style:"brush", italic:true, bold:true, outline:"double", ink:"#db503d"}, "#f7e3c4"],
138
+ ["ポップステッカー", {style:"pop", effect:"shadow", outline:"bold", ink:"#e57d93", side:"#714e93"}, "#f1deec"],
139
+ ["レトロ立体ロゴ", {style:"round", bold:true, ink:"#db503d", side:"#8b293e", effect:"depth"}, "#f6deb1"],
140
+ ["箔押し", {ink:"#b8893c", effect:"foil"}, "#312b28"],
141
+ ["ネオンサイン", {style:"round", ink:"#41bcca", side:"#41bcca", effect:"neon"}, "#202c36"]
142
+ ];
143
+ const design = {...defaults};
144
+ const flags = ["bold","italic","underline","strike","includeRuby","linked"];
145
+ const designFields = ["style","effect","outline",...flags];
146
+ 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"};
147
+ function settings() {
148
+ const base = el("base").value.trim(), reading = el("reading").value.trim();
149
+ const align = el("align").value, grouped = align === "groups";
150
+ const bases = grouped ? base.split(/[||]/) : [base];
151
+ const readings = grouped && reading ? reading.split(/[||]/) : [reading];
152
+ const groups = bases.map((text,i) => ({text, reading:readings[i] || ""}));
153
+ const error = grouped && (bases.some(t=>!t.trim()) || (reading && readings.length !== bases.length))
154
+ ? "親文字とルビの区切り数を揃え、親文字は各組に入力してください。" : "";
155
+ return {...design, styleSpec:styles[design.style], base:bases.join(""), reading:readings.join(""), groups, align, error,
156
+ ratio:Number(el("size").value)/100, rubyInk:design.linked ? design.ink : design.ruby, ornament:el("ornament").value.trim()};
157
+ }
158
+ function finishText(s) {
159
+ const side = colorText(s.side);
160
+ const phrases = {
161
+ flat:"", shadow:"A crisp "+side+" shadow falls down and to the right.",
162
+ depth:"Solid "+side+" sides extend down and to the right from the letter faces.",
163
+ foil:"Metallic foil catches the light in narrow bands across the strokes.",
164
+ emboss:"Beveled edges catch light at the upper left and cast shallow inner shadows.",
165
+ neon:"Bright tube-like strokes give off a soft "+side+" glow."
166
+ };
167
+ return phrases[s.effect];
168
+ }
169
+ function decorations(s) {
170
+ const a=[];
171
+ if (s.bold) a.push("Use extra-heavy strokes.");
172
+ if (s.italic) a.push("Slant the letters to the right.");
173
+ if (s.underline) a.push("Draw a continuous line just beneath the lettering.");
174
+ if (s.strike) a.push("Draw a horizontal strike through the middle of the lettering.");
175
+ if (s.outline === "double") a.push("Trace the letters with a "+colorText(s.edge)+" inner outline and a "+colorText(s.outer)+" outer outline.");
176
+ else if (s.outline !== "none") a.push("Trace the letters with a "+(s.outline === "thin" ? "fine" : "thick")+" "+colorText(s.edge)+" outline.");
177
+ if (s.effect !== "flat") a.push(finishText(s));
178
+ return a.join(" ");
179
+ }
180
+ function rubyText(s,reading) {
181
+ const spread=s.align==="spread" && characters(reading).length>1;
182
+ return "Use small "+colorText(s.rubyInk)+" furigana directly above the main lettering, about "+Math.round(s.ratio*100)+"% of its height. "+
183
+ (spread ? "Space the glyphs evenly from the left edge to the right edge of the title, keeping their natural proportions." : "Center the reading over its corresponding text with natural character spacing.");
184
+ }
185
+ function ornamentText(s) {
186
+ const desc = symbolNames[s.ornament] || "a decorative mark shaped like “"+s.ornament+"”";
187
+ return "Place "+desc+" to the right of the title as a separate ornament.";
188
+ }
189
+ function plainPrompt(s) {
190
+ let text = "Write “"+s.base+"”";
191
+ if (s.reading) {
192
+ if (s.align==="groups" && s.groups.length>1) {
193
+ const pairs=s.groups.filter(g=>g.reading).map(g=>"“"+g.reading+"” above “"+g.text+"”");
194
+ text+=" with small furigana: "+pairs.join(", ");
195
+ } else {
196
+ const spread=s.align==="spread" && characters(s.reading).length>1;
197
+ text+=" with small furigana “"+s.reading+"” "+(spread ? "above it, spanning its width" : "centered above it");
198
+ }
199
+ }
200
+ if (s.ornament) text+=", with “"+s.ornament+"” on the right";
201
+ return text+".";
202
+ }
203
+ function makePrompt(s) {
204
+ const d=decorations(s);
205
+ if (!s.styleSpec[1] && !d && s.ink===defaults.ink && (!s.reading || (s.rubyInk===defaults.ink && s.ratio===.2))) return plainPrompt(s);
206
+ const face=s.styleSpec[1] ? " using "+s.styleSpec[1] : "";
207
+ const lines=["Render the horizontal title “"+s.base+"” in "+colorText(s.ink)+face+"."];
208
+ if (d) lines.push(d);
209
+ if (s.reading) {
210
+ if (s.align==="groups") {
211
+ for (const g of s.groups) if(g.reading) lines.push("Place “"+g.reading+"” directly above “"+g.text+"”.");
212
+ } else lines.push("The reading is “"+s.reading+"”.");
213
+ lines.push(rubyText(s,s.reading));
214
+ if (d) lines.push(s.includeRuby ? "Repeat the title treatment on the reading at its smaller scale." : "Keep the reading plain and upright.");
215
+ }
216
+ if (s.ornament) lines.push(ornamentText(s));
217
+ return lines.join(" ");
218
+ }
219
+ const canvas=el("preview"), ctx=canvas.getContext("2d");
220
+ function measure(text,size,s,decorated) {
221
+ // Keep the native face. paintRun adds bold once, including for single-weight script fonts.
222
+ const font = (decorated && s.italic ? "italic " : "")+s.styleSpec[2]+" "+size+"px "+s.styleSpec[3];
223
+ ctx.font=font;
224
+ const m=ctx.measureText(text), left=text.trim() ? -m.actualBoundingBoxLeft : 0;
225
+ return {text,font,size,left,width:text.trim()? Math.max(1,m.actualBoundingBoxRight-left) : m.width, top:m.actualBoundingBoxAscent,bottom:m.actualBoundingBoxDescent};
226
+ }
227
+ // All geometry is in lettering units, shared by the preview and Layout exporter.
228
+ function composition(s) {
229
+ const size=160, items=[];
230
+ let cursor=0;
231
+ for (const g of s.groups) {
232
+ const base=measure(g.text,size,s,true);
233
+ const spread=s.align==="spread";
234
+ const letters=spread ? characters(g.reading) : (g.reading ? [g.reading] : []);
235
+ const rubySize=size*s.ratio;
236
+ let ruby=letters.map(ch=>measure(ch,rubySize,s,s.includeRuby));
237
+ const sumWidth=runs=>runs.reduce((w,r)=>w+r.width,0);
238
+ let rw=sumWidth(ruby);
239
+ if (spread && rw>base.width) {
240
+ ruby=letters.map(ch=>measure(ch,rubySize*base.width/rw,s,s.includeRuby));
241
+ rw=sumWidth(ruby);
242
+ }
243
+ const width=Math.max(base.width,rw);
244
+ items.push({type:"base",text:g.text, runs:[{...base,x:cursor+(width-base.width)/2}], baseline:0});
245
+ if (ruby.length) {
246
+ const spacing=spread && ruby.length>1 ? (width-rw)/(ruby.length-1) : 0;
247
+ let x=cursor+(spacing ? 0 : (width-rw)/2);
248
+ const runs=ruby.map(r=>{const run={...r,x}; x+=r.width+spacing; return run;});
249
+ items.push({type:"ruby",text:g.reading,runs,baseline:0});
250
+ }
251
+ cursor+=width+(s.groups.length>1 ? size*.045 : 0);
252
+ }
253
+ const bases=items.filter(i=>i.type==="base");
254
+ const baseTop=bases.reduce((a,i)=>Math.max(a,i.runs[0].top),0);
255
+ const rubyDesc=items.filter(i=>i.type==="ruby").reduce((a,i)=>i.runs.reduce((b,r)=>Math.max(b,r.bottom),a),0);
256
+ for (const i of items) if(i.type==="ruby") i.baseline=-baseTop-size*.08-rubyDesc;
257
+ if (s.ornament) {
258
+ const mark=measure(s.ornament,size*.36,s,false);
259
+ items.push({type:"ornament", text:s.ornament,runs:[{...mark,x:cursor+size*.13}],baseline:-baseTop*.45+(mark.top-mark.bottom)/2});
260
+ }
261
+ for(const i of items){
262
+ const pad = i.type==="ornament" ? 0 : ((i.type==="base" || s.includeRuby) ? extent(s,i.runs[0].size) : 0);
263
+ 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]);
264
+ }
265
+ 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]);
266
+ return {items,box};
267
+ }
268
+ function extent(s,size) {
269
+ const edge={none:0,thin:.02,bold:.05,double:.075}[s.outline];
270
+ const effect={flat:0,shadow:.10,depth:.12,foil:0,emboss:.025,neon:.15}[s.effect];
271
+ return size*Math.max(edge+effect,s.underline ? .12 : 0, s.bold ? .014 : 0);
272
+ }
273
+ function frame(box,w,h) {
274
+ const bw=Math.max(1,box[2]-box[0]), bh=Math.max(1,box[3]-box[1]);
275
+ const scale=Math.min(w*.82/bw,h*.68/bh);
276
+ return {scale,x:(w-bw*scale)/2-box[0]*scale,y:(h-bh*scale)/2-box[1]*scale};
277
+ }
278
+ function draftLayout(s,scene,w,h) {
279
+ const f=frame(scene.box,w,h);
280
+ const items=scene.items.map(i=>{
281
+ const box=i.box.map((v,j)=>v*f.scale+(j%2 ? f.y : f.x));
282
+ if (i.type==="ornament") return {label:"object",caption:ornamentText(s),bbox:box};
283
+ const caption=i.type==="base" ? [colorText(s.ink)+" "+(s.styleSpec[1] || "lettering")+".",decorations(s)].filter(Boolean).join(" ") :
284
+ rubyText(s,i.text)+" "+(s.includeRuby ? decorations(s) : "Plain upright lettering.");
285
+ return {label:"text",text:i.text,caption,bbox:box};
286
+ });
287
+ return {width:w,height:h,bbox_coord_space:"abs",bbox_format:"xyxy",summary:{canvas:"single",caption:makePrompt(s)},items};
288
+ }
289
+ // Match the official pixel-layout compiler: enclose fractional edges, then center y/x.
290
+ function compileLayout(draft) {
291
+ const {width,height,summary}=draft;
292
+ const items=draft.items.map(item=>{
293
+ const [l,t,r,b]=item.bbox.map(edge=>Number(edge.toFixed(9)));
294
+ return {...item,bbox:[Math.floor(t)-height/2, Math.floor(l)-width/2, Math.ceil(b)-height/2, Math.ceil(r)-width/2]};
295
+ });
296
+ return {summary,items,bbox_coord_space:"abs_centralized",bbox_format:"yxyx"};
297
+ }
298
+ function paintRun(c,r,baseline,ink,s,decorated,scale) {
299
+ const x=r.x-r.left, y=baseline, n=r.size;
300
+ c.save(); c.font=r.font; c.lineJoin="round"; c.fillStyle=ink;
301
+ function stroke(color,width) { c.strokeStyle=color; c.lineWidth=n*width; c.strokeText(r.text,x,y); }
302
+ if (decorated) {
303
+ if(s.effect==="shadow" || s.effect==="depth"){
304
+ c.fillStyle=s.side;
305
+ const steps=s.effect==="depth" ? 8 : 1, depth=n*(s.effect==="depth" ? .035 : .025);
306
+ for(let j=steps;j>0;j--) c.fillText(r.text,x+depth*j/steps,y+depth*j/steps);
307
+ } else if(s.effect==="emboss"){
308
+ c.fillStyle="#574838"; c.fillText(r.text,x+n*.018,y+n*.018);
309
+ c.fillStyle="#fff2d5"; c.fillText(r.text,x-n*.014,y-n*.014);
310
+ } else if(s.effect==="neon"){
311
+ c.shadowColor=s.side; c.shadowBlur=Math.min(64,n*scale*.1);
312
+ stroke(s.side,.018); c.fillStyle=s.side; c.fillText(r.text,x,y); c.shadowBlur=0;
313
+ }
314
+ if (s.outline==="double") stroke(s.outer,.038);
315
+ if (s.outline!=="none") stroke(s.edge,{thin:.012,bold:.027,double:.021}[s.outline]);
316
+ if(s.bold) stroke(ink,.008);
317
+ }
318
+ c.fillStyle=ink;
319
+ if(decorated && (s.effect==="foil" || s.effect==="emboss")){
320
+ const grad=c.createLinearGradient(x,y-r.top,x+n*.15,y+Math.max(r.bottom,1));
321
+ for(const [p,color] of [[0,ink],[.29,ink],[.42,s.effect==="foil"?"#fff4ce":"#dbcdb9"],[.52,ink],[1,ink]]) grad.addColorStop(p,color);
322
+ c.fillStyle=grad;
323
+ }
324
+ c.fillText(r.text,x,y); c.restore();
325
+ }
326
+ function paintScene(c,scene,f,s,deviceScale) {
327
+ c.save(); c.translate(f.x,f.y); c.scale(f.scale,f.scale);
328
+ for (const i of scene.items) {
329
+ const decorated=i.type==="base" || (i.type==="ruby" && s.includeRuby);
330
+ const ink=i.type==="ruby" ? s.rubyInk : s.ink;
331
+ for (const r of i.runs) paintRun(c,r,i.baseline,ink,s,decorated,f.scale*deviceScale);
332
+ if (decorated && (s.underline || s.strike)){
333
+ const first=i.runs[0], last=i.runs[i.runs.length-1], width=last.x+last.width-first.x;
334
+ const thick=first.size*.035;
335
+ c.fillStyle=ink;
336
+ 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);
337
+ if(s.strike) c.fillRect(first.x,i.baseline-first.top*.45,width,thick);
338
+ }
339
+ }
340
+ c.restore();
341
+ }
342
+ function surface(target) {
343
+ const w=target.clientWidth,h=target.clientHeight,dpr=window.devicePixelRatio||1;
344
+ const pixelWidth=Math.round(w*dpr), pixelHeight=Math.round(h*dpr);
345
+ if(target.width!==pixelWidth || target.height!==pixelHeight){target.width=pixelWidth;target.height=pixelHeight;}
346
+ const c=target.getContext("2d"); c.setTransform(dpr,0,0,dpr,0,0);
347
+ return {c,w,h,dpr};
348
+ }
349
+ function renderPreview(s,scene,w,h,useLayout) {
350
+ const view=surface(canvas),c=view.c;
351
+ c.fillStyle=useLayout ? getComputedStyle(canvas).getPropertyValue("--chip") : el("paper").value;
352
+ c.fillRect(0,0,view.w,view.h);
353
+ if(!scene || !w || !h) return;
354
+ const z=useLayout ? Math.min(view.w/w,view.h/h) : 1;
355
+ c.save(); c.translate((view.w-w*z)/2,(view.h-h*z)/2); c.scale(z,z);
356
+ c.fillStyle=el("paper").value;c.fillRect(0,0,w,h);
357
+ paintScene(c,scene,frame(scene.box,w,h),s,z*view.dpr); c.restore();
358
+ }
359
+ const presetButtons=[];
360
+ function setDesign(key,value) {
361
+ design[key]=value;
362
+ if (flags.includes(key)) el(key).checked=value;
363
+ else if(designFields.includes(key)) el(key).value=value;
364
+ }
365
+ function applyPreset(index) {
366
+ const spec={...defaults,...presets[index][1]};
367
+ for(const [key,value] of Object.entries(spec)) setDesign(key,value);
368
+ update();
369
+ }
370
+ for(const [index,[name]] of presets.entries()){
371
+ const b=document.createElement("button"), thumb=document.createElement("canvas"), label=document.createElement("span");
372
+ b.type="button"; b.className="preset"; thumb.setAttribute("aria-hidden","true"); label.textContent=name;
373
+ b.append(thumb,label); el("presets").append(b); b.onclick=()=>applyPreset(index); presetButtons.push(b);
374
+ }
375
+ function thumbnails(){
376
+ for(const [i,[name,spec,paper]] of presets.entries()){
377
+ const thumb=presetButtons[i].querySelector("canvas"),view=surface(thumb);
378
+ const s={...defaults,...spec,groups:[{text:"紅蓮",reading:spec.style==="plain" ? "グレン" : ""}],align:"spread",ratio:.2,ornament:""};
379
+ s.styleSpec=styles[s.style]; s.rubyInk=s.ink;
380
+ view.c.fillStyle=paper; view.c.fillRect(0,0,view.w,view.h);
381
+ const scene=composition(s); paintScene(view.c,scene,frame(scene.box,view.w,view.h),s,view.dpr);
382
+ }
383
+ }
384
+ function editColor(hex){
385
+ const target=el("target").value;
386
+ if(target==="ruby" && design.linked) setDesign("linked",false);
387
+ design[target]=hex; update();
388
+ }
389
+ for (const [hex,label] of palette){
390
+ const b=document.createElement("button"); b.type="button"; b.title=label; b.setAttribute("aria-label",label); b.dataset.hex=hex;
391
+ b.style.setProperty("--sample",hex); b.onclick=()=>editColor(hex); el("palette").append(b);
392
+ }
393
+ for(const symbol of Object.keys(symbolNames)){
394
+ const b=document.createElement("button"); b.type="button"; b.textContent=symbol; b.setAttribute("aria-label",symbol+"を挿入");
395
+ b.onclick=()=>{const input=el(el("symbolTarget").value); input.setRangeText(symbol,input.selectionStart,input.selectionEnd,"end"); input.focus(); update();};
396
+ el("symbols").append(b);
397
+ }
398
+ function update(){
399
+ const s=settings(), format=el("format").value, useLayout=format==="layout";
400
+ const w=useLayout ? el("width").valueAsNumber : canvas.clientWidth, h=useLayout ? el("height").valueAsNumber : canvas.clientHeight;
401
+ const validSize=n=>Number.isSafeInteger(n) && n>0 && n%16===0;
402
+ const error=(s.base && s.error) || (useLayout && (!validSize(w)||!validSize(h)) ? "生成幅と高さは16の倍数で入力してください。" : "");
403
+ const scene=s.base && !error ? composition(s) : null;
404
+ el("dimensions").hidden=!useLayout; el("groupHint").hidden=s.align!=="groups";
405
+ el("error").textContent=error; el("error").hidden=!error; el("sizeValue").value=el("size").value+"%";
406
+ let prompt="";
407
+ if (scene) {
408
+ if (useLayout) prompt=JSON.stringify(compileLayout(draftLayout(s,scene,w,h)));
409
+ else prompt=makePrompt(s);
410
+ }
411
+ el("prompt").value=prompt;
412
+ el("copy").disabled=!scene; el("notice").textContent="";
413
+ canvas.setAttribute("aria-label",s.base ? s.base+(s.reading ? "、ルビは"+s.reading : "") : "親文字を入力してください");
414
+ const target=el("target").value,hex=target==="ruby" ? s.rubyInk : design[target];
415
+ el("hex").textContent=hex.toUpperCase(); el("picker").value=hex;
416
+ for(const b of el("palette").children) b.setAttribute("aria-pressed",String(b.dataset.hex===hex));
417
+ for(const [i,b] of presetButtons.entries()){
418
+ const spec={...defaults,...presets[i][1]};
419
+ b.setAttribute("aria-pressed",String(Object.keys(defaults).every(k=>design[k]===spec[k])));
420
+ }
421
+ renderPreview(s,scene,w,h,useLayout);
422
+ }
423
+ for(const key of designFields) el(key).addEventListener("input",()=>{design[key]=flags.includes(key)?el(key).checked:el(key).value;});
424
+ el("picker").addEventListener("input",e=>{e.stopPropagation();editColor(e.target.value);});
425
+ document.querySelector(".workspace").addEventListener("input",update);
426
+ function setTheme(value) {document.documentElement.dataset.theme=value;el("theme").value=value;}
427
+ try{setTheme(localStorage.getItem("moss-ruby-theme")==="dark"?"dark":"light");}catch{setTheme("light");}
428
+ el("theme").onchange=()=>{setTheme(el("theme").value);try{localStorage.setItem("moss-ruby-theme",el("theme").value);}catch{} update();};
429
+ el("copy").addEventListener("click",async()=>{
430
+ const box=el("prompt");
431
+ try { await navigator.clipboard.writeText(box.value); }
432
+ catch {
433
+ box.focus();box.select();
434
+ let copied=false; try{copied=document.execCommand("copy");}catch{}
435
+ if(!copied){el("notice").textContent="選択した文章を手動でコピーしてください。";return;}
436
+ }
437
+ el("notice").textContent="コピーしました。";
438
+ });
439
+ new ResizeObserver(()=>{update();thumbnails();}).observe(canvas);
440
+ applyPreset(0); thumbnails();
441
+ </script></body></html>