@cardenelabs/dragon 0.39.0 → 0.41.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.
Files changed (44) hide show
  1. package/README.md +39 -1
  2. package/dist/cli.cjs +1921 -429
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +1926 -434
  5. package/dist/cli.js.map +1 -1
  6. package/dist/export.cjs +1718 -353
  7. package/dist/export.cjs.map +1 -1
  8. package/dist/export.d.cts +1 -1
  9. package/dist/export.d.ts +1 -1
  10. package/dist/export.js +1723 -358
  11. package/dist/export.js.map +1 -1
  12. package/dist/index.cjs +1835 -342
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +5 -15
  15. package/dist/index.d.ts +5 -15
  16. package/dist/index.js +1836 -342
  17. package/dist/index.js.map +1 -1
  18. package/dist/{ink-Cg-v6XSG.d.cts → ink-B_7OXxtb.d.cts} +27 -2
  19. package/dist/{ink-Cg-v6XSG.d.ts → ink-B_7OXxtb.d.ts} +27 -2
  20. package/dist/node.cjs +2946 -0
  21. package/dist/node.cjs.map +1 -0
  22. package/dist/node.d.cts +9 -0
  23. package/dist/node.d.ts +9 -0
  24. package/dist/node.js +2944 -0
  25. package/dist/node.js.map +1 -0
  26. package/dist/player.global.js +2 -2
  27. package/package.json +11 -1
  28. package/src/field-messages.ts +8 -0
  29. package/src/index.ts +5 -2
  30. package/src/layout/git.ts +728 -0
  31. package/src/look/values.ts +40 -1
  32. package/src/messages.ts +47 -4
  33. package/src/node.ts +23 -0
  34. package/src/parser.ts +142 -7
  35. package/src/printer.ts +16 -4
  36. package/src/render/git.ts +161 -0
  37. package/src/render/parts.ts +1 -1
  38. package/src/render/svg.ts +26 -1
  39. package/src/schema.ts +47 -13
  40. package/src/schemas/diagram.schema.json +75 -8
  41. package/src/schemas/validate-diagram.js +1 -1
  42. package/src/timeline.ts +18 -3
  43. package/src/version.ts +1 -20
  44. package/src/words.ts +19 -3
@@ -76,6 +76,10 @@ export const TYPE = {
76
76
  stepBody: text(13.5, 500),
77
77
  stepNo: text(13, 700, "mono"),
78
78
  button: text(14, 700),
79
+ /** 枝分かれの図 (#3164) の、丸の中の commit の名札と、丸の外に添える hash と一言 */
80
+ gitId: text(11, 700),
81
+ gitHash: text(10.5, 600, "mono"),
82
+ gitNote: text(10.5, 650),
79
83
  } as const;
80
84
 
81
85
  /** 置き場所と部品の大きさ。単位は図の座標 (字が原寸の時の px)。 */
@@ -121,6 +125,41 @@ export const LOOK = {
121
125
  done: { r: 6.5, inset: 13 },
122
126
  pastLabel: 0.85,
123
127
  },
128
+ /**
129
+ * 枝分かれの図 (#3164)。見本帳の試作 (`scenes/git.js`) の寸法を写す。
130
+ * commit は列ごとに `pitch` ずつ右へ並べ、一番上でない帯の commit は列の半分だけ右へずらす。`x0` は最初の列の真ん中の x の下限、
131
+ * `textGap` は隣の列の hash と一言の間に空ける最小の隙間。`r` は丸の半径、`orphan` はどの札からも辿れなくなった commit の点線の丸の半径。
132
+ * `topLine` と `line` は帯の上端から丸を並べる線まで (一番上の帯と、それより下の帯)、`topBelow` と `below` は線から帯の下端まで。
133
+ * `bare` は線の名前を下に置かない帯の、線から帯の下端まで。
134
+ * hash と一言は一番上の帯では丸の上に、ほかの帯では丸の下に置き、`above` と `under` は丸の真ん中から丸に近い行の基準線まで、`lineStep` は行の間。
135
+ * 札は丸の上に段を重ねて置き、`tagTop` と `tag` は丸の真ん中から 1 段目の札の真ん中まで (一番上の帯と、ほかの帯)、`row` は札の段の間。
136
+ * 札の段が 2 段より多い commit がある帯は、多い段の分だけ線を下げる。
137
+ * `turn` は枝へ分かれる線と枝から入る線が曲がり終えて横へ進むまでの長さ、`samples` は曲がりを区切る点の数、`boxGap` は commit の並びと箱の間。
138
+ * `labelUnder` はほかの帯で、丸の真ん中から線の名前の札の上端まで。`colors` は帯の色を上から配る順
139
+ */
140
+ git: {
141
+ x0: 120,
142
+ pitch: 90,
143
+ textGap: 12,
144
+ r: 12,
145
+ orphan: 13.5,
146
+ topLine: 120,
147
+ line: 90,
148
+ topBelow: 30,
149
+ below: 82,
150
+ bare: 62,
151
+ above: 18,
152
+ under: 27,
153
+ lineStep: 13,
154
+ tagTop: 58,
155
+ tag: 30,
156
+ row: 22,
157
+ turn: 60,
158
+ samples: 12,
159
+ boxGap: 24,
160
+ labelUnder: 50,
161
+ colors: ["blue", "violet", "green", "amber", "rose"],
162
+ },
124
163
  /** `bend` は線の曲がりを丸める半径 (#3171) */
125
164
  edge: { inset: 3, arrow: 6, arrowHalf: 3.5, parallel: 5, ghostDash: 5, flowDash: 9, bend: 12 },
126
165
  /** `touch` は線の名前と、同じ時刻に見えている段の番号の丸の間に空ける最小の隙間 (#3175) */
@@ -141,7 +180,7 @@ export const LOOK = {
141
180
  * `trail` は状態遷移図の帯の最後の、通った状態の点 (#3171)。`r` は点の半径、`step` は点の中心どうしの間、`now` は変わった値の欄の名前の横の点の半径と、名前からの離れ
142
181
  */
143
182
  strip: { h: 72, line: 44, pad: 12, icon: 24, titleX: 44, fieldGap: 22, sepInset: 14, tagGap: 6, tagH: 15, tagPadX: 7, nameY: 22, valueY: 43, trail: { r: 5.4, step: 16 }, now: { r: 3, gap: 7 } },
144
- stroke: { mark: 1.6, slot: 1.2, hair: 1, edge: 1.7, edgeOn: 2.25, arrow: 1.5, flow: 1.3, halo: 7, on: 1.75, glyph: 2, lifeline: 1.2, envelope: 1.5, badgeRing: 1.5, path: 1.6, end: 1.6, done: 1.2, trail: 1.2 },
183
+ stroke: { git: 2.25, gitOrphan: 1.5, mark: 1.6, slot: 1.2, hair: 1, edge: 1.7, edgeOn: 2.25, arrow: 1.5, flow: 1.3, halo: 7, on: 1.75, glyph: 2, lifeline: 1.2, envelope: 1.5, badgeRing: 1.5, path: 1.6, end: 1.6, done: 1.2, trail: 1.2 },
145
184
  shadow: { near: 0.8, far: 4, nearY: 1, farY: 3 },
146
185
  mini: { w: 168, pad: 8, title: 14, inset: 12, radius: 10 },
147
186
  /**
package/src/messages.ts CHANGED
@@ -65,6 +65,23 @@ export interface Messages {
65
65
  outOfFinish: string;
66
66
  /** 状態遷移図の最初の step より前の線に、属性を書いた */
67
67
  pathNoAttrs: string;
68
+ /** 枝分かれの図だけの行 (`branch` と `commit`) を、別の種類の図に書いた (#3164) */
69
+ gitOnly: (word: string) => string;
70
+ gitNoGroup: string;
71
+ noBranches: string;
72
+ branchShape: string;
73
+ commitShape: string;
74
+ fromShape: string;
75
+ undeclaredBranch: (id: string) => string;
76
+ /** 札を動かす線の送る側が、枝の名札でも HEAD でもない */
77
+ undeclaredRef: (id: string) => string;
78
+ noCommit: (id: string) => string;
79
+ /** 取り込む枝が、まだどの commit も指していない */
80
+ emptyBranch: (id: string) => string;
81
+ mergeSelf: (id: string) => string;
82
+ /** 枝分かれの図で、今いる場所の札の名前 (`name`) を名札にした */
83
+ headReserved: (name: string) => string;
84
+ badHash: string;
68
85
  }
69
86
 
70
87
  const list = (words: readonly string[]): string => words.join(" / ");
@@ -102,8 +119,8 @@ const ja = (): Messages => {
102
119
  sayTwice: "1 つの段に say は 1 つまで。長い本文は say の下に字下げして続ける",
103
120
  codeTwice: "1 つの段に code は 1 行まで",
104
121
  emptyCode: "code の後ろに命令を書く",
105
- declarationInStep: "group と box と strip は最初の step より前に書く",
106
- stepLineBeforeStep: "線と say と code と act と note と set は step の下に書く",
122
+ declarationInStep: "group と box と strip と branch は最初の step より前に書く",
123
+ stepLineBeforeStep: "線と say と code と act と note と set と commit と枝を切る行は step の下に書く",
107
124
  nestedGroup: "group の中に group は書けない。先に end で閉じる",
108
125
  strayEnd: "end の前に、閉じる group が無い",
109
126
  endTakesNothing: "end の後ろには何も書かない",
@@ -136,6 +153,19 @@ const ja = (): Messages => {
136
153
  intoStart: "start へ入る線は書けない。start は始まりの印で、線は start から出る",
137
154
  outOfFinish: "finish から出る線は書けない。finish は終わりの印で、線は finish へ入る",
138
155
  pathNoAttrs: "最初の step より前の線は今回は通らない道なので、属性 (carry と tag と side) を書けない",
156
+ gitOnly: (word) => `${word} の行は git (枝分かれの図) でだけ書ける`,
157
+ gitNoGroup: "git (枝分かれの図) には group を書けない。枝は branch の行で宣言する",
158
+ noBranches: "branch の行で枝を 1 つ以上宣言する",
159
+ branchShape: "branch は branch <名札> [note: <添え書き>] の形で書く",
160
+ commitShape: "commit は commit <名札> on <枝> [hash: <hash>, note: <一言>] の形で書く。当て直しは copy <commit> を、取り込みは merge <枝> を on <枝> の後ろに書く",
161
+ fromShape: "枝を切る行は <枝> from <commit> の形で書く",
162
+ undeclaredBranch: (id) => `${id} という枝は宣言していない`,
163
+ undeclaredRef: (id) => `${id} という枝は宣言していない。札を動かす線は枝の名札か HEAD から引く`,
164
+ noCommit: (id) => `${id} という commit はまだ積んでいない`,
165
+ emptyBranch: (id) => `${id} の枝はまだどの commit も指していないので取り込めない`,
166
+ mergeSelf: (id) => `${id} は積む枝なので、取り込む枝にできない`,
167
+ headReserved: (name) => `${name} は枝分かれの図で今いる場所の札の名前で、名札に使えない`,
168
+ badHash: "hash は 0 から 9 と a から f の字で 4 から 40 字にする",
139
169
  };
140
170
  };
141
171
 
@@ -172,8 +202,8 @@ const en = (): Messages => {
172
202
  sayTwice: "A step takes one say. Continue a long body on indented lines below it",
173
203
  codeTwice: "A step takes at most one code line",
174
204
  emptyCode: "Write the command after code",
175
- declarationInStep: "Write group, box and strip before the first step",
176
- stepLineBeforeStep: "Write lines, say, code, act, note and set under a step",
205
+ declarationInStep: "Write group, box, strip and branch before the first step",
206
+ stepLineBeforeStep: "Write lines, say, code, act, note, set, commit and branch cuts under a step",
177
207
  nestedGroup: "A group cannot hold another group. Close it with end first",
178
208
  strayEnd: "There is no group for this end to close",
179
209
  endTakesNothing: "Write nothing after end",
@@ -206,6 +236,19 @@ const en = (): Messages => {
206
236
  intoStart: "A line cannot go into start. start is the start mark, and lines leave it",
207
237
  outOfFinish: "A line cannot leave finish. finish is the end mark, and lines go into it",
208
238
  pathNoAttrs: "A line before the first step is a path not taken, so it takes no attributes (carry, tag, side)",
239
+ gitOnly: (word) => `${word} lines can be written only in git diagrams`,
240
+ gitNoGroup: "A git diagram takes no group. Declare branches with branch lines",
241
+ noBranches: "Declare at least one branch with a branch line",
242
+ branchShape: "Write a branch as branch <id> [note: <note>]",
243
+ commitShape: "Write a commit as commit <id> on <branch> [hash: <hash>, note: <note>]. For a replayed commit add copy <commit>, and for a merge commit add merge <branch>, after on <branch>",
244
+ fromShape: "Write a branch cut as <branch> from <commit>",
245
+ undeclaredBranch: (id) => `No branch named ${id} is declared`,
246
+ undeclaredRef: (id) => `No branch named ${id} is declared. A line that moves a ref starts from a branch id or HEAD`,
247
+ noCommit: (id) => `No commit named ${id} has been made yet`,
248
+ emptyBranch: (id) => `Branch ${id} does not point at any commit yet, so it cannot be merged`,
249
+ mergeSelf: (id) => `${id} is the branch being committed to, so it cannot be the branch merged in`,
250
+ headReserved: (name) => `${name} names where you are in a git diagram and cannot be an id`,
251
+ badHash: "Write a hash as 4 to 40 characters of 0-9 and a-f",
209
252
  };
210
253
  };
211
254
 
package/src/node.ts ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Node でだけ動く部品の入口 (#3206)。
3
+ *
4
+ * 原本の file を読み書きする部品は、頁で描く入口 (`index.ts`) に置かない。
5
+ * 頁を束ねる道具 (Next.js の Turbopack など) は、呼ぶかどうかに関わらず入口の file の読み込みを全て解くため、
6
+ * 頁の入口に Node の組み込みの module を読む部品が 1 つでも在ると、ブラウザ向けの build が止まる。
7
+ */
8
+ import { readFile } from "node:fs/promises";
9
+ import { FORMAT_VERSION, readDiagram } from "./version";
10
+
11
+ export interface Migrated {
12
+ changed: boolean;
13
+ from: number;
14
+ to: number;
15
+ }
16
+
17
+ /** 原本の file を今の版へ移す。今の版の file には触れない。 */
18
+ export async function migrateFile(path: string): Promise<Migrated> {
19
+ const input: unknown = JSON.parse(await readFile(path, "utf8"));
20
+ const read = readDiagram(input);
21
+ if (!read.ok) throw new Error(`${path} を移せない: ${read.errors.map((error) => `${error.pointer} ${error.message}`).join(" / ")}`);
22
+ return { changed: false, from: read.diagram.version, to: FORMAT_VERSION };
23
+ }
package/src/parser.ts CHANGED
@@ -26,14 +26,34 @@
26
26
  * 最初の `step` より前に書いた線は、移れるが段で通るとは限らない道 (`state.paths`) になり、属性を持たない (#3163)。
27
27
  * 状態遷移図の `start` と `finish` は箱の名札に使えない。時系列図と構成図では宣言して使う普通の名札のまま。
28
28
  *
29
+ * 枝分かれの図 (`git`、#3164) は、最初の `step` より前に `branch <名札> [note: <添え書き>]` で枝を上から順に宣言し、
30
+ * 段の中に `commit <名札> on <枝> [hash: <hash>, note: <一言>]` で commit を積み、`<枝> from <commit>` で枝を切る。
31
+ * 当て直しは `on <枝>` の後ろに `copy <commit>` を、merge commit は `merge <枝>` を続ける。
32
+ * 線の行は札を動かす行になり、送る側に枝の名札か `HEAD`、受ける側に積んだ commit を書く。運ぶ物は書かなければ送る側の名前の札。
33
+ * 枝分かれの図では `HEAD` を名札に使えず、区画 (`group`) は書けない。`branch` と `commit` の行は枝分かれの図でだけ書ける。
34
+ *
29
35
  * 行の頭の語と同じ綴りの名札 (`end` や `step`) も書ける。名札の次に `->` が来る行は線と読む。
30
36
  * 誤りは最初の 1 つで止め、行と列を示す。誤りの文の言葉は呼ぶ側が渡す。
31
37
  */
32
38
  import { type Messages, messagesFor, type Shape } from "./messages";
33
- import { type Box, type Carry, type Color, COLORS, type Diagram, type DiagramEvent, type LabelSide, type Region, type StatePath, type Step, type ViewMode } from "./schema";
39
+ import {
40
+ type Box,
41
+ type Carry,
42
+ type Color,
43
+ COLORS,
44
+ type Diagram,
45
+ type DiagramEvent,
46
+ type GitBranch,
47
+ type GitCommit,
48
+ type LabelSide,
49
+ type Region,
50
+ type StatePath,
51
+ type Step,
52
+ type ViewMode,
53
+ } from "./schema";
34
54
  import { columnOf, isBlankOrComment, type SourceLine, tokenize } from "./tokenize";
35
55
  import { FORMAT_VERSION } from "./version";
36
- import { AS, ATTRS, CARRIES, HEADS, KINDS, type NotationLang, OLD_HEADS, SIDES, STATE_ENDS, VIEWS } from "./words";
56
+ import { AS, ATTRS, CARRIES, COPY, FROM, HEAD, HEADS, KINDS, MERGE, type NotationLang, OLD_HEADS, ON, SIDES, STATE_ENDS, VIEWS } from "./words";
37
57
 
38
58
  export interface LineError {
39
59
  line: number;
@@ -65,6 +85,12 @@ const fail = (source: SourceLine, index: number, message: string): NotationError
65
85
  const ID = /^[^\s[\]「」=:]+$/u;
66
86
  /** 線の行。名札、`->`、名札 */
67
87
  const EDGE = /^([^\s:[\]]+?)\s*->\s*([^\s:[\]]+)/du;
88
+ /** 枝分かれの図の `commit` の行。名札と、`on` の枝と、`copy` の当て直しの元と、`merge` の取り込む枝 */
89
+ const COMMIT = new RegExp(`^commit\\s+([^\\s[]+)(?:\\s+${ON}\\s+([^\\s[]+))?(?:\\s+${COPY}\\s+([^\\s[]+))?(?:\\s+${MERGE}\\s+([^\\s[]+))?`, "du");
90
+ /** 枝分かれの図の、枝を切る行。枝と `from` と切る commit */
91
+ const CUT = new RegExp(`^([^\\s[]+)\\s+${FROM}(?:\\s+([^\\s[]+))?\\s*$`, "du");
92
+ /** commit の hash。原本の JSON の hash の形と同じ */
93
+ const HASH = /^[0-9a-f]{4,40}$/u;
68
94
 
69
95
  const isOneOf = <T extends string>(list: readonly T[], word: string): word is T => (list as readonly string[]).includes(word);
70
96
 
@@ -260,6 +286,11 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
260
286
  const view = shown?.value as ViewMode | undefined;
261
287
 
262
288
  const isState = kind === "state";
289
+ const isGit = kind === "git";
290
+ const branches: GitBranch[] = [];
291
+ /** 枝分かれの図で積んだ commit と、枝の札が今指す commit (まだ何も指さない枝は `null`) */
292
+ const commits = new Set<string>();
293
+ const tips = new Map<string, string | null>();
263
294
  const regions: Region[] = [];
264
295
  const boxes: Box[] = [];
265
296
  const paths: StatePath[] = [];
@@ -278,15 +309,32 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
278
309
  if (!boxes.some((box) => box.id === id)) throw fail(source, at, m.undeclaredBox(id));
279
310
  return id;
280
311
  };
281
- /** 線の端。状態遷移図では送る側に `start`、受ける側に `finish` を書ける */
312
+ const branchAt = (source: SourceLine, id: string, at: number): string => {
313
+ if (!tips.has(id)) throw fail(source, at, m.undeclaredBranch(id));
314
+ return id;
315
+ };
316
+ const commitAt = (source: SourceLine, id: string, at: number): string => {
317
+ if (!commits.has(id)) throw fail(source, at, m.noCommit(id));
318
+ return id;
319
+ };
320
+ /**
321
+ * 線の端。状態遷移図では送る側に `start`、受ける側に `finish` を書ける。
322
+ * 枝分かれの図では送る側が枝の名札か `HEAD`、受ける側が積んだ commit
323
+ */
282
324
  const endAt = (source: SourceLine, id: string, at: number, side: "from" | "to"): string => {
325
+ if (isGit) {
326
+ if (side === "to") return commitAt(source, id, at);
327
+ if (id !== HEAD && !tips.has(id)) throw fail(source, at, m.undeclaredRef(id));
328
+ return id;
329
+ }
283
330
  if (!isState || !isOneOf(STATE_ENDS, id)) return boxAt(source, id, at);
284
331
  if ((id === "start") !== (side === "from")) throw fail(source, at, id === "start" ? m.intoStart : m.outOfFinish);
285
332
  return id;
286
333
  };
287
- /** 状態遷移図の箱と区画の名札に、始まりと終わりの印の名前は使えない */
334
+ /** 状態遷移図の箱と区画の名札に、始まりと終わりの印の名前は使えない。枝分かれの図の名札に、今いる場所の札の名前は使えない */
288
335
  const notReserved = (source: SourceLine, id: string, at: number): void => {
289
336
  if (isState && isOneOf(STATE_ENDS, id)) throw fail(source, at, m.reservedId(id));
337
+ if (isGit && id === HEAD) throw fail(source, at, m.headReserved(id));
290
338
  };
291
339
  /** 段の中に書く行の、書き先の段。最初の `step` より前なら誤り */
292
340
  const inStep = (source: SourceLine): Building => {
@@ -321,7 +369,14 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
321
369
  else inStep(source).events.push(readEdge(source, edge));
322
370
  continue;
323
371
  }
324
- const word = text.split(/\s/u)[0] ?? "";
372
+ const [word = "", second] = text.split(/\s+/u);
373
+ // 枝分かれの図で、宣言した枝の名札の次に `from` が来る行は、枝を切る行
374
+ if (isGit && tips.has(word) && second === FROM) {
375
+ const step = inStep(source);
376
+ step.events.push(readCut(source));
377
+ continue;
378
+ }
379
+ if (!isGit && (word === "branch" || word === "commit")) throw fail(source, 0, m.gitOnly(word));
325
380
  if (!isOneOf(HEADS, word)) {
326
381
  const old = oldForm(text, building !== undefined);
327
382
  throw fail(source, 0, old ? m.oldForm(old.word, old.shape) : m.unknownHead(word));
@@ -375,12 +430,21 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
375
430
  case "set":
376
431
  inStep(source).events.push(readSet(source));
377
432
  break;
433
+ case "branch":
434
+ readBranch(source);
435
+ break;
436
+ case "commit": {
437
+ const step = inStep(source);
438
+ step.events.push(readCommit(source));
439
+ break;
440
+ }
378
441
  }
379
442
  }
380
443
  if (group) throw fail(group.source, 0, m.unclosedGroup(group.id));
381
444
  finish();
382
445
 
383
- if (boxes.length === 0) throw fail(head, 0, m.noBoxes);
446
+ if (isGit && branches.length === 0) throw fail(head, 0, m.noBranches);
447
+ if (boxes.length === 0 && !isGit) throw fail(head, 0, m.noBoxes);
384
448
  if (steps.length === 0) throw fail(head, 0, m.noSteps);
385
449
 
386
450
  return {
@@ -394,11 +458,13 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
394
458
  steps,
395
459
  ...(kind === "sequence" ? { sequence: { lifelines: boxes.map((box) => box.id) } } : {}),
396
460
  ...(paths.length > 0 ? { state: { paths } } : {}),
461
+ ...(isGit ? { git: { branches } } : {}),
397
462
  };
398
463
 
399
464
  /** `group` の行。同じ名札をもう一度開いた時は、名前も属性も書かない */
400
465
  function readGroup(source: SourceLine): void {
401
466
  beforeSteps(source);
467
+ if (isGit) throw fail(source, 0, m.gitNoGroup);
402
468
  if (group) throw fail(source, 0, m.nestedGroup);
403
469
  const declared = readDeclared(source, "group", ATTRS.group, m);
404
470
  if (regions.some((region) => region.id === declared.id)) {
@@ -427,6 +493,73 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
427
493
  });
428
494
  }
429
495
 
496
+ /** 枝分かれの図の `branch <名札> [note: <添え書き>]` の行。枝は宣言した順に上から帯に並ぶ */
497
+ function readBranch(source: SourceLine): void {
498
+ beforeSteps(source);
499
+ const declared = readDeclared(source, "branch", ATTRS.branch, m);
500
+ if (declared.name !== undefined) throw fail(source, 0, m.branchShape);
501
+ notReserved(source, declared.id, declared.idAt);
502
+ declare(source, declared.id, declared.idAt);
503
+ const note = declared.attrs.get("note")?.value;
504
+ branches.push({ id: declared.id, ...(note !== undefined ? { note } : {}) });
505
+ tips.set(declared.id, null);
506
+ }
507
+
508
+ /**
509
+ * 枝分かれの図の `commit <名札> on <枝> [copy <commit>] [merge <枝>] [hash: <hash>, note: <一言>]` の行。
510
+ * 積んだ枝の札は新しい commit へ進む。当て直しは枝の札を動かさない
511
+ */
512
+ function readCommit(source: SourceLine): GitCommit {
513
+ const text = source.text;
514
+ const found = COMMIT.exec(text);
515
+ const at = (k: number): number => found?.indices?.[k]?.[0] ?? 0;
516
+ const id = found?.[1];
517
+ const on = found?.[2];
518
+ if (!found || id === undefined || on === undefined) throw fail(source, 0, m.commitShape);
519
+ const rest = skipSpaces(text, found[0].length);
520
+ if (rest < text.length && text[rest] !== "[") throw fail(source, rest, m.commitShape);
521
+ if (!ID.test(id)) throw fail(source, at(1), m.badId(id));
522
+ notReserved(source, id, at(1));
523
+ declare(source, id, at(1));
524
+ const branch = branchAt(source, on, at(2));
525
+ const copy = found[3] === undefined ? undefined : commitAt(source, found[3], at(3));
526
+ const merge = found[4] === undefined ? undefined : mergedAt(source, found[4], at(4), branch);
527
+ const attrs = rest < text.length ? readAttrs(source, rest, ATTRS.commit, m) : new Map<string, Attr>();
528
+ const hash = attrs.get("hash");
529
+ if (hash && !HASH.test(hash.value)) throw fail(source, hash.at, m.badHash);
530
+ const note = attrs.get("note")?.value;
531
+ commits.add(id);
532
+ if (copy === undefined) tips.set(branch, id);
533
+ return {
534
+ type: "commit",
535
+ id,
536
+ branch,
537
+ ...(copy !== undefined ? { copy } : {}),
538
+ ...(merge !== undefined ? { merge } : {}),
539
+ ...(hash ? { hash: hash.value } : {}),
540
+ ...(note !== undefined ? { note } : {}),
541
+ };
542
+ }
543
+
544
+ /** merge commit が取り込む枝。積む枝と別の、もう commit を指している枝 */
545
+ function mergedAt(source: SourceLine, id: string, at: number, into: string): string {
546
+ branchAt(source, id, at);
547
+ if (id === into) throw fail(source, at, m.mergeSelf(id));
548
+ if (tips.get(id) === null) throw fail(source, at, m.emptyBranch(id));
549
+ return id;
550
+ }
551
+
552
+ /** 枝分かれの図の `<枝> from <commit>` の行。枝の札を commit へ置く */
553
+ function readCut(source: SourceLine): DiagramEvent {
554
+ const found = CUT.exec(source.text);
555
+ const branch = found?.[1];
556
+ const from = found?.[2];
557
+ if (!found || branch === undefined || from === undefined) throw fail(source, 0, m.fromShape);
558
+ commitAt(source, from, found.indices?.[2]?.[0] ?? 0);
559
+ tips.set(branch, from);
560
+ return { type: "branch", branch, from };
561
+ }
562
+
430
563
  /** `strip <題>: <欄>, <欄>` の行 */
431
564
  function readStrip(source: SourceLine): void {
432
565
  beforeSteps(source);
@@ -514,9 +647,11 @@ function parseLines(lines: SourceLine[], m: Messages): Diagram {
514
647
  if (carried && !isOneOf(CARRIES, carried.value)) throw fail(source, carried.at, m.badCarry);
515
648
  const side = attrs.get("side");
516
649
  if (side && !isOneOf(SIDES, side.value)) throw fail(source, side.at, m.badSide);
517
- let carry: Carry = { kind: "envelope" };
650
+ // 枝分かれの図の線は札を動かす線で、書かなければ送る側の名前の札を運ぶ
651
+ let carry: Carry = isGit ? { kind: "tag", text: from } : { kind: "envelope" };
518
652
  if (tag) carry = { kind: "tag", text: tag.value };
519
653
  else if (carried) carry = carried.value === "coin" ? { kind: "coin" } : { kind: "none" };
654
+ if (isGit && from !== HEAD) tips.set(from, to);
520
655
  return {
521
656
  type: "edge",
522
657
  from,
package/src/printer.ts CHANGED
@@ -10,8 +10,10 @@
10
10
  * 箱は JSON の並びのまま書き、同じ区画の箱が続く所を 1 つの `group … end` にする。
11
11
  * 区画の箱が飛び飛びの時は同じ `group` を開き直す。区画の並びが箱の現れる順と違う時と、
12
12
  * 箱の無い区画がある時は、先に全ての区画を中の無い `group … end` で宣言してから開き直す。
13
+ * 枝分かれの図 (#3164) は、枝の `branch` の行を箱より前に書き、札を動かす線の運ぶ物が送る側の名前の札なら書かない。
13
14
  */
14
15
  import type { Box, Diagram, DiagramEvent, Region } from "./schema";
16
+ import { COPY, FROM, MERGE, ON } from "./words";
15
17
 
16
18
  const quote = (text: string): string => `"${text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
17
19
  /** 行の終わりか `[` の前に置く名前と文 */
@@ -48,10 +50,12 @@ const declareBox = (b: Box): string =>
48
50
  /** 線の行の両端と名前 */
49
51
  const line = (from: string, to: string, label: string | undefined): string => `${from} -> ${to}${label === undefined ? "" : `: ${name(label)}`}`;
50
52
 
51
- function event(e: DiagramEvent): string {
53
+ /** 段の中の 1 行。`git` は枝分かれの図か。枝分かれの図の線は、送る側の名前の札を書かない時の運ぶ物にする */
54
+ function event(e: DiagramEvent, git: boolean): string {
52
55
  switch (e.type) {
53
56
  case "edge": {
54
- const carry: [string, string][] = e.carry.kind === "tag" ? [["tag", e.carry.text]] : e.carry.kind === "envelope" ? [] : [["carry", e.carry.kind]];
57
+ const plain = git ? e.carry.kind === "tag" && e.carry.text === e.from : e.carry.kind === "envelope";
58
+ const carry: [string, string][] = plain ? [] : e.carry.kind === "tag" ? [["tag", e.carry.text]] : [["carry", e.carry.kind]];
55
59
  return `${line(e.from, e.to, e.label)}${attrs([...carry, ["side", e.labelSide]])}`;
56
60
  }
57
61
  case "action":
@@ -60,6 +64,13 @@ function event(e: DiagramEvent): string {
60
64
  return `note ${e.box}: ${e.text}`;
61
65
  case "strip":
62
66
  return `set ${key(e.field)}${e.value === undefined ? "" : `: ${name(e.value)}`}${attrs([["tag", e.tag]])}`;
67
+ case "commit":
68
+ return `commit ${e.id} ${ON} ${e.branch}${e.copy === undefined ? "" : ` ${COPY} ${e.copy}`}${e.merge === undefined ? "" : ` ${MERGE} ${e.merge}`}${attrs([
69
+ ["hash", e.hash],
70
+ ["note", e.note],
71
+ ])}`;
72
+ case "branch":
73
+ return `${e.branch} ${FROM} ${e.from}`;
63
74
  }
64
75
  }
65
76
 
@@ -97,14 +108,15 @@ function declarations(diagram: Diagram): string[] {
97
108
  }
98
109
 
99
110
  export function printNotation(diagram: Diagram): string {
100
- const blocks = [`${diagram.kind} ${name(diagram.title)}${attrs([["view", diagram.view]])}`, ...declarations(diagram)];
111
+ const branches = (diagram.git?.branches ?? []).map((b) => `branch ${b.id}${attrs([["note", b.note]])}`);
112
+ const blocks = [`${diagram.kind} ${name(diagram.title)}${attrs([["view", diagram.view]])}`, ...(branches.length > 0 ? [branches.join("\n")] : []), ...declarations(diagram)];
101
113
  if (diagram.strip) blocks.push(`strip ${key(diagram.strip.title)}: ${diagram.strip.fields.map(field).join(", ")}`);
102
114
  if (diagram.state) blocks.push(diagram.state.paths.map((p) => line(p.from, p.to, p.label)).join("\n"));
103
115
  for (const step of diagram.steps) {
104
116
  const body = step.body.split("\n");
105
117
  const say = body.length === 1 ? [` say ${step.body}`] : [" say", ...body.map((line) => (line === "" ? "" : ` ${line}`))];
106
118
  blocks.push(
107
- [`step ${step.title}`, ...say, ...(step.code === undefined ? [] : [` code ${step.code}`]), ...step.events.map((e) => ` ${event(e)}`)].join("\n"),
119
+ [`step ${step.title}`, ...say, ...(step.code === undefined ? [] : [` code ${step.code}`]), ...step.events.map((e) => ` ${event(e, diagram.kind === "git")}`)].join("\n"),
108
120
  );
109
121
  }
110
122
  return `${blocks.join("\n\n")}\n`;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * 枝分かれの図 (#3164) を描く部品。見本帳の試作 `docs/design/base/scenes/git.js` の commit と札を写す。
3
+ *
4
+ * commit の丸は、親から引く線を引き終えた時に弾んで出て、hash と一言を丸の外に添える。
5
+ * 親から引く線は引いた後も残し、当て直しの線は点線で出す。どの札からも辿れなくなった commit は、その時に点線の丸を重ねる。
6
+ * 札は枝ごとと HEAD に 1 つずつ置き、出来事のたびに次の置き場へ走らせる。札を動かす線は、その段の間だけ引いて消す。
7
+ * 札はその後も動くので、線を残すと札の去った所を指したまま残る。
8
+ * 札の見た目は運ぶ物の札と同じで、どの札も主役ではないので、時刻の表の運ぶ物とは別に動かす。
9
+ */
10
+ import type { GitLayout, GitMove } from "../layout/git";
11
+ import type { Diagram } from "../schema";
12
+ import { hasWide, textWidth } from "../layout/measure";
13
+ import type { Point, Rect } from "../layout/scene";
14
+ import { EASE, LOOK, MOTION, TYPE } from "../look/values";
15
+ import type { EdgeTime, Span, Timeline } from "../timeline";
16
+ import type { Frame } from "./motion";
17
+ import { type Ctx, carrier, cs, esc, pathOf, write } from "./parts";
18
+
19
+ const r1 = (v: number): number => Math.round(v * 100) / 100;
20
+ const center = (r: Rect): Point => [r.x + r.w / 2, r.y + r.h / 2];
21
+
22
+ /** 札の形。真ん中を (0, 0) に置き、動きで置き場へ運ぶ */
23
+ function tagShape(text: string, sh: string): string {
24
+ const C = LOOK.carrier;
25
+ const ja = hasWide(text);
26
+ const w = textWidth(text, ja ? TYPE.carrierJa : TYPE.carrier) + C.tagPadX * 2;
27
+ return `<rect class="dg-car" x="${r1(-w / 2)}" y="${-C.tagH / 2}" width="${r1(w)}" height="${C.tagH}" rx="${C.tagH / 2}" ${sh}/><text class="dg-car-t${ja ? " dg-car-tj" : ""}" y="${LOOK.baseline.carrier}" text-anchor="middle">${esc(text)}</text>`;
28
+ }
29
+
30
+ export function drawGit(layout: GitLayout, diagram: Diagram, timeline: Timeline, ctx: Ctx): { links: string; lines: string; commits: string; tags: string } {
31
+ const { m } = ctx;
32
+ const G = LOOK.git;
33
+ const timeOf = (step: number, event: number): EdgeTime | undefined => timeline.edges.find((t) => t.step === step && t.event === event);
34
+
35
+ const links = layout.links
36
+ .map((l) => {
37
+ const time = timeOf(l.step, l.event);
38
+ if (!time) return "";
39
+ ctx.traces.push({ from: l.from, to: l.to, points: l.points, shown: [[time.start, Number.POSITIVE_INFINITY]] });
40
+ const d = pathOf(l.points);
41
+ if (l.kind === "copy") return `<g style="${cs(l.color)}"><path class="dg-git-cp dg-a" d="${d}" style="${m.vis(time.start, m.last)}"/></g>`;
42
+ const kf = m.kf([
43
+ [0, { opacity: 0, "stroke-dashoffset": 1 }],
44
+ [time.start, { opacity: 0, "stroke-dashoffset": 1 }, EASE.inOut],
45
+ [time.start + 0.05, { opacity: 1 }],
46
+ [time.drawn, { "stroke-dashoffset": 0 }],
47
+ [m.last, { opacity: 1, "stroke-dashoffset": 0 }, EASE.inOut],
48
+ [m.total, { opacity: 0, "stroke-dashoffset": 0 }],
49
+ ]);
50
+ return `<g style="${cs(l.color)}"><path class="dg-git-l dg-a" pathLength="1" d="${d}" style="${kf}"/></g>`;
51
+ })
52
+ .join("");
53
+
54
+ const commits = layout.commits
55
+ .map((c) => {
56
+ const at = timeOf(c.step, c.event)?.drawn ?? 0;
57
+ const ring = { x: c.cx - c.r, y: c.cy - c.r, w: c.r * 2, h: c.r * 2 };
58
+ ctx.ink.push({ text: c.id, rect: ring, shown: [[at, Number.POSITIVE_INFINITY]], boxed: true });
59
+ const lines = (c.text?.lines ?? [])
60
+ .map((line, k) => {
61
+ const hash = k === 0 && c.hash !== undefined;
62
+ const baseline = c.text?.baselines[k] ?? c.cy;
63
+ return write(ctx.ink, hash ? "dg-git-h" : "dg-git-n", c.cx, baseline, line, hash ? TYPE.gitHash : TYPE.gitNote, [[at, Number.POSITIVE_INFINITY]], "middle");
64
+ })
65
+ .join("");
66
+ const id = `<text class="dg-git-id" x="${r1(c.cx)}" y="${r1(c.cy + LOOK.baseline.badge)}" text-anchor="middle">${esc(c.id)}</text>`;
67
+ const node = `<g class="dg-popc dg-a" style="${m.pop(at)}"><circle class="dg-git-c" cx="${r1(c.cx)}" cy="${r1(c.cy)}" r="${c.r}" ${ctx.sh}/>${id}</g>`;
68
+ const text = lines === "" ? "" : `<g class="dg-a" style="${m.vis(at)}">${lines}</g>`;
69
+ const orphanAt = c.orphan === undefined ? undefined : timeOf(c.orphan, c.orphanEvent ?? 0)?.drawn;
70
+ const orphan =
71
+ orphanAt === undefined
72
+ ? ""
73
+ : `<g class="dg-a" data-orphan="${esc(c.id)}" style="${m.vis(orphanAt, m.last, { f: 0.5 })}"><circle class="dg-git-old" cx="${r1(c.cx)}" cy="${r1(c.cy)}" r="${G.orphan}"/><text class="dg-git-oldl" x="${r1(c.cx)}" y="${r1(c.cy + LOOK.baseline.badge)}" text-anchor="middle">${esc(c.id)}</text></g>`;
74
+ return `<g data-commit="${esc(c.id)}" style="${cs(c.color)}">${node}${text}${orphan}</g>`;
75
+ })
76
+ .join("");
77
+
78
+ const lines = layout.moves
79
+ .flatMap((mv) => {
80
+ const time = timeOf(mv.step, mv.event);
81
+ if (!mv.line || !time) return [];
82
+ const end = (timeline.steps[mv.step] as Span).end;
83
+ ctx.traces.push({ from: mv.ref, to: mv.target ?? mv.ref, points: mv.line, shown: [[time.start, end + 0.4]] });
84
+ const kf = m.kf([
85
+ [0, { opacity: 0, "stroke-dashoffset": 1 }],
86
+ [time.start, { opacity: 0, "stroke-dashoffset": 1 }, EASE.inOut],
87
+ [time.start + 0.05, { opacity: 1 }],
88
+ [time.drawn, { "stroke-dashoffset": 0 }],
89
+ [end, { opacity: 1 }, EASE.inOut],
90
+ [end + 0.4, { opacity: 0 }],
91
+ [m.total, { opacity: 0, "stroke-dashoffset": 0 }],
92
+ ]);
93
+ return [`<g style="${cs(mv.color)}"><path class="dg-e-on dg-a" pathLength="1" d="${pathOf(mv.line)}" style="${kf}"/></g>`];
94
+ })
95
+ .join("");
96
+
97
+ // 線に書いた運ぶ物は、線を走って着いた所で消える。着いた所には枝の札が留まるので、運ぶ物は留めない
98
+ const carried = timeline.carriers
99
+ .flatMap((t) => {
100
+ const mv = layout.moves.find((x) => x.step === t.step && x.event === t.event && x.line);
101
+ const source = diagram.steps[t.step]?.events[t.event];
102
+ if (!mv?.line || source?.type !== "edge") return [];
103
+ const edge = { step: t.step, event: t.event, from: mv.ref, to: mv.target ?? mv.ref, points: mv.line, color: mv.color, carry: source.carry };
104
+ return [carrier(edge, { ...t, start: t.depart, end: t.arrive + MOTION.fade }, ctx)];
105
+ })
106
+ .join("");
107
+ const refs = [...new Set(layout.moves.map((mv) => mv.ref))];
108
+ const tags = refs.map((ref) => tagMotion(ref, layout.moves.filter((mv) => mv.ref === ref), timeOf, ctx)).join("") + carried;
109
+ return { links, lines, commits, tags };
110
+ }
111
+
112
+ /**
113
+ * 1 つの札の動き。現れる出来事では着いた時に出し、動く出来事では前の置き場から次の置き場へ走らせ、消える出来事では着いた時に消す。
114
+ * 留まっている間の四角を、字の重なりを数える記録に残す
115
+ */
116
+ function tagMotion(ref: string, list: GitMove[], timeOf: (step: number, event: number) => EdgeTime | undefined, ctx: Ctx): string {
117
+ const { m } = ctx;
118
+ const points: [number, number, number][] = [];
119
+ const fades: Frame[] = [[0, { opacity: 0 }]];
120
+ let on = false;
121
+ let rest: { rect: Rect; since: number } | undefined;
122
+ const leave = (t: number): void => {
123
+ if (rest) ctx.ink.push({ text: ref, rect: rest.rect, shown: [[rest.since, t]], boxed: true });
124
+ rest = undefined;
125
+ };
126
+ for (const mv of list) {
127
+ const time = timeOf(mv.step, mv.event);
128
+ if (!time) continue;
129
+ const { start: a, drawn: b } = time;
130
+ const from = mv.from ? center(mv.from) : undefined;
131
+ const to = mv.to ? center(mv.to) : undefined;
132
+ leave(a);
133
+ // 線に運ぶ物を書いた時は、枝の札は走らずに消え、運ぶ物が着いた時に着いた所へ出る
134
+ if (mv.carried && from && to && on) {
135
+ points.push([a + MOTION.fade, from[0], from[1]], [b - MOTION.fade, to[0], to[1]]);
136
+ fades.push([a, { opacity: 1 }, EASE.inOut], [a + MOTION.fade, { opacity: 0 }], [b - MOTION.fade, { opacity: 0 }, EASE.out], [b, { opacity: 1 }]);
137
+ rest = { rect: mv.to as Rect, since: b };
138
+ continue;
139
+ }
140
+ if (from) points.push([a, from[0], from[1]]);
141
+ if (to) points.push([b, to[0], to[1]]);
142
+ if (to && !on) {
143
+ // 前の置き場から走る札は走り出す時に、何も無い所に現れる札は着いた時に出す
144
+ const show = from ? a : b - MOTION.fade;
145
+ fades.push([show, { opacity: 0 }, EASE.out], [show + MOTION.fade, { opacity: 1 }]);
146
+ on = true;
147
+ } else if (!to && on) {
148
+ fades.push([b, { opacity: 1 }, EASE.inOut], [b + MOTION.untilFade, { opacity: 0 }]);
149
+ on = false;
150
+ }
151
+ if (mv.to) rest = { rect: mv.to, since: b };
152
+ }
153
+ leave(Number.POSITIVE_INFINITY);
154
+ if (points.length === 0) return "";
155
+ const first = points[0] as [number, number, number];
156
+ const last = points[points.length - 1] as [number, number, number];
157
+ if (on) fades.push([m.last, { opacity: 1 }, EASE.inOut], [m.total, { opacity: 0 }]);
158
+ else fades.push([m.total, { opacity: 0 }]);
159
+ const style = m.move([[0, first[1], first[2]], ...points, [m.total, last[1], last[2]]], fades);
160
+ return `<g class="dg-a" data-ref="${esc(ref)}" style="${style}">${tagShape(ref, ctx.sh)}</g>`;
161
+ }
@@ -98,7 +98,7 @@ export interface Ctx {
98
98
  * 字を 1 つ描き、字の四角と見えている間を `ink` に記録する (#3175)。`ink` を渡さない字 (寄って追う窓の頭の列) は記録しない。
99
99
  * `anchor` を渡さない字は左端を `x` に置き、`text-anchor` を書かない
100
100
  */
101
- function write(ink: Ink[] | undefined, cls: string, x: number, y: number, text: string, style: TextStyle, shown: Shown[] = ALWAYS, anchor?: "start" | "middle"): string {
101
+ export function write(ink: Ink[] | undefined, cls: string, x: number, y: number, text: string, style: TextStyle, shown: Shown[] = ALWAYS, anchor?: "start" | "middle"): string {
102
102
  ink?.push({ text, rect: textBox(text, x, y, style, anchor), shown });
103
103
  return `<text class="${cls}" x="${r1(x)}" y="${r1(y)}"${anchor ? ` text-anchor="${anchor}"` : ""}>${esc(text)}</text>`;
104
104
  }