@cardenelabs/dragon 0.41.0 → 0.42.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 (47) hide show
  1. package/README.md +21 -1
  2. package/dist/cli.cjs +4122 -969
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +4122 -969
  5. package/dist/cli.js.map +1 -1
  6. package/dist/export.cjs +3704 -942
  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 +3704 -942
  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/export/capture.ts +17 -5
  27. package/src/export/fonts.ts +19 -1
  28. package/src/export/index.ts +2 -2
  29. package/src/field-messages.ts +12 -0
  30. package/src/figure-text.ts +26 -0
  31. package/src/index.ts +11 -1
  32. package/src/layout/scene.ts +23 -2
  33. package/src/layout/time.ts +680 -0
  34. package/src/look/values.ts +142 -2
  35. package/src/messages.ts +108 -5
  36. package/src/parser.ts +427 -6
  37. package/src/player.ts +48 -10
  38. package/src/printer.ts +63 -12
  39. package/src/render/icons.ts +2 -0
  40. package/src/render/parts.ts +29 -9
  41. package/src/render/svg.ts +129 -21
  42. package/src/render/time.ts +291 -0
  43. package/src/schema.ts +109 -10
  44. package/src/schemas/diagram.schema.json +224 -12
  45. package/src/schemas/validate-diagram.js +1 -1
  46. package/src/timeline.ts +147 -10
  47. package/src/words.ts +39 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cardenelabs/dragon",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "Dragon — 動く図を、人は行ごとの記法で、AI は JSON で書く。時系列図と構成図を段ごとに動かし、mp4・GIF・HTML・PNG に書き出す。",
5
5
  "license": "MIT",
6
6
  "author": "cardene777",
@@ -39,6 +39,12 @@ const LAUNCH_TEXT: Record<NotationLang, { missing: string; cannotLaunch: string;
39
39
  },
40
40
  };
41
41
 
42
+ /** 撮る頁が字の file を読めない時の断りの文。読めない file を `"<字の名前>" <字の範囲>` で並べて名指す (#3212) */
43
+ const FONT_TEXT: Record<NotationLang, (faces: string[]) => string> = {
44
+ ja: (faces) => `書き出しに埋める字の file を Chromium が読めない (${faces.join("、")})`,
45
+ en: (faces) => `Chromium cannot read the font files embedded in the export (${faces.join("; ")})`,
46
+ };
47
+
42
48
  /** 画面なしの Chromium を起こす。起こせない時は、渡した言葉で入れ方を添えて断る */
43
49
  export async function launch(lang: NotationLang): Promise<Browser> {
44
50
  const text = LAUNCH_TEXT[lang];
@@ -70,8 +76,9 @@ export interface Stage {
70
76
  /**
71
77
  * 図 1 枚を置いた頁を開き、字が読み込まれるまで待つ。`body` は頁の地の CSS。
72
78
  * 図は置く前から止めておく。置いてから止めると、止めるまでに進んだ分だけ毎回絵がずれる。
79
+ * 字の file を 1 つでも読めない時は、読めない file を `lang` の言葉で名指して断る。
73
80
  */
74
- export async function stage(browser: Browser, svg: string, fontCss: string, body: string): Promise<Stage> {
81
+ export async function stage(browser: Browser, svg: string, fontCss: string, body: string, lang: NotationLang): Promise<Stage> {
75
82
  const { width, height } = sizeOf(svg);
76
83
  const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: SCALE });
77
84
  const paused = svg.replace(/^<svg\b/, '<svg style="--play:paused;--at:0"');
@@ -86,12 +93,17 @@ export async function stage(browser: Browser, svg: string, fontCss: string, body
86
93
  });
87
94
  await page.goto("http://localhost/");
88
95
  await page.waitForFunction(() => "__tools" in window);
89
- await page.evaluate(async () => {
90
- const loads: Promise<FontFace>[] = [];
91
- document.fonts.forEach((face) => loads.push(face.load()));
92
- await Promise.all(loads);
96
+ const unreadable = await page.evaluate(async () => {
97
+ const faces: FontFace[] = [];
98
+ document.fonts.forEach((face) => faces.push(face));
99
+ const loads = await Promise.allSettled(faces.map((face) => face.load()));
93
100
  await document.fonts.ready;
101
+ return faces.filter((_, i) => loads[i]?.status === "rejected").map((face) => `"${face.family.replace(/^["']|["']$/g, "")}" ${face.unicodeRange}`);
94
102
  });
103
+ if (unreadable.length) {
104
+ await page.close();
105
+ throw new Error(FONT_TEXT[lang](unreadable));
106
+ }
95
107
  return { page, width, height };
96
108
  }
97
109
 
@@ -4,6 +4,9 @@
4
4
  * 同梱した字の package は、字の範囲ごとに分けた file (woff2) と、file ごとの範囲の表 (`unicode.json`) を持つ。
5
5
  * 描く字が入る file だけを、描く字だけに削り、`data:` で埋めた `@font-face` にする。
6
6
  * 太さの軸は、値の表 (`TYPE`) が使う太さの間に縮める。
7
+ *
8
+ * 形を 1 つも持たない字の file を Chromium は読まない。空白の類だけを描く file には、
9
+ * 同じ file の形のある字を 1 つ足して削る。足した字は `unicode-range` に載せないので描かれない (#3212)。
7
10
  */
8
11
  import { readFileSync } from "node:fs";
9
12
  import { readFile } from "node:fs/promises";
@@ -39,6 +42,20 @@ function ranges(list: string): [number, number][] {
39
42
 
40
43
  const hex = (code: number): string => `U+${code.toString(16).toUpperCase()}`;
41
44
 
45
+ /** 形を持たない字 (空白の類、書式の字、制御の字) か */
46
+ const shapeless = (char: string): boolean => /^[\s\p{Cf}\p{Cc}]$/u.test(char);
47
+
48
+ /** 範囲の中で最初の、形を持つ字。空白の類だけを描く file を読める形にするために足す */
49
+ function shapedIn(span: [number, number][]): string | undefined {
50
+ for (const [from, to] of span) {
51
+ for (let code = from; code <= to; code++) {
52
+ const char = String.fromCodePoint(code);
53
+ if (!shapeless(char)) return char;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+
42
59
  /** 字を空白ごと集める。改行は字の file に要らない */
43
60
  export function charsOf(texts: string[]): string[] {
44
61
  return [...new Set([...texts.join("")])].filter((char) => char !== "\n" && char !== "\r" && char !== "\t").sort();
@@ -57,8 +74,9 @@ export async function fontFaces(chars: string[]): Promise<string> {
57
74
  return span.some(([from, to]) => code >= from && code <= to);
58
75
  });
59
76
  if (!own.length) return "";
77
+ const filler = own.every(shapeless) ? (shapedIn(span) ?? "") : "";
60
78
  const file = join(base, "files", `${name}-${key.replace(/[[\]]/g, "")}-wght-normal.woff2`);
61
- const woff2 = await subsetFont(await readFile(file), own.join(""), { targetFormat: "woff2", variationAxes: { wght: WEIGHT } });
79
+ const woff2 = await subsetFont(await readFile(file), own.join("") + filler, { targetFormat: "woff2", variationAxes: { wght: WEIGHT } });
62
80
  const unicode = own.map((char) => hex(char.codePointAt(0) ?? 0)).join(",");
63
81
  return `@font-face{font-family:"${family}";font-style:normal;font-display:block;font-weight:${WEIGHT.min} ${WEIGHT.max};src:url(data:font/woff2;base64,${woff2.toString("base64")}) format("woff2");unicode-range:${unicode}}`;
64
82
  });
@@ -100,13 +100,13 @@ export async function exportDiagram(input: unknown, options: ExportOptions): Pro
100
100
  const browser = await launch(lang);
101
101
  try {
102
102
  if (formats.includes("png")) {
103
- const fixed = await stage(browser, rendered.svg, fontCss, "");
103
+ const fixed = await stage(browser, rendered.svg, fontCss, "", lang);
104
104
  outputs.push(["png", await still(fixed, timeline.stills[timeline.stills.length - 1] ?? 0)]);
105
105
  }
106
106
  if (mp4 || gif) {
107
107
  const fps = mp4 ? (options.fps ?? DEFAULTS.fps) : (options.gifFps ?? DEFAULTS.gifFps);
108
108
  const gifEvery = gif ? Math.max(1, Math.round(fps / (options.gifFps ?? DEFAULTS.gifFps))) : 0;
109
- const shot = await film(await stage(browser, videoSvg, fontCss, `${vars};background:var(--bg)`), {
109
+ const shot = await film(await stage(browser, videoSvg, fontCss, `${vars};background:var(--bg)`, lang), {
110
110
  total: timeline.total,
111
111
  fps,
112
112
  mp4,
@@ -38,6 +38,12 @@ export interface FieldMessages {
38
38
  kindOnly: (types: readonly string[], kind: string) => string;
39
39
  /** 16 進の字を `min` から `max` 字で書く決まり (commit の hash、#3164) */
40
40
  hex: (min: number, max: number) => string;
41
+ /** 数と単位 (`units`) の組で書く決まり (時間軸の図の目盛りの長さ、#3165) */
42
+ duration: (units: readonly string[]) => string;
43
+ /** 分数か百分率で書く決まり (物差しの線、#3165) */
44
+ ratio: string;
45
+ /** 頁を移る形だけを書ける決まり (箱の飛び先と段の出典の URL、#3199) */
46
+ url: string;
41
47
  /** 選べる決まりがどれも欄が足りない時の、足りない欄。それ以外の時は空 */
42
48
  anyOf: (fields: readonly string[]) => string;
43
49
  oneOf: string;
@@ -83,6 +89,9 @@ const ja: FieldMessages = {
83
89
  reserved: (names) => `${names.join(" と ")} は状態遷移図の始まりと終わりの印の名前で、箱の名札に使えない`,
84
90
  kindOnly: (types, kind) => `${types.join(" と ")} の出来事は kind が ${kind} の時だけ書ける`,
85
91
  hex: (min, max) => `0 から 9 と a から f の字で ${min} から ${max} 字にする`,
92
+ duration: (units) => `数と単位 (${units.join(" / ")}) の組で書く (12s など)`,
93
+ ratio: "分数 (2/3) か百分率 (97%) で書く",
94
+ url: "/ で始まる path か、http:// か https:// で始まる URL にする",
86
95
  anyOf: (fields) =>
87
96
  fields.length > 0 ? `${fields.join(" か ")} の${fields.length === 2 ? "どちらか" : "どれか"}の欄が要る` : "書ける形のどれにも合わない",
88
97
  oneOf: "書ける形のどれか 1 つだけに合わせる",
@@ -107,6 +116,9 @@ const en: FieldMessages = {
107
116
  reserved: (names) => `${names.join(" and ")} name the start and end marks of a state diagram and cannot be box ids`,
108
117
  kindOnly: (types, kind) => `${types.join(" and ")} events are allowed only when kind is ${kind}`,
109
118
  hex: (min, max) => `Use ${min} to ${max} characters of 0-9 and a-f`,
119
+ duration: (units) => `Write a number and a unit (${units.join(" / ")}), such as 12s`,
120
+ ratio: "Write a fraction (2/3) or a percentage (97%)",
121
+ url: "Use a path that starts with / or a URL that starts with http:// or https://",
110
122
  anyOf: (fields) => (fields.length > 0 ? `Write one of the ${fields.join(" or ")} fields` : "Does not match any of the allowed shapes"),
111
123
  oneOf: "Match exactly one of the allowed shapes",
112
124
  discriminator: (tag, values) => `${tag} is one of ${values.join(" / ")}`,
@@ -9,6 +9,9 @@ import type { NotationLang } from "./words";
9
9
  export interface FigureText {
10
10
  /** 描けない時の断りの文。`detail` は誤りの場所と文を並べた物 */
11
11
  cannotDraw: (detail: string) => string;
12
+ /** 描く設定の `colors` (#3198) の誤り。色味に無い色の名前と、色の値として読めない値の色の名前 */
13
+ unknownColor: (name: string) => string;
14
+ unreadableColor: (name: string) => string;
12
15
  /** 寄って動かす見せ方の、隅の全体図の札 */
13
16
  overview: string;
14
17
  /** 再生の釦の読み上げの名前 */
@@ -36,6 +39,15 @@ export interface FigureText {
36
39
  envelope: string;
37
40
  textsOverlap: (a: string, b: string) => string;
38
41
  lineCrosses: (from: string, to: string, text: string) => string;
42
+ /**
43
+ * 時間軸の図 (#3165)。時刻の字の単位、拡大の帯の名前、目盛りの番号の範囲の書き方、列の上の目盛りの番号と時刻の間、
44
+ * 空きの目盛りの枠の字
45
+ */
46
+ timeUnits: Record<"ms" | "s" | "min" | "h" | "d", string>;
47
+ zoom: string;
48
+ range: (from: string, to: string) => string;
49
+ headJoin: string;
50
+ empty: string;
39
51
  }
40
52
 
41
53
  /** 英数字で終わる語の後ろに空白を置く。「段の番号 1 と」のように、数と仮名の間を空けて読みやすくする */
@@ -46,6 +58,8 @@ const capital = (text: string): string => text.charAt(0).toUpperCase() + text.sl
46
58
  export const FIGURE_TEXT: Record<NotationLang, FigureText> = {
47
59
  ja: {
48
60
  cannotDraw: (detail) => `図を描けない: ${detail}`,
61
+ unknownColor: (name) => `colors の ${name} は色味に無い色の名前`,
62
+ unreadableColor: (name) => `colors の ${name} の値を色として読めない`,
49
63
  overview: "全体図",
50
64
  prev: "前の段",
51
65
  pause: "止める",
@@ -65,9 +79,16 @@ export const FIGURE_TEXT: Record<NotationLang, FigureText> = {
65
79
  envelope: "「封筒」",
66
80
  textsOverlap: (a, b) => `${spaced(a)}と${spaced(b)}が重なる`,
67
81
  lineCrosses: (from, to, text) => `線 ${from} → ${to} が${spaced(text)}を横切る`,
82
+ timeUnits: { ms: "ミリ秒", s: "秒", min: "分", h: "時間", d: "日" },
83
+ zoom: "拡大",
84
+ range: (from, to) => `${from}〜${to}`,
85
+ headJoin: " ・ ",
86
+ empty: "空き",
68
87
  },
69
88
  en: {
70
89
  cannotDraw: (detail) => `Cannot draw the diagram: ${detail}`,
90
+ unknownColor: (name) => `colors.${name} is not a color name of the palette`,
91
+ unreadableColor: (name) => `colors.${name} cannot be read as a color`,
71
92
  overview: "Overview",
72
93
  prev: "Previous step",
73
94
  pause: "Pause",
@@ -87,5 +108,10 @@ export const FIGURE_TEXT: Record<NotationLang, FigureText> = {
87
108
  envelope: "the envelope",
88
109
  textsOverlap: (a, b) => capital(`${a} and ${b} overlap`),
89
110
  lineCrosses: (from, to, text) => `The line ${from} → ${to} crosses ${text}`,
111
+ timeUnits: { ms: "ms", s: "s", min: "min", h: "h", d: "d" },
112
+ zoom: "Zoom",
113
+ range: (from, to) => `${from}–${to}`,
114
+ headJoin: " · ",
115
+ empty: "Empty",
90
116
  },
91
117
  };
package/src/index.ts CHANGED
@@ -25,6 +25,15 @@ export {
25
25
  type Region,
26
26
  type StatePath,
27
27
  type Step,
28
+ type StepSource,
29
+ type StripMeter,
30
+ type TimeMarkEvent,
31
+ type TimePeriod,
32
+ type TimePoint,
33
+ type TimeRow,
34
+ type TimeScale,
35
+ type TimeSpanEvent,
36
+ type TimeSpec,
28
37
  validateDiagram,
29
38
  type ViewMode,
30
39
  } from "./schema";
@@ -47,8 +56,9 @@ export type {
47
56
  SceneStrip,
48
57
  SceneTrail,
49
58
  } from "./layout/scene";
59
+ export type { TimeAxis, TimeBox, TimeColumn, TimeLayout, TimeMark, TimePeriodPlaced, TimePointPlaced, TimeRowPlaced, TimeSpanPlaced, TimeTick, TimeWire, TimeZoom } from "./layout/time";
50
60
  export { type Family, FONTS } from "./look/fonts";
51
- export { type ColorKey, DEFAULT_PALETTE, type Palette, PALETTES, READABLE_PX, resolvePalette, type Theme } from "./look/values";
61
+ export { type ColorKey, type ColorName, type Colors, DEFAULT_PALETTE, type Palette, PALETTES, READABLE_PX, resolvePalette, type Theme } from "./look/values";
52
62
  export { mountDiagram, type Player, type PlayerOptions } from "./player";
53
63
  export { ICONS } from "./render/icons";
54
64
  export { describeOverlap, type InkPart, type Overlap, type OverlapSpot } from "./render/ink";
@@ -128,6 +128,8 @@ export interface SceneField {
128
128
  x: number;
129
129
  y: number;
130
130
  w: number;
131
+ /** 時間軸の図の物差しの欄 (#3165)。`line` の割合の所に線を引き、線の字 `text` を添える。棒は `x` から幅 `w` */
132
+ meter?: { line: number; text: string; x: number; w: number };
131
133
  }
132
134
 
133
135
  /** 状態遷移図の帯の最後の欄。段が辿り着く順に状態を点で並べ、着いた状態を塗る (#3171) */
@@ -578,8 +580,23 @@ export function placeLabel(request: LabelRequest, obstacles: Obstacles): SceneLa
578
580
  return { ...first, step: request.step, event: request.event, text: request.text, family: labelStyle(request.text).family, color: request.color };
579
581
  }
580
582
 
581
- /** 中身の帯の欄の幅。欄の名前と、入る値と札を並べた最も長い形が収まる幅。 */
583
+ /**
584
+ * 割合の字 (`2/3` か `97%`) の値 (#3165)。0 から 1 の間に収める。割合の形でない字は `undefined`
585
+ */
586
+ export function ratioOf(text: string): number | undefined {
587
+ const percent = /^([0-9]+(?:\.[0-9]+)?)%$/u.exec(text.trim());
588
+ if (percent) return Math.min(1, Math.max(0, Number(percent[1]) / 100));
589
+ const fraction = /^([0-9]+)\/([0-9]+)$/u.exec(text.trim());
590
+ if (fraction && Number(fraction[2]) > 0) return Math.min(1, Math.max(0, Number(fraction[1]) / Number(fraction[2])));
591
+ return undefined;
592
+ }
593
+
594
+ /** 欄に付けた物差し (#3165)。時間軸の図だけが持つ */
595
+ const meterOf = (diagram: Diagram, name: string) => diagram.strip?.meters?.find((m) => m.field === name);
596
+
597
+ /** 中身の帯の欄の幅。欄の名前と、入る値と札を並べた最も長い形が収まる幅。物差しの欄は物差しの幅 */
582
598
  function fieldWidth(diagram: Diagram, name: string): number {
599
+ if (meterOf(diagram, name)) return Math.max(textWidth(name, TYPE.fieldName), LOOK.time.meter.w);
583
600
  let value = 0;
584
601
  let tag = 0;
585
602
  for (const step of diagram.steps) {
@@ -626,7 +643,10 @@ export function layoutStrip(diagram: Diagram, x: number, y: number, width: numbe
626
643
  };
627
644
  for (const name of diagram.strip.fields) {
628
645
  const w = fieldWidth(diagram, name);
629
- fields.push({ name, ...place(w), w });
646
+ const at = place(w);
647
+ const meter = meterOf(diagram, name);
648
+ const line = meter ? ratioOf(meter.line) : undefined;
649
+ fields.push({ name, ...at, w, ...(meter && line !== undefined ? { meter: { line, text: meter.line, x: at.x, w: LOOK.time.meter.w } } : {}) });
630
650
  }
631
651
  const laidTrail = trail ? { ...trail, ...place(trailWidth(trail)), w: trailWidth(trail) } : undefined;
632
652
  return { x, y, w: width, h: h + row * line, title: diagram.strip.title, fields, ...(laidTrail ? { trail: laidTrail } : {}) };
@@ -679,6 +699,7 @@ export function shiftContent(layout: Layout, dx: number, dy: number): void {
679
699
  for (const field of layout.strip.fields) {
680
700
  field.x += dx;
681
701
  field.y += dy;
702
+ if (field.meter) field.meter.x += dx;
682
703
  }
683
704
  if (layout.strip.trail) {
684
705
  layout.strip.trail.x += dx;