@andamento/svg 0.1.0 → 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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/relief.ts","../src/canvas.ts"],"sourcesContent":["/**\n * Renders a layout to an SVG string or element, to a canvas, or to a PNG.\n *\n * @module @andamento/svg\n */\nimport { cellShape, contentSlots, coverRect, type Focus, matchSlots, safeArea, paletteFill, type CellFill, roundCorners, type Cell, type ContentCells, type ContentPlacement, type Layout, type Polygon } from \"@andamento/core\";\n\nimport { defaultBevel, reliefPaths, shadowOffset, type ReliefOptions } from \"./relief\";\nexport { defaultBevel, reliefLayers, reliefPaths, shadowOffset } from \"./relief\";\nexport type { ReliefLayer, ReliefOptions, ReliefPath } from \"./relief\";\n\nexport const defaultPalette = [\"#e9d8a6\", \"#94d2bd\", \"#ee9b00\", \"#0a9396\", \"#ca6702\", \"#bb3e03\", \"#ae2012\", \"#005f73\"];\n\n/** Soft neutrals for tiles without content: visible as tiles, but quiet next to photos. */\nexport const neutralPalette = [\"#e7e5e4\", \"#d6d3d1\", \"#f5f5f4\", \"#dedad6\", \"#ecebe9\"];\n\nexport type ImageSource = readonly string[] | ((cell: Cell) => string | undefined);\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 RenderOptions {\n /** Images: an array assigned in reading order, or a function per cell. */\n images?: ImageSource;\n /** Reuse the images array from the start when there are more cells than images. */\n repeatImages?: boolean;\n /** Which cells may hold an image from the `images` array (default \"all\"). */\n contentCells?: ContentCells;\n /** Where the images go when there are fewer than cells (default \"reading\"). */\n placement?: ContentPlacement;\n /**\n * Width / height of each image in `images`. When given, each image goes in a cell of\n * similar shape, to crop as little as possible (see `matchSlots`). Ignored with `repeatImages`.\n */\n imageAspects?: readonly number[];\n /**\n * How each image fills its cell: \"cover\" (default) fills the cell's bounding box and is\n * cropped to the cell's shape; \"contain\" shows the whole image inside the cell's safe area\n * (see `safeArea`), uncropped. Give `imageAspects` so the safe area has each image's shape.\n */\n imageFit?: \"cover\" | \"contain\";\n /**\n * With `imageFit: \"contain\"`, for cells an `edges: \"window\"` layout cuts: fit the image in\n * the whole tile (\"tile\", the default; partly hidden like the tile) or in the part that\n * shows (\"visible\"). See `SafeAreaOptions.within`.\n */\n containWithin?: \"tile\" | \"visible\";\n /**\n * Focal point of each image in `images` (by position; fractions of its width and height,\n * see `estimateFocus`): what to keep in view when \"cover\" crops it. It goes as near the\n * middle of what shows of its cell as covering the cell allows (see `coverRect`). Needs\n * each image's shape, from `imageAspects` or the focus's `aspect` (the canvas renderers\n * measure the images themselves).\n */\n imageFocus?: readonly (Focus | undefined)[];\n /** With `imageAspects`: \"shape\" also picks which cells get images by their shape. */\n choose?: \"placement\" | \"shape\";\n /**\n * Cell color when there is no image: a color, a palette (neighboring cells get\n * different entries), or a function. Defaults to `defaultPalette`.\n */\n fill?: FillSource;\n /**\n * Raised tiles: a lit bevel round each tile, and optionally a shadow cast into the grout.\n * `true` for the defaults. See `ReliefOptions`.\n */\n relief?: boolean | ReliefOptions;\n /** Outline drawn on top of each cell. */\n stroke?: string;\n strokeWidth?: number;\n /** Color painted over the whole region. Omit for transparent. */\n background?: string;\n /**\n * One image across all the cells (a URL): drawn once over the layout bounds (cropped to\n * cover them) and clipped to the cells, so each cell shows its piece. Cells' `fill` isn't\n * drawn; per-cell `images` still go on top.\n */\n backdrop?: string;\n /** Prefix for generated element ids; set it when several layouts share a page. */\n idPrefix?: string;\n /** Decimal places for coordinates. Defaults to 3. */\n precision?: number;\n /** Width/height attributes of the <svg>; it always gets a viewBox. */\n width?: string | number;\n height?: string | number;\n /** Accessible title. */\n title?: string;\n /**\n * Text alternative for each image in `images` (by position). Cells showing an image with\n * one become labeled images to assistive technology, and the SVG a group of them; the\n * other cells are hidden as decoration.\n */\n imageAlts?: readonly string[];\n}\n\nconst formatter = (precision: number) => (n: number) => {\n const s = n.toFixed(precision);\n // Trim trailing zeros: \"12.500\" -> \"12.5\", \"3.000\" -> \"3\", \"-0\" -> \"0\".\n const t = s.includes(\".\") ? s.replace(/\\.?0+$/, \"\") : s;\n return t === \"-0\" ? \"0\" : t;\n};\n\n/** `d` attribute for a polygon. With `radius`, corners are rounded with circular arcs. */\nexport function polygonToPath(p: Polygon, precision = 3, radius = 0): string {\n if (p.length === 0) return \"\";\n const f = formatter(precision);\n if (radius <= 0) return \"M\" + p.map((v) => `${f(v.x)} ${f(v.y)}`).join(\"L\") + \"Z\";\n const parts: string[] = [];\n for (const c of roundCorners(p, radius)) {\n parts.push(`${parts.length ? \"L\" : \"M\"}${f(c.start.x)} ${f(c.start.y)}`);\n if (c.radius > 0) {\n const r = f(c.radius);\n parts.push(`A${r} ${r} 0 0 ${c.sweep > 0 ? 1 : 0} ${f(c.end.x)} ${f(c.end.y)}`);\n }\n }\n return parts.join(\"\") + \"Z\";\n}\n\n/**\n * `d` attribute for a cell's outline, including the layout's corner rounding and any holes\n * (as extra subpaths; draw with `fill-rule=\"evenodd\"`). For a window cell this is the\n * whole tile (see `cellShape`); clip it to `viewPath`.\n */\nexport function cellPath(layout: Layout, cell: Cell, precision = 3): string {\n const s = cellShape(cell);\n return [s.outline, ...s.holes].map((p) => polygonToPath(p, precision, layout.cornerRadius)).join(\"\");\n}\n\n/**\n * `d` attribute for the area tiles show in (draw or clip with `evenodd`): `layout.view` in\n * a window layout, else the region with its holes.\n */\nexport function viewPath(layout: Layout, precision = 3): string {\n if (!layout.view) return regionPath(layout, precision);\n return layout.view.flatMap((v) => [v.outer, ...v.holes]).map((p) => polygonToPath(p, precision)).join(\"\");\n}\n\n/** `d` attribute for the region with its holes (draw with `fill-rule=\"evenodd\"`). */\nexport function regionPath(layout: Layout, precision = 3): string {\n return [layout.region, ...layout.holes].map((p) => polygonToPath(p, precision)).join(\"\");\n}\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 const slot = slots[i]!;\n let image: string | undefined;\n if (typeof images === \"function\") image = images(c);\n else if (images && slot >= 0) image = images[slot % images.length];\n return { fill: fills[i]!, image, slot };\n });\n}\n\n/** Minimal element tree, serializable to a string or built into DOM nodes. */\nexport interface SvgNode {\n tag: string;\n attrs: Record<string, string | number | undefined>;\n children: (SvgNode | string)[];\n}\n\nconst el = (tag: string, attrs: SvgNode[\"attrs\"] = {}, children: SvgNode[\"children\"] = []): SvgNode => ({\n tag,\n attrs,\n children,\n});\n\nexport function toSvgTree(layout: Layout, opts: RenderOptions = {}): SvgNode {\n const precision = opts.precision ?? 3;\n const prefix = opts.idPrefix ?? \"andamento\";\n const { x, y, width, height } = layout.bounds;\n const styles = resolveCellStyles(layout, opts);\n const r = (n: number) => Number(n.toFixed(precision));\n\n const children: SvgNode[\"children\"] = [];\n if (opts.title) children.push(el(\"title\", {}, [opts.title]));\n if (opts.background) {\n children.push(el(\"path\", { d: regionPath(layout, precision), fill: opts.background, \"fill-rule\": \"evenodd\", class: \"andamento-region\" }));\n }\n\n // In a window layout, everything from here on is drawn whole and cut to the view.\n const start = children.length;\n if (opts.backdrop) {\n const clipId = `${prefix}-backdrop`;\n const shapes = layout.cells.map((cell) => el(\"path\", { d: cellPath(layout, cell, precision), \"clip-rule\": \"evenodd\" }));\n children.push(el(\"clipPath\", { id: clipId }, shapes));\n children.push(\n el(\"image\", {\n class: \"andamento-backdrop\",\n href: opts.backdrop,\n x: r(x),\n y: r(y),\n width: r(width),\n height: r(height),\n preserveAspectRatio: \"xMidYMid slice\",\n \"clip-path\": `url(#${clipId})`,\n }),\n );\n }\n\n const relief: ReliefOptions | undefined = opts.relief === true ? {} : opts.relief || undefined;\n const bevel = relief ? (relief.bevel ?? defaultBevel(layout)) : 0;\n const cast = relief && shadowOffset(relief);\n if (cast) {\n // Every tile's shape, moved away from the light and blurred, kept within the region.\n const regionId = `${prefix}-region`;\n const blurId = `${prefix}-shadow`;\n children.push(el(\"clipPath\", { id: regionId }, [el(\"path\", { d: regionPath(layout, precision), \"clip-rule\": \"evenodd\" })]));\n children.push(el(\"filter\", { id: blurId, x: \"-10%\", y: \"-10%\", width: \"120%\", height: \"120%\" }, [el(\"feGaussianBlur\", { stdDeviation: r(cast.blur) })]));\n children.push(\n el(\"g\", { class: \"andamento-shadow\", \"clip-path\": `url(#${regionId})` }, [\n el(\"path\", {\n d: layout.cells.map((c) => cellPath(layout, c, precision)).join(\"\"),\n \"fill-rule\": \"evenodd\",\n transform: `translate(${r(cast.dx)} ${r(cast.dy)})`,\n fill: \"#000\",\n \"fill-opacity\": cast.opacity,\n filter: `url(#${blurId})`,\n }),\n ]),\n );\n }\n\n layout.cells.forEach((cell, i) => {\n const d = cellPath(layout, cell, precision);\n const style = styles[i]!;\n const holed = !!cell.holes?.length;\n const parts: SvgNode[] = opts.backdrop ? [] : [el(\"path\", { d, fill: style.fill, \"fill-rule\": holed ? \"evenodd\" : undefined })];\n if (style.image) {\n const clipId = `${prefix}-clip-${cell.index}`;\n parts.unshift(el(\"clipPath\", { id: clipId }, [el(\"path\", { d, \"clip-rule\": holed ? \"evenodd\" : undefined })]));\n const contain = opts.imageFit === \"contain\";\n const aspect = contain && opts.imageAspects && style.slot >= 0 ? opts.imageAspects[style.slot % opts.imageAspects.length] : undefined;\n const focus = !contain && style.slot >= 0 ? (Array.isArray(opts.images) ? opts.imageFocus?.[style.slot % opts.images.length] : undefined) : undefined;\n const shape = focus ? (opts.imageAspects?.[style.slot % opts.imageAspects.length] ?? focus.aspect) : undefined;\n const box = contain\n ? safeArea(cell, layout, { aspect, within: opts.containWithin })\n : focus && shape\n ? coverRect(cell, layout, { aspect: shape, focus })\n : cellShape(cell).bbox;\n parts.push(\n el(\"image\", {\n href: style.image,\n x: r(box.x),\n y: r(box.y),\n width: r(box.width),\n height: r(box.height),\n preserveAspectRatio: contain ? \"xMidYMid meet\" : \"xMidYMid slice\",\n \"clip-path\": `url(#${clipId})`,\n }),\n );\n }\n if (relief && bevel > 0) {\n for (const p of reliefPaths(layout, cell, relief, bevel, precision)) {\n parts.push(el(\"path\", { class: \"andamento-bevel\", d: p.d, fill: p.fill, \"fill-opacity\": p.opacity }));\n }\n }\n if (opts.stroke) {\n parts.push(el(\"path\", { d, fill: \"none\", stroke: opts.stroke, \"stroke-width\": opts.strokeWidth ?? 1 }));\n }\n children.push(\n el(\n \"g\",\n {\n class: \"andamento-cell\",\n \"data-cell-id\": cell.id,\n \"data-index\": cell.index,\n \"data-empty\": style.image ? undefined : \"\",\n \"data-boundary\": cell.boundary ? \"\" : undefined,\n ...cellA11y(style, opts.imageAlts),\n },\n parts,\n ),\n );\n });\n if (layout.view) {\n const viewId = `${prefix}-view`;\n const body = children.splice(start);\n children.push(el(\"clipPath\", { id: viewId }, [el(\"path\", { d: viewPath(layout, precision), \"clip-rule\": \"evenodd\" })]));\n children.push(el(\"g\", { class: \"andamento-view\", \"clip-path\": `url(#${viewId})` }, body));\n }\n\n return el(\n \"svg\",\n {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: `${r(x)} ${r(y)} ${r(width)} ${r(height)}`,\n width: opts.width,\n height: opts.height,\n role: opts.imageAlts?.length ? \"group\" : opts.title ? \"img\" : undefined,\n },\n children,\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 % alts.length] : undefined;\n return alt ? { role: \"img\", \"aria-label\": alt } : { \"aria-hidden\": \"true\" };\n}\n\nconst escapeText = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\nconst escapeAttr = (s: string) => escapeText(s).replace(/\"/g, \"&quot;\");\n\nexport function serialize(node: SvgNode | string): string {\n if (typeof node === \"string\") return escapeText(node);\n const attrs = Object.entries(node.attrs)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n .join(\"\");\n if (node.children.length === 0) return `<${node.tag}${attrs}/>`;\n return `<${node.tag}${attrs}>${node.children.map(serialize).join(\"\")}</${node.tag}>`;\n}\n\n/** Render a layout to a standalone SVG document string. */\nexport function renderToString(layout: Layout, opts: RenderOptions = {}): string {\n return serialize(toSvgTree(layout, opts));\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nfunction build(node: SvgNode | string, doc: Document): Node {\n if (typeof node === \"string\") return doc.createTextNode(node);\n const elem = doc.createElementNS(SVG_NS, node.tag);\n for (const [k, v] of Object.entries(node.attrs)) {\n if (v !== undefined && k !== \"xmlns\") elem.setAttribute(k, String(v));\n }\n for (const child of node.children) elem.appendChild(build(child, doc));\n return elem;\n}\n\n/** Render a layout to a live <svg> element. */\nexport function renderToElement(layout: Layout, opts: RenderOptions = {}, doc: Document = globalThis.document): SVGSVGElement {\n if (!doc) throw new Error(\"renderToElement needs a DOM Document; pass one explicitly outside the browser\");\n return build(toSvgTree(layout, opts), doc) as SVGSVGElement;\n}\n\nexport { drawLayout, imagesUsed, loadImages, rasterSize, renderToCanvas, renderToPng, tracePolygon } from \"./canvas\";\nexport type { CanvasContextLike, CanvasImage, CanvasLike, CanvasRenderOptions, RasterOptions } from \"./canvas\";\n","import { bevelFacets, lightVector, type Cell, type Layout, type Polygon } from \"@andamento/core\";\n\n/**\n * Makes tiles look raised: a bevel round each tile's edges, lit from one side, and\n * optionally a shadow each tile casts into the grout (the gaps) on the other.\n */\nexport interface ReliefOptions {\n /** Bevel width in layout units. Defaults to 8% of a typical tile's size; 0 for none. */\n bevel?: number;\n /** Direction the light comes from: degrees clockwise from the top (default 315, top left). */\n light?: number;\n /** Opacity of the brightest highlight and the darkest bevel shadow, 0–1. Defaults to 0.4. */\n strength?: number;\n /** How far tiles' shadows fall into the grout, in layout units (default 0: no shadow). */\n shadow?: number;\n /** Blur of the cast shadow (standard deviation, layout units). Defaults to `shadow`. */\n shadowBlur?: number;\n /** Opacity of the cast shadow. Defaults to 0.35. */\n shadowOpacity?: number;\n}\n\n/** One layer of a cell's bevel: all its faces of about the same shade, as one path. */\nexport interface ReliefPath {\n d: string;\n /** \"#fff\" for highlights, \"#000\" for shadows. */\n fill: string;\n opacity: number;\n}\n\n/** The default bevel width for a layout: 8% of the square root of the mean tile area. */\nexport function defaultBevel(layout: Layout): number {\n const n = layout.cells.length;\n if (n === 0) return 0;\n const mean = layout.cells.reduce((s, c) => s + c.area, 0) / n;\n return 0.08 * Math.sqrt(mean);\n}\n\nconst LEVELS = 8;\n\n/** One layer of a cell's bevel as polygons: all its faces of about the same shade. */\nexport interface ReliefLayer {\n polygons: Polygon[];\n /** \"#fff\" for highlights, \"#000\" for shadows. */\n fill: string;\n opacity: number;\n}\n\n/**\n * A cell's bevel grouped into a few shade levels, in layout coordinates, to draw over the\n * cell's content. Pass the bevel width from `defaultBevel` if not set.\n */\nexport function reliefLayers(layout: Layout, cell: Cell, relief: ReliefOptions, bevel: number): ReliefLayer[] {\n const strength = relief.strength ?? 0.4;\n const groups = new Map<number, Polygon[]>();\n for (const facet of bevelFacets(cell, layout, { width: bevel, light: relief.light })) {\n const level = Math.round(facet.shade * LEVELS);\n if (level === 0) continue;\n const list = groups.get(level);\n if (list) list.push(facet.polygon);\n else groups.set(level, [facet.polygon]);\n }\n return [...groups.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([level, polygons]) => ({\n polygons,\n fill: level > 0 ? \"#fff\" : \"#000\",\n opacity: Number(((Math.abs(level) / LEVELS) * strength).toFixed(3)),\n }));\n}\n\n/** `reliefLayers` as SVG paths, one per layer. */\nexport function reliefPaths(layout: Layout, cell: Cell, relief: ReliefOptions, bevel: number, precision = 3): ReliefPath[] {\n const f = (n: number) => Number(n.toFixed(precision));\n return reliefLayers(layout, cell, relief, bevel).map(({ polygons, fill, opacity }) => ({\n d: polygons.map((poly) => \"M\" + poly.map((p) => `${f(p.x)} ${f(p.y)}`).join(\"L\") + \"Z\").join(\"\"),\n fill,\n opacity,\n }));\n}\n\n/** Offset of the cast shadow (away from the light), or undefined for none. */\nexport function shadowOffset(relief: ReliefOptions): { dx: number; dy: number; blur: number; opacity: number } | undefined {\n const s = relief.shadow ?? 0;\n if (!(s > 0)) return undefined;\n const l = lightVector(relief.light);\n return { dx: -l.x * s, dy: -l.y * s, blur: relief.shadowBlur ?? s, opacity: relief.shadowOpacity ?? 0.35 };\n}\n","import { cellShape, coverRect, roundCorners, safeArea, type Cell, type Layout, type Polygon, type Rect } from \"@andamento/core\";\nimport { resolveCellStyles, type RenderOptions } from \"./index\";\nimport { defaultBevel, reliefLayers, shadowOffset, type ReliefOptions } from \"./relief\";\n\n/**\n * The parts of a 2D canvas context the renderer uses. A browser `CanvasRenderingContext2D`\n * or `OffscreenCanvasRenderingContext2D` fits, and so do Node canvases such as\n * `@napi-rs/canvas` or `skia-canvas`.\n */\nexport interface CanvasContextLike {\n save(): void;\n restore(): void;\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;\n beginPath(): void;\n moveTo(x: number, y: number): void;\n lineTo(x: number, y: number): void;\n arc(x: number, y: number, radius: number, start: number, end: number, counterclockwise?: boolean): void;\n closePath(): void;\n fill(fillRule?: \"nonzero\" | \"evenodd\"): void;\n clip(fillRule?: \"nonzero\" | \"evenodd\"): void;\n stroke(): void;\n clearRect(x: number, y: number, w: number, h: number): void;\n drawImage(image: never, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;\n fillStyle: unknown;\n strokeStyle: unknown;\n lineWidth: number;\n lineJoin: unknown;\n globalAlpha: number;\n shadowColor: string;\n shadowBlur: number;\n shadowOffsetX: number;\n shadowOffsetY: number;\n}\n\n/** A loaded image: an HTMLImageElement, ImageBitmap, canvas, or a Node canvas image. */\nexport type CanvasImage = { width: number; height: number };\n\nexport interface CanvasRenderOptions\n extends Pick<\n RenderOptions,\n \"images\" | \"repeatImages\" | \"contentCells\" | \"placement\" | \"imageAspects\" | \"choose\" | \"imageFit\" | \"containWithin\" | \"imageFocus\" | \"fill\" | \"stroke\" | \"strokeWidth\" | \"background\"\n > {\n /** Raised tiles, as for SVG. */\n relief?: boolean | ReliefOptions;\n /** One image across all the cells (a URL), as for SVG. */\n backdrop?: string;\n /**\n * Loaded images by URL (see `loadImages`). Images not in it are skipped and their cells\n * show `fill`. `renderToCanvas` and `renderToPng` load them for you.\n */\n loaded?: ReadonlyMap<string, CanvasImage>;\n}\n\n/**\n * Draw a layout on a canvas context, scaled to fit `width` by `height` device pixels (the\n * canvas size by default) and centerd, like SVG's default `preserveAspectRatio`. It draws\n * what the SVG renderer does: background, cast shadows, fills, images, bevels and strokes.\n * Synchronous: pass loaded images in `loaded`.\n */\nexport function drawLayout(\n ctx: CanvasContextLike,\n layout: Layout,\n options: CanvasRenderOptions & { width?: number; height?: number } = {},\n): void {\n const canvas = (ctx as { canvas?: { width: number; height: number } }).canvas;\n const width = options.width ?? canvas?.width ?? layout.bounds.width;\n const height = options.height ?? canvas?.height ?? layout.bounds.height;\n const b = layout.bounds;\n const scale = Math.min(width / (b.width || 1), height / (b.height || 1)) || 1;\n const ox = (width - b.width * scale) / 2 - b.x * scale;\n const oy = (height - b.height * scale) / 2 - b.y * scale;\n const toLayout = () => ctx.setTransform(scale, 0, 0, scale, ox, oy);\n const styles = resolveCellStyles(layout, options);\n const loaded = options.loaded ?? new Map<string, CanvasImage>();\n const radius = layout.cornerRadius;\n const cellLoops = (c: Cell) => { const s = cellShape(c); return [s.outline, ...s.holes]; };\n\n ctx.save();\n toLayout();\n ctx.lineJoin = \"round\";\n\n if (options.background) {\n ctx.beginPath();\n for (const p of [layout.region, ...layout.holes]) tracePolygon(ctx, p, 0);\n ctx.fillStyle = options.background;\n ctx.fill(\"evenodd\");\n }\n\n if (layout.view) {\n // A window layout: tiles are drawn whole and cut to the view.\n ctx.beginPath();\n for (const v of layout.view) for (const p of [v.outer, ...v.holes]) tracePolygon(ctx, p, 0);\n ctx.clip(\"evenodd\");\n }\n\n const relief = options.relief === true ? {} : options.relief || undefined;\n const cast = relief && shadowOffset(relief);\n if (cast) {\n // Shadows only: draw the shapes far off to the side and offset their shadow back, so\n // only the blurred shadow lands, kept within the region.\n ctx.save();\n ctx.beginPath();\n for (const p of [layout.region, ...layout.holes]) tracePolygon(ctx, p, 0);\n ctx.clip(\"evenodd\");\n const away = (b.width + b.height) * 4;\n ctx.setTransform(scale, 0, 0, scale, ox - away * scale, oy);\n ctx.shadowColor = `rgba(0,0,0,${cast.opacity})`;\n // A canvas shadow blur is about twice the Gaussian standard deviation; shadow settings\n // are in device pixels, unaffected by the transform.\n ctx.shadowBlur = cast.blur * scale * 2;\n ctx.shadowOffsetX = (away + cast.dx) * scale;\n ctx.shadowOffsetY = cast.dy * scale;\n ctx.beginPath();\n for (const c of layout.cells) for (const p of cellLoops(c)) tracePolygon(ctx, p, radius);\n ctx.fillStyle = \"#000\";\n ctx.fill(\"evenodd\");\n ctx.restore();\n }\n\n const backdrop = options.backdrop ? loaded.get(options.backdrop) : undefined;\n if (backdrop) {\n ctx.save();\n ctx.beginPath();\n for (const c of layout.cells) for (const p of cellLoops(c)) tracePolygon(ctx, p, radius);\n ctx.clip(\"evenodd\");\n drawCover(ctx, backdrop, b);\n ctx.restore();\n }\n\n const bevel = relief ? (relief.bevel ?? defaultBevel(layout)) : 0;\n layout.cells.forEach((cell, i) => {\n const style = styles[i]!;\n ctx.beginPath();\n for (const p of cellLoops(cell)) tracePolygon(ctx, p, radius);\n if (!backdrop) {\n ctx.fillStyle = style.fill;\n ctx.fill(\"evenodd\");\n }\n const img = style.image ? loaded.get(style.image) : undefined;\n if (img) {\n ctx.save();\n ctx.clip(\"evenodd\");\n if (options.imageFit === \"contain\") {\n const aspect = options.imageAspects && style.slot >= 0 ? options.imageAspects[style.slot % options.imageAspects.length] : undefined;\n drawContain(ctx, img, safeArea(cell, layout, { aspect, within: options.containWithin }));\n } else {\n const focus = style.slot >= 0 ? (Array.isArray(options.images) ? options.imageFocus?.[style.slot % options.images.length] : undefined) : undefined;\n if (focus && img.width && img.height) {\n const r = coverRect(cell, layout, { aspect: img.width / img.height, focus });\n ctx.drawImage(img as never, 0, 0, img.width, img.height, r.x, r.y, r.width, r.height);\n } else drawCover(ctx, img, cellShape(cell).bbox);\n }\n ctx.restore();\n }\n if (relief && bevel > 0) {\n for (const layer of reliefLayers(layout, cell, relief, bevel)) {\n ctx.beginPath();\n for (const poly of layer.polygons) tracePolygon(ctx, poly, 0);\n ctx.globalAlpha = layer.opacity;\n ctx.fillStyle = layer.fill;\n ctx.fill();\n ctx.globalAlpha = 1;\n }\n }\n if (options.stroke) {\n ctx.beginPath();\n for (const p of cellLoops(cell)) tracePolygon(ctx, p, radius);\n ctx.strokeStyle = options.stroke;\n ctx.lineWidth = options.strokeWidth ?? 1;\n ctx.stroke();\n }\n });\n ctx.restore();\n}\n\n/** Add a polygon (with rounded corners) to the current path, as a closed subpath. */\nexport function tracePolygon(ctx: Pick<CanvasContextLike, \"moveTo\" | \"lineTo\" | \"arc\" | \"closePath\">, poly: Polygon, radius: number): void {\n if (poly.length < 3) return;\n if (radius <= 0) {\n ctx.moveTo(poly[0]!.x, poly[0]!.y);\n for (let i = 1; i < poly.length; i++) ctx.lineTo(poly[i]!.x, poly[i]!.y);\n ctx.closePath();\n return;\n }\n roundCorners(poly, radius).forEach((c, i) => {\n if (i === 0) ctx.moveTo(c.start.x, c.start.y);\n else ctx.lineTo(c.start.x, c.start.y);\n if (c.radius > 0) {\n const a0 = Math.atan2(c.start.y - c.center.y, c.start.x - c.center.x);\n // y points down, so increasing angles turn clockwise on screen: a positive sweep.\n ctx.arc(c.center.x, c.center.y, c.radius, a0, a0 + c.sweep, c.sweep < 0);\n }\n });\n ctx.closePath();\n}\n\n/** Draw `img` covering `box`, cropped to its shape and centerd (CSS `object-fit: cover`). */\nfunction drawCover(ctx: CanvasContextLike, img: CanvasImage, box: Rect) {\n if (!img.width || !img.height || !box.width || !box.height) return;\n const s = Math.max(box.width / img.width, box.height / img.height);\n const sw = box.width / s, sh = box.height / s;\n ctx.drawImage(img as never, (img.width - sw) / 2, (img.height - sh) / 2, sw, sh, box.x, box.y, box.width, box.height);\n}\n\n/** Draw `img` whole inside `box`, centerd (CSS `object-fit: contain`). */\nfunction drawContain(ctx: CanvasContextLike, img: CanvasImage, box: Rect) {\n if (!img.width || !img.height || !box.width || !box.height) return;\n const s = Math.min(box.width / img.width, box.height / img.height);\n const w = img.width * s, h = img.height * s;\n ctx.drawImage(img as never, 0, 0, img.width, img.height, box.x + (box.width - w) / 2, box.y + (box.height - h) / 2, w, h);\n}\n\n/** The image URLs a layout would draw with these options (cell images and the backdrop). */\nexport function imagesUsed(layout: Layout, options: CanvasRenderOptions = {}): string[] {\n const urls = new Set<string>();\n for (const s of resolveCellStyles(layout, options)) if (s.image) urls.add(s.image);\n if (options.backdrop) urls.add(options.backdrop);\n return [...urls];\n}\n\n/**\n * Load images for drawing (in the browser, with `crossOrigin = \"anonymous\"` so the canvas\n * can still be exported; the server must allow it). Images that fail are left out. Pass\n * your own `load` elsewhere, e.g. `loadImage` from a Node canvas package.\n */\nexport async function loadImages(\n urls: readonly string[],\n load: (url: string) => Promise<CanvasImage> = browserImage,\n): Promise<Map<string, CanvasImage>> {\n const out = new Map<string, CanvasImage>();\n await Promise.all(\n urls.map(async (url) => {\n try {\n out.set(url, await load(url));\n } catch {\n // Missing or blocked: the cell shows its fill.\n }\n }),\n );\n return out;\n}\n\nfunction browserImage(url: string): Promise<CanvasImage> {\n const Img = (globalThis as { Image?: new () => HTMLImageLike }).Image;\n if (!Img) return Promise.reject(new Error(\"No Image constructor: pass a load function\"));\n return new Promise((resolve, reject) => {\n const img = new Img();\n img.crossOrigin = \"anonymous\";\n img.onload = () => resolve(img);\n img.onerror = () => reject(new Error(`Could not load ${url}`));\n img.src = url;\n });\n}\n\ninterface HTMLImageLike extends CanvasImage {\n crossOrigin: string | null;\n src: string;\n onload: (() => void) | null;\n onerror: (() => void) | null;\n}\n\n/** A canvas that can be drawn on and exported (browser or offscreen canvas, or your own). */\nexport interface CanvasLike {\n width: number;\n height: number;\n getContext(type: \"2d\"): unknown;\n}\n\nexport interface RasterOptions extends CanvasRenderOptions {\n /** Output width in CSS pixels; the height follows the layout's shape. Defaults to the layout's width. */\n width?: number;\n /** Device pixels per CSS pixel, for sharp output on high-density screens. Defaults to 1. */\n pixelRatio?: number;\n /** Load an image (see `loadImages`). */\n loadImage?: (url: string) => Promise<CanvasImage>;\n}\n\n/**\n * Draw a layout onto `canvas`, sizing it to the layout (`width` × `pixelRatio`) and loading\n * its images first. Resolves to the canvas.\n */\nexport async function renderToCanvas<C extends CanvasLike>(layout: Layout, canvas: C, options: RasterOptions = {}): Promise<C> {\n const { w, h } = rasterSize(layout, options);\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext(\"2d\") as CanvasContextLike | null;\n if (!ctx) throw new Error(\"Could not get a 2D context from the canvas\");\n const loaded = options.loaded ?? (await loadImages(imagesUsed(layout, options), options.loadImage));\n ctx.clearRect(0, 0, w, h);\n drawLayout(ctx, layout, { ...options, loaded, width: w, height: h });\n return canvas;\n}\n\n/** Pixel size of the raster for a layout: `width` (default the layout's) times `pixelRatio`. */\nexport function rasterSize(layout: Layout, options: Pick<RasterOptions, \"width\" | \"pixelRatio\"> = {}): { w: number; h: number } {\n const b = layout.bounds;\n const cssWidth = options.width ?? b.width;\n const ratio = options.pixelRatio ?? 1;\n return { w: Math.max(1, Math.round(cssWidth * ratio)), h: Math.max(1, Math.round(((cssWidth * b.height) / (b.width || 1)) * ratio)) };\n}\n\n/**\n * Render a layout to a PNG (or JPEG / WebP with `type`) image, in the browser or a worker.\n * Images must load (and, from other sites, allow cross-origin use) or their cells show\n * their fill. Elsewhere, use `drawLayout` with your own canvas.\n */\nexport async function renderToPng(\n layout: Layout,\n options: RasterOptions & { type?: string; quality?: number; createCanvas?: (w: number, h: number) => CanvasLike } = {},\n): Promise<Blob> {\n const { w, h } = rasterSize(layout, options);\n const canvas = options.createCanvas ? options.createCanvas(w, h) : makeCanvas(w, h);\n await renderToCanvas(layout, canvas, options);\n const type = options.type ?? \"image/png\";\n const c = canvas as CanvasLike & {\n convertToBlob?: (o: { type: string; quality?: number }) => Promise<Blob>;\n toBlob?: (cb: (b: Blob | null) => void, type: string, quality?: number) => void;\n };\n if (c.convertToBlob) return c.convertToBlob({ type, quality: options.quality });\n if (c.toBlob) {\n return new Promise((resolve, reject) =>\n c.toBlob!((blob) => (blob ? resolve(blob) : reject(new Error(\"The canvas could not be exported\"))), type, options.quality),\n );\n }\n throw new Error(\"This canvas can't export images: use drawLayout and your canvas's own export\");\n}\n\nfunction makeCanvas(w: number, h: number): CanvasLike {\n const g = globalThis as { OffscreenCanvas?: new (w: number, h: number) => CanvasLike; document?: { createElement(t: \"canvas\"): CanvasLike } };\n if (g.OffscreenCanvas) return new g.OffscreenCanvas(w, h);\n if (g.document) {\n const c = g.document.createElement(\"canvas\");\n c.width = w;\n c.height = h;\n return c;\n }\n throw new Error(\"No canvas available: pass createCanvas, or use drawLayout with your own\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,IAAAA,eAA+M;;;ACL/M,kBAA+E;AA8BxE,SAAS,aAAa,QAAwB;AACnD,QAAM,IAAI,OAAO,MAAM;AACvB,MAAI,MAAM,EAAG,QAAO;AACpB,QAAM,OAAO,OAAO,MAAM,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,MAAM,CAAC,IAAI;AAC5D,SAAO,OAAO,KAAK,KAAK,IAAI;AAC9B;AAEA,IAAM,SAAS;AAcR,SAAS,aAAa,QAAgB,MAAY,QAAuB,OAA8B;AAC5G,QAAM,WAAW,OAAO,YAAY;AACpC,QAAM,SAAS,oBAAI,IAAuB;AAC1C,aAAW,aAAS,yBAAY,MAAM,QAAQ,EAAE,OAAO,OAAO,OAAO,OAAO,MAAM,CAAC,GAAG;AACpF,UAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,MAAM;AAC7C,QAAI,UAAU,EAAG;AACjB,UAAM,OAAO,OAAO,IAAI,KAAK;AAC7B,QAAI,KAAM,MAAK,KAAK,MAAM,OAAO;AAAA,QAC5B,QAAO,IAAI,OAAO,CAAC,MAAM,OAAO,CAAC;AAAA,EACxC;AACA,SAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,EACxB,KAAK,CAAC,GAAG,MAAM,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,EAC1B,IAAI,CAAC,CAAC,OAAO,QAAQ,OAAO;AAAA,IAC3B;A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AS,IAAI,SAAS,EAAE,KAAK,EAAE,CAAC,KAAK,KAAK,GAAG;AACnF;AAGO,SAAS,eAAe,QAAgB,OAAsB,CAAC,GAAW;AAC/E,SAAO,UAAU,UAAU,QAAQ,IAAI,CAAC;AAC1C;AAEA,IAAM,SAAS;AAEf,SAAS,MAAM,MAAwB,KAAqB;AAC1D,MAAI,OAAO,SAAS,SAAU,QAAO,IAAI,eAAe,IAAI;AAC5D,QAAM,OAAO,IAAI,gBAAgB,QAAQ,KAAK,GAAG;AACjD,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAK,KAAK,GAAG;AAC/C,QAAI,MAAM,UAAa,MAAM,QAAS,MAAK,aAAa,GAAG,OAAO,CAAC,CAAC;AAAA,EACtE;AACA,aAAW,SAAS,KAAK,SAAU,MAAK,YAAY,MAAM,OAAO,GAAG,CAAC;AACrE,SAAO;AACT;AAGO,SAAS,gBAAgB,QAAgB,OAAsB,CAAC,GAAG,MAAgB,WAAW,UAAyB;AAC5H,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,+EAA+E;AACzG,SAAO,MAAM,UAAU,QAAQ,IAAI,GAAG,GAAG;AAC3C;","names":["import_core","import_core"]}
1
+ {"version":3,"sources":["/Users/matthewputnam/code/andamento/packages/svg/dist/index.cjs","../src/index.ts","../src/relief.ts","../src/canvas.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACDA,uCAAyJ;ADGzJ;AACA;AETA;AA8BO,SAAS,YAAA,CAAa,MAAA,EAAwB;AACnD,EAAA,MAAM,EAAA,EAAI,MAAA,CAAO,KAAA,CAAM,MAAA;AACvB,EAAA,GAAA,CAAI,EAAA,IAAM,CAAA,EAAG,OAAO,CAAA;AACpB,EAAA,MAAM,KAAA,EAAO,MAAA,CAAO,KAAA,CAAM,MAAA,CAAO,CAAC,CAAA,EAAG,CAAA,EAAA,GAAM,EAAA,EAAI,CAAA,CAAE,IAAA,EAAM,CAAC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AAA;AAC7C,EAAA;AACwC,EAAA;AACjC,EAAA;AACT;AAG0F;AAC9D,EAAA;AACe,EAAA;AAC3C;ADiHqD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/matthewputnam/code/andamento/packages/svg/dist/index.cjs","sourcesContent":[null,"/**\n * Renders a layout to an SVG string or element, to a canvas, or to a PNG.\n *\n * @module @andamento/svg\n */\nimport { cellShape, coverRect, type Focus, safeArea, roundCorners, type Cell, type ContentCells, type ContentPlacement, type Layout, type Polygon } from \"@andamento/core\";\n\nimport { defaultBevel, reliefPaths, shadowOffset, type ReliefOptions } from \"./relief\";\nexport { defaultBevel, reliefLayers, reliefPaths, shadowOffset } from \"./relief\";\nexport type { ReliefLayer, ReliefOptions, ReliefPath } from \"./relief\";\n\nexport { defaultPalette } from \"./styles\";\nexport type { FillSource } from \"./styles\";\nimport { cellA11y, resolveCellStyles, type FillSource } from \"./styles\";\n\n/** Soft neutrals for tiles without content: visible as tiles, but quiet next to photos. */\nexport const neutralPalette = [\"#e7e5e4\", \"#d6d3d1\", \"#f5f5f4\", \"#dedad6\", \"#ecebe9\"];\n\nexport type ImageSource = readonly string[] | ((cell: Cell) => string | undefined);\n\nexport interface RenderOptions {\n /** Images: an array assigned in reading order, or a function per cell. */\n images?: ImageSource;\n /** Reuse the images array from the start when there are more cells than images. */\n repeatImages?: boolean;\n /** Which cells may hold an image from the `images` array (default \"all\"). */\n contentCells?: ContentCells;\n /** Where the images go when there are fewer than cells (default \"reading\"). */\n placement?: ContentPlacement;\n /**\n * Width / height of each image in `images`. When given, each image goes in a cell of\n * similar shape, to crop as little as possible (see `matchSlots`). Ignored with `repeatImages`.\n */\n imageAspects?: readonly number[];\n /**\n * How each image fills its cell: \"cover\" (default) fills the cell's bounding box and is\n * cropped to the cell's shape; \"contain\" shows the whole image inside the cell's safe area\n * (see `safeArea`), uncropped. Give `imageAspects` so the safe area has each image's shape.\n */\n imageFit?: \"cover\" | \"contain\";\n /**\n * With `imageFit: \"contain\"`, for cells an `edges: \"window\"` layout cuts: fit the image in\n * the whole tile (\"tile\", the default; partly hidden like the tile) or in the part that\n * shows (\"visible\"). See `SafeAreaOptions.within`.\n */\n containWithin?: \"tile\" | \"visible\";\n /**\n * Focal point of each image in `images` (by position; fractions of its width and height,\n * see `estimateFocus`): what to keep in view when \"cover\" crops it. It goes as near the\n * middle of what shows of its cell as covering the cell allows (see `coverRect`). Needs\n * each image's shape, from `imageAspects` or the focus's `aspect` (the canvas renderers\n * measure the images themselves).\n */\n imageFocus?: readonly (Focus | undefined)[];\n /** With `imageAspects`: \"shape\" also picks which cells get images by their shape. */\n choose?: \"placement\" | \"shape\";\n /**\n * Cell color when there is no image: a color, a palette (neighboring cells get\n * different entries), or a function. Defaults to `defaultPalette`.\n */\n fill?: FillSource;\n /**\n * Raised tiles: a lit bevel round each tile, and optionally a shadow cast into the grout.\n * `true` for the defaults. See `ReliefOptions`.\n */\n relief?: boolean | ReliefOptions;\n /** Outline drawn on top of each cell. */\n stroke?: string;\n strokeWidth?: number;\n /** Color painted over the whole region. Omit for transparent. */\n background?: string;\n /**\n * One image across all the cells (a URL): drawn once over the layout bounds (cropped to\n * cover them) and clipped to the cells, so each cell shows its piece. Cells' `fill` isn't\n * drawn; per-cell `images` still go on top.\n */\n backdrop?: string;\n /** Prefix for generated element ids; set it when several layouts share a page. */\n idPrefix?: string;\n /** Decimal places for coordinates. Defaults to 3. */\n precision?: number;\n /** Width/height attributes of the <svg>; it always gets a viewBox. */\n width?: string | number;\n height?: string | number;\n /** Accessible title. */\n title?: string;\n /**\n * Text alternative for each image in `images` (by position). Cells showing an image with\n * one become labeled images to assistive technology, and the SVG a group of them; the\n * other cells are hidden as decoration.\n */\n imageAlts?: readonly string[];\n}\n\nconst formatter = (precision: number) => (n: number) => {\n const s = n.toFixed(precision);\n // Trim trailing zeros: \"12.500\" -> \"12.5\", \"3.000\" -> \"3\", \"-0\" -> \"0\".\n const t = s.includes(\".\") ? s.replace(/\\.?0+$/, \"\") : s;\n return t === \"-0\" ? \"0\" : t;\n};\n\n/** `d` attribute for a polygon. With `radius`, corners are rounded with circular arcs. */\nexport function polygonToPath(p: Polygon, precision = 3, radius = 0): string {\n if (p.length === 0) return \"\";\n const f = formatter(precision);\n if (radius <= 0) return \"M\" + p.map((v) => `${f(v.x)} ${f(v.y)}`).join(\"L\") + \"Z\";\n const parts: string[] = [];\n for (const c of roundCorners(p, radius)) {\n parts.push(`${parts.length ? \"L\" : \"M\"}${f(c.start.x)} ${f(c.start.y)}`);\n if (c.radius > 0) {\n const r = f(c.radius);\n parts.push(`A${r} ${r} 0 0 ${c.sweep > 0 ? 1 : 0} ${f(c.end.x)} ${f(c.end.y)}`);\n }\n }\n return parts.join(\"\") + \"Z\";\n}\n\n/**\n * `d` attribute for a cell's outline, including the layout's corner rounding and any holes\n * (as extra subpaths; draw with `fill-rule=\"evenodd\"`). For a window cell this is the\n * whole tile (see `cellShape`); clip it to `viewPath`.\n */\nexport function cellPath(layout: Layout, cell: Cell, precision = 3): string {\n const s = cellShape(cell);\n return [s.outline, ...s.holes].map((p) => polygonToPath(p, precision, layout.cornerRadius)).join(\"\");\n}\n\n/**\n * `d` attribute for the area tiles show in (draw or clip with `evenodd`): `layout.view` in\n * a window layout, else the region with its holes.\n */\nexport function viewPath(layout: Layout, precision = 3): string {\n if (!layout.view) return regionPath(layout, precision);\n return layout.view.flatMap((v) => [v.outer, ...v.holes]).map((p) => polygonToPath(p, precision)).join(\"\");\n}\n\n/** `d` attribute for the region with its holes (draw with `fill-rule=\"evenodd\"`). */\nexport function regionPath(layout: Layout, precision = 3): string {\n return [layout.region, ...layout.holes].map((p) => polygonToPath(p, precision)).join(\"\");\n}\n\n\n\n\n\n/** Minimal element tree, serializable to a string or built into DOM nodes. */\nexport interface SvgNode {\n tag: string;\n attrs: Record<string, string | number | undefined>;\n children: (SvgNode | string)[];\n}\n\nconst el = (tag: string, attrs: SvgNode[\"attrs\"] = {}, children: SvgNode[\"children\"] = []): SvgNode => ({\n tag,\n attrs,\n children,\n});\n\nexport function toSvgTree(layout: Layout, opts: RenderOptions = {}): SvgNode {\n const precision = opts.precision ?? 3;\n const prefix = opts.idPrefix ?? \"andamento\";\n const { x, y, width, height } = layout.bounds;\n const styles = resolveCellStyles(layout, opts);\n const r = (n: number) => Number(n.toFixed(precision));\n\n const children: SvgNode[\"children\"] = [];\n if (opts.title) children.push(el(\"title\", {}, [opts.title]));\n if (opts.background) {\n children.push(el(\"path\", { d: regionPath(layout, precision), fill: opts.background, \"fill-rule\": \"evenodd\", class: \"andamento-region\" }));\n }\n\n // In a window layout, everything from here on is drawn whole and cut to the view.\n const start = children.length;\n if (opts.backdrop) {\n const clipId = `${prefix}-backdrop`;\n const shapes = layout.cells.map((cell) => el(\"path\", { d: cellPath(layout, cell, precision), \"clip-rule\": \"evenodd\" }));\n children.push(el(\"clipPath\", { id: clipId }, shapes));\n children.push(\n el(\"image\", {\n class: \"andamento-backdrop\",\n href: opts.backdrop,\n x: r(x),\n y: r(y),\n width: r(width),\n height: r(height),\n preserveAspectRatio: \"xMidYMid slice\",\n \"clip-path\": `url(#${clipId})`,\n }),\n );\n }\n\n const relief: ReliefOptions | undefined = opts.relief === true ? {} : opts.relief || undefined;\n const bevel = relief ? (relief.bevel ?? defaultBevel(layout)) : 0;\n const cast = relief && shadowOffset(relief);\n if (cast) {\n // Every tile's shape, moved away from the light and blurred, kept within the region.\n const regionId = `${prefix}-region`;\n const blurId = `${prefix}-shadow`;\n children.push(el(\"clipPath\", { id: regionId }, [el(\"path\", { d: regionPath(layout, precision), \"clip-rule\": \"evenodd\" })]));\n children.push(el(\"filter\", { id: blurId, x: \"-10%\", y: \"-10%\", width: \"120%\", height: \"120%\" }, [el(\"feGaussianBlur\", { stdDeviation: r(cast.blur) })]));\n children.push(\n el(\"g\", { class: \"andamento-shadow\", \"clip-path\": `url(#${regionId})` }, [\n el(\"path\", {\n d: layout.cells.map((c) => cellPath(layout, c, precision)).join(\"\"),\n \"fill-rule\": \"evenodd\",\n transform: `translate(${r(cast.dx)} ${r(cast.dy)})`,\n fill: \"#000\",\n \"fill-opacity\": cast.opacity,\n filter: `url(#${blurId})`,\n }),\n ]),\n );\n }\n\n layout.cells.forEach((cell, i) => {\n const d = cellPath(layout, cell, precision);\n const style = styles[i]!;\n const holed = !!cell.holes?.length;\n const parts: SvgNode[] = opts.backdrop ? [] : [el(\"path\", { d, fill: style.fill, \"fill-rule\": holed ? \"evenodd\" : undefined })];\n if (style.image) {\n const clipId = `${prefix}-clip-${cell.index}`;\n parts.unshift(el(\"clipPath\", { id: clipId }, [el(\"path\", { d, \"clip-rule\": holed ? \"evenodd\" : undefined })]));\n const contain = opts.imageFit === \"contain\";\n const aspect = contain && opts.imageAspects && style.slot >= 0 ? opts.imageAspects[style.slot] : undefined;\n const focus = !contain && style.slot >= 0 ? opts.imageFocus?.[style.slot] : undefined;\n const shape = focus ? (opts.imageAspects?.[style.slot] ?? focus.aspect) : undefined;\n const box = contain\n ? safeArea(cell, layout, { aspect, within: opts.containWithin })\n : focus && shape\n ? coverRect(cell, layout, { aspect: shape, focus })\n : cellShape(cell).bbox;\n parts.push(\n el(\"image\", {\n href: style.image,\n x: r(box.x),\n y: r(box.y),\n width: r(box.width),\n height: r(box.height),\n preserveAspectRatio: contain ? \"xMidYMid meet\" : \"xMidYMid slice\",\n \"clip-path\": `url(#${clipId})`,\n }),\n );\n }\n if (relief && bevel > 0) {\n for (const p of reliefPaths(layout, cell, relief, bevel, precision)) {\n parts.push(el(\"path\", { class: \"andamento-bevel\", d: p.d, fill: p.fill, \"fill-opacity\": p.opacity }));\n }\n }\n if (opts.stroke) {\n parts.push(el(\"path\", { d, fill: \"none\", stroke: opts.stroke, \"stroke-width\": opts.strokeWidth ?? 1 }));\n }\n children.push(\n el(\n \"g\",\n {\n class: \"andamento-cell\",\n \"data-cell-id\": cell.id,\n \"data-index\": cell.index,\n \"data-empty\": style.image ? undefined : \"\",\n \"data-boundary\": cell.boundary ? \"\" : undefined,\n ...cellA11y(style, opts.imageAlts),\n },\n parts,\n ),\n );\n });\n if (layout.view) {\n const viewId = `${prefix}-view`;\n const body = children.splice(start);\n children.push(el(\"clipPath\", { id: viewId }, [el(\"path\", { d: viewPath(layout, precision), \"clip-rule\": \"evenodd\" })]));\n children.push(el(\"g\", { class: \"andamento-view\", \"clip-path\": `url(#${viewId})` }, body));\n }\n\n return el(\n \"svg\",\n {\n xmlns: \"http://www.w3.org/2000/svg\",\n viewBox: `${r(x)} ${r(y)} ${r(width)} ${r(height)}`,\n width: opts.width,\n height: opts.height,\n role: opts.imageAlts?.length ? \"group\" : opts.title ? \"img\" : undefined,\n },\n children,\n );\n}\n\n\nconst escapeText = (s: string) => s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\nconst escapeAttr = (s: string) => escapeText(s).replace(/\"/g, \"&quot;\");\n\nexport function serialize(node: SvgNode | string): string {\n if (typeof node === \"string\") return escapeText(node);\n const attrs = Object.entries(node.attrs)\n .filter(([, v]) => v !== undefined)\n .map(([k, v]) => ` ${k}=\"${escapeAttr(String(v))}\"`)\n .join(\"\");\n if (node.children.length === 0) return `<${node.tag}${attrs}/>`;\n return `<${node.tag}${attrs}>${node.children.map(serialize).join(\"\")}</${node.tag}>`;\n}\n\n/** Render a layout to a standalone SVG document string. */\nexport function renderToString(layout: Layout, opts: RenderOptions = {}): string {\n return serialize(toSvgTree(layout, opts));\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\nfunction build(node: SvgNode | string, doc: Document): Node {\n if (typeof node === \"string\") return doc.createTextNode(node);\n const elem = doc.createElementNS(SVG_NS, node.tag);\n for (const [k, v] of Object.entries(node.attrs)) {\n if (v !== undefined && k !== \"xmlns\") elem.setAttribute(k, String(v));\n }\n for (const child of node.children) elem.appendChild(build(child, doc));\n return elem;\n}\n\n/** Render a layout to a live <svg> element. */\nexport function renderToElement(layout: Layout, opts: RenderOptions = {}, doc: Document = globalThis.document): SVGSVGElement {\n if (!doc) throw new Error(\"renderToElement needs a DOM Document; pass one explicitly outside the browser\");\n return build(toSvgTree(layout, opts), doc) as SVGSVGElement;\n}\n\nexport { drawLayout, imagesUsed, loadImages, rasterSize, renderToCanvas, renderToPng, tracePolygon } from \"./canvas\";\nexport type { CanvasContextLike, CanvasImage, CanvasLike, CanvasRenderOptions, RasterOptions } from \"./canvas\";\n","import { bevelFacets, lightVector, type Cell, type Layout, type Polygon } from \"@andamento/core\";\n\n/**\n * Makes tiles look raised: a bevel round each tile's edges, lit from one side, and\n * optionally a shadow each tile casts into the grout (the gaps) on the other.\n */\nexport interface ReliefOptions {\n /** Bevel width in layout units. Defaults to 8% of a typical tile's size; 0 for none. */\n bevel?: number;\n /** Direction the light comes from: degrees clockwise from the top (default 315, top left). */\n light?: number;\n /** Opacity of the brightest highlight and the darkest bevel shadow, 0–1. Defaults to 0.4. */\n strength?: number;\n /** How far tiles' shadows fall into the grout, in layout units (default 0: no shadow). */\n shadow?: number;\n /** Blur of the cast shadow (standard deviation, layout units). Defaults to `shadow`. */\n shadowBlur?: number;\n /** Opacity of the cast shadow. Defaults to 0.35. */\n shadowOpacity?: number;\n}\n\n/** One layer of a cell's bevel: all its faces of about the same shade, as one path. */\nexport interface ReliefPath {\n d: string;\n /** \"#fff\" for highlights, \"#000\" for shadows. */\n fill: string;\n opacity: number;\n}\n\n/** The default bevel width for a layout: 8% of the square root of the mean tile area. */\nexport function defaultBevel(layout: Layout): number {\n const n = layout.cells.length;\n if (n === 0) return 0;\n const mean = layout.cells.reduce((s, c) => s + c.area, 0) / n;\n return 0.08 * Math.sqrt(mean);\n}\n\nconst LEVELS = 8;\n\n/** One layer of a cell's bevel as polygons: all its faces of about the same shade. */\nexport interface ReliefLayer {\n polygons: Polygon[];\n /** \"#fff\" for highlights, \"#000\" for shadows. */\n fill: string;\n opacity: number;\n}\n\n/**\n * A cell's bevel grouped into a few shade levels, in layout coordinates, to draw over the\n * cell's content. Pass the bevel width from `defaultBevel` if not set.\n */\nexport function reliefLayers(layout: Layout, cell: Cell, relief: ReliefOptions, bevel: number): ReliefLayer[] {\n const strength = relief.strength ?? 0.4;\n const groups = new Map<number, Polygon[]>();\n for (const facet of bevelFacets(cell, layout, { width: bevel, light: relief.light })) {\n const level = Math.round(facet.shade * LEVELS);\n if (level === 0) continue;\n const list = groups.get(level);\n if (list) list.push(facet.polygon);\n else groups.set(level, [facet.polygon]);\n }\n return [...groups.entries()]\n .sort((a, b) => a[0] - b[0])\n .map(([level, polygons]) => ({\n polygons,\n fill: level > 0 ? \"#fff\" : \"#000\",\n opacity: Number(((Math.abs(level) / LEVELS) * strength).toFixed(3)),\n }));\n}\n\n/** `reliefLayers` as SVG paths, one per layer. */\nexport function reliefPaths(layout: Layout, cell: Cell, relief: ReliefOptions, bevel: number, precision = 3): ReliefPath[] {\n const f = (n: number) => Number(n.toFixed(precision));\n return reliefLayers(layout, cell, relief, bevel).map(({ polygons, fill, opacity }) => ({\n d: polygons.map((poly) => \"M\" + poly.map((p) => `${f(p.x)} ${f(p.y)}`).join(\"L\") + \"Z\").join(\"\"),\n fill,\n opacity,\n }));\n}\n\n/** Offset of the cast shadow (away from the light), or undefined for none. */\nexport function shadowOffset(relief: ReliefOptions): { dx: number; dy: number; blur: number; opacity: number } | undefined {\n const s = relief.shadow ?? 0;\n if (!(s > 0)) return undefined;\n const l = lightVector(relief.light);\n return { dx: -l.x * s, dy: -l.y * s, blur: relief.shadowBlur ?? s, opacity: relief.shadowOpacity ?? 0.35 };\n}\n","import { cellShape, coverRect, roundCorners, safeArea, type Cell, type Layout, type Polygon, type Rect } from \"@andamento/core\";\nimport type { RenderOptions } from \"./index\";\nimport { resolveCellStyles } from \"./styles\";\nimport { defaultBevel, reliefLayers, shadowOffset, type ReliefOptions } from \"./relief\";\n\n/**\n * The parts of a 2D canvas context the renderer uses. A browser `CanvasRenderingContext2D`\n * or `OffscreenCanvasRenderingContext2D` fits, and so do Node canvases such as\n * `@napi-rs/canvas` or `skia-canvas`.\n */\nexport interface CanvasContextLike {\n save(): void;\n restore(): void;\n setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;\n beginPath(): void;\n moveTo(x: number, y: number): void;\n lineTo(x: number, y: number): void;\n arc(x: number, y: number, radius: number, start: number, end: number, counterclockwise?: boolean): void;\n closePath(): void;\n fill(fillRule?: \"nonzero\" | \"evenodd\"): void;\n clip(fillRule?: \"nonzero\" | \"evenodd\"): void;\n stroke(): void;\n clearRect(x: number, y: number, w: number, h: number): void;\n drawImage(image: never, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;\n fillStyle: unknown;\n strokeStyle: unknown;\n lineWidth: number;\n lineJoin: unknown;\n globalAlpha: number;\n shadowColor: string;\n shadowBlur: number;\n shadowOffsetX: number;\n shadowOffsetY: number;\n}\n\n/** A loaded image: an HTMLImageElement, ImageBitmap, canvas, or a Node canvas image. */\nexport type CanvasImage = { width: number; height: number };\n\nexport interface CanvasRenderOptions\n extends Pick<\n RenderOptions,\n \"images\" | \"repeatImages\" | \"contentCells\" | \"placement\" | \"imageAspects\" | \"choose\" | \"imageFit\" | \"containWithin\" | \"imageFocus\" | \"fill\" | \"stroke\" | \"strokeWidth\" | \"background\"\n > {\n /** Raised tiles, as for SVG. */\n relief?: boolean | ReliefOptions;\n /** One image across all the cells (a URL), as for SVG. */\n backdrop?: string;\n /**\n * Loaded images by URL (see `loadImages`). Images not in it are skipped and their cells\n * show `fill`. `renderToCanvas` and `renderToPng` load them for you.\n */\n loaded?: ReadonlyMap<string, CanvasImage>;\n}\n\n/**\n * Draw a layout on a canvas context, scaled to fit `width` by `height` device pixels (the\n * canvas size by default) and centerd, like SVG's default `preserveAspectRatio`. It draws\n * what the SVG renderer does: background, cast shadows, fills, images, bevels and strokes.\n * Synchronous: pass loaded images in `loaded`.\n */\nexport function drawLayout(\n ctx: CanvasContextLike,\n layout: Layout,\n options: CanvasRenderOptions & { width?: number; height?: number } = {},\n): void {\n const canvas = (ctx as { canvas?: { width: number; height: number } }).canvas;\n const width = options.width ?? canvas?.width ?? layout.bounds.width;\n const height = options.height ?? canvas?.height ?? layout.bounds.height;\n const b = layout.bounds;\n const scale = Math.min(width / (b.width || 1), height / (b.height || 1)) || 1;\n const ox = (width - b.width * scale) / 2 - b.x * scale;\n const oy = (height - b.height * scale) / 2 - b.y * scale;\n const toLayout = () => ctx.setTransform(scale, 0, 0, scale, ox, oy);\n const styles = resolveCellStyles(layout, options);\n const loaded = options.loaded ?? new Map<string, CanvasImage>();\n const radius = layout.cornerRadius;\n const cellLoops = (c: Cell) => { const s = cellShape(c); return [s.outline, ...s.holes]; };\n\n ctx.save();\n toLayout();\n ctx.lineJoin = \"round\";\n\n if (options.background) {\n ctx.beginPath();\n for (const p of [layout.region, ...layout.holes]) tracePolygon(ctx, p, 0);\n ctx.fillStyle = options.background;\n ctx.fill(\"evenodd\");\n }\n\n if (layout.view) {\n // A window layout: tiles are drawn whole and cut to the view.\n ctx.beginPath();\n for (const v of layout.view) for (const p of [v.outer, ...v.holes]) tracePolygon(ctx, p, 0);\n ctx.clip(\"evenodd\");\n }\n\n const relief = options.relief === true ? {} : options.relief || undefined;\n const cast = relief && shadowOffset(relief);\n if (cast) {\n // Shadows only: draw the shapes far off to the side and offset their shadow back, so\n // only the blurred shadow lands, kept within the region.\n ctx.save();\n ctx.beginPath();\n for (const p of [layout.region, ...layout.holes]) tracePolygon(ctx, p, 0);\n ctx.clip(\"evenodd\");\n const away = (b.width + b.height) * 4;\n ctx.setTransform(scale, 0, 0, scale, ox - away * scale, oy);\n ctx.shadowColor = `rgba(0,0,0,${cast.opacity})`;\n // A canvas shadow blur is about twice the Gaussian standard deviation; shadow settings\n // are in device pixels, unaffected by the transform.\n ctx.shadowBlur = cast.blur * scale * 2;\n ctx.shadowOffsetX = (away + cast.dx) * scale;\n ctx.shadowOffsetY = cast.dy * scale;\n ctx.beginPath();\n for (const c of layout.cells) for (const p of cellLoops(c)) tracePolygon(ctx, p, radius);\n ctx.fillStyle = \"#000\";\n ctx.fill(\"evenodd\");\n ctx.restore();\n }\n\n const backdrop = options.backdrop ? loaded.get(options.backdrop) : undefined;\n if (backdrop) {\n ctx.save();\n ctx.beginPath();\n for (const c of layout.cells) for (const p of cellLoops(c)) tracePolygon(ctx, p, radius);\n ctx.clip(\"evenodd\");\n drawCover(ctx, backdrop, b);\n ctx.restore();\n }\n\n const bevel = relief ? (relief.bevel ?? defaultBevel(layout)) : 0;\n layout.cells.forEach((cell, i) => {\n const style = styles[i]!;\n ctx.beginPath();\n for (const p of cellLoops(cell)) tracePolygon(ctx, p, radius);\n if (!backdrop) {\n ctx.fillStyle = style.fill;\n ctx.fill(\"evenodd\");\n }\n const img = style.image ? loaded.get(style.image) : undefined;\n if (img) {\n ctx.save();\n ctx.clip(\"evenodd\");\n if (options.imageFit === \"contain\") {\n const aspect = options.imageAspects && style.slot >= 0 ? options.imageAspects[style.slot] : undefined;\n drawContain(ctx, img, safeArea(cell, layout, { aspect, within: options.containWithin }));\n } else {\n const focus = style.slot >= 0 ? options.imageFocus?.[style.slot] : undefined;\n if (focus && img.width && img.height) {\n const r = coverRect(cell, layout, { aspect: img.width / img.height, focus });\n ctx.drawImage(img as never, 0, 0, img.width, img.height, r.x, r.y, r.width, r.height);\n } else drawCover(ctx, img, cellShape(cell).bbox);\n }\n ctx.restore();\n }\n if (relief && bevel > 0) {\n for (const layer of reliefLayers(layout, cell, relief, bevel)) {\n ctx.beginPath();\n for (const poly of layer.polygons) tracePolygon(ctx, poly, 0);\n ctx.globalAlpha = layer.opacity;\n ctx.fillStyle = layer.fill;\n ctx.fill();\n ctx.globalAlpha = 1;\n }\n }\n if (options.stroke) {\n ctx.beginPath();\n for (const p of cellLoops(cell)) tracePolygon(ctx, p, radius);\n ctx.strokeStyle = options.stroke;\n ctx.lineWidth = options.strokeWidth ?? 1;\n ctx.stroke();\n }\n });\n ctx.restore();\n}\n\n/** Add a polygon (with rounded corners) to the current path, as a closed subpath. */\nexport function tracePolygon(ctx: Pick<CanvasContextLike, \"moveTo\" | \"lineTo\" | \"arc\" | \"closePath\">, poly: Polygon, radius: number): void {\n if (poly.length < 3) return;\n if (radius <= 0) {\n ctx.moveTo(poly[0]!.x, poly[0]!.y);\n for (let i = 1; i < poly.length; i++) ctx.lineTo(poly[i]!.x, poly[i]!.y);\n ctx.closePath();\n return;\n }\n roundCorners(poly, radius).forEach((c, i) => {\n if (i === 0) ctx.moveTo(c.start.x, c.start.y);\n else ctx.lineTo(c.start.x, c.start.y);\n if (c.radius > 0) {\n const a0 = Math.atan2(c.start.y - c.center.y, c.start.x - c.center.x);\n // y points down, so increasing angles turn clockwise on screen: a positive sweep.\n ctx.arc(c.center.x, c.center.y, c.radius, a0, a0 + c.sweep, c.sweep < 0);\n }\n });\n ctx.closePath();\n}\n\n/** Draw `img` covering `box`, cropped to its shape and centerd (CSS `object-fit: cover`). */\nfunction drawCover(ctx: CanvasContextLike, img: CanvasImage, box: Rect) {\n if (!img.width || !img.height || !box.width || !box.height) return;\n const s = Math.max(box.width / img.width, box.height / img.height);\n const sw = box.width / s, sh = box.height / s;\n ctx.drawImage(img as never, (img.width - sw) / 2, (img.height - sh) / 2, sw, sh, box.x, box.y, box.width, box.height);\n}\n\n/** Draw `img` whole inside `box`, centerd (CSS `object-fit: contain`). */\nfunction drawContain(ctx: CanvasContextLike, img: CanvasImage, box: Rect) {\n if (!img.width || !img.height || !box.width || !box.height) return;\n const s = Math.min(box.width / img.width, box.height / img.height);\n const w = img.width * s, h = img.height * s;\n ctx.drawImage(img as never, 0, 0, img.width, img.height, box.x + (box.width - w) / 2, box.y + (box.height - h) / 2, w, h);\n}\n\n/** The image URLs a layout would draw with these options (cell images and the backdrop). */\nexport function imagesUsed(layout: Layout, options: CanvasRenderOptions = {}): string[] {\n const urls = new Set<string>();\n for (const s of resolveCellStyles(layout, options)) if (s.image) urls.add(s.image);\n if (options.backdrop) urls.add(options.backdrop);\n return [...urls];\n}\n\n/**\n * Load images for drawing (in the browser, with `crossOrigin = \"anonymous\"` so the canvas\n * can still be exported; the server must allow it). Images that fail are left out. Pass\n * your own `load` elsewhere, e.g. `loadImage` from a Node canvas package.\n */\nexport async function loadImages(\n urls: readonly string[],\n load: (url: string) => Promise<CanvasImage> = browserImage,\n): Promise<Map<string, CanvasImage>> {\n const out = new Map<string, CanvasImage>();\n await Promise.all(\n urls.map(async (url) => {\n try {\n out.set(url, await load(url));\n } catch {\n // Missing or blocked: the cell shows its fill.\n }\n }),\n );\n return out;\n}\n\nfunction browserImage(url: string): Promise<CanvasImage> {\n const Img = (globalThis as { Image?: new () => HTMLImageLike }).Image;\n if (!Img) return Promise.reject(new Error(\"No Image constructor: pass a load function\"));\n return new Promise((resolve, reject) => {\n const img = new Img();\n img.crossOrigin = \"anonymous\";\n img.onload = () => resolve(img);\n img.onerror = () => reject(new Error(`Could not load ${url}`));\n img.src = url;\n });\n}\n\ninterface HTMLImageLike extends CanvasImage {\n crossOrigin: string | null;\n src: string;\n onload: (() => void) | null;\n onerror: (() => void) | null;\n}\n\n/** A canvas that can be drawn on and exported (browser or offscreen canvas, or your own). */\nexport interface CanvasLike {\n width: number;\n height: number;\n getContext(type: \"2d\"): unknown;\n}\n\nexport interface RasterOptions extends CanvasRenderOptions {\n /** Output width in CSS pixels; the height follows the layout's shape. Defaults to the layout's width. */\n width?: number;\n /** Device pixels per CSS pixel, for sharp output on high-density screens. Defaults to 1. */\n pixelRatio?: number;\n /** Load an image (see `loadImages`). */\n loadImage?: (url: string) => Promise<CanvasImage>;\n}\n\n/**\n * Draw a layout onto `canvas`, sizing it to the layout (`width` × `pixelRatio`) and loading\n * its images first. Resolves to the canvas.\n */\nexport async function renderToCanvas<C extends CanvasLike>(layout: Layout, canvas: C, options: RasterOptions = {}): Promise<C> {\n const { w, h } = rasterSize(layout, options);\n canvas.width = w;\n canvas.height = h;\n const ctx = canvas.getContext(\"2d\") as CanvasContextLike | null;\n if (!ctx) throw new Error(\"Could not get a 2D context from the canvas\");\n const loaded = options.loaded ?? (await loadImages(imagesUsed(layout, options), options.loadImage));\n ctx.clearRect(0, 0, w, h);\n drawLayout(ctx, layout, { ...options, loaded, width: w, height: h });\n return canvas;\n}\n\n/** Pixel size of the raster for a layout: `width` (default the layout's) times `pixelRatio`. */\nexport function rasterSize(layout: Layout, options: Pick<RasterOptions, \"width\" | \"pixelRatio\"> = {}): { w: number; h: number } {\n const b = layout.bounds;\n const cssWidth = options.width ?? b.width;\n const ratio = options.pixelRatio ?? 1;\n return { w: Math.max(1, Math.round(cssWidth * ratio)), h: Math.max(1, Math.round(((cssWidth * b.height) / (b.width || 1)) * ratio)) };\n}\n\n/**\n * Render a layout to a PNG (or JPEG / WebP with `type`) image, in the browser or a worker.\n * Images must load (and, from other sites, allow cross-origin use) or their cells show\n * their fill. Elsewhere, use `drawLayout` with your own canvas.\n */\nexport async function renderToPng(\n layout: Layout,\n options: RasterOptions & { type?: string; quality?: number; createCanvas?: (w: number, h: number) => CanvasLike } = {},\n): Promise<Blob> {\n const { w, h } = rasterSize(layout, options);\n const canvas = options.createCanvas ? options.createCanvas(w, h) : makeCanvas(w, h);\n await renderToCanvas(layout, canvas, options);\n const type = options.type ?? \"image/png\";\n const c = canvas as CanvasLike & {\n convertToBlob?: (o: { type: string; quality?: number }) => Promise<Blob>;\n toBlob?: (cb: (b: Blob | null) => void, type: string, quality?: number) => void;\n };\n if (c.convertToBlob) return c.convertToBlob({ type, quality: options.quality });\n if (c.toBlob) {\n return new Promise((resolve, reject) =>\n c.toBlob!((blob) => (blob ? resolve(blob) : reject(new Error(\"The canvas could not be exported\"))), type, options.quality),\n );\n }\n throw new Error(\"This canvas can't export images: use drawLayout and your canvas's own export\");\n}\n\nfunction makeCanvas(w: number, h: number): CanvasLike {\n const g = globalThis as { OffscreenCanvas?: new (w: number, h: number) => CanvasLike; document?: { createElement(t: \"canvas\"): CanvasLike } };\n if (g.OffscreenCanvas) return new g.OffscreenCanvas(w, h);\n if (g.document) {\n const c = g.document.createElement(\"canvas\");\n c.width = w;\n c.height = h;\n return c;\n }\n throw new Error(\"No canvas available: pass createCanvas, or use drawLayout with your own\");\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Polygon, Layout, Cell, ContentCells, ContentPlacement, Focus, CellFill } from '@andamento/core';
1
+ import { Polygon, Layout, Cell, CellFill, ContentCells, ContentPlacement, Focus } from '@andamento/core';
2
2
 
3
3
  /**
4
4
  * Makes tiles look raised: a bevel round each tile's edges, lit from one side, and
@@ -49,6 +49,30 @@ declare function shadowOffset(relief: ReliefOptions): {
49
49
  opacity: number;
50
50
  } | undefined;
51
51
 
52
+ declare const defaultPalette: string[];
53
+ /** A color, a palette (neighboring cells get different entries), or a color per cell. */
54
+ type FillSource = string | readonly string[] | CellFill;
55
+ interface CellStyle {
56
+ fill: string;
57
+ image?: string;
58
+ /** Which item of `images` the cell shows (-1 if none or if `images` is a function). */
59
+ slot: number;
60
+ }
61
+ /**
62
+ * Fill color per cell (by `cell.index`): a color, a palette (neighboring cells get
63
+ * different entries), or a function.
64
+ */
65
+ declare function resolveFills(layout: Layout, fill: FillSource): string[];
66
+ type StyleOptions = Pick<RenderOptions, "images" | "repeatImages" | "fill" | "contentCells" | "placement" | "imageAspects" | "choose">;
67
+ /** Resolve the fill color and image for every cell (shared by the SVG and React renderers). */
68
+ declare function resolveCellStyles(layout: Layout, opts?: StyleOptions): CellStyle[];
69
+ /** With `imageAlts`: a cell showing a described image is an image; the rest is decoration. */
70
+ declare function cellA11y(style: CellStyle, alts: readonly string[] | undefined): {
71
+ role?: "img";
72
+ "aria-label"?: string;
73
+ "aria-hidden"?: "true";
74
+ };
75
+
52
76
  /**
53
77
  * The parts of a 2D canvas context the renderer uses. A browser `CanvasRenderingContext2D`
54
78
  * or `OffscreenCanvasRenderingContext2D` fits, and so do Node canvases such as
@@ -155,12 +179,9 @@ declare function renderToPng(layout: Layout, options?: RasterOptions & {
155
179
  * @module @andamento/svg
156
180
  */
157
181
 
158
- declare const defaultPalette: string[];
159
182
  /** Soft neutrals for tiles without content: visible as tiles, but quiet next to photos. */
160
183
  declare const neutralPalette: string[];
161
184
  type ImageSource = readonly string[] | ((cell: Cell) => string | undefined);
162
- /** A color, a palette (neighboring cells get different entries), or a color per cell. */
163
- type FillSource = string | readonly string[] | CellFill;
164
185
  interface RenderOptions {
165
186
  /** Images: an array assigned in reading order, or a function per cell. */
166
187
  images?: ImageSource;
@@ -249,20 +270,6 @@ declare function cellPath(layout: Layout, cell: Cell, precision?: number): strin
249
270
  declare function viewPath(layout: Layout, precision?: number): string;
250
271
  /** `d` attribute for the region with its holes (draw with `fill-rule="evenodd"`). */
251
272
  declare function regionPath(layout: Layout, precision?: number): string;
252
- interface CellStyle {
253
- fill: string;
254
- image?: string;
255
- /** Which item of `images` the cell shows (-1 if none or if `images` is a function). */
256
- slot: number;
257
- }
258
- /**
259
- * Fill color per cell (by `cell.index`): a color, a palette (neighboring cells get
260
- * different entries), or a function.
261
- */
262
- declare function resolveFills(layout: Layout, fill: FillSource): string[];
263
- type StyleOptions = Pick<RenderOptions, "images" | "repeatImages" | "fill" | "contentCells" | "placement" | "imageAspects" | "choose">;
264
- /** Resolve the fill color and image for every cell (shared by the SVG and React renderers). */
265
- declare function resolveCellStyles(layout: Layout, opts?: StyleOptions): CellStyle[];
266
273
  /** Minimal element tree, serializable to a string or built into DOM nodes. */
267
274
  interface SvgNode {
268
275
  tag: string;
@@ -270,16 +277,10 @@ interface SvgNode {
270
277
  children: (SvgNode | string)[];
271
278
  }
272
279
  declare function toSvgTree(layout: Layout, opts?: RenderOptions): SvgNode;
273
- /** With `imageAlts`: a cell showing a described image is an image; the rest is decoration. */
274
- declare function cellA11y(style: CellStyle, alts: readonly string[] | undefined): {
275
- role?: "img";
276
- "aria-label"?: string;
277
- "aria-hidden"?: "true";
278
- };
279
280
  declare function serialize(node: SvgNode | string): string;
280
281
  /** Render a layout to a standalone SVG document string. */
281
282
  declare function renderToString(layout: Layout, opts?: RenderOptions): string;
282
283
  /** Render a layout to a live <svg> element. */
283
284
  declare function renderToElement(layout: Layout, opts?: RenderOptions, doc?: Document): SVGSVGElement;
284
285
 
285
- export { type CanvasContextLike, type CanvasImage, type CanvasLike, type CanvasRenderOptions, type CellStyle, type FillSource, type ImageSource, type RasterOptions, type ReliefLayer, type ReliefOptions, type ReliefPath, type RenderOptions, type SvgNode, cellA11y, cellPath, defaultBevel, defaultPalette, drawLayout, imagesUsed, loadImages, neutralPalette, polygonToPath, rasterSize, regionPath, reliefLayers, reliefPaths, renderToCanvas, renderToElement, renderToPng, renderToString, resolveCellStyles, resolveFills, serialize, shadowOffset, toSvgTree, tracePolygon, viewPath };
286
+ export { type CellStyle as C, type CanvasContextLike, type CanvasImage, type CanvasLike, type CanvasRenderOptions, type FillSource, type ImageSource, type RasterOptions, type ReliefLayer, type ReliefOptions, type ReliefPath, type RenderOptions, type SvgNode, resolveFills as a, cellA11y as c, cellPath, defaultBevel, defaultPalette, drawLayout, imagesUsed, loadImages, neutralPalette, polygonToPath, resolveCellStyles as r, rasterSize, regionPath, reliefLayers, reliefPaths, renderToCanvas, renderToElement, renderToPng, renderToString, serialize, shadowOffset, toSvgTree, tracePolygon, viewPath };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Polygon, Layout, Cell, ContentCells, ContentPlacement, Focus, CellFill } from '@andamento/core';
1
+ import { Polygon, Layout, Cell, CellFill, ContentCells, ContentPlacement, Focus } from '@andamento/core';
2
2
 
3
3
  /**
4
4
  * Makes tiles look raised: a bevel round each tile's edges, lit from one side, and
@@ -49,6 +49,30 @@ declare function shadowOffset(relief: ReliefOptions): {
49
49
  opacity: number;
50
50
  } | undefined;
51
51
 
52
+ declare const defaultPalette: string[];
53
+ /** A color, a palette (neighboring cells get different entries), or a color per cell. */
54
+ type FillSource = string | readonly string[] | CellFill;
55
+ interface CellStyle {
56
+ fill: string;
57
+ image?: string;
58
+ /** Which item of `images` the cell shows (-1 if none or if `images` is a function). */
59
+ slot: number;
60
+ }
61
+ /**
62
+ * Fill color per cell (by `cell.index`): a color, a palette (neighboring cells get
63
+ * different entries), or a function.
64
+ */
65
+ declare function resolveFills(layout: Layout, fill: FillSource): string[];
66
+ type StyleOptions = Pick<RenderOptions, "images" | "repeatImages" | "fill" | "contentCells" | "placement" | "imageAspects" | "choose">;
67
+ /** Resolve the fill color and image for every cell (shared by the SVG and React renderers). */
68
+ declare function resolveCellStyles(layout: Layout, opts?: StyleOptions): CellStyle[];
69
+ /** With `imageAlts`: a cell showing a described image is an image; the rest is decoration. */
70
+ declare function cellA11y(style: CellStyle, alts: readonly string[] | undefined): {
71
+ role?: "img";
72
+ "aria-label"?: string;
73
+ "aria-hidden"?: "true";
74
+ };
75
+
52
76
  /**
53
77
  * The parts of a 2D canvas context the renderer uses. A browser `CanvasRenderingContext2D`
54
78
  * or `OffscreenCanvasRenderingContext2D` fits, and so do Node canvases such as
@@ -155,12 +179,9 @@ declare function renderToPng(layout: Layout, options?: RasterOptions & {
155
179
  * @module @andamento/svg
156
180
  */
157
181
 
158
- declare const defaultPalette: string[];
159
182
  /** Soft neutrals for tiles without content: visible as tiles, but quiet next to photos. */
160
183
  declare const neutralPalette: string[];
161
184
  type ImageSource = readonly string[] | ((cell: Cell) => string | undefined);
162
- /** A color, a palette (neighboring cells get different entries), or a color per cell. */
163
- type FillSource = string | readonly string[] | CellFill;
164
185
  interface RenderOptions {
165
186
  /** Images: an array assigned in reading order, or a function per cell. */
166
187
  images?: ImageSource;
@@ -249,20 +270,6 @@ declare function cellPath(layout: Layout, cell: Cell, precision?: number): strin
249
270
  declare function viewPath(layout: Layout, precision?: number): string;
250
271
  /** `d` attribute for the region with its holes (draw with `fill-rule="evenodd"`). */
251
272
  declare function regionPath(layout: Layout, precision?: number): string;
252
- interface CellStyle {
253
- fill: string;
254
- image?: string;
255
- /** Which item of `images` the cell shows (-1 if none or if `images` is a function). */
256
- slot: number;
257
- }
258
- /**
259
- * Fill color per cell (by `cell.index`): a color, a palette (neighboring cells get
260
- * different entries), or a function.
261
- */
262
- declare function resolveFills(layout: Layout, fill: FillSource): string[];
263
- type StyleOptions = Pick<RenderOptions, "images" | "repeatImages" | "fill" | "contentCells" | "placement" | "imageAspects" | "choose">;
264
- /** Resolve the fill color and image for every cell (shared by the SVG and React renderers). */
265
- declare function resolveCellStyles(layout: Layout, opts?: StyleOptions): CellStyle[];
266
273
  /** Minimal element tree, serializable to a string or built into DOM nodes. */
267
274
  interface SvgNode {
268
275
  tag: string;
@@ -270,16 +277,10 @@ interface SvgNode {
270
277
  children: (SvgNode | string)[];
271
278
  }
272
279
  declare function toSvgTree(layout: Layout, opts?: RenderOptions): SvgNode;
273
- /** With `imageAlts`: a cell showing a described image is an image; the rest is decoration. */
274
- declare function cellA11y(style: CellStyle, alts: readonly string[] | undefined): {
275
- role?: "img";
276
- "aria-label"?: string;
277
- "aria-hidden"?: "true";
278
- };
279
280
  declare function serialize(node: SvgNode | string): string;
280
281
  /** Render a layout to a standalone SVG document string. */
281
282
  declare function renderToString(layout: Layout, opts?: RenderOptions): string;
282
283
  /** Render a layout to a live <svg> element. */
283
284
  declare function renderToElement(layout: Layout, opts?: RenderOptions, doc?: Document): SVGSVGElement;
284
285
 
285
- export { type CanvasContextLike, type CanvasImage, type CanvasLike, type CanvasRenderOptions, type CellStyle, type FillSource, type ImageSource, type RasterOptions, type ReliefLayer, type ReliefOptions, type ReliefPath, type RenderOptions, type SvgNode, cellA11y, cellPath, defaultBevel, defaultPalette, drawLayout, imagesUsed, loadImages, neutralPalette, polygonToPath, rasterSize, regionPath, reliefLayers, reliefPaths, renderToCanvas, renderToElement, renderToPng, renderToString, resolveCellStyles, resolveFills, serialize, shadowOffset, toSvgTree, tracePolygon, viewPath };
286
+ export { type CellStyle as C, type CanvasContextLike, type CanvasImage, type CanvasLike, type CanvasRenderOptions, type FillSource, type ImageSource, type RasterOptions, type ReliefLayer, type ReliefOptions, type ReliefPath, type RenderOptions, type SvgNode, resolveFills as a, cellA11y as c, cellPath, defaultBevel, defaultPalette, drawLayout, imagesUsed, loadImages, neutralPalette, polygonToPath, resolveCellStyles as r, rasterSize, regionPath, reliefLayers, reliefPaths, renderToCanvas, renderToElement, renderToPng, renderToString, serialize, shadowOffset, toSvgTree, tracePolygon, viewPath };
package/dist/index.js CHANGED
@@ -1,5 +1,11 @@
1
+ import {
2
+ cellA11y,
3
+ defaultPalette,
4
+ resolveCellStyles
5
+ } from "./chunk-GCRUDQEZ.js";
6
+
1
7
  // src/index.ts
2
- import { cellShape as cellShape2, contentSlots, coverRect as coverRect2, matchSlots, safeArea as safeArea2, paletteFill, roundCorners as roundCorners2 } from "@andamento/core";
8
+ import { cellShape as cellShape2, coverRect as coverRect2, safeArea as safeArea2, roundCorners as roundCorners2 } from "@andamento/core";
3
9
 
4
10
  // src/relief.ts
5
11
  import { bevelFacets, lightVector } from "@andamento/core";
@@ -115,10 +121,10 @@ function drawLayout(ctx, layout, options = {}) {
115
121
  ctx.save();
116
122
  ctx.clip("evenodd");
117
123
  if (options.imageFit === "contain") {
118
- const aspect = options.imageAspects && style.slot >= 0 ? options.imageAspects[style.slot % options.imageAspects.length] : void 0;
124
+ const aspect = options.imageAspects && style.slot >= 0 ? options.imageAspects[style.slot] : void 0;
119
125
  drawContain(ctx, img, safeArea(cell, layout, { aspect, within: options.containWithin }));
120
126
  } else {
121
- const focus = style.slot >= 0 ? Array.isArray(options.images) ? options.imageFocus?.[style.slot % options.images.length] : void 0 : void 0;
127
+ const focus = style.slot >= 0 ? options.imageFocus?.[style.slot] : void 0;
122
128
  if (focus && img.width && img.height) {
123
129
  const r = coverRect(cell, layout, { aspect: img.width / img.height, focus });
124
130
  ctx.drawImage(img, 0, 0, img.width, img.height, r.x, r.y, r.width, r.height);
@@ -249,7 +255,6 @@ function makeCanvas(w, h) {
249
255
  }
250
256
 
251
257
  // src/index.ts
252
- var defaultPalette = ["#e9d8a6", "#94d2bd", "#ee9b00", "#0a9396", "#ca6702", "#bb3e03", "#ae2012", "#005f73"];
253
258
  var neutralPalette = ["#e7e5e4", "#d6d3d1", "#f5f5f4", "#dedad6", "#ecebe9"];
254
259
  var formatter = (precision) => (n) => {
255
260
  const s = n.toFixed(precision);
@@ -281,28 +286,6 @@ function viewPath(layout, precision = 3) {
281
286
  function regionPath(layout, precision = 3) {
282
287
  return [layout.region, ...layout.holes].map((p) => polygonToPath(p, precision)).join("");
283
288
  }
284
- function resolveFills(layout, fill) {
285
- if (typeof fill === "string") return layout.cells.map(() => fill);
286
- const f = typeof fill === "function" ? fill : paletteFill(fill.length ? fill : defaultPalette);
287
- return layout.cells.map((c) => f(c, layout));
288
- }
289
- function resolveCellStyles(layout, opts = {}) {
290
- const fills = resolveFills(layout, opts.fill ?? defaultPalette);
291
- const images = opts.images;
292
- let slots = layout.cells.map(() => -1);
293
- if (Array.isArray(images) && images.length > 0) {
294
- const count = opts.repeatImages ? Infinity : images.length;
295
- const content = { cells: opts.contentCells, placement: opts.placement, choose: opts.choose };
296
- slots = opts.imageAspects && !opts.repeatImages ? matchSlots(layout, images.map((_, i) => opts.imageAspects[i] ?? 1), content) : contentSlots(layout, count, content);
297
- }
298
- return layout.cells.map((c, i) => {
299
- const slot = slots[i];
300
- let image;
301
- if (typeof images === "function") image = images(c);
302
- else if (images && slot >= 0) image = images[slot % images.length];
303
- return { fill: fills[i], image, slot };
304
- });
305
- }
306
289
  var el = (tag, attrs = {}, children = []) => ({
307
290
  tag,
308
291
  attrs,
@@ -367,9 +350,9 @@ function toSvgTree(layout, opts = {}) {
367
350
  const clipId = `${prefix}-clip-${cell.index}`;
368
351
  parts.unshift(el("clipPath", { id: clipId }, [el("path", { d, "clip-rule": holed ? "evenodd" : void 0 })]));
369
352
  const contain = opts.imageFit === "contain";
370
- const aspect = contain && opts.imageAspects && style.slot >= 0 ? opts.imageAspects[style.slot % opts.imageAspects.length] : void 0;
371
- const focus = !contain && style.slot >= 0 ? Array.isArray(opts.images) ? opts.imageFocus?.[style.slot % opts.images.length] : void 0 : void 0;
372
- const shape = focus ? opts.imageAspects?.[style.slot % opts.imageAspects.length] ?? focus.aspect : void 0;
353
+ const aspect = contain && opts.imageAspects && style.slot >= 0 ? opts.imageAspects[style.slot] : void 0;
354
+ const focus = !contain && style.slot >= 0 ? opts.imageFocus?.[style.slot] : void 0;
355
+ const shape = focus ? opts.imageAspects?.[style.slot] ?? focus.aspect : void 0;
373
356
  const box = contain ? safeArea2(cell, layout, { aspect, within: opts.containWithin }) : focus && shape ? coverRect2(cell, layout, { aspect: shape, focus }) : cellShape2(cell).bbox;
374
357
  parts.push(
375
358
  el("image", {
@@ -424,11 +407,6 @@ function toSvgTree(layout, opts = {}) {
424
407
  children
425
408
  );
426
409
  }
427
- function cellA11y(style, alts) {
428
- if (!alts?.length) return {};
429
- const alt = style.image && style.slot >= 0 ? alts[style.slot % alts.length] : void 0;
430
- return alt ? { role: "img", "aria-label": alt } : { "aria-hidden": "true" };
431
- }
432
410
  var escapeText = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
433
411
  var escapeAttr = (s) => escapeText(s).replace(/"/g, "&quot;");
434
412
  function serialize(node) {
@@ -455,7 +433,6 @@ function renderToElement(layout, opts = {}, doc = globalThis.document) {
455
433
  return build(toSvgTree(layout, opts), doc);
456
434
  }
457
435
  export {
458
- cellA11y,
459
436
  cellPath,
460
437
  defaultBevel,
461
438
  defaultPalette,
@@ -472,8 +449,6 @@ export {
472
449
  renderToElement,
473
450
  renderToPng,
474
451
  renderToString,
475
- resolveCellStyles,
476
- resolveFills,
477
452
  serialize,
478
453
  shadowOffset,
479
454
  toSvgTree,