@johnoscott/isometric-engine 0.15.0 → 0.16.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 (66) hide show
  1. package/README.md +1 -1
  2. package/iso-editor.js +230 -193
  3. package/iso-render.js +184 -147
  4. package/iso-systems.js +183 -146
  5. package/isometric-diagram.js +389 -0
  6. package/js/iso-core/index.js +5 -0
  7. package/js/iso-core/mono.js +242 -0
  8. package/js/iso-editor/ui/canvas.js +23 -1
  9. package/js/iso-objects/ants.js +1 -1
  10. package/js/iso-objects/index.js +10 -2
  11. package/js/iso-objects/mono-paint.js +96 -0
  12. package/js/iso-objects/motion-doc.js +0 -79
  13. package/js/iso-objects/motion-entry.js +4 -2
  14. package/js/iso-objects/motion-schema.js +83 -0
  15. package/js/iso-objects/motion.js +9 -4
  16. package/js/iso-objects/timeline.js +51 -11
  17. package/js/iso-systems/compile.js +25 -1
  18. package/js/iso-systems/render.js +1 -1
  19. package/js/iso-systems/schema.json +1 -0
  20. package/js/iso-viewer/index.js +6 -0
  21. package/js/iso-viewer/page.js +40 -17
  22. package/js/iso-viewer/play.js +340 -0
  23. package/js/iso-viewer/player.js +147 -162
  24. package/js/iso-viewer/transport.js +289 -0
  25. package/package.json +39 -2
  26. package/src/iso-core/index.ts +1 -0
  27. package/src/iso-core/mono.ts +306 -0
  28. package/src/iso-core/theme.ts +2 -1
  29. package/src/iso-editor/ui/canvas.ts +14 -1
  30. package/src/iso-objects/ants.ts +2 -2
  31. package/src/iso-objects/index.ts +5 -3
  32. package/src/iso-objects/mono-paint.ts +97 -0
  33. package/src/iso-objects/motion-doc.ts +0 -52
  34. package/src/iso-objects/motion-entry.ts +4 -3
  35. package/src/iso-objects/motion-schema.ts +55 -0
  36. package/src/iso-objects/motion.ts +6 -5
  37. package/src/iso-objects/scene.ts +3 -0
  38. package/src/iso-objects/timeline.ts +63 -13
  39. package/src/iso-objects/types.ts +2 -0
  40. package/src/iso-systems/compile.ts +29 -2
  41. package/src/iso-systems/render.ts +5 -1
  42. package/src/iso-systems/schema.json +1 -0
  43. package/src/iso-viewer/index.ts +4 -0
  44. package/src/iso-viewer/page.ts +28 -12
  45. package/src/iso-viewer/play.ts +280 -0
  46. package/src/iso-viewer/player.ts +133 -134
  47. package/src/iso-viewer/transport.ts +272 -0
  48. package/types/iso-core/index.d.ts +1 -0
  49. package/types/iso-core/mono.d.ts +61 -0
  50. package/types/iso-core/theme.d.ts +2 -0
  51. package/types/iso-objects/ants.d.ts +1 -0
  52. package/types/iso-objects/index.d.ts +5 -3
  53. package/types/iso-objects/mono-paint.d.ts +20 -0
  54. package/types/iso-objects/motion-doc.d.ts +0 -594
  55. package/types/iso-objects/motion-entry.d.ts +4 -3
  56. package/types/iso-objects/motion-schema.d.ts +594 -0
  57. package/types/iso-objects/motion.d.ts +4 -2
  58. package/types/iso-objects/scene.d.ts +3 -0
  59. package/types/iso-objects/timeline.d.ts +22 -2
  60. package/types/iso-objects/types.d.ts +2 -0
  61. package/types/iso-systems/compile.d.ts +5 -0
  62. package/types/iso-systems/render.d.ts +4 -0
  63. package/types/iso-viewer/index.d.ts +4 -0
  64. package/types/iso-viewer/play.d.ts +37 -0
  65. package/types/iso-viewer/transport.d.ts +73 -0
  66. package/types/player/isometric-diagram.d.ts +24 -0
@@ -0,0 +1,289 @@
1
+ function pageClock() {
2
+ const g = globalThis;
3
+ return {
4
+ now: () => performance.now(),
5
+ next(f) {
6
+ const id = {};
7
+ const once = () => {
8
+ if (id.raf !== void 0) g.cancelAnimationFrame?.(id.raf);
9
+ clearTimeout(id.timer);
10
+ f();
11
+ };
12
+ id.raf = g.requestAnimationFrame?.(once);
13
+ id.timer = setTimeout(once, id.raf === void 0 ? 16 : 100);
14
+ return id;
15
+ },
16
+ cancel(id) {
17
+ const x = id;
18
+ if (x.raf !== void 0) g.cancelAnimationFrame?.(x.raf);
19
+ clearTimeout(x.timer);
20
+ }
21
+ };
22
+ }
23
+ const BACK_WITHIN = 400;
24
+ function transport(tl0, o = {}) {
25
+ const clock = o.clock ?? pageClock();
26
+ let tl = tl0, T = 0, rate = good(o.rate ?? 1), loop = o.loop ?? false, playing = false, active = true, gone = false;
27
+ let on = (o.ambient ?? tl.ambient) === "on";
28
+ let A = on ? 0 : "off";
29
+ let pending, last = 0, beat = tl.beatAt(0), told = false, turn = 0, until;
30
+ const subs = {};
31
+ function good(r) {
32
+ if (!(Number.isFinite(r) && r > 0)) throw new Error("rate is a number over 0");
33
+ return r;
34
+ }
35
+ const clamp = (ms) => Math.max(0, Math.min(tl.duration, ms));
36
+ function emit(k, ...a) {
37
+ for (const f of [...subs[k] ?? []]) f(...a);
38
+ }
39
+ const moves = () => active && !gone && (playing || on && tl.loops);
40
+ function arm() {
41
+ if (moves()) {
42
+ if (pending === void 0) {
43
+ last = clock.now();
44
+ pending = clock.next(tick);
45
+ }
46
+ } else if (pending !== void 0) {
47
+ clock.cancel(pending);
48
+ pending = void 0;
49
+ }
50
+ }
51
+ function passed(from, to) {
52
+ const mine = turn;
53
+ for (const b of tl.beats) {
54
+ if (b.start <= from || b.start > to || b.index === beat?.index) continue;
55
+ beat = b;
56
+ told = true;
57
+ emit("beat", b, "play");
58
+ if (turn !== mine) return false;
59
+ }
60
+ return true;
61
+ }
62
+ function play1(dt) {
63
+ if (!playing) {
64
+ emit("time", T, "ambient");
65
+ return;
66
+ }
67
+ const was = T, to = T + dt, mine = turn;
68
+ if (until !== void 0 && to >= until) {
69
+ T = until;
70
+ if (!passed(was, T)) return;
71
+ until = void 0;
72
+ playing = false;
73
+ emit("time", T, "play");
74
+ if (turn === mine) emit("pause");
75
+ return;
76
+ }
77
+ if (to < tl.duration) {
78
+ T = to;
79
+ if (passed(was, T)) emit("time", T, "play");
80
+ return;
81
+ }
82
+ if (loop) {
83
+ if (!passed(was, tl.duration)) return;
84
+ T = to % tl.duration;
85
+ if (on) A = T;
86
+ beat = void 0;
87
+ emit("loop");
88
+ if (turn !== mine) return;
89
+ const first = tl.beatAt(0);
90
+ if (first) {
91
+ beat = first;
92
+ emit("beat", first, "play");
93
+ if (turn !== mine || !passed(first.start, T)) return;
94
+ }
95
+ emit("time", T, "play");
96
+ return;
97
+ }
98
+ T = tl.duration;
99
+ if (!passed(was, T)) return;
100
+ playing = false;
101
+ emit("time", T, "play");
102
+ if (turn !== mine) return;
103
+ emit("pause");
104
+ if (turn !== mine) return;
105
+ emit("end");
106
+ }
107
+ function tick() {
108
+ pending = void 0;
109
+ const now = clock.now(), dt = Math.max(0, now - last) * rate;
110
+ last = now;
111
+ if (on && A !== "off") A += dt;
112
+ play1(dt);
113
+ if (pending === void 0) {
114
+ if (moves()) pending = clock.next(tick);
115
+ }
116
+ }
117
+ function land(how, again = false) {
118
+ const b = tl.beatAt(T);
119
+ turn++;
120
+ const mine = turn, other = b?.name !== beat?.name || b?.index !== beat?.index;
121
+ beat = b;
122
+ if (b && (other || again)) {
123
+ told = true;
124
+ emit("beat", b, how);
125
+ if (turn !== mine) return;
126
+ }
127
+ emit("time", T, how);
128
+ }
129
+ function seek(ms, o2 = {}) {
130
+ if (gone || !Number.isFinite(ms)) return;
131
+ const to = clamp(ms);
132
+ if (on && A !== "off") A = o2.join ? to : A + to - T;
133
+ T = to;
134
+ last = clock.now();
135
+ if (until !== void 0 && T >= until) until = void 0;
136
+ land("seek");
137
+ arm();
138
+ }
139
+ function restart() {
140
+ if (gone) return;
141
+ T = 0;
142
+ if (on) A = 0;
143
+ until = void 0;
144
+ last = clock.now();
145
+ land("seek", true);
146
+ arm();
147
+ }
148
+ const api = {
149
+ get timeline() {
150
+ return tl;
151
+ },
152
+ get duration() {
153
+ return tl.duration;
154
+ },
155
+ get time() {
156
+ return T;
157
+ },
158
+ get ambientTime() {
159
+ return A;
160
+ },
161
+ get playing() {
162
+ return playing;
163
+ },
164
+ get beat() {
165
+ return beat;
166
+ },
167
+ get cue() {
168
+ return tl.cues(T);
169
+ },
170
+ get rate() {
171
+ return rate;
172
+ },
173
+ set rate(r) {
174
+ const v = good(r);
175
+ if (v === rate) return;
176
+ rate = v;
177
+ emit("rate", v);
178
+ },
179
+ get loop() {
180
+ return loop;
181
+ },
182
+ set loop(v) {
183
+ loop = v;
184
+ },
185
+ get ambient() {
186
+ return on;
187
+ },
188
+ set ambient(v) {
189
+ if (gone || v === on) return;
190
+ on = v;
191
+ if (on && A === "off") A = beat?.start ?? 0;
192
+ arm();
193
+ emit("ambient", on);
194
+ emit("time", T, "ambient");
195
+ },
196
+ get active() {
197
+ return active;
198
+ },
199
+ set active(v) {
200
+ if (v === active) return;
201
+ active = v;
202
+ arm();
203
+ },
204
+ state: () => tl.at(T, { ambient: A }),
205
+ play(p = {}) {
206
+ if (gone || playing || tl.duration <= 0) return;
207
+ if (T >= tl.duration && p.until === void 0) restart();
208
+ until = p.until !== void 0 && p.until > T && p.until <= tl.duration ? p.until : void 0;
209
+ if (p.until !== void 0 && until === void 0) return;
210
+ playing = true;
211
+ last = clock.now();
212
+ arm();
213
+ emit("play");
214
+ if (playing && !told && beat) {
215
+ told = true;
216
+ emit("beat", beat, "play");
217
+ }
218
+ },
219
+ pause() {
220
+ if (!playing) return;
221
+ playing = false;
222
+ until = void 0;
223
+ turn++;
224
+ arm();
225
+ emit("pause");
226
+ },
227
+ toggle() {
228
+ if (playing) api.pause();
229
+ else api.play();
230
+ },
231
+ seek,
232
+ seekBeat(b) {
233
+ const ms = typeof b === "number" ? tl.beats[b]?.start : tl.beats.find((x) => x.name === b)?.start;
234
+ if (ms === void 0) return false;
235
+ seek(ms);
236
+ return true;
237
+ },
238
+ next() {
239
+ const n = tl.beats.find((b) => b.start > T);
240
+ seek(n ? n.start : tl.duration);
241
+ },
242
+ prev() {
243
+ const back = [...tl.beats].reverse().find((b) => b.start < T - BACK_WITHIN);
244
+ seek(back ? back.start : 0);
245
+ },
246
+ restart,
247
+ rebind(next) {
248
+ if (gone || !next.ok) return false;
249
+ until = void 0;
250
+ const was = tl.beatAt(T), frac = was ? (T - was.start) / Math.max(1, was.end - was.start) : 0, d = A === "off" ? 0 : A - T, before = tl;
251
+ tl = next;
252
+ if (was) {
253
+ const same = next.beats.find((b) => b.name === was.name);
254
+ if (same) T = same.start + frac * (same.end - same.start);
255
+ else {
256
+ const near = before.beats.filter((b) => b.index < was.index).reverse().map((b) => next.beats.find((x) => x.name === b.name)).find(Boolean);
257
+ T = near ? near.start : 0;
258
+ }
259
+ }
260
+ T = clamp(T);
261
+ if (on && A !== "off") A = T + d;
262
+ last = clock.now();
263
+ land("rebind");
264
+ arm();
265
+ return true;
266
+ },
267
+ on(k, f) {
268
+ const set = subs[k] ??= /* @__PURE__ */ new Set();
269
+ set.add(f);
270
+ return () => {
271
+ set.delete(f);
272
+ };
273
+ },
274
+ dispose() {
275
+ gone = true;
276
+ turn++;
277
+ playing = false;
278
+ if (pending !== void 0) clock.cancel(pending);
279
+ pending = void 0;
280
+ for (const k of Object.keys(subs)) subs[k].clear();
281
+ }
282
+ };
283
+ arm();
284
+ return api;
285
+ }
286
+ export {
287
+ pageClock,
288
+ transport
289
+ };
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@johnoscott/isometric-engine",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "description": "A generic isometric diagram engine: render (L0–L2) and editor (L0–L3), with a 2D view and a YAML diagram format.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": [
8
8
  "./src/**",
9
- "./js/**"
9
+ "./js/**",
10
+ "./isometric-diagram.js"
10
11
  ],
11
12
  "repository": {
12
13
  "type": "git",
@@ -28,6 +29,7 @@
28
29
  "iso-editor.d.ts",
29
30
  "iso-systems.js",
30
31
  "iso-systems.d.ts",
32
+ "isometric-diagram.js",
31
33
  "types/",
32
34
  "assets/",
33
35
  "LICENSES/",
@@ -54,6 +56,16 @@
54
56
  "source": "./src/iso-objects/motion-entry.ts",
55
57
  "default": "./js/iso-objects/motion-entry.js"
56
58
  },
59
+ "./transport": {
60
+ "types": "./types/iso-viewer/transport.d.ts",
61
+ "source": "./src/iso-viewer/transport.ts",
62
+ "default": "./js/iso-viewer/transport.js"
63
+ },
64
+ "./player": {
65
+ "types": "./types/player/isometric-diagram.d.ts",
66
+ "default": "./isometric-diagram.js"
67
+ },
68
+ "./isometric-diagram.js": "./isometric-diagram.js",
57
69
  "./modules/iso-core/compile-schema": {
58
70
  "types": "./types/iso-core/compile-schema.d.ts",
59
71
  "source": "./src/iso-core/compile-schema.ts",
@@ -84,6 +96,11 @@
84
96
  "source": "./src/iso-core/kernel.ts",
85
97
  "default": "./js/iso-core/kernel.js"
86
98
  },
99
+ "./modules/iso-core/mono": {
100
+ "types": "./types/iso-core/mono.d.ts",
101
+ "source": "./src/iso-core/mono.ts",
102
+ "default": "./js/iso-core/mono.js"
103
+ },
87
104
  "./modules/iso-core/parse": {
88
105
  "types": "./types/iso-core/parse.d.ts",
89
106
  "source": "./src/iso-core/parse.ts",
@@ -179,6 +196,11 @@
179
196
  "source": "./src/iso-objects/looks.ts",
180
197
  "default": "./js/iso-objects/looks.js"
181
198
  },
199
+ "./modules/iso-objects/mono-paint": {
200
+ "types": "./types/iso-objects/mono-paint.d.ts",
201
+ "source": "./src/iso-objects/mono-paint.ts",
202
+ "default": "./js/iso-objects/mono-paint.js"
203
+ },
182
204
  "./modules/iso-objects/motion-builder": {
183
205
  "types": "./types/iso-objects/motion-builder.d.ts",
184
206
  "source": "./src/iso-objects/motion-builder.ts",
@@ -189,6 +211,11 @@
189
211
  "source": "./src/iso-objects/motion-doc.ts",
190
212
  "default": "./js/iso-objects/motion-doc.js"
191
213
  },
214
+ "./modules/iso-objects/motion-schema": {
215
+ "types": "./types/iso-objects/motion-schema.d.ts",
216
+ "source": "./src/iso-objects/motion-schema.ts",
217
+ "default": "./js/iso-objects/motion-schema.js"
218
+ },
192
219
  "./modules/iso-objects/motion": {
193
220
  "types": "./types/iso-objects/motion.d.ts",
194
221
  "source": "./src/iso-objects/motion.ts",
@@ -279,6 +306,11 @@
279
306
  "source": "./src/iso-viewer/page.ts",
280
307
  "default": "./js/iso-viewer/page.js"
281
308
  },
309
+ "./modules/iso-viewer/play": {
310
+ "types": "./types/iso-viewer/play.d.ts",
311
+ "source": "./src/iso-viewer/play.ts",
312
+ "default": "./js/iso-viewer/play.js"
313
+ },
282
314
  "./modules/iso-viewer/still": {
283
315
  "types": "./types/iso-viewer/still.d.ts",
284
316
  "source": "./src/iso-viewer/still.ts",
@@ -319,6 +351,11 @@
319
351
  "source": "./src/iso-viewer/timeline-time.ts",
320
352
  "default": "./js/iso-viewer/timeline-time.js"
321
353
  },
354
+ "./modules/iso-viewer/transport": {
355
+ "types": "./types/iso-viewer/transport.d.ts",
356
+ "source": "./src/iso-viewer/transport.ts",
357
+ "default": "./js/iso-viewer/transport.js"
358
+ },
322
359
  "./modules/iso-viewer/view-css": {
323
360
  "types": "./types/iso-viewer/view-css.d.ts",
324
361
  "source": "./src/iso-viewer/view-css.ts",
@@ -25,3 +25,4 @@ export type { SvgNode } from './svg-dom.ts';
25
25
  export { VEl, vdoc, serialize } from './vdom.ts';
26
26
  export type { VNode } from './vdom.ts';
27
27
  export { createHash, sha256Hex } from './shims/crypto.ts';
28
+ export { MONO, greyOf, contrast, monoOf, type MonoLook, type MonoTable, type MonoPattern } from './mono.ts';
@@ -0,0 +1,306 @@
1
+ // Black-and-white (monochrome) palettes, patterns and connector line rhythms, plus
2
+ // deterministic mapping from any Theme to a print-ready light or dark MonoLook.
3
+
4
+ import type { Theme } from './theme.ts';
5
+
6
+ export type MonoPattern = 'none' | 'hatch' | 'hatch-wide' | 'dots';
7
+ export type MonoStep = 0 | 1 | 2 | 3;
8
+
9
+ export interface MonoFace {
10
+ top: string;
11
+ left: string;
12
+ right: string;
13
+ edge: string;
14
+ }
15
+
16
+ export interface MonoRhythm {
17
+ dash: number[];
18
+ width: number;
19
+ }
20
+
21
+ export interface MonoRoleLook extends MonoFace {
22
+ step: MonoStep;
23
+ pattern: MonoPattern;
24
+ }
25
+
26
+ export interface MonoLook {
27
+ mode: 'light' | 'dark';
28
+ paper: string;
29
+ ink: string;
30
+ roles: Record<string, MonoRoleLook>;
31
+ kinds: Record<string, MonoRhythm>;
32
+ warnings: string[];
33
+ }
34
+
35
+ export interface MonoTable {
36
+ roles?: Record<string, { step?: MonoStep; pattern?: MonoPattern }>;
37
+ kinds?: Record<string, { dash?: number[]; width?: number }>;
38
+ }
39
+
40
+ const deepFreeze = <T>(v: T): T => {
41
+ if (v && typeof v === 'object') {
42
+ Object.freeze(v);
43
+ for (const child of Object.values(v as Record<string, unknown>)) deepFreeze(child);
44
+ }
45
+ return v;
46
+ };
47
+
48
+ /** Fixed L* cutoffs separating steps 0/1, 1/2 and 2/3 from a role's light top face. */
49
+ const STEP_THRESHOLDS = [86, 81, 76] as const;
50
+
51
+ const KIND_ORDER = ['send', 'reply', 'token', 'blocked', 'user', 'event', 'control', 'planned'] as const;
52
+
53
+ export const MONO = deepFreeze({
54
+ light: {
55
+ paper: '#ffffff',
56
+ ink: '#141414',
57
+ steps: [
58
+ { top: '#f4f4f4', left: '#dcdcdc', right: '#c4c4c4', edge: '#3a3a3a' },
59
+ { top: '#dedede', left: '#bfbfbf', right: '#a2a2a2', edge: '#2e2e2e' },
60
+ { top: '#bcbcbc', left: '#9a9a9a', right: '#7e7e7e', edge: '#222222' },
61
+ { top: '#8f8f8f', left: '#707070', right: '#565656', edge: '#141414' },
62
+ ] as readonly [MonoFace, MonoFace, MonoFace, MonoFace],
63
+ },
64
+ dark: {
65
+ paper: '#161616',
66
+ ink: '#f2f2f2',
67
+ steps: [
68
+ { top: '#2a2a2a', left: '#222222', right: '#1b1b1b', edge: '#b8b8b8' },
69
+ { top: '#454545', left: '#383838', right: '#2c2c2c', edge: '#c8c8c8' },
70
+ { top: '#6a6a6a', left: '#565656', right: '#444444', edge: '#dadada' },
71
+ { top: '#9c9c9c', left: '#808080', right: '#686868', edge: '#141414' },
72
+ ] as readonly [MonoFace, MonoFace, MonoFace, MonoFace],
73
+ },
74
+ patterns: ['none', 'hatch', 'hatch-wide', 'dots'] as readonly MonoPattern[],
75
+ rhythms: [
76
+ { dash: [], width: 2.6 },
77
+ { dash: [9, 4], width: 2.4 },
78
+ { dash: [7, 6], width: 2.4 },
79
+ { dash: [3, 6], width: 2.4 },
80
+ { dash: [1.5, 3.5], width: 2.6 },
81
+ { dash: [10, 3, 2, 3], width: 2.4 },
82
+ { dash: [], width: 1.4 },
83
+ { dash: [7, 6], width: 1.4 },
84
+ { dash: [3, 3], width: 1.6 },
85
+ { dash: [14, 4], width: 1.8 },
86
+ ] as readonly MonoRhythm[],
87
+ kindOrder: KIND_ORDER,
88
+ thresholds: STEP_THRESHOLDS,
89
+ darkWidthAdd: 0.4,
90
+ });
91
+
92
+ const HEX_RE = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
93
+ const HSL_RE = /^hsl\(\s*([+-]?(?:\d+\.?\d*|\.\d+))\s+([+-]?(?:\d+\.?\d*|\.\d+))%\s+([+-]?(?:\d+\.?\d*|\.\d+))%\s*\)$/i;
94
+
95
+ function parseColor(color: string): [number, number, number] {
96
+ if (typeof color !== 'string') throw new Error(`mono: invalid colour "${String(color)}"`);
97
+ const s = color.trim();
98
+ const hex = HEX_RE.exec(s);
99
+ if (hex) {
100
+ const h = hex[1];
101
+ if (h.length === 3) {
102
+ return [
103
+ parseInt(h[0] + h[0], 16) / 255,
104
+ parseInt(h[1] + h[1], 16) / 255,
105
+ parseInt(h[2] + h[2], 16) / 255,
106
+ ];
107
+ }
108
+ return [
109
+ parseInt(h.slice(0, 2), 16) / 255,
110
+ parseInt(h.slice(2, 4), 16) / 255,
111
+ parseInt(h.slice(4, 6), 16) / 255,
112
+ ];
113
+ }
114
+ const hsl = HSL_RE.exec(s);
115
+ if (hsl) {
116
+ const h = Number(hsl[1]);
117
+ const sat = Number(hsl[2]);
118
+ const lig = Number(hsl[3]);
119
+ if (!Number.isFinite(h) || sat < 0 || sat > 100 || lig < 0 || lig > 100) {
120
+ throw new Error(`mono: invalid colour "${color}"`);
121
+ }
122
+ const hue = ((h % 360) + 360) % 360;
123
+ const S = sat / 100;
124
+ const L = lig / 100;
125
+ const a = S * Math.min(L, 1 - L);
126
+ const f = (n: number) => {
127
+ const k = (n + hue / 30) % 12;
128
+ return L - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));
129
+ };
130
+ return [f(0), f(8), f(4)];
131
+ }
132
+ throw new Error(`mono: invalid colour "${color}"`);
133
+ }
134
+
135
+ function luminance(color: string): number {
136
+ const [r, g, b] = parseColor(color);
137
+ // IEC 61966-2-1 / WCAG 2.1 sRGB transfer function
138
+ const lin = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
139
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
140
+ }
141
+
142
+ /** CIE lightness L* (0 to 100) of a #rgb, #rrggbb or hsl(h s% l%) colour. */
143
+ export function greyOf(color: string): number {
144
+ const y = luminance(color);
145
+ return y > 216 / 24389 ? 116 * Math.cbrt(y) - 16 : (24389 / 27) * y;
146
+ }
147
+
148
+ /** WCAG 2.1 contrast ratio between two colours (1 to 21). */
149
+ export function contrast(a: string, b: string): number {
150
+ const la = luminance(a);
151
+ const lb = luminance(b);
152
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);
153
+ }
154
+
155
+ const VALID_PATTERNS = new Set<string>(MONO.patterns);
156
+ const FIXED_KIND_INDEX = new Map<string, number>(MONO.kindOrder.map((k, i) => [k, i]));
157
+
158
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
159
+ const uniqueSorted = (names: readonly string[]) => [...new Set(names)].sort(cmp);
160
+ const round2 = (n: number) => Math.round(n * 100) / 100;
161
+
162
+ function stepFromLightness(lStar: number): MonoStep {
163
+ if (lStar >= STEP_THRESHOLDS[0]) return 0;
164
+ if (lStar >= STEP_THRESHOLDS[1]) return 1;
165
+ if (lStar >= STEP_THRESHOLDS[2]) return 2;
166
+ return 3;
167
+ }
168
+
169
+ function validateOwn(own: MonoTable): void {
170
+ if (own.roles) {
171
+ for (const [name, ov] of Object.entries(own.roles)) {
172
+ if (ov.step !== undefined) {
173
+ if (typeof ov.step !== 'number' || !Number.isInteger(ov.step) || ov.step < 0 || ov.step > 3) {
174
+ throw new Error(`mono: invalid step "${String(ov.step)}" for role "${name}"`);
175
+ }
176
+ }
177
+ if (ov.pattern !== undefined) {
178
+ if (typeof ov.pattern !== 'string' || !VALID_PATTERNS.has(ov.pattern)) {
179
+ throw new Error(`mono: invalid pattern "${String(ov.pattern)}" for role "${name}"`);
180
+ }
181
+ }
182
+ }
183
+ }
184
+ if (own.kinds) {
185
+ for (const [name, ov] of Object.entries(own.kinds)) {
186
+ if (ov.dash !== undefined) {
187
+ if (!Array.isArray(ov.dash) || !ov.dash.every(n => typeof n === 'number' && Number.isFinite(n) && n >= 0)) {
188
+ throw new Error(`mono: invalid dash "${String(ov.dash)}" for kind "${name}"`);
189
+ }
190
+ }
191
+ if (ov.width !== undefined) {
192
+ if (typeof ov.width !== 'number' || !Number.isFinite(ov.width) || ov.width <= 0) {
193
+ throw new Error(`mono: invalid width "${String(ov.width)}" for kind "${name}"`);
194
+ }
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ /** Map a theme's roles and kinds into deterministic monochrome steps, patterns and line rhythms. */
201
+ export function monoOf(
202
+ theme: Theme,
203
+ mode: 'light' | 'dark',
204
+ use?: { roles?: string[]; kinds?: string[] },
205
+ own?: MonoTable,
206
+ ): MonoLook {
207
+ if (mode !== 'light' && mode !== 'dark') throw new Error(`mono: invalid mode "${String(mode)}"`);
208
+ if (own) validateOwn(own);
209
+
210
+ const palette = MONO[mode];
211
+ const warnings: string[] = [];
212
+ const lTop = theme.light['l-top'];
213
+
214
+ const roleNames = uniqueSorted(use?.roles ?? Object.keys(theme.roles));
215
+ const stepByRole = new Map<string, MonoStep>();
216
+ const byStep: string[][] = [[], [], [], []];
217
+
218
+ for (const name of roleNames) {
219
+ const ovStep = own?.roles?.[name]?.step;
220
+ let step: MonoStep;
221
+ if (ovStep !== undefined) {
222
+ step = ovStep;
223
+ } else {
224
+ const def = theme.roles[name];
225
+ if (!def) throw new Error(`mono: unknown role "${name}"`);
226
+ if (typeof lTop !== 'string') throw new Error('mono: theme.light is missing "l-top"');
227
+ step = stepFromLightness(greyOf(`hsl(${def.h} ${def.s}% ${lTop})`));
228
+ }
229
+ stepByRole.set(name, step);
230
+ byStep[step].push(name);
231
+ }
232
+
233
+ const patternByRole = new Map<string, MonoPattern>();
234
+ for (let step = 0; step < byStep.length; step++) {
235
+ const group = byStep[step];
236
+ for (let i = 0; i < group.length; i++) {
237
+ const name = group[i];
238
+ const ovPattern = own?.roles?.[name]?.pattern;
239
+ if (ovPattern !== undefined) {
240
+ patternByRole.set(name, ovPattern);
241
+ } else {
242
+ const idx = i % MONO.patterns.length;
243
+ const pattern = MONO.patterns[idx];
244
+ patternByRole.set(name, pattern);
245
+ if (i >= MONO.patterns.length) {
246
+ const alike = group.slice(0, i).find(r => patternByRole.get(r) === pattern);
247
+ if (alike !== undefined) {
248
+ warnings.push(`role "${name}" wraps on step ${step} to pattern "${pattern}", matching "${alike}"`);
249
+ }
250
+ }
251
+ }
252
+ }
253
+ }
254
+
255
+ const roles: Record<string, MonoRoleLook> = {};
256
+ for (const name of roleNames) {
257
+ const step = stepByRole.get(name)!;
258
+ const pattern = patternByRole.get(name)!;
259
+ const face = palette.steps[step];
260
+ roles[name] = {
261
+ step,
262
+ pattern,
263
+ top: face.top,
264
+ left: face.left,
265
+ right: face.right,
266
+ edge: face.edge,
267
+ };
268
+ }
269
+
270
+ const kindNames = uniqueSorted(use?.kinds ?? Object.keys(theme.kinds));
271
+ const widthBump = mode === 'dark' ? MONO.darkWidthAdd : 0;
272
+ const kinds: Record<string, MonoRhythm> = {};
273
+ let extraIndex = 0;
274
+
275
+ for (const name of kindNames) {
276
+ const ov = own?.kinds?.[name];
277
+ const fixedIdx = FIXED_KIND_INDEX.get(name);
278
+ let rhythmIdx: number;
279
+ if (fixedIdx !== undefined) {
280
+ rhythmIdx = fixedIdx;
281
+ } else {
282
+ rhythmIdx = MONO.kindOrder.length + extraIndex;
283
+ extraIndex++;
284
+ if (rhythmIdx >= MONO.rhythms.length) {
285
+ const wrapped = rhythmIdx % MONO.rhythms.length;
286
+ if (!ov || ov.dash === undefined || ov.width === undefined) {
287
+ warnings.push(`kind "${name}" exceeds the ${MONO.rhythms.length} line rhythms; reusing rhythm ${wrapped}`);
288
+ }
289
+ rhythmIdx = wrapped;
290
+ }
291
+ }
292
+ const base = MONO.rhythms[rhythmIdx];
293
+ const dash = ov?.dash !== undefined ? [...ov.dash] : [...base.dash];
294
+ const width = ov?.width !== undefined ? ov.width : round2(base.width + widthBump);
295
+ kinds[name] = { dash, width };
296
+ }
297
+
298
+ return {
299
+ mode,
300
+ paper: palette.paper,
301
+ ink: palette.ink,
302
+ roles,
303
+ kinds,
304
+ warnings,
305
+ };
306
+ }