@arraypress/covers 0.0.0-stage → 1.0.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 (50) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/LICENSE +29 -0
  3. package/README.md +561 -2
  4. package/fonts/OFL.txt +93 -0
  5. package/fonts/inter-latin-400.woff +0 -0
  6. package/fonts/inter-latin-500.woff +0 -0
  7. package/fonts/inter-latin-600.woff +0 -0
  8. package/fonts/inter-latin-700.woff +0 -0
  9. package/package.json +96 -4
  10. package/recipes/aurora.json +132 -0
  11. package/recipes/bauhaus.json +113 -0
  12. package/recipes/bigType.json +103 -0
  13. package/recipes/contour.json +109 -0
  14. package/recipes/cutout.json +191 -0
  15. package/recipes/diagram.json +92 -0
  16. package/recipes/dither.json +170 -0
  17. package/recipes/duotone.json +75 -0
  18. package/recipes/gridTitle.json +136 -0
  19. package/recipes/iconTile.json +214 -0
  20. package/recipes/issue.json +221 -0
  21. package/recipes/mark.json +170 -0
  22. package/recipes/photo.json +156 -0
  23. package/recipes/riso.json +387 -0
  24. package/recipes/stripes.json +206 -0
  25. package/recipes/waveform.json +154 -0
  26. package/schema/recipe.schema.json +2292 -0
  27. package/src/astro.d.ts +31 -0
  28. package/src/astro.js +86 -0
  29. package/src/color.js +246 -0
  30. package/src/diagram.js +248 -0
  31. package/src/extract.js +90 -0
  32. package/src/flatten.js +234 -0
  33. package/src/fonts.js +200 -0
  34. package/src/geometry.js +187 -0
  35. package/src/grid.js +41 -0
  36. package/src/handmade.js +253 -0
  37. package/src/icons.js +157 -0
  38. package/src/index.d.ts +897 -0
  39. package/src/index.js +19 -0
  40. package/src/json-recipe.js +458 -0
  41. package/src/layer-options.js +37 -0
  42. package/src/layers.js +972 -0
  43. package/src/palette.js +185 -0
  44. package/src/png.js +77 -0
  45. package/src/print.js +658 -0
  46. package/src/recipes.js +78 -0
  47. package/src/render.js +462 -0
  48. package/src/rng.js +95 -0
  49. package/src/svg.js +69 -0
  50. package/src/text.js +230 -0
package/src/layers.js ADDED
@@ -0,0 +1,972 @@
1
+ /**
2
+ * Layer renderers.
3
+ *
4
+ * Each layer type is one function from a layer (its options) and a render
5
+ * context to SVG markup: `{ defs, body }`. Layers paint in order, bottom
6
+ * first. Every option has a default, drawn from the palette, the canvas
7
+ * size and the layer's own seeded random stream, so `{ type: 'mesh' }` on
8
+ * its own is already a finished background.
9
+ *
10
+ * Common to every layer: `id` (names it for recipe overrides), `opacity`
11
+ * (0–1) and `blend` (a CSS `mix-blend-mode`: `multiply`, `screen`,
12
+ * `overlay`, `soft-light`, …).
13
+ *
14
+ * @module layers
15
+ */
16
+
17
+ import { readFile } from 'node:fs/promises';
18
+ import { attrs, esc, layerAttrs, num } from './svg.js';
19
+ import { len, place, anchorAlign, unit, regionPx } from './geometry.js';
20
+ import { toHex, mixOklab, toOklch, fromOklch } from './color.js';
21
+ import { harfbuzz, loadFont, pickFont } from './fonts.js';
22
+ import { layout, runPath } from './text.js';
23
+ import { resolveIcon, parseSvgIcon } from './icons.js';
24
+ import { gridPath } from './grid.js';
25
+ import { diagram } from './diagram.js';
26
+ import { paper, scribble } from './handmade.js';
27
+ import { ink, dither, contour, waveform, tiles, rule } from './print.js';
28
+
29
+ /**
30
+ * Everything a layer renderer needs.
31
+ *
32
+ * @typedef {object} RenderContext
33
+ * @property {number} width - Canvas width in px.
34
+ * @property {number} height - Canvas height in px.
35
+ * @property {{ width: number, height: number }} canvas - The same, as an object.
36
+ * @property {import('./index.js').Palette} palette - The resolved palette.
37
+ * @property {import('./rng.js').Rng} rng - This layer's own random stream.
38
+ * @property {string} id - A unique id prefix for this layer's defs.
39
+ * @property {import('./index.js').FontSource[]} fonts - Available fonts (Inter last).
40
+ * @property {any} [sharp] - The `sharp` module, when available.
41
+ */
42
+
43
+ /** @typedef {{ defs: string, body: string, pad?: number, finest?: number }} Markup */
44
+
45
+ /**
46
+ * Wrap a body in the layer's opacity/blend group (only when needed).
47
+ *
48
+ * @param {any} layer - The layer.
49
+ * @param {string} body - Its markup.
50
+ * @returns {string} Markup.
51
+ */
52
+ export function wrap(layer, body) {
53
+ const a = attrs(layerAttrs(layer));
54
+ return a ? `<g${a}>${body}</g>` : body;
55
+ }
56
+
57
+ /**
58
+ * Colour stops for a gradient. With `ease`, each pair of colours gets
59
+ * intermediate stops along a smoothstep curve (mixed in OKLab), which
60
+ * removes the hard "edge" a linear gradient shows where it starts and ends.
61
+ *
62
+ * @param {string[]} colors - Two or more colours.
63
+ * @param {boolean} ease - Ease between them.
64
+ * @param {number[]} [opacities] - Per-colour stop opacity.
65
+ * @returns {string} `<stop>` elements.
66
+ */
67
+ function stops(colors, ease, opacities) {
68
+ const out = [];
69
+ const n = colors.length - 1;
70
+ const steps = ease ? 6 : 1;
71
+ for (let i = 0; i <= n; i++) {
72
+ if (i === n || !ease) {
73
+ out.push({ o: n === 0 ? 0 : i / n, c: colors[i], a: opacities?.[i] ?? 1 });
74
+ continue;
75
+ }
76
+ for (let s = 0; s < steps; s++) {
77
+ const t = s / steps;
78
+ const e = t * t * (3 - 2 * t);
79
+ const a0 = opacities?.[i] ?? 1;
80
+ const a1 = opacities?.[i + 1] ?? 1;
81
+ out.push({ o: (i + t) / n, c: mixOklab(colors[i], colors[i + 1], e), a: a0 + (a1 - a0) * e });
82
+ }
83
+ }
84
+ return out.map((s) => `<stop${attrs({ offset: num(s.o, 4), 'stop-color': s.c, 'stop-opacity': s.a < 1 ? num(s.a, 3) : undefined })}/>`).join('');
85
+ }
86
+
87
+ /** @param {any} v @param {string} fallback @returns {string} */
88
+ const color = (v, fallback) => (v ? toHex(v) : fallback);
89
+
90
+ /** @param {string[] | undefined} list @param {string[]} fallback @returns {string[]} */
91
+ const colorList = (list, fallback) => (list?.length ? list.map(toHex) : fallback);
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // Backgrounds
95
+ // ---------------------------------------------------------------------------
96
+
97
+ /**
98
+ * `solid` — one flat colour.
99
+ *
100
+ * @param {import('./index.js').SolidLayer} layer
101
+ * @param {RenderContext} ctx
102
+ * @returns {Markup}
103
+ */
104
+ export function solid(layer, ctx) {
105
+ return { defs: '', body: wrap(layer, `<rect${attrs({ width: ctx.width, height: ctx.height, fill: color(layer.color, ctx.palette.bg) })}/>`) };
106
+ }
107
+
108
+ /**
109
+ * `linear` — a linear gradient at a CSS angle (0° points up, 90° right).
110
+ *
111
+ * @param {import('./index.js').LinearLayer} layer
112
+ * @param {RenderContext} ctx
113
+ * @returns {Markup}
114
+ */
115
+ export function linear(layer, ctx) {
116
+ const p = ctx.palette;
117
+ const colors = colorList(layer.colors, [p.colors[0], p.colors[1] ?? p.bg]);
118
+ const angle = layer.angle ?? Math.round(ctx.rng.range(0, 360));
119
+ const a = (angle * Math.PI) / 180;
120
+ const { width: w, height: h } = ctx;
121
+ const L = Math.abs(w * Math.sin(a)) + Math.abs(h * Math.cos(a));
122
+ const dx = (Math.sin(a) * L) / 2;
123
+ const dy = (-Math.cos(a) * L) / 2;
124
+ const id = `${ctx.id}g`;
125
+ const defs = `<linearGradient${attrs({ id, gradientUnits: 'userSpaceOnUse', x1: w / 2 - dx, y1: h / 2 - dy, x2: w / 2 + dx, y2: h / 2 + dy })}>${stops(colors, layer.ease !== false, layer.opacities)}</linearGradient>`;
126
+ return { defs, body: wrap(layer, `<rect${attrs({ width: w, height: h, fill: `url(#${id})` })}/>`) };
127
+ }
128
+
129
+ /**
130
+ * `radial` — a radial gradient from a centre (fractions of the canvas).
131
+ *
132
+ * @param {import('./index.js').RadialLayer} layer
133
+ * @param {RenderContext} ctx
134
+ * @returns {Markup}
135
+ */
136
+ export function radial(layer, ctx) {
137
+ const p = ctx.palette;
138
+ const colors = colorList(layer.colors, [p.colors[0], p.bg]);
139
+ const x = (layer.x ?? ctx.rng.range(0.2, 0.8)) * ctx.width;
140
+ const y = (layer.y ?? ctx.rng.range(0.2, 0.8)) * ctx.height;
141
+ const r = len(layer.radius, ctx.canvas, '80vmax');
142
+ const id = `${ctx.id}g`;
143
+ const defs = `<radialGradient${attrs({ id, gradientUnits: 'userSpaceOnUse', cx: x, cy: y, r })}>${stops(colors, layer.ease !== false)}</radialGradient>`;
144
+ return { defs, body: wrap(layer, `<rect${attrs({ width: ctx.width, height: ctx.height, fill: `url(#${id})` })}/>`) };
145
+ }
146
+
147
+ /**
148
+ * `mesh` — soft blurred fields of colour: the "mesh gradient" look.
149
+ *
150
+ * The default `sweep` arrangement lays a few large, elongated fields along
151
+ * one seeded direction, with centres free to sit beyond the frame, and
152
+ * blurs them more along that direction than across it (`streak`), which is
153
+ * how editorial gradients read: broad diagonal washes, not round spots.
154
+ * `ring` spreads rounder blobs around the centre instead.
155
+ *
156
+ * Under the fields sits a gradient across the sweep between its first two
157
+ * colours (`base: 'auto'`), so colour reaches every edge and corner and the
158
+ * page colour never shows through as a vignette. `tone` pulls every colour into a lightness and
159
+ * chroma band (OKLCH), keeping its hue: pastel palettes become clear
160
+ * mid-tones, and a dark palette can't fall to black between fields.
161
+ *
162
+ * @param {import('./index.js').MeshLayer} layer
163
+ * @param {RenderContext} ctx
164
+ * @returns {Markup}
165
+ */
166
+ export function mesh(layer, ctx) {
167
+ const { width: w, height: h, rng, palette: p } = ctx;
168
+ const max = Math.max(w, h);
169
+ // A few hues read as a colour story; every hue at once reads as a rainbow.
170
+ const pool = rng.shuffle(colorList(layer.colors, p.colors));
171
+ const want = Math.max(1, layer.hues ?? (layer.colors?.length ? pool.length : 3));
172
+ let colors = layer.hueSpan ? neighbours(pool, want, layer.hueSpan) : pool.slice(0, want);
173
+ if (layer.tone) colors = colors.map((c) => toneColor(c, /** @type {any} */ (layer.tone)));
174
+ const count = layer.blobs?.length ?? layer.count ?? 4;
175
+ const sweep = (layer.arrangement ?? 'sweep') === 'sweep';
176
+ const spread = layer.spread ?? (sweep ? 1 : 0.7);
177
+ const [smin, smax] = layer.size ?? (sweep ? [0.42, 0.72] : [0.3, 0.52]);
178
+ const blur = len(layer.blur, ctx.canvas, '11vmax');
179
+ const streak = Math.max(0.2, layer.streak ?? (sweep ? 1.5 : 1));
180
+ const angle = layer.angle ?? rng.range(0, 180);
181
+ const phase = rng.range(0, Math.PI * 2);
182
+
183
+ const blobs = [];
184
+ for (let i = 0; i < count; i++) {
185
+ const given = layer.blobs?.[i];
186
+ const rx = (given?.r ?? rng.range(smin, smax)) * max;
187
+ let cx;
188
+ let cy;
189
+ let squash;
190
+ let rot;
191
+ if (sweep) {
192
+ // Along the sweep (u) and across it (v), in units of the longer side,
193
+ // relative to the centre; then rotated into place by the group.
194
+ const t = count === 1 ? 0 : i / (count - 1) - 0.5;
195
+ const u = (t * 1.15 + rng.range(-0.12, 0.12)) * spread;
196
+ const v = rng.range(-0.32, 0.32) * spread;
197
+ cx = u * max;
198
+ cy = v * max;
199
+ squash = rng.range(0.26, 0.5);
200
+ rot = rng.range(-14, 14);
201
+ } else {
202
+ const ang = phase + (i / count) * Math.PI * 2 + rng.range(-0.45, 0.45);
203
+ const dist = spread * rng.range(0.45, 0.85);
204
+ cx = (0.5 + Math.cos(ang) * dist * 0.72) * w;
205
+ cy = (0.5 + Math.sin(ang) * dist * 0.72) * h;
206
+ squash = rng.range(0.55, 0.95);
207
+ rot = rng.range(0, 180);
208
+ }
209
+ blobs.push({
210
+ cx: given?.x != null ? (sweep ? (given.x - 0.5) * w : given.x * w) : cx,
211
+ cy: given?.y != null ? (sweep ? (given.y - 0.5) * h : given.y * h) : cy,
212
+ rx,
213
+ ry: rx * (given?.squash ?? squash),
214
+ rot: given?.rotate ?? rot,
215
+ fill: given?.color ? toHex(given.color) : colors[i % colors.length],
216
+ opacity: given?.opacity ?? 1,
217
+ });
218
+ }
219
+
220
+ const id = `${ctx.id}b`;
221
+ let defs_extra = '';
222
+ const std = sweep ? `${num(blur * streak)} ${num(blur / streak)}` : num(blur);
223
+ const defs = blur > 0
224
+ ? `<filter${attrs({ id, x: '-50%', y: '-50%', width: '200%', height: '200%', 'color-interpolation-filters': 'sRGB' })}><feGaussianBlur stdDeviation="${std}"/></filter>`
225
+ : '';
226
+ // The base: by default a gradient across the sweep between its first two
227
+ // colours (so the field is full-bleed and never muddy), else a flat fill.
228
+ let base = '';
229
+ if (layer.base !== null && layer.base !== false) {
230
+ if (layer.base === undefined || layer.base === 'auto') {
231
+ const reach = Math.hypot(w, h) / 2;
232
+ const gid = `${ctx.id}g`;
233
+ const ends = [colors[0], colors[1 % colors.length]];
234
+ defs_extra = `<linearGradient${attrs({ id: gid, gradientUnits: 'userSpaceOnUse', x1: 0, y1: -reach, x2: 0, y2: reach })}>${stops(ends, true)}</linearGradient>`;
235
+ base = `<g transform="translate(${num(w / 2)} ${num(h / 2)}) rotate(${num(sweep ? angle : 0)})"><rect${attrs({ x: -reach, y: -reach, width: reach * 2, height: reach * 2, fill: `url(#${gid})` })}/></g>`;
236
+ } else {
237
+ base = `<rect${attrs({ width: w, height: h, fill: layer.base === 'bg' ? p.bg : toHex(layer.base) })}/>`;
238
+ }
239
+ }
240
+ const shapes = blobs
241
+ .map((b) => `<ellipse${attrs({ cx: b.cx, cy: b.cy, rx: b.rx, ry: b.ry, fill: b.fill, opacity: b.opacity < 1 ? b.opacity : undefined, transform: `rotate(${num(b.rot)} ${num(b.cx)} ${num(b.cy)})` })}/>`)
242
+ .join('');
243
+ let field = `<g${attrs({ filter: blur > 0 ? `url(#${id})` : undefined })}>${shapes}</g>`;
244
+ const reach = Math.hypot(w, h) / 2 + blur * 2;
245
+
246
+ // A fold: a second field meeting the first along a soft curve, with a
247
+ // sharper edge than the blur elsewhere and a faint sheen along it (silk).
248
+ if (layer.fold) {
249
+ const f = layer.fold === true ? {} : layer.fold;
250
+ const fc = f.color ? toHex(f.color) : colors[2 % colors.length];
251
+ const far = f.to ? toHex(f.to) : mixOklab(fc, colors[0], 0.35);
252
+ const at = (f.position ?? rng.range(-0.15, 0.2)) * max;
253
+ const bend = (f.bend ?? rng.range(-0.28, 0.28)) * max;
254
+ const v = [at - bend * 0.6, at + bend, at - bend, at + bend * 0.5];
255
+ const curve = `M${num(-reach)} ${num(v[0])}C${num(-reach / 3)} ${num(v[1])} ${num(reach / 3)} ${num(v[2])} ${num(reach)} ${num(v[3])}`;
256
+ const fid = `${ctx.id}f`;
257
+ const gid2 = `${ctx.id}fg`;
258
+ const soft = blur * (f.softness ?? 0.16);
259
+ defs_extra += `<filter${attrs({ id: fid, x: '-20%', y: '-20%', width: '140%', height: '140%' })}><feGaussianBlur stdDeviation="${num(soft * streak)} ${num(soft)}"/></filter>`
260
+ + `<linearGradient${attrs({ id: gid2, gradientUnits: 'userSpaceOnUse', x1: 0, y1: at, x2: 0, y2: reach })}>${stops([fc, far], true)}</linearGradient>`;
261
+ const sheen = f.sheen ?? 0.4;
262
+ field += `<g filter="url(#${fid})"><path${attrs({ d: `${curve}V${num(reach)}H${num(-reach)}Z`, fill: `url(#${gid2})` })}/>`
263
+ + (sheen > 0 ? `<path${attrs({ d: curve, fill: 'none', stroke: mixOklab(fc, '#ffffff', 0.55), 'stroke-width': blur * 0.5, opacity: sheen })}/>` : '')
264
+ + '</g>';
265
+ }
266
+
267
+ // Streaks: thin, long, light ellipses blurred hard along the sweep (motion).
268
+ const nStreaks = layer.streaks ?? 0;
269
+ if (nStreaks > 0) {
270
+ const sid = `${ctx.id}s`;
271
+ defs_extra += `<filter${attrs({ id: sid, x: '-50%', y: '-50%', width: '200%', height: '200%' })}><feGaussianBlur stdDeviation="${num(blur * 0.7)} ${num(blur * 0.05)}"/></filter>`;
272
+ let lines = '';
273
+ for (let i = 0; i < nStreaks; i++) {
274
+ const rx = rng.range(0.35, 0.8) * max;
275
+ lines += `<ellipse${attrs({
276
+ cx: rng.range(-0.45, 0.45) * max,
277
+ cy: rng.range(-0.4, 0.4) * max,
278
+ rx,
279
+ ry: rx * rng.range(0.04, 0.11),
280
+ fill: mixOklab(colors[i % colors.length], '#ffffff', rng.range(0, 0.3)),
281
+ opacity: num(rng.range(0.45, 0.85), 2),
282
+ transform: `rotate(${num(rng.range(-6, 6))})`,
283
+ })}/>`;
284
+ }
285
+ field += `<g filter="url(#${sid})">${lines}</g>`;
286
+ }
287
+
288
+ // The sweep's group is rotated, so its (anisotropic) blur runs along the sweep.
289
+ const placed = sweep ? `<g transform="translate(${num(w / 2)} ${num(h / 2)}) rotate(${num(angle)})">${field}</g>` : field;
290
+ // For renderImage: librsvg clips a filter's input to the canvas, so blur
291
+ // near an edge pulls in transparency. It renders this layer on a padded
292
+ // canvas instead (`pad`), at a reduced scale the softest detail allows.
293
+ const finest = Math.min(sweep ? blur / streak : blur, layer.fold ? blur * ((layer.fold === true ? undefined : layer.fold.softness) ?? 0.16) : Infinity, nStreaks > 0 ? blur * 0.05 : Infinity);
294
+ return { defs: defs + defs_extra, body: wrap(layer, `${base}${placed}`), pad: Math.ceil(3 * blur * (sweep ? Math.max(1, streak) : 1)), finest };
295
+ }
296
+
297
+ /**
298
+ * Neighbouring hues only: the first colour, then others whose OKLCH hue is
299
+ * within `span`° of it; when the pool has too few, more are made by turning
300
+ * the first colour's hue (keeping its lightness and chroma) inside the span.
301
+ * Blue with violet, teal with blue, orange with pink, never olive with teal.
302
+ *
303
+ * @param {string[]} pool - Candidate colours (already shuffled).
304
+ * @param {number} want - How many.
305
+ * @param {number} span - Degrees of hue the colours may spread over.
306
+ * @returns {string[]}
307
+ */
308
+ function neighbours(pool, want, span) {
309
+ const first = toOklch(pool[0]);
310
+ const dist = (/** @type {number} */ h) => Math.abs((((h - first.h) % 360) + 540) % 360 - 180);
311
+ const chosen = [pool[0]];
312
+ if (first.c >= 0.02) {
313
+ for (const c of pool.slice(1)) {
314
+ const o = toOklch(c);
315
+ if (chosen.length < want && o.c >= 0.02 && dist(o.h) <= span * 0.45) chosen.push(c);
316
+ }
317
+ }
318
+ // Inside the span with a little room: gamut mapping can nudge a hue.
319
+ const turns = [span * 0.45, -span * 0.45, span * 0.22, -span * 0.22];
320
+ for (let i = 0; chosen.length < want && i < turns.length; i++) {
321
+ chosen.push(first.c < 0.02 ? pool[(i + 1) % pool.length] : fromOklch({ l: first.l, c: first.c, h: (first.h + turns[i] + 360) % 360 }));
322
+ }
323
+ return chosen;
324
+ }
325
+
326
+ /**
327
+ * Pull a colour into a lightness / chroma band in OKLCH, keeping its hue.
328
+ * Greys (chroma under 0.02) keep their chroma, since their hue means nothing.
329
+ * A yellow pulled dark is turned toward amber, since dark yellow is olive.
330
+ *
331
+ * @param {string} c - The colour.
332
+ * @param {{ l?: [number, number], c?: [number, number] }} band - Ranges to clamp into.
333
+ * @returns {string} `#rrggbb`.
334
+ */
335
+ export function toneColor(c, band) {
336
+ const o = toOklch(c);
337
+ const clamp = (/** @type {number} */ v, /** @type {[number, number] | undefined} */ r) => (r ? Math.min(r[1], Math.max(r[0], v)) : v);
338
+ const l = clamp(o.l, band.l);
339
+ // Yellow can't be dark: below ~0.7 lightness it reads as olive. Turn it
340
+ // toward amber as it darkens instead.
341
+ let h = o.h;
342
+ if (o.c >= 0.02 && h > 70 && h < 115 && l < 0.7) h = 70 - (0.7 - l) * 60 * ((115 - h) / 45 + 0.5);
343
+ return fromOklch({ l, c: o.c < 0.02 ? o.c : clamp(o.c, band.c), h });
344
+ }
345
+
346
+ /**
347
+ * `stripes` — bands of colour across a region: vertical, horizontal or at
348
+ * an angle. Widths can be even, random, tapering (each narrower than the
349
+ * last: the classic stripe band) or given as weights.
350
+ *
351
+ * @param {import('./index.js').StripesLayer} layer
352
+ * @param {RenderContext} ctx
353
+ * @returns {Markup}
354
+ */
355
+ export function stripes(layer, ctx) {
356
+ const { rng, palette: p } = ctx;
357
+ const r = regionPx(layer.region, ctx.canvas);
358
+ const direction = layer.direction ?? 'vertical';
359
+ const angle = direction === 'vertical' ? 0 : direction === 'horizontal' ? 90 : layer.angle ?? 45;
360
+ const colors = colorList(layer.colors, p.colors);
361
+ const count = layer.count ?? (Array.isArray(layer.widths) ? layer.widths.length : 8);
362
+ const gap = len(layer.gap, ctx.canvas, 0);
363
+ const radius = len(layer.radius, ctx.canvas, 0);
364
+
365
+ // Bands run along the rotated x axis; for a slant they must cover the diagonal.
366
+ const diagonal = angle % 90 !== 0;
367
+ const extent = diagonal ? Math.hypot(r.width, r.height) : angle === 0 ? r.width : r.height;
368
+ const cross = diagonal ? extent : angle === 0 ? r.height : r.width;
369
+
370
+ const mode = layer.widths ?? 'even';
371
+ const weights = Array.from({ length: count }, (_, i) =>
372
+ Array.isArray(mode) ? mode[i % mode.length] : mode === 'random' ? rng.range(0.35, 1.65) : mode === 'taper' ? (layer.taper ?? 0.78) ** i : 1,
373
+ );
374
+ const total = weights.reduce((a, b) => a + b, 0);
375
+ const free = Math.max(0, extent - gap * (count - 1));
376
+
377
+ let x = -extent / 2;
378
+ const bands = weights.map((wt, i) => {
379
+ const bw = (wt / total) * free;
380
+ const band = `<rect${attrs({ x, y: -cross / 2, width: Math.max(0, bw), height: cross, rx: radius || undefined, fill: colors[i % colors.length] })}/>`;
381
+ x += bw + gap;
382
+ return band;
383
+ });
384
+
385
+ const id = `${ctx.id}c`;
386
+ const cx = r.x + r.width / 2;
387
+ const cy = r.y + r.height / 2;
388
+ const defs = `<clipPath id="${id}"><rect${attrs({ x: r.x, y: r.y, width: r.width, height: r.height, rx: len(layer.regionRadius, ctx.canvas, 0) || undefined })}/></clipPath>`;
389
+ const rot = angle === 0 ? '' : ` rotate(${num(angle)})`;
390
+ return { defs, body: wrap(layer, `<g clip-path="url(#${id})"><g transform="translate(${num(cx)} ${num(cy)})${rot}">${bands.join('')}</g></g>`) };
391
+ }
392
+
393
+ /**
394
+ * `image` — a local image, cover- or contain-fit into a region, with an
395
+ * optional duotone, tint, greyscale or blur.
396
+ *
397
+ * With `sharp` installed the image is resized and cropped to its box
398
+ * before embedding (smaller SVGs, and `focus: 'attention'` / `'entropy'`
399
+ * smart crops). Without it the original bytes are embedded and fitted by
400
+ * `preserveAspectRatio` (PNG, JPEG and SVG only, since librsvg can't decode
401
+ * WebP or AVIF).
402
+ *
403
+ * @param {import('./index.js').ImageLayer} layer
404
+ * @param {RenderContext} ctx
405
+ * @returns {Promise<Markup>}
406
+ */
407
+ export async function image(layer, ctx) {
408
+ if (!layer.src) throw new TypeError('An image layer needs a src (a file path or bytes)');
409
+ const box = regionPx(layer.region, ctx.canvas);
410
+ const fit = layer.fit ?? 'cover';
411
+ const focus = layer.focus ?? 'center';
412
+ let bytes = typeof layer.src === 'string' ? await readSource(layer.src) : layer.src;
413
+ let mime = sniff(bytes);
414
+ let preserve = `${alignFor(focus)} ${fit === 'contain' ? 'meet' : 'slice'}`;
415
+ let sharpBlurred = false;
416
+
417
+ if (ctx.sharp && mime !== 'image/svg+xml') {
418
+ const w = Math.round(box.width);
419
+ const hgt = Math.round(box.height);
420
+ const position = typeof focus === 'string' && ['attention', 'entropy'].includes(focus) ? focus : (POSITIONS[focus] ?? 'centre');
421
+ let img = ctx.sharp(bytes).rotate().resize(w, hgt, { fit, position, background: { r: 0, g: 0, b: 0, alpha: 0 } });
422
+ // Stretch the tones first, so a duotone spans both of its colours.
423
+ if (layer.normalize ?? Boolean(layer.duotone || layer.grayscale)) img = img.normalise();
424
+ // Blur here rather than in SVG: sharp clamps at the edges, where an SVG
425
+ // blur (in librsvg) fades the photo to transparent.
426
+ if (layer.blur) {
427
+ img = img.blur(Math.max(0.3, len(layer.blur, ctx.canvas)));
428
+ sharpBlurred = true;
429
+ }
430
+ const meta = await ctx.sharp(bytes).metadata();
431
+ const alpha = meta.hasAlpha || fit === 'contain';
432
+ bytes = await (alpha ? img.png() : img.jpeg({ quality: 90 })).toBuffer();
433
+ mime = alpha ? 'image/png' : 'image/jpeg';
434
+ preserve = 'none';
435
+ } else if (!mime) {
436
+ throw new TypeError('Unrecognised image format (use PNG, JPEG, WebP, AVIF, GIF or SVG)');
437
+ }
438
+
439
+ const p = ctx.palette;
440
+ const id = `${ctx.id}f`;
441
+ const filters = [];
442
+ if (layer.blur && !sharpBlurred) filters.push(`<feGaussianBlur stdDeviation="${num(len(layer.blur, ctx.canvas))}" edgeMode="duplicate"/>`);
443
+ if (layer.duotone || layer.grayscale) {
444
+ filters.push('<feColorMatrix type="matrix" values=".2126 .7152 .0722 0 0 .2126 .7152 .0722 0 0 .2126 .7152 .0722 0 0 0 0 0 1 0"/>');
445
+ }
446
+ if (layer.duotone) {
447
+ const [lo, hi] = Array.isArray(layer.duotone) ? layer.duotone.map(toHex) : defaultDuotone(p);
448
+ const [a, b] = [lo, hi].map((c) => [1, 3, 5].map((i) => parseInt(c.slice(i, i + 2), 16) / 255));
449
+ filters.push(
450
+ `<feComponentTransfer>${['R', 'G', 'B'].map((ch, i) => `<feFunc${ch} type="table" tableValues="${num(a[i], 4)} ${num(b[i], 4)}"/>`).join('')}</feComponentTransfer>`,
451
+ );
452
+ }
453
+ const defs = filters.length
454
+ ? `<filter${attrs({ id, x: 0, y: 0, width: '100%', height: '100%', 'color-interpolation-filters': 'sRGB' })}>${filters.join('')}</filter>`
455
+ : '';
456
+
457
+ let body = `<image${attrs({ x: box.x, y: box.y, width: box.width, height: box.height, preserveAspectRatio: preserve, filter: defs ? `url(#${id})` : undefined, href: `data:${mime};base64,${Buffer.from(bytes).toString('base64')}` })}/>`;
458
+ if (layer.tint) {
459
+ const t = typeof layer.tint === 'string' ? { color: layer.tint } : layer.tint;
460
+ body += `<rect${attrs({ x: box.x, y: box.y, width: box.width, height: box.height, fill: color(t.color, p.accent), opacity: t.amount ?? 0.35, style: `mix-blend-mode:${t.blend ?? 'multiply'}` })}/>`;
461
+ }
462
+ return { defs, body: wrap(layer, body) };
463
+ }
464
+
465
+ /** Anchor name to sharp's crop `position`. */
466
+ const POSITIONS = /** @type {Record<string, string>} */ ({
467
+ center: 'centre', top: 'top', bottom: 'bottom', left: 'left', right: 'right',
468
+ 'top-left': 'left top', 'top-right': 'right top', 'bottom-left': 'left bottom', 'bottom-right': 'right bottom',
469
+ });
470
+
471
+ /** @param {string} focus @returns {string} preserveAspectRatio alignment. */
472
+ function alignFor(focus) {
473
+ const x = focus.includes('left') ? 'xMin' : focus.includes('right') ? 'xMax' : 'xMid';
474
+ const y = focus.includes('top') ? 'YMin' : focus.includes('bottom') ? 'YMax' : 'YMid';
475
+ return x + y;
476
+ }
477
+
478
+ /** @param {import('./index.js').Palette} p @returns {[string, string]} Shadow and highlight. */
479
+ function defaultDuotone(p) {
480
+ const dark = p.mode === 'dark' ? p.bg : p.text;
481
+ const light = p.mode === 'dark' ? p.text : p.bg;
482
+ return [mixOklab(dark, p.accent, 0.12), mixOklab(p.accent, light, 0.2)];
483
+ }
484
+
485
+ /** @param {string} src @returns {Promise<Uint8Array>} */
486
+ async function readSource(src) {
487
+ const data = src.match(/^data:[^;,]+;base64,(.*)$/s);
488
+ if (data) return Buffer.from(data[1], 'base64');
489
+ if (/^https?:/i.test(src)) throw new TypeError('Image src must be a local file or bytes: covers never fetch from the network');
490
+ return readFile(src);
491
+ }
492
+
493
+ /**
494
+ * Sniff an image's MIME type from its first bytes.
495
+ *
496
+ * @param {Uint8Array} b - Image bytes.
497
+ * @returns {string | undefined} The MIME type.
498
+ */
499
+ export function sniff(b) {
500
+ if (b[0] === 0x89 && b[1] === 0x50) return 'image/png';
501
+ if (b[0] === 0xff && b[1] === 0xd8) return 'image/jpeg';
502
+ if (b[0] === 0x47 && b[1] === 0x49) return 'image/gif';
503
+ const head = Buffer.from(b.subarray(0, 32)).toString('latin1');
504
+ if (head.startsWith('RIFF') && head.slice(8, 12) === 'WEBP') return 'image/webp';
505
+ if (head.slice(4, 12) === 'ftypavif' || head.slice(4, 12) === 'ftypavis') return 'image/avif';
506
+ if (/^\s*(<\?xml|<svg)/i.test(Buffer.from(b.subarray(0, 256)).toString('utf8'))) return 'image/svg+xml';
507
+ return undefined;
508
+ }
509
+
510
+ // ---------------------------------------------------------------------------
511
+ // Texture
512
+ // ---------------------------------------------------------------------------
513
+
514
+ /**
515
+ * `grain` — film grain. In SVG output it's `feTurbulence` (tiny, and
516
+ * browsers render it fast). {@link import('./render.js').renderImage}
517
+ * swaps it for seeded pixel noise composited by sharp, since librsvg's
518
+ * turbulence costs ~200ms at 1200×1200 against ~10ms for the noise.
519
+ *
520
+ * @param {import('./index.js').GrainLayer} layer
521
+ * @param {RenderContext} ctx
522
+ * @returns {Markup}
523
+ */
524
+ export function grain(layer, ctx) {
525
+ const amount = layer.amount ?? 0.08;
526
+ const size = layer.size ?? 1;
527
+ const id = `${ctx.id}n`;
528
+ const seed = ctx.rng.int(1, 9999);
529
+ const gray = layer.monochrome === false ? '' : '<feColorMatrix type="saturate" values="0"/>';
530
+ // Stretch the turbulence's narrow range to the full 0–1 and make it opaque.
531
+ const contrast = '<feComponentTransfer><feFuncR type="linear" slope="2.2" intercept="-0.6"/><feFuncG type="linear" slope="2.2" intercept="-0.6"/><feFuncB type="linear" slope="2.2" intercept="-0.6"/><feFuncA type="linear" slope="0" intercept="1"/></feComponentTransfer>';
532
+ const defs = `<filter${attrs({ id, x: 0, y: 0, width: '100%', height: '100%', filterUnits: 'userSpaceOnUse', 'color-interpolation-filters': 'sRGB' })}><feTurbulence${attrs({ type: 'fractalNoise', baseFrequency: num(0.9 / size, 3), numOctaves: 2, seed, stitchTiles: 'stitch' })}/>${gray}${contrast}</filter>`;
533
+ let mask;
534
+ let maskDefs = '';
535
+ if (layer.vary === 'edges') {
536
+ // Heavier toward the edges and corners, like spray paint.
537
+ const mid = `${ctx.id}nm`;
538
+ maskDefs = `<radialGradient${attrs({ id: `${mid}g`, gradientUnits: 'userSpaceOnUse', cx: ctx.width / 2, cy: ctx.height / 2, r: Math.hypot(ctx.width, ctx.height) / 2 })}><stop offset="0" stop-color="#fff" stop-opacity="${num(VARY_FLOOR, 3)}"/><stop offset="1" stop-color="#fff"/></radialGradient>`
539
+ + `<mask${attrs({ id: mid, maskUnits: 'userSpaceOnUse', x: 0, y: 0, width: ctx.width, height: ctx.height })}><rect${attrs({ width: ctx.width, height: ctx.height, fill: `url(#${mid}g)` })}/></mask>`;
540
+ mask = `url(#${mid})`;
541
+ }
542
+ const body = `<rect${attrs({ width: ctx.width, height: ctx.height, filter: `url(#${id})`, opacity: Math.min(1, amount * (layer.vary === 'edges' ? VARY_PEAK : 1)), mask, style: `mix-blend-mode:${layer.blend ?? 'overlay'}` })}/>`;
543
+ return { defs: defs + maskDefs, body: layer.opacity != null && layer.opacity < 1 ? `<g opacity="${num(layer.opacity)}">${body}</g>` : body };
544
+ }
545
+
546
+ /** `grain.vary: 'edges'`: the centre's share of the edge strength, and the edge's multiple of `amount`. */
547
+ export const VARY_FLOOR = 0.35;
548
+ export const VARY_PEAK = 1.8;
549
+
550
+ /**
551
+ * `pattern` — a line texture: `grid`, `dots`, `lines`, `rings` or `waves`,
552
+ * optionally faded out toward the edges with a mask.
553
+ *
554
+ * Grid lines are drawn as paths across the canvas (not an SVG
555
+ * `<pattern>`, which clips a line on a tile edge to half its width) and
556
+ * centred, so the canvas's middle lands on a line.
557
+ *
558
+ * @param {import('./index.js').PatternLayer} layer
559
+ * @param {RenderContext} ctx
560
+ * @returns {Markup}
561
+ */
562
+ export function pattern(layer, ctx) {
563
+ const { width: w, height: h, palette: p } = ctx;
564
+ const kind = layer.kind ?? 'grid';
565
+ const size = Math.max(2, len(layer.size, ctx.canvas, kind === 'dots' ? '3.2vmin' : kind === 'rings' ? '7vmin' : '8.33vmin'));
566
+ const stroke = len(layer.stroke, ctx.canvas, kind === 'dots' ? '0.22vmin' : '0.1vmin');
567
+ const col = color(layer.color, p.text);
568
+ const dash = layer.dash === 'dotted' ? `0 ${num(stroke * 4)}` : layer.dash === 'dashed' || layer.dash === true ? `${num(stroke * 4)} ${num(stroke * 5)}`
569
+ : Array.isArray(layer.dash) ? layer.dash.map((d) => num(len(d, ctx.canvas))).join(' ') : undefined;
570
+ const dashAttrs = dash ? { 'stroke-dasharray': dash, 'stroke-linecap': layer.dash === 'dotted' ? 'round' : undefined } : {};
571
+ const cx = (layer.center?.x ?? 0.5) * w;
572
+ const cy = (layer.center?.y ?? 0.5) * h;
573
+ let shapes = '';
574
+ let defs = '';
575
+
576
+ if (kind === 'grid' || kind === 'lines') {
577
+ const angle = kind === 'lines' ? layer.angle ?? 0 : 0;
578
+ const d = [];
579
+ if (angle === 0) {
580
+ // Rows and columns: every `size` from the centre, or `divisions` equal
581
+ // cells (inner lines only); broken wherever they cross a `gaps` region.
582
+ const n = layer.divisions;
583
+ const ys = n ? Array.from({ length: n - 1 }, (_, k) => ((k + 1) * h) / n) : range(cy % size, h, size);
584
+ const xs = kind !== 'grid' ? [] : n ? Array.from({ length: n - 1 }, (_, k) => ((k + 1) * w) / n) : range(cx % size, w, size);
585
+ const gaps = (layer.gaps ?? []).map((g) => regionPx(g, ctx.canvas));
586
+ d.push(gridPath(xs, ys, w, h, gaps));
587
+ shapes = `<path${attrs({ d: d.join(''), fill: 'none', stroke: col, 'stroke-width': stroke, ...dashAttrs })}/>`;
588
+ } else {
589
+ const reach = Math.hypot(w, h) / 2;
590
+ for (let y = -Math.ceil(reach / size) * size; y <= reach; y += size) d.push(`M${num(-reach)} ${num(y)}H${num(reach)}`);
591
+ shapes = `<path${attrs({ d: d.join(''), fill: 'none', stroke: col, 'stroke-width': stroke, ...dashAttrs, transform: `translate(${num(cx)} ${num(cy)}) rotate(${num(angle)})` })}/>`;
592
+ }
593
+ } else if (kind === 'dots') {
594
+ const id = `${ctx.id}p`;
595
+ defs += `<pattern${attrs({ id, patternUnits: 'userSpaceOnUse', x: cx % size - size / 2, y: cy % size - size / 2, width: size, height: size })}><circle${attrs({ cx: size / 2, cy: size / 2, r: stroke, fill: col })}/></pattern>`;
596
+ shapes = `<rect${attrs({ width: w, height: h, fill: `url(#${id})` })}/>`;
597
+ } else if (kind === 'rings') {
598
+ const reach = Math.hypot(Math.max(cx, w - cx), Math.max(cy, h - cy));
599
+ for (let r = size; r <= reach; r += size) shapes += `<circle${attrs({ cx, cy, r })}/>`;
600
+ shapes = `<g${attrs({ fill: 'none', stroke: col, 'stroke-width': stroke, ...dashAttrs })}>${shapes}</g>`;
601
+ } else if (kind === 'waves') {
602
+ const wavelength = len(layer.wavelength, ctx.canvas, size * 3.2);
603
+ const amp = len(layer.amplitude, ctx.canvas, size * 0.22);
604
+ const phase = ctx.rng.range(0, Math.PI * 2);
605
+ const step = wavelength / 24;
606
+ const d = [];
607
+ for (let y = cy % size; y <= h + amp; y += size) {
608
+ const shift = phase + y * 0.004;
609
+ let line = '';
610
+ for (let x = 0; x <= w + step; x += step) {
611
+ line += `${x === 0 ? 'M' : 'L'}${num(x)} ${num(y + Math.sin((x / wavelength) * Math.PI * 2 + shift) * amp)}`;
612
+ }
613
+ d.push(line);
614
+ }
615
+ shapes = `<path${attrs({ d: d.join(''), fill: 'none', stroke: col, 'stroke-width': stroke, 'stroke-linecap': 'round', ...dashAttrs })}/>`;
616
+ } else {
617
+ throw new TypeError(`Unknown pattern kind "${kind}" (grid, dots, lines, rings, waves)`);
618
+ }
619
+
620
+ const fade = fadeMask(layer.fade ?? 'none', ctx, cx, cy);
621
+ defs += fade.defs;
622
+ let body = `<g${attrs({ opacity: layer.opacity ?? 0.14, mask: fade.ref })}>${shapes}</g>`;
623
+ if (layer.region) {
624
+ const r = regionPx(layer.region, ctx.canvas);
625
+ defs += `<clipPath id="${ctx.id}r"><rect${attrs(r)}/></clipPath>`;
626
+ body = `<g clip-path="url(#${ctx.id}r)">${body}</g>`;
627
+ }
628
+ return { defs, body: layer.blend ? `<g style="mix-blend-mode:${esc(layer.blend)}">${body}</g>` : body };
629
+ }
630
+
631
+ /**
632
+ * `[from, from + step, …]` up to `to`.
633
+ *
634
+ * @param {number} from @param {number} to @param {number} step
635
+ * @returns {number[]}
636
+ */
637
+ function range(from, to, step) {
638
+ const out = [];
639
+ for (let v = from; v <= to; v += step) out.push(v);
640
+ return out;
641
+ }
642
+
643
+ /**
644
+ * A luminance mask that fades a layer: `'radial'` (strong in the middle),
645
+ * `'edges'` (a softer vignette), or toward a side (`'top'` fades out toward
646
+ * the top, etc.).
647
+ *
648
+ * @param {string} fade - The fade.
649
+ * @param {RenderContext} ctx
650
+ * @param {number} cx - Centre x for radial fades.
651
+ * @param {number} cy - Centre y for radial fades.
652
+ * @returns {{ defs: string, ref: string | undefined }} Mask defs and its `url()`.
653
+ */
654
+ function fadeMask(fade, ctx, cx, cy) {
655
+ if (!fade || fade === 'none') return { defs: '', ref: undefined };
656
+ const { width: w, height: h } = ctx;
657
+ const id = `${ctx.id}m`;
658
+ const gid = `${ctx.id}mg`;
659
+ let grad;
660
+ if (fade === 'radial' || fade === 'edges') {
661
+ const r = fade === 'radial' ? Math.max(w, h) * 0.62 : Math.hypot(w, h) * 0.6;
662
+ const inner = fade === 'radial' ? 0.05 : 0.45;
663
+ grad = `<radialGradient${attrs({ id: gid, gradientUnits: 'userSpaceOnUse', cx, cy, r })}><stop offset="${inner}" stop-color="#fff"/><stop offset="0.55" stop-color="#fff" stop-opacity="0.6"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></radialGradient>`;
664
+ } else {
665
+ const to = { top: [0, 1, 0, 0], bottom: [0, 0, 0, 1], left: [1, 0, 0, 0], right: [0, 0, 1, 0] }[fade];
666
+ if (!to) throw new TypeError(`Unknown fade "${fade}" (none, radial, edges, top, bottom, left, right)`);
667
+ grad = `<linearGradient${attrs({ id: gid, x1: to[0], y1: to[1], x2: to[2], y2: to[3] })}><stop offset="0" stop-color="#fff"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>`;
668
+ }
669
+ return {
670
+ defs: `${grad}<mask${attrs({ id, maskUnits: 'userSpaceOnUse', x: 0, y: 0, width: w, height: h })}><rect${attrs({ width: w, height: h, fill: `url(#${gid})` })}/></mask>`,
671
+ ref: `url(#${id})`,
672
+ };
673
+ }
674
+
675
+ // ---------------------------------------------------------------------------
676
+ // Objects
677
+ // ---------------------------------------------------------------------------
678
+
679
+ /**
680
+ * `shapes` — circles, squares and pills, scattered (without overlapping
681
+ * where they can help it), in a row, or placed one by one with `items`.
682
+ *
683
+ * @param {import('./index.js').ShapesLayer} layer
684
+ * @param {RenderContext} ctx
685
+ * @returns {Markup}
686
+ */
687
+ export function shapes(layer, ctx) {
688
+ const { rng, palette: p } = ctx;
689
+ const r = regionPx(layer.region, ctx.canvas);
690
+ const colors = colorList(layer.colors, p.colors);
691
+ const [smin, smax] = (layer.size ?? ['7vmin', '20vmin']).map((v) => len(v, ctx.canvas));
692
+ const kinds = layer.kind === 'mixed' || !layer.kind ? (layer.kind === 'mixed' ? ['circle', 'square', 'pill'] : ['circle']) : [layer.kind];
693
+ const outline = layer.outline ? len(layer.outline === true ? '0.35vmin' : layer.outline, ctx.canvas) : 0;
694
+
695
+ /** @type {{ kind: string, x: number, y: number, size: number, color: string, rotate: number, opacity: number }[]} */
696
+ let items;
697
+ if (layer.items?.length) {
698
+ items = layer.items.map((it, i) => ({
699
+ kind: it.kind ?? kinds[i % kinds.length],
700
+ x: r.x + (it.x ?? 0.5) * r.width,
701
+ y: r.y + (it.y ?? 0.5) * r.height,
702
+ size: len(it.size, ctx.canvas, smax),
703
+ color: it.color ? toHex(it.color) : colors[i % colors.length],
704
+ rotate: it.rotate ?? 0,
705
+ opacity: it.opacity ?? 1,
706
+ }));
707
+ } else {
708
+ const count = layer.count ?? 6;
709
+ const placement = layer.placement ?? 'scatter';
710
+ items = [];
711
+ for (let i = 0; i < count; i++) {
712
+ const size = placement === 'scatter' ? rng.range(smin, smax) : smax;
713
+ let x = r.x + r.width / 2;
714
+ let y = r.y + r.height / 2;
715
+ if (placement === 'row') {
716
+ x = r.x + ((i + 0.5) / count) * r.width;
717
+ } else if (placement === 'column') {
718
+ y = r.y + ((i + 0.5) / count) * r.height;
719
+ } else {
720
+ // Best of a few candidates: the one furthest from everything placed.
721
+ let best = -Infinity;
722
+ for (let t = 0; t < 24; t++) {
723
+ const cxp = r.x + size / 2 + rng.next() * Math.max(0, r.width - size);
724
+ const cyp = r.y + size / 2 + rng.next() * Math.max(0, r.height - size);
725
+ const gap = items.reduce((m, o) => Math.min(m, Math.hypot(o.x - cxp, o.y - cyp) - (o.size + size) / 2), Infinity);
726
+ if (gap > best) { best = gap; x = cxp; y = cyp; }
727
+ }
728
+ }
729
+ const kind = kinds[placement === 'scatter' ? rng.int(0, kinds.length - 1) : i % kinds.length];
730
+ items.push({
731
+ kind,
732
+ x,
733
+ y,
734
+ size,
735
+ color: colors[i % colors.length],
736
+ rotate: layer.rotate === false || kind === 'circle' ? 0 : placement === 'scatter' ? rng.range(-35, 35) : 0,
737
+ opacity: 1,
738
+ });
739
+ }
740
+ }
741
+
742
+ const radius = layer.radius ?? 0.22;
743
+ const body = items
744
+ .map((it) => {
745
+ const paint = outline ? { fill: 'none', stroke: it.color, 'stroke-width': outline } : { fill: it.color };
746
+ const op = it.opacity < 1 ? it.opacity : undefined;
747
+ if (it.kind === 'circle') return `<circle${attrs({ cx: it.x, cy: it.y, r: it.size / 2, ...paint, opacity: op })}/>`;
748
+ const wd = it.kind === 'pill' ? it.size * 2.2 : it.size;
749
+ const ht = it.size;
750
+ const rx = it.kind === 'pill' ? ht / 2 : ht * radius;
751
+ return `<rect${attrs({ x: it.x - wd / 2, y: it.y - ht / 2, width: wd, height: ht, rx, ...paint, opacity: op, transform: it.rotate ? `rotate(${num(it.rotate)} ${num(it.x)} ${num(it.y)})` : undefined })}/>`;
752
+ })
753
+ .join('');
754
+ return { defs: '', body: wrap(layer, body) };
755
+ }
756
+
757
+ /**
758
+ * `icon` — an Iconify icon by name (`'lucide:feather'`), a raw SVG string or
759
+ * a path, optionally on a rounded tile with a soft shadow.
760
+ *
761
+ * @param {import('./index.js').IconLayer} layer
762
+ * @param {RenderContext} ctx
763
+ * @returns {Markup}
764
+ */
765
+ export function icon(layer, ctx) {
766
+ const p = ctx.palette;
767
+ // A name that is markup is a raw SVG (so one `icon` option can carry either).
768
+ const name = typeof layer.name === 'string' ? layer.name.trim() : undefined;
769
+ const svg = layer.svg ?? (name?.startsWith('<') ? name : undefined);
770
+ const data = svg
771
+ ? parseSvgIcon(svg)
772
+ : name
773
+ ? resolveIcon(name)
774
+ : layer.path
775
+ ? { body: `<path fill="currentColor" d="${esc(layer.path)}"/>`, viewBox: /** @type {[number, number, number, number]} */ (layer.viewBox ?? [0, 0, 24, 24]) }
776
+ : null;
777
+ if (!data) throw new TypeError('An icon layer needs a name, svg or path');
778
+
779
+ const tileOpts = layer.tile === true ? {} : layer.tile || null;
780
+ const size = len(layer.size, ctx.canvas, tileOpts ? '15vmin' : '24vmin');
781
+ const tileSize = tileOpts ? len(tileOpts.size, ctx.canvas, size / 0.5) : size;
782
+ const margin = len(layer.margin, ctx.canvas, unit(ctx.canvas) * 0.07);
783
+ const at = place({ width: tileSize, height: tileSize, canvas: ctx.canvas, anchor: layer.anchor ?? 'center', margin, position: layer.position, offset: layer.offset });
784
+
785
+ let defs = '';
786
+ let body = '';
787
+ if (tileOpts) {
788
+ const radius = len(tileOpts.radius, ctx.canvas, tileSize * 0.24);
789
+ const fill = color(tileOpts.color, p.surface);
790
+ const shadow = tileOpts.shadow ?? 'soft';
791
+ const fid = `${ctx.id}s`;
792
+ if (shadow === 'soft') {
793
+ const strength = p.mode === 'dark' ? 2.2 : 1;
794
+ defs += `<filter${attrs({ id: fid, x: '-60%', y: '-60%', width: '220%', height: '220%', 'color-interpolation-filters': 'sRGB' })}>`
795
+ + shadowPass('a', tileSize * 0.12, tileSize * 0.08, 0.12 * strength)
796
+ + shadowPass('b', tileSize * 0.015, tileSize * 0.012, 0.08 * strength)
797
+ + '<feMerge><feMergeNode in="a"/><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter>';
798
+ }
799
+ const border = tileOpts.border === false ? null : tileOpts.border ?? (p.mode === 'dark' ? mixOklab(fill, p.text, 0.12) : mixOklab(fill, p.text, 0.08));
800
+ body += `<rect${attrs({ x: at.x, y: at.y, width: tileSize, height: tileSize, rx: radius, fill, filter: shadow === 'soft' ? `url(#${fid})` : undefined })}/>`;
801
+ if (border) body += `<rect${attrs({ x: at.x + 0.5, y: at.y + 0.5, width: tileSize - 1, height: tileSize - 1, rx: Math.max(0, radius - 0.5), fill: 'none', stroke: toHex(border), 'stroke-width': 1 })}/>`;
802
+ }
803
+
804
+ const [vx, vy, vw, vh] = data.viewBox;
805
+ const fitScale = Math.min(size / vw, size / vh);
806
+ const iw = vw * fitScale;
807
+ const ih = vh * fitScale;
808
+ let inner = data.body;
809
+ if (layer.strokeWidth != null) inner = inner.replace(/stroke-width="[^"]*"/g, `stroke-width="${num(layer.strokeWidth)}"`);
810
+ body += `<svg${attrs({
811
+ x: at.x + (tileSize - iw) / 2,
812
+ y: at.y + (tileSize - ih) / 2,
813
+ width: iw,
814
+ height: ih,
815
+ viewBox: `${num(vx)} ${num(vy)} ${num(vw)} ${num(vh)}`,
816
+ overflow: 'visible',
817
+ color: color(layer.color, tileOpts ? p.accent : p.text),
818
+ })}>${inner}</svg>`;
819
+ return { defs, body: wrap(layer, body) };
820
+ }
821
+
822
+ /**
823
+ * One drop-shadow pass for a filter (blurred alpha, offset down, tinted).
824
+ *
825
+ * @param {string} name - Result name.
826
+ * @param {number} blur - Blur std deviation.
827
+ * @param {number} dy - Downward offset.
828
+ * @param {number} opacity - Shadow opacity.
829
+ * @returns {string} Filter primitives.
830
+ */
831
+ function shadowPass(name, blur, dy, opacity) {
832
+ return `<feGaussianBlur in="SourceAlpha" stdDeviation="${num(blur)}"/><feOffset dy="${num(dy)}" result="${name}o"/>`
833
+ + `<feFlood flood-color="#000" flood-opacity="${num(Math.min(1, opacity), 3)}"/><feComposite in2="${name}o" operator="in" result="${name}"/>`;
834
+ }
835
+
836
+ /**
837
+ * `text` — type set as outlines: wrapped, balanced, truncated with an
838
+ * ellipsis past `maxLines`, optionally shrunk to fit (`minSize`), with an
839
+ * optional label above and a pill or box behind.
840
+ *
841
+ * @param {import('./index.js').TextLayer} layer
842
+ * @param {RenderContext} ctx
843
+ * @returns {Promise<Markup>}
844
+ */
845
+ export async function text(layer, ctx) {
846
+ // An override object in `content` (a recipe's "{title}") means its content.
847
+ const raw = layer.content && typeof layer.content === 'object' ? /** @type {any} */ (layer.content).content : layer.content;
848
+ const content = transform(String(raw ?? ''), layer.transform);
849
+ if (!content.trim()) return { defs: '', body: '' };
850
+ const hb = await harfbuzz();
851
+ const p = ctx.palette;
852
+ const u = unit(ctx.canvas);
853
+ const margin = len(layer.margin, ctx.canvas, u * 0.07);
854
+ const anchor = layer.anchor ?? 'bottom-left';
855
+ const align = layer.align ?? anchorAlign(anchor);
856
+ const bg = layer.background ? (typeof layer.background === 'string' ? { color: layer.background } : layer.background) : null;
857
+ const pad = bg ? padding(bg.padding, ctx.canvas, len(layer.size, ctx.canvas, u * 0.06)) : [0, 0];
858
+ const maxWidth = len(layer.maxWidth, ctx.canvas, ctx.width - 2 * margin) - 2 * pad[1];
859
+
860
+ const face = await loadFont(pickFont(ctx.fonts, layer.font ?? 'Inter', layer.weight ?? 600, layer.style));
861
+ const set = layout({
862
+ face, hb,
863
+ text: content,
864
+ size: len(layer.size, ctx.canvas, u * 0.06),
865
+ minSize: layer.minSize != null ? len(layer.minSize, ctx.canvas) : undefined,
866
+ letterSpacing: layer.letterSpacing ?? -0.02,
867
+ maxWidth,
868
+ maxLines: layer.maxLines ?? 3,
869
+ ellipsis: layer.ellipsis,
870
+ balance: layer.balance ?? true,
871
+ });
872
+ const lh = set.size * (layer.lineHeight ?? 1.12);
873
+ const cap = (face.capHeight / face.upem) * set.size;
874
+ const titleH = cap + (set.lines.length - 1) * lh;
875
+
876
+ // The label sits above, in its own face and size.
877
+ let labelOpts = layer.label ? (typeof layer.label === 'string' ? { content: layer.label } : layer.label) : null;
878
+ // A label whose content is itself an options object: its fields win.
879
+ if (labelOpts && labelOpts.content && typeof labelOpts.content === 'object') {
880
+ labelOpts = { ...labelOpts, ...labelOpts.content };
881
+ if (typeof labelOpts.content === 'object') labelOpts.content = undefined;
882
+ }
883
+ let label = null;
884
+ if (labelOpts?.content) {
885
+ const lface = await loadFont(pickFont(ctx.fonts, labelOpts.font ?? layer.font ?? 'Inter', labelOpts.weight ?? 500, labelOpts.style));
886
+ const lsize = len(labelOpts.size, ctx.canvas, Math.max(12, set.size * 0.32, u * 0.02));
887
+ const lset = layout({
888
+ face: lface, hb,
889
+ text: transform(labelOpts.content, labelOpts.transform ?? 'uppercase'),
890
+ size: lsize,
891
+ letterSpacing: labelOpts.letterSpacing ?? 0.08,
892
+ maxWidth,
893
+ maxLines: labelOpts.maxLines ?? 1,
894
+ });
895
+ const llh = lsize * (labelOpts.lineHeight ?? 1.3);
896
+ const lcap = (lface.capHeight / lface.upem) * lsize;
897
+ label = { face: lface, set: lset, lh: llh, cap: lcap, height: lcap + (lset.lines.length - 1) * llh, gap: len(labelOpts.gap, ctx.canvas, Math.max(lsize * 1.4, set.size * 0.42)), color: color(labelOpts.color, p.muted) };
898
+ }
899
+
900
+ const blockW = Math.max(set.width, label?.set.width ?? 0);
901
+ const blockH = titleH + (label ? label.height + label.gap : 0);
902
+ const boxW = blockW + 2 * pad[1];
903
+ const boxH = blockH + 2 * pad[0];
904
+ const at = place({ width: boxW, height: boxH, canvas: ctx.canvas, anchor, margin, position: layer.position, offset: layer.offset });
905
+ const left = at.x + pad[1];
906
+ const top = at.y + pad[0];
907
+
908
+ /** @param {number} w @returns {number} */
909
+ const lineX = (w) => (align === 'center' ? left + (blockW - w) / 2 : align === 'right' ? left + blockW - w : left);
910
+
911
+ let body = '';
912
+ if (bg) {
913
+ const r = bg.radius != null ? len(bg.radius, ctx.canvas) : Math.min(boxH, boxW) / 2;
914
+ body += `<rect${attrs({ x: at.x, y: at.y, width: boxW, height: boxH, rx: r, fill: color(bg.color, p.surface), opacity: bg.opacity })}/>`;
915
+ }
916
+ let y = top;
917
+ if (label) {
918
+ const d = label.set.lines.map((l, i) => runPath(label.face, l.run, label.set.size, lineX(l.run.width), y + label.cap + i * label.lh)).join('');
919
+ body += `<path${attrs({ d, fill: label.color })}/>`;
920
+ y += label.height + label.gap;
921
+ }
922
+ const d = set.lines.map((l, i) => runPath(face, l.run, set.size, lineX(l.run.width), y + cap + i * lh)).join('');
923
+ body += `<path${attrs({ d, fill: color(layer.color, p.text) })}/>`;
924
+ return { defs: '', body: wrap(layer, body) };
925
+ }
926
+
927
+ /** @param {string} s @param {string | undefined} t @returns {string} */
928
+ function transform(s, t) {
929
+ const clean = s.replace(/[\t\r ]+/g, ' ').replace(/ *\n */g, '\n').trim();
930
+ return t === 'uppercase' ? clean.toUpperCase() : t === 'lowercase' ? clean.toLowerCase() : clean;
931
+ }
932
+
933
+ /**
934
+ * Padding as `[vertical, horizontal]` pixels.
935
+ *
936
+ * @param {import('./index.js').Length | [import('./index.js').Length, import('./index.js').Length] | undefined} v
937
+ * @param {{ width: number, height: number }} canvas
938
+ * @param {number} size - The text size, for the default.
939
+ * @returns {[number, number]}
940
+ */
941
+ function padding(v, canvas, size) {
942
+ if (Array.isArray(v)) return [len(v[0], canvas), len(v[1], canvas)];
943
+ if (v != null) return [len(v, canvas), len(v, canvas)];
944
+ return [size * 0.5, size * 0.75];
945
+ }
946
+
947
+ /**
948
+ * `frame` — an inset border (and optional fill), like a mount or a card.
949
+ *
950
+ * @param {import('./index.js').FrameLayer} layer
951
+ * @param {RenderContext} ctx
952
+ * @returns {Markup}
953
+ */
954
+ export function frame(layer, ctx) {
955
+ const inset = len(layer.inset, ctx.canvas, '3.5vmin');
956
+ const stroke = len(layer.stroke, ctx.canvas, '0.15vmin');
957
+ const half = layer.fill ? 0 : stroke / 2;
958
+ const body = `<rect${attrs({
959
+ x: inset + half,
960
+ y: inset + half,
961
+ width: Math.max(0, ctx.width - 2 * (inset + half)),
962
+ height: Math.max(0, ctx.height - 2 * (inset + half)),
963
+ rx: len(layer.radius, ctx.canvas, '2vmin'),
964
+ fill: layer.fill ? toHex(layer.fill) : 'none',
965
+ stroke: stroke > 0 ? color(layer.color, ctx.palette.text) : undefined,
966
+ 'stroke-width': stroke > 0 ? stroke : undefined,
967
+ })}/>`;
968
+ return { defs: '', body: wrap({ ...layer, opacity: layer.opacity ?? (layer.fill ? 1 : 0.22) }, body) };
969
+ }
970
+
971
+ /** Every layer type, by name. */
972
+ export const LAYERS = Object.freeze({ solid, linear, radial, mesh, stripes, image, grain, pattern, shapes, icon, text, frame, diagram, paper, scribble, ink, dither, contour, waveform, tiles, rule });