@first-ch/tools-mcp 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/css-layout.mjs ADDED
@@ -0,0 +1,612 @@
1
+ /* Flexbox / CSS Grid ジェネレーター(css_layout_generate)
2
+ * FirstCHTools の site/css-layout/app.js(正本)から、指定→CSS / HTML の組み立てと指摘を写したもの
3
+ * (2箇所ルール: site側が正本・片方を直したらもう片方も同じ内容で反映する)。
4
+ *
5
+ * site側にはコアの開始/終了の目印が無いため、次の3節を節見出しのコメントごと写している:
6
+ * 「grid-template-areas の検証」「CSS の組み立て」「指摘(チェック結果)」
7
+ * site側との違いは、関数がモジュール内の state / T を直接読む代わりに引数で受けることだけ:
8
+ * parseAreas(text) → parseAreas(text, T) / flexDecls() → flexDecls(state) / gridColsCss() → gridColsCss(state)
9
+ * gridDecls(area) → gridDecls(state, area) / itemDecls(it) → itemDecls(state, it)
10
+ * buildCss(area) → buildCss(state, area) / buildHtml(area) → buildHtml(state, area) / diagnose(area) → diagnose(state, area, T)
11
+ * 同期の確認は、site側の3節を切り出して上の置き換えを当てたもの(字下げ2文字を落とす)と、
12
+ * こちらの3節(行頭の export を落とす)の diff が空になること。
13
+ * 文言(T・VAL)・子要素の既定(DEF_ITEM)・状態の初期値・プリセット(PRESETS)も site と同じ値。
14
+ * プレビューの描画・折り返し行数の実測(DOM が要る)・コピー・タブ・URLパラメータは持たない。
15
+ * 完全ローカル処理・ネットワーク送信なし。 */
16
+
17
+ /* ==================== 文言(site の T。site は <html lang>、こちらは lang 引数で選ぶ) ==================== */
18
+
19
+ export const CL_TEXT = {
20
+ ja: {
21
+ item: (n) => `子要素 ${n}`,
22
+ lines: (n) => `${n}行`,
23
+ tracks: (n) => `${n}本`,
24
+ areaErrRagged: (n, m) => `grid-template-areas は全ての行のマス数を揃える必要があります(${n}行目が${m}マス)。`,
25
+ areaErrRect: (name) => `エリア「${name}」が長方形になっていません。名前がL字や分断された形になると、CSSは grid-template-areas の値全体を捨てます。`,
26
+ areaErrEmpty: 'エリア名を1行以上入れてください(例: 「header header」/「side main」)。',
27
+ areaErrName: (tok) => `「${tok}」はエリア名に使えません(英数字・- ・_ のみ。「.」1文字だけは空きマスの意味)。`,
28
+ areaOk: (r, c, n) => `${r} 行 × ${c} 列・名前の付いたエリアは ${n} 個。`,
29
+ trackCountMismatch: (t, a) => `列トラックは ${t} 本ですが、エリアの行は ${a} マスです。あふれたマスは暗黙のトラック(grid-auto-columns: auto)に入ります。`,
30
+ noFreeSpace: '1fr のトラックが余白を全部使うため、justify-content に配る余りが残りません。',
31
+ justifyDead: 'flex-grow が 0 より大きい子要素があるので、行に余白が残らず justify-content は効きません。',
32
+ alignContentDead: 'align-content は折り返した「行」を動かすプロパティです。flex-wrap: nowrap では行が1本しかないので何も起きません。',
33
+ alignItemsStretchNote: 'align-items: stretch は子要素の高さをいちばん高いものに揃えます(背の低い箱が伸びているのはこれ)。外したい子要素には align-self か height を指定します。',
34
+ reverseNote: 'row-reverse / column-reverse は描く順だけを反転します。Tab移動と読み上げの順はHTMLのままなので、マークアップは読む順で書いてください。',
35
+ gapNote: 'flexbox の gap は Safari 14.1(2021年)以降が必要です。それ以前のSafariは無視して隙間が消えるため、対応が必要なら margin を使います。',
36
+ shrinkNote: 'flex-shrink は元の幅に掛け算されます。同じ値でも、幅の広い子要素のほうが多くのピクセルを譲ります。',
37
+ basisNote: 'flex-basis: 0 は行の全幅を flex-grow の比で配ります。auto は先に中身の幅を確保して残りだけを配るので、grow を同じにしても幅は揃いません。',
38
+ minWidthNote: 'flex の子要素は中身の幅より狭くなりません(min-width: auto)。長いURLや表が入ると行があふれるので、縮めたい子要素には min-width: 0 を足します。',
39
+ frMinNote: '1fr の最小値は auto なので、幅の広い中身(長いURL・表・pre)が入るとトラックが持ち分を超えてグリッドがあふれます。縮めたいときは minmax(0, 1fr) と書きます。',
40
+ autoFitNote: 'auto-fit は空いたトラックを畳むので子要素が伸びて埋まります。auto-fill はトラックを残すため末尾に空きができます——違いはここだけです。',
41
+ wrapNote: 'flex-wrap: wrap が狭い画面での積み上がりを作ります。無いと子要素は下へ回らず、読めない幅まで縮み続けます。',
42
+ dense: 'grid-auto-flow の dense は空いたマスを後ろの子要素で埋めるため、HTMLより前に表示される子要素が出ます。読む順が崩れます。',
43
+ itemsN: (n) => `子要素 ${n} 個`,
44
+ areaLegend: '名前付きエリア',
45
+ selHint: (n) => `子要素 ${n} を編集しています。プレビューの箱をクリックすると切り替わります。`,
46
+ selHintArea: '名前付きエリアでは配置を名前で決めるため、ここで子要素ごとに設定する項目はありません。',
47
+ dirRow: '主軸は左→右。justify-content が横、align-items が縦を動かします。',
48
+ dirRowRev: '主軸は右→左。HTMLで最初の子要素が右端に描かれます。',
49
+ dirCol: '主軸は上→下。justify-content が縦、align-items が横を動かす——2つの役割が入れ替わります。',
50
+ dirColRev: '主軸は下→上。HTMLで最初の子要素が下端に描かれます。',
51
+ },
52
+ en: {
53
+ item: (n) => `Item ${n}`,
54
+ lines: (n) => (n === 1 ? '1 line' : `${n} lines`),
55
+ tracks: (n) => (n === 1 ? '1 track' : `${n} tracks`),
56
+ areaErrRagged: (n, m) => `Every row of grid-template-areas needs the same number of cells. Row ${n} has ${m}.`,
57
+ areaErrRect: (name) => `The area "${name}" is not a rectangle. CSS throws away the whole grid-template-areas value when any name is L-shaped or split.`,
58
+ areaErrEmpty: 'Type at least one row of area names, for example "header header" / "side main".',
59
+ areaErrName: (tok) => `"${tok}" cannot be an area name. Use letters, digits, - and _ (a lone "." means an empty cell).`,
60
+ areaOk: (r, c, n) => `${r} × ${c} cells, ${n} named ${n === 1 ? 'area' : 'areas'}.`,
61
+ trackCountMismatch: (t, a) => `grid-template-columns has ${t} tracks but the area rows have ${a} cells. The extra cells fall into implicit tracks sized by grid-auto-columns (auto).`,
62
+ noFreeSpace: 'A track is 1fr, so it eats all the free space — justify-content then has nothing left to distribute.',
63
+ justifyDead: 'An item has flex-grow above 0, so the items fill the line and justify-content has no free space to distribute.',
64
+ alignContentDead: 'align-content only moves wrapped lines. With flex-wrap: nowrap there is a single line, so it does nothing.',
65
+ alignItemsStretchNote: 'align-items: stretch makes the items as tall as the tallest one (that is why the short boxes match). Give an item align-self or a height to opt out.',
66
+ reverseNote: 'row-reverse / column-reverse only flips the painting order. Tab and screen-reader order still follow the HTML, so keep the markup in reading order.',
67
+ gapNote: 'gap in flexbox needs Safari 14.1+ (2021). Older Safari ignores it and the items touch — use margins if you must support it.',
68
+ shrinkNote: 'flex-shrink is multiplied by the base size, so a wide item gives up more pixels than a narrow one at the same shrink value.',
69
+ basisNote: 'flex-basis: 0 distributes the whole line by flex-grow. With auto the content width is reserved first and only the leftover is shared, so equal grow values still produce unequal widths.',
70
+ minWidthNote: 'A flex item will not shrink below the width of its content (min-width: auto). Long words or a table inside make the line overflow — add min-width: 0 to the item to allow it.',
71
+ frMinNote: 'A 1fr track has a minimum of auto, so wide content (long URLs, tables, pre) pushes the track past its share and the grid overflows. Write minmax(0, 1fr) to let it shrink.',
72
+ autoFitNote: 'auto-fit collapses the empty tracks, so the items stretch to fill the row. auto-fill keeps them, leaving a gap at the end — that is the only difference.',
73
+ wrapNote: 'flex-wrap: wrap is what lets narrow screens stack. Without it the items shrink past readability instead of moving down.',
74
+ dense: 'grid-auto-flow: dense backfills holes, so items can appear before earlier ones. Reading order stops matching the HTML.',
75
+ itemsN: (n) => `${n} items`,
76
+ areaLegend: 'Named areas',
77
+ selHint: (n) => `Editing item ${n}. Click a box in the preview to switch.`,
78
+ selHintArea: 'With named areas each box is placed by its name, so there is nothing to set per item here.',
79
+ dirRow: 'Main axis runs left → right. justify-content moves the items horizontally, align-items vertically.',
80
+ dirRowRev: 'Main axis runs right → left. The first item in the HTML is painted on the right.',
81
+ dirCol: 'Main axis runs top → bottom. justify-content now moves the items vertically and align-items horizontally — the two swap roles.',
82
+ dirColRev: 'Main axis runs bottom → top. The first item in the HTML is painted at the bottom.',
83
+ },
84
+ };
85
+
86
+ /* 値ごとの一言解説(site の VAL と同じ。[日本語, 英語]) */
87
+ export const VAL = {
88
+ 'justify-content': {
89
+ 'flex-start': ['主軸の先頭へ寄せます(既定)。', 'Packs the items at the start of the main axis (default).'],
90
+ 'flex-end': ['主軸の末尾へ寄せます。', 'Packs the items at the end of the main axis.'],
91
+ center: ['主軸の中央へ寄せます。余白は両端に等分されます。', 'Centres the items; the free space is split between the two ends.'],
92
+ 'space-between': ['両端を端に付け、余白を子要素の「間」に等分します。子要素が1つだと先頭寄せと同じ見え方です。', 'Pushes the ends to the edges and splits the free space between the items. With one item it looks like flex-start.'],
93
+ 'space-around': ['子要素の両側に同じ余白を付けます。端の余白は間の余白の半分になります。', 'Gives each item equal space on both sides, so the outer gaps end up half the inner ones.'],
94
+ 'space-evenly': ['端も間もすべて同じ余白にします。見た目に「等間隔」を求めるならこちらです。', 'Makes every gap — including the outer ones — the same. This is the one that actually looks evenly spaced.'],
95
+ start: ['書字方向の先頭へ寄せます(flex-start とほぼ同じですが Grid ではこちらが標準の書き方)。', 'Packs at the start in writing order — the usual spelling in Grid.'],
96
+ end: ['書字方向の末尾へ寄せます。', 'Packs at the end in writing order.'],
97
+ stretch: ['伸ばせるトラックがあれば余白を分配します(固定サイズのトラックには効きません)。', 'Distributes the free space to stretchable tracks (does nothing to fixed ones).'],
98
+ },
99
+ 'align-items': {
100
+ stretch: ['交差軸いっぱいに伸ばします(既定)。高さを指定していない子要素は、いちばん高い子要素に揃います。', 'Stretches the items across the cross axis (default), so items without a height match the tallest one.'],
101
+ 'flex-start': ['交差軸の先頭(横並びなら上端)へ揃えます。高さは中身なりになります。', 'Aligns to the start of the cross axis (the top in a row), leaving each item at its content height.'],
102
+ 'flex-end': ['交差軸の末尾(横並びなら下端)へ揃えます。', 'Aligns to the end of the cross axis (the bottom in a row).'],
103
+ center: ['交差軸の中央へ揃えます。高さの違う箱を縦中央で並べる定番です。', 'Centres on the cross axis — the standard way to line up boxes of different heights.'],
104
+ baseline: ['文字のベースラインを揃えます。文字サイズが違う見出しと本文を横に並べるときに効きます。', 'Lines up the text baselines, which is what you want when a large heading sits next to body text.'],
105
+ start: ['書字方向の先頭へ揃えます(Grid での標準の書き方)。', 'Aligns to the start in writing order (the usual spelling in Grid).'],
106
+ end: ['書字方向の末尾へ揃えます。', 'Aligns to the end in writing order.'],
107
+ },
108
+ 'align-content': {
109
+ stretch: ['行(トラック)を伸ばして余白を埋めます(既定)。', 'Stretches the lines to fill the free space (default).'],
110
+ 'flex-start': ['折り返した行のまとまりを上端へ寄せます。', 'Packs the wrapped lines at the top.'],
111
+ 'flex-end': ['行のまとまりを下端へ寄せます。', 'Packs the wrapped lines at the bottom.'],
112
+ center: ['行のまとまりを縦中央へ寄せます。', 'Centres the block of wrapped lines.'],
113
+ 'space-between': ['最初と最後の行を端に付け、行の間に余白を等分します。', 'Pins the first and last line to the edges and splits the space between the lines.'],
114
+ 'space-around': ['各行の上下に同じ余白を付けます。', 'Gives each line equal space above and below.'],
115
+ 'space-evenly': ['行の間も上下端もすべて同じ余白にします。', 'Makes every gap between and around the lines the same.'],
116
+ start: ['書字方向の先頭へ寄せます。', 'Packs at the start in writing order.'],
117
+ end: ['書字方向の末尾へ寄せます。', 'Packs at the end in writing order.'],
118
+ },
119
+ 'align-self': {
120
+ auto: ['親の align-items に従います(既定)。', 'Follows the container’s align-items (default).'],
121
+ stretch: ['この子要素だけ交差軸いっぱいに伸ばします。', 'Stretches just this item across the cross axis.'],
122
+ 'flex-start': ['この子要素だけ先頭(上端)へ揃えます。', 'Aligns just this item to the start (top).'],
123
+ 'flex-end': ['この子要素だけ末尾(下端)へ揃えます。「片方だけ下に置く」の定番。', 'Aligns just this item to the end (bottom) — the usual way to drop one item down.'],
124
+ center: ['この子要素だけ中央へ揃えます。', 'Centres just this item.'],
125
+ baseline: ['この子要素の文字のベースラインを揃えます。', 'Aligns this item on its text baseline.'],
126
+ },
127
+ 'justify-items': {
128
+ stretch: ['各マスの中で横いっぱいに伸ばします(既定)。', 'Stretches each item to fill its cell horizontally (default).'],
129
+ start: ['各マスの左(書字方向の先頭)へ寄せます。中身の幅になります。', 'Packs each item at the inline start of its cell, at content width.'],
130
+ end: ['各マスの右(書字方向の末尾)へ寄せます。', 'Packs each item at the inline end of its cell.'],
131
+ center: ['各マスの中で横中央へ寄せます。', 'Centres each item horizontally in its cell.'],
132
+ },
133
+ 'grid-auto-flow': {
134
+ row: ['行を埋めてから次の行へ進みます(既定)。', 'Fills a row, then moves to the next one (default).'],
135
+ column: ['列を埋めてから次の列へ進みます。', 'Fills a column, then moves to the next one.'],
136
+ 'row dense': ['行順に置きつつ、前にできた空きマスを後ろの子要素で埋めます。', 'Fills by row but backfills earlier holes with later items.'],
137
+ 'column dense': ['列順に置きつつ、空きマスを後ろの子要素で埋めます。', 'Fills by column but backfills earlier holes with later items.'],
138
+ },
139
+ 'flex-wrap': {
140
+ nowrap: ['折り返しません(既定)。子要素は1行に押し込まれ、収まらなければ縮みます。', 'No wrapping (default): everything is squeezed into one line and the items shrink instead.'],
141
+ wrap: ['収まらない子要素を次の行へ送ります。レスポンシブの土台になります。', 'Moves items that do not fit onto the next line — the basis of responsive rows.'],
142
+ 'wrap-reverse': ['折り返しますが、行が積み上がる向きが逆(上へ)になります。', 'Wraps, but the new lines stack in the opposite direction (upwards).'],
143
+ },
144
+ };
145
+
146
+ export const valHint = (prop, value, lang) => {
147
+ const row = VAL[prop] && VAL[prop][value];
148
+ return row ? (lang === 'en' ? row[1] : row[0]) : '';
149
+ };
150
+
151
+ /* ==================== 状態(site の state の初期値と同じ) ==================== */
152
+
153
+ export const DEF_ITEM = () => ({ grow: 0, shrink: 1, basis: 'auto', self: 'auto', order: 0, cspan: 1, rspan: 1 });
154
+
155
+ export function defaultState() {
156
+ return {
157
+ mode: 'flex',
158
+ flex: {
159
+ display: 'flex',
160
+ direction: 'row',
161
+ wrap: 'wrap',
162
+ justify: 'flex-start',
163
+ alignItems: 'stretch',
164
+ alignContent: 'stretch',
165
+ rowGap: 12,
166
+ colGap: 12,
167
+ count: 4,
168
+ sel: 0,
169
+ varied: true,
170
+ height: 200,
171
+ items: [DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM()],
172
+ },
173
+ grid: {
174
+ cols: ['1fr', '1fr', '1fr'],
175
+ rows: ['auto'],
176
+ autoFit: false,
177
+ autoFitMin: 200,
178
+ flow: 'row',
179
+ rowGap: 12,
180
+ colGap: 12,
181
+ justifyItems: 'stretch',
182
+ alignItems: 'stretch',
183
+ justifyContent: 'start',
184
+ alignContent: 'start',
185
+ useAreas: false,
186
+ areas: 'header header header\nside main main\nfoot foot foot',
187
+ count: 6,
188
+ sel: 0,
189
+ height: 260,
190
+ items: [DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM(), DEF_ITEM()],
191
+ },
192
+ };
193
+ }
194
+
195
+ /* ==================== grid-template-areas の検証 ==================== */
196
+
197
+ export const NAME_RE = /^[A-Za-z_][\w-]*$/;
198
+
199
+ /** areas のテキストを検証して {rows, cols, names, error} を返す */
200
+ export function parseAreas(text, T) {
201
+ const lines = text.split('\n').map((l) => l.trim()).filter((l) => l !== '');
202
+ if (!lines.length) return { error: T.areaErrEmpty };
203
+ const grid = lines.map((l) => l.replace(/["']/g, ' ').trim().split(/\s+/));
204
+ const w = grid[0].length;
205
+ for (let r = 0; r < grid.length; r++) {
206
+ if (grid[r].length !== w) return { error: T.areaErrRagged(r + 1, grid[r].length) };
207
+ for (const tok of grid[r]) {
208
+ if (tok === '.' || /^\.+$/.test(tok)) continue;
209
+ if (!NAME_RE.test(tok)) return { error: T.areaErrName(tok) };
210
+ }
211
+ }
212
+ // 同じ名前が長方形になっているか(仕様: 長方形でないと値全体が無効)
213
+ const seen = new Map();
214
+ for (let r = 0; r < grid.length; r++) {
215
+ for (let c = 0; c < w; c++) {
216
+ const tok = grid[r][c];
217
+ if (/^\.+$/.test(tok)) continue;
218
+ const box = seen.get(tok);
219
+ if (!box) seen.set(tok, { r0: r, r1: r, c0: c, c1: c, n: 1 });
220
+ else {
221
+ box.r0 = Math.min(box.r0, r); box.r1 = Math.max(box.r1, r);
222
+ box.c0 = Math.min(box.c0, c); box.c1 = Math.max(box.c1, c);
223
+ box.n++;
224
+ }
225
+ }
226
+ }
227
+ for (const [name, box] of seen) {
228
+ const need = (box.r1 - box.r0 + 1) * (box.c1 - box.c0 + 1);
229
+ if (need !== box.n) return { error: T.areaErrRect(name) };
230
+ }
231
+ return { grid, rows: grid.length, cols: w, names: [...seen.keys()] };
232
+ }
233
+
234
+ /* ==================== CSS の組み立て ==================== */
235
+
236
+ export const px = (n) => `${n}px`;
237
+ export const gapValue = (row, col) => (row === col ? px(row) : `${px(row)} ${px(col)}`);
238
+
239
+ /** 同じ値のトラックが2本以上続けば repeat() へ畳む */
240
+ export function tracksToCss(list) {
241
+ if (!list.length) return 'none';
242
+ const out = [];
243
+ let i = 0;
244
+ while (i < list.length) {
245
+ let j = i;
246
+ while (j + 1 < list.length && list[j + 1] === list[i]) j++;
247
+ const n = j - i + 1;
248
+ out.push(n >= 2 ? `repeat(${n}, ${list[i]})` : list[i]);
249
+ i = j + 1;
250
+ }
251
+ return out.join(' ');
252
+ }
253
+
254
+ export function flexDecls(state) {
255
+ const f = state.flex;
256
+ const d = [['display', f.display], ['flex-direction', f.direction]];
257
+ if (f.wrap !== 'nowrap') d.push(['flex-wrap', f.wrap]);
258
+ if (f.justify !== 'flex-start') d.push(['justify-content', f.justify]);
259
+ if (f.alignItems !== 'stretch') d.push(['align-items', f.alignItems]);
260
+ if (f.wrap !== 'nowrap' && f.alignContent !== 'stretch') d.push(['align-content', f.alignContent]);
261
+ if (f.rowGap || f.colGap) d.push(['gap', gapValue(f.rowGap, f.colGap)]);
262
+ return d;
263
+ }
264
+
265
+ export function gridColsCss(state) {
266
+ const g = state.grid;
267
+ return g.autoFit ? `repeat(auto-fit, minmax(${px(g.autoFitMin)}, 1fr))` : tracksToCss(g.cols);
268
+ }
269
+
270
+ export function gridDecls(state, area) {
271
+ const g = state.grid;
272
+ const d = [['display', 'grid'], ['grid-template-columns', gridColsCss(state)]];
273
+ if (g.rows.length && !(g.rows.length === 1 && g.rows[0] === 'auto')) d.push(['grid-template-rows', tracksToCss(g.rows)]);
274
+ if (g.useAreas && area && area.grid) {
275
+ const w = area.grid.reduce((m, row) => Math.max(m, ...row.map((t) => t.length)), 0);
276
+ d.push(['grid-template-areas', '\n' + area.grid.map((row) => ' "' + row.map((t) => t.padEnd(w)).join(' ').trimEnd() + '"').join('\n')]);
277
+ }
278
+ if (g.rowGap || g.colGap) d.push(['gap', gapValue(g.rowGap, g.colGap)]);
279
+ if (g.flow !== 'row') d.push(['grid-auto-flow', g.flow]);
280
+ if (g.justifyItems !== 'stretch') d.push(['justify-items', g.justifyItems]);
281
+ if (g.alignItems !== 'stretch') d.push(['align-items', g.alignItems]);
282
+ if (g.justifyContent !== 'start') d.push(['justify-content', g.justifyContent]);
283
+ if (g.alignContent !== 'start') d.push(['align-content', g.alignContent]);
284
+ return d;
285
+ }
286
+
287
+ /** 子要素ごとの宣言(既定と違うものだけ) */
288
+ export function itemDecls(state, it) {
289
+ const d = [];
290
+ if (state.mode === 'flex') {
291
+ if (it.grow !== 0 || it.shrink !== 1 || it.basis !== 'auto') d.push(['flex', `${it.grow} ${it.shrink} ${it.basis}`]);
292
+ if (it.self !== 'auto') d.push(['align-self', it.self]);
293
+ if (it.order !== 0) d.push(['order', String(it.order)]);
294
+ } else {
295
+ if (it.cspan > 1) d.push(['grid-column', `span ${it.cspan}`]);
296
+ if (it.rspan > 1) d.push(['grid-row', `span ${it.rspan}`]);
297
+ }
298
+ return d;
299
+ }
300
+
301
+ // 複数行の値(grid-template-areas)はコロンの直後に改行させる=行末に空白を残さない
302
+ export const declsToCss = (decls, indent) => decls.map(([k, v]) => `${indent}${k}:${v[0] === '\n' ? '' : ' '}${v};`).join('\n');
303
+
304
+ export function buildCss(state, area) {
305
+ const mode = state.mode;
306
+ const decls = mode === 'flex' ? flexDecls(state) : gridDecls(state, area);
307
+ let css = '.layout {\n' + declsToCss(decls, ' ') + '\n}';
308
+ if (mode === 'grid' && state.grid.useAreas && area && area.names) {
309
+ for (const name of area.names) css += `\n\n.layout > .${name} {\n grid-area: ${name};\n}`;
310
+ return css;
311
+ }
312
+ const items = mode === 'flex' ? state.flex.items.slice(0, state.flex.count) : state.grid.items.slice(0, state.grid.count);
313
+ items.forEach((it, i) => {
314
+ const d = itemDecls(state, it);
315
+ if (d.length) css += `\n\n.layout > :nth-child(${i + 1}) {\n` + declsToCss(d, ' ') + '\n}';
316
+ });
317
+ return css;
318
+ }
319
+
320
+ export function buildHtml(state, area) {
321
+ if (state.mode === 'grid' && state.grid.useAreas && area && area.names) {
322
+ return '<div class="layout">\n' + area.names.map((n) => ` <div class="${n}">${n}</div>`).join('\n') + '\n</div>';
323
+ }
324
+ const n = state.mode === 'flex' ? state.flex.count : state.grid.count;
325
+ const rows = [];
326
+ for (let i = 1; i <= n; i++) rows.push(` <div class="item">${i}</div>`);
327
+ return '<div class="layout">\n' + rows.join('\n') + '\n</div>';
328
+ }
329
+
330
+ /* ==================== 指摘(チェック結果) ==================== */
331
+
332
+ export function diagnose(state, area, T) {
333
+ const out = [];
334
+ const add = (kind, text) => out.push({ kind, text });
335
+ if (state.mode === 'flex') {
336
+ const f = state.flex;
337
+ const grows = f.items.slice(0, f.count).some((it) => it.grow > 0);
338
+ if (grows && f.justify !== 'flex-start') add('warn', T.justifyDead);
339
+ if (f.wrap === 'nowrap' && f.alignContent !== 'stretch') add('warn', T.alignContentDead);
340
+ if (f.direction.endsWith('reverse')) add('warn', T.reverseNote);
341
+ if (f.wrap === 'nowrap') add('info', T.wrapNote);
342
+ if (f.alignItems === 'stretch') add('info', T.alignItemsStretchNote);
343
+ if (f.rowGap || f.colGap) add('info', T.gapNote);
344
+ if (f.items.slice(0, f.count).some((it) => it.basis === '0')) add('info', T.basisNote);
345
+ if (f.items.slice(0, f.count).some((it) => it.shrink > 1)) add('info', T.shrinkNote);
346
+ add('info', T.minWidthNote);
347
+ } else {
348
+ const g = state.grid;
349
+ if (g.useAreas) {
350
+ if (area.error) add('warn', area.error);
351
+ else {
352
+ add('ok', T.areaOk(area.rows, area.cols, area.names.length));
353
+ const tracks = g.autoFit ? 0 : g.cols.length;
354
+ if (tracks && tracks !== area.cols) add('warn', T.trackCountMismatch(tracks, area.cols));
355
+ }
356
+ }
357
+ if (g.autoFit) add('info', T.autoFitNote);
358
+ if (!g.autoFit && g.cols.includes('1fr')) add('info', T.frMinNote);
359
+ if (g.flow.indexOf('dense') !== -1) add('warn', T.dense);
360
+ if (!g.autoFit && g.cols.every((c) => c.endsWith('fr')) && g.justifyContent !== 'start') add('warn', T.noFreeSpace);
361
+ if (g.rowGap || g.colGap) add('info', T.gapNote);
362
+ }
363
+ return out;
364
+ }
365
+
366
+ /* ==================== プリセット(site の PRESETS と同じ。id はこちらで付けた呼び名) ==================== */
367
+
368
+ export const PRESETS = [
369
+ {
370
+ ja: '横並びを中央へ', en: 'Centre a row', mode: 'flex',
371
+ flex: { justify: 'center', alignItems: 'center', wrap: 'wrap', direction: 'row', rowGap: 12, colGap: 12, count: 3 },
372
+ },
373
+ {
374
+ ja: 'ヘッダー(両端+縦中央)', en: 'Header (ends + middle)', mode: 'flex',
375
+ flex: { justify: 'space-between', alignItems: 'center', wrap: 'nowrap', direction: 'row', rowGap: 0, colGap: 16, count: 3 },
376
+ },
377
+ {
378
+ ja: '折り返すカード列', en: 'Wrapping card row', mode: 'flex',
379
+ flex: { justify: 'flex-start', alignItems: 'stretch', wrap: 'wrap', direction: 'row', rowGap: 16, colGap: 16, count: 6 },
380
+ items: { all: { grow: 1, shrink: 1, basis: '240px' } },
381
+ },
382
+ {
383
+ ja: 'サイドバー+本文', en: 'Sidebar + content', mode: 'grid',
384
+ grid: { cols: ['240px', 'minmax(0, 1fr)'], rows: ['auto'], useAreas: false, count: 2, rowGap: 24, colGap: 40, autoFit: false },
385
+ },
386
+ {
387
+ ja: '聖杯レイアウト(エリア)', en: 'Holy grail (areas)', mode: 'grid',
388
+ grid: {
389
+ cols: ['200px', 'minmax(0, 1fr)', '160px'], rows: ['auto', '1fr', 'auto'], useAreas: true, autoFit: false, rowGap: 12, colGap: 12, height: 320,
390
+ areas: 'header header header\nnav main aside\nfooter footer footer',
391
+ },
392
+ },
393
+ {
394
+ ja: '自動で折り返すグリッド', en: 'Auto-fit grid', mode: 'grid',
395
+ grid: { autoFit: true, autoFitMin: 200, rows: ['auto'], useAreas: false, count: 7, rowGap: 16, colGap: 16 },
396
+ },
397
+ {
398
+ ja: '写真の敷き詰め(dense)', en: 'Photo mosaic (dense)', mode: 'grid',
399
+ grid: { cols: ['1fr', '1fr', '1fr', '1fr'], rows: ['120px', '120px'], useAreas: false, autoFit: false, flow: 'row dense', count: 8, rowGap: 8, colGap: 8 },
400
+ items: { 0: { cspan: 2, rspan: 2 }, 3: { cspan: 2 } },
401
+ },
402
+ {
403
+ ja: '縦に積んで下端へ1つ', en: 'Stack with one at the bottom', mode: 'flex',
404
+ flex: { direction: 'column', wrap: 'nowrap', justify: 'flex-start', alignItems: 'stretch', rowGap: 10, colGap: 10, count: 4, height: 300, varied: false },
405
+ items: { 3: { self: 'flex-end' } },
406
+ },
407
+ ];
408
+
409
+ // プリセットの呼び名(PRESETS と同じ並び)
410
+ export const PRESET_IDS = ['center-row', 'header', 'card-row', 'sidebar', 'holy-grail', 'auto-fit', 'mosaic', 'stack-bottom'];
411
+
412
+ /** site の applyPreset のうち状態を書き換える部分(画面の同期・タブ切替を除く) */
413
+ export function applyPreset(state, p) {
414
+ state.mode = p.mode;
415
+ if (p.flex) Object.assign(state.flex, p.flex);
416
+ if (p.grid) Object.assign(state.grid, JSON.parse(JSON.stringify(p.grid)));
417
+ const st = p.mode === 'flex' ? state.flex : state.grid;
418
+ st.items = st.items.map(() => DEF_ITEM());
419
+ if (p.items) {
420
+ for (const key of Object.keys(p.items)) {
421
+ if (key === 'all') st.items = st.items.map((it) => Object.assign(it, p.items.all));
422
+ else Object.assign(st.items[Number(key)], p.items[key]);
423
+ }
424
+ }
425
+ st.sel = 0;
426
+ return state;
427
+ }
428
+
429
+ /* ==================== MCP ツール ==================== */
430
+
431
+ export class CssLayoutError extends Error {}
432
+
433
+ // site のフォーム(select の選択肢・range の範囲)と同じ値域
434
+ export const CL_CHOICES = {
435
+ display: ['flex', 'inline-flex'],
436
+ direction: ['row', 'row-reverse', 'column', 'column-reverse'],
437
+ wrap: ['nowrap', 'wrap', 'wrap-reverse'],
438
+ flexJustify: ['flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly'],
439
+ flexAlignItems: ['stretch', 'flex-start', 'flex-end', 'center', 'baseline'],
440
+ flexAlignContent: ['stretch', 'flex-start', 'flex-end', 'center', 'space-between', 'space-around', 'space-evenly'],
441
+ basis: ['auto', '0', '0%', '25%', '33.333%', '50%', '100%', '120px', '200px', '240px', 'min-content', 'max-content'],
442
+ self: ['auto', 'stretch', 'flex-start', 'flex-end', 'center', 'baseline'],
443
+ flow: ['row', 'column', 'row dense', 'column dense'],
444
+ justifyItems: ['stretch', 'start', 'end', 'center'],
445
+ gridAlignItems: ['stretch', 'start', 'end', 'center'],
446
+ gridContent: ['start', 'end', 'center', 'space-between', 'space-around', 'space-evenly', 'stretch'],
447
+ };
448
+ const RANGES = {
449
+ gap: [0, 80], flexCount: [1, 8], gridCount: [1, 12], grow: [0, 5], shrink: [0, 5], order: [-2, 2],
450
+ span: [1, 6], autoFitMin: [80, 400], tracks: [1, 12],
451
+ };
452
+ // トラックの値は site の一覧にある値のほか、URLパラメータと同じく自由に書ける。ただし宣言を壊す文字は通さない
453
+ const TRACK_RE = /^[^;{}<>"'\n\r\\]{1,60}$/;
454
+ const BASIS_RE = /^(?:0|\d+(?:\.\d+)?(?:px|%|rem|em|vw|vh|ch))$/;
455
+
456
+ function oneOf(name, v, list) {
457
+ if (list.indexOf(v) === -1) throw new CssLayoutError(`${name} は ${list.join(' / ')} のどれか: ${v}`);
458
+ return v;
459
+ }
460
+ function intIn(name, v, [lo, hi]) {
461
+ if (!Number.isInteger(v) || v < lo || v > hi) throw new CssLayoutError(`${name} は ${lo}〜${hi} の整数: ${v}`);
462
+ return v;
463
+ }
464
+ function trackList(name, v) {
465
+ if (!Array.isArray(v) || v.length < RANGES.tracks[0] || v.length > RANGES.tracks[1]) {
466
+ throw new CssLayoutError(`${name} は1〜12本のトラックの配列で渡してください(例: ["240px", "minmax(0, 1fr)"])`);
467
+ }
468
+ return v.map((t) => {
469
+ const s = String(t).trim();
470
+ if (!TRACK_RE.test(s)) throw new CssLayoutError(`${name} に使えない値: ${t}`);
471
+ return s;
472
+ });
473
+ }
474
+
475
+ /**
476
+ * Flexbox / CSS Grid の CSS と HTML を組み立てる。
477
+ * 既定の状態(site を開いたときと同じ)→ preset → 個別の指定、の順に重ねる。
478
+ */
479
+ export async function cssLayoutGenerateTool(opts = {}) {
480
+ const lang = opts.lang || 'ja';
481
+ if (lang !== 'ja' && lang !== 'en') throw new CssLayoutError(`lang は ja か en: ${opts.lang}`);
482
+ const T = CL_TEXT[lang];
483
+
484
+ if (opts.mode === 'presets') {
485
+ return {
486
+ presets: PRESETS.map((p, i) => {
487
+ const r = cssLayoutBuild(applyPreset(defaultState(), p), p.mode === 'grid' && p.grid && p.grid.useAreas ? p.grid.areas : null, T);
488
+ return { id: PRESET_IDS[i], name: lang === 'en' ? p.en : p.ja, mode: p.mode, css: r.css, html: r.html };
489
+ }),
490
+ };
491
+ }
492
+
493
+ const state = defaultState();
494
+ let areasText = null;
495
+ if (opts.preset !== undefined) {
496
+ const i = PRESET_IDS.indexOf(opts.preset);
497
+ if (i === -1) throw new CssLayoutError(`preset は ${PRESET_IDS.join(' / ')} のどれか: ${opts.preset}`);
498
+ applyPreset(state, PRESETS[i]);
499
+ if (state.mode === 'grid' && state.grid.useAreas) areasText = state.grid.areas;
500
+ }
501
+ const gridHints = opts.columns !== undefined || opts.rows !== undefined || opts.areas !== undefined || opts.autoFit !== undefined;
502
+ let mode = opts.mode;
503
+ if (mode === undefined) mode = opts.preset !== undefined ? state.mode : gridHints ? 'grid' : 'flex';
504
+ oneOf('mode', mode, ['flex', 'grid', 'presets']);
505
+ state.mode = mode;
506
+ const isFlex = mode === 'flex';
507
+ const st = isFlex ? state.flex : state.grid;
508
+
509
+ if (opts.gap !== undefined) st.rowGap = st.colGap = intIn('gap', opts.gap, RANGES.gap);
510
+ if (opts.rowGap !== undefined) st.rowGap = intIn('rowGap', opts.rowGap, RANGES.gap);
511
+ if (opts.colGap !== undefined) st.colGap = intIn('colGap', opts.colGap, RANGES.gap);
512
+ if (opts.count !== undefined) st.count = intIn('count', opts.count, isFlex ? RANGES.flexCount : RANGES.gridCount);
513
+
514
+ if (isFlex) {
515
+ const f = state.flex;
516
+ if (opts.display !== undefined) f.display = oneOf('display', opts.display, CL_CHOICES.display);
517
+ if (opts.direction !== undefined) f.direction = oneOf('direction', opts.direction, CL_CHOICES.direction);
518
+ if (opts.wrap !== undefined) f.wrap = oneOf('wrap', opts.wrap, CL_CHOICES.wrap);
519
+ if (opts.justifyContent !== undefined) f.justify = oneOf('justifyContent', opts.justifyContent, CL_CHOICES.flexJustify);
520
+ if (opts.alignItems !== undefined) f.alignItems = oneOf('alignItems', opts.alignItems, CL_CHOICES.flexAlignItems);
521
+ if (opts.alignContent !== undefined) f.alignContent = oneOf('alignContent', opts.alignContent, CL_CHOICES.flexAlignContent);
522
+ for (const k of ['columns', 'rows', 'areas', 'autoFit', 'autoFitMin', 'flow', 'justifyItems']) {
523
+ if (opts[k] !== undefined) throw new CssLayoutError(`${k} は mode="grid" の指定です`);
524
+ }
525
+ } else {
526
+ const g = state.grid;
527
+ if (opts.columns !== undefined) { g.cols = trackList('columns', opts.columns); g.autoFit = false; }
528
+ if (opts.rows !== undefined) g.rows = trackList('rows', opts.rows);
529
+ if (opts.autoFit !== undefined) g.autoFit = !!opts.autoFit;
530
+ if (opts.autoFitMin !== undefined) g.autoFitMin = intIn('autoFitMin', opts.autoFitMin, RANGES.autoFitMin);
531
+ if (opts.flow !== undefined) g.flow = oneOf('flow', opts.flow, CL_CHOICES.flow);
532
+ if (opts.justifyItems !== undefined) g.justifyItems = oneOf('justifyItems', opts.justifyItems, CL_CHOICES.justifyItems);
533
+ if (opts.alignItems !== undefined) g.alignItems = oneOf('alignItems', opts.alignItems, CL_CHOICES.gridAlignItems);
534
+ if (opts.justifyContent !== undefined) g.justifyContent = oneOf('justifyContent', opts.justifyContent, CL_CHOICES.gridContent);
535
+ if (opts.alignContent !== undefined) g.alignContent = oneOf('alignContent', opts.alignContent, CL_CHOICES.gridContent);
536
+ if (opts.areas !== undefined) {
537
+ if (typeof opts.areas !== 'string') throw new CssLayoutError('areas は文字列(行を改行か " / " で区切る)で渡してください');
538
+ // site の URLパラメータ areas と同じく「/」も行の区切りとして読む
539
+ areasText = opts.areas.replace(/\s*\/\s*/g, '\n');
540
+ g.areas = areasText;
541
+ g.useAreas = true;
542
+ }
543
+ for (const k of ['display', 'direction', 'wrap']) {
544
+ if (opts[k] !== undefined) throw new CssLayoutError(`${k} は mode="flex" の指定です`);
545
+ }
546
+ }
547
+
548
+ if (opts.items !== undefined) {
549
+ if (!Array.isArray(opts.items)) throw new CssLayoutError('items は子要素ごとの指定の配列で渡してください');
550
+ if (opts.items.length > st.items.length) throw new CssLayoutError(`items は ${st.items.length} 件まで`);
551
+ opts.items.forEach((raw, i) => {
552
+ if (raw === null || raw === undefined) return;
553
+ const it = st.items[i];
554
+ if (isFlex) {
555
+ if (raw.grow !== undefined) it.grow = intIn(`items[${i}].grow`, raw.grow, RANGES.grow);
556
+ if (raw.shrink !== undefined) it.shrink = intIn(`items[${i}].shrink`, raw.shrink, RANGES.shrink);
557
+ if (raw.basis !== undefined) {
558
+ const b = String(raw.basis).trim();
559
+ if (CL_CHOICES.basis.indexOf(b) === -1 && !BASIS_RE.test(b)) throw new CssLayoutError(`items[${i}].basis に使えない値: ${raw.basis}`);
560
+ it.basis = b;
561
+ }
562
+ if (raw.alignSelf !== undefined) it.self = oneOf(`items[${i}].alignSelf`, raw.alignSelf, CL_CHOICES.self);
563
+ if (raw.order !== undefined) it.order = intIn(`items[${i}].order`, raw.order, RANGES.order);
564
+ } else {
565
+ if (raw.columnSpan !== undefined) it.cspan = intIn(`items[${i}].columnSpan`, raw.columnSpan, RANGES.span);
566
+ if (raw.rowSpan !== undefined) it.rspan = intIn(`items[${i}].rowSpan`, raw.rowSpan, RANGES.span);
567
+ }
568
+ });
569
+ }
570
+
571
+ const r = cssLayoutBuild(state, state.mode === 'grid' && state.grid.useAreas ? areasText ?? state.grid.areas : null, T);
572
+ const hints = {};
573
+ if (isFlex) {
574
+ const f = state.flex;
575
+ hints['flex-direction'] = f.direction === 'row' ? T.dirRow : f.direction === 'row-reverse' ? T.dirRowRev : f.direction === 'column' ? T.dirCol : T.dirColRev;
576
+ hints['flex-wrap'] = valHint('flex-wrap', f.wrap, lang);
577
+ hints['justify-content'] = valHint('justify-content', f.justify, lang);
578
+ hints['align-items'] = valHint('align-items', f.alignItems, lang);
579
+ hints['align-content'] = valHint('align-content', f.alignContent, lang);
580
+ } else {
581
+ const g = state.grid;
582
+ hints['grid-auto-flow'] = valHint('grid-auto-flow', g.flow, lang);
583
+ hints['justify-items'] = valHint('justify-items', g.justifyItems, lang);
584
+ hints['align-items'] = valHint('align-items', g.alignItems, lang);
585
+ hints['justify-content'] = valHint('justify-content', g.justifyContent, lang);
586
+ hints['align-content'] = valHint('align-content', g.alignContent, lang);
587
+ }
588
+ return { mode: state.mode, ...(opts.preset !== undefined ? { preset: opts.preset } : {}), ...r, hints };
589
+ }
590
+
591
+ /** site の render() のうち、CSS・HTML・集計・指摘を作る部分(プレビューの描画と行数の実測を除く) */
592
+ export function cssLayoutBuild(state, areasText, T) {
593
+ const mode = state.mode;
594
+ const area = mode === 'grid' && state.grid.useAreas ? parseAreas(areasText ?? '', T) : null;
595
+ const drawArea = area && !area.error ? area : null;
596
+ const css = buildCss(state, drawArea);
597
+ const html = buildHtml(state, drawArea);
598
+ const st = mode === 'flex' ? state.flex : state.grid;
599
+ const diag = diagnose(state, mode === 'grid' && state.grid.useAreas ? (area || {}) : null, T);
600
+ return {
601
+ css,
602
+ html,
603
+ items: drawArea ? drawArea.names.length : st.count,
604
+ declarations: (mode === 'flex' ? flexDecls(state) : gridDecls(state, drawArea)).length,
605
+ css_length: css.length,
606
+ ...(mode === 'grid'
607
+ ? { tracks: drawArea ? `${drawArea.rows}×${drawArea.cols}` : state.grid.autoFit ? 'auto-fit' : state.grid.cols.length }
608
+ : {}),
609
+ ...(area ? { areas: area.error ? { error: area.error } : { rows: area.rows, cols: area.cols, names: area.names } } : {}),
610
+ notes: diag.map((d) => ({ level: d.kind, message: d.text })),
611
+ };
612
+ }