@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/src/parser.ts CHANGED
@@ -51,6 +51,10 @@
51
51
  * 中身の帯の欄の名前の後ろに `[meter: <割合>]` を書くと物差しになり、`set` の値を割合 (`97%` か `2/3`) で書く。
52
52
  * 印の列と箱は同じ名札を持てる (空いた目盛りの列でその箱を空きの枠にするため)。時間軸の図では `now` を名札に使えない。
53
53
  *
54
+ * 木の図 (`tree`、#3233) は、段の中に `leaf <名札> [hash: <hash>]` で葉を出し、`node <名札> of <子>, <子> [hash: <hash>]` で
55
+ * 前に書いた葉か親を子にして親を組む。箱は書いた段で現れ、親は 1 つだけ持てる。最後の段を終えた時に親を持たない木の箱は根の 1 つだけ。
56
+ * 線の端には木の箱も `box` の箱も書ける。木の図に区画 (`group`) は書けず、`leaf` と `node` の行は木の図でだけ書ける。
57
+ *
54
58
  * 行の頭の語と同じ綴りの名札 (`end` や `step`) も書ける。名札の次に `->` が来る行は線と読む。
55
59
  * 誤りは最初の 1 つで止め、行と列を示す。誤りの文の言葉は呼ぶ側が渡す。
56
60
  */
@@ -91,6 +95,7 @@ import {
91
95
  MERGE,
92
96
  type NotationLang,
93
97
  NOW,
98
+ OF,
94
99
  OLD_HEADS,
95
100
  ON,
96
101
  SIDES,
@@ -98,6 +103,7 @@ import {
98
103
  STATE_ENDS,
99
104
  TIME_EDGE_ATTRS,
100
105
  TIME_HEADS,
106
+ TREE_HEADS,
101
107
  VIEWS,
102
108
  } from "./words";
103
109
 
@@ -135,6 +141,9 @@ const EDGE = /^([^\s:[\]]+?)\s*->\s*([^\s:[\]]+)/du;
135
141
  const COMMIT = new RegExp(`^commit\\s+([^\\s[]+)(?:\\s+${ON}\\s+([^\\s[]+))?(?:\\s+${COPY}\\s+([^\\s[]+))?(?:\\s+${MERGE}\\s+([^\\s[]+))?`, "du");
136
142
  /** 枝分かれの図の、枝を切る行。枝と `from` と切る commit */
137
143
  const CUT = new RegExp(`^([^\\s[]+)\\s+${FROM}(?:\\s+([^\\s[]+))?\\s*$`, "du");
144
+ /** 木の図の `leaf` の行の名札と、`node` の行の名札と `of` */
145
+ const LEAF = /^leaf\s+([^\s[]+)/du;
146
+ const NODE = new RegExp(`^node\\s+([^\\s[]+)\\s+${OF}\\s+`, "du");
138
147
  /** commit の hash。原本の JSON の hash の形と同じ */
139
148
  const HASH = /^[0-9a-f]{4,40}$/u;
140
149
  /** 箱の飛び先と段の出典の URL。原本の JSON の URL の形と同じ */
@@ -356,6 +365,10 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
356
365
  const isState = kind === "state";
357
366
  const isGit = kind === "git";
358
367
  const isTime = kind === "time";
368
+ const isTree = kind === "tree";
369
+ /** 木の図で書いた木の箱と、書いた行と名札の位置。子の箱から親の名札 */
370
+ const trees = new Map<string, { source: SourceLine; at: number }>();
371
+ const parents = new Map<string, string>();
359
372
  /** 時間軸の図の目盛りと区切りと印の列と節目と拡大の範囲 (#3165) */
360
373
  let scale: TimeScale | undefined;
361
374
  let period: TimePeriod | undefined;
@@ -414,6 +427,7 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
414
427
  if (!boxes.some((box) => box.id === id) && !points.some((point) => point.id === id)) throw fail(source, at, m.undeclaredNote(id));
415
428
  return id;
416
429
  }
430
+ if (isTree && trees.has(id)) return id;
417
431
  if (!isState || !isOneOf(STATE_ENDS, id)) return boxAt(source, id, at);
418
432
  if ((id === "start") !== (side === "from")) throw fail(source, at, id === "start" ? m.intoStart : m.outOfFinish);
419
433
  return id;
@@ -472,6 +486,7 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
472
486
  }
473
487
  if (!isGit && (word === "branch" || word === "commit")) throw fail(source, 0, m.gitOnly(word));
474
488
  if (!isTime && isOneOf(TIME_HEADS, word)) throw fail(source, 0, m.timeOnly(word));
489
+ if (!isTree && isOneOf(TREE_HEADS, word)) throw fail(source, 0, m.treeOnly(word));
475
490
  if (!isOneOf(HEADS, word)) {
476
491
  const old = oldForm(text, building !== undefined);
477
492
  throw fail(source, 0, old ? m.oldForm(old.word, old.shape) : m.unknownHead(word));
@@ -562,6 +577,16 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
562
577
  case "span":
563
578
  inStep(source).events.push(readSpan(source));
564
579
  break;
580
+ case "leaf": {
581
+ const step = inStep(source);
582
+ step.events.push(readLeaf(source));
583
+ break;
584
+ }
585
+ case "node": {
586
+ const step = inStep(source);
587
+ step.events.push(readNode(source));
588
+ break;
589
+ }
565
590
  }
566
591
  }
567
592
  if (group) throw fail(group.source, 0, m.unclosedGroup(group.id));
@@ -569,8 +594,14 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
569
594
  finish();
570
595
 
571
596
  if (isGit && branches.length === 0) throw fail(head, 0, m.noBranches);
572
- if (boxes.length === 0 && !isGit && !isTime) throw fail(head, 0, m.noBoxes);
597
+ if (isTree && trees.size === 0) throw fail(head, 0, m.noLeaves);
598
+ if (boxes.length === 0 && !isGit && !isTime && !isTree) throw fail(head, 0, m.noBoxes);
573
599
  if (steps.length === 0) throw fail(head, 0, m.noSteps);
600
+ // 木の形は全ての行を読んでから確かめる。親を持たない木の箱が 2 つ以上なら、書いた順で 2 つ目を示す
601
+ const roots = [...trees.keys()].filter((id) => !parents.has(id));
602
+ const [root, stray] = roots;
603
+ const strayAt = stray === undefined ? undefined : trees.get(stray);
604
+ if (root !== undefined && stray !== undefined && strayAt) throw fail(strayAt.source, strayAt.at, m.manyRoots(stray, root));
574
605
 
575
606
  return {
576
607
  version: FORMAT_VERSION,
@@ -786,6 +817,7 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
786
817
  function readGroup(source: SourceLine): void {
787
818
  beforeSteps(source);
788
819
  if (isGit) throw fail(source, 0, m.gitNoGroup);
820
+ if (isTree) throw fail(source, 0, m.treeNoGroup);
789
821
  if (group) throw fail(source, 0, m.nestedGroup);
790
822
  const declared = readDeclared(source, "group", ATTRS.group, m);
791
823
  if (regions.some((region) => region.id === declared.id)) {
@@ -898,6 +930,62 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
898
930
  return { type: "branch", branch, from };
899
931
  }
900
932
 
933
+ /** 木の図の `leaf <名札> [hash: <hash>]` の行 */
934
+ function readLeaf(source: SourceLine): DiagramEvent {
935
+ const text = source.text;
936
+ const found = LEAF.exec(text);
937
+ const id = found?.[1];
938
+ if (!found || id === undefined) throw fail(source, 0, m.leafShape);
939
+ const idAt = found.indices?.[1]?.[0] ?? 0;
940
+ if (!ID.test(id)) throw fail(source, idAt, m.badId(id));
941
+ declare(source, id, idAt);
942
+ trees.set(id, { source, at: idAt });
943
+ const rest = skipSpaces(text, found[0].length);
944
+ if (rest < text.length && text[rest] !== "[") throw fail(source, rest, m.leafShape);
945
+ const hash = treeHash(source, rest, ATTRS.leaf);
946
+ return { type: "leaf", id, ...(hash !== undefined ? { hash } : {}) };
947
+ }
948
+
949
+ /**
950
+ * 木の図の `node <名札> of <子>, <子> [hash: <hash>]` の行。子は前に書いた葉か親で、まだ親を持たない箱に限る。
951
+ * 子は `,` で区切り、`[` か行の終わりで終わる
952
+ */
953
+ function readNode(source: SourceLine): DiagramEvent {
954
+ const text = source.text;
955
+ const found = NODE.exec(text);
956
+ const id = found?.[1];
957
+ if (!found || id === undefined) throw fail(source, 0, m.nodeShape);
958
+ const idAt = found.indices?.[1]?.[0] ?? 0;
959
+ if (!ID.test(id)) throw fail(source, idAt, m.badId(id));
960
+ declare(source, id, idAt);
961
+ const children: string[] = [];
962
+ let end = found[0].length;
963
+ for (;;) {
964
+ const start = skipSpaces(text, end);
965
+ end = start;
966
+ while (end < text.length && text[end] !== "," && text[end] !== "[") end++;
967
+ const child = text.slice(start, end).trim();
968
+ if (child === "" || !ID.test(child)) throw fail(source, start, m.nodeShape);
969
+ if (!trees.has(child)) throw fail(source, start, ids.has(child) && child !== id ? m.notTreeBox(child) : m.noTreeChild(child));
970
+ if (parents.has(child)) throw fail(source, start, m.twoParents(child));
971
+ parents.set(child, id);
972
+ children.push(child);
973
+ if (text[end] !== ",") break;
974
+ end++;
975
+ }
976
+ const hash = treeHash(source, end, ATTRS.node);
977
+ trees.set(id, { source, at: idAt });
978
+ return { type: "node", id, children, ...(hash !== undefined ? { hash } : {}) };
979
+ }
980
+
981
+ /** 葉と親の行の名札の後ろの `[hash: <hash>]`。`at` は `[` か行の終わり */
982
+ function treeHash(source: SourceLine, at: number, keys: readonly string[]): string | undefined {
983
+ if (at >= source.text.length) return undefined;
984
+ const hash = readAttrs(source, at, keys, m).get("hash");
985
+ if (hash && !HASH.test(hash.value)) throw fail(source, hash.at, m.badHash);
986
+ return hash?.value;
987
+ }
988
+
901
989
  /** `strip <題>: <欄>, <欄>` の行 */
902
990
  function readStrip(source: SourceLine): void {
903
991
  beforeSteps(source);
package/src/printer.ts CHANGED
@@ -13,10 +13,11 @@
13
13
  * 枝分かれの図 (#3164) は、枝の `branch` の行を箱より前に書き、札を動かす線の運ぶ物が送る側の名前の札なら書かない。
14
14
  * 時間軸の図 (#3165) は、目盛りと区切りと印の列と節目と拡大の範囲の行を箱より前に書き、物差しの欄の後ろに `[meter: <割合>]` を書く。
15
15
  * 時間軸の図の `note` は属性を持てるので、`[` を含む字を `"` で囲む。
16
+ * 木の図 (#3233) の葉と親は、段の中に `leaf` と `node … of …` の行で書く。
16
17
  * 段の出典 (#3199) は `say` と `code` の後ろ、段の中で起きることより前に、JSON の並びのまま 1 つずつ `source` の行に書く。
17
18
  */
18
19
  import type { Box, Diagram, DiagramEvent, Region, TimeSpec } from "./schema";
19
- import { AT, COPY, FROM, MERGE, NOW, ON } from "./words";
20
+ import { AT, COPY, FROM, MERGE, NOW, OF, ON } from "./words";
20
21
 
21
22
  const quote = (text: string): string => `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
22
23
  /** 行の終わりか `[` の前に置く名前と文 */
@@ -89,6 +90,10 @@ function event(e: DiagramEvent, kind: Diagram["kind"]): string {
89
90
  ])}`;
90
91
  case "branch":
91
92
  return `${e.branch} ${FROM} ${e.from}`;
93
+ case "leaf":
94
+ return `leaf ${e.id}${attrs([["hash", e.hash]])}`;
95
+ case "node":
96
+ return `node ${e.id} ${OF} ${e.children.join(", ")}${attrs([["hash", e.hash]])}`;
92
97
  }
93
98
  }
94
99
 
@@ -5,6 +5,7 @@
5
5
  * `undo` (戻る矢印) と `yen` (円の印) は、注文の試作 (`docs/design/base/scenes/order.js`) が返品と返金に足した形 (#3171)。
6
6
  * package の入口からも出し、見本帳の部品「絵」の頁がこの表から使える絵柄の一覧を作る。1 つずつの絵は `iconSvg` が描く (#3172)。
7
7
  * `flag` (旗) は、時間軸の図の節目の丸に描く形 (#3165)。ブロックの確定の試作 (`docs/design/base/scenes/finality.js`) が持っていた。
8
+ * `tree` (親子に分かれる木) は、木の図の根の箱に描く形 (#3233)。step 2 で本人が選んだ試作が持っていた。
8
9
  */
9
10
  export const ICONS: Readonly<Record<string, string>> = {
10
11
  app: "M -9 -7 h18 a2 2 0 0 1 2 2 v10 a2 2 0 0 1 -2 2 h-18 a2 2 0 0 1 -2 -2 v-10 a2 2 0 0 1 2 -2 z M -11 -2 h22",
@@ -43,5 +44,6 @@ export const ICONS: Readonly<Record<string, string>> = {
43
44
  layers: "M 0 -8 l9 4.5 l-9 4.5 l-9 -4.5 z M -9 2.5 l9 4.5 l9 -4.5",
44
45
  code: "M -4 -6 l-5 6 l5 6 M 4 -6 l5 6 l-5 6",
45
46
  paint: "M -8 8 c 0 -3 2 -5 4.5 -5 l 9 -9 l 3.5 3.5 l -9 9 c 0 2.5 -2 4.5 -5 4.5 z",
47
+ tree: "M 0 -5 v4 M -6 -1 h12 M -6 -1 v3 M 6 -1 v3 M -9 2 h6 v6 h-6 z M 3 2 h6 v6 h-6 z M -3 -10 h6 v5 h-6 z",
46
48
  block: "M -9 -7 h18 a2 2 0 0 1 2 2 v10 a2 2 0 0 1 -2 2 h-18 a2 2 0 0 1 -2 -2 v-10 a2 2 0 0 1 2 -2 z M -11 -2.5 h22 M -6 2.5 h8",
47
49
  };
package/src/render/svg.ts CHANGED
@@ -14,6 +14,7 @@ import type { Layout, Rect, SceneField, SceneLabel } from "../layout/scene";
14
14
  import { layoutSequence } from "../layout/sequence";
15
15
  import { layoutState } from "../layout/state";
16
16
  import { isTimeLayout, layoutTime } from "../layout/time";
17
+ import { isTreeLayout, layoutTree } from "../layout/tree";
17
18
  import { FONTS } from "../look/fonts";
18
19
  import { type ColorKey, type Colors, EASE, FONT_VARS, isColorName, isColorValue, LOOK, MOTION, type Palette, paletteVars, resolvePalette, type TextStyle, type Theme, TYPE } from "../look/values";
19
20
  import { readDiagram } from "../version";
@@ -45,6 +46,7 @@ import {
45
46
  } from "./parts";
46
47
  import { drawGit } from "./git";
47
48
  import { drawTime, meterField, sansOf, timeFocus } from "./time";
49
+ import { drawTree } from "./tree";
48
50
  import { findOverlaps, type Ink, type Overlap, type Trace } from "./ink";
49
51
  import { Motion } from "./motion";
50
52
 
@@ -172,6 +174,19 @@ const PART_CSS = [
172
174
  `.dg-git-n{${font(TYPE.gitNote)};fill:var(--ink2)}`,
173
175
  `.dg-git-old{fill:var(--surf);stroke:var(--c);stroke-width:${S.gitOrphan};stroke-dasharray:3 3;stroke-opacity:.6}`,
174
176
  `.dg-git-oldl{${font(TYPE.gitId)};fill:var(--ct);opacity:.55}`,
177
+ // 木の図 (#3233)。木の線は線の灰で、運ぶ物が通った跡は運ぶ物の色で引く
178
+ `.dg-tree-l{fill:none;stroke:var(--line);stroke-width:${S.tree};stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1 2}`,
179
+ `.dg-tree-tr{fill:none;stroke:var(--c);stroke-width:${S.treeTrail};stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1 2}`,
180
+ `.dg-tree-h{fill:none;stroke:var(--c);stroke-width:${S.treeTrail};stroke-linecap:round;stroke-linejoin:round}`,
181
+ `.dg-tree-con{fill:none;stroke:var(--line);stroke-width:${S.treeCon};stroke-linecap:round;stroke-dasharray:2 3.5}`,
182
+ `.dg-tree-card{fill:var(--surf);stroke:var(--hair);stroke-width:${S.hair}}`,
183
+ `.dg-tree-cg{fill:none;stroke:var(--mute);stroke-width:${S.glyph};stroke-linecap:round;stroke-linejoin:round}`,
184
+ `.dg-tree-ct{${font(TYPE.treeCard)};fill:var(--ink)}`,
185
+ `.dg-tree-hash{${font(TYPE.treeHash)};fill:var(--ink)}`,
186
+ `.dg-tree-name{${font(TYPE.treeName)};fill:var(--mute)}`,
187
+ `.dg-tree-one{${font(TYPE.boxName)};fill:var(--ink)}`,
188
+ `.dg-tree-rh{${font(TYPE.rootHash)};fill:var(--ink)}`,
189
+ `.dg-tree-rn{${font(TYPE.rootName)};fill:var(--mute)}`,
175
190
  // 時間軸の図 (#3165)。和文を含む字は、末尾に j を付けた class で同じ大きさと太さの和文の字にする
176
191
  `.dg-tm-ep{fill:color-mix(in srgb,var(--ink) ${X.timeShade}%,transparent)}`,
177
192
  `.dg-tm-sep{stroke:var(--hair);stroke-width:${S.hair};stroke-dasharray:2 4}`,
@@ -370,6 +385,15 @@ export function drawSvg(diagram: Diagram, layout: Layout, timeline: Timeline, pa
370
385
  L.node.push(git.commits);
371
386
  L.top.push(git.tags);
372
387
  }
388
+ // 木の図の木の線と通った跡と木の箱と札は、木の図を描く部品が描く (#3233)。木の線を走る線は通った跡が見せるので、ほかの線と同じ線で描かない
389
+ const treeLayout = isTreeLayout(layout) ? layout : undefined;
390
+ if (treeLayout) {
391
+ const tree = drawTree(treeLayout, diagram, timeline, ctx);
392
+ L.base.push(tree.links);
393
+ L.lit.push(tree.trails);
394
+ L.node.push(tree.nodes);
395
+ }
396
+ const runs = new Set((treeLayout?.runs ?? []).map((r) => `${r.step}/${r.event}`));
373
397
  // 時間軸の図の目盛りと印と拡大の帯の箱と節目は、時間軸の図を描く部品が描く (#3165)。拡大の帯の線は他の図と同じ線で描く
374
398
  const timeLayout = isTimeLayout(layout) ? layout : undefined;
375
399
  if (timeLayout) {
@@ -382,7 +406,7 @@ export function drawSvg(diagram: Diagram, layout: Layout, timeline: Timeline, pa
382
406
  const wired = new Set((timeLayout?.wires ?? []).map((w) => `${w.step}/${w.event}`));
383
407
  for (const e of layout.edges) {
384
408
  const time = timeline.edges.find((t) => t.step === e.step && t.event === e.event);
385
- if (!time || (timeLayout && !wired.has(`${e.step}/${e.event}`))) continue;
409
+ if (!time || (timeLayout && !wired.has(`${e.step}/${e.event}`)) || runs.has(`${e.step}/${e.event}`)) continue;
386
410
  const drawn = edge(e, time, ctx, isState);
387
411
  L.base.push(drawn.base);
388
412
  L.lit.push(drawn.lit);
@@ -413,9 +437,10 @@ export function drawSvg(diagram: Diagram, layout: Layout, timeline: Timeline, pa
413
437
  const until = (timeline.steps[a.step] as Span).end;
414
438
  L.top.push(whole && until > whole.start ? action(a, time.at, whole.end, ctx) : action(a, time.at, until, ctx, whole));
415
439
  }
440
+ // 木の図の運ぶ物は着いた所で消える。通った跡が行き先を残し、兄弟の箱から同じ親へ着いた運ぶ物が重ならないため
416
441
  for (const time of timeline.carriers) {
417
442
  const e = layout.edges.find((x) => x.step === time.step && x.event === time.event);
418
- if (e) L.top.push(carrier(e, time, ctx));
443
+ if (e) L.top.push(carrier(e, treeLayout ? { ...time, start: time.depart, end: time.arrive + MOTION.fade } : time, ctx));
419
444
  }
420
445
  const content = Object.values(L)
421
446
  .map((parts) => parts.join(""))
@@ -471,6 +496,16 @@ function focusParts(layout: Layout, diagram: Diagram, step: number): Rect[] {
471
496
  rects.push({ x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) });
472
497
  }
473
498
  rects.push(...layout.labels.filter((l) => l.step === step), ...layout.actions.filter((a) => a.step === step));
499
+ // 木の図は、その段で現れる木の箱と木の線と、線の両端の木の箱を見る (#3233)
500
+ if (isTreeLayout(layout)) {
501
+ const ends = new Set((diagram.steps[step]?.events ?? []).flatMap((e) => (e.type === "edge" ? [e.from, e.to] : [])));
502
+ rects.push(...layout.nodes.filter((n) => n.step === step || ends.has(n.id)));
503
+ for (const l of layout.links.filter((x) => x.step === step)) {
504
+ const xs = l.points.map((p) => p[0]);
505
+ const ys = l.points.map((p) => p[1]);
506
+ rects.push({ x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) });
507
+ }
508
+ }
474
509
  for (const event of diagram.steps[step]?.events ?? []) {
475
510
  const ids = event.type === "edge" ? [event.from, event.to] : event.type === "action" || event.type === "swap" ? [event.box] : [];
476
511
  for (const id of ids) {
@@ -582,6 +617,7 @@ function followView(layout: Layout, timeline: Timeline, diagram: Diagram, m: Mot
582
617
  const shapes = [
583
618
  ...layout.regions.map((r) => `<rect class="dg-mm-band" style="${cs(r.color)}" x="${mx + r.x * k}" y="${my + r.y * k}" width="${r.w * k}" height="${r.h * k}" rx="3"/>`),
584
619
  ...layout.boxes.map((b) => `<rect class="dg-mm-card" style="${cs(b.color)}" x="${mx + b.x * k}" y="${my + b.y * k}" width="${b.w * k}" height="${b.h * k}" rx="1.5"/>`),
620
+ ...(isTreeLayout(layout) ? layout.nodes : []).map((n) => `<rect class="dg-mm-card" style="${cs(n.color)}" x="${mx + n.x * k}" y="${my + n.y * k}" width="${n.w * k}" height="${n.h * k}" rx="1.5"/>`),
585
621
  ].join("");
586
622
  const vp = m.move(cam.map(([t, cx, cy, , e]) => [t, mx + (cx - vw / 2) * k, my + (cy - vh / 2) * k, 1, e]));
587
623
  return {
@@ -634,7 +670,9 @@ export function renderDiagram(input: unknown, options: RenderOptions = {}): Rend
634
670
  ? layoutGit(diagram)
635
671
  : diagram.kind === "time"
636
672
  ? layoutTime(diagram, lang)
637
- : layoutArchitecture(diagram);
673
+ : diagram.kind === "tree"
674
+ ? layoutTree(diagram)
675
+ : layoutArchitecture(diagram);
638
676
  return renderLayout(diagram, layout, buildTimeline(diagram, options.still === true), options);
639
677
  }
640
678
 
@@ -0,0 +1,164 @@
1
+ /**
2
+ * 木の図 (#3233) を描く部品。見た目の元は step 2 で本人が選んだ「根を上」の試作 (`.context/propose/merkle-look/`)。
3
+ *
4
+ * 木の箱は書いた段で、親から子への木の線を引き終えた時に弾んで出る。木の線は親を書いた段で引き、最後まで残す。
5
+ * 値を持つ葉の下の名札の札は、葉より前の最初の段から出しておき、葉が出た時に葉と札を点線で結ぶ。
6
+ * 木の線を走る運ぶ物は着いた所で消え、通った木の線を運ぶ物の色で最後まで残す (`data-tree-trail`)。
7
+ * 木の線を運ぶ物が初めて通った段から後は、それまでに運ぶ物を送るか受けた木の箱だけを濃く出し、ほかの木の箱と札と木の線を薄く出す。
8
+ * 線の両端になった木の箱は、その段の間だけ縁に色を付ける。
9
+ */
10
+ import type { TreeLayout } from "../layout/tree";
11
+ import { EASE, LOOK, MOTION, TYPE } from "../look/values";
12
+ import type { Diagram } from "../schema";
13
+ import type { EdgeTime, Timeline } from "../timeline";
14
+ import type { Frame } from "./motion";
15
+ import { ALWAYS } from "./ink";
16
+ import { activeKf, arrowHead, type Ctx, cs, esc, glyph, pathOf, write } from "./parts";
17
+
18
+ const r1 = (v: number): number => Math.round(v * 100) / 100;
19
+
20
+ export function drawTree(layout: TreeLayout, diagram: Diagram, timeline: Timeline, ctx: Ctx): { links: string; trails: string; nodes: string } {
21
+ const { m } = ctx;
22
+ const T = LOOK.tree;
23
+ const B = LOOK.box;
24
+ const timeOf = (step: number, event: number): EdgeTime | undefined => timeline.edges.find((t) => t.step === step && t.event === event);
25
+
26
+ // 木の箱ごとの、線の両端になる段と、運ぶ物を初めて送るか受けた段
27
+ const active = new Map<string, Set<number>>();
28
+ const touched = new Map<string, number>();
29
+ diagram.steps.forEach((step, s) => {
30
+ for (const e of step.events) {
31
+ if (e.type !== "edge") continue;
32
+ for (const id of [e.from, e.to]) {
33
+ active.set(id, (active.get(id) ?? new Set()).add(s));
34
+ if (e.carry.kind !== "none" && !touched.has(id)) touched.set(id, s);
35
+ }
36
+ }
37
+ });
38
+ const carries = (step: number, event: number): boolean => {
39
+ const e = diagram.steps[step]?.events[event];
40
+ return e?.type === "edge" && e.carry.kind !== "none";
41
+ };
42
+ const fadeStep = layout.runs.filter((run) => carries(run.step, run.event)).reduce<number | undefined>((s, run) => (s === undefined ? run.step : Math.min(s, run.step)), undefined);
43
+ const fadeAt = fadeStep === undefined ? undefined : timeline.steps[fadeStep]?.start;
44
+
45
+ /** 木の箱 `id` の薄くなる動き。薄くしない箱は `undefined` */
46
+ const fadeOf = (id: string): string | undefined => {
47
+ if (fadeStep === undefined || fadeAt === undefined) return undefined;
48
+ const t = touched.get(id);
49
+ if (t !== undefined && t <= fadeStep) return undefined;
50
+ const back = t === undefined ? undefined : timeline.steps[t]?.start;
51
+ const frames: Frame[] = [
52
+ [0, { opacity: 1 }],
53
+ [fadeAt, { opacity: 1 }, EASE.inOut],
54
+ [fadeAt + MOTION.fade, { opacity: T.faint }],
55
+ ];
56
+ if (back !== undefined) frames.push([back, { opacity: T.faint }, EASE.inOut], [back + MOTION.fade, { opacity: 1 }]);
57
+ frames.push([m.last, { opacity: back === undefined ? T.faint : 1 }, EASE.inOut], [m.total, { opacity: 1 }]);
58
+ return m.kf(frames);
59
+ };
60
+ const faded = (id: string, markup: string, attrs = ""): string => {
61
+ const fade = fadeOf(id);
62
+ return fade ? `<g class="dg-a"${attrs} style="${fade}">${markup}</g>` : attrs === "" ? markup : `<g${attrs}>${markup}</g>`;
63
+ };
64
+
65
+ const drawnAt = new Map(layout.nodes.map((n) => [n.id, timeOf(n.step, n.event)?.drawn ?? 0]));
66
+
67
+ // 木の線と、葉と札を結ぶ点線。木の線は親を書いた段で引き始め、引き終えた後も残す
68
+ const links = layout.links
69
+ .map((l) => {
70
+ const time = timeOf(l.step, l.event);
71
+ if (!time) return "";
72
+ ctx.traces.push({ from: l.from, to: l.to, points: l.points, shown: [[time.start, Number.POSITIVE_INFINITY]] });
73
+ const kf = m.kf([
74
+ [0, { opacity: 0, "stroke-dashoffset": 1 }],
75
+ [time.start, { opacity: 0, "stroke-dashoffset": 1 }, EASE.inOut],
76
+ [time.start + 0.05, { opacity: 1 }],
77
+ [time.drawn, { "stroke-dashoffset": 0 }],
78
+ [m.last, { opacity: 1, "stroke-dashoffset": 0 }, EASE.inOut],
79
+ [m.total, { opacity: 0, "stroke-dashoffset": 0 }],
80
+ ]);
81
+ return faded(l.from, `<path class="dg-tree-l dg-a" data-tree-link="${esc(l.from)}" pathLength="1" d="${pathOf(l.points)}" style="${kf}"/>`);
82
+ })
83
+ .join("");
84
+ const ties = layout.nodes
85
+ .flatMap((n) => {
86
+ if (!n.card) return [];
87
+ const at = drawnAt.get(n.id) ?? 0;
88
+ const d = `M ${r1(n.cx)} ${r1(n.y + n.h + LOOK.edge.inset)} V ${r1(n.card.y - LOOK.edge.inset)}`;
89
+ return [faded(n.id, `<path class="dg-tree-con dg-a" d="${d}" style="${m.vis(at)}"/>`)];
90
+ })
91
+ .join("");
92
+
93
+ // 木の線を運ぶ物が通った跡。運ぶ物が走るのに合わせて引き、最後まで残す。同じ木の線は最初に通った段の跡だけを描く
94
+ const traced = new Set<string>();
95
+ const trails = layout.runs
96
+ .flatMap((run) => {
97
+ const e = layout.edges.find((x) => x.step === run.step && x.event === run.event);
98
+ if (!e || traced.has(run.link)) return [];
99
+ const carried = timeline.carriers.find((c) => c.step === run.step && c.event === run.event);
100
+ const time = timeOf(run.step, run.event);
101
+ const a = carried?.depart ?? time?.start;
102
+ const b = carried?.arrive ?? time?.drawn;
103
+ if (a === undefined || b === undefined) return [];
104
+ traced.add(run.link);
105
+ const kf = m.kf([
106
+ [0, { opacity: 0, "stroke-dashoffset": 1 }],
107
+ [a, { opacity: 0, "stroke-dashoffset": 1 }, EASE.inOut],
108
+ [a + 0.05, { opacity: 1 }],
109
+ [b, { "stroke-dashoffset": 0 }],
110
+ [m.last, { opacity: 1, "stroke-dashoffset": 0 }, EASE.inOut],
111
+ [m.total, { opacity: 0, "stroke-dashoffset": 0 }],
112
+ ]);
113
+ const d = pathOf(e.points);
114
+ return [
115
+ `<g style="${cs(e.color)}"><path class="dg-tree-tr dg-a" data-tree-trail="${esc(run.link)}" pathLength="1" d="${d}" style="${kf}"/><path class="dg-tree-h dg-a" d="${arrowHead(e.points)}" style="${m.vis(b)}"/></g>`,
116
+ ];
117
+ })
118
+ .join("");
119
+
120
+ // 葉の下の名札の札。最初の段から出しておく
121
+ const cards = layout.nodes
122
+ .flatMap((n) => {
123
+ const c = n.card;
124
+ if (!c) return [];
125
+ const gx = c.x + T.card.padX + T.card.icon / 2;
126
+ const cy = c.y + c.h / 2;
127
+ const text = write(ctx.ink, "dg-tree-ct", c.x + T.card.padX + T.card.icon + T.card.gap, cy + LOOK.baseline.label, c.text, TYPE.treeCard, ALWAYS);
128
+ return [
129
+ faded(
130
+ n.id,
131
+ `<rect class="dg-tree-card" x="${r1(c.x)}" y="${r1(c.y)}" width="${r1(c.w)}" height="${c.h}" rx="${T.card.radius}"/>${glyph("doc", gx, cy, T.card.glyph, "dg-tree-cg")}${text}`,
132
+ ` data-tree-card="${esc(n.id)}"`,
133
+ ),
134
+ ];
135
+ })
136
+ .join("");
137
+
138
+ // 木の箱。親から子への線を引き終えた時に弾んで出る。根は左に枝の絵柄を持ち、字を絵柄の右に左揃えで並べる
139
+ const nodes = layout.nodes
140
+ .map((n) => {
141
+ const at = drawnAt.get(n.id) ?? 0;
142
+ const on = [...(active.get(n.id) ?? [])].sort((x, y) => x - y);
143
+ const act = on.length > 0 ? activeKf(ctx, on) : undefined;
144
+ const radius = n.root ? T.root.radius : T.radius;
145
+ const rect = (cls: string, extra = ""): string => `<rect class="${cls}" x="${r1(n.x)}" y="${r1(n.y)}" width="${r1(n.w)}" height="${n.h}" rx="${radius}"${extra}/>`;
146
+ const frame = `${act ? `<g class="dg-a" style="${act}">${rect("dg-halo")}</g>` : ""}${rect("dg-st", ` ${ctx.sh}`)}${act ? `<g class="dg-a" style="${act}">${rect("dg-on")}</g>` : ""}`;
147
+ const ix = n.x + T.root.iconX + B.icon / 2;
148
+ const mark = n.root ? `<rect class="dg-ic" x="${r1(ix - B.icon / 2)}" y="${r1(n.cy - B.icon / 2)}" width="${B.icon}" height="${B.icon}" rx="${B.iconRadius}"/>${glyph("tree", ix, n.cy, B.iconScale)}` : "";
149
+ const shown: [number, number][] = [[at, Number.POSITIVE_INFINITY]];
150
+ const texts = n.lines
151
+ .map((line, k) => {
152
+ const style = n.styles[k] ?? TYPE.boxName;
153
+ const cls = style === TYPE.treeHash ? "dg-tree-hash" : style === TYPE.treeName ? "dg-tree-name" : style === TYPE.rootHash ? "dg-tree-rh" : style === TYPE.rootName ? "dg-tree-rn" : "dg-tree-one";
154
+ const baseline = n.baselines[k] ?? n.cy;
155
+ return n.root ? write(ctx.ink, cls, n.x + T.root.textX, baseline, line, style, shown) : write(ctx.ink, cls, n.cx, baseline, line, style, shown, "middle");
156
+ })
157
+ .join("");
158
+ const inner = faded(n.id, `${frame}${mark}${texts}`, ` data-tree-node="${esc(n.id)}"${n.root ? ` data-tree-root="${esc(n.id)}"` : ""}`);
159
+ return `<g class="dg-popc dg-a" style="${cs(n.color)};${m.pop(at)}">${inner}</g>`;
160
+ })
161
+ .join("");
162
+
163
+ return { links: links + ties, trails, nodes: cards + nodes };
164
+ }
package/src/schema.ts CHANGED
@@ -53,7 +53,9 @@ export type DiagramEvent =
53
53
  | { type: "branch"; branch: string; from: string }
54
54
  | { type: "now"; to: number }
55
55
  | TimeMarkEvent
56
- | TimeSpanEvent;
56
+ | TimeSpanEvent
57
+ | TreeLeaf
58
+ | TreeNode;
57
59
 
58
60
  /** 時間軸の図 (#3165) の、印の列 `row` の `from` から `to` の目盛りの印の色を変える出来事 */
59
61
  export interface TimeMarkEvent {
@@ -133,6 +135,23 @@ export interface GitCommit {
133
135
  note?: string;
134
136
  }
135
137
 
138
+ /**
139
+ * 木の図 (#3233) の葉を出す出来事。書いた段で葉の箱が現れる。`hash` を書くと箱に値を出し、名札を葉の下の札に出す
140
+ */
141
+ export interface TreeLeaf {
142
+ type: "leaf";
143
+ id: string;
144
+ hash?: string;
145
+ }
146
+
147
+ /** 木の図の、1 つ以上の子から親を組む出来事。書いた段で親の箱と、子から親への木の線が現れる */
148
+ export interface TreeNode {
149
+ type: "node";
150
+ id: string;
151
+ children: string[];
152
+ hash?: string;
153
+ }
154
+
136
155
  /** 枝分かれの図の枝。上から宣言した順に帯を並べる */
137
156
  export interface GitBranch {
138
157
  id: string;
@@ -163,7 +182,7 @@ export interface Step {
163
182
 
164
183
  export interface Diagram {
165
184
  version: number;
166
- kind: "sequence" | "architecture" | "state" | "git" | "time";
185
+ kind: "sequence" | "architecture" | "state" | "git" | "time" | "tree";
167
186
  title: string;
168
187
  view?: ViewMode;
169
188
  regions?: Region[];
@@ -190,7 +209,7 @@ export interface CheckOptions {
190
209
  }
191
210
 
192
211
  /** 段の中で起きることの種類。schema の event の `discriminator` が見る `type` の値 */
193
- const EVENT_TYPES = ["edge", "action", "swap", "strip", "commit", "branch", "now", "mark", "span"] as const satisfies readonly DiagramEvent["type"][];
212
+ const EVENT_TYPES = ["edge", "action", "swap", "strip", "commit", "branch", "now", "mark", "span", "leaf", "node"] as const satisfies readonly DiagramEvent["type"][];
194
213
 
195
214
  /**
196
215
  * その種類の図に書けない根の欄を書いた時の決まりの場所 (#3164)。根の欄に `not: {}` を置く決まり (`absent`) を指し、
@@ -217,6 +236,10 @@ const GIT_EVENTS = ["commit", "branch"] as const satisfies readonly DiagramEvent
217
236
  const TIME_EVENT = /\/events\/items\/not$/u;
218
237
  /** 時間軸の図だけが書ける出来事 */
219
238
  const TIME_EVENTS = ["now", "mark", "span"] as const satisfies readonly DiagramEvent["type"][];
239
+ /** 木の図でない図に、木の図だけの出来事を書いた時の決まりの場所 (#3233)。出来事の `allOf` の中に `not` を置く */
240
+ const TREE_EVENT = /\/events\/items\/allOf\/0\/not$/u;
241
+ /** 木の図だけが書ける出来事 */
242
+ const TREE_EVENTS = ["leaf", "node"] as const satisfies readonly DiagramEvent["type"][];
220
243
  /** 時間軸の図の目盛りの長さの決まり (`^[0-9]+(\.[0-9]+)?(<単位>|<単位>)$`)。書ける単位を読む */
221
244
  const DURATION = /^\^\[0-9\]\+\(\\\.\[0-9\]\+\)\?\(([a-z|]+)\)\$$/u;
222
245
  /** 割合の決まり。百分率の `%` を持つ */
@@ -263,6 +286,7 @@ function toFieldError(error: ErrorObject, errors: readonly ErrorObject[], m: Fie
263
286
  if (RESERVED_ID.test(error.schemaPath)) return { pointer: at, message: m.reserved(STATE_ENDS) };
264
287
  if (GIT_EVENT.test(error.schemaPath)) return { pointer: at, message: m.kindOnly(GIT_EVENTS, "git") };
265
288
  if (TIME_EVENT.test(error.schemaPath)) return { pointer: `${at}/type`, message: m.kindOnly(TIME_EVENTS, "time") };
289
+ if (TREE_EVENT.test(error.schemaPath)) return { pointer: `${at}/type`, message: m.kindOnly(TREE_EVENTS, "tree") };
266
290
  const last = at.slice(at.lastIndexOf("/") + 1);
267
291
  if (error.schemaPath === ABSENT) return { pointer: at, message: m.not({ field: last, kind: ABSENT_KINDS[last] ?? last }) };
268
292
  const allowed = NOT_ALLOWED[last];