@andamento/svg 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matt Putnam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @andamento/svg
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Draws [`@andamento/core`](https://www.npmjs.com/package/@andamento/core) tiling layouts as
4
+ an SVG string or element, on a canvas, or as a PNG. Images, fills, rounded corners, raised
5
+ tiles and one picture across all the tiles are all supported.
6
+
7
+ **[Manual](https://mattputnam.github.io/andamento/) · [SVG, canvas and PNG](https://mattputnam.github.io/andamento/frameworks/svg-canvas) · [Examples](https://mattputnam.github.io/andamento/examples/) · [API](https://mattputnam.github.io/andamento/reference/)**
8
+
9
+ ```bash
10
+ npm install @andamento/core @andamento/svg
11
+ ```
12
+
13
+ ```ts
14
+ import { createLayout, herringbone } from "@andamento/core";
15
+ import { renderToString, renderToPng } from "@andamento/svg";
16
+
17
+ const layout = createLayout({ region: { x: 0, y: 0, width: 240, height: 150 }, tiling: herringbone({ length: 60, width: 20 }), gap: 2 });
18
+ const svg = renderToString(layout, { fill: ["#e9c46a", "#f4a261", "#e76f51"], background: "#264653" });
19
+ const png = await renderToPng(layout, { images: photoUrls, width: 1200, relief: true });
20
+ ```
21
+
22
+ MIT licensed.
@@ -0,0 +1,36 @@
1
+ // src/styles.ts
2
+ import { contentSlots, matchSlots, paletteFill } from "@andamento/core";
3
+ var defaultPalette = ["#e9d8a6", "#94d2bd", "#ee9b00", "#0a9396", "#ca6702", "#bb3e03", "#ae2012", "#005f73"];
4
+ function resolveFills(layout, fill) {
5
+ if (typeof fill === "string") return layout.cells.map(() => fill);
6
+ const f = typeof fill === "function" ? fill : paletteFill(fill.length ? fill : defaultPalette);
7
+ return layout.cells.map((c) => f(c, layout));
8
+ }
9
+ function resolveCellStyles(layout, opts = {}) {
10
+ const fills = resolveFills(layout, opts.fill ?? defaultPalette);
11
+ const images = opts.images;
12
+ let slots = layout.cells.map(() => -1);
13
+ if (Array.isArray(images) && images.length > 0) {
14
+ const count = opts.repeatImages ? Infinity : images.length;
15
+ const content = { cells: opts.contentCells, placement: opts.placement, choose: opts.choose };
16
+ slots = opts.imageAspects && !opts.repeatImages ? matchSlots(layout, images.map((_, i) => opts.imageAspects[i] ?? 1), content) : contentSlots(layout, count, content);
17
+ }
18
+ return layout.cells.map((c, i) => {
19
+ if (typeof images === "function") return { fill: fills[i], image: images(c), slot: -1 };
20
+ const slot = images && images.length > 0 && slots[i] >= 0 ? slots[i] % images.length : -1;
21
+ return { fill: fills[i], image: slot >= 0 ? images[slot] : void 0, slot };
22
+ });
23
+ }
24
+ function cellA11y(style, alts) {
25
+ if (!alts?.length) return {};
26
+ const alt = style.image && style.slot >= 0 ? alts[style.slot] : void 0;
27
+ return alt ? { role: "img", "aria-label": alt } : { "aria-hidden": "true" };
28
+ }
29
+
30
+ export {
31
+ defaultPalette,
32
+ resolveFills,
33
+ resolveCellStyles,
34
+ cellA11y
35
+ };
36
+ //# sourceMappingURL=chunk-GCRUDQEZ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/styles.ts"],"sourcesContent":["import { contentSlots, matchSlots, paletteFill, type CellFill, type Layout } from \"@andamento/core\";\nimport type { RenderOptions } from \"./index\";\n\nexport const defaultPalette = [\"#e9d8a6\", \"#94d2bd\", \"#ee9b00\", \"#0a9396\", \"#ca6702\", \"#bb3e03\", \"#ae2012\", \"#005f73\"];\n\n/** A color, a palette (neighboring cells get different entries), or a color per cell. */\nexport type FillSource = string | readonly string[] | CellFill;\n\nexport interface CellStyle {\n fill: string;\n image?: string;\n /** Which item of `images` the cell shows (-1 if none or if `images` is a function). */\n slot: number;\n}\n\n/**\n * Fill color per cell (by `cell.index`): a color, a palette (neighboring cells get\n * different entries), or a function.\n */\nexport function resolveFills(layout: Layout, fill: FillSource): string[] {\n if (typeof fill === \"string\") return layout.cells.map(() => fill);\n const f = typeof fill === \"function\" ? fill : paletteFill(fill.length ? fill : defaultPalette);\n return layout.cells.map((c) => f(c, layout));\n}\n\ntype StyleOptions = Pick<RenderOptions, \"images\" | \"repeatImages\" | \"fill\" | \"contentCells\" | \"placement\" | \"imageAspects\" | \"choose\">;\n\n/** Resolve the fill color and image for every cell (shared by the SVG and React renderers). */\nexport function resolveCellStyles(layout: Layout, opts: StyleOptions = {}): CellStyle[] {\n const fills = resolveFills(layout, opts.fill ?? defaultPalette);\n const images = opts.images;\n let slots: number[] = layout.cells.map(() => -1);\n if (Array.isArray(images) && images.length > 0) {\n const count = opts.repeatImages ? Infinity : images.length;\n const content = { cells: opts.contentCells, placement: opts.placement, choose: opts.choose };\n slots =\n opts.imageAspects && !opts.repeatImages\n ? matchSlots(layout, images.map((_, i) => opts.imageAspects![i] ?? 1), content)\n : contentSlots(layout, count, content);\n }\n return layout.cells.map((c, i) => {\n if (typeof images === \"function\") return { fill: fills[i]!, image: images(c), slot: -1 };\n // With repeatImages, slots run past the images: the image shown is the slot wrapped round.\n const slot = images && images.length > 0 && slots[i]! >= 0 ? slots[i]! % images.length : -1;\n return { fill: fills[i]!, image: slot >= 0 ? images![slot] : undefined, slot };\n });\n}\n\n/** With `imageAlts`: a cell showing a described image is an image; the rest is decoration. */\nexport function cellA11y(style: CellStyle, alts: readonly string[] | undefined): { role?: \"img\"; \"aria-label\"?: string; \"aria-hidden\"?: \"true\" } {\n if (!alts?.length) return {};\n const alt = style.image && style.slot >= 0 ? alts[style.slot] : undefined;\n return alt ? { role: \"img\", \"aria-label\": alt } : { \"aria-hidden\": \"true\" };\n}\n"],"mappings":";AAAA,SAAS,cAAc,YAAY,mBAA+C;AAG3E,IAAM,iBAAiB,CAAC,WAAW,WAAW,WAAW,WAAW,WAAW,WAAW,WAAW,SAAS;AAgB9G,SAAS,aAAa,QAAgB,MAA4B;AACvE,MAAI,OAAO,SAAS,SAAU,QAAO,OAAO,MAAM,IAAI,MAAM,IAAI;AAChE,QAAM,IAAI,OAAO,SAAS,aAAa,OAAO,YAAY,KAAK,SAAS,OAAO,cAAc;AAC7F,SAAO,OAAO,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,MAAM,CAAC;AAC7C;AAKO,SAAS,kBAAkB,QAAgB,OAAqB,CAAC,GAAgB;AACtF,QAAM,QAAQ,aAAa,QAAQ,KAAK,QAAQ,cAAc;AAC9D,QAAM,SAAS,KAAK;AACpB,MAAI,QAAkB,OAAO,MAAM,IAAI,MAAM,EAAE;AAC/C,MAAI,MAAM,QAAQ,MAAM,KAAK,OAAO,SAAS,GAAG;AAC9C,UAAM,QAAQ,KAAK,eAAe,WAAW,OAAO;AACpD,UAAM,UAAU,EAAE,OAAO,KAAK,cAAc,WAAW,KAAK,WAAW,QAAQ,KAAK,OAAO;AAC3F,YACE,KAAK,gBAAgB,CAAC,KAAK,eACvB,WAAW,QAAQ,OAAO,IAAI,CAAC,GAAG,MAAM,KAAK,aAAc,CAAC,KAAK,CAAC,GAAG,OAAO,IAC5E,aAAa,QAAQ,OAAO,OAAO;AAAA,EAC3C;AACA,SAAO,OAAO,MAAM,IAAI,CAAC,GAAG,MAAM;AAChC,QAAI,OAAO,WAAW,WAAY,QAAO,EAAE,MAAM,MAAM,CAAC,GAAI,OAAO,OAAO,CAAC,GAAG,MAAM,GAAG;AAEvF,UAAM,OAAO,UAAU,OAAO,SAAS,KAAK,MAAM,CAAC,KAAM,IAAI,MAAM,CAAC,IAAK,OAAO,SAAS;AACzF,WAAO,EAAE,MAAM,MAAM,CAAC,GAAI,OAAO,QAAQ,IAAI,OAAQ,IAAI,IAAI,QAAW,KAAK;AAAA,EAC/E,CAAC;AACH;AAGO,SAAS,SAAS,OAAkB,MAAsG;AAC/I,MAAI,CAAC,MAAM,OAAQ,QAAO,CAAC;AAC3B,QAAM,MAAM,MAAM,SAAS,MAAM,QAAQ,IAAI,KAAK,MAAM,IAAI,IAAI;AAChE,SAAO,MAAM,EAAE,MAAM,OAAO,cAAc,IAAI,IAAI,EAAE,eAAe,OAAO;AAC5E;","names":[]}
@@ -0,0 +1,36 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/styles.ts
2
+ var _core = require('@andamento/core');
3
+ var defaultPalette = ["#e9d8a6", "#94d2bd", "#ee9b00", "#0a9396", "#ca6702", "#bb3e03", "#ae2012", "#005f73"];
4
+ function resolveFills(layout, fill) {
5
+ if (typeof fill === "string") return layout.cells.map(() => fill);
6
+ const f = typeof fill === "function" ? fill : _core.paletteFill.call(void 0, fill.length ? fill : defaultPalette);
7
+ return layout.cells.map((c) => f(c, layout));
8
+ }
9
+ function resolveCellStyles(layout, opts = {}) {
10
+ const fills = resolveFills(layout, _nullishCoalesce(opts.fill, () => ( defaultPalette)));
11
+ const images = opts.images;
12
+ let slots = layout.cells.map(() => -1);
13
+ if (Array.isArray(images) && images.length > 0) {
14
+ const count = opts.repeatImages ? Infinity : images.length;
15
+ const content = { cells: opts.contentCells, placement: opts.placement, choose: opts.choose };
16
+ slots = opts.imageAspects && !opts.repeatImages ? _core.matchSlots.call(void 0, layout, images.map((_, i) => _nullishCoalesce(opts.imageAspects[i], () => ( 1))), content) : _core.contentSlots.call(void 0, layout, count, content);
17
+ }
18
+ return layout.cells.map((c, i) => {
19
+ if (typeof images === "function") return { fill: fills[i], image: images(c), slot: -1 };
20
+ const slot = images && images.length > 0 && slots[i] >= 0 ? slots[i] % images.length : -1;
21
+ return { fill: fills[i], image: slot >= 0 ? images[slot] : void 0, slot };
22
+ });
23
+ }
24
+ function cellA11y(style, alts) {
25
+ if (!_optionalChain([alts, 'optionalAccess', _2 => _2.length])) return {};
26
+ const alt = style.image && style.slot >= 0 ? alts[style.slot] : void 0;
27
+ return alt ? { role: "img", "aria-label": alt } : { "aria-hidden": "true" };
28
+ }
29
+
30
+
31
+
32
+
33
+
34
+
35
+ exports.defaultPalette = defaultPalette; exports.resolveFills = resolveFills; exports.resolveCellStyles = resolveCellStyles; exports.cellA11y = cellA11y;
36
+ //# sourceMappingURL=chunk-JSRCX7PI.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/matthewputnam/code/andamento/packages/svg/dist/chunk-JSRCX7PI.cjs","../src/styles.ts"],"names":[],"mappings":"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AA;AAChE,EAAA,OAAO,IAAA,EAAM,EAAE,IAAA,EAAM,KAAA,EAAO,YAAA,EAAc,IAAI,EAAA,EAAI,EAAE,aAAA,EAAe,OAAO,CAAA;AAC5E;ADzBA;AACA;AACE;AACA;AACA;AACA;AACF,yJAAC","file":"/Users/matthewputnam/code/andamento/packages/svg/dist/chunk-JSRCX7PI.cjs","sourcesContent":[null,"import { contentSlots, matchSlots, paletteFill, type CellFill, type Layout } from \"@andamento/core\";\nimport type { RenderOptions } from \"./index\";\n\nexport const defaultPalette = [\"#e9d8a6\", \"#94d2bd\", \"#ee9b00\", \"#0a9396\", \"#ca6702\", \"#bb3e03\", \"#ae2012\", \"#005f73\"];\n\n/** A color, a palette (neighboring cells get different entries), or a color per cell. */\nexport type FillSource = string | readonly string[] | CellFill;\n\nexport interface CellStyle {\n fill: string;\n image?: string;\n /** Which item of `images` the cell shows (-1 if none or if `images` is a function). */\n slot: number;\n}\n\n/**\n * Fill color per cell (by `cell.index`): a color, a palette (neighboring cells get\n * different entries), or a function.\n */\nexport function resolveFills(layout: Layout, fill: FillSource): string[] {\n if (typeof fill === \"string\") return layout.cells.map(() => fill);\n const f = typeof fill === \"function\" ? fill : paletteFill(fill.length ? fill : defaultPalette);\n return layout.cells.map((c) => f(c, layout));\n}\n\ntype StyleOptions = Pick<RenderOptions, \"images\" | \"repeatImages\" | \"fill\" | \"contentCells\" | \"placement\" | \"imageAspects\" | \"choose\">;\n\n/** Resolve the fill color and image for every cell (shared by the SVG and React renderers). */\nexport function resolveCellStyles(layout: Layout, opts: StyleOptions = {}): CellStyle[] {\n const fills = resolveFills(layout, opts.fill ?? defaultPalette);\n const images = opts.images;\n let slots: number[] = layout.cells.map(() => -1);\n if (Array.isArray(images) && images.length > 0) {\n const count = opts.repeatImages ? Infinity : images.length;\n const content = { cells: opts.contentCells, placement: opts.placement, choose: opts.choose };\n slots =\n opts.imageAspects && !opts.repeatImages\n ? matchSlots(layout, images.map((_, i) => opts.imageAspects![i] ?? 1), content)\n : contentSlots(layout, count, content);\n }\n return layout.cells.map((c, i) => {\n if (typeof images === \"function\") return { fill: fills[i]!, image: images(c), slot: -1 };\n // With repeatImages, slots run past the images: the image shown is the slot wrapped round.\n const slot = images && images.length > 0 && slots[i]! >= 0 ? slots[i]! % images.length : -1;\n return { fill: fills[i]!, image: slot >= 0 ? images![slot] : undefined, slot };\n });\n}\n\n/** With `imageAlts`: a cell showing a described image is an image; the rest is decoration. */\nexport function cellA11y(style: CellStyle, alts: readonly string[] | undefined): { role?: \"img\"; \"aria-label\"?: string; \"aria-hidden\"?: \"true\" } {\n if (!alts?.length) return {};\n const alt = style.image && style.slot >= 0 ? alts[style.slot] : undefined;\n return alt ? { role: \"img\", \"aria-label\": alt } : { \"aria-hidden\": \"true\" };\n}\n"]}
package/dist/index.cjs ADDED
@@ -0,0 +1,458 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+ var _chunkJSRCX7PIcjs = require('./chunk-JSRCX7PI.cjs');
6
+
7
+ // src/index.ts
8
+ var _core = require('@andamento/core');
9
+
10
+ // src/relief.ts
11
+
12
+ function defaultBevel(layout) {
13
+ const n = layout.cells.length;
14
+ if (n === 0) return 0;
15
+ const mean = layout.cells.reduce((s, c) => s + c.area, 0) / n;
16
+ return 0.08 * Math.sqrt(mean);
17
+ }
18
+ var LEVELS = 8;
19
+ function reliefLayers(layout, cell, relief, bevel) {
20
+ const strength = _nullishCoalesce(relief.strength, () => ( 0.4));
21
+ const groups = /* @__PURE__ */ new Map();
22
+ for (const facet of _core.bevelFacets.call(void 0, cell, layout, { width: bevel, light: relief.light })) {
23
+ const level = Math.round(facet.shade * LEVELS);
24
+ if (level === 0) continue;
25
+ const list = groups.get(level);
26
+ if (list) list.push(facet.polygon);
27
+ else groups.set(level, [facet.polygon]);
28
+ }
29
+ return [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([level, polygons]) => ({
30
+ polygons,
31
+ fill: level > 0 ? "#fff" : "#000",
32
+ opacity: Number((Math.abs(level) / LEVELS * strength).toFixed(3))
33
+ }));
34
+ }
35
+ function reliefPaths(layout, cell, relief, bevel, precision = 3) {
36
+ const f = (n) => Number(n.toFixed(precision));
37
+ return reliefLayers(layout, cell, relief, bevel).map(({ polygons, fill, opacity }) => ({
38
+ d: polygons.map((poly) => "M" + poly.map((p) => `${f(p.x)} ${f(p.y)}`).join("L") + "Z").join(""),
39
+ fill,
40
+ opacity
41
+ }));
42
+ }
43
+ function shadowOffset(relief) {
44
+ const s = _nullishCoalesce(relief.shadow, () => ( 0));
45
+ if (!(s > 0)) return void 0;
46
+ const l = _core.lightVector.call(void 0, relief.light);
47
+ return { dx: -l.x * s, dy: -l.y * s, blur: _nullishCoalesce(relief.shadowBlur, () => ( s)), opacity: _nullishCoalesce(relief.shadowOpacity, () => ( 0.35)) };
48
+ }
49
+
50
+ // src/canvas.ts
51
+
52
+ function drawLayout(ctx, layout, options = {}) {
53
+ const canvas = ctx.canvas;
54
+ const width = _nullishCoalesce(_nullishCoalesce(options.width, () => ( _optionalChain([canvas, 'optionalAccess', _ => _.width]))), () => ( layout.bounds.width));
55
+ const height = _nullishCoalesce(_nullishCoalesce(options.height, () => ( _optionalChain([canvas, 'optionalAccess', _2 => _2.height]))), () => ( layout.bounds.height));
56
+ const b = layout.bounds;
57
+ const scale = Math.min(width / (b.width || 1), height / (b.height || 1)) || 1;
58
+ const ox = (width - b.width * scale) / 2 - b.x * scale;
59
+ const oy = (height - b.height * scale) / 2 - b.y * scale;
60
+ const toLayout = () => ctx.setTransform(scale, 0, 0, scale, ox, oy);
61
+ const styles = _chunkJSRCX7PIcjs.resolveCellStyles.call(void 0, layout, options);
62
+ const loaded = _nullishCoalesce(options.loaded, () => ( /* @__PURE__ */ new Map()));
63
+ const radius = layout.cornerRadius;
64
+ const cellLoops = (c) => {
65
+ const s = _core.cellShape.call(void 0, c);
66
+ return [s.outline, ...s.holes];
67
+ };
68
+ ctx.save();
69
+ toLayout();
70
+ ctx.lineJoin = "round";
71
+ if (options.background) {
72
+ ctx.beginPath();
73
+ for (const p of [layout.region, ...layout.holes]) tracePolygon(ctx, p, 0);
74
+ ctx.fillStyle = options.background;
75
+ ctx.fill("evenodd");
76
+ }
77
+ if (layout.view) {
78
+ ctx.beginPath();
79
+ for (const v of layout.view) for (const p of [v.outer, ...v.holes]) tracePolygon(ctx, p, 0);
80
+ ctx.clip("evenodd");
81
+ }
82
+ const relief = options.relief === true ? {} : options.relief || void 0;
83
+ const cast = relief && shadowOffset(relief);
84
+ if (cast) {
85
+ ctx.save();
86
+ ctx.beginPath();
87
+ for (const p of [layout.region, ...layout.holes]) tracePolygon(ctx, p, 0);
88
+ ctx.clip("evenodd");
89
+ const away = (b.width + b.height) * 4;
90
+ ctx.setTransform(scale, 0, 0, scale, ox - away * scale, oy);
91
+ ctx.shadowColor = `rgba(0,0,0,${cast.opacity})`;
92
+ ctx.shadowBlur = cast.blur * scale * 2;
93
+ ctx.shadowOffsetX = (away + cast.dx) * scale;
94
+ ctx.shadowOffsetY = cast.dy * scale;
95
+ ctx.beginPath();
96
+ for (const c of layout.cells) for (const p of cellLoops(c)) tracePolygon(ctx, p, radius);
97
+ ctx.fillStyle = "#000";
98
+ ctx.fill("evenodd");
99
+ ctx.restore();
100
+ }
101
+ const backdrop = options.backdrop ? loaded.get(options.backdrop) : void 0;
102
+ if (backdrop) {
103
+ ctx.save();
104
+ ctx.beginPath();
105
+ for (const c of layout.cells) for (const p of cellLoops(c)) tracePolygon(ctx, p, radius);
106
+ ctx.clip("evenodd");
107
+ drawCover(ctx, backdrop, b);
108
+ ctx.restore();
109
+ }
110
+ const bevel = relief ? _nullishCoalesce(relief.bevel, () => ( defaultBevel(layout))) : 0;
111
+ layout.cells.forEach((cell, i) => {
112
+ const style = styles[i];
113
+ ctx.beginPath();
114
+ for (const p of cellLoops(cell)) tracePolygon(ctx, p, radius);
115
+ if (!backdrop) {
116
+ ctx.fillStyle = style.fill;
117
+ ctx.fill("evenodd");
118
+ }
119
+ const img = style.image ? loaded.get(style.image) : void 0;
120
+ if (img) {
121
+ ctx.save();
122
+ ctx.clip("evenodd");
123
+ if (options.imageFit === "contain") {
124
+ const aspect = options.imageAspects && style.slot >= 0 ? options.imageAspects[style.slot] : void 0;
125
+ drawContain(ctx, img, _core.safeArea.call(void 0, cell, layout, { aspect, within: options.containWithin }));
126
+ } else {
127
+ const focus = style.slot >= 0 ? _optionalChain([options, 'access', _3 => _3.imageFocus, 'optionalAccess', _4 => _4[style.slot]]) : void 0;
128
+ if (focus && img.width && img.height) {
129
+ const r = _core.coverRect.call(void 0, cell, layout, { aspect: img.width / img.height, focus });
130
+ ctx.drawImage(img, 0, 0, img.width, img.height, r.x, r.y, r.width, r.height);
131
+ } else drawCover(ctx, img, _core.cellShape.call(void 0, cell).bbox);
132
+ }
133
+ ctx.restore();
134
+ }
135
+ if (relief && bevel > 0) {
136
+ for (const layer of reliefLayers(layout, cell, relief, bevel)) {
137
+ ctx.beginPath();
138
+ for (const poly of layer.polygons) tracePolygon(ctx, poly, 0);
139
+ ctx.globalAlpha = layer.opacity;
140
+ ctx.fillStyle = layer.fill;
141
+ ctx.fill();
142
+ ctx.globalAlpha = 1;
143
+ }
144
+ }
145
+ if (options.stroke) {
146
+ ctx.beginPath();
147
+ for (const p of cellLoops(cell)) tracePolygon(ctx, p, radius);
148
+ ctx.strokeStyle = options.stroke;
149
+ ctx.lineWidth = _nullishCoalesce(options.strokeWidth, () => ( 1));
150
+ ctx.stroke();
151
+ }
152
+ });
153
+ ctx.restore();
154
+ }
155
+ function tracePolygon(ctx, poly, radius) {
156
+ if (poly.length < 3) return;
157
+ if (radius <= 0) {
158
+ ctx.moveTo(poly[0].x, poly[0].y);
159
+ for (let i = 1; i < poly.length; i++) ctx.lineTo(poly[i].x, poly[i].y);
160
+ ctx.closePath();
161
+ return;
162
+ }
163
+ _core.roundCorners.call(void 0, poly, radius).forEach((c, i) => {
164
+ if (i === 0) ctx.moveTo(c.start.x, c.start.y);
165
+ else ctx.lineTo(c.start.x, c.start.y);
166
+ if (c.radius > 0) {
167
+ const a0 = Math.atan2(c.start.y - c.center.y, c.start.x - c.center.x);
168
+ ctx.arc(c.center.x, c.center.y, c.radius, a0, a0 + c.sweep, c.sweep < 0);
169
+ }
170
+ });
171
+ ctx.closePath();
172
+ }
173
+ function drawCover(ctx, img, box) {
174
+ if (!img.width || !img.height || !box.width || !box.height) return;
175
+ const s = Math.max(box.width / img.width, box.height / img.height);
176
+ const sw = box.width / s, sh = box.height / s;
177
+ ctx.drawImage(img, (img.width - sw) / 2, (img.height - sh) / 2, sw, sh, box.x, box.y, box.width, box.height);
178
+ }
179
+ function drawContain(ctx, img, box) {
180
+ if (!img.width || !img.height || !box.width || !box.height) return;
181
+ const s = Math.min(box.width / img.width, box.height / img.height);
182
+ const w = img.width * s, h = img.height * s;
183
+ ctx.drawImage(img, 0, 0, img.width, img.height, box.x + (box.width - w) / 2, box.y + (box.height - h) / 2, w, h);
184
+ }
185
+ function imagesUsed(layout, options = {}) {
186
+ const urls = /* @__PURE__ */ new Set();
187
+ for (const s of _chunkJSRCX7PIcjs.resolveCellStyles.call(void 0, layout, options)) if (s.image) urls.add(s.image);
188
+ if (options.backdrop) urls.add(options.backdrop);
189
+ return [...urls];
190
+ }
191
+ async function loadImages(urls, load = browserImage) {
192
+ const out = /* @__PURE__ */ new Map();
193
+ await Promise.all(
194
+ urls.map(async (url) => {
195
+ try {
196
+ out.set(url, await load(url));
197
+ } catch (e) {
198
+ }
199
+ })
200
+ );
201
+ return out;
202
+ }
203
+ function browserImage(url) {
204
+ const Img = globalThis.Image;
205
+ if (!Img) return Promise.reject(new Error("No Image constructor: pass a load function"));
206
+ return new Promise((resolve, reject) => {
207
+ const img = new Img();
208
+ img.crossOrigin = "anonymous";
209
+ img.onload = () => resolve(img);
210
+ img.onerror = () => reject(new Error(`Could not load ${url}`));
211
+ img.src = url;
212
+ });
213
+ }
214
+ async function renderToCanvas(layout, canvas, options = {}) {
215
+ const { w, h } = rasterSize(layout, options);
216
+ canvas.width = w;
217
+ canvas.height = h;
218
+ const ctx = canvas.getContext("2d");
219
+ if (!ctx) throw new Error("Could not get a 2D context from the canvas");
220
+ const loaded = await _asyncNullishCoalesce(options.loaded, async () => ( await loadImages(imagesUsed(layout, options), options.loadImage)));
221
+ ctx.clearRect(0, 0, w, h);
222
+ drawLayout(ctx, layout, { ...options, loaded, width: w, height: h });
223
+ return canvas;
224
+ }
225
+ function rasterSize(layout, options = {}) {
226
+ const b = layout.bounds;
227
+ const cssWidth = _nullishCoalesce(options.width, () => ( b.width));
228
+ const ratio = _nullishCoalesce(options.pixelRatio, () => ( 1));
229
+ return { w: Math.max(1, Math.round(cssWidth * ratio)), h: Math.max(1, Math.round(cssWidth * b.height / (b.width || 1) * ratio)) };
230
+ }
231
+ async function renderToPng(layout, options = {}) {
232
+ const { w, h } = rasterSize(layout, options);
233
+ const canvas = options.createCanvas ? options.createCanvas(w, h) : makeCanvas(w, h);
234
+ await renderToCanvas(layout, canvas, options);
235
+ const type = _nullishCoalesce(options.type, () => ( "image/png"));
236
+ const c = canvas;
237
+ if (c.convertToBlob) return c.convertToBlob({ type, quality: options.quality });
238
+ if (c.toBlob) {
239
+ return new Promise(
240
+ (resolve, reject) => c.toBlob((blob) => blob ? resolve(blob) : reject(new Error("The canvas could not be exported")), type, options.quality)
241
+ );
242
+ }
243
+ throw new Error("This canvas can't export images: use drawLayout and your canvas's own export");
244
+ }
245
+ function makeCanvas(w, h) {
246
+ const g = globalThis;
247
+ if (g.OffscreenCanvas) return new g.OffscreenCanvas(w, h);
248
+ if (g.document) {
249
+ const c = g.document.createElement("canvas");
250
+ c.width = w;
251
+ c.height = h;
252
+ return c;
253
+ }
254
+ throw new Error("No canvas available: pass createCanvas, or use drawLayout with your own");
255
+ }
256
+
257
+ // src/index.ts
258
+ var neutralPalette = ["#e7e5e4", "#d6d3d1", "#f5f5f4", "#dedad6", "#ecebe9"];
259
+ var formatter = (precision) => (n) => {
260
+ const s = n.toFixed(precision);
261
+ const t = s.includes(".") ? s.replace(/\.?0+$/, "") : s;
262
+ return t === "-0" ? "0" : t;
263
+ };
264
+ function polygonToPath(p, precision = 3, radius = 0) {
265
+ if (p.length === 0) return "";
266
+ const f = formatter(precision);
267
+ if (radius <= 0) return "M" + p.map((v) => `${f(v.x)} ${f(v.y)}`).join("L") + "Z";
268
+ const parts = [];
269
+ for (const c of _core.roundCorners.call(void 0, p, radius)) {
270
+ parts.push(`${parts.length ? "L" : "M"}${f(c.start.x)} ${f(c.start.y)}`);
271
+ if (c.radius > 0) {
272
+ const r = f(c.radius);
273
+ parts.push(`A${r} ${r} 0 0 ${c.sweep > 0 ? 1 : 0} ${f(c.end.x)} ${f(c.end.y)}`);
274
+ }
275
+ }
276
+ return parts.join("") + "Z";
277
+ }
278
+ function cellPath(layout, cell, precision = 3) {
279
+ const s = _core.cellShape.call(void 0, cell);
280
+ return [s.outline, ...s.holes].map((p) => polygonToPath(p, precision, layout.cornerRadius)).join("");
281
+ }
282
+ function viewPath(layout, precision = 3) {
283
+ if (!layout.view) return regionPath(layout, precision);
284
+ return layout.view.flatMap((v) => [v.outer, ...v.holes]).map((p) => polygonToPath(p, precision)).join("");
285
+ }
286
+ function regionPath(layout, precision = 3) {
287
+ return [layout.region, ...layout.holes].map((p) => polygonToPath(p, precision)).join("");
288
+ }
289
+ var el = (tag, attrs = {}, children = []) => ({
290
+ tag,
291
+ attrs,
292
+ children
293
+ });
294
+ function toSvgTree(layout, opts = {}) {
295
+ const precision = _nullishCoalesce(opts.precision, () => ( 3));
296
+ const prefix = _nullishCoalesce(opts.idPrefix, () => ( "andamento"));
297
+ const { x, y, width, height } = layout.bounds;
298
+ const styles = _chunkJSRCX7PIcjs.resolveCellStyles.call(void 0, layout, opts);
299
+ const r = (n) => Number(n.toFixed(precision));
300
+ const children = [];
301
+ if (opts.title) children.push(el("title", {}, [opts.title]));
302
+ if (opts.background) {
303
+ children.push(el("path", { d: regionPath(layout, precision), fill: opts.background, "fill-rule": "evenodd", class: "andamento-region" }));
304
+ }
305
+ const start = children.length;
306
+ if (opts.backdrop) {
307
+ const clipId = `${prefix}-backdrop`;
308
+ const shapes = layout.cells.map((cell) => el("path", { d: cellPath(layout, cell, precision), "clip-rule": "evenodd" }));
309
+ children.push(el("clipPath", { id: clipId }, shapes));
310
+ children.push(
311
+ el("image", {
312
+ class: "andamento-backdrop",
313
+ href: opts.backdrop,
314
+ x: r(x),
315
+ y: r(y),
316
+ width: r(width),
317
+ height: r(height),
318
+ preserveAspectRatio: "xMidYMid slice",
319
+ "clip-path": `url(#${clipId})`
320
+ })
321
+ );
322
+ }
323
+ const relief = opts.relief === true ? {} : opts.relief || void 0;
324
+ const bevel = relief ? _nullishCoalesce(relief.bevel, () => ( defaultBevel(layout))) : 0;
325
+ const cast = relief && shadowOffset(relief);
326
+ if (cast) {
327
+ const regionId = `${prefix}-region`;
328
+ const blurId = `${prefix}-shadow`;
329
+ children.push(el("clipPath", { id: regionId }, [el("path", { d: regionPath(layout, precision), "clip-rule": "evenodd" })]));
330
+ children.push(el("filter", { id: blurId, x: "-10%", y: "-10%", width: "120%", height: "120%" }, [el("feGaussianBlur", { stdDeviation: r(cast.blur) })]));
331
+ children.push(
332
+ el("g", { class: "andamento-shadow", "clip-path": `url(#${regionId})` }, [
333
+ el("path", {
334
+ d: layout.cells.map((c) => cellPath(layout, c, precision)).join(""),
335
+ "fill-rule": "evenodd",
336
+ transform: `translate(${r(cast.dx)} ${r(cast.dy)})`,
337
+ fill: "#000",
338
+ "fill-opacity": cast.opacity,
339
+ filter: `url(#${blurId})`
340
+ })
341
+ ])
342
+ );
343
+ }
344
+ layout.cells.forEach((cell, i) => {
345
+ const d = cellPath(layout, cell, precision);
346
+ const style = styles[i];
347
+ const holed = !!_optionalChain([cell, 'access', _5 => _5.holes, 'optionalAccess', _6 => _6.length]);
348
+ const parts = opts.backdrop ? [] : [el("path", { d, fill: style.fill, "fill-rule": holed ? "evenodd" : void 0 })];
349
+ if (style.image) {
350
+ const clipId = `${prefix}-clip-${cell.index}`;
351
+ parts.unshift(el("clipPath", { id: clipId }, [el("path", { d, "clip-rule": holed ? "evenodd" : void 0 })]));
352
+ const contain = opts.imageFit === "contain";
353
+ const aspect = contain && opts.imageAspects && style.slot >= 0 ? opts.imageAspects[style.slot] : void 0;
354
+ const focus = !contain && style.slot >= 0 ? _optionalChain([opts, 'access', _7 => _7.imageFocus, 'optionalAccess', _8 => _8[style.slot]]) : void 0;
355
+ const shape = focus ? _nullishCoalesce(_optionalChain([opts, 'access', _9 => _9.imageAspects, 'optionalAccess', _10 => _10[style.slot]]), () => ( focus.aspect)) : void 0;
356
+ const box = contain ? _core.safeArea.call(void 0, cell, layout, { aspect, within: opts.containWithin }) : focus && shape ? _core.coverRect.call(void 0, cell, layout, { aspect: shape, focus }) : _core.cellShape.call(void 0, cell).bbox;
357
+ parts.push(
358
+ el("image", {
359
+ href: style.image,
360
+ x: r(box.x),
361
+ y: r(box.y),
362
+ width: r(box.width),
363
+ height: r(box.height),
364
+ preserveAspectRatio: contain ? "xMidYMid meet" : "xMidYMid slice",
365
+ "clip-path": `url(#${clipId})`
366
+ })
367
+ );
368
+ }
369
+ if (relief && bevel > 0) {
370
+ for (const p of reliefPaths(layout, cell, relief, bevel, precision)) {
371
+ parts.push(el("path", { class: "andamento-bevel", d: p.d, fill: p.fill, "fill-opacity": p.opacity }));
372
+ }
373
+ }
374
+ if (opts.stroke) {
375
+ parts.push(el("path", { d, fill: "none", stroke: opts.stroke, "stroke-width": _nullishCoalesce(opts.strokeWidth, () => ( 1)) }));
376
+ }
377
+ children.push(
378
+ el(
379
+ "g",
380
+ {
381
+ class: "andamento-cell",
382
+ "data-cell-id": cell.id,
383
+ "data-index": cell.index,
384
+ "data-empty": style.image ? void 0 : "",
385
+ "data-boundary": cell.boundary ? "" : void 0,
386
+ ..._chunkJSRCX7PIcjs.cellA11y.call(void 0, style, opts.imageAlts)
387
+ },
388
+ parts
389
+ )
390
+ );
391
+ });
392
+ if (layout.view) {
393
+ const viewId = `${prefix}-view`;
394
+ const body = children.splice(start);
395
+ children.push(el("clipPath", { id: viewId }, [el("path", { d: viewPath(layout, precision), "clip-rule": "evenodd" })]));
396
+ children.push(el("g", { class: "andamento-view", "clip-path": `url(#${viewId})` }, body));
397
+ }
398
+ return el(
399
+ "svg",
400
+ {
401
+ xmlns: "http://www.w3.org/2000/svg",
402
+ viewBox: `${r(x)} ${r(y)} ${r(width)} ${r(height)}`,
403
+ width: opts.width,
404
+ height: opts.height,
405
+ role: _optionalChain([opts, 'access', _11 => _11.imageAlts, 'optionalAccess', _12 => _12.length]) ? "group" : opts.title ? "img" : void 0
406
+ },
407
+ children
408
+ );
409
+ }
410
+ var escapeText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
411
+ var escapeAttr = (s) => escapeText(s).replace(/"/g, "&quot;");
412
+ function serialize(node) {
413
+ if (typeof node === "string") return escapeText(node);
414
+ const attrs = Object.entries(node.attrs).filter(([, v]) => v !== void 0).map(([k, v]) => ` ${k}="${escapeAttr(String(v))}"`).join("");
415
+ if (node.children.length === 0) return `<${node.tag}${attrs}/>`;
416
+ return `<${node.tag}${attrs}>${node.children.map(serialize).join("")}</${node.tag}>`;
417
+ }
418
+ function renderToString(layout, opts = {}) {
419
+ return serialize(toSvgTree(layout, opts));
420
+ }
421
+ var SVG_NS = "http://www.w3.org/2000/svg";
422
+ function build(node, doc) {
423
+ if (typeof node === "string") return doc.createTextNode(node);
424
+ const elem = doc.createElementNS(SVG_NS, node.tag);
425
+ for (const [k, v] of Object.entries(node.attrs)) {
426
+ if (v !== void 0 && k !== "xmlns") elem.setAttribute(k, String(v));
427
+ }
428
+ for (const child of node.children) elem.appendChild(build(child, doc));
429
+ return elem;
430
+ }
431
+ function renderToElement(layout, opts = {}, doc = globalThis.document) {
432
+ if (!doc) throw new Error("renderToElement needs a DOM Document; pass one explicitly outside the browser");
433
+ return build(toSvgTree(layout, opts), doc);
434
+ }
435
+
436
+
437
+
438
+
439
+
440
+
441
+
442
+
443
+
444
+
445
+
446
+
447
+
448
+
449
+
450
+
451
+
452
+
453
+
454
+
455
+
456
+
457
+ exports.cellPath = cellPath; exports.defaultBevel = defaultBevel; exports.defaultPalette = _chunkJSRCX7PIcjs.defaultPalette; exports.drawLayout = drawLayout; exports.imagesUsed = imagesUsed; exports.loadImages = loadImages; exports.neutralPalette = neutralPalette; exports.polygonToPath = polygonToPath; exports.rasterSize = rasterSize; exports.regionPath = regionPath; exports.reliefLayers = reliefLayers; exports.reliefPaths = reliefPaths; exports.renderToCanvas = renderToCanvas; exports.renderToElement = renderToElement; exports.renderToPng = renderToPng; exports.renderToString = renderToString; exports.serialize = serialize; exports.shadowOffset = shadowOffset; exports.toSvgTree = toSvgTree; exports.tracePolygon = tracePolygon; exports.viewPath = viewPath;
458
+ //# sourceMappingURL=index.cjs.map