@cardenelabs/dragon 0.44.0 → 0.45.2

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 (77) hide show
  1. package/README.md +21 -0
  2. package/dist/cli.cjs +4166 -4063
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +4166 -4063
  5. package/dist/cli.js.map +1 -1
  6. package/dist/export.cjs +4066 -3963
  7. package/dist/export.cjs.map +1 -1
  8. package/dist/export.js +4065 -3964
  9. package/dist/export.js.map +1 -1
  10. package/dist/index.cjs +12297 -12194
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.js +12297 -12194
  13. package/dist/index.js.map +1 -1
  14. package/dist/light/chunk-5OQV42W3.cjs +1172 -0
  15. package/dist/light/chunk-5OQV42W3.cjs.map +1 -0
  16. package/dist/light/chunk-CLS6JVKK.cjs +84 -0
  17. package/dist/light/chunk-CLS6JVKK.cjs.map +1 -0
  18. package/dist/light/chunk-EHTQUCW4.js +1172 -0
  19. package/dist/light/chunk-EHTQUCW4.js.map +1 -0
  20. package/dist/light/chunk-JCEKXALJ.cjs +489 -0
  21. package/dist/light/chunk-JCEKXALJ.cjs.map +1 -0
  22. package/dist/light/chunk-YDKPEKGZ.js +84 -0
  23. package/dist/light/chunk-YDKPEKGZ.js.map +1 -0
  24. package/dist/light/chunk-YEQSLVIN.js +489 -0
  25. package/dist/light/chunk-YEQSLVIN.js.map +1 -0
  26. package/dist/light/git-GESUYKGR.js +637 -0
  27. package/dist/light/git-GESUYKGR.js.map +1 -0
  28. package/dist/light/git-K3KAAAWW.cjs +637 -0
  29. package/dist/light/git-K3KAAAWW.cjs.map +1 -0
  30. package/dist/light/index.cjs +9897 -0
  31. package/dist/light/index.cjs.map +1 -0
  32. package/dist/light/index.d.cts +976 -0
  33. package/dist/light/index.d.ts +976 -0
  34. package/dist/light/index.js +9897 -0
  35. package/dist/light/index.js.map +1 -0
  36. package/dist/light/lineup-2V2U7HZH.js +283 -0
  37. package/dist/light/lineup-2V2U7HZH.js.map +1 -0
  38. package/dist/light/lineup-623J25LU.cjs +283 -0
  39. package/dist/light/lineup-623J25LU.cjs.map +1 -0
  40. package/dist/light/state-OZVCHX7H.cjs +335 -0
  41. package/dist/light/state-OZVCHX7H.cjs.map +1 -0
  42. package/dist/light/state-T4OTVING.js +335 -0
  43. package/dist/light/state-T4OTVING.js.map +1 -0
  44. package/dist/light/time-6WEMD4FQ.js +719 -0
  45. package/dist/light/time-6WEMD4FQ.js.map +1 -0
  46. package/dist/light/time-PQCPVQOE.cjs +719 -0
  47. package/dist/light/time-PQCPVQOE.cjs.map +1 -0
  48. package/dist/light/tree-6D7KI57H.cjs +478 -0
  49. package/dist/light/tree-6D7KI57H.cjs.map +1 -0
  50. package/dist/light/tree-ZJZQI5QT.js +478 -0
  51. package/dist/light/tree-ZJZQI5QT.js.map +1 -0
  52. package/dist/player.global.js +3 -3
  53. package/package.json +14 -2
  54. package/src/api.ts +71 -0
  55. package/src/figure-text.ts +4 -0
  56. package/src/index.ts +6 -69
  57. package/src/kinds/all.ts +16 -0
  58. package/src/kinds/git.ts +3 -0
  59. package/src/kinds/lineup.ts +3 -0
  60. package/src/kinds/registry.ts +46 -0
  61. package/src/kinds/state.ts +2 -0
  62. package/src/kinds/time.ts +3 -0
  63. package/src/kinds/tree.ts +3 -0
  64. package/src/layout/git.ts +0 -1
  65. package/src/layout/lineup.ts +0 -1
  66. package/src/layout/scene.ts +58 -16
  67. package/src/layout/time.ts +0 -1
  68. package/src/layout/tree.ts +0 -1
  69. package/src/light.ts +31 -0
  70. package/src/look/values.ts +1 -1
  71. package/src/player-global.ts +3 -0
  72. package/src/player.ts +1 -1
  73. package/src/render/draw.ts +751 -0
  74. package/src/render/parts.ts +3 -0
  75. package/src/render/svg.ts +4 -725
  76. package/src/render/time.ts +1 -4
  77. package/src/view.ts +1 -1
@@ -0,0 +1,751 @@
1
+ /**
2
+ * 原本の JSON から図を描く本体。置き場所と時刻の表を作り、部品を重なりの順に並べて SVG にする。
3
+ * git、lineup、state、time、tree の部品は登録簿から引くので、読んでいない種類は描けない (`kinds/registry.ts`、#3248)。
4
+ *
5
+ * 動きは全て SVG の中の CSS の keyframes が回す。1 周の長さは `--T`、止める時刻は `--at`、
6
+ * 止めるか流すかは `--play` の変数で外から変えられる (頁に置く `player.ts` がこれを使う)。
7
+ * 色と字は値の表から CSS の変数として 1 度だけ書き、部品はその変数だけを読む。
8
+ * 止め絵を選ぶと (`still`)、最後の段の止め絵に全ての段の線の名前と箱の中の処理を出し、流れ全体を 1 枚で読ませる (#3200)。
9
+ */
10
+ import { FIGURE_TEXT } from "../figure-text";
11
+ import { layoutArchitecture } from "../layout/architecture";
12
+ import type { GitLayout } from "../layout/git";
13
+ import type { LineupLayout } from "../layout/lineup";
14
+ import { textWidth } from "../layout/measure";
15
+ import { type Layout, type Rect, rewrapStrip, type SceneField, type SceneLabel, type SceneStrip } from "../layout/scene";
16
+ import { layoutSequence } from "../layout/sequence";
17
+ import type { TimeLayout } from "../layout/time";
18
+ import type { TreeLayout } from "../layout/tree";
19
+ import { kindParts } from "../kinds/registry";
20
+ import { FONTS } from "../look/fonts";
21
+ import { type ColorKey, type Colors, EASE, FONT_VARS, isColorName, isColorValue, LOOK, MOTION, type Palette, paletteVars, resolvePalette, type TextStyle, type Theme, TYPE } from "../look/values";
22
+ import { readDiagram } from "../version";
23
+ import type { Diagram, ViewMode } from "../schema";
24
+ import { buildTimeline, type LabelTime, type Span, type Timeline } from "../timeline";
25
+ import type { NotationLang } from "../words";
26
+ import {
27
+ action,
28
+ badge,
29
+ band,
30
+ card,
31
+ carrier,
32
+ type Ctx,
33
+ cs,
34
+ doneMark,
35
+ edge,
36
+ endMark,
37
+ esc,
38
+ type FieldChange,
39
+ ghostCard,
40
+ headCard,
41
+ label,
42
+ lifeline,
43
+ linkTo,
44
+ path,
45
+ sansOf,
46
+ side,
47
+ strip,
48
+ type SubChange,
49
+ } from "./parts";
50
+ import { findOverlaps, type Ink, type Overlap, type Trace } from "./ink";
51
+ import { Motion } from "./motion";
52
+
53
+ const isGitLayout = (layout: Layout): layout is GitLayout => layout.kind === "git";
54
+ const isLineupLayout = (layout: Layout): layout is LineupLayout => layout.kind === "lineup";
55
+ const isTimeLayout = (layout: Layout): layout is TimeLayout => layout.kind === "time";
56
+ const isTreeLayout = (layout: Layout): layout is TreeLayout => layout.kind === "tree";
57
+
58
+ export interface RenderOptions {
59
+ /** 色味の名前。書かないか知らない名前なら紙と墨 */
60
+ palette?: string;
61
+ /**
62
+ * `palette` の色味に重ねる色の値 (#3198)。鍵は色味が持つ色の変数の名前 (`bg`、`ink`、`c-green` など) で、値は描く `theme` の色になる。
63
+ * 渡さない色は色味の値のまま残る。色味に無い名前と、色の値として読めない値は、名前を挙げて描かずに断る
64
+ */
65
+ colors?: Colors;
66
+ theme?: Theme;
67
+ /** 描く部品が出す字 (断りの文、全体図の札、読み上げの名前) の言葉。書かなければ日本語 (#3001) */
68
+ lang?: NotationLang;
69
+ /**
70
+ * 最後の段の止め絵に、全ての段の線の名前と箱の中の処理を最後の段と同じ濃さで出す (#3200)。途中の段の止め絵は今の段の名前だけを出す。
71
+ * 箱の下の 1 行に出す処理は、その箱で最後に起きた処理か書き換えの字を出す。違う段の名前が重なっても置き直さず、最後の段の重なり (`overlaps`) に出す
72
+ */
73
+ still?: boolean;
74
+ }
75
+
76
+ export interface Rendered {
77
+ svg: string;
78
+ palette: string;
79
+ theme: Theme;
80
+ /** 書き手が原本で決めた見せ方 */
81
+ view?: ViewMode;
82
+ fonts: { sans: string; mono: string };
83
+ layout: Layout;
84
+ timeline: Timeline;
85
+ diagram: Diagram;
86
+ /** 段ごとの止め絵で、同時に見えている字どうしの重なりと、線が札を持たない字を横切る所 (#3175)。重なりが無ければ空 */
87
+ overlaps: Overlap[];
88
+ }
89
+
90
+ const font = (t: TextStyle): string => `font:${t.weight} ${t.size}px var(--${t.family})`;
91
+ const mix = (pct: number, base = "var(--surf)"): string => `color-mix(in srgb,var(--c) ${pct}%,${base})`;
92
+ const S = LOOK.stroke;
93
+ const X = LOOK.mix;
94
+ /** 状態遷移図で段が終わった線と番号の灰 (#3171) */
95
+ const PAST = `color-mix(in srgb,var(--mute) ${X.past}%,var(--bg))`;
96
+
97
+ /** 部品の見た目。どの値も値の表から読む。 */
98
+ const PART_CSS = [
99
+ ".dg{display:block;width:100%;height:auto;overflow:visible}",
100
+ ".dg .dg-a{animation-duration:var(--T);animation-timing-function:linear;animation-iteration-count:infinite;animation-fill-mode:both;animation-delay:calc(var(--at,0) * -1s);animation-play-state:var(--play,running)}",
101
+ ".dg .dg-popc{transform-box:fill-box;transform-origin:center}",
102
+ ".dg-bg{fill:var(--bg)}",
103
+ ".dg-band{fill:color-mix(in srgb,var(--c) var(--tint),var(--bg));stroke:color-mix(in srgb,var(--c) var(--edge),transparent)}",
104
+ `.dg-bi{fill:${mix(X.regionIcon)};stroke:${mix(X.regionIconEdge, "transparent")}}`,
105
+ `.dg-bz{${font(TYPE.regionName)};fill:var(--ct)}`,
106
+ `.dg-bx{${font(TYPE.regionNote)};fill:var(--mute)}`,
107
+ ".dg-st{fill:var(--surf);stroke:var(--hair)}",
108
+ `.dg-halo{fill:none;stroke:var(--c);stroke-width:${S.halo};stroke-opacity:.16}`,
109
+ `.dg-on{fill:none;stroke:var(--c);stroke-width:${S.on}}`,
110
+ `.dg-ic{fill:${mix(X.icon)}}`,
111
+ `.dg-slot{fill:none;stroke:${mix(X.slot, "transparent")};stroke-width:${S.slot};stroke-dasharray:3 3}`,
112
+ `.dg-gl{fill:none;stroke:var(--c);stroke-width:${S.glyph};stroke-linecap:round;stroke-linejoin:round}`,
113
+ `.dg-sn{${font(TYPE.boxName)};fill:var(--ink)}`,
114
+ `.dg-ss{${font(TYPE.boxSub)};fill:var(--mute)}`,
115
+ `.dg-ss-ok{${font(TYPE.boxSubStrong)};fill:var(--ct)}`,
116
+ `.dg-ss-act{${font(TYPE.boxSubStrong)};fill:var(--ink)}`,
117
+ `.dg-ll{stroke:var(--line);stroke-width:${S.lifeline};stroke-dasharray:3 4}`,
118
+ `.dg-e{fill:none;stroke:var(--line);stroke-width:${S.edge};stroke-linecap:round;stroke-dasharray:0 ${LOOK.edge.ghostDash}}`,
119
+ `.dg-eh{fill:none;stroke:var(--line);stroke-width:${S.arrow};stroke-linecap:round;stroke-linejoin:round}`,
120
+ `.dg-e-on{fill:none;stroke:var(--c);stroke-width:${S.edgeOn};stroke-linecap:round;stroke-dasharray:1 2}`,
121
+ `.dg-eh-on{fill:none;stroke:var(--c);stroke-width:${S.edgeOn};stroke-linecap:round;stroke-linejoin:round}`,
122
+ `.dg-flow{fill:none;stroke:var(--surf);stroke-width:${S.flow};stroke-linecap:round;stroke-dasharray:1.5 ${LOOK.edge.flowDash}}`,
123
+ `.dg-e-past{fill:none;stroke:${PAST};stroke-width:${S.edge};stroke-linecap:round}`,
124
+ `.dg-eh-past{fill:none;stroke:${PAST};stroke-width:${S.arrow};stroke-linecap:round;stroke-linejoin:round}`,
125
+ ".dg-bd{cursor:pointer}",
126
+ ".dg-bdf{fill:var(--c)}",
127
+ `.dg-bdft{${font(TYPE.badge)};fill:var(--on-c)}`,
128
+ `.dg-bdr{fill:none;stroke:var(--c);stroke-width:${S.badgeRing};pointer-events:none}`,
129
+ `.dg-bdp{fill:${mix(X.badgePast)};stroke:${mix(X.badgePastEdge, "transparent")};stroke-width:${S.hair}}`,
130
+ `.dg-bdpt{${font(TYPE.badge)};fill:var(--ct)}`,
131
+ `.dg-bdp-g{fill:var(--surf);stroke:${PAST};stroke-width:${S.hair}}`,
132
+ `.dg-bdpt-g{${font(TYPE.badge)};fill:var(--mute)}`,
133
+ `.dg-cap rect,.dg-act rect{fill:${mix(X.cap)};stroke:${mix(X.capEdge, "transparent")}}`,
134
+ `.dg-cap text{${font(TYPE.label)};fill:var(--ct)}`,
135
+ `.dg-capj text{${font(TYPE.labelJa)}}`,
136
+ `.dg-cap-past text{${font(TYPE.label)};fill:var(--mute);fill-opacity:${LOOK.state.pastLabel}}`,
137
+ `.dg-cap-pastj text{${font(TYPE.labelJa)}}`,
138
+ `.dg-act text{${font(TYPE.action)};fill:var(--ct)}`,
139
+ ".dg-car{fill:var(--carry,var(--ink))}",
140
+ `.dg-car-t{${font(TYPE.carrier)};fill:var(--bg)}`,
141
+ `.dg-car-tj{${font(TYPE.carrierJa)}}`,
142
+ `.dg-env{fill:var(--carry,var(--ink));stroke:var(--surf);stroke-width:${S.envelope}}`,
143
+ `.dg-env-in{fill:none;stroke:var(--surf);stroke-width:${S.flow};stroke-linejoin:round;stroke-linecap:round}`,
144
+ ".dg-coin{fill:var(--coin);stroke:var(--surf);stroke-width:1.2}",
145
+ ".dg-coin-in{fill:none;stroke:var(--coinin);stroke-width:1.1}",
146
+ ".dg-strip{fill:var(--surf);stroke:var(--hair)}",
147
+ `.dg-sep{stroke:var(--hair);stroke-width:${S.hair}}`,
148
+ `.dg-sh{${font(TYPE.stripTitle)};fill:var(--ink)}`,
149
+ `.dg-fl{${font(TYPE.fieldName)};fill:var(--mute)}`,
150
+ `.dg-fv{${font(TYPE.fieldValue)};fill:var(--ink)}`,
151
+ `.dg-fvj{${font(TYPE.fieldValueJa)};fill:var(--ink)}`,
152
+ ".dg-fv-c{fill:var(--ct)}",
153
+ ".dg-fl-now{fill:var(--c)}",
154
+ `.dg-tr-ring{fill:none;stroke:var(--line);stroke-width:${S.trail}}`,
155
+ ".dg-tr-fill{fill:var(--c)}",
156
+ ".dg-tg rect{fill:var(--c)}",
157
+ `.dg-tg text{${font(TYPE.tag)};fill:var(--on-c)}`,
158
+ `.dg-side{fill:color-mix(in srgb,var(--c) ${X.side}%,var(--bg));stroke:${mix(X.sideEdge, "transparent")};stroke-dasharray:4 4}`,
159
+ `.dg-side-t{${font(TYPE.regionName)};fill:var(--ct)}`,
160
+ `.dg-side-n{${font(TYPE.regionNote)};fill:var(--mute)}`,
161
+ `.dg-ghost{fill:var(--surf);stroke:${mix(X.ghostEdge, "transparent")};stroke-dasharray:4 3}`,
162
+ `.dg-path{fill:none;stroke:${mix(X.path, "transparent")};stroke-width:${S.path};stroke-linecap:round;stroke-dasharray:0 ${LOOK.edge.ghostDash}}`,
163
+ `.dg-path-h{fill:none;stroke:${mix(X.path, "transparent")};stroke-width:${S.arrow};stroke-linecap:round;stroke-linejoin:round}`,
164
+ `.dg-path-t{${font(TYPE.label)};fill:var(--ct)}`,
165
+ `.dg-path-tj{${font(TYPE.labelJa)}}`,
166
+ ".dg-start{fill:var(--ink)}",
167
+ `.dg-end{fill:var(--bg);stroke:var(--ink);stroke-width:${S.end}}`,
168
+ ".dg-end-in{fill:var(--ink)}",
169
+ `.dg-end-x{fill:var(--bg);stroke:${mix(X.path, "transparent")};stroke-width:${S.arrow};stroke-dasharray:2 2.5}`,
170
+ `.dg-end-xi{fill:${mix(X.path, "transparent")}}`,
171
+ `.dg-mark{${font(TYPE.regionNote)};fill:var(--mute)}`,
172
+ `.dg-done{fill:var(--ink);stroke:var(--surf);stroke-width:${S.done}}`,
173
+ `.dg-done-ck{fill:none;stroke:var(--surf);stroke-width:${S.glyph};stroke-linecap:round;stroke-linejoin:round}`,
174
+ `.dg-git-l{fill:none;stroke:var(--c);stroke-width:${S.git};stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1 2}`,
175
+ `.dg-git-cp{fill:none;stroke:var(--c);stroke-width:${S.gitOrphan};stroke-linecap:round;stroke-dasharray:3 3;stroke-opacity:.7}`,
176
+ `.dg-git-c{fill:var(--surf);stroke:var(--c);stroke-width:${S.git}}`,
177
+ `.dg-git-id{${font(TYPE.gitId)};fill:var(--ct)}`,
178
+ `.dg-git-h{${font(TYPE.gitHash)};fill:var(--mute)}`,
179
+ `.dg-git-n{${font(TYPE.gitNote)};fill:var(--ink2)}`,
180
+ `.dg-git-old{fill:var(--surf);stroke:var(--c);stroke-width:${S.gitOrphan};stroke-dasharray:3 3;stroke-opacity:.6}`,
181
+ `.dg-git-oldl{${font(TYPE.gitId)};fill:var(--ct);opacity:.55}`,
182
+ // 木の図 (#3233)。木の線は線の灰で、運ぶ物が通った跡は運ぶ物の色で引く
183
+ `.dg-tree-l{fill:none;stroke:var(--line);stroke-width:${S.tree};stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1 2}`,
184
+ `.dg-tree-tr{fill:none;stroke:var(--c);stroke-width:${S.treeTrail};stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:1 2}`,
185
+ `.dg-tree-h{fill:none;stroke:var(--c);stroke-width:${S.treeTrail};stroke-linecap:round;stroke-linejoin:round}`,
186
+ `.dg-tree-con{fill:none;stroke:var(--line);stroke-width:${S.treeCon};stroke-linecap:round;stroke-dasharray:2 3.5}`,
187
+ `.dg-tree-card{fill:var(--surf);stroke:var(--hair);stroke-width:${S.hair}}`,
188
+ `.dg-tree-cg{fill:none;stroke:var(--mute);stroke-width:${S.glyph};stroke-linecap:round;stroke-linejoin:round}`,
189
+ `.dg-tree-ct{${font(TYPE.treeCard)};fill:var(--ink)}`,
190
+ `.dg-tree-hash{${font(TYPE.treeHash)};fill:var(--ink)}`,
191
+ `.dg-tree-name{${font(TYPE.treeName)};fill:var(--mute)}`,
192
+ `.dg-tree-one{${font(TYPE.boxName)};fill:var(--ink)}`,
193
+ `.dg-tree-rh{${font(TYPE.rootHash)};fill:var(--ink)}`,
194
+ `.dg-tree-rn{${font(TYPE.rootName)};fill:var(--mute)}`,
195
+ // 列の図 (#3239)。封は列の左端から右へ伸びる
196
+ ".dg-ln-chip{fill:var(--c)}",
197
+ `.dg-ln-plain{fill:color-mix(in srgb,var(--mute) ${X.chipPlain}%,var(--surf))}`,
198
+ `.dg-ln-t{${font(TYPE.chip)};fill:var(--on-c)}`,
199
+ `.dg-ln-tp{${font(TYPE.chip)};fill:var(--ink)}`,
200
+ ".dg-ln-seal{transform-box:fill-box;transform-origin:0 50%}",
201
+ `.dg-ln-sd{fill:color-mix(in srgb,var(--mute) ${X.sealDark}%,var(--surf))}`,
202
+ `.dg-ln-sl{fill:color-mix(in srgb,var(--mute) ${X.sealLight}%,var(--surf))}`,
203
+ `.dg-ln-stamp{fill:var(--surf);stroke:var(--c);stroke-width:${S.stamp}}`,
204
+ `.dg-ln-st{${font(TYPE.stamp)};fill:var(--ct)}`,
205
+ // 時間軸の図 (#3165)。和文を含む字は、末尾に j を付けた class で同じ大きさと太さの和文の字にする
206
+ `.dg-tm-ep{fill:color-mix(in srgb,var(--ink) ${X.timeShade}%,transparent)}`,
207
+ `.dg-tm-sep{stroke:var(--hair);stroke-width:${S.hair};stroke-dasharray:2 4}`,
208
+ `.dg-tm-hd{${font(TYPE.timeHead)};fill:var(--ink)}`,
209
+ `.dg-tm-hdj{${font(sansOf(TYPE.timeHead))}}`,
210
+ `.dg-tm-slot{fill:none;stroke:var(--line);stroke-width:${S.timeSlot};opacity:.55}`,
211
+ ".dg-tm-m{fill:var(--c)}",
212
+ ".dg-tm-x{fill:var(--c-slate)}",
213
+ `.dg-tm-fr{fill:none;stroke:var(--c-blue);stroke-width:${S.timeFrame};stroke-dasharray:3 2}`,
214
+ `.dg-tm-gd{fill:none;stroke:color-mix(in srgb,var(--c-blue) ${X.timeGuide}%,transparent);stroke-width:${S.hair};stroke-dasharray:2 3}`,
215
+ `.dg-tm-ax{fill:none;stroke:var(--line);stroke-width:${S.timeAxis}}`,
216
+ `.dg-tm-tk{${font(TYPE.timeTick)};fill:var(--mute)}`,
217
+ `.dg-tm-tkj{${font(sansOf(TYPE.timeTick))}}`,
218
+ `.dg-tm-en{${font(TYPE.timePeriod)};fill:var(--ink2)}`,
219
+ `.dg-tm-er{${font(TYPE.timeRange)};fill:var(--mute)}`,
220
+ `.dg-tm-erj{${font(sansOf(TYPE.timeRange))}}`,
221
+ `.dg-tm-rn{${font(TYPE.timeRow)};fill:var(--ink2)}`,
222
+ `.dg-tm-br{fill:none;stroke:var(--c);stroke-width:${S.timeSpan};stroke-linecap:round;stroke-linejoin:round}`,
223
+ `.dg-tm-bt{${font(TYPE.spanText)};fill:var(--ct)}`,
224
+ `.dg-tm-bx{fill:color-mix(in srgb,var(--c) ${X.timeSpan}%,transparent);stroke:var(--c);stroke-width:${S.timeSpan};stroke-dasharray:4 3}`,
225
+ `.dg-tm-con{fill:none;stroke:var(--line);stroke-width:${S.timeDrop};stroke-linecap:round;stroke-dasharray:0 3.5}`,
226
+ ".dg-tm-pg{fill:var(--surf);stroke:var(--line);stroke-dasharray:2 2.5}",
227
+ `.dg-tm-pgl{fill:none;stroke:var(--mute);stroke-width:${S.timeFlag};stroke-linecap:round;stroke-linejoin:round}`,
228
+ `.dg-tm-pc{fill:var(--surf);stroke:var(--c);stroke-width:${S.timePoint}}`,
229
+ `.dg-tm-pcg{fill:none;stroke:var(--c);stroke-width:${S.timeFlag};stroke-linecap:round;stroke-linejoin:round}`,
230
+ `.dg-tm-pn{${font(TYPE.pointName)};fill:var(--ink)}`,
231
+ `.dg-tm-pnj{${font(sansOf(TYPE.pointName))}}`,
232
+ ".dg-tm-pn-g{fill:var(--mute)}",
233
+ `.dg-tm-ps{${font(TYPE.pointState)};fill:var(--ct)}`,
234
+ `.dg-tm-ln{fill:none;stroke:var(--c);stroke-width:${S.edgeOn};stroke-linecap:round;stroke-dasharray:1 2}`,
235
+ `.dg-tm-nd{stroke:var(--ink);stroke-width:${S.timeNeedle};opacity:.55}`,
236
+ ".dg-tm-nh{fill:var(--ink)}",
237
+ ".dg-tm-ph{fill:none;stroke:var(--line);stroke-dasharray:3 3}",
238
+ `.dg-tm-ex{fill:color-mix(in srgb,var(--c-slate) ${X.timeEmpty}%,var(--surf));stroke:var(--c-slate);stroke-width:${S.timeFrame};stroke-dasharray:3 3}`,
239
+ `.dg-tm-ext{${font(TYPE.emptyText)};fill:var(--t-slate)}`,
240
+ ".dg-tm-mt{fill:var(--hair)}",
241
+ ".dg-tm-mf{fill:var(--c);transform-box:fill-box;transform-origin:0 50%}",
242
+ `.dg-tm-mk{stroke:var(--ink2);stroke-width:${S.timeMeter}}`,
243
+ `.dg-tm-ml{${font(TYPE.meterLine)};fill:var(--ink2)}`,
244
+ ".dg-vp-bg{fill:var(--bg)}",
245
+ ".dg-vp-frame{fill:none;stroke:var(--hair)}",
246
+ ".dg-hd-bg{fill:var(--bg)}",
247
+ ".dg-mm-bg{fill:var(--surf);stroke:var(--hair)}",
248
+ `.dg-mm-t{${font(TYPE.miniTitle)};fill:var(--mute)}`,
249
+ ".dg-mm-world{fill:var(--sunk);stroke:var(--hair)}",
250
+ `.dg-mm-band{fill:${mix(X.miniBand)};stroke:${mix(X.miniBandEdge, "transparent")};stroke-width:.6}`,
251
+ `.dg-mm-card{fill:${mix(X.mini)}}`,
252
+ `.dg-mm-vp{fill:color-mix(in srgb,var(--ink) ${X.view}%,transparent);stroke:var(--ink);stroke-width:${S.badgeRing};vector-effect:non-scaling-stroke}`,
253
+ ].join("");
254
+
255
+ /** 同じ原本と同じ見た目からは同じ名前になるよう、中身から短い名前を作る (keyframes の名前が頁の中で混ざらないため)。 */
256
+ function nameOf(text: string): string {
257
+ let h = 0x811c9dc5;
258
+ for (let i = 0; i < text.length; i++) {
259
+ h ^= text.charCodeAt(i);
260
+ h = Math.imul(h, 0x01000193);
261
+ }
262
+ return (h >>> 0).toString(36);
263
+ }
264
+
265
+ /** 各箱が動く段。線の両端、処理、字の書き換えの箱。 */
266
+ function involved(diagram: Diagram): Map<string, number[]> {
267
+ const on = new Map<string, Set<number>>();
268
+ const add = (id: string, s: number): void => {
269
+ on.set(id, (on.get(id) ?? new Set()).add(s));
270
+ };
271
+ diagram.steps.forEach((step, s) => {
272
+ for (const event of step.events) {
273
+ if (event.type === "edge") {
274
+ add(event.from, s);
275
+ add(event.to, s);
276
+ } else if (event.type === "action" || event.type === "swap") add(event.box, s);
277
+ }
278
+ });
279
+ return new Map([...on].map(([id, steps]) => [id, [...steps].sort((a, b) => a - b)]));
280
+ }
281
+
282
+ /**
283
+ * 箱の下の字の移り変わり。書き換えはそのまま残し、構成図の処理はその段の間だけ出して元へ戻す。
284
+ * 止め絵を選んだ図は、その箱で最後に起きたのが処理なら、最後の段で起きることが済んだ時にその処理を出し直して繰り返す前まで残す (#3200)
285
+ */
286
+ function subChanges(diagram: Diagram, timeline: Timeline, actionsInBox: boolean): Map<string, SubChange[]> {
287
+ type Raw = { t: number; order: number; box: string; set?: string; act?: string | null };
288
+ const raw: Raw[] = [];
289
+ const { whole } = timeline;
290
+ let order = 0;
291
+ for (const time of timeline.events) {
292
+ const event = diagram.steps[time.step]?.events[time.event];
293
+ if (event?.type === "swap") raw.push({ t: time.at, order: order++, box: event.box, set: event.text });
294
+ if (actionsInBox && event?.type === "action") {
295
+ raw.push({ t: time.at, order: order++, box: event.box, act: event.label });
296
+ const end = (timeline.steps[time.step] as Span).end;
297
+ if (!whole || end <= whole.start) raw.push({ t: end, order: order++, box: event.box, act: null });
298
+ }
299
+ }
300
+ raw.sort((a, b) => a.t - b.t || a.order - b.order);
301
+ const out = new Map<string, SubChange[]>();
302
+ for (const box of diagram.boxes) {
303
+ let base: [string, string] = [box.sub ?? "", "dg-ss"];
304
+ let acting: string | undefined;
305
+ let shown = base.join("|");
306
+ const list: SubChange[] = [];
307
+ const changes = raw.filter((r) => r.box === box.id);
308
+ const latest = [...changes].reverse().find((r) => r.set !== undefined || typeof r.act === "string");
309
+ if (whole && typeof latest?.act === "string") changes.push({ t: whole.start, order: order++, box: box.id, act: latest.act });
310
+ for (const change of changes) {
311
+ // 書き換えは、出ている処理の字も置き換える
312
+ if (change.set !== undefined) {
313
+ base = [change.set, "dg-ss-ok"];
314
+ acting = undefined;
315
+ }
316
+ if (change.act !== undefined) acting = change.act ?? undefined;
317
+ const now: [string, string] = acting !== undefined ? [acting, "dg-ss-act"] : base;
318
+ if (now.join("|") === shown) continue;
319
+ shown = now.join("|");
320
+ list.push([change.t, now[0], now[1]]);
321
+ }
322
+ // すぐ次の字に替わる字は読めないので出さない
323
+ const kept = list.filter((change, k) => {
324
+ const next = list[k + 1];
325
+ return next === undefined || next[0] - change[0] >= MOTION.minShow;
326
+ });
327
+ out.set(box.id, kept);
328
+ }
329
+ return out;
330
+ }
331
+
332
+ function fieldChanges(diagram: Diagram, timeline: Timeline, layout: Layout): Map<string, FieldChange[]> {
333
+ const out = new Map<string, FieldChange[]>();
334
+ for (const time of timeline.events) {
335
+ const event = diagram.steps[time.step]?.events[time.event];
336
+ if (event?.type !== "strip") continue;
337
+ const color: ColorKey = layout.badges[time.step]?.color ?? "slate";
338
+ const list = out.get(event.field) ?? [];
339
+ const until = (timeline.steps[time.step] as Span).end;
340
+ list.push({ at: time.at, color, step: time.step, until, ...(event.value !== undefined ? { value: event.value } : {}), ...(event.tag !== undefined ? { tag: event.tag } : {}) });
341
+ out.set(event.field, list);
342
+ }
343
+ return out;
344
+ }
345
+
346
+ export interface FollowFrame {
347
+ /** 枠の幅 (px)。寄って追う窓はこの幅で、字を原寸で見せる */
348
+ width: number;
349
+ /** 枠の中で見える高さ (px)。渡すと、窓と全体図をこの高さに収め (#3047)、窓をこの高さまで伸ばす (#3053)。枠の高さが図で伸びる置き場では渡さない */
350
+ height?: number;
351
+ /** 隅の全体図の札の言葉。渡し忘れを型の検査で止めるため、省けない欄にする */
352
+ lang: NotationLang;
353
+ }
354
+
355
+ /**
356
+ * 同じ線の同じ名前を後の段が置く時は、薄く残した名前をその段が始まるまでで消す (#3184)。
357
+ * 止め絵で全ての段の名前を出し直す間は、同じ所に出る後の段の名前に任せる (#3200)
358
+ */
359
+ function fadeBefore(l: SceneLabel, time: LabelTime, steps: Span[]): LabelTime {
360
+ if (l.until === undefined) return time;
361
+ const { after, again: _again, ...rest } = time;
362
+ if (!after) return rest;
363
+ const cut = (steps[l.until] as Span).start;
364
+ return cut > after.start ? { ...rest, after: { start: after.start, end: Math.min(after.end, cut) } } : rest;
365
+ }
366
+
367
+ /** 図を描く。`follow` を渡すと、寄って追う窓と隅の全体図で描く。`ink` を渡すと、描いた字の四角と見えている間をそこへ記録する (#3175)。 */
368
+ export function drawSvg(diagram: Diagram, layout: Layout, timeline: Timeline, palette: Palette, theme: Theme, follow?: FollowFrame, ink: Ink[] = [], traces: Trace[] = []): string {
369
+ // 札の言葉で全体図の地の幅が変わりうるので、同じ頁に置いた別の言葉の図と名前を分ける。
370
+ // 色は色味の名前でなく色の値から名前を作り、色の値を重ねた図 (#3198) と同じ色味の名前の図の変数の規則を分ける
371
+ const vars = paletteVars(palette, theme);
372
+ const id = nameOf(`${JSON.stringify(diagram)}|${vars}|${follow ? `${follow.width}|${follow.lang}` : ""}`);
373
+ const m = new Motion(`dg${id}`, timeline.total, timeline.last);
374
+ const ctx: Ctx = { m, t: timeline, id, sh: `filter="url(#dg-sh-${id})"`, end: (timeline.steps[timeline.steps.length - 1] as Span).end, ink, traces };
375
+ const on = involved(diagram);
376
+ // 時系列図の処理は生存線の上の札に出し、他の図の種類は箱の下の字に出す
377
+ const subs = subChanges(diagram, timeline, layout.kind !== "sequence");
378
+
379
+ const L = { band: [] as string[], base: [] as string[], lit: [] as string[], node: [] as string[], badge: [] as string[], top: [] as string[] };
380
+ for (const region of layout.regions) L.band.push(band(region, ink));
381
+ const ghostColor = layout.boxes.find((b) => b.ghost)?.color ?? "slate";
382
+ if (layout.side) L.band.push(side(layout.side, ghostColor, ink));
383
+ // 脇道へ入る道は脇道の状態の色、それ以外の道は送る側の色で描く
384
+ const boxColor = (id: string, ghost?: boolean): ColorKey | undefined => layout.boxes.find((b) => b.id === id && (ghost === undefined || b.ghost === ghost))?.color;
385
+ for (const p of layout.paths) L.base.push(path(p, boxColor(p.to, true) ?? boxColor(p.from) ?? ghostColor, ink, traces));
386
+ for (const e of layout.ends) L.node.push(endMark(e, ghostColor, ink));
387
+ // 状態遷移図は、段で変わった値を今の状態の色で描き、帯の通った状態の点を着いた時刻に塗る (#3171)
388
+ const isState = layout.kind === "state";
389
+ const arrivals = new Map((timeline.states ?? []).flatMap((s) => (s.lit[0] ? [[s.box, s.lit[0].start] as [string, number]] : [])));
390
+ // 時間軸の図の物差しの欄は、満ち具合の動きで棒を伸ばす (#3165)
391
+ const meters = new Map((timeline.meters ?? []).map((meter) => [meter.field, meter.keys]));
392
+ const gauge = (field: SceneField): string | undefined => (field.meter ? kindParts("time").meterField({ ...field, meter: field.meter }, meters.get(field.name) ?? [[0, 0]], ctx) : undefined);
393
+ const drawStrip = (s: SceneStrip): string => strip(s, fieldChanges(diagram, timeline, layout), ctx, isState, arrivals, gauge);
394
+ // 寄って追う図の表は窓の下に置くので、窓の中身には描かない (#3270)
395
+ if (layout.strip && !follow) L.band.push(drawStrip(layout.strip));
396
+ for (const line of layout.lifelines) L.base.push(lifeline(line.x, line.y1, line.y2));
397
+ // 枝分かれの図の線と commit と札は、枝分かれの図を描く部品が描く (#3164)
398
+ if (isGitLayout(layout)) {
399
+ const git = kindParts("git").drawGit(layout, diagram, timeline, ctx);
400
+ L.base.push(git.links);
401
+ L.lit.push(git.lines);
402
+ L.node.push(git.commits);
403
+ L.top.push(git.tags);
404
+ }
405
+ // 木の図の木の線と通った跡と木の箱と札は、木の図を描く部品が描く (#3233)。木の線を走る線は通った跡が見せるので、ほかの線と同じ線で描かない
406
+ const treeLayout = isTreeLayout(layout) ? layout : undefined;
407
+ const tree = treeLayout ? kindParts("tree").drawTree(treeLayout, diagram, timeline, ctx) : undefined;
408
+ if (tree) {
409
+ L.base.push(tree.links);
410
+ L.lit.push(tree.trails);
411
+ L.node.push(tree.nodes);
412
+ }
413
+ const runs = new Set((treeLayout?.runs ?? []).map((r) => `${r.step}/${r.event}`));
414
+ // 列の図の列とチップと封と札は、列の図を描く部品が描く (#3239)
415
+ const lineupLayout = isLineupLayout(layout) ? layout : undefined;
416
+ if (lineupLayout) {
417
+ const lineup = kindParts("lineup").drawLineup(lineupLayout, diagram, timeline, ctx, subs);
418
+ L.base.push(lineup.lanes);
419
+ L.node.push(lineup.chips);
420
+ }
421
+ // 時間軸の図の目盛りと印と拡大の帯の箱と節目は、時間軸の図を描く部品が描く (#3165)。拡大の帯の線は他の図と同じ線で描く
422
+ const timeLayout = isTimeLayout(layout) ? layout : undefined;
423
+ if (timeLayout) {
424
+ const drawn = kindParts("time").drawTime(timeLayout, diagram, timeline, ctx, subs);
425
+ L.base.push(drawn.base);
426
+ L.lit.push(drawn.lit);
427
+ L.node.push(drawn.node);
428
+ L.top.push(drawn.top);
429
+ }
430
+ const wired = new Set((timeLayout?.wires ?? []).map((w) => `${w.step}/${w.event}`));
431
+ for (const e of layout.edges) {
432
+ const time = timeline.edges.find((t) => t.step === e.step && t.event === e.event);
433
+ if (!time || (timeLayout && !wired.has(`${e.step}/${e.event}`)) || runs.has(`${e.step}/${e.event}`)) continue;
434
+ // 木の図の箱は段ごとに現れるので、木の線を走らない線の点線は、両端の木の箱が現れてから出す (#3240)
435
+ const since = Math.max(tree?.appear.get(e.from) ?? 0, tree?.appear.get(e.to) ?? 0);
436
+ const drawn = edge(e, time, ctx, isState, since);
437
+ L.base.push(drawn.base);
438
+ L.lit.push(drawn.lit);
439
+ }
440
+ const states = new Map((timeline.states ?? []).map((s) => [s.box, s]));
441
+ // 飛び先を持つ箱は、箱の札をその飛び先への link で包む (#3199)。時間軸の図の箱は時間軸の図を描く部品が包む
442
+ const links = new Map(diagram.boxes.flatMap((b) => (b.link === undefined ? [] : [[b.id, b.link] as [string, string]])));
443
+ const linked = (id: string, markup: string): string => linkTo(links.get(id), markup);
444
+ for (const box of timeLayout || lineupLayout ? [] : layout.boxes) {
445
+ if (box.ghost) {
446
+ L.node.push(linked(box.id, ghostCard(box, ink)));
447
+ continue;
448
+ }
449
+ const state = states.get(box.id);
450
+ L.node.push(linked(box.id, card(box, ctx, on.get(box.id) ?? [], subs.get(box.id) ?? [], isState ? (state?.lit ?? []) : undefined)));
451
+ if (state?.done !== undefined) L.node.push(doneMark(box, state.done, ctx));
452
+ }
453
+ for (const b of layout.badges) if (!(follow && onStrip(layout, b))) L.badge.push(badge(b, ctx, isState));
454
+ for (const l of layout.labels) {
455
+ const time = timeline.labels.find((t) => t.step === l.step && t.event === l.event);
456
+ if (time) L.top.push(label(l, fadeBefore(l, time, timeline.steps), ctx));
457
+ }
458
+ // 止め絵を選んだ図は、全ての段の名前を出す間にも処理の札を出す。その間に見えている札は繰り返す前まで延ばす (#3200)
459
+ const { whole } = timeline;
460
+ for (const a of layout.actions) {
461
+ const time = timeline.events.find((t) => t.step === a.step && t.event === a.event);
462
+ if (!time) continue;
463
+ const until = (timeline.steps[a.step] as Span).end;
464
+ L.top.push(whole && until > whole.start ? action(a, time.at, whole.end, ctx) : action(a, time.at, until, ctx, whole));
465
+ }
466
+ // 木の図の運ぶ物は着いた所で消える。通った跡が行き先を残し、兄弟の箱から同じ親へ着いた運ぶ物が重ならないため
467
+ for (const time of timeline.carriers) {
468
+ const e = layout.edges.find((x) => x.step === time.step && x.event === time.event);
469
+ if (e) L.top.push(carrier(e, treeLayout ? { ...time, start: time.depart, end: time.arrive + MOTION.fade } : time, ctx));
470
+ }
471
+ const content = Object.values(L)
472
+ .map((parts) => parts.join(""))
473
+ .join("");
474
+
475
+ const { near, far, nearY, farY } = LOOK.shadow;
476
+ const shadow = `<filter id="dg-sh-${id}" x="-20%" y="-30%" width="140%" height="180%"><feDropShadow dx="0" dy="${nearY}" stdDeviation="${near}" style="flood-color:var(--sh);flood-opacity:var(--shA)"/><feDropShadow dx="0" dy="${farY}" stdDeviation="${far}" style="flood-color:var(--sh);flood-opacity:var(--shB)"/></filter>`;
477
+ // 寄って追う時系列図は、頭の箱を窓の上端に貼る頭の列にも描く (#3118)。頭の列の箱はアイコンを外した 2 段 (#3120)。止めて見せる図では描かない
478
+ const heads = follow && layout.kind === "sequence" ? layout.boxes.map((box) => linked(box.id, headCard(box, ctx, on.get(box.id) ?? [], subs.get(box.id) ?? []))).join("") : "";
479
+ // 表の値だけが変わる段の番号の丸は表の隅に在るので、表と一緒に窓の下へ移す (#3270)。
480
+ // 窓の下の表は図の左端から始まるので、丸の半径だけ内へ寄せる。寄せないと丸の左が図の端で切れる
481
+ const drawTable = (s: SceneStrip, from: SceneStrip): string =>
482
+ drawStrip(s) + layout.badges.filter((b) => onStrip(layout, b)).map((b) => badge({ ...b, x: b.x - from.x + s.x + LOOK.badge.r, y: b.y - from.y + s.y }, ctx, isState)).join("");
483
+ const view = follow ? followView(layout, timeline, diagram, m, id, content, follow, heads, drawTable) : { body: `<rect class="dg-bg" width="${layout.width}" height="${layout.height}" rx="${LOOK.region.radius}"/>${content}`, w: layout.width, h: layout.height };
484
+ const css = `.dg-${id}{${FONT_VARS};--T:${timeline.total}s;${vars}}${PART_CSS}${m.frames.join("")}`;
485
+ return (
486
+ `<svg xmlns="http://www.w3.org/2000/svg" class="dg dg-${id}" viewBox="0 0 ${Math.ceil(view.w)} ${Math.ceil(view.h)}" width="${Math.ceil(view.w)}" height="${Math.ceil(view.h)}" role="img" aria-label="${esc(diagram.title)}" data-dragon="figure" data-view="${follow ? "follow" : "fixed"}">` +
487
+ `<style>${css}</style><defs>${shadow}</defs>${view.body}</svg>`
488
+ );
489
+ }
490
+
491
+ /** 四角を全部囲む四角。 */
492
+ function union(rects: Rect[]): Rect {
493
+ const x = Math.min(...rects.map((r) => r.x));
494
+ const y = Math.min(...rects.map((r) => r.y));
495
+ return { x, y, w: Math.max(...rects.map((r) => r.x + r.w)) - x, h: Math.max(...rects.map((r) => r.y + r.h)) - y };
496
+ }
497
+
498
+ /** 番号の丸が値の表の上に在るか。表の値だけが変わる段の丸は表の隅に置かれる */
499
+ function onStrip(layout: Layout, badge: { y: number }): boolean {
500
+ return layout.strip !== undefined && badge.y >= layout.strip.y;
501
+ }
502
+
503
+ /** 段で動く物が占める所。 */
504
+ function focusOf(layout: Layout, diagram: Diagram, step: number): Rect | undefined {
505
+ const rects = focusParts(layout, diagram, step);
506
+ return rects.length === 0 ? undefined : union(rects);
507
+ }
508
+
509
+ /**
510
+ * 番号の丸が窓から外れる段で、窓に入れる所 (#3046)。
511
+ * 丸とその周りを起点に、丸に近い動く物から順に、窓 (`vw` × `vh`) に収まる間だけ囲む。収まらない物は飛ばして次を見る
512
+ */
513
+ function badgeFocus(badge: { x: number; y: number }, parts: Rect[], vw: number, vh: number): Rect {
514
+ const room = LOOK.badge.r + LOOK.follow.badgeRoom;
515
+ const { x: bx, y: by } = badge;
516
+ const away = (p: Rect): number => Math.hypot(Math.max(0, p.x - bx, bx - p.x - p.w), Math.max(0, p.y - by, by - p.y - p.h));
517
+ let held: Rect = { x: bx - room, y: by - room, w: room * 2, h: room * 2 };
518
+ for (const p of [...parts].sort((a, b) => away(a) - away(b))) {
519
+ const next = union([held, p]);
520
+ if (next.w <= vw && next.h <= vh) held = next;
521
+ }
522
+ return held;
523
+ }
524
+
525
+ /** 段で動く物を 1 つずつ。 */
526
+ function focusParts(layout: Layout, diagram: Diagram, step: number): Rect[] {
527
+ const rects: Rect[] = [];
528
+ for (const e of layout.edges.filter((x) => x.step === step)) {
529
+ const xs = e.points.map((p) => p[0]);
530
+ const ys = e.points.map((p) => p[1]);
531
+ rects.push({ x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) });
532
+ }
533
+ rects.push(...layout.labels.filter((l) => l.step === step), ...layout.actions.filter((a) => a.step === step));
534
+ // 木の図は、その段で現れる木の箱と木の線と、線の両端の木の箱を見る (#3233)
535
+ if (isTreeLayout(layout)) {
536
+ const ends = new Set((diagram.steps[step]?.events ?? []).flatMap((e) => (e.type === "edge" ? [e.from, e.to] : [])));
537
+ rects.push(...layout.nodes.filter((n) => n.step === step || ends.has(n.id)));
538
+ for (const l of layout.links.filter((x) => x.step === step)) {
539
+ const xs = l.points.map((p) => p[0]);
540
+ const ys = l.points.map((p) => p[1]);
541
+ rects.push({ x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) });
542
+ }
543
+ }
544
+ // 列の図は、その段で変わる列を見る (#3239)
545
+ if (isLineupLayout(layout)) {
546
+ const changed = new Set((diagram.steps[step]?.events ?? []).flatMap((e) => ("box" in e ? [e.box] : [])));
547
+ rects.push(...layout.lanes.filter((lane) => changed.has(lane.id)));
548
+ }
549
+ for (const event of diagram.steps[step]?.events ?? []) {
550
+ const ids = event.type === "edge" ? [event.from, event.to] : event.type === "action" || event.type === "swap" ? [event.box] : [];
551
+ for (const id of ids) {
552
+ const box = layout.boxes.find((b) => b.id === id);
553
+ // 時系列図の頭の箱は遠いので、線の行だけを見る
554
+ if (box && (layout.kind === "architecture" || event.type === "swap")) rects.push(box);
555
+ }
556
+ }
557
+ return rects;
558
+ }
559
+
560
+ /**
561
+ * 寄って追う窓。段ごとに動く所へ寄り、窓の外の全体図に今見ている所の枠を同じ動きで出す。
562
+ * 全体図は窓に重ねると今動く線や箱を覆うので、窓の外に置く (#3042)。
563
+ * 縦長の全体図は窓の右に列を取り、横長の全体図は窓の下に置く。失う窓の幅か図の高さの小さい側を選ぶ。
564
+ * 枠の中で見える高さを渡された時は、窓と全体図がその高さに入るまで窓を低くする (#3047)。
565
+ * 枠が余る時は窓を広げ、図の原寸の幅と、見える高さか図の高さまで使う。全体図は今の大きさのまま置く (#3053)。
566
+ * 枠の幅が `LOOK.follow.narrow` より狭い時は、縦長の全体図を出さずに窓へ枠の幅の全部を渡す (#3055)。
567
+ * 段で動く物を全部囲んだ所の真ん中に寄せると今の段の番号の丸が窓から外れる段では、丸に近い動く物から窓に収まるだけ囲んだ所へ寄せる (#3046)。
568
+ * 時系列図は頭の箱 `heads` を窓の上端の頭の列に貼り、窓が横に動く時だけ一緒に動かす。頭の箱は図の上端に在り、線を追う窓からは外れるため。
569
+ * 窓は頭の列の下の残りの高さで動く物を真ん中に見せる (#3118)。
570
+ * 頭の列の箱はアイコンを外した 2 段にして低く貼り、線は図の頭の箱の下から見せ始める (#3120)。
571
+ * 値の表は図の一番下に在り、窓が近づくまで映らず、窓より広い表は右側が切れる。全体図と同じ理由で窓の外に出し、
572
+ * 窓と全体図の下に図の枠の幅で組み直す (#3270)。窓と全体図は表を除いた図の高さ `worldH` の中だけを見る。
573
+ */
574
+ function followView(layout: Layout, timeline: Timeline, diagram: Diagram, m: Motion, id: string, content: string, follow: FollowFrame, heads: string, drawTable: (s: SceneStrip, from: SceneStrip) => string): { body: string; w: number; h: number } {
575
+ const F = LOOK.follow;
576
+ const M = LOOK.mini;
577
+ const frameWidth = Math.max(1, follow.width);
578
+ const full = Math.min(layout.width, frameWidth);
579
+ const worldH = layout.strip ? layout.strip.y : layout.height;
580
+ const title = FIGURE_TEXT[follow.lang].overview;
581
+ /** 窓の高さ `vh` の時の全体図の寸法。全体図は窓の高さで縮むので、窓を低くしたら測り直す */
582
+ const sized = (vh: number) => {
583
+ // 全体図の寸法は枠の幅と窓の高さで決め、置き場所に依らない
584
+ // 全体図の幅は表を含む図の比で決める。表を除いた比にすると全体図の列が太り、窓が狭くなる
585
+ const mw = Math.min(M.w, full * 0.4, ((vh * 0.4) / layout.height) * layout.width);
586
+ const k = mw / layout.width;
587
+ const mh = worldH * k;
588
+ // 地の幅は図の縦横の比で決まるので、縦に長い図では札より狭くなる。その時は地を札の幅まで広げ、図は広げた地の真ん中に置く
589
+ const bw = Math.max(mw, Math.ceil(textWidth(title, TYPE.miniTitle)));
590
+ // 縦横の比は窓の高さに依らないので、低くしても全体図の置き場所は変わらない
591
+ return { vh, mw, k, mh, bw, bgW: bw + M.pad * 2, bgH: mh + M.pad * 2 + M.title, beside: mh > mw };
592
+ };
593
+ const natural = sized(Math.min(worldH, Math.max(F.minH, full * F.aspect)));
594
+ // 携帯の幅では縦長の全体図の列が枠の幅の 3 割を取り、窓が図の横の 3 割ほどしか見せない。その時は全体図を出さない。
595
+ // 横長の全体図は窓の下に出して幅を取らないので、狭い枠でも出す
596
+ const bare = natural.beside && frameWidth < F.narrow;
597
+ const tableH = layout.strip ? rewrapStrip(layout.strip, 0, 0, full).h + M.inset : 0;
598
+ // 窓の右の全体図は窓の高さの中に収まり、窓の下の全体図と表は窓の高さに足される
599
+ const room = follow.height === undefined ? Number.POSITIVE_INFINITY : (natural.beside ? follow.height : follow.height - natural.bgH - M.inset) - tableH;
600
+ // 見える高さが窓より低ければ窓と全体図を縮め、高ければ全体図はそのままに窓を図の高さまで伸ばす。
601
+ // 全体図も伸ばすと、狭い枠では右の全体図の列が太って窓が狭くなる
602
+ const { vh, mw, k, mh, bw, bgW, bgH, beside } =
603
+ room < natural.vh ? sized(Math.max(F.fitMinH, room)) : { ...natural, vh: Number.isFinite(room) ? Math.min(worldH, room) : natural.vh };
604
+ // 右の全体図の列は枠の余りに置き、窓は図の原寸の幅まで広げる。枠が図より狭い時は今までどおり枠の幅から列を引く
605
+ const vw = beside && !bare ? Math.min(layout.width, frameWidth - bgW - M.inset) : full;
606
+ const clampX = (x: number): number => Math.min(layout.width - vw / 2, Math.max(vw / 2, x));
607
+ // 時系列図は窓の上端に頭の列を貼るので、動く物は頭の列の下の残りの高さ `below` に見せる (#3118)。
608
+ // 線は図の頭の箱の下 `top` から見せ始め、図の頭の箱は頭の列の下か窓の上に隠す (#3120)
609
+ const top = heads === "" ? 0 : Math.max(...layout.boxes.map((b) => b.y + b.h)) + F.headRoom;
610
+ const strip = heads === "" ? 0 : F.head.pad * 2 + F.head.h;
611
+ const below = vh - strip;
612
+ /** 頭の列の下の残りの窓の真ん中の高さを、図の頭の箱の下と図の下端で止める */
613
+ const clampY = (y: number): number => Math.min(worldH - below / 2, Math.max(top + below / 2, y));
614
+ const r = LOOK.badge.r;
615
+ let prev: [number, number] = [layout.width / 2, worldH / 2];
616
+ // 頭の列の下の残りの窓の真ん中。窓の真ん中は、これより頭の列の高さの半分だけ上に在る
617
+ const middles = timeline.steps.map((_, s) => {
618
+ // 時間軸の図は、針と印の列を必ず窓に入れる (#3165)。番号の丸へ寄せ直すと、針が窓から外れるため
619
+ if (isTimeLayout(layout)) {
620
+ const f = kindParts("time").timeFocus(layout, timeline, s, focusParts(layout, diagram, s), vw, below);
621
+ prev = [f.x + f.w / 2, f.y + f.h / 2];
622
+ return [clampX(prev[0]), clampY(prev[1])] as [number, number];
623
+ }
624
+ const f = focusOf(layout, diagram, s);
625
+ prev = f ? [f.x + f.w / 2, f.y + f.h / 2] : prev;
626
+ const at: [number, number] = [clampX(prev[0]), clampY(prev[1])];
627
+ // 動く物を全部囲んだ所が窓より大きいと、その端に在る番号の丸が窓から外れる。その段だけ丸の近くへ寄せ直す (#3046)
628
+ const b = layout.badges.find((x) => x.step === s);
629
+ if (!b || onStrip(layout, b) || (Math.abs(b.x - at[0]) <= vw / 2 - r && Math.abs(b.y - at[1]) <= below / 2 - r)) return at;
630
+ const near = badgeFocus(b, focusParts(layout, diagram, s), vw, below);
631
+ // 動く物の無い次の段は、寄せ直した窓のまま止める
632
+ prev = [near.x + near.w / 2, near.y + near.h / 2];
633
+ return [clampX(prev[0]), clampY(prev[1])] as [number, number];
634
+ });
635
+ const centers = middles.map(([x, y]): [number, number] => [x, y - strip / 2]);
636
+ const c0 = centers[0] as [number, number];
637
+ const cam: [number, number, number, number?, string?][] = [
638
+ [0, c0[0], c0[1]],
639
+ [(timeline.steps[0] as Span).start, c0[0], c0[1]],
640
+ ];
641
+ centers.forEach((c, s) => {
642
+ if (s === 0) return;
643
+ const before = centers[s - 1] as [number, number];
644
+ const start = (timeline.steps[s] as Span).start;
645
+ cam.push([start, before[0], before[1], 1, EASE.inOut], [start + F.ease, c[0], c[1]]);
646
+ });
647
+ const cl = centers[centers.length - 1] as [number, number];
648
+ cam.push([timeline.last, cl[0], cl[1], 1, EASE.inOut], [timeline.total, c0[0], c0[1]]);
649
+ const camKf = m.move(cam.map(([t, cx, cy, s, e]) => [t, vw / 2 - cx, vh / 2 - cy, s, e]));
650
+
651
+ // 右に出す時は窓の上端に揃え、下に出す時は窓の右端から内へ寄せる
652
+ const bgX = beside ? vw + M.inset : vw - bgW - M.inset;
653
+ const bgY = beside ? 0 : vh + M.inset;
654
+ const bx = bgX + M.pad;
655
+ const mx = bx + (bw - mw) / 2;
656
+ const my = bgY + M.pad + M.title;
657
+ /**
658
+ * 全体図の地と札と、今見ている所の枠。窓と同じ動きで枠を動かす。
659
+ * 時系列図の枠は頭の列の下の線を見せる所だけを囲む。頭の箱は頭の列に常に出ているため (#3122)
660
+ */
661
+ const overview = (): { clip: string; body: string } => {
662
+ const shapes = [
663
+ ...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"/>`),
664
+ ...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"/>`),
665
+ ...(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"/>`),
666
+ ].join("");
667
+ const vp = m.move(cam.map(([t, cx, cy, , e]) => [t, mx + (cx - vw / 2) * k, my + (cy - vh / 2) * k, 1, e]));
668
+ return {
669
+ clip: `<clipPath id="dg-mm-${id}"><rect x="${mx}" y="${my}" width="${mw}" height="${mh}" rx="4"/></clipPath>`,
670
+ body:
671
+ `<rect class="dg-mm-bg" x="${bgX}" y="${bgY}" width="${bgW}" height="${bgH}" rx="${M.radius}"/>` +
672
+ `<text class="dg-mm-t" x="${bx}" y="${my - M.pad + 2}">${title}</text>` +
673
+ `<g clip-path="url(#dg-mm-${id})"><rect class="dg-mm-world" x="${mx}" y="${my}" width="${mw}" height="${mh}"/>${shapes}<rect class="dg-mm-vp dg-a"${strip === 0 ? "" : ` y="${strip * k}"`} width="${vw * k}" height="${(vh - strip) * k}" rx="2" style="${vp}"/></g>`,
674
+ };
675
+ };
676
+ const mini = bare ? { clip: "", body: "" } : overview();
677
+ // 頭の列は窓の中身の上に重ね、窓と同じ時刻と緩急で横にだけ動かす (#3118)
678
+ const head =
679
+ strip === 0
680
+ ? ""
681
+ : `<g class="dg-hd"><rect class="dg-hd-bg" width="${vw}" height="${strip}"/><line class="dg-sep" x1="0" y1="${strip}" x2="${vw}" y2="${strip}"/>` +
682
+ `<g class="dg-a" style="${m.move(cam.map(([t, cx, , s, e]) => [t, vw / 2 - cx, 0, s, e]))}">${heads}</g></g>`;
683
+ const body =
684
+ `<defs><clipPath id="dg-vp-${id}"><rect width="${vw}" height="${vh}" rx="${LOOK.region.radius}"/></clipPath>${mini.clip}</defs>` +
685
+ `<g clip-path="url(#dg-vp-${id})"><rect class="dg-vp-bg" width="${vw}" height="${vh}"/><g class="dg-a" style="${camKf}">${content}</g>${head}</g>` +
686
+ `<rect class="dg-vp-frame" x="0.5" y="0.5" width="${vw - 1}" height="${vh - 1}" rx="${LOOK.region.radius}"/>${mini.body}`;
687
+ const w = beside && !bare ? vw + M.inset + bgW : full;
688
+ const bottom = beside ? vh : bgY + bgH;
689
+ if (!layout.strip) return { body, w, h: bottom };
690
+ const table = rewrapStrip(layout.strip, 0, bottom + M.inset, full);
691
+ return { body: body + drawTable(table, layout.strip), w, h: table.y + table.h };
692
+ }
693
+
694
+ /**
695
+ * 描く色味。名前で選んだ色味の `theme` の色に `colors` の色を重ねる (#3198)。
696
+ * 色味に無い色の名前と、色の値として読めない値は、名前を全て挙げて描かずに断る
697
+ */
698
+ export function paletteOf(options: RenderOptions, theme: Theme): Palette {
699
+ const palette = resolvePalette(options.palette);
700
+ if (!options.colors) return palette;
701
+ const words = FIGURE_TEXT[options.lang ?? "ja"];
702
+ const errors = Object.entries(options.colors).flatMap(([name, value]) => (!isColorName(name) ? [words.unknownColor(name)] : isColorValue(value) ? [] : [words.unreadableColor(name)]));
703
+ if (errors.length > 0) throw new Error(words.cannotDraw(errors.join(" / ")));
704
+ return { ...palette, [theme]: { ...palette[theme], ...options.colors } };
705
+ }
706
+
707
+ /** 原本の JSON から図を描く。原本が形に合わない時は、誤りの場所を添えて断る。 */
708
+ export function renderDiagram(input: unknown, options: RenderOptions = {}): Rendered {
709
+ const lang = options.lang ?? "ja";
710
+ const read = readDiagram(input, { lang });
711
+ if (!read.ok) throw new Error(FIGURE_TEXT[lang].cannotDraw(read.errors.map((e) => `${e.pointer} ${e.message}`).join(" / ")));
712
+ const diagram = read.diagram;
713
+ const layout =
714
+ diagram.kind === "sequence"
715
+ ? layoutSequence(diagram)
716
+ : diagram.kind === "state"
717
+ ? kindParts("state", lang).layoutState(diagram, lang)
718
+ : diagram.kind === "git"
719
+ ? kindParts("git", lang).layoutGit(diagram)
720
+ : diagram.kind === "time"
721
+ ? kindParts("time", lang).layoutTime(diagram, lang)
722
+ : diagram.kind === "tree"
723
+ ? kindParts("tree", lang).layoutTree(diagram)
724
+ : diagram.kind === "lineup"
725
+ ? kindParts("lineup", lang).layoutLineup(diagram)
726
+ : layoutArchitecture(diagram);
727
+ return renderLayout(diagram, layout, buildTimeline(diagram, options.still === true), options);
728
+ }
729
+
730
+ /**
731
+ * 置き場所を決めた図を描き、描いた字の重なりを数える (#3175)。`renderDiagram` が原本を読んで置き場所を決めた後に呼ぶ。
732
+ * 重なりは、字を描く部品が記録した字だけから数えるので、描く所が位置を決める字 (箱の名前) も対象に入る
733
+ */
734
+ export function renderLayout(diagram: Diagram, layout: Layout, timeline: Timeline, options: RenderOptions = {}): Rendered {
735
+ const theme: Theme = options.theme === "dark" ? "dark" : "light";
736
+ const palette = paletteOf(options, theme);
737
+ const ink: Ink[] = [];
738
+ const traces: Trace[] = [];
739
+ const svg = drawSvg(diagram, layout, timeline, palette, theme, undefined, ink, traces);
740
+ return {
741
+ svg,
742
+ palette: palette.id,
743
+ theme,
744
+ ...(diagram.view ? { view: diagram.view } : {}),
745
+ fonts: { ...FONTS },
746
+ layout,
747
+ timeline,
748
+ diagram,
749
+ overlaps: findOverlaps(ink, timeline.stills, traces),
750
+ };
751
+ }