@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.
@@ -0,0 +1 @@
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,EAAA,EAAI,CAAA;AAC5D,EAAA,OAAO,KAAA,EAAO,IAAA,CAAK,IAAA,CAAK,IAAI,CAAA;AAC9B;AAEA,IAAM,OAAA,EAAS,CAAA;AAcR,SAAS,YAAA,CAAa,MAAA,EAAgB,IAAA,EAAY,MAAA,EAAuB,KAAA,EAA8B;AAC5G,EAAA,MAAM,SAAA,mBAAW,MAAA,CAAO,QAAA,UAAY,KAAA;AACpC,EAAA,MAAM,OAAA,kBAAS,IAAI,GAAA,CAAuB,CAAA;AAC1C,EAAA,IAAA,CAAA,MAAW,MAAA,GAAS,+BAAA,IAAY,EAAM,MAAA,EAAQ,EAAE,KAAA,EAAO,KAAA,EAAO,KAAA,EAAO,MAAA,CAAO,MAAM,CAAC,CAAA,EAAG;AACpF,IAAA,MAAM,MAAA,EAAQ,IAAA,CAAK,KAAA,CAAM,KAAA,CAAM,MAAA,EAAQ,MAAM,CAAA;AAC7C,IAAA,GAAA,CAAI,MAAA,IAAU,CAAA,EAAG,QAA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ACyB,IAAA;AACmB,MAAA;AACT,QAAA;AACjC,MAAA;AACF,IAAA;AACiB,IAAA;AAC0B,MAAA;AAC3C,IAAA;AACS,IAAA;AACP,MAAA;AACE,QAAA;AACA,QAAA;AACS,UAAA;AACc,UAAA;AACF,UAAA;AACqB,UAAA;AACF,UAAA;AACL,UAAA;AACnC,QAAA;AACA,QAAA;AACF,MAAA;AACF,IAAA;AACD,EAAA;AACgB,EAAA;AACS,IAAA;AACU,IAAA;AACe,IAAA;AACA,IAAA;AACnD,EAAA;AAEO,EAAA;AACL,IAAA;AACA,IAAA;AACS,MAAA;AACmC,MAAA;AAC9B,MAAA;AACC,MAAA;AACiC,MAAA;AAChD,IAAA;AACA,IAAA;AACF,EAAA;AACF;AAG2D;AACG;AAEJ;AACR,EAAA;AAEpC,EAAA;AAGuC,EAAA;AACF,EAAA;AACnD;AAGiF;AACvC,EAAA;AAC1C;AAEe;AAE6C;AACjB,EAAA;AACQ,EAAA;AACA,EAAA;AACJ,IAAA;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"]}
@@ -0,0 +1,286 @@
1
+ import { Polygon, Layout, Cell, CellFill, ContentCells, ContentPlacement, Focus } from '@andamento/core';
2
+
3
+ /**
4
+ * Makes tiles look raised: a bevel round each tile's edges, lit from one side, and
5
+ * optionally a shadow each tile casts into the grout (the gaps) on the other.
6
+ */
7
+ interface ReliefOptions {
8
+ /** Bevel width in layout units. Defaults to 8% of a typical tile's size; 0 for none. */
9
+ bevel?: number;
10
+ /** Direction the light comes from: degrees clockwise from the top (default 315, top left). */
11
+ light?: number;
12
+ /** Opacity of the brightest highlight and the darkest bevel shadow, 0–1. Defaults to 0.4. */
13
+ strength?: number;
14
+ /** How far tiles' shadows fall into the grout, in layout units (default 0: no shadow). */
15
+ shadow?: number;
16
+ /** Blur of the cast shadow (standard deviation, layout units). Defaults to `shadow`. */
17
+ shadowBlur?: number;
18
+ /** Opacity of the cast shadow. Defaults to 0.35. */
19
+ shadowOpacity?: number;
20
+ }
21
+ /** One layer of a cell's bevel: all its faces of about the same shade, as one path. */
22
+ interface ReliefPath {
23
+ d: string;
24
+ /** "#fff" for highlights, "#000" for shadows. */
25
+ fill: string;
26
+ opacity: number;
27
+ }
28
+ /** The default bevel width for a layout: 8% of the square root of the mean tile area. */
29
+ declare function defaultBevel(layout: Layout): number;
30
+ /** One layer of a cell's bevel as polygons: all its faces of about the same shade. */
31
+ interface ReliefLayer {
32
+ polygons: Polygon[];
33
+ /** "#fff" for highlights, "#000" for shadows. */
34
+ fill: string;
35
+ opacity: number;
36
+ }
37
+ /**
38
+ * A cell's bevel grouped into a few shade levels, in layout coordinates, to draw over the
39
+ * cell's content. Pass the bevel width from `defaultBevel` if not set.
40
+ */
41
+ declare function reliefLayers(layout: Layout, cell: Cell, relief: ReliefOptions, bevel: number): ReliefLayer[];
42
+ /** `reliefLayers` as SVG paths, one per layer. */
43
+ declare function reliefPaths(layout: Layout, cell: Cell, relief: ReliefOptions, bevel: number, precision?: number): ReliefPath[];
44
+ /** Offset of the cast shadow (away from the light), or undefined for none. */
45
+ declare function shadowOffset(relief: ReliefOptions): {
46
+ dx: number;
47
+ dy: number;
48
+ blur: number;
49
+ opacity: number;
50
+ } | undefined;
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
+
76
+ /**
77
+ * The parts of a 2D canvas context the renderer uses. A browser `CanvasRenderingContext2D`
78
+ * or `OffscreenCanvasRenderingContext2D` fits, and so do Node canvases such as
79
+ * `@napi-rs/canvas` or `skia-canvas`.
80
+ */
81
+ interface CanvasContextLike {
82
+ save(): void;
83
+ restore(): void;
84
+ setTransform(a: number, b: number, c: number, d: number, e: number, f: number): void;
85
+ beginPath(): void;
86
+ moveTo(x: number, y: number): void;
87
+ lineTo(x: number, y: number): void;
88
+ arc(x: number, y: number, radius: number, start: number, end: number, counterclockwise?: boolean): void;
89
+ closePath(): void;
90
+ fill(fillRule?: "nonzero" | "evenodd"): void;
91
+ clip(fillRule?: "nonzero" | "evenodd"): void;
92
+ stroke(): void;
93
+ clearRect(x: number, y: number, w: number, h: number): void;
94
+ drawImage(image: never, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
95
+ fillStyle: unknown;
96
+ strokeStyle: unknown;
97
+ lineWidth: number;
98
+ lineJoin: unknown;
99
+ globalAlpha: number;
100
+ shadowColor: string;
101
+ shadowBlur: number;
102
+ shadowOffsetX: number;
103
+ shadowOffsetY: number;
104
+ }
105
+ /** A loaded image: an HTMLImageElement, ImageBitmap, canvas, or a Node canvas image. */
106
+ type CanvasImage = {
107
+ width: number;
108
+ height: number;
109
+ };
110
+ interface CanvasRenderOptions extends Pick<RenderOptions, "images" | "repeatImages" | "contentCells" | "placement" | "imageAspects" | "choose" | "imageFit" | "containWithin" | "imageFocus" | "fill" | "stroke" | "strokeWidth" | "background"> {
111
+ /** Raised tiles, as for SVG. */
112
+ relief?: boolean | ReliefOptions;
113
+ /** One image across all the cells (a URL), as for SVG. */
114
+ backdrop?: string;
115
+ /**
116
+ * Loaded images by URL (see `loadImages`). Images not in it are skipped and their cells
117
+ * show `fill`. `renderToCanvas` and `renderToPng` load them for you.
118
+ */
119
+ loaded?: ReadonlyMap<string, CanvasImage>;
120
+ }
121
+ /**
122
+ * Draw a layout on a canvas context, scaled to fit `width` by `height` device pixels (the
123
+ * canvas size by default) and centerd, like SVG's default `preserveAspectRatio`. It draws
124
+ * what the SVG renderer does: background, cast shadows, fills, images, bevels and strokes.
125
+ * Synchronous: pass loaded images in `loaded`.
126
+ */
127
+ declare function drawLayout(ctx: CanvasContextLike, layout: Layout, options?: CanvasRenderOptions & {
128
+ width?: number;
129
+ height?: number;
130
+ }): void;
131
+ /** Add a polygon (with rounded corners) to the current path, as a closed subpath. */
132
+ declare function tracePolygon(ctx: Pick<CanvasContextLike, "moveTo" | "lineTo" | "arc" | "closePath">, poly: Polygon, radius: number): void;
133
+ /** The image URLs a layout would draw with these options (cell images and the backdrop). */
134
+ declare function imagesUsed(layout: Layout, options?: CanvasRenderOptions): string[];
135
+ /**
136
+ * Load images for drawing (in the browser, with `crossOrigin = "anonymous"` so the canvas
137
+ * can still be exported; the server must allow it). Images that fail are left out. Pass
138
+ * your own `load` elsewhere, e.g. `loadImage` from a Node canvas package.
139
+ */
140
+ declare function loadImages(urls: readonly string[], load?: (url: string) => Promise<CanvasImage>): Promise<Map<string, CanvasImage>>;
141
+ /** A canvas that can be drawn on and exported (browser or offscreen canvas, or your own). */
142
+ interface CanvasLike {
143
+ width: number;
144
+ height: number;
145
+ getContext(type: "2d"): unknown;
146
+ }
147
+ interface RasterOptions extends CanvasRenderOptions {
148
+ /** Output width in CSS pixels; the height follows the layout's shape. Defaults to the layout's width. */
149
+ width?: number;
150
+ /** Device pixels per CSS pixel, for sharp output on high-density screens. Defaults to 1. */
151
+ pixelRatio?: number;
152
+ /** Load an image (see `loadImages`). */
153
+ loadImage?: (url: string) => Promise<CanvasImage>;
154
+ }
155
+ /**
156
+ * Draw a layout onto `canvas`, sizing it to the layout (`width` × `pixelRatio`) and loading
157
+ * its images first. Resolves to the canvas.
158
+ */
159
+ declare function renderToCanvas<C extends CanvasLike>(layout: Layout, canvas: C, options?: RasterOptions): Promise<C>;
160
+ /** Pixel size of the raster for a layout: `width` (default the layout's) times `pixelRatio`. */
161
+ declare function rasterSize(layout: Layout, options?: Pick<RasterOptions, "width" | "pixelRatio">): {
162
+ w: number;
163
+ h: number;
164
+ };
165
+ /**
166
+ * Render a layout to a PNG (or JPEG / WebP with `type`) image, in the browser or a worker.
167
+ * Images must load (and, from other sites, allow cross-origin use) or their cells show
168
+ * their fill. Elsewhere, use `drawLayout` with your own canvas.
169
+ */
170
+ declare function renderToPng(layout: Layout, options?: RasterOptions & {
171
+ type?: string;
172
+ quality?: number;
173
+ createCanvas?: (w: number, h: number) => CanvasLike;
174
+ }): Promise<Blob>;
175
+
176
+ /**
177
+ * Renders a layout to an SVG string or element, to a canvas, or to a PNG.
178
+ *
179
+ * @module @andamento/svg
180
+ */
181
+
182
+ /** Soft neutrals for tiles without content: visible as tiles, but quiet next to photos. */
183
+ declare const neutralPalette: string[];
184
+ type ImageSource = readonly string[] | ((cell: Cell) => string | undefined);
185
+ interface RenderOptions {
186
+ /** Images: an array assigned in reading order, or a function per cell. */
187
+ images?: ImageSource;
188
+ /** Reuse the images array from the start when there are more cells than images. */
189
+ repeatImages?: boolean;
190
+ /** Which cells may hold an image from the `images` array (default "all"). */
191
+ contentCells?: ContentCells;
192
+ /** Where the images go when there are fewer than cells (default "reading"). */
193
+ placement?: ContentPlacement;
194
+ /**
195
+ * Width / height of each image in `images`. When given, each image goes in a cell of
196
+ * similar shape, to crop as little as possible (see `matchSlots`). Ignored with `repeatImages`.
197
+ */
198
+ imageAspects?: readonly number[];
199
+ /**
200
+ * How each image fills its cell: "cover" (default) fills the cell's bounding box and is
201
+ * cropped to the cell's shape; "contain" shows the whole image inside the cell's safe area
202
+ * (see `safeArea`), uncropped. Give `imageAspects` so the safe area has each image's shape.
203
+ */
204
+ imageFit?: "cover" | "contain";
205
+ /**
206
+ * With `imageFit: "contain"`, for cells an `edges: "window"` layout cuts: fit the image in
207
+ * the whole tile ("tile", the default; partly hidden like the tile) or in the part that
208
+ * shows ("visible"). See `SafeAreaOptions.within`.
209
+ */
210
+ containWithin?: "tile" | "visible";
211
+ /**
212
+ * Focal point of each image in `images` (by position; fractions of its width and height,
213
+ * see `estimateFocus`): what to keep in view when "cover" crops it. It goes as near the
214
+ * middle of what shows of its cell as covering the cell allows (see `coverRect`). Needs
215
+ * each image's shape, from `imageAspects` or the focus's `aspect` (the canvas renderers
216
+ * measure the images themselves).
217
+ */
218
+ imageFocus?: readonly (Focus | undefined)[];
219
+ /** With `imageAspects`: "shape" also picks which cells get images by their shape. */
220
+ choose?: "placement" | "shape";
221
+ /**
222
+ * Cell color when there is no image: a color, a palette (neighboring cells get
223
+ * different entries), or a function. Defaults to `defaultPalette`.
224
+ */
225
+ fill?: FillSource;
226
+ /**
227
+ * Raised tiles: a lit bevel round each tile, and optionally a shadow cast into the grout.
228
+ * `true` for the defaults. See `ReliefOptions`.
229
+ */
230
+ relief?: boolean | ReliefOptions;
231
+ /** Outline drawn on top of each cell. */
232
+ stroke?: string;
233
+ strokeWidth?: number;
234
+ /** Color painted over the whole region. Omit for transparent. */
235
+ background?: string;
236
+ /**
237
+ * One image across all the cells (a URL): drawn once over the layout bounds (cropped to
238
+ * cover them) and clipped to the cells, so each cell shows its piece. Cells' `fill` isn't
239
+ * drawn; per-cell `images` still go on top.
240
+ */
241
+ backdrop?: string;
242
+ /** Prefix for generated element ids; set it when several layouts share a page. */
243
+ idPrefix?: string;
244
+ /** Decimal places for coordinates. Defaults to 3. */
245
+ precision?: number;
246
+ /** Width/height attributes of the <svg>; it always gets a viewBox. */
247
+ width?: string | number;
248
+ height?: string | number;
249
+ /** Accessible title. */
250
+ title?: string;
251
+ /**
252
+ * Text alternative for each image in `images` (by position). Cells showing an image with
253
+ * one become labeled images to assistive technology, and the SVG a group of them; the
254
+ * other cells are hidden as decoration.
255
+ */
256
+ imageAlts?: readonly string[];
257
+ }
258
+ /** `d` attribute for a polygon. With `radius`, corners are rounded with circular arcs. */
259
+ declare function polygonToPath(p: Polygon, precision?: number, radius?: number): string;
260
+ /**
261
+ * `d` attribute for a cell's outline, including the layout's corner rounding and any holes
262
+ * (as extra subpaths; draw with `fill-rule="evenodd"`). For a window cell this is the
263
+ * whole tile (see `cellShape`); clip it to `viewPath`.
264
+ */
265
+ declare function cellPath(layout: Layout, cell: Cell, precision?: number): string;
266
+ /**
267
+ * `d` attribute for the area tiles show in (draw or clip with `evenodd`): `layout.view` in
268
+ * a window layout, else the region with its holes.
269
+ */
270
+ declare function viewPath(layout: Layout, precision?: number): string;
271
+ /** `d` attribute for the region with its holes (draw with `fill-rule="evenodd"`). */
272
+ declare function regionPath(layout: Layout, precision?: number): string;
273
+ /** Minimal element tree, serializable to a string or built into DOM nodes. */
274
+ interface SvgNode {
275
+ tag: string;
276
+ attrs: Record<string, string | number | undefined>;
277
+ children: (SvgNode | string)[];
278
+ }
279
+ declare function toSvgTree(layout: Layout, opts?: RenderOptions): SvgNode;
280
+ declare function serialize(node: SvgNode | string): string;
281
+ /** Render a layout to a standalone SVG document string. */
282
+ declare function renderToString(layout: Layout, opts?: RenderOptions): string;
283
+ /** Render a layout to a live <svg> element. */
284
+ declare function renderToElement(layout: Layout, opts?: RenderOptions, doc?: Document): SVGSVGElement;
285
+
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 };