@cardenelabs/dragon 0.37.0 → 0.40.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 (48) hide show
  1. package/README.md +38 -1
  2. package/dist/cli.cjs +2403 -550
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +2408 -555
  5. package/dist/cli.js.map +1 -1
  6. package/dist/export.cjs +2252 -537
  7. package/dist/export.cjs.map +1 -1
  8. package/dist/export.d.cts +3 -1
  9. package/dist/export.d.ts +3 -1
  10. package/dist/export.js +2257 -542
  11. package/dist/export.js.map +1 -1
  12. package/dist/index.cjs +2387 -495
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +11 -154
  15. package/dist/index.d.ts +11 -154
  16. package/dist/index.js +2387 -496
  17. package/dist/index.js.map +1 -1
  18. package/dist/ink-B_7OXxtb.d.cts +360 -0
  19. package/dist/ink-B_7OXxtb.d.ts +360 -0
  20. package/dist/player.global.js +2 -2
  21. package/package.json +1 -1
  22. package/src/cli.ts +9 -0
  23. package/src/export/index.ts +4 -1
  24. package/src/field-messages.ts +8 -0
  25. package/src/figure-text.ts +28 -0
  26. package/src/index.ts +3 -0
  27. package/src/layout/architecture.ts +123 -44
  28. package/src/layout/git.ts +728 -0
  29. package/src/layout/measure.ts +10 -0
  30. package/src/layout/scene.ts +300 -19
  31. package/src/layout/sequence.ts +29 -11
  32. package/src/layout/state.ts +82 -62
  33. package/src/look/values.ts +57 -4
  34. package/src/messages.ts +47 -4
  35. package/src/parser.ts +142 -7
  36. package/src/player.ts +44 -0
  37. package/src/printer.ts +16 -4
  38. package/src/render/git.ts +161 -0
  39. package/src/render/ink.ts +104 -0
  40. package/src/render/parts.ts +103 -36
  41. package/src/render/svg.ts +63 -15
  42. package/src/schema.ts +47 -13
  43. package/src/schemas/diagram.schema.json +75 -8
  44. package/src/schemas/validate-diagram.js +1 -1
  45. package/src/timeline.ts +18 -3
  46. package/src/words.ts +19 -3
  47. package/dist/schema-B2MTRv66.d.cts +0 -133
  48. package/dist/schema-B2MTRv66.d.ts +0 -133
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cardenelabs/dragon",
3
- "version": "0.37.0",
3
+ "version": "0.40.0",
4
4
  "description": "Dragon — 動く図を、人は行ごとの記法で、AI は JSON で書く。時系列図と構成図を段ごとに動かし、mp4・GIF・HTML・PNG に書き出す。",
5
5
  "license": "MIT",
6
6
  "author": "cardene777",
package/src/cli.ts CHANGED
@@ -2,6 +2,8 @@
2
2
  /**
3
3
  * `dragon export <図の file>` の命令。原本の JSON (`.json`) か記法 (`.dragon`) を読み、mp4、GIF、HTML、PNG を書き出す。
4
4
  * 書き出した file の path を 1 行ずつ出す。
5
+ * 図に字の重なりがある時は、書き出したうえで重なりを段と文で 1 件 1 行ずつ標準エラーに出し、終わり方は 0 のままにする (#3178)。
6
+ * 重なりは描けない誤りではなく、止めると避けられない重なりを持つ図を書き出せなくなるため。
5
7
  *
6
8
  * 使い方の文と誤りの文は、図の中の字と同じ言葉で出す (#3003)。`--lang` を渡せばその言葉、無ければ日本語。
7
9
  * dragon記法の語は英語だけで file から言葉が決まらないため、記法の file も JSON の原本と同じに扱う (#3137)。
@@ -12,6 +14,7 @@ import { parseArgs } from "node:util";
12
14
  import { type ExportFormat, exportDiagram, FORMATS } from "./export/index";
13
15
  import { PALETTES, type Theme } from "./look/values";
14
16
  import { parseNotation } from "./parser";
17
+ import { describeOverlap } from "./render/ink";
15
18
  import type { NotationLang } from "./words";
16
19
 
17
20
  const OPTIONS = {
@@ -43,6 +46,8 @@ interface CliText {
43
46
  badValue: (option: string, value: string, allowed: string) => string;
44
47
  /** 設定ごとの許す値の言い方 */
45
48
  allowed: { lang: string; theme: string; positive: string; format: string };
49
+ /** 字の重なりの 1 行。`step` は 1 から数える */
50
+ overlap: (step: number, text: string) => string;
46
51
  }
47
52
 
48
53
  /** 命令が出す文。英語は日本語の文をそのまま英語にする */
@@ -68,6 +73,7 @@ const CLI_TEXT: Record<NotationLang, CliText> = {
68
73
  cannotWrite: (path, detail) => `書き出せない: ${path} (${detail})`,
69
74
  badValue: (option, value, allowed) => `使えない値: ${option} ${value} (${allowed})`,
70
75
  allowed: { lang: "ja か en", theme: "light か dark", positive: "0 より大きい数", format: `${FORMATS.join(" / ")} を , で区切る` },
76
+ overlap: (step, text) => `段 ${step}: ${text}`,
71
77
  },
72
78
  en: {
73
79
  usage: [
@@ -90,6 +96,7 @@ const CLI_TEXT: Record<NotationLang, CliText> = {
90
96
  cannotWrite: (path, detail) => `Cannot write: ${path} (${detail})`,
91
97
  badValue: (option, value, allowed) => `Invalid value: ${option} ${value} (${allowed})`,
92
98
  allowed: { lang: "ja or en", theme: "light or dark", positive: "a number above 0", format: `${FORMATS.join(" / ")} separated by ,` },
99
+ overlap: (step, text) => `Step ${step}: ${text}`,
93
100
  },
94
101
  };
95
102
 
@@ -224,6 +231,8 @@ async function main(argv: string[]): Promise<number> {
224
231
  throw error instanceof Error ? error : new Error(String(error));
225
232
  }
226
233
  for (const path of Object.values(result.files)) console.log(path);
234
+ const said = lang ?? "ja";
235
+ for (const overlap of result.overlaps) console.error(CLI_TEXT[said].overlap(overlap.step + 1, describeOverlap(overlap, said)));
227
236
  return 0;
228
237
  }
229
238
 
@@ -10,6 +10,7 @@ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
10
10
  import { join } from "node:path";
11
11
  import { paletteVars, resolvePalette, type Theme } from "../look/values";
12
12
  import { BUTTON_TEXT, stepNo } from "../player";
13
+ import type { Overlap } from "../render/ink";
13
14
  import { drawSvg, type Rendered, renderDiagram } from "../render/svg";
14
15
  import type { ViewMode } from "../schema";
15
16
  import { chooseView } from "../view";
@@ -48,6 +49,8 @@ export interface ExportResult {
48
49
  /** 動画のコマの大きさ (CSS の px)。撮る画素はこの 2 倍 */
49
50
  width: number;
50
51
  height: number;
52
+ /** 段ごとの止め絵で同時に見えている字の重なり (#3178)。命令はこれを標準エラーに出す */
53
+ overlaps: Overlap[];
51
54
  }
52
55
 
53
56
  /** 書き出せる形。命令が `--format` の値を確かめる時にも使う */
@@ -120,7 +123,7 @@ export async function exportDiagram(input: unknown, options: ExportOptions): Pro
120
123
  }
121
124
  }
122
125
  const files = writeOutputs(options.outDir, options.name ?? "diagram", outputs);
123
- return { files, view, frames, ...sizeOf(videoSvg) };
126
+ return { files, view, frames, ...sizeOf(videoSvg), overlaps: rendered.overlaps };
124
127
  }
125
128
 
126
129
  /**
@@ -34,6 +34,10 @@ export interface FieldMessages {
34
34
  not: (allowed: Allowed | undefined) => string;
35
35
  /** 状態遷移図の箱の名札に、始まりと終わりの印の名前 (`names`) を書いた */
36
36
  reserved: (names: readonly string[]) => string;
37
+ /** `kind` の図だけが書ける出来事の種類 (`types`) を、別の種類の図に書いた (#3164) */
38
+ kindOnly: (types: readonly string[], kind: string) => string;
39
+ /** 16 進の字を `min` から `max` 字で書く決まり (commit の hash、#3164) */
40
+ hex: (min: number, max: number) => string;
37
41
  /** 選べる決まりがどれも欄が足りない時の、足りない欄。それ以外の時は空 */
38
42
  anyOf: (fields: readonly string[]) => string;
39
43
  oneOf: string;
@@ -77,6 +81,8 @@ const ja: FieldMessages = {
77
81
  const: (value) => `${value} にする`,
78
82
  not: (allowed) => (allowed ? `${allowed.field} の欄は kind が ${allowed.kind} の時だけ書ける` : "この欄の組み合わせは書けない"),
79
83
  reserved: (names) => `${names.join(" と ")} は状態遷移図の始まりと終わりの印の名前で、箱の名札に使えない`,
84
+ kindOnly: (types, kind) => `${types.join(" と ")} の出来事は kind が ${kind} の時だけ書ける`,
85
+ hex: (min, max) => `0 から 9 と a から f の字で ${min} から ${max} 字にする`,
80
86
  anyOf: (fields) =>
81
87
  fields.length > 0 ? `${fields.join(" か ")} の${fields.length === 2 ? "どちらか" : "どれか"}の欄が要る` : "書ける形のどれにも合わない",
82
88
  oneOf: "書ける形のどれか 1 つだけに合わせる",
@@ -99,6 +105,8 @@ const en: FieldMessages = {
99
105
  const: (value) => `Use ${value}`,
100
106
  not: (allowed) => (allowed ? `The ${allowed.field} field is allowed only when kind is ${allowed.kind}` : "This combination of fields is not allowed"),
101
107
  reserved: (names) => `${names.join(" and ")} name the start and end marks of a state diagram and cannot be box ids`,
108
+ kindOnly: (types, kind) => `${types.join(" and ")} events are allowed only when kind is ${kind}`,
109
+ hex: (min, max) => `Use ${min} to ${max} characters of 0-9 and a-f`,
102
110
  anyOf: (fields) => (fields.length > 0 ? `Write one of the ${fields.join(" or ")} fields` : "Does not match any of the allowed shapes"),
103
111
  oneOf: "Match exactly one of the allowed shapes",
104
112
  discriminator: (tag, values) => `${tag} is one of ${values.join(" / ")}`,
@@ -27,8 +27,22 @@ export interface FigureText {
27
27
  /** 状態遷移図の始まりと終わりの印の字 */
28
28
  start: string;
29
29
  end: string;
30
+ /** 字の重なりを知らせる文 (#3178)。段の番号の呼び方、字の囲み方、2 つの字の重なり、線が字を横切る所 */
31
+ badgeName: (no: string) => string;
32
+ quoted: (text: string) => string;
33
+ /** 書き手が書いていない図の部品の呼び方 (#3184)。箱 `box` の絵柄と、運ぶ物の硬貨と封筒 */
34
+ iconOf: (box: string) => string;
35
+ coin: string;
36
+ envelope: string;
37
+ textsOverlap: (a: string, b: string) => string;
38
+ lineCrosses: (from: string, to: string, text: string) => string;
30
39
  }
31
40
 
41
+ /** 英数字で終わる語の後ろに空白を置く。「段の番号 1 と」のように、数と仮名の間を空けて読みやすくする */
42
+ const spaced = (word: string): string => (/[0-9A-Za-z]$/u.test(word) ? `${word} ` : word);
43
+ /** 英語の文の頭を大文字にする */
44
+ const capital = (text: string): string => text.charAt(0).toUpperCase() + text.slice(1);
45
+
32
46
  export const FIGURE_TEXT: Record<NotationLang, FigureText> = {
33
47
  ja: {
34
48
  cannotDraw: (detail) => `図を描けない: ${detail}`,
@@ -44,6 +58,13 @@ export const FIGURE_TEXT: Record<NotationLang, FigureText> = {
44
58
  trail: "通った状態",
45
59
  start: "始まり",
46
60
  end: "終わり",
61
+ badgeName: (no) => `段の番号 ${no}`,
62
+ quoted: (text) => `「${text}」`,
63
+ iconOf: (box) => `「${box} の絵柄」`,
64
+ coin: "「硬貨」",
65
+ envelope: "「封筒」",
66
+ textsOverlap: (a, b) => `${spaced(a)}と${spaced(b)}が重なる`,
67
+ lineCrosses: (from, to, text) => `線 ${from} → ${to} が${spaced(text)}を横切る`,
47
68
  },
48
69
  en: {
49
70
  cannotDraw: (detail) => `Cannot draw the diagram: ${detail}`,
@@ -59,5 +80,12 @@ export const FIGURE_TEXT: Record<NotationLang, FigureText> = {
59
80
  trail: "States passed",
60
81
  start: "Start",
61
82
  end: "End",
83
+ badgeName: (no) => `step number ${no}`,
84
+ quoted: (text) => `"${text}"`,
85
+ iconOf: (box) => `the icon of "${box}"`,
86
+ coin: "the coin",
87
+ envelope: "the envelope",
88
+ textsOverlap: (a, b) => capital(`${a} and ${b} overlap`),
89
+ lineCrosses: (from, to, text) => `The line ${from} → ${to} crosses ${text}`,
62
90
  },
63
91
  };
package/src/index.ts CHANGED
@@ -18,6 +18,8 @@ export {
18
18
  type Diagram,
19
19
  type DiagramEvent,
20
20
  type FieldError,
21
+ type GitBranch,
22
+ type GitCommit,
21
23
  type LabelSide,
22
24
  type Region,
23
25
  type StatePath,
@@ -48,6 +50,7 @@ export { type Family, FONTS } from "./look/fonts";
48
50
  export { type ColorKey, DEFAULT_PALETTE, type Palette, PALETTES, READABLE_PX, resolvePalette, type Theme } from "./look/values";
49
51
  export { mountDiagram, type Player, type PlayerOptions } from "./player";
50
52
  export { ICONS } from "./render/icons";
53
+ export { describeOverlap, type InkPart, type Overlap, type OverlapSpot } from "./render/ink";
51
54
  export { iconSvg } from "./render/parts";
52
55
  export { type Rendered, type RenderOptions, renderDiagram } from "./render/svg";
53
56
  export type { CarrierTime, EdgeTime, EventTime, LabelTime, Span, StateTime, Timeline } from "./timeline";
@@ -11,6 +11,7 @@ import type { Diagram, LabelSide, Region } from "../schema";
11
11
  import { textWidth } from "./measure";
12
12
  import {
13
13
  badgeOnPath,
14
+ badgeRect,
14
15
  boxColors,
15
16
  boxWidth,
16
17
  cornerBadge,
@@ -18,16 +19,26 @@ import {
18
19
  edgesOf,
19
20
  labelStyle,
20
21
  type Layout,
22
+ lineBadges,
23
+ LOOP_ROOM,
24
+ loopBadge,
25
+ loopLabelBase,
26
+ loopUnder,
27
+ replaceSameSpot,
21
28
  layoutStrip,
22
29
  type Point,
23
30
  placeLabel,
31
+ placeSlot,
24
32
  type Rect,
25
33
  regionColors,
26
34
  type SceneBox,
27
35
  type SceneEdge,
28
36
  type SceneLabel,
29
37
  type SceneRegion,
38
+ seatCarriers,
30
39
  shiftContent,
40
+ slotBoxWidth,
41
+ slotRooms,
31
42
  stripNeed,
32
43
  } from "./scene";
33
44
 
@@ -156,7 +167,9 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
156
167
 
157
168
  // 列の幅と列の間。隣の列を横に結ぶ名前のある線は、名前が収まるまで間を広げる (広げすぎる時は脇へ寄せる)
158
169
  const columnCount = Math.max(1, ...[...slots.values()].map((s) => s.col + 1));
159
- const widths = new Map(diagram.boxes.map((b) => [b.id, boxWidth(diagram, b.id, true)]));
170
+ // 運ぶ物を出し入れする箱は、絵柄の横に置き場を並べられる幅にする (#3176)
171
+ const carriedIn = slotRooms(diagram);
172
+ const widths = new Map(diagram.boxes.map((b) => [b.id, Math.max(boxWidth(diagram, b.id, true), slotBoxWidth(carriedIn.get(b.id), b.icon !== undefined, B.padX))]));
160
173
  const colW = Array.from({ length: columnCount }, (_, c) => Math.max(B.minW, ...[...slots].filter(([, s]) => s.col === c).map(([id]) => widths.get(id) ?? B.minW)));
161
174
  const between = Array.from({ length: Math.max(0, columnCount - 1) }, () => A.columnGap as number);
162
175
  for (const { edge } of edges) {
@@ -173,6 +186,14 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
173
186
  for (let c = 0; c < columnCount; c++) colLeft.push(c === 0 ? margin + (headerW > 0 ? headerW : R.pad) : (colLeft[c - 1] as number) + (colW[c - 1] as number) + (between[c - 1] as number));
174
187
  const center = (c: number): number => (colLeft[c] as number) + (colW[c] as number) / 2;
175
188
 
189
+ // 同じ箱へ戻る線は箱の下の輪で描くので、輪を持つ箱の行の下は、輪とその下の名前が収まるだけ空ける (#3186)
190
+ const looped = new Set(edges.filter(({ edge }) => edge.from === edge.to).map(({ edge }) => edge.from));
191
+ const loopRows = new Set([...looped].flatMap((id) => {
192
+ const slot = slots.get(id);
193
+ return slot ? [`${slot.group}:${slot.row}`] : [];
194
+ }));
195
+ const loopRoom = (g: number, row: number): number => (loopRows.has(`${g}:${row}`) ? LOOP_ROOM : 0);
196
+
176
197
  // 帯を上から積む
177
198
  const boxes: SceneBox[] = [];
178
199
  const bands: { group: number; y: number; h: number; rows: number }[] = [];
@@ -181,12 +202,15 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
181
202
  const rows = Math.max(1, ...group.members.map((id) => (slots.get(id)?.row ?? 0) + 1));
182
203
  const room = rooms[g] as Room;
183
204
  const top = cursor + R.pad + room.top;
205
+ // 行の上端。輪を持つ行の下は、行の間に輪の分を足す
206
+ const rowTop: number[] = [0];
207
+ for (let r = 1; r < rows; r++) rowTop.push((rowTop[r - 1] as number) + B.h + A.rowGap + loopRoom(g, r - 1));
184
208
  for (const id of group.members) {
185
209
  const slot = slots.get(id) as Slot;
186
210
  const source = diagram.boxes.find((b) => b.id === id);
187
211
  const w = widths.get(id) ?? B.minW;
188
212
  const cx = center(slot.col);
189
- const y = top + slot.row * (B.h + A.rowGap);
213
+ const y = top + (rowTop[slot.row] as number);
190
214
  boxes.push({
191
215
  id,
192
216
  name: source?.name ?? id,
@@ -201,32 +225,41 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
201
225
  cy: y + B.h / 2,
202
226
  });
203
227
  }
204
- const contentBottom = top + rows * B.h + (rows - 1) * A.rowGap;
228
+ const contentBottom = top + (rowTop[rows - 1] as number) + B.h + loopRoom(g, rows - 1);
205
229
  const header = headers[g];
206
230
  const h = Math.max(contentBottom + R.pad + room.bottom - cursor, header ? header.h + R.inset * 2 : 0, group.region ? R.minH : 0);
207
231
  bands.push({ group: g, y: cursor, h, rows });
208
232
  cursor += h + R.gap;
209
233
  });
210
234
  const bandsBottom = cursor - R.gap;
235
+ for (const box of boxes) placeSlot(box, carriedIn.get(box.id));
211
236
 
212
237
  const byId = new Map(boxes.map((b) => [b.id, b]));
213
238
  const bandOf = (id: string) => bands[slots.get(id)?.group ?? 0] as (typeof bands)[number];
239
+ /** 折れ線のどれかの区間が、四角を `pad` だけ広げた所に掛かる */
240
+ const crosses = (points: Point[], rect: Rect, pad: number): boolean => {
241
+ for (let i = 1; i < points.length; i++) {
242
+ const [x1, y1] = points[i - 1] as Point;
243
+ const [x2, y2] = points[i] as Point;
244
+ if (Math.min(x1, x2) <= rect.x + rect.w + pad && Math.max(x1, x2) >= rect.x - pad && Math.min(y1, y2) <= rect.y + rect.h + pad && Math.max(y1, y2) >= rect.y - pad) return true;
245
+ }
246
+ return false;
247
+ };
248
+ // 輪を持つ箱の下の、輪と名前の置き場。ほかの線は、その箱から出る線と入る線も含めてここを通さない (#3186)
249
+ const loopZones: Rect[] = [...looped].flatMap((id) => {
250
+ const box = byId.get(id);
251
+ return box ? [{ x: box.x, y: box.y + box.h, w: box.w, h: LOOP_ROOM }] : [];
252
+ });
253
+ const onLoop = (points: Point[]): boolean => loopZones.some((zone) => crosses(points, zone, 0));
214
254
  const blocked = (points: Point[], a: string, b: string): boolean =>
215
- boxes.some((box) => {
216
- if (box.id === a || box.id === b) return false;
217
- const pad = LOOK.label.search;
218
- for (let i = 1; i < points.length; i++) {
219
- const [x1, y1] = points[i - 1] as Point;
220
- const [x2, y2] = points[i] as Point;
221
- if (Math.min(x1, x2) <= box.x + box.w + pad && Math.max(x1, x2) >= box.x - pad && Math.min(y1, y2) <= box.y + box.h + pad && Math.max(y1, y2) >= box.y - pad) return true;
222
- }
223
- return false;
224
- });
225
- // 箱の下 (上) の、次の行か次の帯との間の真ん中
255
+ boxes.some((box) => box.id !== a && box.id !== b && crosses(points, box, LOOK.label.search)) || onLoop(points);
256
+ // 箱の下 (上) の、次の行か次の帯との間の真ん中。箱の下に輪が在る時は、輪と名前の下を通す (#3186)
226
257
  const laneBelow = (id: string): number => {
227
258
  const box = byId.get(id) as SceneBox;
228
259
  const band = bandOf(id);
229
- return (slots.get(id)?.row ?? 0) < band.rows - 1 ? box.y + box.h + A.rowGap / 2 : Math.min(box.y + box.h + R.pad / 2, band.y + band.h - LOOK.edge.inset);
260
+ const slot = slots.get(id);
261
+ const under = box.y + box.h + (slot ? loopRoom(slot.group, slot.row) : 0);
262
+ return (slot?.row ?? 0) < band.rows - 1 ? under + A.rowGap / 2 : Math.min(under + R.pad / 2, band.y + band.h - LOOK.edge.inset);
230
263
  };
231
264
  const laneAbove = (id: string): number => {
232
265
  const box = byId.get(id) as SceneBox;
@@ -234,9 +267,14 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
234
267
  return (slots.get(id)?.row ?? 0) > 0 ? box.y - A.rowGap / 2 : Math.max(box.y - R.pad / 2, band.y + LOOK.edge.inset);
235
268
  };
236
269
  const inset = LOOK.edge.inset;
270
+ /** 列 `col` の右 (左) の、隣の列との間の真ん中。同じ列の箱は幅が違うので、箱ではなく列の端から測る (幅の広い箱の中を通さない) */
271
+ const gapX = (col: number, toRight: boolean): number =>
272
+ toRight ? (colLeft[col] as number) + (colW[col] as number) + (between[col] ?? A.columnGap) / 2 : (colLeft[col] as number) - (between[col - 1] ?? A.columnGap) / 2;
237
273
  const route = (from: string, to: string): Point[] => {
238
274
  const a = byId.get(from) as SceneBox;
239
275
  const b = byId.get(to) as SceneBox;
276
+ // 同じ箱へ戻る線は、状態遷移図と同じ箱の下の輪で描く (#3186)
277
+ if (from === to) return loopUnder(a);
240
278
  const sa = slots.get(from) as Slot;
241
279
  const sb = slots.get(to) as Slot;
242
280
  if (sa.group === sb.group && sa.row === sb.row) {
@@ -246,13 +284,23 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
246
284
  [right ? b.x - inset : b.x + b.w + inset, b.cy],
247
285
  ];
248
286
  if (!blocked(straight, from, to)) return straight;
249
- const lane = laneBelow(from);
250
- return [
287
+ const below = laneBelow(from);
288
+ const under: Point[] = [
251
289
  [a.cx, a.y + a.h],
252
- [a.cx, lane],
253
- [b.cx, lane],
290
+ [a.cx, below],
291
+ [b.cx, below],
254
292
  [b.cx, b.y + b.h + inset],
255
293
  ];
294
+ if (!onLoop(under)) return under;
295
+ // 下を回ると輪を横切る時は、上を回る
296
+ const above = laneAbove(from);
297
+ const over: Point[] = [
298
+ [a.cx, a.y],
299
+ [a.cx, above],
300
+ [b.cx, above],
301
+ [b.cx, b.y - inset],
302
+ ];
303
+ return onLoop(over) ? under : over;
256
304
  }
257
305
  const down = b.cy > a.cy;
258
306
  const leave: Point = [a.cx, down ? a.y + a.h : a.y];
@@ -260,7 +308,7 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
260
308
  if (sa.col === sb.col) {
261
309
  const straight: Point[] = [leave, enter];
262
310
  if (!blocked(straight, from, to)) return straight;
263
- const x = a.x + a.w + (between[sa.col] ?? A.columnGap) / 2;
311
+ const x = gapX(sa.col, true);
264
312
  return [
265
313
  [a.x + a.w, a.cy],
266
314
  [x, a.cy],
@@ -275,23 +323,39 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
275
323
  [[right ? a.x + a.w : a.x, a.cy], [b.cx, a.cy], enter],
276
324
  [leave, [a.cx, lane], [b.cx, lane], enter],
277
325
  ];
326
+ // 輪を持つ箱の下からは出入りしない。箱の脇から列の間へ出て、列の間を縦に走る (#3186)
327
+ if (looped.has(from) || looped.has(to)) {
328
+ const ax = gapX(sa.col, right);
329
+ const bx = gapX(sb.col, !right);
330
+ const out: Point[] = [
331
+ [right ? a.x + a.w : a.x, a.cy],
332
+ [ax, a.cy],
333
+ ];
334
+ const side: Point = [right ? b.x - inset : b.x + b.w + inset, b.cy];
335
+ candidates.push(
336
+ [...out, [ax, b.cy], side],
337
+ [...out, [ax, lane], [b.cx, lane], enter],
338
+ [leave, [a.cx, lane], [bx, lane], [bx, b.cy], side],
339
+ [...out, [ax, lane], [bx, lane], [bx, b.cy], side],
340
+ );
341
+ }
278
342
  return candidates.find((points) => !blocked(points, from, to)) ?? (candidates[2] as Point[]);
279
343
  };
280
344
 
281
- const sceneEdges: SceneEdge[] = edges.map(({ step, event, edge }) => {
282
- const target = byId.get(edge.to) as SceneBox;
283
- return {
284
- step,
285
- event,
286
- from: edge.from,
287
- to: edge.to,
288
- points: route(edge.from, edge.to),
289
- color: edgeColor(edge, colors),
290
- carry: edge.carry,
291
- settle: [target.cx, target.cy + B.iconY],
292
- };
293
- });
294
- // 同じ 2 つの箱を行きと帰りで結ぶまっすぐな線は、少しずらして重ならないようにする
345
+ const sceneEdges: SceneEdge[] = edges.map(({ step, event, edge }) => ({
346
+ step,
347
+ event,
348
+ from: edge.from,
349
+ to: edge.to,
350
+ points: route(edge.from, edge.to),
351
+ color: edgeColor(edge, colors),
352
+ carry: edge.carry,
353
+ }));
354
+ // 運ぶ物は着いた箱の置き場に留まり、出る箱の置き場で走り出しを待つ (#3176)
355
+ seatCarriers(sceneEdges, byId, carriedIn);
356
+ // 同じ 2 つの箱を行きと帰りで結ぶまっすぐな線は、少しずらして重ならないようにする。
357
+ // ずらした線の名前は、ずらした側 (もう一方の線の反対側) に置き、どちらの線の名前かを取り違えないようにする (#3175)
358
+ const outward = new Map<SceneEdge, LabelSide>();
295
359
  for (const edge of sceneEdges) {
296
360
  if (edge.points.length !== 2) continue;
297
361
  const back = sceneEdges.some((other) => other.from === edge.to && other.to === edge.from && other.points.length === 2);
@@ -300,6 +364,7 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
300
364
  const flat = Math.abs(q[1] - p[1]) < Math.abs(q[0] - p[0]);
301
365
  const d = (edge.from < edge.to ? 1 : -1) * LOOK.edge.parallel;
302
366
  edge.points = edge.points.map(([x, y]) => (flat ? [x, y + d] : [x + d, y]));
367
+ outward.set(edge, flat ? (d > 0 ? "below" : "above") : d > 0 ? "right" : "left");
303
368
  }
304
369
 
305
370
  const regions: SceneRegion[] = [];
@@ -321,15 +386,24 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
321
386
  });
322
387
  });
323
388
 
389
+ // 線の名前は、同じ時刻に見えている段の番号 (その段とそれより前の段の番号) も避ける (#3175)
390
+ // 輪の番号は弧に重ねず弧の右に置く (#3186)
391
+ const badgeAt = (edge: SceneEdge, taken: Point[], lines: Point[][]): Point => (edge.from === edge.to ? loopBadge(edge.points) : badgeOnPath(edge.points, taken, lines));
392
+ const early = lineBadges(sceneEdges, diagram.steps.length, badgeAt);
324
393
  const labels: SceneLabel[] = [];
325
394
  for (const edge of sceneEdges) {
326
395
  const source = diagram.steps[edge.step]?.events[edge.event];
327
396
  if (source?.type !== "edge" || source.label === undefined) continue;
397
+ const seen = [...early].filter(([s]) => s <= edge.step).map(([, b]) => badgeRect(b.point));
328
398
  const soft: Rect[] = [...regions.map((r) => r.header), ...labels.filter((l) => l.step === edge.step)];
399
+ // 指示の無い線の名前は、空いていなければ反対の側も探す。ずらした線は自分の側だけを探す
400
+ const side = source.labelSide ?? outward.get(edge);
401
+ // 輪の名前は輪の下から探す (#3186)
402
+ const below = edge.from === edge.to ? { side: "below" as const, base: loopLabelBase(edge.points, textWidth(source.label, labelStyle(source.label)) + LOOK.label.padX * 2) } : undefined;
329
403
  labels.push(
330
404
  placeLabel(
331
- { step: edge.step, event: edge.event, text: source.label, points: edge.points, color: edge.color, ...(source.labelSide ? { side: source.labelSide } : {}) },
332
- { hard: boxes, soft },
405
+ { step: edge.step, event: edge.event, text: source.label, points: edge.points, color: edge.color, ...(below ?? (side ? { side } : { flip: true })) },
406
+ { hard: boxes, soft, touch: seen },
333
407
  ),
334
408
  );
335
409
  }
@@ -341,16 +415,21 @@ function arrange(diagram: Diagram, groups: Group[], slots: Map<string, Slot>, ro
341
415
  const contentRight = Math.max(...boxes.map((b) => b.x + b.w + R.pad), ...labels.map((l) => l.x + l.w + LOOK.label.soft), ...sceneEdges.flatMap((e) => e.points.map((p) => p[0] + R.pad)));
342
416
  const width = Math.max(contentRight + margin, stripNeed(diagram) + margin * 2);
343
417
  for (const region of regions) region.w = width - margin * 2;
344
- const strip = layoutStrip(diagram, margin, bandsBottom + gap, width - margin * 2);
418
+ // 箱の下を回る線の名前は帯の下へ出ることがあるので、名前の下端まで図に入れる (#3176)
419
+ const contentBottom = Math.max(bandsBottom, ...labels.map((l) => l.y + l.h));
420
+ const strip = layoutStrip(diagram, margin, contentBottom + gap, width - margin * 2);
345
421
  layout.width = width;
346
- layout.height = (strip ? strip.y + strip.h : bandsBottom) + margin;
422
+ layout.height = (strip ? strip.y + strip.h : contentBottom) + margin;
347
423
  if (strip) layout.strip = strip;
348
- layout.badges = diagram.steps.map((step, s) => {
349
- const edge = sceneEdges.find((e) => e.step === s);
350
- if (!edge) return cornerBadge(step.events, s, layout);
351
- const [x, y] = badgeOnPath(edge.points);
352
- return { step: s, x, y, color: edge.color };
353
- });
424
+ const lines = lineBadges(sceneEdges, diagram.steps.length, badgeAt);
425
+ // 同じ所に置いた番号は、後の段が始まると入れ替える (#3184)
426
+ layout.badges = replaceSameSpot(
427
+ diagram.steps.map((step, s) => {
428
+ const line = lines.get(s);
429
+ if (!line) return cornerBadge(step.events, s, layout);
430
+ return { step: s, x: line.point[0], y: line.point[1], color: line.edge.color };
431
+ }),
432
+ );
354
433
  return layout;
355
434
  }
356
435