@open-artifact/whiteboard-core 0.10.0 → 0.12.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 (43) hide show
  1. package/package.json +4 -4
  2. package/src/backdrop.d.ts +4 -2
  3. package/src/backdrop.js +10 -3
  4. package/src/check.d.ts +9 -1
  5. package/src/check.js +91 -11
  6. package/src/drawn-svg/looks.d.ts +166 -0
  7. package/src/drawn-svg/looks.js +594 -0
  8. package/src/drawn-svg/svg-geometry.d.ts +7 -0
  9. package/src/drawn-svg/svg-geometry.js +37 -0
  10. package/src/drawn-svg/vetting.d.ts +4 -2
  11. package/src/drawn-svg/vetting.js +11 -5
  12. package/src/edits.d.ts +2 -2
  13. package/src/edits.js +2 -2
  14. package/src/geometry.js +2 -1
  15. package/src/history/board-diff.d.ts +7 -2
  16. package/src/history/board-diff.js +31 -6
  17. package/src/history/table-steps.d.ts +8 -3
  18. package/src/history/table-steps.js +38 -7
  19. package/src/hit-test.d.ts +2 -1
  20. package/src/hit-test.js +26 -5
  21. package/src/ideas.d.ts +2 -2
  22. package/src/ideas.js +3 -1
  23. package/src/index.d.ts +5 -0
  24. package/src/index.js +5 -0
  25. package/src/links.d.ts +2 -0
  26. package/src/links.js +9 -5
  27. package/src/next-item.d.ts +16 -1
  28. package/src/next-item.js +65 -15
  29. package/src/normalize.d.ts +2 -0
  30. package/src/normalize.js +14 -4
  31. package/src/schema.d.ts +20 -0
  32. package/src/schema.js +6 -0
  33. package/src/selection.js +8 -8
  34. package/src/table-tints.d.ts +84 -0
  35. package/src/table-tints.js +217 -0
  36. package/src/table.d.ts +17 -4
  37. package/src/table.js +59 -6
  38. package/src/text/placeholder.d.ts +17 -0
  39. package/src/text/placeholder.js +16 -0
  40. package/src/text/push-down.d.ts +29 -0
  41. package/src/text/push-down.js +72 -0
  42. package/src/text/turned-anchor.d.ts +19 -0
  43. package/src/text/turned-anchor.js +32 -0
@@ -0,0 +1,594 @@
1
+ /**
2
+ * Drawing looks: how an agent drawing's `style` is drawn.
3
+ *
4
+ * - {@link drawingLookOf} and {@link drawingLookRenderer} pick the look and
5
+ * whether it is a rewrite of the SVG (`svg`) or painted pixels (`raster`).
6
+ * - {@link DRAWING_LOOK_TONES} holds each look's paper and ink per color
7
+ * scheme; {@link drawingLookPaper} is what text over a drawing reads on.
8
+ * - {@link sketchDrawnSvg}, {@link comicDrawnSvg} and
9
+ * {@link blueprintDrawnSvg} rewrite a parsed drawing in place.
10
+ * - {@link drawingPaintPlan} flattens a drawing into filled and stroked
11
+ * parts for the raster looks.
12
+ *
13
+ * Everything works on the core's XML tree, so it runs in Node, the page and
14
+ * workers alike.
15
+ */
16
+ import { isSvgBase64DataUrl } from "../image-source.js";
17
+ import { DRAWING_STYLES } from "../schema.js";
18
+ import { mixHexColors, parseRgbaColor } from "../theme.js";
19
+ import { brushSvgStrokes } from "./restyle.js";
20
+ import { flattenSvgShape, IDENTITY_MATRIX, matrixAreaScale, parseSvgTransform } from "./svg-geometry.js";
21
+ import { createSvgElement, XmlElement } from "./xml.js";
22
+ /** True for a known drawing style. */
23
+ export function isDrawingStyle(value) {
24
+ return DRAWING_STYLES.includes(value);
25
+ }
26
+ /** The look for a drawing's `style`: no style or an unknown word draws plain. */
27
+ export function drawingLookOf(style) {
28
+ return style !== undefined && isDrawingStyle(style) ? style : 'plain';
29
+ }
30
+ /** The look of an image element, or `undefined` when it is not an SVG drawing. */
31
+ export function imageDrawingLook(image) {
32
+ return isSvgBase64DataUrl(image.src) || image.src.startsWith('data:image/svg+xml') ? drawingLookOf(image.style) : undefined;
33
+ }
34
+ /** Whether a look rewrites the SVG or paints pixels. */
35
+ export function drawingLookRenderer(look) {
36
+ return look === 'marker' || look === 'watercolor' || look === 'paper' ? 'raster' : 'svg';
37
+ }
38
+ /** Paper and ink of every style, per board color scheme. */
39
+ export const DRAWING_LOOK_TONES = {
40
+ plain: { light: { paper: undefined, ink: '#1A1A1A' }, dark: { paper: undefined, ink: '#EFEFEF' } },
41
+ draft: { light: { paper: '#F5F0E4', ink: '#4A4A50' }, dark: { paper: '#2B2926', ink: '#D4D0C8' } },
42
+ comic: { light: { paper: undefined, ink: '#141414' }, dark: { paper: undefined, ink: '#F4F0E6' } },
43
+ blueprint: { light: { paper: '#1E4E8C', ink: '#F2F7FF' }, dark: { paper: '#0E2340', ink: '#CFE1FF' } },
44
+ marker: { light: { paper: undefined, ink: '#202020' }, dark: { paper: undefined, ink: '#EFEFEF' } },
45
+ watercolor: { light: { paper: '#F7F2E7', ink: '#5A4E44' }, dark: { paper: '#26231F', ink: '#D8CFC2' } },
46
+ paper: { light: { paper: undefined, ink: '#2A2A2A' }, dark: { paper: undefined, ink: '#F1ECE2' } },
47
+ };
48
+ /** The paper a look lays behind a drawing in a scheme (`undefined`: the board shows through). */
49
+ export function drawingLookPaper(look, scheme) {
50
+ return DRAWING_LOOK_TONES[look][scheme].paper;
51
+ }
52
+ /** A `#rgb[a]` / `#rrggbb[aa]` color as `#rrggbb` and its alpha; `undefined` for anything else. */
53
+ export function solidHex(color) {
54
+ if (!color.startsWith('#'))
55
+ return undefined;
56
+ const rgba = parseRgbaColor(color);
57
+ if (rgba === undefined)
58
+ return undefined;
59
+ const channel = (value) => Math.round(value * 255).toString(16).padStart(2, '0');
60
+ return { hex: `#${channel(rgba.r)}${channel(rgba.g)}${channel(rgba.b)}`, alpha: rgba.a };
61
+ }
62
+ function hexToHsl(hex) {
63
+ const rgba = parseRgbaColor(hex) ?? { r: 0, g: 0, b: 0, a: 1 };
64
+ const [max, min] = [Math.max(rgba.r, rgba.g, rgba.b), Math.min(rgba.r, rgba.g, rgba.b)];
65
+ const l = (max + min) / 2;
66
+ if (max === min)
67
+ return { h: 0, s: 0, l };
68
+ const d = max - min;
69
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
70
+ const h = max === rgba.r ? (rgba.g - rgba.b) / d + (rgba.g < rgba.b ? 6 : 0) : max === rgba.g ? (rgba.b - rgba.r) / d + 2 : (rgba.r - rgba.g) / d + 4;
71
+ return { h: h * 60, s, l };
72
+ }
73
+ function hslToHex({ h, s, l }) {
74
+ const c = (1 - Math.abs(2 * l - 1)) * s;
75
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
76
+ const m = l - c / 2;
77
+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];
78
+ const channel = (value) => Math.round(Math.min(1, Math.max(0, value + m)) * 255).toString(16).padStart(2, '0');
79
+ return `#${channel(r)}${channel(g)}${channel(b)}`;
80
+ }
81
+ /** Saturation of a hex color (0–1). */
82
+ export function hexSaturation(hex) {
83
+ return hexToHsl(hex).s;
84
+ }
85
+ /** A hex color made flatter and bolder, as printed comic colors are. */
86
+ export function comicColor(hex) {
87
+ const { h, s, l } = hexToHsl(hex);
88
+ if (s < 0.08)
89
+ return hslToHex({ h, s, l: Math.min(0.92, Math.max(0.12, l)) });
90
+ return hslToHex({ h, s: Math.min(1, s * 1.3 + 0.12), l: Math.min(0.72, Math.max(0.3, l)) });
91
+ }
92
+ /** The average color of each gradient (`id` → `#rrggbb`), so painted looks can use it as a flat color. */
93
+ export function gradientColors(root) {
94
+ const colors = new Map();
95
+ for (const node of root.descendants()) {
96
+ const id = node.getAttribute('id');
97
+ if (id === null || !/Gradient$/.test(node.localName))
98
+ continue;
99
+ const stops = node.children.flatMap((stop) => {
100
+ const color = stop.localName === 'stop' ? solidHex(stop.getAttribute('stop-color') ?? '') : undefined;
101
+ return color === undefined ? [] : [color.hex];
102
+ });
103
+ if (stops.length > 0)
104
+ colors.set(id, stops.reduce((mixed, stop, index) => mixHexColors(mixed, stop, 1 / (index + 1))));
105
+ }
106
+ return colors;
107
+ }
108
+ /** A paint as `#rrggbb` (gradients averaged), `currentColor`, or `undefined` for none or unknown. */
109
+ function paintColor(value, gradients) {
110
+ if (/^currentcolor$/i.test(value))
111
+ return { color: 'currentColor', alpha: 1 };
112
+ const reference = /^url\(\s*#([^)\s]+)\s*\)$/.exec(value)?.[1];
113
+ if (reference !== undefined) {
114
+ const color = gradients.get(reference);
115
+ return color === undefined ? undefined : { color, alpha: 1 };
116
+ }
117
+ const solid = solidHex(value);
118
+ return solid === undefined ? undefined : { color: solid.hex, alpha: solid.alpha };
119
+ }
120
+ /* -------------------------------------------------------------------------- */
121
+ /* Tree helpers */
122
+ /* -------------------------------------------------------------------------- */
123
+ /** Tags that draw a shape. */
124
+ const SHAPE_TAGS = new Set(['path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon']);
125
+ /** Geometry attributes copied into a clip path. */
126
+ const CLIP_GEOMETRY = ['transform', 'd', 'points', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'width', 'height', 'cx', 'cy', 'r', 'rx', 'ry'];
127
+ /** A `0 0 W H` viewBox, or `undefined`. */
128
+ export function drawingViewBox(root) {
129
+ const match = /^\s*0[\s,]+0[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)\s*$/.exec(root.getAttribute('viewBox') ?? '');
130
+ const size = match === null ? undefined : [Number(match[1]), Number(match[2])];
131
+ return size !== undefined && size[0] > 0 && size[1] > 0 ? size : undefined;
132
+ }
133
+ /** A deep copy of an element (elements and attributes only), without ids. */
134
+ export function cloneSvgElement(element) {
135
+ const copy = new XmlElement(element.name, element.namespaceURI);
136
+ for (const attribute of element.attributes)
137
+ if (attribute.name !== 'id')
138
+ copy.setAttribute(attribute.name, attribute.value);
139
+ for (const child of element.children)
140
+ copy.appendChild(cloneSvgElement(child));
141
+ return copy;
142
+ }
143
+ /** Sets attributes on an element (skipping `undefined` values). */
144
+ function setAttributes(element, attributes) {
145
+ for (const [name, value] of Object.entries(attributes))
146
+ if (value !== undefined)
147
+ element.setAttribute(name, String(value));
148
+ return element;
149
+ }
150
+ /** Rounds to two decimals for path data. */
151
+ function round2(value) {
152
+ return Math.round(value * 100) / 100;
153
+ }
154
+ const ROOT_PAINT = { fill: '#000', stroke: 'none', width: 1, fillOpacity: 1, strokeOpacity: 1, opacity: 1, dashed: false, cap: 'butt', at: IDENTITY_MATRIX };
155
+ /** The paint state of `element` under `inherited`. */
156
+ function paintStateOf(element, inherited) {
157
+ const fraction = (name, fallback) => {
158
+ const value = Number(element.getAttribute(name) ?? fallback);
159
+ return Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : fallback;
160
+ };
161
+ const width = Number(element.getAttribute('stroke-width') ?? inherited.width);
162
+ return {
163
+ fill: element.getAttribute('fill') ?? inherited.fill,
164
+ stroke: element.getAttribute('stroke') ?? inherited.stroke,
165
+ width: Number.isFinite(width) ? width : inherited.width,
166
+ fillOpacity: fraction('fill-opacity', inherited.fillOpacity),
167
+ strokeOpacity: fraction('stroke-opacity', inherited.strokeOpacity),
168
+ opacity: inherited.opacity * fraction('opacity', 1),
169
+ dashed: inherited.dashed || (element.hasAttribute('stroke-dasharray') && element.getAttribute('stroke-dasharray') !== 'none'),
170
+ cap: element.getAttribute('stroke-linecap') ?? inherited.cap,
171
+ at: inherited.at === undefined ? undefined : parseSvgTransform(inherited.at, element.getAttribute('transform') ?? ''),
172
+ };
173
+ }
174
+ /** Each shape element of a drawing (outside `skip`) with its paint, in drawing order. */
175
+ function paintedShapes(root, skip) {
176
+ const found = [];
177
+ const visit = (element, inherited) => {
178
+ if (skip.has(element))
179
+ return;
180
+ const state = element === root ? paintStateOf(element, ROOT_PAINT) : paintStateOf(element, inherited);
181
+ if (element === root || element.localName === 'g') {
182
+ for (const child of element.children)
183
+ visit(child, state);
184
+ return;
185
+ }
186
+ if (SHAPE_TAGS.has(element.localName))
187
+ found.push({ element, state });
188
+ };
189
+ visit(root, ROOT_PAINT);
190
+ return found;
191
+ }
192
+ /** An id prefix no element of the drawing uses yet. */
193
+ function freshIdPrefix(root, base) {
194
+ const ids = new Set([root, ...root.descendants()].map((node) => node.getAttribute('id') ?? ''));
195
+ let prefix = base;
196
+ for (let attempt = 1; [...ids].some((id) => id.startsWith(prefix)); attempt++)
197
+ prefix = `${base}${String(attempt)}-`;
198
+ return prefix;
199
+ }
200
+ /** A small seeded random generator (xorshift32 over an FNV-1a hash of the seed text). */
201
+ export function seededLookRandom(seedText) {
202
+ let hash = 0x811c9dc5;
203
+ for (let index = 0; index < seedText.length; index++)
204
+ hash = Math.imul(hash ^ seedText.charCodeAt(index), 0x01000193);
205
+ let state = hash >>> 0 || 0x9e3779b9;
206
+ return () => {
207
+ state ^= state << 13;
208
+ state ^= state >>> 17;
209
+ state ^= state << 5;
210
+ state >>>= 0;
211
+ return state / 4294967296;
212
+ };
213
+ }
214
+ /** The bounding box `[minX, minY, maxX, maxY]` of polylines. */
215
+ function polylineBounds(polylines) {
216
+ const bounds = [Infinity, Infinity, -Infinity, -Infinity];
217
+ for (const polyline of polylines)
218
+ for (let index = 0; index + 1 < polyline.length; index += 2) {
219
+ const [x, y] = [polyline[index], polyline[index + 1]];
220
+ bounds[0] = Math.min(bounds[0], x);
221
+ bounds[1] = Math.min(bounds[1], y);
222
+ bounds[2] = Math.max(bounds[2], x);
223
+ bounds[3] = Math.max(bounds[3], y);
224
+ }
225
+ return bounds;
226
+ }
227
+ /** A sheet of paper behind the whole drawing. */
228
+ function paperSheet(width, height, color) {
229
+ return setAttributes(createSvgElement('rect'), { x: 0, y: 0, width, height, rx: round2(Math.min(width, height) * 0.012), fill: color, stroke: 'none' });
230
+ }
231
+ /* -------------------------------------------------------------------------- */
232
+ /* Draft */
233
+ /* -------------------------------------------------------------------------- */
234
+ /** Most pencil hatch lines in a drawing. */
235
+ export const MAX_SKETCH_HATCH_LINES = 4000;
236
+ /** How faint a filled area's own color stays under its hatching. */
237
+ export const SKETCH_FILL_OPACITY = 0.16;
238
+ /**
239
+ * Pencil hatching for a box `[minX, minY, maxX, maxY]`: parallel lines at
240
+ * `angle` (radians) `spacing` apart across the box, each a little crooked
241
+ * and some stopping short, as path data. `undefined` past `budget` lines.
242
+ */
243
+ export function pencilHatchPath(bounds, spacing, angle, budget, random) {
244
+ const [minX, minY, maxX, maxY] = bounds;
245
+ const [cx, cy] = [(minX + maxX) / 2, (minY + maxY) / 2];
246
+ const radius = Math.hypot(maxX - minX, maxY - minY) / 2 + spacing;
247
+ const count = Math.ceil((2 * radius) / spacing);
248
+ if (!(count > 0) || count > budget)
249
+ return undefined;
250
+ const [dx, dy, nx, ny] = [Math.cos(angle), Math.sin(angle), -Math.sin(angle), Math.cos(angle)];
251
+ let d = '';
252
+ for (let index = 0; index <= count; index++) {
253
+ const offset = -radius + index * spacing + (random() - 0.5) * spacing * 0.35;
254
+ // Some strokes stop short, as a quick hand leaves gaps.
255
+ const [from, to] = [-radius * (random() < 0.25 ? 0.2 + 0.6 * random() : 1), radius * (random() < 0.25 ? 0.2 + 0.6 * random() : 1)];
256
+ const wobble = (random() - 0.5) * spacing * 0.5;
257
+ const point = (along, bend) => `${round2(cx + dx * along + nx * (offset + bend))} ${round2(cy + dy * along + ny * (offset + bend))}`;
258
+ d += `M${point(from, 0)}Q${point((from + to) / 2, wobble)} ${point(to, 0)}`;
259
+ }
260
+ return { d, lines: count + 1 };
261
+ }
262
+ /**
263
+ * Rewrites a drawing as a pencil sketch (in place): graphite ink, ink lines
264
+ * brushed so they taper, wander and overshoot, with a faint second pass on
265
+ * some of them; filled areas turned to loose hatching over a faint wash of
266
+ * their color; a paper sheet behind. Elements in `skip` are left alone.
267
+ * Returns whether the drawing was rewritten (it needs a `0 0 W H` viewBox).
268
+ */
269
+ export function sketchDrawnSvg(root, scheme, skip = new Set()) {
270
+ const size = drawingViewBox(root);
271
+ if (size === undefined)
272
+ return false;
273
+ const tone = DRAWING_LOOK_TONES.draft[scheme];
274
+ const random = seededLookRandom(`draft|${String(size[0])}x${String(size[1])}|${String(root.descendants().length)}`);
275
+ root.setAttribute('color', tone.ink);
276
+ const shapes = paintedShapes(root, skip);
277
+ // A second, fainter pass on every third ink line, a hair off the first.
278
+ const nudge = Math.max(0.6, size[0] / 500);
279
+ shapes.forEach(({ element, state }, index) => {
280
+ if (index % 3 !== 1 || !/^currentcolor$/i.test(state.stroke) || state.dashed || !(state.width <= 4))
281
+ return;
282
+ const pass = cloneSvgElement(element);
283
+ setAttributes(pass, {
284
+ fill: 'none',
285
+ 'stroke-opacity': round2(state.strokeOpacity * 0.38),
286
+ transform: `translate(${String(round2(nudge * (random() - 0.3)))} ${String(round2(nudge * (random() - 0.3)))})${element.getAttribute('transform') !== null ? ` ${element.getAttribute('transform') ?? ''}` : ''}`,
287
+ });
288
+ element.after(pass);
289
+ });
290
+ // Colored lines go graphite-tinted.
291
+ for (const { element, state } of shapes) {
292
+ const stroke = solidHex(state.stroke);
293
+ if (stroke !== undefined && element.hasAttribute('stroke'))
294
+ element.setAttribute('stroke', mixHexColors(stroke.hex, tone.ink, 0.45));
295
+ }
296
+ brushSvgStrokes(root, skip);
297
+ // Hatch the filled areas still standing (brushing may have replaced ink-only shapes).
298
+ const prefix = freshIdPrefix(root, 'wbd-');
299
+ const gradients = gradientColors(root);
300
+ const spacing = Math.max(3.5, Math.min(size[0], size[1]) / 70);
301
+ let [budget, clips] = [MAX_SKETCH_HATCH_LINES, 0];
302
+ for (const { element, state } of paintedShapes(root, skip)) {
303
+ if (element.parent === null || element.localName === 'line')
304
+ continue;
305
+ // Solid ink areas stay solid, as a pencil fills them in.
306
+ const fill = paintColor(state.fill, gradients);
307
+ if (fill === undefined || fill.color === 'currentColor')
308
+ continue;
309
+ const local = parseSvgTransform(IDENTITY_MATRIX, element.getAttribute('transform') ?? '');
310
+ const polylines = local === undefined ? undefined : flattenSvgShape(element, local);
311
+ const bounds = polylines === undefined || polylines.length === 0 ? undefined : polylineBounds(polylines);
312
+ element.setAttribute('fill-opacity', String(round2(state.fillOpacity * fill.alpha * SKETCH_FILL_OPACITY)));
313
+ if (bounds === undefined || bounds[2] - bounds[0] < spacing || bounds[3] - bounds[1] < spacing / 2)
314
+ continue;
315
+ const hatch = pencilHatchPath(bounds, spacing, Math.PI / 4 + (random() - 0.5) * 0.5, budget, random);
316
+ if (hatch === undefined)
317
+ continue;
318
+ budget -= hatch.lines;
319
+ const id = `${prefix}${String(clips++)}`;
320
+ const clip = setAttributes(createSvgElement('clipPath'), { id });
321
+ const outline = createSvgElement(element.localName);
322
+ for (const name of CLIP_GEOMETRY) {
323
+ const value = element.getAttribute(name);
324
+ if (value !== null)
325
+ outline.setAttribute(name, value);
326
+ }
327
+ clip.appendChild(outline);
328
+ const lines = setAttributes(createSvgElement('path'), {
329
+ d: hatch.d,
330
+ fill: 'none',
331
+ stroke: mixHexColors(fill.color, tone.ink, scheme === 'light' ? 0.35 : 0.25),
332
+ 'stroke-width': round2(Math.max(0.7, size[0] / 650)),
333
+ 'stroke-linecap': 'round',
334
+ 'stroke-opacity': round2(Math.min(1, 0.4 + 0.5 * state.fillOpacity * fill.alpha)),
335
+ 'clip-path': `url(#${id})`,
336
+ });
337
+ element.after(clip, lines);
338
+ }
339
+ root.insertBefore(paperSheet(size[0], size[1], tone.paper ?? '#ffffff'), root.childNodes[0] ?? null);
340
+ return true;
341
+ }
342
+ /* -------------------------------------------------------------------------- */
343
+ /* Comic */
344
+ /* -------------------------------------------------------------------------- */
345
+ /** Thickness of a comic drawing's outer outline, as a share of its larger side. */
346
+ export const COMIC_OUTLINE_SHARE = 0.016;
347
+ /** How far a comic drawing's hard shadow falls, as a share of its larger side. */
348
+ export const COMIC_SHADOW_SHARE = 0.018;
349
+ /**
350
+ * The hard shadow's tone: near-black ink on a light board; on a dark board
351
+ * black would vanish, so the shadow is a lifted warm grey that still reads
352
+ * as a cast shadow under the light rims.
353
+ */
354
+ export const COMIC_SHADOW_TONES = {
355
+ light: { color: '#141414', opacity: 0.88 },
356
+ dark: { color: '#5C5850', opacity: 1 },
357
+ };
358
+ /** Recolors every paint in a copied tree to `color`, keeps filled shapes only, and returns the copy. */
359
+ function silhouetteOf(content, inherited, color, keep, extra) {
360
+ const copy = cloneSvgElement(content);
361
+ const visit = (original, twin, inherited) => {
362
+ const state = paintStateOf(original, inherited);
363
+ for (const name of ['fill', 'stroke']) {
364
+ const value = twin.getAttribute(name);
365
+ if (value !== null && value !== 'none')
366
+ twin.setAttribute(name, color);
367
+ }
368
+ if (/Gradient$|^clipPath$|^defs$/.test(twin.localName)) {
369
+ twin.remove();
370
+ return;
371
+ }
372
+ if (original.localName === 'g' || original === content) {
373
+ const [sources, twins] = [original.children, twin.children];
374
+ sources.forEach((child, index) => {
375
+ const mirror = twins[index];
376
+ if (mirror !== undefined)
377
+ visit(child, mirror, state);
378
+ });
379
+ return;
380
+ }
381
+ if (!SHAPE_TAGS.has(original.localName) || !keep(original, state))
382
+ twin.remove();
383
+ else
384
+ extra(twin, state);
385
+ };
386
+ visit(content, copy, inherited);
387
+ return copy;
388
+ }
389
+ /** True when a shape paints a visible fill. */
390
+ function isFilledShape(element, state) {
391
+ return element.localName !== 'line' && state.fill !== 'none' && state.fillOpacity * state.opacity > 0.2;
392
+ }
393
+ /**
394
+ * Rewrites a drawing as a comic panel (in place): flat, bolder fills; a
395
+ * thick outline round the whole of each filled mass and thinner ink lines
396
+ * inside; a hard shadow offset under the filled shapes. Elements in `skip`
397
+ * keep their own paint. Returns whether it was rewritten.
398
+ */
399
+ export function comicDrawnSvg(root, scheme, skip = new Set()) {
400
+ const size = drawingViewBox(root);
401
+ if (size === undefined)
402
+ return false;
403
+ const tone = DRAWING_LOOK_TONES.comic[scheme];
404
+ const unit = Math.max(size[0], size[1]);
405
+ const [outline, inner, drop] = [Math.max(3, unit * COMIC_OUTLINE_SHARE), Math.max(1.4, unit * 0.005), Math.max(3, unit * COMIC_SHADOW_SHARE)];
406
+ root.setAttribute('color', tone.ink);
407
+ const shapes = paintedShapes(root, skip);
408
+ // Flat, bold colors.
409
+ for (const node of [root, ...root.descendants()]) {
410
+ if (skip.has(node))
411
+ continue;
412
+ for (const name of ['fill', 'stroke']) {
413
+ const solid = solidHex(node.getAttribute(name) ?? '');
414
+ if (solid !== undefined)
415
+ node.setAttribute(name, comicColor(solid.hex));
416
+ }
417
+ const fillOpacity = Number(node.getAttribute('fill-opacity') ?? 1);
418
+ if (node.hasAttribute('fill-opacity') && fillOpacity >= 0.3)
419
+ node.setAttribute('fill-opacity', '1');
420
+ }
421
+ // Thin ink edges on filled shapes that had none.
422
+ for (const { element, state } of shapes)
423
+ if (isFilledShape(element, state) && state.stroke === 'none')
424
+ setAttributes(element, { stroke: 'currentColor', 'stroke-width': round2(inner / Math.sqrt(matrixAreaScale(state.at ?? IDENTITY_MATRIX))), 'stroke-linejoin': 'round' });
425
+ const content = setAttributes(createSvgElement('g'), {});
426
+ content.append(...root.childNodes);
427
+ const filledOnly = (element, state) => !skip.has(element) && isFilledShape(element, state);
428
+ const rootPaint = paintStateOf(root, ROOT_PAINT);
429
+ const shadowTone = COMIC_SHADOW_TONES[scheme];
430
+ const shadow = silhouetteOf(content, rootPaint, shadowTone.color, filledOnly, (twin) => void twin.removeAttribute('stroke-dasharray'));
431
+ setAttributes(shadow, { transform: `translate(${String(round2(drop))} ${String(round2(drop))})`, opacity: shadowTone.opacity, color: shadowTone.color });
432
+ const rim = silhouetteOf(content, rootPaint, tone.ink, filledOnly, (twin, state) => {
433
+ const scale = Math.sqrt(matrixAreaScale(state.at ?? IDENTITY_MATRIX)) || 1;
434
+ setAttributes(twin, { stroke: tone.ink, 'stroke-width': round2((state.stroke !== 'none' ? state.width : 0) + outline / scale), 'stroke-linejoin': 'round', 'stroke-linecap': 'round', 'stroke-opacity': 1, 'fill-opacity': 1 });
435
+ twin.removeAttribute('stroke-dasharray');
436
+ });
437
+ setAttributes(rim, { color: tone.ink });
438
+ root.append(shadow, rim, content);
439
+ return true;
440
+ }
441
+ /* -------------------------------------------------------------------------- */
442
+ /* Blueprint */
443
+ /* -------------------------------------------------------------------------- */
444
+ /** Saturation above which a blueprint keeps a color (what moves or flows). */
445
+ export const BLUEPRINT_KEEP_SATURATION = 0.45;
446
+ /**
447
+ * How a kept fill is washed on blue paper: tinted toward white and laid
448
+ * nearly opaque, since a thin wash of a warm color over blue turns olive.
449
+ */
450
+ export const BLUEPRINT_KEPT_WASH = { tint: 0.3, opacity: 0.85 };
451
+ /** The fill of a section cut (`class="cut"`): a flat mid-grey, so walls cut through read as solid. */
452
+ export const BLUEPRINT_CUT_FILL = { light: '#8E959E', dark: '#5F6772' };
453
+ /** True when an element's `class` names the `cut` marker. */
454
+ function hasCutClass(element) {
455
+ return /(?:^|\s)cut(?:\s|$)/.test(element.getAttribute('class') ?? '');
456
+ }
457
+ /**
458
+ * The parts of a drawing marked as section cuts (`class="cut"` on them or
459
+ * on a group around them). `class` is only a marker here: no CSS applies.
460
+ */
461
+ export function drawingCutParts(root) {
462
+ const cuts = new Set();
463
+ for (const node of [root, ...root.descendants()])
464
+ if (hasCutClass(node) || (node.parent instanceof XmlElement && cuts.has(node.parent)))
465
+ cuts.add(node);
466
+ return cuts;
467
+ }
468
+ /** Grid lines for a blueprint sheet `width` × `height`: minor lines and every fifth one stronger. */
469
+ export function blueprintGridPaths(width, height) {
470
+ const raw = Math.max(width, height) / 32;
471
+ const magnitude = 10 ** Math.floor(Math.log10(raw));
472
+ const pitch = [1, 2, 2.5, 5, 10].map((step) => step * magnitude).find((step) => step >= raw) ?? raw;
473
+ let [minor, major] = ['', ''];
474
+ for (let index = 1; index * pitch < width; index++) {
475
+ const line = `M${String(round2(index * pitch))} 0V${String(height)}`;
476
+ if (index % 5 === 0)
477
+ major += line;
478
+ else
479
+ minor += line;
480
+ }
481
+ for (let index = 1; index * pitch < height; index++) {
482
+ const line = `M0 ${String(round2(index * pitch))}H${String(width)}`;
483
+ if (index % 5 === 0)
484
+ major += line;
485
+ else
486
+ minor += line;
487
+ }
488
+ return { minor, major, pitch };
489
+ }
490
+ /**
491
+ * Rewrites a drawing as a blueprint (in place): blue paper with a faint
492
+ * grid, pale lines at their own weights (dashes kept), fills as pale
493
+ * washes outlined in line; strongly colored parts (what is meant to stand
494
+ * out) keep their hue in a light, nearly opaque wash, and section cuts
495
+ * (`cuts`, by default the parts marked `class="cut"`) are filled solid
496
+ * mid-grey. Returns whether it was rewritten.
497
+ */
498
+ export function blueprintDrawnSvg(root, scheme, skip = new Set(), cuts = drawingCutParts(root)) {
499
+ const size = drawingViewBox(root);
500
+ if (size === undefined)
501
+ return false;
502
+ const tone = DRAWING_LOOK_TONES.blueprint[scheme];
503
+ const paper = tone.paper ?? '#1E4E8C';
504
+ root.setAttribute('color', tone.ink);
505
+ const shapes = paintedShapes(root, skip);
506
+ const gradients = gradientColors(root);
507
+ const lineWidth = round2(Math.max(1, Math.max(size[0], size[1]) / 400));
508
+ for (const node of [root, ...root.descendants()]) {
509
+ if (skip.has(node))
510
+ continue;
511
+ const stroke = node.getAttribute('stroke');
512
+ const strokeColor = stroke === null ? undefined : paintColor(stroke, gradients);
513
+ if (strokeColor !== undefined && strokeColor.color !== 'currentColor')
514
+ node.setAttribute('stroke', hexSaturation(strokeColor.color) >= BLUEPRINT_KEEP_SATURATION ? mixHexColors(strokeColor.color, '#ffffff', 0.4) : 'currentColor');
515
+ const fill = node.getAttribute('fill');
516
+ const fillColor = fill === null ? undefined : paintColor(fill, gradients);
517
+ if (fillColor === undefined || fillColor.color === 'currentColor')
518
+ continue;
519
+ const keep = hexSaturation(fillColor.color) >= BLUEPRINT_KEEP_SATURATION;
520
+ const darkness = 1 - hexToHsl(fillColor.color).l;
521
+ const opacity = Number(node.getAttribute('fill-opacity') ?? 1) * fillColor.alpha;
522
+ const shown = Number.isFinite(opacity) ? opacity : 1;
523
+ setAttributes(node, {
524
+ fill: keep ? mixHexColors(fillColor.color, '#ffffff', BLUEPRINT_KEPT_WASH.tint) : tone.ink,
525
+ 'fill-opacity': round2(keep ? Math.min(shown, BLUEPRINT_KEPT_WASH.opacity) : shown * (0.06 + 0.16 * darkness)),
526
+ });
527
+ }
528
+ for (const { element, state } of shapes) {
529
+ if (cuts.has(element) && element.localName !== 'line') {
530
+ setAttributes(element, { fill: BLUEPRINT_CUT_FILL[scheme], 'fill-opacity': 1 });
531
+ if (state.stroke === 'none')
532
+ setAttributes(element, { stroke: 'currentColor', 'stroke-width': lineWidth, 'stroke-linejoin': 'round' });
533
+ continue;
534
+ }
535
+ // Filled parts without a line get one.
536
+ if (isFilledShape(element, state) && state.stroke === 'none')
537
+ setAttributes(element, { stroke: 'currentColor', 'stroke-width': lineWidth, 'stroke-linejoin': 'round' });
538
+ }
539
+ const grid = blueprintGridPaths(size[0], size[1]);
540
+ const gridColor = mixHexColors(paper, tone.ink, 0.28);
541
+ const sheet = [
542
+ paperSheet(size[0], size[1], paper),
543
+ setAttributes(createSvgElement('path'), { d: grid.minor, fill: 'none', stroke: gridColor, 'stroke-width': round2(lineWidth * 0.45), 'stroke-opacity': 0.55 }),
544
+ setAttributes(createSvgElement('path'), { d: grid.major, fill: 'none', stroke: gridColor, 'stroke-width': round2(lineWidth * 0.8), 'stroke-opacity': 0.7 }),
545
+ ];
546
+ const first = root.childNodes[0] ?? null;
547
+ for (const part of sheet)
548
+ root.insertBefore(part, first);
549
+ return true;
550
+ }
551
+ /** Most parts a painted drawing may have. */
552
+ export const MAX_PAINT_PARTS = 1500;
553
+ /** Most outline points a painted drawing may have. */
554
+ export const MAX_PAINT_POINTS = 80000;
555
+ /**
556
+ * The shapes of a drawing with their resolved paint, back to front, for the
557
+ * raster looks. `undefined` when the drawing has no `0 0 W H` viewBox or is
558
+ * too big to paint. Shapes in `skip` or that cannot be flattened are left out.
559
+ */
560
+ export function drawingPaintPlan(root, skip = new Set()) {
561
+ const size = drawingViewBox(root);
562
+ if (size === undefined)
563
+ return undefined;
564
+ const gradients = gradientColors(root);
565
+ const parts = [];
566
+ let points = 0;
567
+ for (const { element, state } of paintedShapes(root, skip)) {
568
+ if (state.at === undefined)
569
+ continue;
570
+ const contours = flattenSvgShape(element, state.at);
571
+ if (contours === undefined || contours.length === 0)
572
+ continue;
573
+ const fillPaint = element.localName === 'line' ? undefined : paintColor(state.fill, gradients);
574
+ const strokePaint = paintColor(state.stroke, gradients);
575
+ const width = state.width * Math.sqrt(matrixAreaScale(state.at));
576
+ const fillAlpha = (fillPaint?.alpha ?? 0) * state.fillOpacity * state.opacity;
577
+ const strokeAlpha = (strokePaint?.alpha ?? 0) * state.strokeOpacity * state.opacity;
578
+ const part = {
579
+ fill: fillPaint !== undefined && fillAlpha > 0.01 ? { color: fillPaint.color, alpha: fillAlpha } : undefined,
580
+ stroke: strokePaint !== undefined && strokeAlpha > 0.01 && width > 0
581
+ ? { color: strokePaint.color, alpha: strokeAlpha, width, dashed: state.dashed, round: state.cap === 'round' || state.cap === 'square' }
582
+ : undefined,
583
+ contours,
584
+ closed: /^(?:rect|circle|ellipse|polygon)$/.test(element.localName) || (element.localName === 'path' && /z\s*$/i.test(element.getAttribute('d') ?? '')),
585
+ };
586
+ if (part.fill === undefined && part.stroke === undefined)
587
+ continue;
588
+ points += contours.reduce((total, contour) => total + contour.length / 2, 0);
589
+ parts.push(part);
590
+ if (parts.length > MAX_PAINT_PARTS || points > MAX_PAINT_POINTS)
591
+ return undefined;
592
+ }
593
+ return { width: size[0], height: size[1], parts };
594
+ }
@@ -94,6 +94,13 @@ export declare function pathPointsToPolyline(points: readonly SvgPathPoint[]): S
94
94
  * two-point polyline; `detail` scales how finely curves are sampled.
95
95
  */
96
96
  export declare function flattenSvgPath(path: unknown, maxChars?: number, coordinateLimit?: number, keepDots?: boolean, detail?: number): SvgPolyline[] | undefined;
97
+ /** A path's arcs (each as its larger radius) and the same path with every arc drawn as a straight line. */
98
+ export interface SvgPathArcs {
99
+ radii: number[];
100
+ lines: string;
101
+ }
102
+ /** Splits the arcs out of path data; `undefined` when the data cannot be read. */
103
+ export declare function splitSvgPathArcs(path: string): SvgPathArcs | undefined;
97
104
  /** The path equivalent of a basic shape element, or `undefined` for other elements. */
98
105
  export declare function svgShapePathData(element: SvgShapeSource): string | undefined;
99
106
  /**
@@ -283,6 +283,43 @@ export function flattenSvgPath(path, maxChars = 4000, coordinateLimit = 1000, ke
283
283
  flush();
284
284
  return polylines;
285
285
  }
286
+ /** Splits the arcs out of path data; `undefined` when the data cannot be read. */
287
+ export function splitSvgPathArcs(path) {
288
+ if (path.replace(SVG_PATH_TOKEN_PATTERN, '').replace(/[\s,]/g, '') !== '')
289
+ return undefined;
290
+ const tokens = [...path.matchAll(SVG_PATH_TOKEN_PATTERN)].map((match) => (match[1] !== undefined ? match[1] : Number(match[2])));
291
+ const radii = [];
292
+ const parts = [];
293
+ let command = '';
294
+ let index = 0;
295
+ while (index < tokens.length) {
296
+ const token = tokens[index];
297
+ if (typeof token === 'string') {
298
+ command = token;
299
+ index += 1;
300
+ if (command.toUpperCase() !== 'A')
301
+ parts.push(command);
302
+ continue;
303
+ }
304
+ const argCount = SVG_PATH_ARG_COUNTS[command.toUpperCase()] ?? 0;
305
+ const args = tokens.slice(index, index + argCount);
306
+ if (argCount === 0 || args.length < argCount || args.some((arg) => typeof arg !== 'number'))
307
+ return undefined;
308
+ index += argCount;
309
+ if (command.toUpperCase() === 'A') {
310
+ radii.push(Math.max(Math.abs(Number(args[0])), Math.abs(Number(args[1]))));
311
+ parts.push(command === 'a' ? 'l' : 'L', String(args[5]), String(args[6]));
312
+ }
313
+ else
314
+ parts.push(...args.map(String));
315
+ // Coordinate pairs after a moveto are implicit linetos.
316
+ if (command === 'M')
317
+ command = 'L';
318
+ else if (command === 'm')
319
+ command = 'l';
320
+ }
321
+ return { radii, lines: parts.join(' ') };
322
+ }
286
323
  /* -------------------------------------------------------------------------- */
287
324
  /* Shapes */
288
325
  /* -------------------------------------------------------------------------- */
@@ -50,8 +50,10 @@ export interface SvgVetBudget {
50
50
  }
51
51
  /**
52
52
  * Total outline length of a shape (or of the shapes in a group), used to
53
- * count dash segments. `Infinity` when it cannot be measured cheaply
54
- * (non-numeric geometry, arcs).
53
+ * count dash segments. A path's arc counts as the full circle of its larger
54
+ * radius, plus the straight line between its ends. `Infinity` when it
55
+ * cannot be measured cheaply (non-numeric geometry) or has an arc with a
56
+ * radius under 1.
55
57
  */
56
58
  export declare function svgShapeLength(element: XmlElement): number;
57
59
  /** How many dash segments `dasharray` cuts the element's outline into (`Infinity` when unbounded or unreadable). */