@btps/boundview 1.2.0-rc.3 → 1.2.0-rc.3.2

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.
@@ -0,0 +1,644 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ const f = (n) => String(Math.round(n * 100) / 100);
8
+ /** A CSS list split at its commas outside any brackets: "linear-gradient(90deg, rgb(1, 2, 3) 0%), url(a.png)" is two. */
9
+ export const splitTop = (value) => {
10
+ const out = [];
11
+ let depth = 0;
12
+ let from = 0;
13
+ for (let i = 0; i < value.length; i++) {
14
+ const char = value[i];
15
+ if (char === '(')
16
+ depth++;
17
+ else if (char === ')')
18
+ depth--;
19
+ else if (char === ',' && depth === 0) {
20
+ out.push(value.slice(from, i).trim());
21
+ from = i + 1;
22
+ }
23
+ }
24
+ out.push(value.slice(from).trim());
25
+ return out.filter(Boolean);
26
+ };
27
+ /** A quarter circle's control points, as a fraction of its radius. */
28
+ const K = 0.5523;
29
+ const PATH_LIMIT = 19000;
30
+ /** Each corner's radii from computed style ("12px", "12px 8px", "50%"), scaled down together where they overlap (CSS). */
31
+ export const cornersOf = (css, width, height) => {
32
+ const keys = ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius'];
33
+ const corners = keys.map((key) => {
34
+ const [h = '0', v = h] = css[key].split(/\s+/);
35
+ const read = (value, of) => (value.endsWith('%') ? (parseFloat(value) / 100) * of : parseFloat(value) || 0);
36
+ return [read(h, width), read(v, height)];
37
+ });
38
+ return fitted(corners, width, height);
39
+ };
40
+ const fitted = (corners, width, height) => {
41
+ const [tl, tr, br, bl] = corners;
42
+ const ratios = [width / (tl[0] + tr[0]), width / (bl[0] + br[0]), height / (tl[1] + bl[1]), height / (tr[1] + br[1])].filter(Number.isFinite);
43
+ const scale = Math.min(1, ...ratios);
44
+ return corners.map(([h, v]) => [Math.max(0, h * scale), Math.max(0, v * scale)]);
45
+ };
46
+ export const isRound = (corners) => corners.some(([h, v]) => h > 0 || v > 0);
47
+ /** Corners `by` further out (negative: in), as a border's inner edge or an outline's outer one; a square corner stays square. */
48
+ export const grown = (corners, top, right, bottom, left) => corners.map(([h, v], i) => {
49
+ if (h <= 0 && v <= 0)
50
+ return [0, 0];
51
+ const dh = i === 0 || i === 3 ? left : right;
52
+ const dv = i === 0 || i === 1 ? top : bottom;
53
+ return [Math.max(0, h + dh), Math.max(0, v + dv)];
54
+ });
55
+ /** A rectangle with its corners, as path data: drawn clockwise from the top left. */
56
+ export const roundedRect = (r, corners) => {
57
+ const { x, y, width: w, height: h } = r;
58
+ if (w <= 0 || h <= 0)
59
+ return '';
60
+ if (!corners || !isRound(corners))
61
+ return `M${f(x)} ${f(y)}H${f(x + w)}V${f(y + h)}H${f(x)}Z`;
62
+ const [[tlh, tlv], [trh, trv], [brh, brv], [blh, blv]] = fitted(corners, w, h);
63
+ const arc = (x1, y1, c1x, c1y, c2x, c2y, x2, y2) => x1 === x2 && y1 === y2 ? '' : `C${f(c1x)} ${f(c1y)} ${f(c2x)} ${f(c2y)} ${f(x2)} ${f(y2)}`;
64
+ return (`M${f(x + tlh)} ${f(y)}H${f(x + w - trh)}` +
65
+ arc(x + w - trh, y, x + w - trh + trh * K, y, x + w, y + trv - trv * K, x + w, y + trv) +
66
+ `V${f(y + h - brv)}` +
67
+ arc(x + w, y + h - brv, x + w, y + h - brv + brv * K, x + w - brh + brh * K, y + h, x + w - brh, y + h) +
68
+ `H${f(x + blh)}` +
69
+ arc(x + blh, y + h, x + blh - blh * K, y + h, x, y + h - blv + blv * K, x, y + h - blv) +
70
+ `V${f(y + tlv)}` +
71
+ arc(x, y + tlv, x, y + tlv - tlv * K, x + tlh - tlh * K, y, x + tlh, y) +
72
+ 'Z');
73
+ };
74
+ /** What lies between two outlines, the inner one cut out. */
75
+ const ring = (outer, inner, fill, opacity) => ({ type: 'path', d: `${outer}${inner}`, fillRule: 'evenodd', fill, ...(opacity !== undefined && opacity < 1 && { opacity: Math.round(opacity * 1000) / 1000 }) });
76
+ /** Many small shapes as few paths, each within the path limit. */
77
+ const batched = (pieces, fill) => {
78
+ const out = [];
79
+ let d = '';
80
+ for (const piece of pieces) {
81
+ if (d.length + piece.length > PATH_LIMIT) {
82
+ out.push({ type: 'path', d, fill });
83
+ d = '';
84
+ }
85
+ d += piece;
86
+ }
87
+ if (d)
88
+ out.push({ type: 'path', d, fill });
89
+ return out;
90
+ };
91
+ /**
92
+ * A dashed or dotted stroke from (x1, y1) to (x2, y2), `width` thick, as one dashed line, spaced as the browser spaces
93
+ * it: a dash three widths long, a dot as wide as the line, the gaps evened out so it starts and ends on a mark.
94
+ */
95
+ const marks = (x1, y1, x2, y2, width, style, colour) => {
96
+ const length = Math.hypot(x2 - x1, y2 - y1);
97
+ if (length <= 0 || width <= 0)
98
+ return [];
99
+ const mark = style === 'dotted' ? width : Math.max(width * 3, 3);
100
+ const count = Math.max(1, Math.round((length + mark) / (mark * 2)));
101
+ const gap = count > 1 ? (length - count * mark) / (count - 1) : 0;
102
+ const r = (n) => Math.round(n * 100) / 100;
103
+ return [
104
+ {
105
+ type: 'line',
106
+ from: [r(x1), r(y1)],
107
+ to: [r(x2), r(y2)],
108
+ stroke: colour,
109
+ strokeWidth: r(width),
110
+ ...(count > 1 && { dash: [r(mark), Math.max(0.01, r(gap))] }),
111
+ },
112
+ ];
113
+ };
114
+ /** A box's border, as the browser paints it from its four sides and its corners. */
115
+ export const borders = (box, corners, sides) => {
116
+ const shown = sides.map((side) => (side.width > 0 && side.colour && side.style !== 'none' && side.style !== 'hidden' ? side : undefined));
117
+ if (shown.every((side) => !side))
118
+ return [];
119
+ const [t, r, b, l] = shown.map((side) => side?.width ?? 0);
120
+ const inner = { x: box.x + l, y: box.y + t, width: box.width - l - r, height: box.height - t - b };
121
+ const innerCorners = grown(corners, -t, -r, -b, -l);
122
+ const visible = shown.filter((side) => side !== undefined);
123
+ const first = visible[0];
124
+ const plain = (style) => !['dashed', 'dotted', 'double'].includes(style);
125
+ const same = visible.every((side) => side.colour === first.colour && (plain(side.style) ? plain(first.style) : side.style === first.style));
126
+ // One colour, solid: the ring between the border's outer and inner edges, exact for any widths and corners.
127
+ if (same && plain(first.style))
128
+ return [ring(roundedRect(box, corners), roundedRect(inner, innerCorners), first.colour)];
129
+ // Double: its outer and inner thirds.
130
+ if (same && first.style === 'double') {
131
+ const third = (w) => Math.round((w / 3) * 100) / 100;
132
+ const [t1, r1, b1, l1] = [t, r, b, l].map(third);
133
+ const outerInner = { x: box.x + l1, y: box.y + t1, width: box.width - l1 - r1, height: box.height - t1 - b1 };
134
+ const innerOuter = { x: inner.x - l1, y: inner.y - t1, width: inner.width + l1 + r1, height: inner.height + t1 + b1 };
135
+ return [
136
+ ring(roundedRect(box, corners), roundedRect(outerInner, grown(corners, -t1, -r1, -b1, -l1)), first.colour),
137
+ ring(roundedRect(innerOuter, grown(innerCorners, t1, r1, b1, l1)), roundedRect(inner, innerCorners), first.colour),
138
+ ];
139
+ }
140
+ // Each side on its own: solid sides as their part of the frame, mitred at the corners; dashed and dotted along the
141
+ // middle of the side, between its corners' curves.
142
+ const out = [];
143
+ const [[tlh, tlv], [trh, trv], [brh, brv], [blh, blv]] = corners;
144
+ const o = { l: box.x, t: box.y, r: box.x + box.width, b: box.y + box.height };
145
+ const i = { l: inner.x, t: inner.y, r: inner.x + inner.width, b: inner.y + inner.height };
146
+ const frames = [
147
+ [[o.l, o.t], [o.r, o.t], [i.r, i.t], [i.l, i.t]],
148
+ [[o.r, o.t], [o.r, o.b], [i.r, i.b], [i.r, i.t]],
149
+ [[o.r, o.b], [o.l, o.b], [i.l, i.b], [i.r, i.b]],
150
+ [[o.l, o.b], [o.l, o.t], [i.l, i.t], [i.l, i.b]],
151
+ ];
152
+ const middles = [
153
+ [o.l + Math.max(tlh, l), o.t + t / 2, o.r - Math.max(trh, r), o.t + t / 2],
154
+ [o.r - r / 2, o.t + Math.max(trv, t), o.r - r / 2, o.b - Math.max(brv, b)],
155
+ [o.r - Math.max(brh, r), o.b - b / 2, o.l + Math.max(blh, l), o.b - b / 2],
156
+ [o.l + l / 2, o.b - Math.max(blv, b), o.l + l / 2, o.t + Math.max(tlv, t)],
157
+ ];
158
+ shown.forEach((side, index) => {
159
+ if (!side)
160
+ return;
161
+ const colour = side.colour;
162
+ if (side.style === 'dashed' || side.style === 'dotted') {
163
+ const [x1, y1, x2, y2] = middles[index];
164
+ out.push(...marks(x1, y1, x2, y2, side.width, side.style, colour));
165
+ return;
166
+ }
167
+ const points = frames[index];
168
+ if (side.style === 'double') {
169
+ // The side's outer and inner thirds of its frame.
170
+ const lerp = (a, c, k) => [a[0] + (c[0] - a[0]) * k, a[1] + (c[1] - a[1]) * k];
171
+ const [p0, p1, p2, p3] = points;
172
+ for (const [from, to] of [[0, 1 / 3], [2 / 3, 1]]) {
173
+ const quad = [lerp(p0, p3, from), lerp(p1, p2, from), lerp(p1, p2, to), lerp(p0, p3, to)];
174
+ out.push({ type: 'path', d: `M${quad.map(([x, y]) => `${f(x)} ${f(y)}`).join('L')}Z`, fill: colour });
175
+ }
176
+ return;
177
+ }
178
+ out.push({ type: 'path', d: `M${points.map(([x, y]) => `${f(x)} ${f(y)}`).join('L')}Z`, fill: colour });
179
+ });
180
+ return out;
181
+ };
182
+ /** Computed box-shadow ("rgba(0, 0, 0, 0.2) 0px 1px 3px 0px, ... inset") as its shadows, first painted last. */
183
+ export const shadowsOf = (value, colourOf) => {
184
+ if (!value || value === 'none')
185
+ return [];
186
+ return splitTop(value)
187
+ .flatMap((part) => {
188
+ const colourText = /(rgba?\([^)]*\)|#[0-9a-f]+|[a-z]+(?=\s|$))/i.exec(part.replace(/\binset\b/, ''))?.[1] ?? 'rgba(0,0,0,1)';
189
+ const numbers = part.replace(colourText, '').replace(/\binset\b/, '').trim().split(/\s+/).map(parseFloat).filter(Number.isFinite);
190
+ const hex = colourOf(colourText);
191
+ if (!hex)
192
+ return [];
193
+ const alpha = hex.length === 9 ? parseInt(hex.slice(7), 16) / 255 : 1;
194
+ const [x = 0, y = 0, blur = 0, spread = 0] = numbers;
195
+ return [{ x, y, blur, spread, colour: hex.slice(0, 7), alpha, inset: /\binset\b/.test(part) }];
196
+ })
197
+ .reverse();
198
+ };
199
+ /**
200
+ * What of a convex shape lies outside a box: above it, below it, and beside it between the two. The browser paints an
201
+ * outer shadow only there; inside the box is the box's own.
202
+ */
203
+ const outsideOf = (shape, box) => {
204
+ const top = box.y;
205
+ const bottom = box.y + box.height;
206
+ const left = box.x;
207
+ const right = box.x + box.width;
208
+ const pieces = [
209
+ cut(shape, [0, 1], top),
210
+ cut(shape, [0, -1], -bottom),
211
+ cut(cut(cut(shape, [0, -1], -top), [0, 1], bottom), [1, 0], left),
212
+ cut(cut(cut(shape, [0, -1], -top), [0, 1], bottom), [-1, 0], -right),
213
+ ];
214
+ return pieces.map(polygonPath).join('');
215
+ };
216
+ /**
217
+ * A box's outer shadows, drawn before its background, outside the box only, as the browser clips them to it. A blurred
218
+ * edge as layers: each the shadow grown by a step of the blur, faint enough that where all lie it has its full strength,
219
+ * so the edge fades over the blur's width as the browser's Gaussian does.
220
+ */
221
+ export const outerShadows = (box, corners, shadows) => shadows
222
+ .filter((shadow) => !shadow.inset)
223
+ .flatMap((shadow) => {
224
+ const sigma = shadow.blur / 2;
225
+ const n = shadow.blur <= 0 ? 1 : Math.min(8, Math.max(3, Math.ceil(shadow.blur / 2)));
226
+ const each = n === 1 ? shadow.alpha : 1 - Math.pow(1 - shadow.alpha, 1 / n);
227
+ const out = [];
228
+ for (let k = 0; k < n; k++) {
229
+ // From 2σ out to 2σ in, evenly: a layer each step.
230
+ const by = shadow.spread + (n === 1 ? 0 : 2 * sigma * (1 - (2 * (k + 0.5)) / n));
231
+ const rect = { x: box.x + shadow.x - by, y: box.y + shadow.y - by, width: box.width + 2 * by, height: box.height + 2 * by };
232
+ if (rect.width <= 0 || rect.height <= 0)
233
+ continue;
234
+ const d = outsideOf(outlinePoints(rect, grown(corners, by, by, by, by)), box);
235
+ if (d)
236
+ out.push({ type: 'path', d, fill: shadow.colour, ...(each < 1 && { opacity: Math.round(each * 1000) / 1000 }) });
237
+ }
238
+ return out;
239
+ });
240
+ /** A box's inset shadows, drawn over its background: inside its padding box, where the shifted, shrunk box is not. */
241
+ export const insetShadows = (padding, corners, shadows) => shadows
242
+ .filter((shadow) => shadow.inset)
243
+ .flatMap((shadow) => {
244
+ const outer = roundedRect(padding, corners);
245
+ // The hole, inside the padding box (what falls outside it would be painted outside the box).
246
+ const hole = (grow) => {
247
+ const by = shadow.spread - grow;
248
+ const x1 = Math.max(padding.x, padding.x + shadow.x + by);
249
+ const y1 = Math.max(padding.y, padding.y + shadow.y + by);
250
+ const x2 = Math.min(padding.x + padding.width, padding.x + shadow.x + padding.width - by);
251
+ const y2 = Math.min(padding.y + padding.height, padding.y + shadow.y + padding.height - by);
252
+ return x2 > x1 && y2 > y1 ? roundedRect({ x: x1, y: y1, width: x2 - x1, height: y2 - y1 }, grown(corners, -by, -by, -by, -by)) : '';
253
+ };
254
+ const sigma = shadow.blur / 2;
255
+ const n = shadow.blur <= 0 ? 1 : Math.min(8, Math.max(3, Math.ceil(shadow.blur / 2)));
256
+ const each = 1 - Math.pow(1 - shadow.alpha, 1 / n);
257
+ const out = [];
258
+ for (let k = 0; k < n; k++) {
259
+ const grow = n === 1 ? 0 : 2 * sigma * (1 - (2 * (k + 0.5)) / n);
260
+ out.push(ring(outer, hole(grow), shadow.colour, n === 1 ? shadow.alpha : each));
261
+ }
262
+ return out;
263
+ });
264
+ /** A box's outline: outside its border by its offset, following its corners (as Chrome draws it since 94). */
265
+ export const outline = (box, corners, css, colourOf) => {
266
+ const style = css.outlineStyle;
267
+ const width = parseFloat(css.outlineWidth) || 0;
268
+ if (style === 'none' || width <= 0)
269
+ return [];
270
+ const colour = colourOf(css.outlineColor);
271
+ if (!colour)
272
+ return [];
273
+ const offset = parseFloat(css.outlineOffset) || 0;
274
+ const by = offset + width;
275
+ const outer = { x: box.x - by, y: box.y - by, width: box.width + 2 * by, height: box.height + 2 * by };
276
+ const outerCorners = grown(corners, by, by, by, by);
277
+ return borders(outer, outerCorners, [0, 1, 2, 3].map(() => ({ width, style: style === 'auto' ? 'solid' : style, colour })));
278
+ };
279
+ /** The convex outline of a box with its corners, as points (each curve in a few straight steps). */
280
+ const outlinePoints = (r, corners, steps = 6) => {
281
+ const [[tlh, tlv], [trh, trv], [brh, brv], [blh, blv]] = fitted(corners, r.width, r.height);
282
+ const arc = (cx, cy, h, v, from) => h <= 0 && v <= 0
283
+ ? [[cx, cy]]
284
+ : Array.from({ length: steps + 1 }, (_, i) => {
285
+ const a = from + (Math.PI / 2) * (i / steps);
286
+ return [cx + Math.cos(a) * h, cy + Math.sin(a) * v];
287
+ });
288
+ const { x, y, width: w, height: h } = r;
289
+ return [
290
+ ...arc(x + tlh, y + tlv, tlh, tlv, Math.PI),
291
+ ...arc(x + w - trh, y + trv, trh, trv, -Math.PI / 2),
292
+ ...arc(x + w - brh, y + h - brv, brh, brv, 0),
293
+ ...arc(x + blh, y + h - blv, blh, blv, Math.PI / 2),
294
+ ];
295
+ };
296
+ /** A convex polygon cut to one side of a line: keeps the points where a·p ≤ c. */
297
+ const cut = (points, a, c) => {
298
+ const out = [];
299
+ for (let i = 0; i < points.length; i++) {
300
+ const p = points[i];
301
+ const q = points[(i + 1) % points.length];
302
+ const dp = a[0] * p[0] + a[1] * p[1] - c;
303
+ const dq = a[0] * q[0] + a[1] * q[1] - c;
304
+ if (dp <= 0)
305
+ out.push(p);
306
+ if ((dp < 0 && dq > 0) || (dp > 0 && dq < 0)) {
307
+ const t = dp / (dp - dq);
308
+ out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
309
+ }
310
+ }
311
+ return out;
312
+ };
313
+ /** Sutherland–Hodgman: a polygon cut to a convex one. */
314
+ const clipTo = (points, clip) => {
315
+ let out = points;
316
+ // The clip's winding, so each edge keeps its inside.
317
+ const area = clip.reduce((sum, p, i) => {
318
+ const q = clip[(i + 1) % clip.length];
319
+ return sum + (p[0] * q[1] - q[0] * p[1]);
320
+ }, 0);
321
+ for (let i = 0; i < clip.length && out.length > 0; i++) {
322
+ const p = clip[i];
323
+ const q = clip[(i + 1) % clip.length];
324
+ // The edge's outward normal: inside is where it points away.
325
+ const normal = area > 0 ? [q[1] - p[1], -(q[0] - p[0])] : [-(q[1] - p[1]), q[0] - p[0]];
326
+ out = cut(out, normal, normal[0] * p[0] + normal[1] * p[1]);
327
+ }
328
+ return out;
329
+ };
330
+ const polygonPath = (points) => (points.length < 3 ? '' : `M${points.map(([x, y]) => `${f(x)} ${f(y)}`).join('L')}Z`);
331
+ /** The arguments of a CSS function, split at its top-level commas. */
332
+ const argsOf = (value, name) => {
333
+ const match = new RegExp(`^${name}\\((.*)\\)$`).exec(value.trim());
334
+ return match ? splitTop(match[1]) : undefined;
335
+ };
336
+ /** Colour stops with their positions along a gradient of `length` px: positions in px, the unset ones spread between. */
337
+ const stopsOf = (parts, length, colourOf) => {
338
+ const stops = [];
339
+ for (const part of parts) {
340
+ const colourText = /^(rgba?\([^)]*\)|#[0-9a-f]+|[a-z]+)/i.exec(part)?.[1];
341
+ if (!colourText)
342
+ return undefined;
343
+ const colour = colourOf(colourText) ?? (/transparent|rgba\([^)]*,\s*0\)/i.test(colourText) ? '#ffffff00' : undefined);
344
+ if (!colour)
345
+ return undefined;
346
+ const positions = part
347
+ .slice(colourText.length)
348
+ .trim()
349
+ .split(/\s+/)
350
+ .filter(Boolean)
351
+ .map((p) => (p.endsWith('%') ? (parseFloat(p) / 100) * length : parseFloat(p)));
352
+ if (positions.length === 0)
353
+ stops.push({ colour });
354
+ for (const at of positions)
355
+ stops.push({ colour, at });
356
+ }
357
+ if (stops.length < 2)
358
+ return undefined;
359
+ const first = stops[0];
360
+ const last = stops[stops.length - 1];
361
+ first.at ??= 0;
362
+ last.at ??= length;
363
+ // Unset positions evenly between their set neighbours; each no earlier than the one before.
364
+ for (let i = 1; i < stops.length; i++) {
365
+ const stop = stops[i];
366
+ if (stop.at !== undefined) {
367
+ stop.at = Math.max(stop.at, stops[i - 1].at);
368
+ continue;
369
+ }
370
+ let j = i;
371
+ while (stops[j].at === undefined)
372
+ j++;
373
+ const from = stops[i - 1].at;
374
+ const to = stops[j].at;
375
+ for (let k = i; k < j; k++)
376
+ stops[k].at = from + ((to - from) * (k - i + 1)) / (j - i + 1);
377
+ }
378
+ return stops;
379
+ };
380
+ const mix = (a, b, t) => {
381
+ const read = (c) => [1, 3, 5, 7].map((i) => (i === 7 ? (c.length === 9 ? parseInt(c.slice(7, 9), 16) : 255) : parseInt(c.slice(i, i + 2), 16)));
382
+ const ca = read(a);
383
+ const cb = read(b);
384
+ const m = ca.map((v, i) => Math.round(v + (cb[i] - v) * t));
385
+ const two = (n) => n.toString(16).padStart(2, '0');
386
+ return `#${two(m[0])}${two(m[1])}${two(m[2])}${m[3] < 255 ? two(m[3]) : ''}`;
387
+ };
388
+ /** The colour at `at` px along stops, as the browser interpolates between them. */
389
+ const colourAt = (stops, at) => {
390
+ if (at <= stops[0].at)
391
+ return stops[0].colour;
392
+ for (let i = 1; i < stops.length; i++) {
393
+ const a = stops[i - 1];
394
+ const b = stops[i];
395
+ if (at <= b.at)
396
+ return b.at === a.at ? b.colour : mix(a.colour, b.colour, (at - a.at) / (b.at - a.at));
397
+ }
398
+ return stops[stops.length - 1].colour;
399
+ };
400
+ /** A position ("50%", "10px", "left", "right 8px", "calc(100% - 8px)") along `room`, as background and gradient centres use. */
401
+ export const positionAlong = (value, room) => {
402
+ const v = value.trim();
403
+ const keyword = { left: 0, top: 0, center: 0.5, right: 1, bottom: 1 };
404
+ const parts = v.split(/\s+/);
405
+ if (parts.length === 2 && parts[0] in keyword) {
406
+ const k = keyword[parts[0]];
407
+ const off = positionAlong(parts[1], room);
408
+ return k === 1 ? room - off : off;
409
+ }
410
+ if (v in keyword)
411
+ return keyword[v] * room;
412
+ const calc = /^calc\((-?[\d.]+)%\s*([+-])\s*([\d.]+)px\)$/.exec(v);
413
+ if (calc)
414
+ return (parseFloat(calc[1]) / 100) * room + (calc[2] === '-' ? -1 : 1) * parseFloat(calc[3]);
415
+ if (v.endsWith('%'))
416
+ return (parseFloat(v) / 100) * room;
417
+ return parseFloat(v) || 0;
418
+ };
419
+ /**
420
+ * A radial-gradient layer in a box: a circle as BoundView's radial paint, exactly; an ellipse as bands of its colours,
421
+ * each cut to the box, at most a step of 1/32 of the gradient apart.
422
+ */
423
+ export const radialBackground = (box, corners, value, colourOf) => {
424
+ const args = argsOf(value, 'radial-gradient');
425
+ if (!args)
426
+ return undefined;
427
+ let shape = 'ellipse';
428
+ let size = 'farthest-corner';
429
+ let centre = [box.x + box.width / 2, box.y + box.height / 2];
430
+ let explicit;
431
+ const head = args[0];
432
+ if (!/^(rgba?\(|#|[a-z]+$)/i.test(head) || /\b(circle|ellipse|at|closest|farthest)\b/.test(head)) {
433
+ args.shift();
434
+ const [spec = '', at] = head.split(/\s+at\s+/);
435
+ for (const word of spec.split(/\s+/).filter(Boolean)) {
436
+ if (word === 'circle' || word === 'ellipse')
437
+ shape = word;
438
+ else if (/^(closest|farthest)-(side|corner)$/.test(word))
439
+ size = word;
440
+ }
441
+ const lengths = spec.split(/\s+/).filter((w) => /^[\d.]+(px|%)$/.test(w));
442
+ if (lengths.length > 0) {
443
+ const rx = lengths[0];
444
+ const ry = (lengths[1] ?? lengths[0]);
445
+ explicit = [rx.endsWith('%') ? (parseFloat(rx) / 100) * box.width : parseFloat(rx), ry.endsWith('%') ? (parseFloat(ry) / 100) * box.height : parseFloat(ry)];
446
+ if (lengths.length === 1)
447
+ shape = 'circle';
448
+ }
449
+ const where = at ?? (/^at\s+(.*)$/.exec(head)?.[1]);
450
+ if (where) {
451
+ const [px = 'center', py = 'center'] = where.trim().split(/\s+(?![^(]*\))/);
452
+ const vertical = ['top', 'bottom'].includes(px);
453
+ centre = vertical
454
+ ? [box.x + positionAlong(py, box.width), box.y + positionAlong(px, box.height)]
455
+ : [box.x + positionAlong(px, box.width), box.y + positionAlong(py, box.height)];
456
+ }
457
+ }
458
+ const dx = [centre[0] - box.x, box.x + box.width - centre[0]];
459
+ const dy = [centre[1] - box.y, box.y + box.height - centre[1]];
460
+ const far = [Math.max(...dx), Math.max(...dy)];
461
+ const near = [Math.min(...dx), Math.min(...dy)];
462
+ let rx;
463
+ let ry;
464
+ if (explicit)
465
+ [rx, ry] = explicit;
466
+ else if (shape === 'circle') {
467
+ const r = size === 'closest-side' ? Math.min(...near) : size === 'farthest-side' ? Math.max(...far) : size === 'closest-corner' ? Math.hypot(...near) : Math.hypot(...far);
468
+ rx = ry = r;
469
+ }
470
+ else {
471
+ const side = size.startsWith('closest') ? near : far;
472
+ const k = size.endsWith('corner') ? Math.SQRT2 : 1;
473
+ rx = side[0] * k;
474
+ ry = side[1] * k;
475
+ }
476
+ if (rx <= 0 || ry <= 0)
477
+ return undefined;
478
+ const stops = stopsOf(args, Math.max(rx, ry), colourOf);
479
+ if (!stops)
480
+ return undefined;
481
+ const outlineD = roundedRect(box, corners);
482
+ if (Math.abs(rx - ry) < 0.5) {
483
+ const r = Math.max(rx, ry);
484
+ return [{ type: 'path', d: outlineD, fill: { radial: { centre: [Math.round(centre[0] * 100) / 100, Math.round(centre[1] * 100) / 100], radius: Math.round(r * 100) / 100, stops: stops.slice(0, 8).map(({ colour, at }) => [Math.min(1, Math.max(0, at / r)), colour]) } } }];
485
+ }
486
+ // An ellipse: the last colour everywhere, then each band inward, cut to the box.
487
+ const clip = outlinePoints(box, corners);
488
+ const scale = Math.max(rx, ry);
489
+ // As many bands as the colours have steps to show, up to 24: a faint gradient needs few to look the same.
490
+ const channel = (c, i) => parseInt(c.slice(1 + i * 2, 3 + i * 2), 16);
491
+ const range = Math.max(...[0, 1, 2].map((i) => Math.max(...stops.map(({ colour }) => channel(colour, i))) - Math.min(...stops.map(({ colour }) => channel(colour, i)))));
492
+ const steps = Math.max(2, Math.min(24, Math.ceil(range / 3)));
493
+ const out = [{ type: 'path', d: outlineD, fill: colourAt(stops, scale) }];
494
+ for (let i = steps - 1; i >= 0; i--) {
495
+ const t = (i + 0.5) / steps;
496
+ const ellipse = Array.from({ length: 32 }, (_, k) => {
497
+ const a = (k / 32) * Math.PI * 2;
498
+ return [centre[0] + Math.cos(a) * rx * ((i + 1) / steps), centre[1] + Math.sin(a) * ry * ((i + 1) / steps)];
499
+ });
500
+ const d = polygonPath(clipTo(ellipse, clip));
501
+ if (d)
502
+ out.push({ type: 'path', d, fill: colourAt(stops, t * scale) });
503
+ }
504
+ return out;
505
+ };
506
+ /** A background image's drawn size from background-size, in its positioning area: cover, contain, lengths, auto. */
507
+ export const backgroundSize = (value, areaW, areaH, imageW, imageH) => {
508
+ if (value === 'cover' || value === 'contain') {
509
+ const k = (value === 'cover' ? Math.max : Math.min)(areaW / imageW, areaH / imageH);
510
+ return [imageW * k, imageH * k];
511
+ }
512
+ const [a = 'auto', b = 'auto'] = value.split(/\s+/);
513
+ const length = (v, of) => (v === 'auto' ? undefined : v.endsWith('%') ? (parseFloat(v) / 100) * of : parseFloat(v));
514
+ let w = length(a, areaW);
515
+ let h = length(b, areaH);
516
+ if (w === undefined && h === undefined)
517
+ return [imageW, imageH];
518
+ w ??= imageW * (h / imageH);
519
+ h ??= imageH * (w / imageW);
520
+ return [w, h];
521
+ };
522
+ /** A linear-gradient layer as BoundView's linear paint, along the gradient line CSS draws for its angle. */
523
+ export const linearPaint = (box, value, colourOf) => {
524
+ const args = argsOf(value, 'linear-gradient');
525
+ if (!args)
526
+ return undefined;
527
+ let angle = 180;
528
+ const head = args[0];
529
+ if (/(deg|turn|rad)$/.test(head)) {
530
+ angle = head.endsWith('turn') ? parseFloat(head) * 360 : head.endsWith('rad') ? (parseFloat(head) * 180) / Math.PI : parseFloat(head);
531
+ args.shift();
532
+ }
533
+ else if (head.startsWith('to ')) {
534
+ // A corner: the angle that makes the gradient's middle line run corner to corner, as CSS defines it.
535
+ const sides = head.slice(3).split(/\s+/);
536
+ const h = sides.includes('right') ? 1 : sides.includes('left') ? -1 : 0;
537
+ const v = sides.includes('bottom') ? 1 : sides.includes('top') ? -1 : 0;
538
+ angle = h === 0 ? (v > 0 ? 180 : 0) : v === 0 ? (h > 0 ? 90 : 270) : (Math.atan2(h * box.height, -v * box.width) * 180) / Math.PI;
539
+ args.shift();
540
+ }
541
+ const rad = (angle * Math.PI) / 180;
542
+ const length = Math.abs(box.width * Math.sin(rad)) + Math.abs(box.height * Math.cos(rad));
543
+ const stops = stopsOf(args, length, colourOf);
544
+ if (!stops || length <= 0)
545
+ return undefined;
546
+ // More than eight stops: every eighth kept, ends included (BoundView carries eight).
547
+ const kept = stops.length <= 8 ? stops : Array.from({ length: 8 }, (_, i) => stops[Math.round((i * (stops.length - 1)) / 7)]);
548
+ const cx = box.x + box.width / 2;
549
+ const cy = box.y + box.height / 2;
550
+ const dx = (Math.sin(rad) * length) / 2;
551
+ const dy = (-Math.cos(rad) * length) / 2;
552
+ const r = (n) => Math.round(n * 100) / 100;
553
+ return {
554
+ linear: {
555
+ from: [r(cx - dx), r(cy - dy)],
556
+ to: [r(cx + dx), r(cy + dy)],
557
+ stops: kept.map(({ colour, at }) => [r(Math.min(1, Math.max(0, at / length))), colour]),
558
+ },
559
+ };
560
+ };
561
+ /** A repeating-linear-gradient layer: its stripes, each cut to the box, soft edges in a few steps. */
562
+ export const repeatingLinear = (box, corners, value, colourOf) => {
563
+ const args = argsOf(value, 'repeating-linear-gradient');
564
+ if (!args)
565
+ return undefined;
566
+ let angle = 180;
567
+ const head = args[0];
568
+ if (/deg$/.test(head)) {
569
+ angle = parseFloat(head);
570
+ args.shift();
571
+ }
572
+ else if (head.startsWith('to ')) {
573
+ const sides = { 'to top': 0, 'to right': 90, 'to bottom': 180, 'to left': 270 };
574
+ if (sides[head] === undefined)
575
+ return undefined;
576
+ angle = sides[head];
577
+ args.shift();
578
+ }
579
+ const rad = (angle * Math.PI) / 180;
580
+ const dir = [Math.sin(rad), -Math.cos(rad)];
581
+ const length = Math.abs(box.width * Math.sin(rad)) + Math.abs(box.height * Math.cos(rad));
582
+ const stops = stopsOf(args, length, colourOf);
583
+ if (!stops)
584
+ return undefined;
585
+ const period = stops[stops.length - 1].at - stops[0].at;
586
+ if (period <= 0.5)
587
+ return undefined;
588
+ const centre = [box.x + box.width / 2, box.y + box.height / 2];
589
+ const startAlong = dir[0] * centre[0] + dir[1] * centre[1] - length / 2;
590
+ const clip = outlinePoints(box, corners);
591
+ // Bands within one period: each pair of stops, split in four where its colours differ.
592
+ const bands = [];
593
+ for (let i = 1; i < stops.length; i++) {
594
+ const a = stops[i - 1];
595
+ const b = stops[i];
596
+ if (b.at <= a.at)
597
+ continue;
598
+ const parts = a.colour === b.colour ? 1 : 4;
599
+ for (let k = 0; k < parts; k++) {
600
+ bands.push({ from: a.at + ((b.at - a.at) * k) / parts, to: a.at + ((b.at - a.at) * (k + 1)) / parts, colour: mix(a.colour, b.colour, (k + 0.5) / parts) });
601
+ }
602
+ }
603
+ const byColour = new Map();
604
+ const offset = stops[0].at;
605
+ for (let p = Math.floor(-offset / period) - 1; p * period + offset < length + period; p++) {
606
+ for (const band of bands) {
607
+ const from = startAlong + p * period + band.from;
608
+ const to = startAlong + p * period + band.to;
609
+ // Between two lines across the gradient: along ≥ from and along ≤ to.
610
+ let piece = cut(clip, [-dir[0], -dir[1]], -from);
611
+ piece = cut(piece, dir, to);
612
+ const d = polygonPath(piece);
613
+ if (d)
614
+ byColour.set(band.colour, [...(byColour.get(band.colour) ?? []), d]);
615
+ }
616
+ }
617
+ return [...byColour].flatMap(([colour, pieces]) => batched(pieces, colour));
618
+ };
619
+ /** A line drawn as text decoration: solid, double, dotted, dashed or wavy, from x1 to x2 at y (its middle). */
620
+ export const decorationLine = (x1, x2, y, thickness, style, colour) => {
621
+ if (x2 <= x1 || thickness <= 0)
622
+ return [];
623
+ const band = (top) => `M${f(x1)} ${f(top)}H${f(x2)}V${f(top + thickness)}H${f(x1)}Z`;
624
+ if (style === 'double')
625
+ return [{ type: 'path', d: band(y - thickness * 1.5) + band(y + thickness * 0.5), fill: colour }];
626
+ if (style === 'dotted' || style === 'dashed')
627
+ return marks(x1, y, x2, y, thickness, style, colour);
628
+ if (style === 'wavy') {
629
+ // A wave as Chrome draws it: a period of about six thicknesses, as high as three, stroked.
630
+ const period = Math.max(4, thickness * 6);
631
+ const amp = Math.max(1.5, thickness * 1.5);
632
+ let d = `M${f(x1)} ${f(y)}`;
633
+ for (let x = x1; x < x2; x += period) {
634
+ const half = Math.min(period / 2, x2 - x);
635
+ d += `Q${f(x + half / 2)} ${f(y - amp * 2)} ${f(x + half)} ${f(y)}`;
636
+ if (x + half < x2) {
637
+ const rest = Math.min(period / 2, x2 - x - half);
638
+ d += `Q${f(x + half + rest / 2)} ${f(y + amp * 2)} ${f(x + half + rest)} ${f(y)}`;
639
+ }
640
+ }
641
+ return [{ type: 'path', d, stroke: colour, strokeWidth: Math.max(1, Math.round(thickness * 100) / 100) }];
642
+ }
643
+ return [{ type: 'path', d: band(y - thickness / 2), fill: colour }];
644
+ };