ceulen-dsh 0.2.12 → 0.2.14

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 (60) hide show
  1. package/README.md +176 -13
  2. package/lib/core/upstream.d.ts.map +1 -1
  3. package/lib/core/upstream.js +26 -5
  4. package/lib/core/upstream.js.map +1 -1
  5. package/lib/core/user-words.d.ts +6 -2
  6. package/lib/core/user-words.d.ts.map +1 -1
  7. package/lib/core/user-words.js +28 -6
  8. package/lib/core/user-words.js.map +1 -1
  9. package/lib/modules/classifier/index.js +1 -1
  10. package/lib/modules/classifier/index.js.map +1 -1
  11. package/lib/modules/status/index.d.ts.map +1 -1
  12. package/lib/modules/status/index.js +4 -2
  13. package/lib/modules/status/index.js.map +1 -1
  14. package/lib/modules/steering/index.js +1 -1
  15. package/lib/modules/steering/index.js.map +1 -1
  16. package/lib/modules/subagent/index.d.ts.map +1 -1
  17. package/lib/modules/subagent/index.js +5 -0
  18. package/lib/modules/subagent/index.js.map +1 -1
  19. package/lib/modules/ux/auto.d.ts +27 -4
  20. package/lib/modules/ux/auto.d.ts.map +1 -1
  21. package/lib/modules/ux/auto.js +70 -11
  22. package/lib/modules/ux/auto.js.map +1 -1
  23. package/lib/modules/ux/index.d.ts +5 -0
  24. package/lib/modules/ux/index.d.ts.map +1 -1
  25. package/lib/modules/ux/index.js +60 -10
  26. package/lib/modules/ux/index.js.map +1 -1
  27. package/lib/modules/ux/kit.d.ts +79 -0
  28. package/lib/modules/ux/kit.d.ts.map +1 -0
  29. package/lib/modules/ux/kit.js +449 -0
  30. package/lib/modules/ux/kit.js.map +1 -0
  31. package/lib/modules/ux/review.d.ts.map +1 -1
  32. package/lib/modules/ux/review.js +30 -4
  33. package/lib/modules/ux/review.js.map +1 -1
  34. package/package.json +2 -2
  35. package/scripts/pack-contract.mjs +9 -0
  36. package/scripts/tui-plan-patch.mjs +138 -1
  37. package/scripts/tui-question-fit-smoke.mjs +161 -0
  38. package/skills/dsh-update/SKILL.md +29 -4
  39. package/skills/ux-design/SKILL.md +6 -4
  40. package/skills/ux-design/kit/base.css +49 -0
  41. package/skills/ux-design/kit/diagram.js +598 -0
  42. package/skills/ux-design/kit/motion.js +2 -1
  43. package/skills/ux-design/references/diagram.md +79 -0
  44. package/skills/ux-design/references/motion.md +10 -5
  45. package/skills/ux-presets/SKILL.md +18 -3
  46. package/skills/ux-presets/presets/bento/DESIGN.md +3 -0
  47. package/skills/ux-presets/presets/bento/example.html +1 -1
  48. package/skills/ux-presets/presets/care/DESIGN.md +3 -0
  49. package/skills/ux-presets/presets/care/example.html +1 -1
  50. package/skills/ux-presets/presets/civic/DESIGN.md +3 -0
  51. package/skills/ux-presets/presets/civic/example.html +1 -1
  52. package/skills/ux-presets/presets/explainer/DESIGN.md +119 -0
  53. package/skills/ux-presets/presets/explainer/example.html +238 -0
  54. package/skills/ux-presets/presets/instrument-panel/DESIGN.md +3 -1
  55. package/skills/ux-presets/presets/instrument-panel/example.html +1 -1
  56. package/skills/ux-presets/presets/ledger/DESIGN.md +3 -1
  57. package/skills/ux-presets/presets/ledger/example.html +1 -1
  58. package/skills/ux-presets/presets/pipeline-desk/DESIGN.md +3 -1
  59. package/skills/ux-presets/presets/pipeline-desk/example.html +1 -1
  60. package/skills/ux-presets/presets.json +645 -0
@@ -0,0 +1,598 @@
1
+ // Diagram kit. Copy this file next to the page, do not retype it.
2
+ // It turns plain lines into a laid-out, animated block diagram:
3
+ //
4
+ // <figure data-diagram>
5
+ // <pre>
6
+ // User -> Router: prompt
7
+ // Router -> Fast model: easy task
8
+ // Router -> Strong model: hard task
9
+ // Router :: picks a model per request
10
+ // [Harness] Router, Fast model, Strong model
11
+ // step: User, Router | A prompt arrives at the router
12
+ // </pre>
13
+ // <figcaption>How a request is routed</figcaption>
14
+ // </figure>
15
+ //
16
+ // Never place a box or a line by hand. See references/diagram.md.
17
+ (() => {
18
+ const root = document.documentElement
19
+ if (root.dataset.diagramKit !== undefined) return
20
+ root.dataset.diagramKit = 'on'
21
+ const calm = matchMedia('(prefers-reduced-motion: reduce)').matches
22
+ const NS = 'http://www.w3.org/2000/svg'
23
+ const out = 'cubic-bezier(0.22, 1, 0.36, 1)'
24
+ let serial = 0
25
+
26
+ const style = document.createElement('style')
27
+ style.dataset.diagramKit = ''
28
+ style.textContent = `
29
+ [data-diagram] { --d-bg: var(--k-bg, Canvas); --d-surface: var(--k-surface, Canvas); --d-text: var(--k-text, CanvasText); --d-muted: var(--k-muted, GrayText); --d-line: var(--k-link, var(--k-accent, CanvasText)); --d-accent: var(--k-accent, Highlight); --d-on-accent: var(--k-on-accent, HighlightText); --d-stroke: color-mix(in srgb, var(--d-text) 28%, transparent); }
30
+ [data-diagram] .d-scroll { max-width: 100%; overflow-x: auto; }
31
+ [data-diagram] .d-svg { display: block; height: auto; max-width: 100%; margin-inline: auto; font-family: inherit; overflow: visible; }
32
+ [data-diagram] .d-node rect { fill: var(--d-surface); stroke: var(--d-stroke); stroke-width: 1.5; transition: stroke 240ms, stroke-width 240ms; }
33
+ [data-diagram] .d-node text { fill: var(--d-text); font-size: 14px; font-weight: 600; }
34
+ [data-diagram] .d-node .d-note { fill: var(--d-muted); font-size: 12px; font-weight: 400; }
35
+ [data-diagram] .d-node[data-tone="accent"] rect { fill: var(--d-accent); stroke: var(--d-accent); }
36
+ [data-diagram] .d-node[data-tone="accent"] text, [data-diagram] .d-node[data-tone="accent"] .d-note { fill: var(--d-on-accent); }
37
+ [data-diagram] .d-node[data-tone="muted"] rect { fill: transparent; stroke-dasharray: 4 4; }
38
+ [data-diagram] .d-node[data-tone="muted"] text { fill: var(--d-muted); }
39
+ [data-diagram] .d-edge path { fill: none; stroke: var(--d-line); stroke-width: 1.75; stroke-linecap: round; }
40
+ [data-diagram] .d-edge[data-dashed] path { stroke-dasharray: 5 6; }
41
+ [data-diagram] .d-edge text { fill: var(--d-muted); font-size: 12px; font-weight: 500; }
42
+ [data-diagram] .d-edge .d-label-bg { fill: var(--d-bg); }
43
+ [data-diagram] .d-arrow { fill: var(--d-line); }
44
+ [data-diagram] .d-dot { fill: var(--d-line); opacity: 0; pointer-events: none; }
45
+ [data-diagram] .d-group rect { fill: color-mix(in srgb, var(--d-text) 4%, transparent); stroke: var(--d-stroke); stroke-width: 1; stroke-dasharray: 2 5; }
46
+ [data-diagram] .d-group text { fill: var(--d-muted); font-size: 12px; font-weight: 600; }
47
+ [data-diagram] .d-node, [data-diagram] .d-edge, [data-diagram] .d-group { transition: opacity 240ms; }
48
+ [data-diagram] .d-dim { opacity: 0.25; }
49
+ [data-diagram] .d-on rect { stroke: var(--d-line); stroke-width: 2.5; }
50
+ [data-diagram] .d-on[data-tone="accent"] rect { stroke: var(--d-text); }
51
+ [data-diagram] .d-steps { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-top: 16px; }
52
+ [data-diagram] .d-steps p { flex: 1 1 14rem; margin: 0; color: var(--d-text); }
53
+ [data-diagram] .d-steps b { color: var(--d-muted); font-weight: 600; font-variant-numeric: tabular-nums; margin-right: 0.5em; }
54
+ [data-diagram] .d-steps button { flex: none; min-height: 44px; min-width: 44px; padding: 0 18px; border-radius: 999px; border: 1.5px solid var(--d-stroke); background: var(--d-surface); color: var(--d-text); font: inherit; font-weight: 600; cursor: pointer; transition: transform 150ms; }
55
+ [data-diagram] .d-steps .d-next { background: var(--d-accent); color: var(--d-on-accent); border-color: transparent; }
56
+ [data-diagram] .d-steps button:active { transform: scale(0.97); }
57
+ [data-diagram] .d-steps button:focus-visible { outline: 2px solid var(--d-line); outline-offset: 2px; }
58
+ [data-diagram] .d-steps button:disabled { opacity: 0.5; cursor: not-allowed; }
59
+ [data-diagram] .d-error { margin: 8px 0 0; color: var(--d-text); font-weight: 600; }
60
+ @media (prefers-reduced-motion: reduce) { [data-diagram] * { transition: none !important; } }
61
+ `
62
+ document.head.append(style)
63
+
64
+ /* ---------- reading the lines ---------- */
65
+
66
+ function parse (source) {
67
+ const nodes = new Map()
68
+ const edges = []
69
+ const groups = []
70
+ const steps = []
71
+ const tones = []
72
+ const errors = []
73
+ const node = (name) => {
74
+ const id = name.trim()
75
+ if (id === '') return null
76
+ if (!nodes.has(id)) nodes.set(id, { id, note: '', tone: '' })
77
+ return nodes.get(id)
78
+ }
79
+ const list = (text) => text.split(',').map((part) => part.trim()).filter((part) => part !== '')
80
+ source.split('\n').forEach((raw, index) => {
81
+ const at = index + 1
82
+ const line = raw.trim()
83
+ if (line === '' || line.startsWith('#') || line.startsWith('//')) return
84
+ let match = /^step\s*:\s*(.*)$/i.exec(line)
85
+ if (match !== null) {
86
+ const bar = match[1].indexOf('|')
87
+ steps.push({ at, ids: list(bar < 0 ? match[1] : match[1].slice(0, bar)), text: bar < 0 ? '' : match[1].slice(bar + 1).trim() })
88
+ return
89
+ }
90
+ match = /^(accent|muted)\s*:\s*(.*)$/i.exec(line)
91
+ if (match !== null) {
92
+ tones.push({ at, tone: match[1].toLowerCase(), ids: list(match[2]) })
93
+ return
94
+ }
95
+ match = /^\[(.+?)\]\s*(.*)$/.exec(line)
96
+ if (match !== null) {
97
+ groups.push({ at, label: match[1].trim(), ids: list(match[2]) })
98
+ return
99
+ }
100
+ match = /^(.+?)\s*::\s*(.+)$/.exec(line)
101
+ if (match !== null && !/->/.test(match[1])) {
102
+ const target = node(match[1])
103
+ if (target !== null) target.note = match[2].trim()
104
+ return
105
+ }
106
+ if (/->/.test(line)) {
107
+ const colon = line.indexOf(':', line.lastIndexOf('->'))
108
+ const label = colon < 0 ? '' : line.slice(colon + 1).trim()
109
+ const parts = (colon < 0 ? line : line.slice(0, colon)).split(/\s*(<->|-->|->)\s*/)
110
+ for (let i = 0; i + 2 < parts.length; i += 2) {
111
+ const from = node(parts[i])
112
+ const to = node(parts[i + 2])
113
+ if (from === null || to === null) { errors.push(`line ${at}: an arrow needs a name on both sides`); return }
114
+ if (from === to) continue
115
+ edges.push({ from: from.id, to: to.id, label: i + 3 === parts.length ? label : '', dashed: parts[i + 1] === '-->', both: parts[i + 1] === '<->' })
116
+ }
117
+ return
118
+ }
119
+ if (!/[:|]/.test(line)) { node(line); return }
120
+ errors.push(`line ${at}: not understood: "${line.slice(0, 60)}"`)
121
+ })
122
+ const known = (entry, what) => {
123
+ const missing = entry.ids.filter((id) => !nodes.has(id))
124
+ if (missing.length > 0) errors.push(`line ${entry.at}: ${what} names "${missing.join('", "')}", which no arrow line has. Names must match exactly.`)
125
+ return missing.length === 0
126
+ }
127
+ for (const entry of tones) if (known(entry, entry.tone)) for (const id of entry.ids) nodes.get(id).tone = entry.tone
128
+ for (const group of groups) known(group, 'the group')
129
+ for (const step of steps) known(step, 'the step')
130
+ if (nodes.size === 0 && errors.length === 0) errors.push('no boxes: write lines such as "User -> Router: prompt"')
131
+ return { nodes: [...nodes.values()], edges, groups, steps, errors }
132
+ }
133
+
134
+ /* ---------- measuring text ---------- */
135
+
136
+ const canvas = document.createElement('canvas').getContext('2d')
137
+ function wrap (text, font, maxWidth, maxLines) {
138
+ canvas.font = font
139
+ const lines = []
140
+ let line = ''
141
+ for (const word of text.split(/\s+/)) {
142
+ const next = line === '' ? word : `${line} ${word}`
143
+ if (line !== '' && canvas.measureText(next).width > maxWidth) { lines.push(line); line = word } else line = next
144
+ }
145
+ if (line !== '') lines.push(line)
146
+ if (lines.length > maxLines) {
147
+ lines.length = maxLines
148
+ lines[maxLines - 1] = `${lines[maxLines - 1].replace(/.{2}$/, '')}…`
149
+ }
150
+ return { lines, width: Math.max(0, ...lines.map((entry) => canvas.measureText(entry).width)) }
151
+ }
152
+
153
+ /* ---------- layout: ranks, order, positions ---------- */
154
+
155
+ function layout (graph, family, across, textMax) {
156
+ const titleFont = `600 14px ${family}`
157
+ const noteFont = `400 12px ${family}`
158
+ const labelFont = `500 12px ${family}`
159
+ const items = new Map()
160
+ graph.nodes.forEach((node, index) => {
161
+ const title = wrap(node.id, titleFont, textMax, 3)
162
+ const note = node.note === '' ? { lines: [], width: 0 } : wrap(node.note, noteFont, textMax, 3)
163
+ items.set(node.id, {
164
+ ...node, index, title: title.lines, noteLines: note.lines, real: true,
165
+ w: Math.max(96, Math.ceil(Math.max(title.width, note.width)) + 32),
166
+ h: 24 + title.lines.length * 18 + (note.lines.length === 0 ? 0 : 4 + note.lines.length * 16),
167
+ ins: [], outs: [], rank: 0,
168
+ })
169
+ })
170
+
171
+ /* a cycle is drawn against the flow: find the arrows that close one */
172
+ const links = []
173
+ const state = new Map()
174
+ const outgoing = new Map(graph.nodes.map((node) => [node.id, []]))
175
+ for (const edge of graph.edges) outgoing.get(edge.from).push(edge)
176
+ const back = new Set()
177
+ const visit = (id) => {
178
+ state.set(id, 1)
179
+ for (const edge of outgoing.get(id)) {
180
+ if (state.get(edge.to) === 1) back.add(edge)
181
+ else if (state.get(edge.to) === undefined) visit(edge.to)
182
+ }
183
+ state.set(id, 2)
184
+ }
185
+ for (const node of graph.nodes) if (state.get(node.id) === undefined) visit(node.id)
186
+ for (const edge of graph.edges) {
187
+ const rev = back.has(edge)
188
+ links.push({ edge, rev, s: rev ? edge.to : edge.from, t: rev ? edge.from : edge.to })
189
+ }
190
+ for (const link of links) { items.get(link.s).outs.push(link); items.get(link.t).ins.push(link) }
191
+
192
+ /* rank = longest path from a start; a start then moves up beside what it feeds */
193
+ const order = []
194
+ const seen = new Set()
195
+ const topo = (id) => { if (seen.has(id)) return; seen.add(id); for (const link of items.get(id).ins) topo(link.s); order.push(id) }
196
+ for (const node of graph.nodes) topo(node.id)
197
+ for (const id of order) { const item = items.get(id); item.rank = Math.max(0, ...item.ins.map((link) => items.get(link.s).rank + 1)) }
198
+ for (const id of order) {
199
+ const item = items.get(id)
200
+ if (item.ins.length === 0 && item.outs.length > 0) item.rank = Math.max(0, Math.min(...item.outs.map((link) => items.get(link.t).rank)) - 1)
201
+ }
202
+
203
+ /* an arrow across several ranks gets a waypoint in each, so it bends round boxes */
204
+ const layers = []
205
+ const put = (item) => {
206
+ layers[item.rank] ??= []
207
+ layers[item.rank].push(item)
208
+ }
209
+ for (const node of graph.nodes) put(items.get(node.id))
210
+ for (const link of links) {
211
+ const from = items.get(link.s)
212
+ const to = items.get(link.t)
213
+ link.path = [from]
214
+ for (let rank = from.rank + 1; rank < to.rank; rank++) {
215
+ const way = { real: false, rank, index: from.index, w: across ? 0 : 16, h: across ? 16 : 0, ins: [], outs: [], id: `way-${links.indexOf(link)}-${rank}` }
216
+ put(way)
217
+ link.path.push(way)
218
+ }
219
+ link.path.push(to)
220
+ for (let i = 0; i + 1 < link.path.length; i++) { link.path[i].next = (link.path[i].next ?? []).concat(link.path[i + 1]); link.path[i + 1].prev = (link.path[i + 1].prev ?? []).concat(link.path[i]) }
221
+ }
222
+ for (let rank = 0; rank < layers.length; rank++) layers[rank] ??= []
223
+
224
+ /* order inside a rank: each box sits at the average place of its neighbours, group members together */
225
+ const groupOf = new Map()
226
+ graph.groups.forEach((group, index) => { for (const id of group.ids) if (!groupOf.has(id)) groupOf.set(id, index) })
227
+ for (const layer of layers) {
228
+ layer.sort((a, b) => a.index - b.index)
229
+ for (const [place, item] of layer.entries()) item.place = place
230
+ }
231
+ const sweep = (layer, side) => {
232
+ const keyed = layer.map((item) => {
233
+ const near = item[side] ?? []
234
+ return { item, key: near.length === 0 ? item.place : near.reduce((sum, other) => sum + other.place, 0) / near.length }
235
+ })
236
+ const groupKey = new Map()
237
+ for (const entry of keyed) {
238
+ const group = entry.item.real ? groupOf.get(entry.item.id) : undefined
239
+ if (group === undefined) continue
240
+ const bucket = groupKey.get(group) ?? { sum: 0, count: 0 }
241
+ bucket.sum += entry.key; bucket.count += 1
242
+ groupKey.set(group, bucket)
243
+ }
244
+ for (const entry of keyed) {
245
+ const group = entry.item.real ? groupOf.get(entry.item.id) : undefined
246
+ entry.cluster = group === undefined ? entry.key : groupKey.get(group).sum / groupKey.get(group).count
247
+ }
248
+ keyed.sort((a, b) => a.cluster - b.cluster || a.key - b.key || a.item.place - b.item.place)
249
+ keyed.forEach((entry, place) => { entry.item.place = place })
250
+ layer.sort((a, b) => a.place - b.place)
251
+ }
252
+ for (let round = 0; round < 4; round++) {
253
+ for (let rank = 1; rank < layers.length; rank++) sweep(layers[rank], 'prev')
254
+ for (let rank = layers.length - 2; rank >= 0; rank--) sweep(layers[rank], 'next')
255
+ }
256
+
257
+ /* positions. "main" runs along the flow, "cross" runs across it */
258
+ const hasGroups = graph.groups.length > 0
259
+ const main = (item) => (across ? item.w : item.h)
260
+ const cross = (item) => (across ? item.h : item.w)
261
+ const crossGap = (across ? 22 : 28) + (hasGroups ? 14 : 0)
262
+ canvas.font = labelFont
263
+ const labelSize = (rank) => {
264
+ let size = 0
265
+ for (const link of links) {
266
+ if (link.edge.label === '') continue
267
+ const middle = link.path[Math.floor((link.path.length - 1) / 2)].rank
268
+ if (middle === rank) size = Math.max(size, across ? canvas.measureText(link.edge.label).width + 28 : 30)
269
+ }
270
+ return size
271
+ }
272
+ let cursor = 0
273
+ const rankStart = []
274
+ layers.forEach((layer, rank) => {
275
+ rankStart[rank] = cursor
276
+ const size = Math.max(0, ...layer.map(main))
277
+ for (const item of layer) item.m = cursor + (size - main(item)) / 2
278
+ cursor += size + Math.max(across ? 64 : 52, labelSize(rank)) + (hasGroups ? 16 : 0)
279
+ })
280
+ for (const layer of layers) {
281
+ let at = 0
282
+ for (const item of layer) { item.c = at; at += cross(item) + crossGap }
283
+ const shift = (at - crossGap) / 2
284
+ for (const item of layer) item.c -= shift
285
+ }
286
+ const settle = (layer, side) => {
287
+ const wanted = layer.map((item) => {
288
+ const near = item[side] ?? []
289
+ return near.length === 0 ? item.c + cross(item) / 2 : near.reduce((sum, other) => sum + other.c + cross(other) / 2, 0) / near.length
290
+ })
291
+ let edge = -Infinity
292
+ let drift = 0
293
+ layer.forEach((item, i) => {
294
+ item.c = Math.max(wanted[i] - cross(item) / 2, edge)
295
+ edge = item.c + cross(item) + crossGap
296
+ drift += item.c + cross(item) / 2 - wanted[i]
297
+ })
298
+ drift /= Math.max(1, layer.length)
299
+ for (const item of layer) item.c -= drift
300
+ }
301
+ for (let round = 0; round < 3; round++) {
302
+ for (let rank = 1; rank < layers.length; rank++) settle(layers[rank], 'prev')
303
+ for (let rank = layers.length - 2; rank >= 0; rank--) settle(layers[rank], 'next')
304
+ }
305
+ const all = layers.flat()
306
+ const pad = hasGroups ? 34 : 14
307
+ const low = Math.min(...all.map((item) => item.c))
308
+ for (const item of all) {
309
+ item.x = (across ? item.m : item.c - low) + pad
310
+ item.y = (across ? item.c - low : item.m) + pad
311
+ }
312
+
313
+ /* groups: a frame round the members, unless another box would end up inside it */
314
+ const frames = []
315
+ for (const group of graph.groups) {
316
+ const members = group.ids.map((id) => items.get(id)).filter((item) => item !== undefined)
317
+ if (members.length === 0) continue
318
+ const frame = {
319
+ label: group.label, ids: group.ids,
320
+ x: Math.min(...members.map((item) => item.x)) - 14,
321
+ y: Math.min(...members.map((item) => item.y)) - 30,
322
+ right: Math.max(...members.map((item) => item.x + item.w)) + 14,
323
+ bottom: Math.max(...members.map((item) => item.y + item.h)) + 14,
324
+ }
325
+ const crowded = all.some((item) => item.real && !group.ids.includes(item.id) && item.x < frame.right && item.x + item.w > frame.x && item.y < frame.bottom && item.y + item.h > frame.y)
326
+ if (!crowded) frames.push(frame)
327
+ }
328
+
329
+ /* arrows: a smooth curve through the waypoints, two arrows between one pair kept apart */
330
+ const pairCount = new Map()
331
+ const pairKey = (link) => [link.s, link.t].sort().join('\u0000')
332
+ for (const link of links) pairCount.set(pairKey(link), (pairCount.get(pairKey(link)) ?? 0) + 1)
333
+ const pairSeen = new Map()
334
+ const routes = links.map((link) => {
335
+ const total = pairCount.get(pairKey(link))
336
+ const nth = pairSeen.get(pairKey(link)) ?? 0
337
+ pairSeen.set(pairKey(link), nth + 1)
338
+ const offset = (nth - (total - 1) / 2) * 16
339
+ const points = link.path.map((item, i) => {
340
+ const first = i === 0
341
+ const last = i === link.path.length - 1
342
+ const centre = { x: item.x + item.w / 2, y: item.y + item.h / 2 }
343
+ if (across) return { x: first ? item.x + item.w : last ? item.x : centre.x, y: centre.y + (item.real ? offset : 0) }
344
+ return { x: centre.x + (item.real ? offset : 0), y: first ? item.y + item.h : last ? item.y : centre.y }
345
+ })
346
+ let d = `M${points[0].x},${points[0].y}`
347
+ for (let i = 0; i + 1 < points.length; i++) {
348
+ const a = points[i]
349
+ const b = points[i + 1]
350
+ d += across
351
+ ? ` C${(a.x + b.x) / 2},${a.y} ${(a.x + b.x) / 2},${b.y} ${b.x},${b.y}`
352
+ : ` C${a.x},${(a.y + b.y) / 2} ${b.x},${(a.y + b.y) / 2} ${b.x},${b.y}`
353
+ }
354
+ const half = Math.floor((points.length - 1) / 2)
355
+ const from = points[half]
356
+ const to = points[half + 1]
357
+ return { link, d, label: { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2, width: link.edge.label === '' ? 0 : canvas.measureText(link.edge.label).width }, rank: items.get(link.s).rank }
358
+ })
359
+
360
+ const width = Math.max(...all.map((item) => item.x + item.w), ...frames.map((frame) => frame.right)) + pad
361
+ const height = Math.max(...all.map((item) => item.y + item.h), ...frames.map((frame) => frame.bottom)) + pad
362
+ return { boxes: all.filter((item) => item.real), routes, frames, width, height, across }
363
+ }
364
+
365
+ /* ---------- drawing ---------- */
366
+
367
+ const svgEl = (name, attributes = {}, text) => {
368
+ const el = document.createElementNS(NS, name)
369
+ for (const [key, value] of Object.entries(attributes)) el.setAttribute(key, String(value))
370
+ if (text !== undefined) el.textContent = text
371
+ return el
372
+ }
373
+
374
+ function pageBackground (el) {
375
+ for (let node = el; node !== null; node = node.parentElement) {
376
+ const colour = getComputedStyle(node).backgroundColor
377
+ if (colour !== 'rgba(0, 0, 0, 0)' && colour !== 'transparent') return colour
378
+ }
379
+ return ''
380
+ }
381
+
382
+ function draw (figure) {
383
+ const source = figure.querySelector(':scope > pre, :scope > script[type="text/plain"]')
384
+ if (source === null) return
385
+ const graph = parse(source.textContent ?? '')
386
+ for (const el of figure.querySelectorAll(':scope > .d-scroll, :scope > .d-steps, :scope > .d-error')) el.remove()
387
+ if (graph.errors.length > 0) {
388
+ figure.dataset.diagramState = 'error'
389
+ source.hidden = false
390
+ const note = document.createElement('p')
391
+ note.className = 'd-error'
392
+ note.setAttribute('role', 'alert')
393
+ note.textContent = `Diagram not drawn — ${graph.errors.join('; ')}`
394
+ source.after(note)
395
+ console.error(`diagram.js: ${graph.errors.join('; ')}`)
396
+ return
397
+ }
398
+
399
+ const family = getComputedStyle(figure).fontFamily
400
+ const room = Math.max(280, figure.clientWidth)
401
+ const wanted = figure.dataset.diagram
402
+ const textMax = room < 520 ? 132 : 176
403
+ let plan
404
+ if (wanted === 'down') plan = layout(graph, family, false, textMax)
405
+ else if (wanted === 'right') plan = layout(graph, family, true, textMax)
406
+ else {
407
+ plan = layout(graph, family, true, textMax)
408
+ if (room / plan.width < 0.8) {
409
+ const tall = layout(graph, family, false, textMax)
410
+ if (room / tall.width > room / plan.width) plan = tall
411
+ }
412
+ }
413
+ const background = pageBackground(figure)
414
+ if (background !== '') figure.style.setProperty('--d-bg', background)
415
+
416
+ const id = `d${++serial}`
417
+ const caption = figure.querySelector(':scope > figcaption')
418
+ const svg = svgEl('svg', { class: 'd-svg', viewBox: `0 0 ${Math.ceil(plan.width)} ${Math.ceil(plan.height)}`, width: Math.ceil(plan.width), height: Math.ceil(plan.height), role: 'img' })
419
+ svg.setAttribute('aria-label', (caption?.textContent ?? 'Diagram').trim())
420
+ svg.append(svgEl('desc', {}, graph.edges.map((edge) => `${edge.from} to ${edge.to}${edge.label === '' ? '' : `: ${edge.label}`}`).join('. ')))
421
+ /* text stays readable: below 70% the figure scrolls sideways instead of shrinking further */
422
+ if (room / plan.width < 0.7) svg.style.minWidth = `${Math.ceil(plan.width * 0.7)}px`
423
+ const defs = svgEl('defs')
424
+ /* one arrowhead for both ends: auto-start-reverse turns it round at the start of a line */
425
+ const marker = svgEl('marker', { id: `${id}-arrow`, viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 9, markerHeight: 9, orient: 'auto-start-reverse', markerUnits: 'userSpaceOnUse' })
426
+ marker.append(svgEl('path', { class: 'd-arrow', d: 'M0,1 L10,5 L0,9 z' }))
427
+ defs.append(marker)
428
+ svg.append(defs)
429
+
430
+ const groupLayer = svgEl('g', { class: 'd-groups' })
431
+ for (const frame of plan.frames) {
432
+ const g = svgEl('g', { class: 'd-group' })
433
+ g.append(svgEl('rect', { x: frame.x, y: frame.y, width: frame.right - frame.x, height: frame.bottom - frame.y, rx: 14 }))
434
+ g.append(svgEl('text', { x: frame.x + 14, y: frame.y + 19 }, frame.label))
435
+ g.mIds = frame.ids
436
+ groupLayer.append(g)
437
+ }
438
+ const edgeLayer = svgEl('g', { class: 'd-edges' })
439
+ const edges = plan.routes.map((route) => {
440
+ const g = svgEl('g', { class: 'd-edge' })
441
+ const edge = route.link.edge
442
+ if (edge.dashed) g.setAttribute('data-dashed', '')
443
+ const path = svgEl('path', { d: route.d })
444
+ const forward = !route.link.rev
445
+ if (edge.both || forward) path.setAttribute('marker-end', `url(#${id}-arrow)`)
446
+ if (edge.both || !forward) path.setAttribute('marker-start', `url(#${id}-arrow)`)
447
+ g.append(path)
448
+ if (edge.label !== '') {
449
+ g.append(svgEl('rect', { class: 'd-label-bg', x: route.label.x - route.label.width / 2 - 6, y: route.label.y - 10, width: route.label.width + 12, height: 20, rx: 4 }))
450
+ g.append(svgEl('text', { x: route.label.x, y: route.label.y + 4, 'text-anchor': 'middle' }, edge.label))
451
+ }
452
+ const dot = svgEl('circle', { class: 'd-dot', r: 4 })
453
+ g.append(dot)
454
+ edgeLayer.append(g)
455
+ return { g, path, dot, from: edge.from, to: edge.to, rank: route.rank, forward, dashed: edge.dashed }
456
+ })
457
+ const nodeLayer = svgEl('g', { class: 'd-nodes' })
458
+ const nodes = plan.boxes.map((box) => {
459
+ const g = svgEl('g', { class: 'd-node' })
460
+ if (box.tone !== '') g.setAttribute('data-tone', box.tone)
461
+ g.append(svgEl('rect', { x: box.x, y: box.y, width: box.w, height: box.h, rx: 10 }))
462
+ const text = svgEl('text', { 'text-anchor': 'middle' })
463
+ let y = box.y + 12 + 14
464
+ for (const line of box.title) { text.append(svgEl('tspan', { x: box.x + box.w / 2, y }, line)); y += 18 }
465
+ y += 2
466
+ for (const line of box.noteLines) { text.append(svgEl('tspan', { class: 'd-note', x: box.x + box.w / 2, y }, line)); y += 16 }
467
+ g.append(text)
468
+ nodeLayer.append(g)
469
+ return { g, id: box.id, rank: box.rank }
470
+ })
471
+ svg.append(groupLayer, edgeLayer, nodeLayer)
472
+ const scroll = document.createElement('div')
473
+ scroll.className = 'd-scroll'
474
+ scroll.append(svg)
475
+ source.hidden = true
476
+ source.after(scroll)
477
+ figure.dataset.diagramState = 'ok'
478
+
479
+ /* ---------- motion ---------- */
480
+
481
+ const run = (entry) => {
482
+ if (calm) return
483
+ const length = entry.path.getTotalLength()
484
+ const start = performance.now()
485
+ const frame = (now) => {
486
+ const t = Math.min(1, (now - start) / 720)
487
+ const eased = t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2
488
+ const point = entry.path.getPointAtLength((entry.forward ? eased : 1 - eased) * length)
489
+ entry.dot.setAttribute('cx', point.x)
490
+ entry.dot.setAttribute('cy', point.y)
491
+ entry.dot.style.opacity = t < 1 ? '1' : '0'
492
+ if (t < 1 && entry.dot.isConnected) requestAnimationFrame(frame)
493
+ }
494
+ requestAnimationFrame(frame)
495
+ }
496
+ const beat = 120
497
+ const enter = () => {
498
+ if (calm) return
499
+ for (const node of nodes) node.g.animate({ opacity: [0, 1], transform: [plan.across ? 'translateX(-10px)' : 'translateY(-10px)', 'none'] }, { duration: 520, delay: node.rank * beat, easing: out, fill: 'backwards' })
500
+ for (const group of groupLayer.children) group.animate({ opacity: [0, 1] }, { duration: 600, easing: out })
501
+ for (const entry of edges) {
502
+ const delay = entry.rank * beat + 260
503
+ entry.g.animate({ opacity: [0, 1] }, { duration: 260, delay, fill: 'backwards' })
504
+ if (!entry.dashed) {
505
+ const length = entry.path.getTotalLength()
506
+ entry.path.animate({ strokeDasharray: [`${length} ${length}`, `${length} ${length}`], strokeDashoffset: entry.forward ? [length, 0] : [-length, 0] }, { duration: 560, delay, easing: out, fill: 'backwards' })
507
+ }
508
+ setTimeout(() => run(entry), delay + 420)
509
+ }
510
+ }
511
+
512
+ /* the reader's pointer: a box lights its own arrows and sends a dot down each */
513
+ const light = (ids) => {
514
+ for (const node of nodes) { node.g.classList.toggle('d-on', ids !== null && ids.has(node.id)); node.g.classList.toggle('d-dim', ids !== null && !ids.has(node.id)) }
515
+ for (const entry of edges) entry.g.classList.toggle('d-dim', ids !== null && !(ids.has(entry.from) && ids.has(entry.to)))
516
+ for (const group of groupLayer.children) group.classList.toggle('d-dim', ids !== null && !group.mIds.some((member) => ids.has(member)))
517
+ }
518
+ let step = -1
519
+ const showStep = () => {
520
+ if (graph.steps.length === 0 || step < 0) { light(null); return }
521
+ const ids = new Set(graph.steps[step].ids)
522
+ light(ids)
523
+ for (const entry of edges) if (ids.has(entry.from) && ids.has(entry.to)) run(entry)
524
+ }
525
+ for (const node of nodes) {
526
+ node.g.addEventListener('pointerenter', () => {
527
+ const ids = new Set([node.id])
528
+ for (const entry of edges) if (entry.from === node.id || entry.to === node.id) { ids.add(entry.from); ids.add(entry.to) }
529
+ light(ids)
530
+ for (const entry of edges) if (entry.from === node.id) run(entry)
531
+ })
532
+ node.g.addEventListener('pointerleave', showStep)
533
+ }
534
+
535
+ /* steps: the reader sets the pace */
536
+ if (graph.steps.length > 0) {
537
+ const bar = document.createElement('div')
538
+ bar.className = 'd-steps'
539
+ const prev = Object.assign(document.createElement('button'), { type: 'button', className: 'd-prev', textContent: 'Back' })
540
+ const next = Object.assign(document.createElement('button'), { type: 'button', className: 'd-next', textContent: 'Next' })
541
+ const text = document.createElement('p')
542
+ text.setAttribute('aria-live', 'polite')
543
+ const paint = () => {
544
+ const total = graph.steps.length
545
+ prev.disabled = step <= 0
546
+ next.textContent = step === total - 1 ? 'Show all' : step < 0 ? 'Start' : 'Next'
547
+ text.replaceChildren()
548
+ if (step < 0) text.append(`${total} steps. Press Start to walk through them.`)
549
+ else { const count = document.createElement('b'); count.textContent = `${step + 1}/${total}`; text.append(count, graph.steps[step].text) }
550
+ showStep()
551
+ }
552
+ prev.addEventListener('click', () => { step = Math.max(0, step - 1); paint() })
553
+ next.addEventListener('click', () => { step = step === graph.steps.length - 1 ? -1 : step + 1; paint() })
554
+ bar.append(prev, text, next)
555
+ scroll.after(bar)
556
+ paint()
557
+ }
558
+
559
+ /* it draws itself once, when the reader gets to it; a redraw after a resize stays still */
560
+ if (figure.mSeen === true) return
561
+ if (calm || !('IntersectionObserver' in window)) { figure.mSeen = true; return }
562
+ const watcher = new IntersectionObserver((entries) => {
563
+ if (!entries.some((entry) => entry.isIntersecting)) return
564
+ watcher.disconnect()
565
+ figure.mSeen = true
566
+ enter()
567
+ }, { threshold: 0.25 })
568
+ watcher.observe(figure)
569
+ }
570
+
571
+ /* ---------- finding diagrams, now and later ---------- */
572
+
573
+ const widths = new WeakMap()
574
+ const resized = new ResizeObserver((entries) => {
575
+ for (const entry of entries) {
576
+ const before = widths.get(entry.target)
577
+ const now = Math.round(entry.contentRect.width)
578
+ if (before !== undefined && Math.abs(before - now) < 48) continue
579
+ widths.set(entry.target, now)
580
+ if (before !== undefined) draw(entry.target)
581
+ }
582
+ })
583
+ function adopt (figure) {
584
+ if (figure.dataset.diagramState !== undefined) return
585
+ figure.dataset.diagramState = 'pending'
586
+ draw(figure)
587
+ widths.set(figure, Math.round(figure.clientWidth))
588
+ resized.observe(figure)
589
+ }
590
+ function scan () { document.querySelectorAll('[data-diagram]').forEach(adopt) }
591
+ const start = () => {
592
+ scan()
593
+ new MutationObserver(() => scan()).observe(document.body, { childList: true, subtree: true })
594
+ }
595
+ const ready = () => Promise.race([document.fonts?.ready ?? Promise.resolve(), new Promise((resolve) => setTimeout(resolve, 1200))]).then(start)
596
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready)
597
+ else ready()
598
+ })()
@@ -604,7 +604,8 @@
604
604
  const stage = '[data-arrive], [data-count], [data-fill], [data-sweep], tr'
605
605
 
606
606
  addEventListener('pointermove', (event) => {
607
- if (event.pointerType === 'touch') return
607
+ /* data-pointer="off" on <html>: an app people work in keeps still under the cursor */
608
+ if (event.pointerType === 'touch' || root.dataset.pointer === 'off') return
608
609
  pointerX = event.clientX
609
610
  pointerY = event.clientY
610
611
  stir()