@cardenelabs/dragon 0.41.1 → 0.42.1

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 +74 -1
  2. package/dist/cli.cjs +4094 -961
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +4094 -961
  5. package/dist/cli.js.map +1 -1
  6. package/dist/export.cjs +3681 -939
  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 +3681 -939
  11. package/dist/export.js.map +1 -1
  12. package/dist/index.cjs +4016 -815
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +159 -3
  15. package/dist/index.d.ts +159 -3
  16. package/dist/index.js +4016 -815
  17. package/dist/index.js.map +1 -1
  18. package/dist/{ink-B_7OXxtb.d.cts → ink-B8EZL7JV.d.cts} +95 -3
  19. package/dist/{ink-B_7OXxtb.d.ts → ink-B8EZL7JV.d.ts} +95 -3
  20. package/dist/node.cjs +2461 -726
  21. package/dist/node.cjs.map +1 -1
  22. package/dist/node.js +2461 -726
  23. package/dist/node.js.map +1 -1
  24. package/dist/player.global.js +2 -2
  25. package/package.json +1 -1
  26. package/src/field-messages.ts +12 -0
  27. package/src/figure-text.ts +26 -0
  28. package/src/index.ts +11 -1
  29. package/src/layout/scene.ts +23 -2
  30. package/src/layout/time.ts +680 -0
  31. package/src/look/values.ts +142 -2
  32. package/src/messages.ts +108 -5
  33. package/src/parser.ts +427 -6
  34. package/src/player.ts +48 -10
  35. package/src/printer.ts +63 -12
  36. package/src/render/icons.ts +2 -0
  37. package/src/render/parts.ts +29 -9
  38. package/src/render/svg.ts +129 -21
  39. package/src/render/time.ts +291 -0
  40. package/src/schema.ts +109 -10
  41. package/src/schemas/diagram.schema.json +224 -12
  42. package/src/schemas/validate-diagram.js +1 -1
  43. package/src/timeline.ts +147 -10
  44. package/src/words.ts +39 -6
@@ -0,0 +1,680 @@
1
+ /**
2
+ * 時間軸の図の置き場所 (#3165)。見た目の元は見本帳の試作 `docs/design/base/scenes/finality.js`。
3
+ *
4
+ * 下の帯に時間軸を置く。目盛り (`scale`) を左から同じ幅で並べ、印の列 (`rows`) を宣言した順に上から重ね、目盛りごとに細い印を 1 つ置く。
5
+ * 印の下に節目 (`points`) の旗の丸を置き、名札と状態の字を丸の右に添える。節目どうしの線は 2 つの丸の間に横に引き、名前を線の下に置く。
6
+ * 範囲の括弧 (`span`) は節目の下に、時刻の目盛りの線と字と区切り (`period`) の名前はさらに下に置く。範囲の囲み (`span` の `box`) は印の列を囲む。
7
+ * 上の帯は拡大した目盛り (`zoom`) を列にして、宣言した箱を列ごとに同じ並びで縦に置く。線は `at` の列の箱から `into` の列 (無ければ同じ列) の箱へ引く。
8
+ * 印の列と同じ名札の箱は、その列が空きにした目盛りの列で空きの枠になる。時間軸の上の拡大した範囲を枠で囲み、枠の上の角から上の帯へ点線でつなぐ。
9
+ * 中身の帯は図の下に置く。
10
+ */
11
+ import { FIGURE_TEXT } from "../figure-text";
12
+ import { COLOR_ORDER, type ColorKey, LOOK, TYPE } from "../look/values";
13
+ import type { Diagram, DiagramEvent } from "../schema";
14
+ import type { NotationLang } from "../words";
15
+ import { textBox, textWidth } from "./measure";
16
+ import {
17
+ badgeOnPath,
18
+ badgeRect,
19
+ boxColors,
20
+ boxWidth,
21
+ edgeColor,
22
+ type EdgeEvent,
23
+ type Layout,
24
+ layoutStrip,
25
+ placeLabel,
26
+ placeSlot,
27
+ type Point,
28
+ type Rect,
29
+ replaceSameSpot,
30
+ type SceneBadge,
31
+ type SceneBox,
32
+ type SceneEdge,
33
+ type SceneLabel,
34
+ type SceneRegion,
35
+ seatCarriers,
36
+ slotBoxWidth,
37
+ slotRooms,
38
+ stripNeed,
39
+ } from "./scene";
40
+
41
+ /** 時間軸。`x` から目盛り 1 つの幅 `unit` で `count` 個並べ、`line` の高さに時刻の目盛りの線を引く */
42
+ export interface TimeAxis {
43
+ x: number;
44
+ w: number;
45
+ unit: number;
46
+ count: number;
47
+ line: number;
48
+ }
49
+
50
+ /** 印の列 */
51
+ export interface TimeRowPlaced extends Rect {
52
+ id: string;
53
+ name: string;
54
+ color: ColorKey;
55
+ }
56
+
57
+ /** 目盛り 1 つの印。`empty` は空きの印。`colors` は色を変えた段と出来事と色 */
58
+ export interface TimeMark extends Rect {
59
+ row: string;
60
+ unit: number;
61
+ empty: boolean;
62
+ color: ColorKey;
63
+ colors: { step: number; event: number; color: ColorKey }[];
64
+ }
65
+
66
+ /** 時刻の字。目盛りの境 `at` に置き、字の左端を `left` に、基準線を `y` に置く */
67
+ export interface TimeTick {
68
+ at: number;
69
+ x: number;
70
+ text: string;
71
+ left: number;
72
+ y: number;
73
+ }
74
+
75
+ /** 区切り。`name` は区切りの名前と番号、`range` はその区切りの目盛りの番号の範囲。字は区切りの真ん中に置く */
76
+ export interface TimePeriodPlaced extends Rect {
77
+ index: number;
78
+ from: number;
79
+ to: number;
80
+ name: string;
81
+ range: string;
82
+ nameY: number;
83
+ rangeY: number;
84
+ }
85
+
86
+ /** 節目。置いた目盛り `unit` の印の下の旗の丸。`text` は名札と状態の字が占める所、`changes` は状態の字と色を変えた段と出来事 */
87
+ export interface TimePointPlaced {
88
+ id: string;
89
+ unit: number;
90
+ cx: number;
91
+ cy: number;
92
+ r: number;
93
+ text: Rect;
94
+ changes: { step: number; event: number; text: string; color?: ColorKey }[];
95
+ }
96
+
97
+ /** 拡大の帯の箱。`row` は同じ名札の印の列、`empty` はその列が空きにした目盛りの列の箱 */
98
+ export interface TimeBox extends SceneBox {
99
+ row?: string;
100
+ empty?: boolean;
101
+ }
102
+
103
+ /** 拡大の帯の列。目盛り `unit` の列に、宣言した箱を同じ並びで置く。`head` は列の上の字 */
104
+ export interface TimeColumn extends Rect {
105
+ unit: number;
106
+ head: string;
107
+ boxes: TimeBox[];
108
+ }
109
+
110
+ /** 拡大の帯。軸の上の拡大した範囲の枠 `frame` と、枠から帯へつなぐ点線 `guides`。`empty` は空きの枠の字、`headY` は列の上の字の基準線 */
111
+ export interface TimeZoom {
112
+ from: number;
113
+ to: number;
114
+ frame: Rect;
115
+ guides: Point[][];
116
+ columns: TimeColumn[];
117
+ empty: string;
118
+ headY: number;
119
+ }
120
+
121
+ /** 範囲の括弧 (`bracket`) か囲み (`box`)。`until` は消える段 (無ければ最後の段まで残る)。`textY` は字の基準線 */
122
+ export interface TimeSpanPlaced extends Rect {
123
+ step: number;
124
+ event: number;
125
+ kind: "bracket" | "box";
126
+ from: number;
127
+ to: number;
128
+ text: string;
129
+ textRect: Rect;
130
+ textY: number;
131
+ until?: number;
132
+ color: ColorKey;
133
+ }
134
+
135
+ /** 拡大の帯の線の両端の箱。`column` は線を出す列、`into` は受ける列の目盛り */
136
+ export interface TimeWire {
137
+ step: number;
138
+ event: number;
139
+ from: TimeBox;
140
+ to: TimeBox;
141
+ column: number;
142
+ into: number;
143
+ }
144
+
145
+ export interface TimeLayout extends Layout {
146
+ kind: "time";
147
+ axis: TimeAxis;
148
+ rows: TimeRowPlaced[];
149
+ marks: TimeMark[];
150
+ ticks: TimeTick[];
151
+ /** 細かい目盛りの線を引く境 */
152
+ minor: number[];
153
+ periods: TimePeriodPlaced[];
154
+ points: TimePointPlaced[];
155
+ zoom?: TimeZoom;
156
+ spans: TimeSpanPlaced[];
157
+ wires: TimeWire[];
158
+ /** 針の線の上端と下端 */
159
+ needle: { y1: number; y2: number };
160
+ }
161
+
162
+ export const isTimeLayout = (layout: Layout): layout is TimeLayout => layout.kind === "time";
163
+
164
+ const SECONDS = { d: 86400, h: 3600, min: 60, s: 1, ms: 0.001 } as const;
165
+ type TimeUnit = keyof typeof SECONDS;
166
+ const UNITS = Object.keys(SECONDS) as TimeUnit[];
167
+
168
+ /** 単位の長さの字 (`12s` など) の、秒と単位。読めない字は 1 秒 */
169
+ function durationOf(text: string): { seconds: number; unit: TimeUnit } {
170
+ const m = /^([0-9]+(?:\.[0-9]+)?)(ms|s|min|h|d)$/u.exec(text);
171
+ if (!m) return { seconds: 1, unit: "s" };
172
+ const unit = m[2] as TimeUnit;
173
+ return { seconds: Number(m[1]) * SECONDS[unit], unit };
174
+ }
175
+
176
+ /**
177
+ * 並べる時刻を同じ単位で書く単位。一番遅い時刻が 2 以上になる一番大きい単位で、どの単位でも 2 に届かなければ目盛りの長さの単位。
178
+ * 1 で選ぶと、72 秒の軸が 0.2 分刻みの字になって読みにくいため
179
+ */
180
+ const unitFor = (max: number, fallback: TimeUnit): TimeUnit => UNITS.find((u) => max / SECONDS[u] >= 2 - 1e-9) ?? fallback;
181
+
182
+ const timeText = (seconds: number, unit: TimeUnit, lang: NotationLang): string => `${Number((seconds / SECONDS[unit]).toFixed(2))} ${FIGURE_TEXT[lang].timeUnits[unit]}`;
183
+
184
+ /** 時刻の字を置く境。区切りがあれば区切りの境ごとに、無ければ字が `LOOK.time.ticks` 個に収まる切りのよい間ごとに置く */
185
+ function majorTicks(count: number, period: number | undefined, unitPx: number): { at: number[]; step: number } {
186
+ let step = 1;
187
+ if (period) step = period * Math.max(1, Math.ceil(count / period / 8));
188
+ else {
189
+ for (let k = 1; ; k *= 10) {
190
+ const found = [k, k * 2, k * 5].find((n) => count / n <= LOOK.time.ticks);
191
+ if (found !== undefined) {
192
+ step = found;
193
+ break;
194
+ }
195
+ }
196
+ }
197
+ const at: number[] = [];
198
+ for (let u = 0; u <= count; u += step) at.push(u);
199
+ const last = at[at.length - 1] as number;
200
+ if (last !== count && (count - last) * unitPx >= LOOK.time.minorPx) at.push(count);
201
+ return { at, step };
202
+ }
203
+
204
+ /** 細かい目盛りの線を引く境。時刻の字の間を割り切る間のうち、`LOOK.time.minorPx` 以上離れる一番細かい間で引く */
205
+ function minorTicks(count: number, step: number, unitPx: number, majors: number[]): number[] {
206
+ const by = Array.from({ length: step - 1 }, (_, k) => k + 1).find((d) => step % d === 0 && d * unitPx >= LOOK.time.minorPx);
207
+ if (by === undefined) return [];
208
+ const out: number[] = [];
209
+ for (let u = by; u < count; u += by) if (!majors.includes(u)) out.push(u);
210
+ return out;
211
+ }
212
+
213
+ /** 段ごとの、段の始まりと終わりに針がいる境 */
214
+ function needleSteps(diagram: Diagram): [number, number][] {
215
+ let at = 0;
216
+ return diagram.steps.map((step) => {
217
+ const from = at;
218
+ for (const event of step.events) if (event.type === "now") at = Math.max(at, event.to + 1);
219
+ return [from, at];
220
+ });
221
+ }
222
+
223
+ export function layoutTime(diagram: Diagram, lang: NotationLang = "ja"): TimeLayout {
224
+ const T = LOOK.time;
225
+ const { margin, gap } = LOOK;
226
+ const R = LOOK.region;
227
+ const text = FIGURE_TEXT[lang];
228
+ const spec = diagram.time ?? { scale: { unit: "", length: "1s", count: 1 }, rows: [] };
229
+ const { scale } = spec;
230
+ const count = Math.max(1, scale.count);
231
+ const length = durationOf(scale.length);
232
+ const width = Math.max(T.width, stripNeed(diagram) + margin * 2);
233
+
234
+ // 印の列の名前を軸の左に置き、長い名前は軸を右へ寄せる
235
+ const nameRight = Math.max(0, ...spec.rows.map((r) => textWidth(r.name, TYPE.timeRow)));
236
+ const axisX = Math.max(T.axisX, margin + R.inset + nameRight + T.gutterGap);
237
+ const axisW = width - T.right - axisX;
238
+ const unit = axisW / count;
239
+
240
+ const colors = boxColors(diagram);
241
+ const rooms = slotRooms(diagram);
242
+ const regions: SceneRegion[] = [];
243
+ const boxes: TimeBox[] = [];
244
+ const edges: SceneEdge[] = [];
245
+ const wires: TimeWire[] = [];
246
+ const rowIds = new Map(spec.rows.map((r) => [r.id, r]));
247
+
248
+ // 拡大の帯
249
+ let zoom: TimeZoom | undefined;
250
+ let axisTop = margin;
251
+ if (spec.zoom) {
252
+ const { from, to } = spec.zoom;
253
+ const n = to - from + 1;
254
+ const colW = axisW / n;
255
+ const top = margin;
256
+ const headUnit = unitFor(to * length.seconds, length.unit);
257
+ const columns: TimeColumn[] = [];
258
+ for (let k = 0; k < n; k++) {
259
+ const u = from + k;
260
+ const x = axisX + k * colW;
261
+ const placed = diagram.boxes.map((b, j): TimeBox => {
262
+ const room = rooms.get(b.id);
263
+ const w = Math.max(boxWidth(diagram, b.id, false), slotBoxWidth(room, b.icon !== undefined, LOOK.box.padX));
264
+ const y = top + T.boxTop + j * (LOOK.box.h + T.boxGap);
265
+ const row = rowIds.get(b.id);
266
+ const box: TimeBox = {
267
+ id: b.id,
268
+ name: b.name,
269
+ ...(b.sub !== undefined ? { sub: b.sub } : {}),
270
+ ...(b.icon !== undefined ? { icon: b.icon } : {}),
271
+ color: colors.get(b.id) ?? "slate",
272
+ x: x + colW / 2 - w / 2,
273
+ y,
274
+ w,
275
+ h: LOOK.box.h,
276
+ cx: x + colW / 2,
277
+ cy: y + LOOK.box.h / 2,
278
+ ...(row ? { row: row.id } : {}),
279
+ ...(row?.empty?.includes(u) ? { empty: true } : {}),
280
+ };
281
+ placeSlot(box, room);
282
+ return box;
283
+ });
284
+ boxes.push(...placed);
285
+ const head = `${scale.unit} ${(scale.from ?? 0) + u}${text.headJoin}${timeText(u * length.seconds, headUnit, lang)}`;
286
+ columns.push({ unit: u, head, boxes: placed, x, y: top, w: colW, h: 0 });
287
+ }
288
+ const last = Math.max(top + T.boxTop, ...boxes.map((b) => b.y + b.h));
289
+ const bottom = last + T.zoomBottom;
290
+ for (const c of columns) c.h = bottom - top;
291
+ regions.push({
292
+ id: "zoom",
293
+ lines: [text.zoom],
294
+ note: `${n} ${scale.unit}`,
295
+ icon: "clock",
296
+ color: "blue",
297
+ x: margin,
298
+ y: top,
299
+ w: width - margin * 2,
300
+ h: bottom - top,
301
+ header: { x: margin + R.inset, y: top + R.inset, w: Math.max(R.icon, textWidth(text.zoom, TYPE.regionName)), h: R.nameY - R.inset + R.line },
302
+ });
303
+ zoom = { from, to, frame: { x: 0, y: 0, w: 0, h: 0 }, guides: [], columns, empty: text.empty, headY: top + T.head };
304
+ axisTop = bottom + T.zoomGap;
305
+ }
306
+
307
+ // 時間軸の帯の印の列と印
308
+ const rowsTop = axisTop + T.rowsTop;
309
+ const rows: TimeRowPlaced[] = spec.rows.map((r, k) => ({
310
+ id: r.id,
311
+ name: r.name,
312
+ // 色を書かない列は、同じ名札の箱の色にそろえる。印と拡大の帯の箱が同じ物だと見て分かるため
313
+ color: r.color ?? colors.get(r.id) ?? (COLOR_ORDER[k % COLOR_ORDER.length] as ColorKey),
314
+ x: axisX,
315
+ y: rowsTop + k * (T.row + T.rowGap),
316
+ w: axisW,
317
+ h: T.row,
318
+ }));
319
+ const rowsBottom = rows.length > 0 ? Math.max(...rows.map((r) => r.y + r.h)) : rowsTop;
320
+ const markW = Math.min(T.markMax, Math.max(T.markMin, unit * T.markRatio));
321
+ const marks: TimeMark[] = rows.flatMap((row, k) =>
322
+ Array.from({ length: count }, (_, u): TimeMark => ({
323
+ row: row.id,
324
+ unit: u,
325
+ empty: spec.rows[k]?.empty?.includes(u) === true,
326
+ color: row.color,
327
+ colors: [],
328
+ x: axisX + (u + 0.5) * unit - markW / 2,
329
+ y: row.y,
330
+ w: markW,
331
+ h: row.h,
332
+ })),
333
+ );
334
+ diagram.steps.forEach((step, s) =>
335
+ step.events.forEach((event, e) => {
336
+ if (event.type !== "mark") return;
337
+ for (const m of marks) if (m.row === event.row && m.unit >= event.from && m.unit <= event.to && !m.empty) m.colors.push({ step: s, event: e, color: event.color });
338
+ }),
339
+ );
340
+
341
+ // 拡大した範囲の枠と、枠から上の帯への点線
342
+ if (zoom) {
343
+ const frame = { x: axisX + zoom.from * unit - T.frame, y: rowsTop - T.frame, w: (zoom.to - zoom.from + 1) * unit + T.frame * 2, h: rowsBottom - rowsTop + T.frame * 2 };
344
+ const band = Math.max(...zoom.columns.map((c) => c.y + c.h));
345
+ zoom.frame = frame;
346
+ zoom.guides = [
347
+ [
348
+ [frame.x, frame.y],
349
+ [axisX, band],
350
+ ],
351
+ [
352
+ [frame.x + frame.w, frame.y],
353
+ [axisX + axisW, band],
354
+ ],
355
+ ];
356
+ }
357
+
358
+ // 節目
359
+ const pointCy = rowsBottom + T.point.drop;
360
+ const points: TimePointPlaced[] = (spec.points ?? []).map((p) => {
361
+ const changes: TimePointPlaced["changes"] = [];
362
+ diagram.steps.forEach((step, s) =>
363
+ step.events.forEach((event, e) => {
364
+ if (event.type === "swap" && event.box === p.id) changes.push({ step: s, event: e, text: event.text, ...(event.color ? { color: event.color } : {}) });
365
+ }),
366
+ );
367
+ const cx = axisX + (p.at + 0.5) * unit;
368
+ const tx = cx + T.point.text;
369
+ const w = Math.max(textWidth(p.id, TYPE.pointName), ...changes.map((c) => textWidth(c.text, TYPE.pointState)));
370
+ const top = pointCy + T.point.nameY - TYPE.pointName.size * 0.8;
371
+ const bottom = pointCy + T.point.stateY + TYPE.pointState.size * 0.2;
372
+ return { id: p.id, unit: p.at, cx, cy: pointCy, r: T.point.r, text: { x: tx, y: top, w, h: bottom - top }, changes };
373
+ });
374
+ const pointOf = new Map(points.map((p) => [p.id, p]));
375
+
376
+ // 拡大の帯の線と節目どうしの線
377
+ const colorAt = (id: string, step: number): ColorKey | undefined => {
378
+ const point = pointOf.get(id);
379
+ return point?.changes.filter((c) => c.step <= step && c.color).at(-1)?.color;
380
+ };
381
+ diagram.steps.forEach((step, s) =>
382
+ step.events.forEach((event, e) => {
383
+ if (event.type !== "edge") return;
384
+ if (event.at === undefined) {
385
+ const a = pointOf.get(event.from);
386
+ const b = pointOf.get(event.to);
387
+ if (!a || !b || a === b) return;
388
+ const right = b.cx > a.cx;
389
+ const x0 = right ? Math.max(a.cx + a.r, a.text.x + a.text.w + T.point.link) : a.cx - a.r - T.point.end;
390
+ const x1 = right ? b.cx - b.r - T.point.end : Math.min(b.cx - b.r, b.text.x + b.text.w + T.point.link);
391
+ const edge: SceneEdge = { step: s, event: e, from: event.from, to: event.to, points: [[x0, a.cy], [x1, b.cy]], color: event.carry.kind === "coin" ? "coin" : (colorAt(event.to, s) ?? "slate"), carry: event.carry };
392
+ if (event.carry.kind !== "none") edge.settle = [x1 - (right ? 1 : -1) * (LOOK.carrier.coinR + LOOK.edge.arrow), b.cy];
393
+ edges.push(edge);
394
+ return;
395
+ }
396
+ const wired = wire(event, zoom);
397
+ if (!wired) return;
398
+ const edge: SceneEdge = { step: s, event: e, from: event.from, to: event.to, points: wired.points, color: edgeColor(event, colors), carry: event.carry };
399
+ seat(edge, wired.from, wired.to, rooms);
400
+ edges.push(edge);
401
+ wires.push({ step: s, event: e, from: wired.from, to: wired.to, column: event.at, into: event.into ?? event.at });
402
+ }),
403
+ );
404
+
405
+ const layout: TimeLayout = {
406
+ kind: "time",
407
+ width,
408
+ height: 0,
409
+ regions,
410
+ boxes,
411
+ lifelines: [],
412
+ edges,
413
+ labels: [],
414
+ actions: [],
415
+ badges: [],
416
+ paths: [],
417
+ ends: [],
418
+ axis: { x: axisX, w: axisW, unit, count, line: 0 },
419
+ rows,
420
+ marks,
421
+ ticks: [],
422
+ minor: [],
423
+ periods: [],
424
+ points,
425
+ ...(zoom ? { zoom } : {}),
426
+ spans: [],
427
+ wires,
428
+ needle: { y1: rowsTop - T.needle.over, y2: rowsBottom + T.needle.over },
429
+ };
430
+
431
+ // 段の番号を置いてから、線の名前を番号と節目を避けて置く
432
+ const marksBottom = rowsBottom;
433
+ const named = diagram.steps.some((step) => step.events.some((e) => e.type === "edge" && e.at === undefined && e.label !== undefined));
434
+ // 節目の無い図は、印の下に針を進める段の番号を置く間を空ける
435
+ const { r: badgeR, inset } = LOOK.badge;
436
+ let y = points.length > 0 ? pointCy + T.point.r + (named ? T.point.room : T.point.plain) : marksBottom + (badgeR + inset) * 2;
437
+
438
+ // 範囲の括弧と囲み。括弧は消えていない括弧と重ならない段に置く
439
+ const spans: TimeSpanPlaced[] = [];
440
+ const events = diagram.steps.flatMap((step, s) => step.events.flatMap((event, e) => (event.type === "span" ? [{ s, e, event }] : [])));
441
+ for (const { s, e, event } of events) {
442
+ const kind = event.shape === "box" ? "box" : "bracket";
443
+ const later = events.find((o) => o.s > s && (o.event.shape === "box" ? "box" : "bracket") === kind && o.event.from <= event.to && event.from <= o.event.to);
444
+ const color: ColorKey = event.color ?? "slate";
445
+ const x0 = axisX + event.from * unit;
446
+ const x1 = axisX + (event.to + 1) * unit;
447
+ const base = { step: s, event: e, kind, from: event.from, to: event.to, text: event.text, color, ...(later ? { until: later.s } : {}) } as const;
448
+ if (kind === "box") {
449
+ const B = T.box;
450
+ const rect = { x: x0 - B.pad, y: rowsTop - B.pad, w: x1 - x0 + B.pad * 2, h: rowsBottom - rowsTop + B.pad * 2 };
451
+ const w = textWidth(event.text, TYPE.tag) + B.tagPadX * 2;
452
+ const textRect = { x: rect.x + B.tagX, y: rect.y - B.tagH / 2, w, h: B.tagH };
453
+ spans.push({ ...base, ...rect, textRect, textY: rect.y + LOOK.baseline.tag });
454
+ } else spans.push({ ...base, x: x0, y: 0, w: x1 - x0, h: T.bracket.tick, textRect: { x: 0, y: 0, w: 0, h: 0 }, textY: 0 });
455
+ }
456
+ layout.spans = spans;
457
+ layout.badges = badgesOf(diagram, layout, needleSteps(diagram));
458
+ layout.labels = labelsOf(diagram, layout);
459
+ y = Math.max(y, ...layout.labels.map((l) => l.y + l.h + LOOK.label.soft));
460
+
461
+ // 括弧を段に積む。同じ時刻に見える括弧と、字まで含めて重なる括弧は下の段へ送る
462
+ const lanes: TimeSpanPlaced[][] = [];
463
+ for (const span of spans.filter((x) => x.kind === "bracket")) {
464
+ const w = textWidth(span.text, TYPE.spanText);
465
+ const cx = Math.min(axisX + axisW - w / 2, Math.max(axisX + w / 2, span.x + span.w / 2));
466
+ const reach = { x: Math.min(span.x, cx - w / 2), w: Math.max(span.x + span.w, cx + w / 2) - Math.min(span.x, cx - w / 2) };
467
+ const clash = (other: TimeSpanPlaced): boolean => {
468
+ const seen = other.until === undefined || other.until > span.step;
469
+ const ox = Math.min(other.x, other.textRect.x);
470
+ const ow = Math.max(other.x + other.w, other.textRect.x + other.textRect.w) - ox;
471
+ return seen && reach.x < ox + ow && ox < reach.x + reach.w;
472
+ };
473
+ let lane = lanes.findIndex((list) => !list.some(clash));
474
+ if (lane < 0) {
475
+ lanes.push([]);
476
+ lane = lanes.length - 1;
477
+ }
478
+ (lanes[lane] as TimeSpanPlaced[]).push(span);
479
+ span.y = y + T.bracket.gap + lane * T.bracket.lane;
480
+ span.textY = span.y + T.bracket.tick + T.bracket.text;
481
+ span.textRect = textBox(span.text, cx, span.textY, TYPE.spanText, "middle");
482
+ }
483
+ if (lanes.length > 0) y = Math.max(...spans.filter((x) => x.kind === "bracket").map((x) => x.textRect.y + x.textRect.h));
484
+
485
+ // 時刻の目盛りの線と字と区切り
486
+ const axisLine = y + T.axisGap;
487
+ layout.axis.line = axisLine;
488
+ const majors = majorTicks(count, spec.period?.length, unit);
489
+ const tickY = axisLine + T.tickY;
490
+ const tickUnit = unitFor(count * length.seconds, length.unit);
491
+ layout.ticks = majors.at.map((at) => {
492
+ const label = timeText(at * length.seconds, tickUnit, lang);
493
+ const w = textWidth(label, TYPE.timeTick);
494
+ const x = axisX + at * unit;
495
+ const left = at === 0 ? x : at === count ? x - w : Math.min(axisX + axisW - w, Math.max(axisX, x - w / 2));
496
+ return { at, x, text: label, left, y: tickY };
497
+ });
498
+ layout.minor = minorTicks(count, majors.step, unit, majors.at);
499
+ let bottom = tickY + TYPE.timeTick.size * 0.2;
500
+ if (spec.period) {
501
+ const P = spec.period;
502
+ const list: TimePeriodPlaced[] = [];
503
+ for (let index = 0, from = 0; from < count; index++, from += P.length) {
504
+ const to = Math.min(count, from + P.length) - 1;
505
+ const name = `${P.name} ${(P.from ?? 0) + index}`;
506
+ const first = (scale.from ?? 0) + from;
507
+ const range = `${scale.unit} ${text.range(String(first), String((scale.from ?? 0) + to))}`;
508
+ list.push({ index, from, to, name, range, x: axisX + from * unit, y: axisLine, w: (to - from + 1) * unit, h: 0, nameY: tickY, rangeY: tickY + T.rangeY });
509
+ }
510
+ // 区切りの名前が時刻の字に掛かる時は、時刻の字の下の行へ送る
511
+ const tickRects = layout.ticks.map((t) => textBox(t.text, t.left, t.y, TYPE.timeTick));
512
+ const clash = list.some((p) => {
513
+ const r = textBox(p.name, p.x + p.w / 2, p.nameY, TYPE.timePeriod, "middle");
514
+ return tickRects.some((t) => r.x < t.x + t.w + T.nameGap && t.x < r.x + r.w + T.nameGap);
515
+ });
516
+ for (const p of list) {
517
+ if (clash) {
518
+ p.nameY = tickY + T.rangeY + 2;
519
+ p.rangeY = p.nameY + T.rangeY;
520
+ }
521
+ p.h = p.rangeY + TYPE.timeRange.size * 0.2 - axisLine;
522
+ }
523
+ layout.periods = list;
524
+ bottom = Math.max(bottom, ...list.map((p) => p.rangeY + TYPE.timeRange.size * 0.2));
525
+ }
526
+ const axisBottom = bottom + T.bottom;
527
+ regions.push({ id: "axis", lines: [], color: "slate", x: margin, y: axisTop, w: width - margin * 2, h: axisBottom - axisTop, header: { x: margin + R.inset, y: axisTop + R.inset, w: 0, h: 0 } });
528
+
529
+ const strip = layoutStrip(diagram, margin, axisBottom + gap, width - margin * 2);
530
+ if (strip) layout.strip = strip;
531
+ layout.height = (strip ? strip.y + strip.h : axisBottom) + margin;
532
+ // 中身の帯だけを書き換える段の番号は帯の左上に置くので、帯を置いた後に決め直す
533
+ layout.badges = badgesOf(diagram, layout, needleSteps(diagram));
534
+ return layout;
535
+ }
536
+
537
+ /**
538
+ * 拡大の帯の線。`at` の列の箱から、`into` の列 (無ければ同じ列) の箱へ引く。
539
+ * 同じ列で隣り合う箱は縦に結び、間に箱を挟む時は列の右を回る。別の列の箱は、向き合う縁どうしを真っ直ぐ結ぶ
540
+ */
541
+ function wire(event: EdgeEvent, zoom: TimeZoom | undefined): { points: Point[]; from: TimeBox; to: TimeBox } | undefined {
542
+ if (!zoom || event.at === undefined) return undefined;
543
+ const into = event.into ?? event.at;
544
+ const fromColumn = zoom.columns.find((c) => c.unit === event.at);
545
+ const toColumn = zoom.columns.find((c) => c.unit === into);
546
+ const from = fromColumn?.boxes.find((b) => b.id === event.from);
547
+ const to = toColumn?.boxes.find((b) => b.id === event.to);
548
+ if (!fromColumn || !toColumn || !from || !to || from === to) return undefined;
549
+ const jf = fromColumn.boxes.indexOf(from);
550
+ const jt = toColumn.boxes.indexOf(to);
551
+ const down = jt > jf;
552
+ if (fromColumn === toColumn) {
553
+ if (Math.abs(jt - jf) === 1) return { from, to, points: [[from.cx, down ? from.y + from.h + 1 : from.y - 1], [to.cx, down ? to.y - 1 : to.y + to.h + 1]] };
554
+ const lane = Math.min(fromColumn.x + fromColumn.w - LOOK.gap, Math.max(from.x + from.w, to.x + to.w) + LOOK.gap);
555
+ return {
556
+ from,
557
+ to,
558
+ points: [
559
+ [from.x + from.w + 1, from.cy],
560
+ [lane, from.cy],
561
+ [lane, to.cy],
562
+ [to.x + to.w + 1, to.cy],
563
+ ],
564
+ };
565
+ }
566
+ const right = toColumn.x > fromColumn.x;
567
+ if (jf === jt) return { from, to, points: [[right ? from.x + from.w + 1 : from.x - 1, from.cy], [right ? to.x - 1 : to.x + to.w + 1, to.cy]] };
568
+ const fx = from.cx + ((right ? 1 : -1) * from.w) / 4;
569
+ const tx = to.cx - ((right ? 1 : -1) * to.w) / 4;
570
+ return { from, to, points: [[fx, down ? from.y + from.h + 1 : from.y - 1], [tx, down ? to.y - 1 : to.y + to.h + 1]] };
571
+ }
572
+
573
+ /** 拡大の帯の線の運ぶ物を、出る列の箱の置き場で待たせ、受ける列の箱の置き場に留める。同じ名札の箱が列ごとに在るので、箱を 1 つずつ渡す */
574
+ function seat(edge: SceneEdge, from: TimeBox, to: TimeBox, rooms: ReturnType<typeof slotRooms>): void {
575
+ const arrive = { ...edge };
576
+ seatCarriers([arrive], new Map([[edge.to, to]]), rooms);
577
+ const leave = { ...edge };
578
+ seatCarriers([leave], new Map([[edge.from, from]]), rooms);
579
+ if (arrive.settle) edge.settle = arrive.settle;
580
+ if (leave.wait) edge.wait = leave.wait;
581
+ }
582
+
583
+ /**
584
+ * 段の番号。線を引く段は段で最初に引く線の上に置き、運ぶ物が線の始まりで待つ時は運ぶ物を避けて進める。
585
+ * 線の無い段は、針を進める段なら針が進む範囲の真ん中の印と節目の間に、範囲の括弧なら括弧の左に、範囲の囲みなら囲みの左上の角に、
586
+ * 節目の状態を変える段なら節目の丸の左に、印の色を変える段なら印の列の上に、中身の帯だけを書き換える段なら帯の左上に置く。
587
+ * 何も起きない段は前の段の番号と同じ所に置いて数字を入れ替える
588
+ */
589
+ function badgesOf(diagram: Diagram, layout: TimeLayout, needle: [number, number][]): SceneBadge[] {
590
+ const { r, inset } = LOOK.badge;
591
+ const { axis } = layout;
592
+ const taken: Point[] = [];
593
+ const out: SceneBadge[] = [];
594
+ const top = Math.min(...layout.rows.map((row) => row.y), layout.needle.y1 + LOOK.time.needle.over);
595
+ const bottom = Math.max(...layout.rows.map((row) => row.y + row.h), top);
596
+ // 節目があれば印と節目の丸の間に、無ければ印の下に空けた間に置く
597
+ const between = layout.points[0] ? (bottom + layout.points[0].cy - layout.points[0].r) / 2 : bottom + r + inset;
598
+ diagram.steps.forEach((step, s) => {
599
+ const push = (p: Point, color: ColorKey): void => {
600
+ taken.push(p);
601
+ out.push({ step: s, x: p[0], y: p[1], color });
602
+ };
603
+ const edge = layout.edges.filter((e) => e.step === s).sort((a, b) => a.event - b.event)[0];
604
+ if (edge) {
605
+ // 線の始まりで待つ運ぶ物 (置き場を持たない節目から出る物) を、番号で隠さない
606
+ const waits: Point[] = edge.carry.kind !== "none" && !edge.wait ? [edge.points[0] as Point] : [];
607
+ const others = layout.edges.filter((e) => e !== edge).map((e) => e.points);
608
+ push(badgeOnPath(edge.points, [...taken, ...waits], others), edge.color);
609
+ return;
610
+ }
611
+ const [from, to] = needle[s] ?? [0, 0];
612
+ if (to > from) {
613
+ let x = axis.x + ((from + to) / 2) * axis.unit;
614
+ // 節目から印へ下ろす点線の上に置かない
615
+ const near = layout.points.find((p) => Math.abs(p.cx - x) < r + inset);
616
+ if (near) x = near.cx + r + inset * 2;
617
+ push([x, between], "slate");
618
+ return;
619
+ }
620
+ for (const event of step.events) {
621
+ const spot = spotOf(event, s, layout);
622
+ if (spot) {
623
+ push(spot.at, spot.color);
624
+ return;
625
+ }
626
+ }
627
+ if (layout.strip && step.events.some((e) => e.type === "strip")) {
628
+ out.push({ step: s, x: layout.strip.x + inset, y: layout.strip.y + inset, color: "slate" });
629
+ return;
630
+ }
631
+ const before = out[out.length - 1];
632
+ out.push(before ? { ...before, step: s } : { step: s, x: axis.x - r - inset, y: top, color: "slate" });
633
+ });
634
+ return replaceSameSpot(out);
635
+ }
636
+
637
+ /** 線と針の無い段の出来事 1 つで、番号を置く所。置けない出来事は `undefined` */
638
+ function spotOf(event: DiagramEvent, step: number, layout: TimeLayout): { at: Point; color: ColorKey } | undefined {
639
+ const { r, inset } = LOOK.badge;
640
+ if (event.type === "span") {
641
+ const span = layout.spans.find((x) => x.step === step && x.from === event.from && x.to === event.to && x.text === event.text);
642
+ if (!span) return undefined;
643
+ if (span.kind === "box") return { at: [span.x, span.y], color: span.color };
644
+ return { at: [span.x - r - inset, span.y + span.h / 2], color: span.color };
645
+ }
646
+ if (event.type === "swap") {
647
+ const point = layout.points.find((p) => p.id === event.box);
648
+ if (point) return { at: [point.cx - point.r - inset - r, point.cy], color: event.color ?? "slate" };
649
+ }
650
+ if (event.type === "mark") {
651
+ const row = layout.rows.find((x) => x.id === event.row);
652
+ const top = Math.min(...layout.rows.map((x) => x.y));
653
+ if (row) return { at: [layout.axis.x + ((event.from + event.to + 1) / 2) * layout.axis.unit, top - r - inset], color: event.color };
654
+ }
655
+ return undefined;
656
+ }
657
+
658
+ /**
659
+ * 線の名前。節目どうしの線は線の下に、拡大の帯の線は線の右に置き、節目の丸と拡大の帯の箱を離し、
660
+ * 節目の字と列の上の字と同じ段の線の名前と、同じ時刻に見えている段の番号を避ける
661
+ */
662
+ function labelsOf(diagram: Diagram, layout: TimeLayout): SceneLabel[] {
663
+ const labels: SceneLabel[] = [];
664
+ const circles: Rect[] = layout.points.map((p) => ({ x: p.cx - p.r, y: p.cy - p.r, w: p.r * 2, h: p.r * 2 }));
665
+ const texts: Rect[] = layout.points.map((p) => p.text);
666
+ const heads: Rect[] = (layout.zoom?.columns ?? []).map((c) => textBox(c.head, c.x + c.w / 2, layout.zoom?.headY ?? 0, TYPE.timeHead, "middle"));
667
+ for (const edge of layout.edges) {
668
+ const source = diagram.steps[edge.step]?.events[edge.event];
669
+ if (source?.type !== "edge" || source.label === undefined) continue;
670
+ const seen = layout.badges.filter((b) => b.step <= edge.step).map((b) => badgeRect([b.x, b.y]));
671
+ const side = source.labelSide ?? (source.at === undefined ? "below" : undefined);
672
+ labels.push(
673
+ placeLabel(
674
+ { step: edge.step, event: edge.event, text: source.label, points: edge.points, color: edge.color, ...(side ? { side } : {}), flip: source.at !== undefined },
675
+ { hard: [...circles, ...layout.boxes], soft: [...texts, ...heads, ...labels.filter((l) => l.step === edge.step)], touch: seen },
676
+ ),
677
+ );
678
+ }
679
+ return labels;
680
+ }