@cardenelabs/dragon 0.42.1 → 0.43.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cardenelabs/dragon",
3
- "version": "0.42.1",
3
+ "version": "0.43.0",
4
4
  "description": "Dragon — 動く図を、人は行ごとの記法で、AI は JSON で書く。時系列図と構成図を段ごとに動かし、mp4・GIF・HTML・PNG に書き出す。",
5
5
  "license": "MIT",
6
6
  "author": "cardene777",
@@ -7,6 +7,9 @@
7
7
  *
8
8
  * 形を 1 つも持たない字の file を Chromium は読まない。空白の類だけを描く file には、
9
9
  * 同じ file の形のある字を 1 つ足して削る。足した字は `unicode-range` に載せないので描かれない (#3212)。
10
+ *
11
+ * 範囲の重なる字 (`Noto Sans JP` の英字は番号付きの file と `latin` の両方に入る) は、字の表で後に並ぶ 1 つの file にだけ入れる。
12
+ * 範囲が重なる時は後に宣言した `@font-face` が勝つので、前の file に埋めた字は描かれず、大きさだけを取っていた (#3213)。
10
13
  */
11
14
  import { readFileSync } from "node:fs";
12
15
  import { readFile } from "node:fs/promises";
@@ -42,6 +45,12 @@ function ranges(list: string): [number, number][] {
42
45
 
43
46
  const hex = (code: number): string => `U+${code.toString(16).toUpperCase()}`;
44
47
 
48
+ /** 字が範囲の一覧のどれかに入るか */
49
+ function within(span: [number, number][], char: string): boolean {
50
+ const code = char.codePointAt(0) ?? -1;
51
+ return span.some(([from, to]) => code >= from && code <= to);
52
+ }
53
+
45
54
  /** 形を持たない字 (空白の類、書式の字、制御の字) か */
46
55
  const shapeless = (char: string): boolean => /^[\s\p{Cf}\p{Cc}]$/u.test(char);
47
56
 
@@ -67,12 +76,10 @@ export async function fontFaces(chars: string[]): Promise<string> {
67
76
  PACKAGES.flatMap(({ family, name }) => {
68
77
  const base = dirname(require_.resolve(`@fontsource-variable/${name}/unicode.json`));
69
78
  const table = JSON.parse(readFileSync(join(base, "unicode.json"), "utf8")) as Record<string, string>;
70
- return Object.entries(table).map(async ([key, list]) => {
71
- const span = ranges(list);
72
- const own = chars.filter((char) => {
73
- const code = char.codePointAt(0) ?? -1;
74
- return span.some(([from, to]) => code >= from && code <= to);
75
- });
79
+ const spans = Object.entries(table).map(([key, list]) => ({ key, span: ranges(list) }));
80
+ return spans.map(async ({ key, span }, index) => {
81
+ // 後に並ぶ file の範囲にも入る字は、そちらにだけ入れる
82
+ const own = chars.filter((char) => within(span, char) && !spans.slice(index + 1).some((later) => within(later.span, char)));
76
83
  if (!own.length) return "";
77
84
  const filler = own.every(shapeless) ? (shapedIn(span) ?? "") : "";
78
85
  const file = join(base, "files", `${name}-${key.replace(/[[\]]/g, "")}-wght-normal.woff2`);
package/src/index.ts CHANGED
@@ -34,6 +34,8 @@ export {
34
34
  type TimeScale,
35
35
  type TimeSpanEvent,
36
36
  type TimeSpec,
37
+ type TreeLeaf,
38
+ type TreeNode,
37
39
  validateDiagram,
38
40
  type ViewMode,
39
41
  } from "./schema";
@@ -57,8 +59,9 @@ export type {
57
59
  SceneTrail,
58
60
  } from "./layout/scene";
59
61
  export type { TimeAxis, TimeBox, TimeColumn, TimeLayout, TimeMark, TimePeriodPlaced, TimePointPlaced, TimeRowPlaced, TimeSpanPlaced, TimeTick, TimeWire, TimeZoom } from "./layout/time";
62
+ export type { TreeLayout, TreeLink, TreePlaced, TreeRun } from "./layout/tree";
60
63
  export { type Family, FONTS } from "./look/fonts";
61
- export { type ColorKey, type ColorName, type Colors, DEFAULT_PALETTE, type Palette, PALETTES, READABLE_PX, resolvePalette, type Theme } from "./look/values";
64
+ export { type ColorKey, type ColorName, type Colors, DEFAULT_PALETTE, type Palette, PALETTES, READABLE_PX, resolvePalette, type TextStyle, type Theme } from "./look/values";
62
65
  export { mountDiagram, type Player, type PlayerOptions } from "./player";
63
66
  export { ICONS } from "./render/icons";
64
67
  export { describeOverlap, type InkPart, type Overlap, type OverlapSpot } from "./render/ink";
@@ -0,0 +1,458 @@
1
+ /**
2
+ * 木の図の置き場所 (#3233)。見た目の元は step 2 で本人が選んだ「根を上」の試作 (`.context/propose/merkle-look/`)。
3
+ *
4
+ * 葉 (`leaf`) と親 (`node`) の出来事を書いた順に辿り、親を持たない最後の箱を根にする。根を上に置き、根からの深さごとに段を下げて並べる。
5
+ * 子を持たない箱 (葉) は書いた順に左から同じ間で並べ、親は最初の子と最後の子の真ん中の上に置く。
6
+ * 子から親への木の線は、子の上端から縦に出て、子の段と親の段の間の高さで横に渡り、親の下端へ縦に入る。
7
+ * 値を持つ葉は箱に値だけを出し、名札を葉の下の札に出す。値を持つ親は値を大きく、名札を小さく出す。値を持たない箱は名札だけを出す。
8
+ * 根の箱は左に枝の絵柄を持ち、ほかの木の箱より大きい。
9
+ *
10
+ * 木でない箱 (`box`) は木の右に、根の上端の高さから縦に並べる。中身の帯は図の下に置く。
11
+ * 親子の箱どうしの線は木の線の上を走り、ほかの線は箱の向き合う辺どうしを結ぶ。
12
+ * 段の番号は、箱が現れる段では最初に現れた箱の左に、線を引く段では最初の線の上に置く。
13
+ *
14
+ * 原本の JSON が書く前の名札を子に持つ時や、もう親を持つ箱を子にする時は、その子を除いて描く。箱と同じ名札の木の箱は描かない。
15
+ */
16
+ import { type ColorKey, LOOK, type TextStyle, TYPE } from "../look/values";
17
+ import type { Diagram } from "../schema";
18
+ import { textWidth } from "./measure";
19
+ import {
20
+ along,
21
+ badgeOnPath,
22
+ badgeRect,
23
+ boxColors,
24
+ boxWidth,
25
+ carrierHalf,
26
+ edgeColor,
27
+ edgesOf,
28
+ gapBetween,
29
+ labelStyle,
30
+ type Layout,
31
+ layoutStrip,
32
+ loopUnder,
33
+ pathLength,
34
+ placeLabel,
35
+ placeSlot,
36
+ type Point,
37
+ type Rect,
38
+ replaceSameSpot,
39
+ type SceneBadge,
40
+ type SceneBox,
41
+ type SceneEdge,
42
+ type SceneLabel,
43
+ seatCarriers,
44
+ slotBoxWidth,
45
+ slotRooms,
46
+ stripNeed,
47
+ } from "./scene";
48
+
49
+ /** 木の箱。`lines` は箱の中の字を上から並べた行で、`baselines` と `styles` は行ごとの基準線の高さと字の形 */
50
+ export interface TreePlaced extends Rect {
51
+ id: string;
52
+ kind: "leaf" | "node";
53
+ /** 根からの深さ。根が 0 */
54
+ depth: number;
55
+ parent?: string;
56
+ children: string[];
57
+ /** 箱を書いた段と、段の中の出来事の番号 */
58
+ step: number;
59
+ event: number;
60
+ hash?: string;
61
+ root: boolean;
62
+ cx: number;
63
+ cy: number;
64
+ color: ColorKey;
65
+ lines: string[];
66
+ baselines: number[];
67
+ styles: TextStyle[];
68
+ /** 値を持つ葉の下に置く、名札の札 */
69
+ card?: Rect & { text: string };
70
+ }
71
+
72
+ /** 子 (`from`) から親 (`to`) への木の線。親を書いた段と出来事で現れる */
73
+ export interface TreeLink {
74
+ from: string;
75
+ to: string;
76
+ step: number;
77
+ event: number;
78
+ points: Point[];
79
+ }
80
+
81
+ /** 木の線の上を走る線。`link` は走る木の線の子の名札 */
82
+ export interface TreeRun {
83
+ step: number;
84
+ event: number;
85
+ link: string;
86
+ }
87
+
88
+ export interface TreeLayout extends Layout {
89
+ kind: "tree";
90
+ nodes: TreePlaced[];
91
+ links: TreeLink[];
92
+ runs: TreeRun[];
93
+ }
94
+
95
+ export const isTreeLayout = (layout: Layout): layout is TreeLayout => layout.kind === "tree";
96
+
97
+ /** 書いた順の木の箱。子は書いた後の、まだ親を持たない木の箱だけを残す */
98
+ interface Grown {
99
+ id: string;
100
+ kind: "leaf" | "node";
101
+ children: string[];
102
+ step: number;
103
+ event: number;
104
+ hash?: string;
105
+ }
106
+
107
+ function grow(diagram: Diagram): { grown: Grown[]; parents: Map<string, string> } {
108
+ const boxes = new Set(diagram.boxes.map((b) => b.id));
109
+ const byId = new Set<string>();
110
+ const parents = new Map<string, string>();
111
+ const grown: Grown[] = [];
112
+ diagram.steps.forEach((step, s) => {
113
+ step.events.forEach((e, k) => {
114
+ if ((e.type !== "leaf" && e.type !== "node") || byId.has(e.id) || boxes.has(e.id)) return;
115
+ const children = e.type === "node" ? [...new Set(e.children)].filter((c) => byId.has(c) && !parents.has(c)) : [];
116
+ for (const c of children) parents.set(c, e.id);
117
+ grown.push({ id: e.id, kind: e.type, children, step: s, event: k, ...(e.hash !== undefined ? { hash: e.hash } : {}) });
118
+ byId.add(e.id);
119
+ });
120
+ });
121
+ return { grown, parents };
122
+ }
123
+
124
+ /** 箱の中の字の行と、行ごとの字の形。根は名札を上に値を下に、ほかの箱は値を上に名札を下に置く */
125
+ function linesOf(g: Grown, root: boolean): { text: string; style: TextStyle }[] {
126
+ if (g.hash === undefined) return [{ text: g.id, style: TYPE.boxName }];
127
+ if (root)
128
+ return [
129
+ { text: g.id, style: TYPE.rootName },
130
+ { text: g.hash, style: TYPE.rootHash },
131
+ ];
132
+ if (g.kind === "leaf") return [{ text: g.hash, style: TYPE.treeHash }];
133
+ return [
134
+ { text: g.hash, style: TYPE.treeHash },
135
+ { text: g.id, style: TYPE.treeName },
136
+ ];
137
+ }
138
+
139
+ /** 箱どうしの線。縦の範囲が重なれば横に、横の範囲が重なれば縦に、どちらも重ならなければ送る側から縦に出て受ける側の高さで横に入る */
140
+ function route(a: Rect, b: Rect): Point[] {
141
+ const i = LOOK.edge.inset;
142
+ const top = Math.max(a.y, b.y);
143
+ const bottom = Math.min(a.y + a.h, b.y + b.h);
144
+ if (bottom > top) {
145
+ const y = (top + bottom) / 2;
146
+ return b.x >= a.x + a.w
147
+ ? [
148
+ [a.x + a.w + i, y],
149
+ [b.x - i, y],
150
+ ]
151
+ : [
152
+ [a.x - i, y],
153
+ [b.x + b.w + i, y],
154
+ ];
155
+ }
156
+ const left = Math.max(a.x, b.x);
157
+ const right = Math.min(a.x + a.w, b.x + b.w);
158
+ if (right > left) {
159
+ const x = (left + right) / 2;
160
+ return b.y >= a.y + a.h
161
+ ? [
162
+ [x, a.y + a.h + i],
163
+ [x, b.y - i],
164
+ ]
165
+ : [
166
+ [x, a.y - i],
167
+ [x, b.y + b.h + i],
168
+ ];
169
+ }
170
+ const ax = a.x + a.w / 2;
171
+ const ty = b.y + b.h / 2;
172
+ return [
173
+ [ax, b.y > a.y ? a.y + a.h + i : a.y - i],
174
+ [ax, ty],
175
+ [b.x > ax ? b.x - i : b.x + b.w + i, ty],
176
+ ];
177
+ }
178
+
179
+ export function layoutTree(diagram: Diagram): TreeLayout {
180
+ const { margin, gap, box: B, tree: T, badge: BD } = LOOK;
181
+ const { grown, parents } = grow(diagram);
182
+ const tops = grown.filter((g) => !parents.has(g.id));
183
+ const rootId = tops[tops.length - 1]?.id;
184
+ const byId = new Map(grown.map((g) => [g.id, g]));
185
+
186
+ // 根からの深さ。親を持たない箱から子へ辿る
187
+ const depth = new Map<string, number>();
188
+ const walk = (id: string, d: number): void => {
189
+ depth.set(id, d);
190
+ for (const c of byId.get(id)?.children ?? []) walk(c, d + 1);
191
+ };
192
+ for (const t of tops) walk(t.id, 0);
193
+
194
+ const texts = new Map(grown.map((g) => [g.id, linesOf(g, g.id === rootId)]));
195
+ const widest = (id: string): number => Math.max(0, ...(texts.get(id) ?? []).map((line) => textWidth(line.text, line.style)));
196
+ const widthOf = (g: Grown): number =>
197
+ g.id === rootId ? Math.max(T.root.w, T.root.textX + widest(g.id) + T.root.padR) : Math.max(T.w, widest(g.id) + T.padX * 2);
198
+ const cardW = (g: Grown): number => Math.max(T.card.minW, T.card.padX * 2 + T.card.icon + T.card.gap + textWidth(g.id, TYPE.treeCard));
199
+ const hasCard = (g: Grown): boolean => g.kind === "leaf" && g.hash !== undefined;
200
+
201
+ // 子を持たない箱を書いた順に左から並べる。間は一番広い箱か札の幅に、隣の箱との間を足した長さ
202
+ const slots = grown.filter((g) => g.children.length === 0);
203
+ const pitch = Math.max(...grown.filter((g) => g.id !== rootId || g.children.length === 0).map((g) => Math.max(widthOf(g), hasCard(g) ? cardW(g) : 0)), T.w) + T.slotGap;
204
+ const x0 = margin + BD.r * 2 + BD.inset;
205
+ const xs = new Map<string, number>();
206
+ slots.forEach((g, i) => xs.set(g.id, x0 + pitch * (i + 0.5)));
207
+ const xOf = (id: string): number => {
208
+ const known = xs.get(id);
209
+ if (known !== undefined) return known;
210
+ const kids = byId.get(id)?.children ?? [];
211
+ const x = (xOf(kids[0] as string) + xOf(kids[kids.length - 1] as string)) / 2;
212
+ xs.set(id, x);
213
+ return x;
214
+ };
215
+ const top0 = margin + T.top;
216
+ const yOf = (d: number): number => top0 + T.root.h / 2 + d * T.row;
217
+
218
+ const colors = boxColors(diagram);
219
+ const nodes: TreePlaced[] = grown.map((g) => {
220
+ const root = g.id === rootId;
221
+ const d = depth.get(g.id) ?? 0;
222
+ const cx = xOf(g.id);
223
+ const cy = yOf(d);
224
+ const w = widthOf(g);
225
+ const h = root ? T.root.h : T.h;
226
+ const lines = texts.get(g.id) ?? [];
227
+ const baselines =
228
+ lines.length === 1 ? [cy + T.oneY] : root ? [cy + T.root.nameY, cy + T.root.hashY] : [cy + T.hashY, cy + T.nameY];
229
+ const parent = parents.get(g.id);
230
+ const color: ColorKey = root ? T.rootColor : T.color;
231
+ colors.set(g.id, color);
232
+ const cw = cardW(g);
233
+ return {
234
+ id: g.id,
235
+ kind: g.kind,
236
+ depth: d,
237
+ ...(parent !== undefined ? { parent } : {}),
238
+ children: g.children,
239
+ step: g.step,
240
+ event: g.event,
241
+ ...(g.hash !== undefined ? { hash: g.hash } : {}),
242
+ root,
243
+ x: cx - w / 2,
244
+ y: cy - h / 2,
245
+ w,
246
+ h,
247
+ cx,
248
+ cy,
249
+ color,
250
+ lines: lines.map((line) => line.text),
251
+ baselines,
252
+ styles: lines.map((line) => line.style),
253
+ ...(hasCard(g) ? { card: { x: cx - cw / 2, y: cy + T.card.drop - T.card.h / 2, w: cw, h: T.card.h, text: g.id } } : {}),
254
+ };
255
+ });
256
+ const placed = new Map(nodes.map((n) => [n.id, n]));
257
+
258
+ // 子から親への木の線。子の段と親の段の間の高さで横に渡る
259
+ const links: TreeLink[] = nodes.flatMap((p) =>
260
+ p.children.flatMap((id): TreeLink[] => {
261
+ const c = placed.get(id);
262
+ if (!c) return [];
263
+ const mid = (c.y + p.y + p.h) / 2;
264
+ const points: Point[] = [
265
+ [c.cx, c.y - LOOK.edge.inset],
266
+ [c.cx, mid],
267
+ [p.cx, mid],
268
+ [p.cx, p.y + p.h + LOOK.edge.inset],
269
+ ];
270
+ return [{ from: c.id, to: p.id, step: p.step, event: p.event, points }];
271
+ }),
272
+ );
273
+
274
+ // 木でない箱は、木の右に根の上端の高さから縦に並べる。根と箱の間の線に名前を書く時は、名前の分だけ根から離す
275
+ const rooms = slotRooms(diagram);
276
+ const treeRight = Math.max(x0, ...nodes.flatMap((n) => [n.x + n.w, ...(n.card ? [n.card.x + n.card.w] : [])]));
277
+ const rootBox = nodes.find((n) => n.root);
278
+ const ids = new Set(diagram.boxes.map((b) => b.id));
279
+ const named = edgesOf(diagram).flatMap(({ edge }) => (edge.label !== undefined && (ids.has(edge.from) || ids.has(edge.to)) ? [textWidth(edge.label, labelStyle(edge.label)) + LOOK.label.padX * 2] : []));
280
+ const boxX = Math.max(treeRight + T.boxGap, (rootBox ? rootBox.x + rootBox.w : x0) + Math.max(0, ...named) + gap * 2);
281
+ let by = rootBox?.y ?? top0;
282
+ const boxes: SceneBox[] = diagram.boxes.map((b) => {
283
+ const w = Math.max(boxWidth(diagram, b.id, true), slotBoxWidth(rooms.get(b.id), b.icon !== undefined, B.padX));
284
+ const y = by;
285
+ by += B.h + gap;
286
+ const box: SceneBox = {
287
+ id: b.id,
288
+ name: b.name,
289
+ ...(b.sub !== undefined ? { sub: b.sub } : {}),
290
+ ...(b.icon !== undefined ? { icon: b.icon } : {}),
291
+ color: colors.get(b.id) ?? "slate",
292
+ x: boxX,
293
+ y,
294
+ w,
295
+ h: B.h,
296
+ cx: boxX + w / 2,
297
+ cy: y + B.h / 2,
298
+ };
299
+ placeSlot(box, rooms.get(b.id));
300
+ return box;
301
+ });
302
+ const boxById = new Map(boxes.map((b) => [b.id, b]));
303
+
304
+ // 線。親子の箱どうしの線は木の線の上を、向きに合わせて走る
305
+ const runs: TreeRun[] = [];
306
+ const edges: SceneEdge[] = diagram.steps.flatMap((step, s) =>
307
+ step.events.flatMap((e, k): SceneEdge[] => {
308
+ if (e.type !== "edge") return [];
309
+ const a: Rect | undefined = placed.get(e.from) ?? boxById.get(e.from);
310
+ const b: Rect | undefined = placed.get(e.to) ?? boxById.get(e.to);
311
+ if (!a || !b) return [];
312
+ const up = links.find((l) => l.from === e.from && l.to === e.to);
313
+ const down = links.find((l) => l.from === e.to && l.to === e.from);
314
+ const link = up ?? down;
315
+ if (link) runs.push({ step: s, event: k, link: link.from });
316
+ const points = up ? up.points : down ? [...down.points].reverse() : e.from === e.to ? loopUnder({ cx: a.x + a.w / 2, y: a.y, h: a.h }) : route(a, b);
317
+ return [{ step: s, event: k, from: e.from, to: e.to, points, color: edgeColor(e, colors), carry: e.carry }];
318
+ }),
319
+ );
320
+ seatCarriers(edges, boxById, rooms);
321
+
322
+ const layout: TreeLayout = {
323
+ kind: "tree",
324
+ width: 0,
325
+ height: 0,
326
+ regions: [],
327
+ boxes,
328
+ lifelines: [],
329
+ edges,
330
+ labels: [],
331
+ actions: [],
332
+ badges: [],
333
+ paths: [],
334
+ ends: [],
335
+ nodes,
336
+ links,
337
+ runs,
338
+ };
339
+ layout.badges = badgesOf(diagram, layout);
340
+ layout.labels = labelsOf(diagram, layout);
341
+
342
+ const cards = nodes.flatMap((n) => (n.card ? [n.card] : []));
343
+ const solids: Rect[] = [...nodes, ...cards, ...boxes, ...layout.labels];
344
+ const points = edges.flatMap((e) => e.points);
345
+ const right = Math.max(...solids.map((r) => r.x + r.w), ...points.map(([x]) => x), x0);
346
+ const bottom = Math.max(...solids.map((r) => r.y + r.h), ...points.map(([, y]) => y), top0);
347
+ const width = Math.max(right + margin, stripNeed(diagram) + margin * 2);
348
+ const strip = layoutStrip(diagram, margin, bottom + gap, width - margin * 2);
349
+ layout.width = width;
350
+ layout.height = (strip ? strip.y + strip.h : bottom) + margin;
351
+ if (strip) layout.strip = strip;
352
+ // 中身の帯だけを書き換える段の番号は帯の左上に置くので、帯を置いた後に決め直す
353
+ layout.badges = badgesOf(diagram, layout);
354
+ return layout;
355
+ }
356
+
357
+ /**
358
+ * 段の番号。箱が現れる段は最初に現れた木の箱の左に置き、左が埋まっていれば左上の角、右、右上の角の順に空きを探す。
359
+ * 線を引く段は最初の線の上に置く。木の線を走る線は、子の側の曲がり角から横の線に沿って `LOOK.tree.badgeAlong` 進めた所に、ほかの線は真ん中に置き、
360
+ * 運ぶ物が出発を待つ所と着いた所を空ける。同じ 2 つの箱を結ぶ線を前の段が通っていれば、前の段の番号と同じ所に置く (#3184)。
361
+ * どちらも無い段は、書き換える箱か帯の左上の角に置き、それも無ければ前の段の番号と入れ替える
362
+ */
363
+ function badgesOf(diagram: Diagram, layout: TreeLayout): SceneBadge[] {
364
+ const { r, inset } = LOOK.badge;
365
+ const apart = r * 2 + inset;
366
+ const taken: Point[] = [];
367
+ const out: SceneBadge[] = [];
368
+ const solids: Rect[] = [...layout.nodes, ...layout.nodes.flatMap((n) => (n.card ? [n.card] : [])), ...layout.boxes];
369
+ const free = (p: Point): boolean =>
370
+ taken.every(([x, y]) => Math.hypot(p[0] - x, p[1] - y) >= apart) && solids.every((s) => gapBetween(badgeRect(p), s) >= LOOK.label.touch);
371
+ const put = (s: number, p: Point, color: ColorKey): void => {
372
+ taken.push(p);
373
+ out.push({ step: s, x: p[0], y: p[1], color });
374
+ };
375
+ const passed = new Map<string, Point>();
376
+ diagram.steps.forEach((step, s) => {
377
+ const k = step.events.findIndex((e) => e.type === "leaf" || e.type === "node" || e.type === "edge");
378
+ const first = step.events[k];
379
+ const n = layout.nodes.find((x) => x.step === s && x.event === k);
380
+ if (first && first.type !== "edge" && n) {
381
+ const spots: Point[] = [
382
+ [n.x - inset - r, n.cy],
383
+ [n.x, n.y],
384
+ [n.x + n.w + inset + r, n.cy],
385
+ [n.x + n.w, n.y],
386
+ ];
387
+ put(s, spots.find(free) ?? (spots[0] as Point), n.color);
388
+ return;
389
+ }
390
+ const e = layout.edges.find((x) => x.step === s && x.event === k);
391
+ if (first?.type === "edge" && e) {
392
+ const key = [e.from, e.to].sort().join("\n");
393
+ const run = layout.runs.some((x) => x.step === s && x.event === k);
394
+ const lines = layout.edges.filter((x) => x !== e).map((x) => x.points);
395
+ const point = passed.get(key) ?? (run ? onLink(e.points, free) : midway(e, free)) ?? badgeOnPath(e.points, taken, lines);
396
+ passed.set(key, point);
397
+ put(s, point, e.color);
398
+ return;
399
+ }
400
+ const box = step.events.flatMap((ev) => (ev.type === "swap" || ev.type === "action" ? [ev.box] : [])).flatMap((id) => layout.boxes.filter((b) => b.id === id))[0];
401
+ if (box) {
402
+ out.push({ step: s, x: box.x, y: box.y, color: box.color });
403
+ return;
404
+ }
405
+ if (layout.strip && step.events.some((ev) => ev.type === "strip")) {
406
+ out.push({ step: s, x: layout.strip.x + inset, y: layout.strip.y + inset, color: "slate" });
407
+ return;
408
+ }
409
+ const before = out[out.length - 1];
410
+ const root = layout.nodes.find((x) => x.root);
411
+ out.push(before ? { ...before, step: s } : { step: s, x: root?.x ?? LOOK.margin, y: root?.y ?? LOOK.margin, color: root?.color ?? "slate" });
412
+ });
413
+ return replaceSameSpot(out);
414
+ }
415
+
416
+ /** 木の線の上の段の番号の点。最初の曲がり角から横の線に沿って進め、横の線が短い時は縦の線の真ん中の脇に置く */
417
+ function onLink(points: Point[], free: (p: Point) => boolean): Point | undefined {
418
+ const [p0, p1, p2] = points as [Point, Point, Point];
419
+ const flat = Math.abs(p2[0] - p1[0]);
420
+ const { r, inset } = LOOK.badge;
421
+ if (flat >= LOOK.tree.badgeAlong + r) {
422
+ const p = along(points, pathLength([p0, p1]) + LOOK.tree.badgeAlong);
423
+ if (free(p)) return p;
424
+ }
425
+ const side: Point = [p1[0] + r + inset, p1[1]];
426
+ return free(side) ? side : undefined;
427
+ }
428
+
429
+ /** 木の線でない線の段の番号の点。運ぶ物が待つ線の両端を空け、真ん中から外へ空きを探す。線が短くて空かない時は返さない */
430
+ function midway(e: SceneEdge, free: (p: Point) => boolean): Point | undefined {
431
+ const length = pathLength(e.points);
432
+ const room = carrierHalf(e.carry)[0] + LOOK.badge.r + LOOK.badge.inset;
433
+ for (let d = 0; d <= length / 2 - room; d += 1) {
434
+ for (const at of [length / 2 - d, length / 2 + d]) {
435
+ const p = along(e.points, at);
436
+ if (free(p)) return p;
437
+ }
438
+ }
439
+ return undefined;
440
+ }
441
+
442
+ /** 線の名前。箱と木の箱から離し、葉の下の札と同じ段の名前に重ねず、同じ時刻に見える段の番号に食い込ませない */
443
+ function labelsOf(diagram: Diagram, layout: TreeLayout): SceneLabel[] {
444
+ const labels: SceneLabel[] = [];
445
+ const cards = layout.nodes.flatMap((n) => (n.card ? [n.card] : []));
446
+ for (const e of layout.edges) {
447
+ const source = diagram.steps[e.step]?.events[e.event];
448
+ if (source?.type !== "edge" || source.label === undefined) continue;
449
+ const seen = layout.badges.filter((b) => b.step <= e.step).map((b) => badgeRect([b.x, b.y]));
450
+ labels.push(
451
+ placeLabel(
452
+ { step: e.step, event: e.event, text: source.label, points: e.points, color: e.color, ...(source.labelSide ? { side: source.labelSide } : {}), flip: true },
453
+ { hard: [...layout.nodes, ...layout.boxes], soft: [...cards, ...labels.filter((l) => l.step === e.step)], touch: seen },
454
+ ),
455
+ );
456
+ }
457
+ return labels;
458
+ }
@@ -115,6 +115,15 @@ export const TYPE = {
115
115
  gitId: text(11, 700),
116
116
  gitHash: text(10.5, 600, "mono"),
117
117
  gitNote: text(10.5, 650),
118
+ /**
119
+ * 木の図 (#3233) の、箱の中の値 (hash) と名札、根の箱の値と名札、葉の下の札の字。
120
+ * 値を持たない箱の名札は箱の名前 (`boxName`) の字で描く
121
+ */
122
+ treeHash: text(13.5, 700, "mono"),
123
+ treeName: text(10.5, 600),
124
+ rootHash: text(15, 700, "mono"),
125
+ rootName: text(11, 700),
126
+ treeCard: text(11.5, 650),
118
127
  /**
119
128
  * 時間軸の図 (#3165)。拡大の帯の列の上の字、印の列の名前、時刻の字、区切りの名前と目盛りの番号の範囲、
120
129
  * 節目の名札と状態、範囲の括弧の字、空きの枠の字、物差しの線の字。和文を含む字は同じ大きさと太さの和文の字で描く
@@ -209,6 +218,36 @@ export const LOOK = {
209
218
  labelUnder: 50,
210
219
  colors: ["blue", "violet", "green", "amber", "rose"],
211
220
  },
221
+ /**
222
+ * 木の図 (#3233)。step 2 で本人が選んだ「根を上」の試作 (`.context/propose/merkle-look/`) の寸法を写す。
223
+ * 木の箱は幅の下限 `w`、高さ `h`、字の左右の余白 `padX`、角の丸み `radius`。根の箱は `root` の幅の下限と高さと角の丸みを持ち、
224
+ * 左に絵柄を置いて (`iconX` は箱の左端から絵柄の左端まで)、`textX` から字を左に揃えて並べ、右に `padR` を空ける。
225
+ * `nameY` と `hashY` は根の箱の真ん中から名札と値の基準線まで。ほかの箱の値と名札は `hashY` と `nameY`、1 行の字は `oneY` に置く。
226
+ * 葉は書いた順に横に並べ、隣の葉の箱の間を `slotGap` 空ける。根の上端は図の上の余白から `top` 下げ、深さの段の真ん中どうしは `row` 離す。
227
+ * `card` は値を持つ葉の下の名札の札で、葉の真ん中から札の真ん中まで `drop`、高さ `h`、幅の下限 `minW`、
228
+ * 字の左右の余白 `padX`、絵柄の幅 `icon` と絵柄と字の間 `gap`、絵柄の縮み `glyph`、角の丸み `radius`。
229
+ * `boxGap` は木と木でない箱の列の間、`badgeAlong` は木の線を走る段の番号を、曲がり角から横の線に沿って進める長さ。
230
+ * `faint` は木の線を運ぶ物が通った段から後に、運ぶ物を送りも受けもしていない木の箱を薄く出す濃さ。`color` と `rootColor` は木の箱と根の箱の色
231
+ */
232
+ tree: {
233
+ w: 74,
234
+ h: 44,
235
+ padX: 10,
236
+ radius: 10,
237
+ root: { w: 112, h: 54, radius: 13, iconX: 10, textX: 46, padR: 14, nameY: -4, hashY: 14 },
238
+ hashY: -1,
239
+ nameY: 14,
240
+ oneY: 4.5,
241
+ slotGap: 12,
242
+ top: 16,
243
+ row: 102,
244
+ card: { drop: 78, h: 30, minW: 70, padX: 10, icon: 12, gap: 6, glyph: 0.62, radius: 9 },
245
+ boxGap: 24,
246
+ badgeAlong: 22,
247
+ faint: 0.42,
248
+ color: "violet",
249
+ rootColor: "green",
250
+ },
212
251
  /**
213
252
  * 時間軸の図 (#3165)。見本帳の試作 (`scenes/finality.js`) の寸法を写す。
214
253
  * 図の幅は `width` で、時間軸は左の `axisX` から右の余白 `right` の手前まで。印の列の名前が長い時は、名前の右に `gutterGap` を空けて軸を右へ寄せる。
@@ -313,6 +352,9 @@ export const LOOK = {
313
352
  timeFlag: 1.8,
314
353
  timeNeedle: 1.25,
315
354
  timeMeter: 1.25,
355
+ tree: 1.5,
356
+ treeTrail: 2.6,
357
+ treeCon: 1.3,
316
358
  },
317
359
  shadow: { near: 0.8, far: 4, nearY: 1, farY: 3 },
318
360
  mini: { w: 168, pad: 8, title: 14, inset: 12, radius: 10 },
package/src/messages.ts CHANGED
@@ -88,6 +88,20 @@ export interface Messages {
88
88
  badHash: string;
89
89
  /** 時間軸の図だけの行か属性 (`word`) を、別の種類の図に書いた (#3165) */
90
90
  timeOnly: (word: string) => string;
91
+ /** 木の図だけの行 (`leaf` と `node`) を、別の種類の図に書いた (#3233) */
92
+ treeOnly: (word: string) => string;
93
+ treeNoGroup: string;
94
+ noLeaves: string;
95
+ leafShape: string;
96
+ nodeShape: string;
97
+ /** 親の子に、まだ書いていない名札を書いた */
98
+ noTreeChild: (id: string) => string;
99
+ /** 親の子に、木の箱でない箱 (`box`) を書いた */
100
+ notTreeBox: (id: string) => string;
101
+ /** もう親を持つ箱を、別の親の子にした */
102
+ twoParents: (id: string) => string;
103
+ /** 最後の段を終えて、親を持たない箱が根の外に残った */
104
+ manyRoots: (id: string, root: string) => string;
91
105
  /** 時間軸の図の宣言の行を 2 つ書いた */
92
106
  timeTwice: (word: string) => string;
93
107
  noScale: string;
@@ -162,7 +176,7 @@ const ja = (): Messages => {
162
176
  emptyCode: "code の後ろに命令を書く",
163
177
  sourceShape: "source は source <名前> [url: <URL>] の形で書く",
164
178
  declarationInStep: "group と box と strip と branch と、scale と period と row と point と zoom は最初の step より前に書く",
165
- stepLineBeforeStep: "線と say と code と source と act と note と set と commit と枝を切る行と、now と mark と span の行は step の下に書く",
179
+ stepLineBeforeStep: "線と say と code と source と act と note と set と commit と枝を切る行と、now と mark と span と、leaf と node の行は step の下に書く",
166
180
  nestedGroup: "group の中に group は書けない。先に end で閉じる",
167
181
  strayEnd: "end の前に、閉じる group が無い",
168
182
  endTakesNothing: "end の後ろには何も書かない",
@@ -210,6 +224,15 @@ const ja = (): Messages => {
210
224
  headReserved: (name) => `${name} は枝分かれの図で今いる場所の札の名前で、名札に使えない`,
211
225
  badHash: "hash は 0 から 9 と a から f の字で 4 から 40 字にする",
212
226
  timeOnly: (word) => `${word} は time (時間軸の図) でだけ書ける`,
227
+ treeOnly: (word) => `${word} の行は tree (木の図) でだけ書ける`,
228
+ treeNoGroup: "tree (木の図) には group を書けない。木の箱は leaf と node の行で書く",
229
+ noLeaves: "leaf の行で葉を 1 つ以上書く",
230
+ leafShape: "leaf は leaf <名札> [hash: <hash>] の形で書く",
231
+ nodeShape: "node は node <名札> of <子>, <子> [hash: <hash>] の形で書く",
232
+ noTreeChild: (id) => `${id} という葉か親はまだ書いていない。子は前に leaf か node で書いた名札にする`,
233
+ notTreeBox: (id) => `${id} は box の行で置いた箱で、木の箱でない。子は leaf か node で書いた名札にする`,
234
+ twoParents: (id) => `${id} はもう別の親の子になっている。木の箱の親は 1 つだけ`,
235
+ manyRoots: (id, root) => `${id} が親を持たないまま残る。木の根は 1 つだけで、${id} も ${root} も最後に 1 つの根へ組む`,
213
236
  timeTwice: (word) => `${word} は 1 つだけ宣言する`,
214
237
  noScale: "scale の行で目盛りを宣言する",
215
238
  noRows: "row の行で印の列を 1 つ以上宣言する",
@@ -276,7 +299,7 @@ const en = (): Messages => {
276
299
  emptyCode: "Write the command after code",
277
300
  sourceShape: "Write a source as source <name> [url: <URL>]",
278
301
  declarationInStep: "Write group, box, strip, branch, scale, period, row, point and zoom before the first step",
279
- stepLineBeforeStep: "Write lines, say, code, source, act, note, set, commit, branch cuts, now, mark and span under a step",
302
+ stepLineBeforeStep: "Write lines, say, code, source, act, note, set, commit, branch cuts, now, mark, span, leaf and node under a step",
280
303
  nestedGroup: "A group cannot hold another group. Close it with end first",
281
304
  strayEnd: "There is no group for this end to close",
282
305
  endTakesNothing: "Write nothing after end",
@@ -324,6 +347,15 @@ const en = (): Messages => {
324
347
  headReserved: (name) => `${name} names where you are in a git diagram and cannot be an id`,
325
348
  badHash: "Write a hash as 4 to 40 characters of 0-9 and a-f",
326
349
  timeOnly: (word) => `${word} can be written only in time diagrams`,
350
+ treeOnly: (word) => `${word} lines can be written only in tree diagrams`,
351
+ treeNoGroup: "A tree diagram takes no group. Write the tree boxes with leaf and node lines",
352
+ noLeaves: "Write at least one leaf with a leaf line",
353
+ leafShape: "Write a leaf as leaf <id> [hash: <hash>]",
354
+ nodeShape: "Write a node as node <id> of <child>, <child> [hash: <hash>]",
355
+ noTreeChild: (id) => `No leaf or node named ${id} has been written yet. A child must be an id written earlier with leaf or node`,
356
+ notTreeBox: (id) => `${id} is a box from a box line, not a tree box. A child must be an id written with leaf or node`,
357
+ twoParents: (id) => `${id} is already a child of another node. A tree box has only one parent`,
358
+ manyRoots: (id, root) => `${id} is left without a parent. A tree has one root, so join ${id} and ${root} under one root by the end`,
327
359
  timeTwice: (word) => `Declare only one ${word}`,
328
360
  noScale: "Declare the scale with a scale line",
329
361
  noRows: "Declare at least one row with a row line",