expressive-charts 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/README.md +6 -6
  3. package/dist/define-DeZLs1h7.js +95 -0
  4. package/dist/define-DeZLs1h7.js.map +1 -0
  5. package/dist/drawing-Dz_IvJPB.d.cts +208 -0
  6. package/dist/drawing-Dz_IvJPB.d.ts +208 -0
  7. package/dist/effect-CdH5449m.d.ts +232 -0
  8. package/dist/effect-uYC8Vs6_.d.cts +232 -0
  9. package/dist/expressive-charts.css +2 -0
  10. package/dist/expressive-charts.css.d.cts +1 -2
  11. package/dist/expressive-charts.css.d.ts +1 -2
  12. package/dist/expressive-charts.global.js +45 -47
  13. package/dist/expressive-charts.global.js.map +1 -1
  14. package/dist/icons/sport.cjs +211 -156
  15. package/dist/icons/sport.cjs.map +1 -1
  16. package/dist/icons/sport.d.cts +5 -7
  17. package/dist/icons/sport.d.ts +5 -7
  18. package/dist/icons/sport.js +122 -71
  19. package/dist/icons/sport.js.map +1 -1
  20. package/dist/index.cjs +12632 -9979
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +913 -871
  23. package/dist/index.d.ts +913 -871
  24. package/dist/index.js +10444 -8232
  25. package/dist/index.js.map +1 -1
  26. package/dist/path-data-DnEckjY8.js +123 -0
  27. package/dist/path-data-DnEckjY8.js.map +1 -0
  28. package/dist/testing.cjs +2030 -1252
  29. package/dist/testing.cjs.map +1 -1
  30. package/dist/testing.d.cts +135 -139
  31. package/dist/testing.d.ts +135 -139
  32. package/dist/testing.js +696 -499
  33. package/dist/testing.js.map +1 -1
  34. package/dist/transition-DSRt2DH3.js +2053 -0
  35. package/dist/transition-DSRt2DH3.js.map +1 -0
  36. package/package.json +6 -6
  37. package/dist/chunk-7A7LXXT4.js +0 -70
  38. package/dist/chunk-7A7LXXT4.js.map +0 -1
  39. package/dist/chunk-CJUQHEX6.js +0 -618
  40. package/dist/chunk-CJUQHEX6.js.map +0 -1
  41. package/dist/chunk-N2BLUETM.js +0 -1194
  42. package/dist/chunk-N2BLUETM.js.map +0 -1
  43. package/dist/drawing-CdTgixMY.d.cts +0 -206
  44. package/dist/drawing-CdTgixMY.d.ts +0 -206
  45. package/dist/effect-Bu3MHHeg.d.ts +0 -247
  46. package/dist/effect-D4vmdYP4.d.cts +0 -247
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/charts/announce.ts","../src/charts/render/svg.ts","../src/charts/render/text.ts","../src/charts/bar-layout.ts","../src/charts/render/theme.ts","../src/charts/colors.ts","../src/charts/legend.ts","../src/charts/link.ts","../src/charts/motion.ts","../src/charts/render/outside.ts","../src/charts/render/mark-style.ts","../src/charts/render/layer.ts","../src/charts/render/surface.ts","../src/charts/series.ts","../src/charts/shell/events.ts","../src/charts/shell/format.ts","../src/charts/interaction.ts","../src/charts/keyboard.ts","../src/charts/shell/hover.ts","../src/charts/shell/labels.ts","../src/charts/shell/leaving.ts","../src/charts/shell/order.ts","../src/charts/table.ts","../src/charts/shell/setup.ts","../src/charts/shell/transitions.ts","../src/charts/shell/watch.ts","../src/charts/tooltip.ts","../src/charts/bar.ts","../src/charts/donut-layout.ts","../src/charts/donut.ts","../src/charts/time.ts","../src/charts/line-layout.ts","../src/charts/line.ts","../src/core/geometry/ring.ts","../src/charts/adapter/bars.ts","../src/charts/adapter/edits.ts","../src/charts/adapter/space.ts","../src/charts/adapter/host-style.ts","../src/charts/adapter/source.ts","../src/charts/adapter/watch.ts","../src/charts/adapter/expressive.ts","../src/charts/adapter/vega.ts","../src/core/geometry/path.ts","../src/charts/switch.ts","../src/charts/controls/motion-switch.ts","../src/charts/controls/play-button.ts","../src/effects/gaits.ts","../src/effects/travel.ts","../src/effects/flash.ts","../src/effects/wiggle.ts","../src/effects/pulse.ts","../src/effects/trace.ts","../src/effects/caption.ts","../src/effects/delta.ts","../src/effects/label.ts","../src/effects/threshold.ts","../src/effects/morph.ts","../src/effects/combinators.ts","../src/effects/define.ts","../src/icons/svg.ts","../src/icons/core.ts","../src/registries.ts","../src/settings.ts","../src/index.ts"],"sourcesContent":["// Announcements: with `announce`, a polite live region that sums up each update for screen readers.\n// The chart writes the generic part (\"Sorted A to Z\", \"Okafor and Tanaka changed\"); a page that knows\n// more (\"Matchweek 25\") passes a function that writes its own text from the chart's.\n\nexport type SortName = \"value\" | \"key\" | \"none\" | \"custom\";\n\n/** What changed in an update, as the chart sees it. Names are the marks' categories, in visual order. */\nexport interface ChangeFacts {\n /** The chart's new label, when it changed. */\n readonly label?: string;\n /** The new series, by their labels, when they changed. */\n readonly series?: readonly string[];\n /** The new sort, when it changed. */\n readonly sort?: SortName;\n readonly changed: readonly string[];\n readonly added: readonly string[];\n readonly removed: readonly string[];\n /** Marks after the update. */\n readonly count: number;\n}\n\nexport interface Announcer {\n /** Announces `text`, politely. Saying the same thing twice in a row is announced twice. */\n say(text: string): void;\n destroy(): void;\n}\n\nconst SORTED: Record<SortName, string> = {\n value: \"Sorted highest first\",\n key: \"Sorted A to Z\",\n none: \"In data order\",\n custom: \"Sorted\"\n};\n\n/** Lists more than this many marks as a count: \"5 of 8 changed\". */\nconst NAMED = 3;\n\n/**\n * The chart's own summary, a sentence for each kind of change, or \"\" when nothing it reports changed.\n * A new label stands for the view it names; otherwise new series are named. A change of series\n * changes every value, so the marks that changed are counted only when the series stayed.\n */\nexport function changeText(facts: ChangeFacts): string {\n const parts: string[] = [];\n const { series } = facts;\n if (facts.label !== undefined) parts.push(facts.label);\n // A lone value read by a function has no name worth saying.\n else if (series && !(series.length === 1 && series[0] === \"value\")) parts.push(`Showing ${list(series)}`);\n if (facts.sort) parts.push(SORTED[facts.sort]);\n const { changed, added, removed } = facts;\n if (!series && changed.length > 0) parts.push(changed.length <= NAMED ? `${list(changed)} changed` : `${changed.length} of ${facts.count} changed`);\n if (added.length > 0) parts.push(`Added ${added.length <= NAMED ? list(added) : added.length}`);\n if (removed.length > 0) parts.push(`Removed ${removed.length <= NAMED ? list(removed) : removed.length}`);\n return parts.join(\". \");\n}\n\n/** \"a\", \"a and b\", \"a, b and c\". */\nfunction list(names: readonly string[]): string {\n if (names.length <= 1) return names.join(\"\");\n return `${names.slice(0, -1).join(\", \")} and ${names[names.length - 1]}`;\n}\n\n/**\n * The live region for a chart's <svg>: a visually hidden role=\"status\" just after it. Make it before\n * the first announcement: screen readers miss text in a region that appears with it.\n */\nexport function chartAnnouncer(svg: SVGSVGElement): Announcer {\n const region = svg.ownerDocument.createElement(\"div\");\n region.className = \"ec-announcer ec-visually-hidden\";\n region.setAttribute(\"role\", \"status\");\n region.setAttribute(\"aria-live\", \"polite\");\n region.setAttribute(\"aria-atomic\", \"true\");\n svg.after(region);\n /** Alternates, so the same text twice is still a change the region announces. */\n let odd = false;\n return {\n say(text) {\n if (text === \"\") return;\n odd = !odd;\n region.textContent = odd ? text : `${text} `;\n },\n destroy() {\n region.remove();\n }\n };\n}\n","// Small helpers for building SVG. Nothing here runs at import time, so the package still loads in Node.\n\nimport type { Matrix } from \"../../core\";\nimport { formatNumber } from \"../../core/geometry\";\n\nexport const SVG_NS = \"http://www.w3.org/2000/svg\";\n\nexport type Attributes = Readonly<Record<string, string | number | undefined>>;\n\n/** Creates an SVG element in `parent`'s document (or the global one), sets its attributes and appends it to `parent` if given. */\nexport function svgElement<K extends keyof SVGElementTagNameMap>(tag: K, attributes: Attributes = {}, parent?: Element): SVGElementTagNameMap[K] {\n const doc = parent?.ownerDocument ?? document;\n const element = doc.createElementNS(SVG_NS, tag) as SVGElementTagNameMap[K];\n setAttributes(element, attributes);\n parent?.appendChild(element);\n return element;\n}\n\n/** Sets attributes; a value of undefined removes the attribute. Numbers are rounded to 0.001. */\nexport function setAttributes(element: Element, attributes: Attributes): void {\n for (const [name, value] of Object.entries(attributes)) {\n if (value === undefined) element.removeAttribute(name);\n else element.setAttribute(name, typeof value === \"number\" ? formatNumber(value) : value);\n }\n}\n\n/** Sets CSS properties through the CSSOM (allowed under a strict CSP); undefined removes one. */\nexport function setStyles(element: SVGElement, styles: Readonly<Record<string, string | undefined>>): void {\n for (const [name, value] of Object.entries(styles)) {\n if (value === undefined) element.style.removeProperty(name);\n else element.style.setProperty(name, value);\n }\n}\n\n/** A chart's <svg> size and viewBox, in px. */\nexport function sizeAttributes({ width, height }: { readonly width: number; readonly height: number }): Record<string, string | number> {\n return { width, height, viewBox: `0 0 ${formatNumber(width)} ${formatNumber(height)}` };\n}\n\n/**\n * A Matrix as an SVG transform attribute. The linear part keeps 6 decimals, so a small rotation of a\n * long bar stays exact at its far end; the translation is rounded to 0.001 px like path data.\n */\nexport function transformAttribute(m: Matrix): string {\n const [a, b, c, d, e, f] = m;\n return `matrix(${[a, b, c, d].map(linear).join(\" \")} ${formatNumber(e)} ${formatNumber(f)})`;\n}\n\nfunction linear(value: number): string {\n const rounded = Math.round(value * 1e6) / 1e6;\n return rounded === 0 ? \"0\" : String(rounded);\n}\n","// Text widths for layout (label margins). Measured in the chart's own SVG, so the page's font and the\n// chart's CSS apply. Where there's no layout (jsdom, a hidden container), widths are estimated from\n// the character count.\n\nimport type { Rect } from \"../../core\";\nimport { setAttributes, svgElement } from \"./svg\";\n\n/** Where a piece of text goes: its baseline's anchor point, and how it's anchored there. */\nexport interface TextPlacement {\n readonly x: number;\n readonly y: number;\n readonly anchor: \"start\" | \"middle\" | \"end\";\n readonly text: string;\n}\n\n/**\n * How far text reaches, as shares of its size: above its baseline (an accented capital's top), below\n * it (a descender's foot), and past its measured width at either side (a W's lean, an f's hook). So a\n * box holds the text's getBBox() in Chrome with Segoe UI, Arial, Georgia, Verdana and Consolas; a\n * Times New Roman \"ff\" reaches 0.8 px past it.\n */\nconst ASCENT = 1.05;\nconst DESCENT = 0.25;\nconst SIDE = 0.16;\n\n/**\n * The box `placement`'s text covers, drawn with `className` at `size` px: a mark's `labelBounds`.\n * Chart text has tabular digits, so it's measured with its digits as 0s, and text that counts\n * through values while a change plays is measured once for each shape.\n */\nexport function textBox(placement: TextPlacement, measure: Measure, className: string, size: number): Rect {\n const width = measure(placement.text.replace(/\\d/g, \"0\"), className, size);\n const start = placement.anchor === \"start\" ? placement.x : placement.anchor === \"end\" ? placement.x - width : placement.x - width / 2;\n return { x: start - SIDE * size, y: placement.y - ASCENT * size, width: width + 2 * SIDE * size, height: (ASCENT + DESCENT) * size };\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\n/** Moves a <text> to `placement` and sets its text, when it changed. */\nexport function placeText(element: SVGTextElement, placement: TextPlacement): void {\n setAttributes(element, { x: placement.x, y: placement.y, \"text-anchor\": placement.anchor });\n if (element.textContent !== placement.text) element.textContent = placement.text;\n}\n\nexport interface TextMeasure {\n /** Width in px of `text` drawn with `className` at `size` px (the size is only used for estimates). */\n (text: string, className: string, size: number): number;\n /** Forget measured widths, for example once web fonts have loaded. */\n clear(): void;\n}\n\n/** An estimate of the average glyph width, in em. */\nconst AVERAGE_WIDTH = 0.6;\n\nexport function textMeasure(svg: SVGSVGElement): TextMeasure {\n const cache = new Map<string, number>();\n const measure = (text: string, className: string, size: number): number => {\n if (text === \"\") return 0;\n const id = `${className}\\n${size}\\n${text}`;\n const cached = cache.get(id);\n if (cached !== undefined) return cached;\n let width = 0;\n const probe = svgElement(\"text\", { class: className, visibility: \"hidden\", \"aria-hidden\": \"true\" }, svg);\n if (typeof probe.getComputedTextLength === \"function\" && svg.isConnected) {\n probe.textContent = text;\n width = probe.getComputedTextLength();\n }\n probe.remove();\n // Only real measurements are kept: a hidden chart measures again once it's shown.\n if (!(width > 0)) return text.length * size * AVERAGE_WIDTH;\n cache.set(id, width);\n return width;\n };\n return Object.assign(measure, { clear: () => cache.clear() });\n}\n","// The bar chart's layout: pure, so it's tested without a DOM. Options in, marks (described with\n// describe.bar), labels, ticks and size out. Pixel sizes follow the prototype (demo/lab.html).\n//\n// A layout is drawn from a few numbers: the frame (the value scale and the category bands) and each\n// row's values and slot. Transitions interpolate those numbers, and placeRow and placeTick draw any\n// state in between the same way the layout draws its own.\n//\n// Labels that would overlap are thinned: every nth category label is drawn, and the value labels all\n// or none. The frame keeps room for every label, so thinning moves nothing.\n\nimport { describe, type MarkData, type MarkGeometry, type Rect } from \"../core\";\nimport { textBox, type TextPlacement } from \"./render/text\";\nimport type { Accessor, BarChartOptions } from \"./types\";\n\nexport type { TextPlacement } from \"./render/text\";\n\nexport type Orientation = \"horizontal\" | \"vertical\";\n\nexport interface BarSeries<D> {\n /** The segment's name: the stacked field, or the value field. */\n readonly series: string;\n readonly value: (d: D, i: number) => unknown;\n}\n\n/** Which accessor is the category, which give the values. */\nexport interface BarEncoding<D> {\n readonly orientation: Orientation;\n readonly category: (d: D, i: number) => unknown;\n readonly key: (d: D, i: number) => unknown;\n readonly series: readonly BarSeries<D>[];\n}\n\nexport interface BarValue {\n readonly series: string;\n readonly value: number;\n}\n\n/** Which of a row's labels are drawn. */\nexport interface DrawnLabels {\n readonly label: boolean;\n readonly value: boolean;\n}\n\nexport interface BarRow<D> {\n readonly key: string;\n readonly datum: D;\n /** The row's index in `data`. */\n readonly index: number;\n /** Its position along the category axis, in bands: 0 is the first. */\n readonly slot: number;\n readonly values: readonly BarValue[];\n readonly total: number;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n /** The row's name, which the tooltip, the mark's name and the table say, its label drawn or not. */\n readonly category: string;\n /** Which of its labels are drawn: thinning leaves some out. */\n readonly drawn: DrawnLabels;\n /** The category label: its text is empty when it isn't drawn. */\n readonly label: TextPlacement;\n /** The total, at the bar's tip: its text is empty when it isn't drawn. */\n readonly value: TextPlacement;\n /** The pointer target: the row's whole band. */\n readonly hit: Rect;\n}\n\nexport interface Tick {\n readonly value: number;\n readonly line: { readonly x1: number; readonly y1: number; readonly x2: number; readonly y2: number };\n readonly label: TextPlacement;\n}\n\n/**\n * The value axis. Data `lo` sits at px `from`, and each unit of data is `extent / (hi - lo)` px along\n * the axis (`extent` is negative for columns, which grow up). `label` is where the category labels\n * sit across it: their x for bars, their y for columns.\n */\nexport interface BarScale {\n readonly lo: number;\n readonly hi: number;\n readonly from: number;\n readonly extent: number;\n readonly label: number;\n}\n\n/**\n * The category axis. Slot 0's band starts at px `start`; each band is `band` px, with a bar\n * `thickness` px across in it; the plot is `span` px along the axis. Plus the chart's size.\n */\nexport interface BarBands {\n readonly start: number;\n readonly band: number;\n readonly thickness: number;\n readonly span: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface BarFrame {\n readonly orientation: Orientation;\n readonly scale: BarScale;\n readonly bands: BarBands;\n}\n\n/** Which labels a layout draws, so that no two overlap. */\nexport interface BarLabels {\n /** Every nth category label is drawn, from the first: n is 1, 2, 5, 10, 20, 50 and so on. */\n readonly every: number;\n /** Whether the value labels are drawn: none are when any two would overlap. */\n readonly values: boolean;\n}\n\nexport interface BarLayout<D> {\n readonly width: number;\n readonly height: number;\n readonly orientation: Orientation;\n readonly frame: BarFrame;\n /** In visual order: top to bottom, or left to right. A row's slot is its index here. */\n readonly rows: readonly BarRow<D>[];\n readonly ticks: readonly Tick[];\n readonly labels: BarLabels;\n}\n\n/** What placeRow draws a row from: a laid-out row, or a state in between two. */\nexport interface BarRowState<D> {\n readonly key: string;\n readonly datum: D;\n readonly index: number;\n /** The row's name: its category label's text. */\n readonly category: string;\n /** Signed, from the baseline. */\n readonly values: readonly BarValue[];\n /** Fractional in between. */\n readonly slot: number;\n /** The value label's text. */\n readonly text: string;\n /** Which of its labels are drawn, as its layout thinned them. Default: both. */\n readonly drawn?: DrawnLabels;\n}\n\nexport interface BarLayoutInput<D> {\n readonly data: readonly D[];\n readonly encoding: BarEncoding<D>;\n readonly sort: BarChartOptions<D>[\"sort\"];\n readonly width: number;\n readonly height: number | undefined;\n readonly format: (value: number) => string;\n /** Text width in px, for margins and the labels' boxes. */\n readonly measure: Measure;\n /** Px kept clear past the labels at each end of the value axis that bars reach. Default 0. */\n readonly room?: number;\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\n// From the prototype: 34 px rows with 20 px bars, a 2 px gap between segments, rounded tips.\nconst ROW = 34;\nconst BAR = 20;\nconst RADIUS = 4;\nconst GAP = 2;\nconst MAX_COLUMN = 72;\nconst VERTICAL_HEIGHT = 300;\nconst LABEL_SIZE = 12.5;\nconst VALUE_SIZE = 12.5;\nconst TICK_SIZE = 11;\n/** Space under the plot for tick (or category) labels. */\nconst AXIS = 26;\nconst TOP = 4;\n/** Between a label and what it labels. */\nconst PAD = 6;\n/** A row's labels when its layout didn't thin them. */\nconst BOTH: DrawnLabels = { label: true, value: true };\n/** Moves a text baseline down by this share of the font size to centre the text on a line. */\nconst CENTRE = 0.36;\n\n/** Reads the options: which axis is the category, which fields are the values. Throws on what it can't draw. */\nexport function barEncoding<D>(options: BarChartOptions<D>): BarEncoding<D> {\n const { x, y, stack, data } = options;\n let orientation = options.orientation;\n if (orientation !== undefined && orientation !== \"horizontal\" && orientation !== \"vertical\") {\n throw new TypeError(`barChart: orientation must be \"horizontal\" or \"vertical\", got ${String(orientation)}.`);\n }\n if (stack !== undefined) {\n if (!Array.isArray(stack) || stack.length === 0) throw new TypeError(\"barChart: stack needs at least one numeric field.\");\n const seen = new Set<string>();\n for (const field of stack) {\n if (seen.has(field)) throw new TypeError(`barChart: \"${field}\" appears twice in stack.`);\n seen.add(field);\n }\n }\n if (orientation === undefined) {\n if (x !== undefined && y !== undefined) {\n const xNumbers = numeric(data, accessor(x));\n const yNumbers = numeric(data, accessor(y));\n if (xNumbers !== yNumbers) orientation = xNumbers ? \"horizontal\" : \"vertical\";\n else if (data.length === 0) orientation = \"horizontal\";\n else {\n throw new RangeError(\n `barChart: ${xNumbers ? \"x and y both hold numbers\" : \"neither x nor y holds numbers\"}, so it can't tell which is the category. ` +\n `Set orientation: \"horizontal\" (categories along y) or \"vertical\" (categories along x).`\n );\n }\n } else if (stack !== undefined && (x !== undefined || y !== undefined)) {\n orientation = y !== undefined ? \"horizontal\" : \"vertical\";\n } else {\n throw new TypeError(\"barChart needs x and y (the axis whose values aren't numbers is the category), or one of them plus stack.\");\n }\n }\n const horizontal = orientation === \"horizontal\";\n const categoryOption = horizontal ? y : x;\n const valueOption = horizontal ? x : y;\n if (categoryOption === undefined) throw new TypeError(`barChart: a ${orientation} chart takes its categories from ${horizontal ? \"y\" : \"x\"}.`);\n const category = accessor(categoryOption);\n\n let series: BarSeries<D>[];\n if (stack !== undefined) series = stack.map((field) => ({ series: field, value: accessor<D, unknown>(field) }));\n else if (valueOption !== undefined) series = [{ series: typeof valueOption === \"string\" ? valueOption : \"value\", value: accessor(valueOption) }];\n else throw new TypeError(`barChart needs values: ${horizontal ? \"x\" : \"y\"} set to a numeric field, or stack.`);\n\n return { orientation, category, key: options.key === undefined ? category : accessor(options.key), series };\n}\n\nexport function layoutBars<D>(input: BarLayoutInput<D>): BarLayout<D> {\n const rows = sortRows(prepareRows(input), input.sort);\n const domain = niceDomain(rows.map((row) => row.total));\n const texts = rows.map((row) => input.format(row.total));\n const ticks = domain.ticks.map(input.format);\n const frame = (input.encoding.orientation === \"horizontal\" ? horizontalFrame : verticalFrame)(input, rows, domain, texts, ticks);\n const labels = thinLabels(frame, rows, texts, input.measure);\n return {\n width: frame.bands.width,\n height: frame.bands.height,\n orientation: frame.orientation,\n frame,\n rows: rows.map((row, slot) => placeRow(frame, { ...row, slot, text: texts[slot]!, drawn: { label: slot % labels.every === 0, value: labels.values } }, input.measure)),\n ticks: domain.ticks.map((value, i) => placeTick(frame, value, ticks[i]!)),\n labels\n };\n}\n\n/**\n * Which labels to draw so that no two overlap, by their boxes as `labelBounds` gives them: every nth\n * category label from the first, with n the smallest of 1, 2, 5, 10, 20, 50 and so on that leaves none\n * overlapping, and the value labels only if no two would overlap. A category label and a value label\n * aren't compared: within a row they sit apart.\n */\nfunction thinLabels<D>(frame: BarFrame, rows: readonly Prepared<D>[], texts: readonly string[], measure: Measure): BarLabels {\n const placed = rows.map((row, slot) => placeLabels(frame, slot, row.total, row.category, texts[slot]!));\n const horizontal = frame.orientation === \"horizontal\";\n const values = !overlaps(boxesOf(placed.map(({ value }) => value), measure, \"ec-value\", VALUE_SIZE), horizontal);\n const categories = (every: number): Rect[] =>\n boxesOf(\n placed.filter((_, slot) => slot % every === 0).map(({ label }) => label),\n measure,\n \"ec-label\",\n LABEL_SIZE\n );\n let k = 0;\n // Past the last row only the first is drawn, and one label can't overlap.\n while (thinStep(k) < rows.length && overlaps(categories(thinStep(k)), horizontal)) k++;\n return { every: thinStep(k), values };\n}\n\n/** The kth n thinning tries: 1, 2, 5, 10, 20, 50 and so on. */\nconst thinStep = (k: number): number => [1, 2, 5][k % 3]! * 10 ** Math.floor(k / 3);\n\n/** The boxes of the labels that have text. */\nfunction boxesOf(labels: readonly TextPlacement[], measure: Measure, className: string, size: number): Rect[] {\n return labels.filter((label) => label.text !== \"\").map((label) => textBox(label, measure, className, size));\n}\n\n/**\n * Whether any two boxes overlap (touching doesn't count). A sweep along the category axis (y for\n * bars, x for columns), so each box is checked only against those it reaches along it.\n */\nfunction overlaps(boxes: readonly Rect[], horizontal: boolean): boolean {\n // Columns as given; bars turned on their side, so the sweep runs along x either way.\n const along = horizontal ? boxes.map(({ x, y, width, height }) => ({ x: y, y: x, width: height, height: width })) : [...boxes];\n along.sort((a, b) => a.x - b.x);\n const open: Rect[] = [];\n for (const box of along) {\n for (let i = open.length - 1; i >= 0; i--) if (open[i]!.x + open[i]!.width <= box.x) open.splice(i, 1);\n if (open.some((other) => other.y < box.y + box.height && box.y < other.y + other.height)) return true;\n open.push(box);\n }\n return false;\n}\n\n/** A row's labels in a frame: its category beside the axis, and its value past the bar's tip. */\nfunction placeLabels(frame: BarFrame, slot: number, total: number, category: string, text: string): { readonly label: TextPlacement; readonly value: TextPlacement } {\n const { scale, bands } = frame;\n const negative = total < 0;\n const tip = position(scale)(total);\n const band = bands.start + slot * bands.band;\n if (frame.orientation === \"horizontal\") {\n const line = band + bands.band / 2 + LABEL_SIZE * CENTRE;\n return {\n label: { x: scale.label, y: line, anchor: \"end\", text: category },\n value: { x: negative ? tip - PAD : tip + PAD, y: line, anchor: negative ? \"end\" : \"start\", text }\n };\n }\n const centre = band + bands.band / 2;\n return {\n label: { x: centre, y: scale.label, anchor: \"middle\", text: category },\n value: { x: centre, y: negative ? tip + PAD + VALUE_SIZE * 0.8 : tip - PAD, anchor: \"middle\", text }\n };\n}\n\n/**\n * Draws a row in a frame: its bar (described with describe.bar, its drawn labels' boxes as\n * `labelBounds`), labels and pointer target. In between two states of opposite sign a stack can mix\n * signs; values against the total's sign then draw as 0.\n */\nexport function placeRow<D>(frame: BarFrame, row: BarRowState<D>, measure: Measure): BarRow<D> {\n const { scale, bands } = frame;\n const at = position(scale);\n const unit = Math.abs(scale.extent / (scale.hi - scale.lo));\n const total = row.values.reduce((sum, v) => sum + v.value, 0);\n const negative = total < 0;\n const zero = at(0);\n const tip = at(total);\n const band = bands.start + row.slot * bands.band;\n const bar = {\n key: row.key,\n ...(row.values.length === 1 ? { series: row.values[0]!.series } : {}),\n radius: RADIUS,\n gap: GAP,\n segments: row.values.map((v) => ({ series: v.series, size: Math.max(0, negative ? -v.value : v.value) * unit }))\n };\n const drawn = row.drawn ?? BOTH;\n const fields = { key: row.key, datum: row.datum, index: row.index, slot: row.slot, values: row.values, total, category: row.category, drawn };\n const { label, value } = placeLabels(frame, row.slot, total, drawn.label ? row.category : \"\", drawn.value ? row.text : \"\");\n /** The labels' boxes, leaving out a label with no text. */\n const boxes = (): Rect[] => [...boxesOf([label], measure, \"ec-label\", LABEL_SIZE), ...boxesOf([value], measure, \"ec-value\", VALUE_SIZE)];\n\n if (frame.orientation === \"horizontal\") {\n const geometry = describe.bar({\n ...bar,\n x: Math.min(zero, tip),\n y: band + (bands.band - bands.thickness) / 2,\n width: Math.abs(tip - zero),\n height: bands.thickness,\n baseline: negative ? \"right\" : \"left\",\n labelBounds: boxes()\n });\n return {\n ...fields,\n geometry,\n data: barData(row.datum, total, geometry),\n label,\n value,\n hit: { x: 0, y: band, width: bands.width, height: bands.band }\n };\n }\n\n const centre = band + bands.band / 2;\n const geometry = describe.bar({\n ...bar,\n x: centre - bands.thickness / 2,\n y: Math.min(zero, tip),\n width: bands.thickness,\n height: Math.abs(tip - zero),\n baseline: negative ? \"top\" : \"bottom\",\n labelBounds: boxes()\n });\n return {\n ...fields,\n geometry,\n data: barData(row.datum, total, geometry),\n label,\n value,\n hit: { x: band, y: 0, width: bands.band, height: bands.height }\n };\n}\n\n/** Draws a tick's gridline and label in a frame. */\nexport function placeTick(frame: BarFrame, value: number, text: string): Tick {\n const { bands } = frame;\n const at = position(frame.scale)(value);\n if (frame.orientation === \"horizontal\") {\n const bottom = bands.start + bands.span;\n return { value, line: { x1: at, y1: bands.start, x2: at, y2: bottom }, label: { x: at, y: bottom + 16, anchor: \"middle\", text } };\n }\n return {\n value,\n line: { x1: bands.start, y1: at, x2: bands.start + bands.span, y2: at },\n label: { x: bands.start - 8, y: at + TICK_SIZE * CENTRE, anchor: \"end\", text }\n };\n}\n\n/** Data value to px along the value axis. */\nfunction position(scale: BarScale): (value: number) => number {\n const perUnit = scale.extent / (scale.hi - scale.lo);\n return (value) => scale.from + (value - scale.lo) * perUnit;\n}\n\ninterface Prepared<D> {\n readonly key: string;\n readonly category: string;\n readonly datum: D;\n readonly index: number;\n readonly values: readonly { readonly series: string; readonly value: number }[];\n readonly total: number;\n}\n\ninterface Domain {\n readonly lo: number;\n readonly hi: number;\n readonly ticks: readonly number[];\n}\n\nfunction prepareRows<D>({ data, encoding }: BarLayoutInput<D>): Prepared<D>[] {\n const keys = new Set<string>();\n return data.map((datum, index) => {\n const key = String(encoding.key(datum, index));\n if (keys.has(key)) throw new Error(`barChart: two rows have the key \"${key}\". Keys must be unique; pass a key accessor if categories repeat.`);\n keys.add(key);\n const values = encoding.series.map(({ series, value }) => ({ series, value: numberOf(value(datum, index), series, key) }));\n if (values.some((v) => v.value > 0) && values.some((v) => v.value < 0)) {\n throw new RangeError(`barChart: the stack for \"${key}\" mixes positive and negative values, which isn't supported yet.`);\n }\n const total = values.reduce((sum, v) => sum + v.value, 0);\n return { key, category: String(encoding.category(datum, index) ?? \"\"), datum, index, values, total };\n });\n}\n\nfunction sortRows<D>(rows: Prepared<D>[], sort: BarLayoutInput<D>[\"sort\"]): Prepared<D>[] {\n if (sort === undefined || sort === \"none\") return rows;\n // Array.prototype.sort is stable, so ties keep data order.\n if (sort === \"value\") return [...rows].sort((a, b) => b.total - a.total);\n if (sort === \"key\") return [...rows].sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));\n if (typeof sort === \"function\") return [...rows].sort((a, b) => sort(a.datum, b.datum));\n throw new TypeError(`barChart: sort must be \"value\", \"key\", \"none\" or a comparator, got ${String(sort)}.`);\n}\n\n/** Zero is always in the domain; the ends are rounded out to a 1, 2 or 5 step, about four ticks apart (as in the prototype). */\nexport function niceDomain(values: readonly number[]): Domain {\n let lo = values.reduce((min, v) => Math.min(min, v), 0);\n let hi = values.reduce((max, v) => Math.max(max, v), 0);\n if (lo === hi) hi = 1;\n const step = niceStep((hi - lo) / 4);\n lo = clean(Math.floor(lo / step) * step);\n hi = clean(Math.ceil(hi / step) * step);\n const count = Math.round((hi - lo) / step);\n const ticks = Array.from({ length: count + 1 }, (_, i) => clean(lo + i * step));\n return { lo, hi, ticks };\n}\n\n/** A round step near `span`: 1, 2, 5 or 10 times a power of 10. */\nexport function niceStep(span: number): number {\n const power = 10 ** Math.floor(Math.log10(span));\n const f = span / power;\n return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * power;\n}\n\nfunction horizontalFrame<D>(input: BarLayoutInput<D>, rows: readonly Prepared<D>[], domain: Domain, values: readonly string[], ticks: readonly string[]): BarFrame {\n const { width, measure } = input;\n const n = rows.length;\n const labelWidth = widest(rows.map((row) => row.category), \"ec-label\", LABEL_SIZE, measure);\n const valueWidth = widest(values, \"ec-value\", VALUE_SIZE, measure);\n const tickWidth = widest(ticks, \"ec-tick\", TICK_SIZE, measure);\n const { positive, negative } = reach(input, rows);\n // Value labels sit past the tip, so negative bars need room on the left as well.\n const negativeRoom = domain.lo < 0 ? valueWidth + PAD : 0;\n // `room` is outermost: past the names on the left, which negative bars' text goes past too.\n const left = Math.max(labelWidth + 10 + negativeRoom + negative, tickWidth / 2 + 2);\n const right = Math.max(valueWidth + PAD + 4 + positive, tickWidth / 2 + 2);\n const rowSize = input.height === undefined || n === 0 ? ROW : Math.max(0, input.height - TOP - AXIS) / n;\n return {\n orientation: \"horizontal\",\n scale: { lo: domain.lo, hi: domain.hi, from: left, extent: Math.max(0, width - left - right), label: left - 10 - negativeRoom },\n bands: { start: TOP, band: rowSize, thickness: (rowSize * BAR) / ROW, span: n * rowSize, width, height: input.height ?? TOP + n * rowSize + AXIS }\n };\n}\n\nfunction verticalFrame<D>(input: BarLayoutInput<D>, rows: readonly Prepared<D>[], domain: Domain, _values: readonly string[], ticks: readonly string[]): BarFrame {\n const { width, measure } = input;\n const n = rows.length;\n const height = input.height ?? VERTICAL_HEIGHT;\n const tickWidth = widest(ticks, \"ec-tick\", TICK_SIZE, measure);\n const { positive, negative } = reach(input, rows);\n // Room above positive columns (and below negative ones) for their value labels, and `room` past them.\n const top = (domain.hi > 0 ? VALUE_SIZE + PAD + 2 : TOP) + positive;\n const bottom = AXIS + (domain.lo < 0 ? VALUE_SIZE + PAD : 0) + negative;\n const left = tickWidth + 8 + 2;\n const plot = { x: left, y: top, width: Math.max(0, width - left - 8), height: Math.max(0, height - top - bottom) };\n const band = n > 0 ? plot.width / n : 0;\n const base = plot.y + plot.height;\n return {\n orientation: \"vertical\",\n scale: { lo: domain.lo, hi: domain.hi, from: base, extent: -plot.height, label: base + 18 },\n bands: { start: plot.x, band, thickness: Math.min((band * BAR) / ROW, MAX_COLUMN), span: plot.width, width, height }\n };\n}\n\n/**\n * `room` at each end of the value axis that bars reach: the positive end if a total is above 0, the\n * negative end if one is below. An end no bar reaches gets none, so nothing moves for it.\n */\nfunction reach<D>(input: BarLayoutInput<D>, rows: readonly Prepared<D>[]): { readonly positive: number; readonly negative: number } {\n const room = input.room ?? 0;\n return {\n positive: rows.some((row) => row.total > 0) ? room : 0,\n negative: rows.some((row) => row.total < 0) ? room : 0\n };\n}\n\n/**\n * Values along the walk: from 0 at the baseline to the total at the tip. `related(series)` is that\n * series' segment in the same row, its samples running over the segment's own span.\n */\nfunction barData<D>(datum: D, total: number, geometry: MarkGeometry): MarkData<D> {\n const valueAt = (distance: number): number => (geometry.length > 0 ? (total * distance) / geometry.length : 0);\n const data: MarkData<D> = {\n datum,\n samples: [\n { t: 0, value: 0 },\n { t: 1, value: total }\n ],\n related(series) {\n const segment = geometry.segments?.find((s) => s.series === series);\n if (!segment) return undefined;\n const from = Math.hypot(segment.start.x - geometry.start.x, segment.start.y - geometry.start.y);\n return {\n datum,\n samples: [\n { t: 0, value: valueAt(from) },\n { t: 1, value: valueAt(from + segment.length) }\n ],\n related: data.related\n };\n }\n };\n return data;\n}\n\nfunction widest(texts: readonly string[], className: string, size: number, measure: Measure): number {\n return texts.reduce((max, text) => Math.max(max, measure(text, className, size)), 0);\n}\n\nfunction accessor<D, T>(option: Accessor<D, T> | string): (d: D, i: number) => T {\n if (typeof option === \"function\") return option;\n return (d) => (d as Record<string, unknown>)[option] as T;\n}\n\n/** Every value is a number (or missing), and at least one is there. */\nfunction numeric<D>(data: readonly D[], read: (d: D, i: number) => unknown): boolean {\n let found = false;\n for (let i = 0; i < data.length; i++) {\n const value = read(data[i]!, i);\n if (value === null || value === undefined) continue;\n if (typeof value !== \"number\") return false;\n found = true;\n }\n return found;\n}\n\n/** Missing values (null, undefined) count as 0. */\nfunction numberOf(value: unknown, series: string, key: string): number {\n if (value === null || value === undefined) return 0;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new RangeError(`barChart: \"${series}\" for \"${key}\" must be a finite number, got ${typeof value === \"string\" ? JSON.stringify(value) : String(value)}.`);\n}\n\n/** Rounds away float noise (0.30000000000000004 is 0.3), and -0 to 0. */\nexport function clean(value: number): number {\n const rounded = Number(value.toPrecision(12));\n return rounded === 0 ? 0 : rounded;\n}\n","// Theme tokens: `--ec-*` CSS custom properties with light and dark defaults, and the small stylesheet\n// every chart shares. The stylesheet sets the defaults on the root element, following\n// prefers-color-scheme, and on any element with data-theme=\"light\" or \"dark\". Hosts theme a chart by\n// setting the custom properties; every default rule uses :where(), so host CSS overrides it without\n// specificity fights. The same text is injected as a <style> and shipped as dist/expressive-charts.css.\n\nimport type { Color } from \"../../core\";\n\n/** Palette slots run 1–8 and wrap after that. */\nexport const PALETTE_SIZE = 8;\n\n/** A theme's default token values. */\nexport interface Theme {\n readonly surface: string;\n readonly text: string;\n readonly \"text-muted\": string;\n readonly grid: string;\n readonly axis: string;\n readonly focus: string;\n readonly negative: string;\n /** Hairline borders on controls and the tooltip. */\n readonly ring: string;\n /** Opacity of the other marks' bodies while one is hovered: a number, not a colour. Their labels keep theirs. */\n readonly \"dim-opacity\": string;\n /** Slots 1–8: the mark colour, and its -strong variant for hover emphasis. */\n readonly series: readonly (readonly [color: string, strong: string])[];\n}\n\n/**\n * The defaults, validated in theme.test.ts: every mark colour has at least 3:1 contrast against the\n * surface, neighbouring slots stay apart under protanopia, deuteranopia and tritanopia, and each\n * -strong variant is its colour stepped toward the text colour. Slots 1–4 are the prototype's, except\n * that light 3 and 4 are darkened just enough to reach 3:1.\n */\nexport const themes: { readonly light: Theme; readonly dark: Theme } = {\n light: {\n surface: \"#fcfcfb\",\n text: \"#0b0b0b\",\n \"text-muted\": \"#75736d\",\n grid: \"#e1e0d9\",\n axis: \"#c3c2b7\",\n focus: \"#2a78d6\",\n negative: \"#d03b3b\",\n ring: \"rgba(11, 11, 11, 0.1)\",\n \"dim-opacity\": \"0.3\",\n series: [\n [\"#2a78d6\", \"#1c5cab\"],\n [\"#eb6834\", \"#c24d1d\"],\n [\"#02a471\", \"#07835a\"],\n [\"#c28409\", \"#9d6a07\"],\n [\"#8966da\", \"#6e49ba\"],\n [\"#0096b0\", \"#05778c\"],\n [\"#7a8a05\", \"#606d03\"],\n [\"#c34e97\", \"#a32f7a\"]\n ]\n },\n dark: {\n surface: \"#1a1a19\",\n text: \"#f0efec\",\n \"text-muted\": \"#8f8d86\",\n grid: \"#2c2c2a\",\n axis: \"#45453f\",\n focus: \"#3987e5\",\n negative: \"#e66767\",\n ring: \"rgba(255, 255, 255, 0.1)\",\n // Dimmed marks keep about the contrast they have in light (1.5:1 against 1.4:1 on average).\n \"dim-opacity\": \"0.3\",\n series: [\n [\"#3987e5\", \"#6da7ec\"],\n [\"#d95926\", \"#fb7747\"],\n [\"#199e70\", \"#45bc8c\"],\n [\"#c98500\", \"#eda100\"],\n [\"#936fe4\", \"#af8ffe\"],\n [\"#0b99b3\", \"#40b7d2\"],\n [\"#829401\", \"#9eb237\"],\n [\"#c8529c\", \"#e970ba\"]\n ]\n }\n};\n\n/** The colour tokens a drawing can name, besides the series. */\nconst COLOR_TOKENS = [\"surface\", \"text\", \"text-muted\", \"grid\", \"axis\", \"focus\", \"negative\"] as const;\ntype ColorToken = (typeof COLOR_TOKENS)[number];\n\n/** Light's colour tokens: the fallbacks in rules and inline styles, for a page that sets some tokens but has no stylesheet. */\nconst TOKENS: Readonly<Record<string, string>> = Object.fromEntries(COLOR_TOKENS.map((name) => [name, themes.light[name]])) as Record<ColorToken, string>;\n\n/** A series' colours as CSS: the mark colour and the stronger one used for hover emphasis. */\nexport interface SeriesColors {\n readonly color: string;\n readonly strong: string;\n}\n\n/** The CSS colours for a palette slot (1-based; wraps after PALETTE_SIZE), with light's as fallbacks. */\nexport function seriesColors(slot: number): SeriesColors {\n const n = ((Math.max(1, Math.floor(slot)) - 1) % PALETTE_SIZE) + 1;\n const [color, strong] = themes.light.series[n - 1]!;\n return { color: `var(--ec-series-${n}, ${color})`, strong: `var(--ec-series-${n}-strong, ${strong})` };\n}\n\n/**\n * A drawing-API colour as CSS. Theme tokens become custom properties with fallbacks; \"mark\" and\n * \"mark-strong\" are the colours of the mark a run belongs to (set on its overlay group as --ec-mark);\n * anything else passes through as a CSS colour.\n */\nexport function cssColor(color: Color): string {\n if (color === \"mark\") return `var(--ec-mark, ${seriesColors(1).color})`;\n if (color === \"mark-strong\") return `var(--ec-mark-strong, ${seriesColors(1).strong})`;\n const fallback = TOKENS[color];\n if (fallback !== undefined) return `var(--ec-${color}, ${fallback})`;\n const series = /^series-(\\d+)(-strong)?$/.exec(color);\n if (series) {\n const colors = seriesColors(Number(series[1]));\n return series[2] ? colors.strong : colors.color;\n }\n return color;\n}\n\n/** Sets --ec-mark and --ec-mark-strong, which the stylesheet and the \"mark\" token read. */\nexport function markColorStyles(colors: SeriesColors | undefined): Record<string, string | undefined> {\n return { \"--ec-mark\": colors?.color, \"--ec-mark-strong\": colors?.strong };\n}\n\n/** A theme as custom property declarations, one per line. */\nfunction declarations(theme: Theme, indent: string): string {\n const names = [...COLOR_TOKENS, \"ring\", \"dim-opacity\"] as const;\n const lines = names.map((name) => `--ec-${name}: ${theme[name]};`);\n theme.series.forEach(([color, strong], i) => lines.push(`--ec-series-${i + 1}: ${color};`, `--ec-series-${i + 1}-strong: ${strong};`));\n return lines.map((line) => indent + line).join(\"\\n\");\n}\n\n/**\n * The tokens: light on the root and on data-theme=\"light\"; dark when the device prefers it, unless the\n * root says data-theme=\"light\"; dark on data-theme=\"dark\". In that order, so data-theme on any element\n * sets its subtree's theme. :where() keeps all of it at zero specificity.\n */\nconst TOKEN_RULES = `:where(:root, [data-theme=\"light\"]) {\n${declarations(themes.light, \" \")}\n}\n@media (prefers-color-scheme: dark) {\n :where(:root:not([data-theme=\"light\"])) {\n${declarations(themes.dark, \" \")}\n }\n}\n:where([data-theme=\"dark\"]) {\n${declarations(themes.dark, \" \")}\n}`;\n\n// Hover dims the parts in each other mark's body, not the whole mark, so its labels keep their\n// contrast. Not the body itself either: an effect's opacity is an attribute there, which a rule would\n// override. On the parts, the two multiply.\nconst STYLES = `/* expressive-charts: theme tokens and default styles. Every rule has zero specificity, so your CSS wins. */\n${TOKEN_RULES}\n:where(.ec-chart) { display: block; max-width: 100%; height: auto; overflow: visible; touch-action: pan-y; -webkit-tap-highlight-color: transparent; }\n:where(.ec-chart text) { font-variant-numeric: tabular-nums; }\n:where(.ec-chart .ec-gridline) { stroke: var(--ec-grid, ${TOKENS.grid}); stroke-width: 1; }\n:where(.ec-chart .ec-baseline) { stroke: var(--ec-axis, ${TOKENS.axis}); stroke-width: 1; }\n:where(.ec-chart .ec-tick) { fill: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-size: 11px; }\n:where(.ec-chart .ec-label) { fill: var(--ec-text, ${TOKENS.text}); font-size: 12.5px; }\n:where(.ec-chart .ec-value, .ec-chart .ec-text) { fill: var(--ec-text, ${TOKENS.text}); font-size: 12.5px; font-weight: 600; }\n:where(.ec-overlay .ec-text) { fill: var(--ec-text, ${TOKENS.text}); font-size: 12.5px; font-weight: 600; font-variant-numeric: tabular-nums; }\n:where(.ec-chart .ec-hit) { fill: transparent; }\n:where(.ec-chart .ec-mark:focus) { outline: none; }\n:where(.ec-chart .ec-focus) { pointer-events: none; }\n:where(.ec-chart .ec-focus-ring) { fill: none; stroke: var(--ec-focus, ${TOKENS.focus}); }\n:where(.ec-chart .ec-focus-gap) { fill: var(--ec-surface, ${TOKENS.surface}); stroke: var(--ec-surface, ${TOKENS.surface}); }\n:where(.ec-chart .ec-body > *) { transition: opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-segment) { fill: var(--ec-mark); transition: fill var(--ec-hover-duration, 100ms) ease-out, opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-segment) { fill: var(--ec-mark-strong); }\n:where(.ec-chart .ec-stroke) { fill: none; stroke: var(--ec-mark); stroke-linejoin: round; transition: stroke var(--ec-hover-duration, 100ms) ease-out, opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-stroke) { stroke: var(--ec-mark-strong); }\n:where(.ec-chart .ec-end) { fill: var(--ec-mark); stroke: var(--ec-surface, ${TOKENS.surface}); stroke-width: 2; }\n:where(.ec-chart .ec-dot) { fill: var(--ec-mark); stroke: var(--ec-surface, ${TOKENS.surface}); stroke-width: 2; opacity: 0; transition: opacity var(--ec-hover-duration, 100ms) ease-out, fill var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-dot) { fill: var(--ec-mark-strong); opacity: 1; }\n:where(.ec-chart .ec-alone .ec-dot) { opacity: 1; }\n:where(.ec-chart .ec-crosshair) { stroke: var(--ec-axis, ${TOKENS.axis}); stroke-width: 1; stroke-dasharray: 3 3; pointer-events: none; }\n:where(.ec-chart .ec-column:focus) { outline: none; }\n:where(.ec-chart .ec-lines, .ec-chart .ec-points) { pointer-events: none; }\n:where(.ec-chart .ec-slice) { fill: var(--ec-mark); stroke: var(--ec-surface, ${TOKENS.surface}); stroke-width: 2; stroke-linejoin: round; transition: fill var(--ec-hover-duration, 100ms) ease-out, opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-slice) { fill: var(--ec-mark-strong); }\n:where(.ec-chart .ec-center-value) { fill: var(--ec-text, ${TOKENS.text}); font-size: 26px; font-weight: 600; }\n:where(.ec-chart .ec-center-label) { fill: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-size: 12.5px; }\n:where(.ec-chart.ec-hovering .ec-mark:not(.ec-hot) > .ec-body > *) { opacity: var(--ec-dim-opacity, 0.3); }\n:where(.ec-chart.ec-morphing .ec-marks) { visibility: hidden; }\n:where(.ec-switch) { display: grid; grid-template-columns: minmax(0, 1fr); position: relative; }\n:where(.ec-switch-view) { grid-area: 1 / 1; min-width: 0; }\n:where(.ec-switch-view.ec-switch-inactive) { visibility: hidden; }\n:where(.ec-switch-view.ec-switching .ec-focus, .ec-switch-view.ec-switching .ec-overlay, .ec-switch-view.ec-switching .ec-columns) { visibility: hidden; }\n:where(.ec-switch-overlay) { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; }\n:where(.ec-motion-switch) { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; color: var(--ec-text, ${TOKENS.text}); font-size: 13px; }\n:where(.ec-motion-label) { font-weight: 600; }\n:where(.ec-motion-modes) { display: inline-flex; gap: 2px; padding: 2px; border: 1px solid var(--ec-ring, color-mix(in srgb, currentColor 12%, transparent)); border-radius: 8px; background: var(--ec-surface, ${TOKENS.surface}); }\n:where(.ec-motion-modes button) { font: inherit; color: inherit; border: 0; background: transparent; padding: 5px 10px; border-radius: 6px; cursor: pointer; }\n:where(.ec-motion-modes button:hover, .ec-motion-modes button[aria-pressed=\"true\"]) { background: color-mix(in srgb, var(--ec-focus, ${TOKENS.focus}) 12%, transparent); }\n:where(.ec-motion-modes button[aria-pressed=\"true\"]) { font-weight: 600; }\n:where(.ec-motion-modes button:focus-visible) { outline: 2px solid var(--ec-focus, ${TOKENS.focus}); outline-offset: 2px; }\n@media (forced-colors: active) {\n /* Forced colours drop the pressed mode's tint, which leaves only its weight: it takes the viewer's selection colours. */\n :where(.ec-motion-modes button[aria-pressed=\"true\"]) { background: Highlight; color: HighlightText; }\n}\n:where(.ec-motion-hint) { flex: 1 1 220px; min-width: 0; color: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); }\n:where(.ec-play) { font: inherit; font-size: 13px; font-weight: 600; color: var(--ec-text, ${TOKENS.text}); border: 1px solid var(--ec-ring, color-mix(in srgb, currentColor 12%, transparent)); background: var(--ec-surface, ${TOKENS.surface}); padding: 6px 12px; border-radius: 8px; cursor: pointer; }\n:where(.ec-play:hover) { background: color-mix(in srgb, var(--ec-focus, ${TOKENS.focus}) 12%, var(--ec-surface, ${TOKENS.surface})); }\n:where(.ec-play:focus-visible) { outline: 2px solid var(--ec-focus, ${TOKENS.focus}); outline-offset: 2px; }\n:where(.ec-chart .ec-leaving, .ec-chart .ec-overlay) { pointer-events: none; }\n:where(.ec-attached.ec-dimmed) { opacity: var(--ec-dim-opacity, 0.3); }\n:where(.ec-attached) { transition: opacity var(--ec-hover-duration, 100ms) ease-out, fill var(--ec-hover-duration, 100ms) ease-out, stroke var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-tooltip-layer) { position: relative; height: 0; }\n:where(.ec-tooltip) { position: absolute; left: 0; top: 0; z-index: 3; box-sizing: border-box; width: max-content; max-width: 24em; padding: 8px 10px; border: 1px solid var(--ec-ring, color-mix(in srgb, currentColor 12%, transparent)); border-radius: 8px; background: var(--ec-surface, ${TOKENS.surface}); color: var(--ec-text, ${TOKENS.text}); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); font-size: 13px; line-height: 1.35; white-space: pre-line; font-variant-numeric: tabular-nums; pointer-events: none; opacity: 0; visibility: hidden; transition: opacity var(--ec-hover-duration, 100ms) ease-out, visibility 0s linear var(--ec-hover-duration, 100ms); }\n:where(.ec-tooltip.ec-tooltip-shown) { opacity: 1; visibility: visible; pointer-events: auto; transition: opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-tooltip-bridge) { position: absolute; left: 0; top: 0; z-index: 3; pointer-events: none; }\n:where(.ec-tooltip-shown + .ec-tooltip-bridge) { pointer-events: auto; }\n:where(.ec-tooltip-through > .ec-tooltip, .ec-tooltip-through > .ec-tooltip-bridge) { pointer-events: none; }\n:where(.ec-tooltip-title) { font-weight: 600; }\n:where(.ec-legend) { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-bottom: 8px; font-size: 13px; line-height: 1.4; color: var(--ec-text, ${TOKENS.text}); }\n:where(.ec-legend-item) { display: inline-flex; align-items: center; gap: 6px; }\n:where(.ec-legend-swatch) { flex: none; width: 10px; height: 10px; border-radius: 3px; background: var(--ec-mark); forced-color-adjust: none; }\n:where(.ec-table) { margin-top: 8px; font-size: 13px; line-height: 1.4; color: var(--ec-text, ${TOKENS.text}); }\n:where(.ec-table summary) { cursor: pointer; color: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-weight: 600; }\n:where(.ec-table summary:focus-visible) { outline: 2px solid var(--ec-focus, ${TOKENS.focus}); outline-offset: 2px; border-radius: 2px; }\n:where(.ec-table-scroll) { overflow-x: auto; margin-top: 8px; }\n:where(.ec-table table) { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }\n:where(.ec-table th, .ec-table td) { text-align: left; padding: 4px 10px 4px 0; border-bottom: 1px solid var(--ec-grid, ${TOKENS.grid}); font-weight: 400; }\n:where(.ec-table thead th) { color: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-size: 12px; font-weight: 600; }\n:where(.ec-table .ec-num) { text-align: right; }\n:where(.ec-table-caption, .ec-visually-hidden) { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }\n`;\n\nconst MARKER = \"data-expressive-charts\";\n\n/** The stylesheet's text: what's injected, and what the build writes to dist/expressive-charts.css. */\nexport const stylesheet = STYLES;\n\n/** How the stylesheet reaches the page. */\nexport interface StyleOptions {\n /** Set on the injected `<style>`, for a Content-Security-Policy that allows styles by nonce. */\n readonly nonce?: string | undefined;\n /** false: inject nothing; the page loads expressive-charts/style.css itself. Default true. */\n readonly injectStyles?: boolean | undefined;\n}\n\n/**\n * Page-wide, like the stylesheet itself, which is injected once per document by whatever is created\n * first (a chart, an adapter, a control). Set with configure().\n */\nexport const styleOptions: { nonce?: string | undefined; injectStyles?: boolean | undefined } = {};\n\n/** Adds the shared stylesheet to the document once, unless the page loads it itself. */\nexport function injectStyles(doc: Document): void {\n if (styleOptions.injectStyles === false || doc.querySelector(`style[${MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(MARKER, \"\");\n // Before the element is connected: CSP checks the nonce when the stylesheet is created.\n if (styleOptions.nonce) style.setAttribute(\"nonce\", styleOptions.nonce);\n style.textContent = STYLES;\n (doc.head ?? doc.documentElement).appendChild(style);\n}\n","// Categorical colours follow the entity: a key keeps its palette slot through sorts, filters and\n// updates, and charts can share an assignment so the same entity has the same colour in both.\n\nimport { PALETTE_SIZE } from \"./render/theme\";\n\nexport interface ColorAssignment {\n /** The palette slot (1–8) for a key: its pinned slot, or the next free one the first time it's seen. Never reassigned. */\n slot(key: string): number;\n}\n\n/** `fixed` pins slots, as in the prototype's `{ goals: 1, assists: 4 }`. Other keys take free slots in the order they're first seen. */\nexport function colorAssignment(fixed: Readonly<Record<string, number>> = {}): ColorAssignment {\n const slots = new Map<string, number>();\n for (const [key, slot] of Object.entries(fixed)) {\n if (!Number.isInteger(slot) || slot < 1 || slot > PALETTE_SIZE) {\n throw new RangeError(`colorAssignment: the slot for \"${key}\" must be a whole number from 1 to ${PALETTE_SIZE}, got ${String(slot)}.`);\n }\n slots.set(key, slot);\n }\n return {\n slot(key) {\n let slot = slots.get(key);\n if (slot === undefined) {\n const used = new Set(slots.values());\n slot = 1;\n while (used.has(slot) && slot <= PALETTE_SIZE) slot++;\n // Every slot taken: reuse them in turn.\n if (slot > PALETTE_SIZE) slot = (slots.size % PALETTE_SIZE) + 1;\n slots.set(key, slot);\n }\n return slot;\n }\n };\n}\n\n/** The `colors` option as an assignment: a shared one as is, a record as pinned slots. */\nexport function toColorAssignment(colors: ColorAssignment | Readonly<Record<string, number>> | undefined): ColorAssignment {\n if (colors && typeof (colors as ColorAssignment).slot === \"function\") return colors as ColorAssignment;\n return colorAssignment(colors as Readonly<Record<string, number>> | undefined);\n}\n","// The chart's legend: a swatch and a name for each series (bars, when there's more than one) or each\n// category (a donut's slices), above the chart, then any entries the page adds for colours its effects\n// draw. Swatches take their colours from the chart's ColorAssignment, so an entry keeps its colour\n// through every change, and a page's entries from their own colour; the names (the series' labels, the\n// categories or the page's labels) are in the theme's text colour, never a series colour.\n\nimport type { ColorAssignment } from \"./colors\";\nimport { cssColor, markColorStyles, seriesColors } from \"./render/theme\";\nimport type { ChartOptions, LegendEntry, LegendOptions } from \"./types\";\n\n/** The `legend` option. */\nexport type LegendOption = ChartOptions<unknown>[\"legend\"];\n\nexport interface Legend {\n /**\n * Shows `series` in order, each named by its label, then the page's entries from `option`; or\n * removes the legend when `option` is false, or when it would list fewer than two entries in all.\n */\n update(series: readonly { readonly series: string; readonly label: string }[], colors: ColorAssignment, option: LegendOption): void;\n /**\n * Shows `categories` in order, each coloured by its key and named by its category, then the page's\n * entries; or removes the legend when there are no categories or `option` is false. One category is\n * listed too: it names the colour.\n */\n categories(categories: readonly { readonly key: string; readonly label: string }[], colors: ColorAssignment, option: LegendOption): void;\n destroy(): void;\n}\n\n/** Throws on a `legend` option that isn't true, false or an object of valid entries. `chart` names the chart in the message. */\nexport function checkLegendOption(option: unknown, chart: string): void {\n if (option === undefined || typeof option === \"boolean\") return;\n const fail = (what: string): never => {\n throw new TypeError(`${chart}: ${what}`);\n };\n if (typeof option !== \"object\" || option === null || Array.isArray(option)) fail(\"legend must be true or false, or an object with the entries the page adds.\");\n const { entries } = option as LegendOptions;\n if (entries === undefined) return;\n if (!Array.isArray(entries)) fail(\"legend.entries must be an array of { label, color }.\");\n entries.forEach((entry: Partial<LegendEntry> | null, i: number) => {\n const { label, color } = typeof entry === \"object\" && entry !== null ? entry : fail(`legend.entries[${i}] must be an object with a label and a color.`);\n if (typeof label !== \"string\" || label.trim() === \"\") fail(`legend.entries[${i}].label must be a non-empty string: the entry's name.`);\n if (typeof color !== \"string\" || color.trim() === \"\") fail(`legend.entries[${i}].color must be a theme token or a CSS colour.`);\n if (color === \"mark\" || color === \"mark-strong\") fail(`legend.entries[${i}].color can't be \"${color}\": an entry has no mark. Use a theme token or a CSS colour.`);\n });\n}\n\n/** The entries the page adds, from the option. */\nconst extras = (option: LegendOption): readonly LegendEntry[] => (typeof option === \"object\" ? (option.entries ?? []) : []);\n\n/** The legend for a chart's <svg>: made when it's first needed, just before the <svg>. */\nexport function chartLegend(svg: SVGSVGElement): Legend {\n let legend: HTMLDivElement | undefined;\n /** What the legend shows: the entries, their names and their colours. */\n let drawn = \"\";\n\n const remove = (): void => {\n legend?.remove();\n legend = undefined;\n drawn = \"\";\n };\n\n /**\n * Draws the chart's entries, then the page's; `attribute` names each of the chart's entries' key on\n * its element (data-series or data-key).\n */\n const draw = (entries: readonly { readonly key: string; readonly label: string }[], colors: ColorAssignment, attribute: string, more: readonly LegendEntry[]): void => {\n const items = [\n ...entries.map(({ key, label }) => ({ key, label, styles: markColorStyles(seriesColors(colors.slot(key))) })),\n ...more.map(({ label, color }) => ({ key: undefined, label, styles: { \"--ec-mark\": cssColor(color) } }))\n ];\n const doc = svg.ownerDocument;\n legend ??= Object.assign(doc.createElement(\"div\"), { className: \"ec-legend\" });\n if (legend.nextSibling !== svg) svg.before(legend);\n const id = JSON.stringify([attribute, items]);\n if (id === drawn) return;\n drawn = id;\n legend.replaceChildren(\n ...items.map(({ key, label: text, styles }) => {\n const item = doc.createElement(\"span\");\n item.className = \"ec-legend-item\";\n if (key !== undefined) item.setAttribute(attribute, key);\n // The swatch reads --ec-mark, as a mark's segments do.\n for (const [property, value] of Object.entries(styles)) if (value !== undefined) item.style.setProperty(property, value);\n const swatch = doc.createElement(\"span\");\n swatch.className = \"ec-legend-swatch\";\n const label = doc.createElement(\"span\");\n label.className = \"ec-legend-label\";\n label.textContent = text;\n item.append(swatch, label);\n return item;\n })\n );\n };\n\n return {\n update(series, colors, option) {\n const more = extras(option);\n if (option === false || series.length + more.length < 2) remove();\n else draw(series.map(({ series: key, label }) => ({ key, label })), colors, \"data-series\", more);\n },\n categories(categories, colors, option) {\n if (option === false || categories.length === 0) remove();\n else draw(categories, colors, \"data-key\", extras(option));\n },\n destroy: remove\n };\n}\n","// Linked hover (M7 step 4): hovering a mark in one chart or attachment hovers the marks that share its\n// linking value in the others, with `source: \"linked\"`. It isn't an effect, since it hovers other\n// marks: it lives with the charts, as hover dimming does. Each chart and attachment registers its hover\n// here when it's made, keyed by its handle, so a link can hover given marks without focus. Nothing\n// new is public on the handles.\n\nimport type { MarkGeometry } from \"../core\";\nimport { report } from \"../core/report\";\nimport type { RunInput } from \"../core/runner\";\nimport type { MarkEvent, MarkEvents } from \"./types\";\n\n/** What a link takes: a chart (barChart, donutChart, lineChart) or an attachment (expressive, fromVegaView), with rows D. */\nexport interface LinkSource<D> {\n on(type: \"hover\", listener: (event: MarkEvents<D>[\"hover\"]) => void): () => void;\n marks(): readonly MarkGeometry[];\n}\n\n/** The rows of the sources in S: each chart's and attachment's, as a union. */\ntype RowsOf<S> = S extends LinkSource<infer D> ? D : never;\n\nexport interface LinkOptions<D> {\n /**\n * A mark's linking value, given the mark and its data as a hover event has them. Default: its last\n * sample's `at` if it has one (a line point's x), else its key (a bar's or a slice's category).\n * Values are compared as strings, a Date by its ISO string, as keys are. Undefined or null links\n * nothing, and so does a throw (reported).\n */\n readonly by?: (event: Pick<MarkEvent<D>, \"mark\" | \"data\">) => unknown;\n /** Whether linked marks play their chart's hover effect. Default true; false keeps them to emphasis and dimming. */\n readonly effects?: boolean;\n}\n\nexport interface Link {\n /** Ends the link: linked hovers end, and each source can be linked again. The sources' own hovers go on. */\n destroy(): void;\n}\n\n/** A source's hover as a link drives it: what chartHover and expressive() register for their handle. */\nexport interface LinkPort {\n /** The live targets, in visual order, each with its marks as on screen: what their linking values are read from. */\n targets(): readonly { readonly key: string; readonly marks: readonly RunInput[] }[];\n /**\n * Ends the hover there was, then hovers the live targets `keys` for a link: their marks' emphasis,\n * the others' dimming and, with `effects`, their hover effects, with \"linked\" events. No tooltip,\n * focus ring or focus, and nothing is announced. With no keys it only ends the hover.\n */\n hover(keys: readonly string[], effects: boolean): void;\n /** Ends a link's hover. The source's own goes on. */\n unlink(): void;\n /** Ends the hover, its own or a link's, as the source's leave() does. */\n leave(): void;\n /** Sets the link that hears its own hovers, or none. False, setting nothing, once the source is destroyed. */\n listen(listener: LinkListener | undefined): boolean;\n}\n\n/** What a source tells its link. */\nexport interface LinkListener {\n /** Its own hover started, from the pointer, touch or the keyboard, on these marks. */\n hover(marks: readonly RunInput[]): void;\n /** Its own hover ended. */\n leave(): void;\n /** Escape, with focus on it while it shows a link's hover: the link's hover ends, where it started. */\n dismiss(): void;\n /** It was destroyed. */\n gone(): void;\n}\n\n/** Whether a hover is the source's own, from the pointer, touch or the keyboard: not a link's. */\nexport const own = <H extends { readonly source: string }>(hovered: H | undefined): hovered is H => hovered !== undefined && hovered.source !== \"linked\";\n\nconst ports = new WeakMap<object, LinkPort>();\n/** Ports in a link now: a source can be in one at a time. */\nconst linked = new WeakSet<LinkPort>();\n\n/** Registers a chart's or attachment's hover for its handle, and returns the handle. */\nexport function linkable<T extends object>(port: LinkPort, handle: T): T {\n ports.set(handle, port);\n return handle;\n}\n\n/** The hover registered for a handle: for a handle that wraps another, as fromVegaView's wraps expressive()'s. */\nexport const portOf = (handle: object): LinkPort | undefined => ports.get(handle);\n\n/**\n * Links hover across `sources`: when one is hovered by the pointer, touch or the keyboard, every other\n * hovers its targets with that linking value (a line chart its x, a bar chart its bar), as `source:\n * \"linked\"`, and leaves them when it leaves. The newest hover anywhere in the link is the one shown.\n * Throws a TypeError, linking nothing, on a source that isn't a chart or an attachment, or one that's\n * in a link already. A destroyed source drops out.\n */\nexport function link<S extends LinkSource<unknown>>(sources: readonly S[], options: LinkOptions<RowsOf<S>> = {}): Link {\n if (!Array.isArray(sources)) throw new TypeError(\"link needs an array of charts and attachments: link([columns, line]).\");\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"link: options must be an object, such as { by: (event) => event.data.datum.week }.\");\n const { by, effects = true } = options;\n if (by !== undefined && typeof by !== \"function\") throw new TypeError(\"link: by must be a function, such as (event) => event.data.datum.week.\");\n if (typeof effects !== \"boolean\") throw new TypeError(`link: effects must be true or false, got ${String(effects)}.`);\n const members: LinkPort[] = [];\n for (const source of sources) {\n const port = typeof source === \"object\" && source !== null ? ports.get(source) : undefined;\n if (!port) {\n throw new TypeError(\"link: each source must be a chart (barChart, donutChart or lineChart) or an attachment (expressive or fromVegaView). A chartSwitch can't be linked yet.\");\n }\n if (linked.has(port) || members.includes(port)) throw new TypeError(\"link: a chart or attachment can be in one link at a time. Destroy the link it's in first.\");\n members.push(port);\n }\n\n /** The sources still in the link. */\n const live = new Set<LinkPort>();\n /** The source whose own hover the link shows. */\n let origin: LinkPort | undefined;\n\n /** A mark's linking value as a string, or undefined for none. */\n function valueOf(input: RunInput): string | undefined {\n let value: unknown;\n if (by) {\n try {\n value = by(input as RunInput<RowsOf<S>>);\n } catch (error) {\n report(error);\n return undefined;\n }\n } else {\n const { samples } = input.data;\n value = samples[samples.length - 1]?.at ?? input.mark.key;\n }\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value.toISOString();\n return value === undefined || value === null ? undefined : String(value);\n }\n\n function hovered(from: LinkPort, marks: readonly RunInput[]): void {\n origin = from;\n const values = new Set(marks.map(valueOf));\n values.delete(undefined);\n /** Whether a target has a mark with one of the hovered marks' values. */\n const matches = (target: readonly RunInput[]): boolean => target.some((mark) => {\n const value = valueOf(mark);\n return value !== undefined && values.has(value);\n });\n for (const port of live) {\n if (port === from) continue;\n const keys = values.size === 0 ? [] : port.targets().flatMap((target) => (matches(target.marks) ? [target.key] : []));\n port.hover(keys, effects);\n // A listener started another hover meanwhile: that one is shown.\n if (origin !== from) return;\n }\n }\n\n function left(from: LinkPort): void {\n if (origin !== from) return;\n origin = undefined;\n for (const port of live) port.unlink();\n }\n\n for (const port of members) {\n const listening = port.listen({\n hover: (marks) => hovered(port, marks),\n leave: () => left(port),\n dismiss() {\n const from = origin;\n from?.leave();\n if (from) left(from);\n },\n gone() {\n live.delete(port);\n linked.delete(port);\n left(port);\n }\n });\n if (!listening) continue;\n live.add(port);\n linked.add(port);\n }\n\n return {\n destroy() {\n for (const port of live) {\n port.listen(undefined);\n port.unlink();\n linked.delete(port);\n }\n live.clear();\n origin = undefined;\n }\n };\n}\n","// A chart's motion: the page-wide one, the author's own Motion, or a mode string. A mode is a per-chart\n// author default, like setMode(): the viewer's choice and the device's reduced-motion setting still win.\n\nimport { defaultScaling, scaleDuration, type Motion, type MotionMode, type MotionView } from \"../core\";\n\nexport type ChartMotion = MotionView & Pick<Motion, \"subscribe\">;\n\nconst MODES: readonly MotionMode[] = [\"presentation\", \"analysis\", \"off\"];\n\nexport function chartMotion(option: Motion | MotionMode | undefined, page: Motion): ChartMotion {\n if (option === undefined) return page;\n if (typeof option !== \"string\") return option;\n if (!MODES.includes(option)) throw new TypeError(`Unknown motion mode \"${String(option)}\". Use one of: ${MODES.join(\", \")}.`);\n const effective = (): MotionMode => page.viewerChoice ?? (page.prefersReduced ? \"off\" : option);\n return {\n get mode() {\n return effective();\n },\n get staged() {\n return effective() === \"presentation\";\n },\n duration(base, timing = \"transition\") {\n const mode = effective();\n return mode === \"off\" ? 0 : scaleDuration(base, defaultScaling[mode][timing]);\n },\n subscribe: (listener) => page.subscribe(listener)\n };\n}\n","// The focus ring and halos drawn above the marks, masked to outside the mark: they show evenly on every\n// side of marks that touch (a donut's slices), and never cover the mark itself. expressive() draws its\n// ring and halos this way, since its overlay is above the host's marks, and so does donutChart.\n\nimport type { MarkStyle, Matrix, Outline } from \"../../core\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { cssColor } from \"./theme\";\n\n/** The focus ring's px: a gap around the mark, then the ring, as on barChart. */\nexport const RING_GAP = 2;\nexport const RING = 2;\n\n/** What the focus ring goes round: the mark's outline as it is on screen, and an effect's transform on it. */\nexport interface RingTarget {\n readonly outline: Outline;\n /** An open outline (a line) is its stroke's centre: the gap starts at the stroke's edge. */\n readonly thickness: number;\n readonly transform?: Matrix | undefined;\n}\n\nexport interface MaskedRing {\n /** Draws the ring round `target`, or hides it. */\n draw(target: RingTarget | undefined): void;\n}\n\n/** Focus-ring masks made in each document, for their ids: a page's markup doesn't depend on other pages. */\nconst ringMasks = new WeakMap<Document, number>();\n/** Halo masks, for their ids. */\nlet haloMasks = 0;\n\n/**\n * The focus ring, appended to `parent`: a 2 px ring in --ec-focus, 2 px out from the mark. It's a\n * stroke on the outline, masked to outside the mark and its gap, so it can't cover data or merge with\n * a mark in the focus colour. The gap is left clear rather than painted, since what's behind may be\n * any colour. The mask is in the ring's own user space, so the ring takes an effect's transform whole.\n */\nexport function maskedRing(parent: SVGGElement): MaskedRing {\n const doc = parent.ownerDocument;\n const number = (ringMasks.get(doc) ?? 0) + 1;\n ringMasks.set(doc, number);\n const mask = svgElement(\"mask\", { id: `ec-focus-mask-${number}`, maskUnits: \"userSpaceOnUse\", x: -1e5, y: -1e5, width: 2e5, height: 2e5 }, parent);\n svgElement(\"rect\", { x: -1e5, y: -1e5, width: 2e5, height: 2e5, fill: \"white\" }, mask);\n const hole = svgElement(\"path\", { stroke: \"black\", \"stroke-linejoin\": \"round\" }, mask);\n const ring = svgElement(\"path\", { class: \"ec-focus-ring\", visibility: \"hidden\", \"stroke-linejoin\": \"round\", mask: `url(#${mask.id})` }, parent);\n setStyles(ring, { fill: \"none\", stroke: cssColor(\"focus\") });\n return {\n draw(target) {\n if (!target) {\n setAttributes(ring, { visibility: \"hidden\" });\n return;\n }\n const { outline, thickness, transform } = target;\n // The hole isn't filled for an open outline: a fill would close the line into a polygon and hide\n // the ring along its inside.\n const stroke = outline.closed ? 0 : thickness;\n setAttributes(hole, { d: outline.d, fill: outline.closed ? \"black\" : \"none\", \"stroke-width\": stroke + 2 * RING_GAP });\n setAttributes(ring, {\n d: outline.d,\n \"stroke-width\": stroke + 2 * (RING_GAP + RING),\n transform: transform && transformAttribute(transform),\n visibility: undefined\n });\n }\n };\n}\n\n/** One part of a mark the halo goes round: its outline, and its own colour (what the halo is drawn in by default). */\nexport interface HaloPart {\n readonly d: string;\n readonly color: string | undefined;\n /** An open outline (a line) is its stroke's centre: the stroke's width. Undefined for a closed outline. */\n readonly stroke?: number | undefined;\n}\n\nexport interface MaskedHalo {\n /**\n * Strokes each part's outline in a group of its own in `container`, at `width` (half of it outside\n * the mark), masked to outside the mark, so it shows only where it would behind the mark. Around an\n * open outline, the mask cuts out the stroke, as the ring's does, and the halo is stroked at the\n * stroke's width plus its own with round caps, so as much of it shows as round a closed mark, ends\n * included, as svgMarkHandle's halo behind a line does. Moved with the mark's `transform`. No halo,\n * no container or no parts removes it.\n */\n paint(container: SVGGElement | undefined, parts: readonly HaloPart[], halo: MarkStyle[\"halo\"], transform: Matrix | undefined): void;\n remove(): void;\n}\n\nexport function maskedHalo(): MaskedHalo {\n let group: SVGGElement | undefined;\n const remove = (): void => {\n group?.remove();\n group = undefined;\n };\n return {\n paint(container, parts, halo, transform) {\n if (!halo || !container || parts.length === 0) {\n remove();\n return;\n }\n if (!group || group.parentNode !== container) {\n group?.remove();\n group = svgElement(\"g\", { class: \"ec-halo\" }, container);\n }\n group.textContent = \"\";\n const id = `ec-halo-mask-${++haloMasks}`;\n const mask = svgElement(\"mask\", { id, maskUnits: \"userSpaceOnUse\", x: -1e5, y: -1e5, width: 2e5, height: 2e5 }, group);\n svgElement(\"rect\", { x: -1e5, y: -1e5, width: 2e5, height: 2e5, fill: \"white\" }, mask);\n for (const part of parts) {\n // Not filled for an open outline: a fill would close the line into a polygon and mask the halo along its inside.\n const cut = part.stroke === undefined ? { fill: \"black\" } : { fill: \"none\", stroke: \"black\", \"stroke-width\": part.stroke, \"stroke-linejoin\": \"round\" };\n svgElement(\"path\", { d: part.d, ...cut }, mask);\n }\n setAttributes(group, { transform: transform && transformAttribute(transform) });\n for (const part of parts) {\n const open = part.stroke !== undefined;\n const path = svgElement(\n \"path\",\n { d: part.d, \"stroke-width\": halo.width + (part.stroke ?? 0), \"stroke-opacity\": halo.opacity, \"stroke-linejoin\": \"round\", \"stroke-linecap\": open ? \"round\" : undefined, mask: `url(#${id})` },\n group\n );\n setStyles(path, { fill: \"none\", stroke: halo.color === undefined ? (part.color ?? cssColor(\"mark\")) : cssColor(halo.color) });\n }\n },\n remove\n };\n}\n","// The drawing API's MarkHandle in SVG: effects restyle a mark through it (transform, opacity, emphasis,\n// halo). The runner merges every live run's style before calling it.\n\nimport type { MarkHandle, MarkStyle } from \"../../core\";\nimport { mergeFields } from \"../../core/merge\";\nimport { maskedHalo } from \"./outside\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { cssColor, type SeriesColors } from \"./theme\";\n\n/** One part of a mark: a filled bar segment or slice, or a stroked line. */\nexport interface StyledPart {\n readonly element: SVGPathElement;\n /** The part's outline, which the halo follows. */\n readonly d: string;\n readonly colors: SeriesColors;\n /** False for parts too short to see (a zero value): they get no halo. */\n readonly visible: boolean;\n /**\n * For an open outline (a line), which is stroked rather than filled: the stroke's width. Emphasis\n * then mixes the stroke's colour, and the halo is stroked behind it this much wider than its own\n * width, so as much of it shows on each side as round a closed mark.\n */\n readonly open?: { readonly width: number };\n}\n\n/** What a style applies to: the mark's body group (it moves with `transform`) and its parts. */\nexport interface StyleTarget {\n readonly body: SVGGElement;\n readonly parts: readonly StyledPart[];\n}\n\nexport interface SvgMarkHandleOptions {\n /**\n * Where halos go instead of behind the mark: a group above the marks, where each is masked to\n * outside its mark (render/outside.ts). For marks that touch, such as slices, so a halo shows evenly\n * on every side instead of under the neighbour drawn after it.\n */\n readonly halos?: () => SVGGElement | undefined;\n}\n\nexport interface SvgMarkHandle extends MarkHandle {\n readonly style: MarkStyle;\n /** Applies the current style again, after the mark was redrawn (new parts or outlines). */\n repaint(): void;\n}\n\n/**\n * - `transform` is in chart space, on the body, so labels and the hit area stay put.\n * - `opacity` is on the body; it multiplies with the built-in hover dimming.\n * - `emphasis` mixes each part's colour toward its strong colour, without the CSS hover transition\n * (effects animate it themselves): its fill, or an open part's stroke.\n * - `halo` strokes each visible part's outline behind the mark: `width` is the stroke width, so half\n * of it shows outside the mark. An open part's halo is its own width wider, with round caps, so it\n * goes round the line's ends too. With `halos`, it's drawn there instead, masked to outside the mark\n * (outside an open part's stroke).\n */\nexport function svgMarkHandle(target: () => StyleTarget | undefined, options: SvgMarkHandleOptions = {}): SvgMarkHandle {\n let style: MarkStyle = {};\n let halo: SVGGElement | undefined;\n const above = options.halos && maskedHalo();\n\n const repaint = (): void => {\n const current = target();\n if (!current) return;\n const { body, parts } = current;\n setAttributes(body, {\n transform: style.transform && transformAttribute(style.transform),\n opacity: style.opacity\n });\n const emphasis = style.emphasis;\n for (const part of parts) {\n setStyles(part.element, {\n [part.open ? \"stroke\" : \"fill\"]: emphasis === undefined ? undefined : mix(part.colors, emphasis),\n transition: emphasis === undefined ? undefined : \"none\"\n });\n }\n paintHalo(body, parts);\n };\n\n const paintHalo = (body: SVGGElement, parts: readonly StyledPart[]): void => {\n const spec = style.halo;\n if (above) {\n const visible = parts.flatMap((part) => (part.visible ? [{ d: part.d, color: part.colors.color, ...(part.open ? { stroke: part.open.width } : {}) }] : []));\n above.paint(options.halos?.(), visible, spec, style.transform);\n return;\n }\n if (!spec) {\n halo?.remove();\n halo = undefined;\n return;\n }\n if (!halo || halo.parentNode !== body) {\n halo?.remove();\n halo = svgElement(\"g\", { class: \"ec-halo\" }, body);\n body.insertBefore(halo, body.firstChild);\n }\n const visible = parts.filter((part) => part.visible);\n while (halo.childElementCount > visible.length) halo.lastElementChild?.remove();\n visible.forEach((part, index) => {\n const path = (halo!.children[index] as SVGPathElement | undefined) ?? svgElement(\"path\", { \"stroke-linejoin\": \"round\" }, halo);\n setAttributes(path, {\n d: part.d,\n \"stroke-width\": spec.width + (part.open?.width ?? 0),\n \"stroke-opacity\": spec.opacity,\n \"stroke-linecap\": part.open ? \"round\" : undefined\n });\n setStyles(path, { fill: \"none\", stroke: spec.color === undefined ? part.colors.color : cssColor(spec.color) });\n });\n };\n\n return {\n get style() {\n return style;\n },\n set(next) {\n style = mergeFields(style, next);\n repaint();\n },\n reset() {\n style = {};\n repaint();\n },\n repaint\n };\n}\n\nfunction mix(colors: SeriesColors, emphasis: number): string {\n const amount = Math.min(1, Math.max(0, emphasis));\n if (amount === 0) return colors.color;\n if (amount === 1) return colors.strong;\n return `color-mix(in srgb, ${colors.strong} ${Math.round(amount * 1000) / 10}%, ${colors.color})`;\n}\n","// The drawing API's Layer in SVG: one run's overlay group. See src/core/contracts/drawing.ts.\n\nimport { matrix, type Icon, type IconHandle, type IconShape, type Layer, type Paint, type PathHandle, type TextHandle, type TextStyle } from \"../../core\";\nimport { mergeFields } from \"../../core/merge\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { cssColor } from \"./theme\";\n\nlet clipIds = 0;\n\n/** Draws into `group`. Handles keep working on removed elements, so calls after a clear are harmless. */\nexport function svgLayer(group: SVGGElement): Layer {\n return {\n icon(icon, options) {\n const size = options?.size;\n if (size !== undefined && !(size >= 0)) throw new RangeError(`layer.icon: size must be a non-negative number, got ${String(size)}.`);\n // Hidden until the first place().\n const placed = svgElement(\"g\", { class: \"ec-icon\", \"data-icon\": icon.name, visibility: \"hidden\" }, group);\n // The size rule: scale by size / icon.size about the anchor, in icon space, before place().\n const k = size === undefined || !(icon.size > 0) ? 1 : size / icon.size;\n const body = k === 1 ? placed : svgElement(\"g\", { transform: transformAttribute(matrix.scale(k, k, icon.anchor)) }, placed);\n for (const shape of icon.shapes) drawShape(shape, body);\n const handle: IconHandle = {\n place(transform) {\n setAttributes(placed, { transform: transformAttribute(transform), visibility: undefined });\n },\n remove: () => placed.remove()\n };\n return handle;\n },\n\n path(d, paint) {\n const element = svgElement(\"path\", { class: \"ec-path\", d }, group);\n let current: Paint = { ...paint };\n paintPath(element, current);\n const handle: PathHandle = {\n update(next, nextPaint) {\n element.setAttribute(\"d\", next);\n if (nextPaint) {\n current = mergeFields(current, nextPaint);\n paintPath(element, current);\n }\n },\n remove: () => element.remove()\n };\n return handle;\n },\n\n text(content, style) {\n const element = svgElement(\"text\", { class: \"ec-text\" }, group);\n element.textContent = content;\n let current: TextStyle = { ...style };\n styleText(element, current);\n const handle: TextHandle = {\n update(nextStyle, nextContent) {\n current = mergeFields(current, nextStyle);\n styleText(element, current);\n if (nextContent !== undefined) element.textContent = nextContent;\n },\n remove: () => element.remove()\n };\n return handle;\n }\n };\n}\n\n/**\n * One path per shape. Unset fill or stroke draws none; the width is in icon units, so it scales with the icon.\n * The fill rule and opacity are SVG's own, so unset ones are left to SVG's defaults: nonzero, and 1.\n */\nfunction drawShape(shape: IconShape, parent: SVGGElement): void {\n let clip: string | undefined;\n if (shape.clip !== undefined) {\n // userSpaceOnUse (the default) puts the clip path in the shape's own space: icon space.\n clip = `ec-clip-${++clipIds}`;\n const clipPath = svgElement(\"clipPath\", { id: clip }, parent);\n svgElement(\"path\", { d: shape.clip }, clipPath);\n }\n const element = svgElement(\n \"path\",\n {\n d: shape.d,\n \"clip-path\": clip && `url(#${clip})`,\n \"stroke-width\": shape.stroke === undefined ? undefined : (shape.width ?? 1),\n \"stroke-linecap\": shape.linecap,\n \"stroke-linejoin\": shape.linejoin,\n \"fill-rule\": shape.fillRule,\n opacity: shape.opacity\n },\n parent\n );\n setStyles(element, {\n // SVG's default fill is black, so \"none\" is set explicitly.\n fill: shape.fill === undefined ? \"none\" : cssColor(shape.fill),\n stroke: shape.stroke === undefined ? undefined : cssColor(shape.stroke)\n });\n}\n\n/** Overlay paths are unfilled unless a fill is given. */\nfunction paintPath(element: SVGPathElement, paint: Paint): void {\n setAttributes(element, {\n \"stroke-width\": paint.stroke === undefined ? undefined : (paint.width ?? 1),\n opacity: paint.opacity,\n \"stroke-linecap\": paint.linecap,\n \"stroke-linejoin\": \"round\"\n });\n setStyles(element, {\n fill: paint.fill === undefined ? \"none\" : cssColor(paint.fill),\n stroke: paint.stroke === undefined ? undefined : cssColor(paint.stroke)\n });\n}\n\nfunction styleText(element: SVGTextElement, style: TextStyle): void {\n setAttributes(element, { x: style.at.x, y: style.at.y, \"text-anchor\": style.anchor ?? \"start\", opacity: style.opacity });\n setStyles(element, { fill: cssColor(style.color ?? \"text\") });\n}\n","// The runner's surface in SVG: one overlay group per run, above the marks, and the marks' style handles.\n\nimport type { MarkHandle } from \"../../core\";\nimport type { RunnerSurface } from \"../../core/runner\";\nimport { svgLayer } from \"./layer\";\nimport { setAttributes, setStyles, svgElement } from \"./svg\";\nimport { markColorStyles, type SeriesColors } from \"./theme\";\n\nexport interface SvgSurfaceOptions {\n /** Where runs draw: a group above the marks, in chart coordinates. */\n readonly overlay: SVGGElement;\n /** The mark's own style handle. */\n mark(key: string): MarkHandle;\n /** The colours the \"mark\" token means in this mark's groups. */\n colors(key: string): SeriesColors | undefined;\n}\n\nexport interface SvgSurface extends RunnerSurface {\n /** Sets the \"mark\" colours again on the key's live groups, after the mark's colours changed (a new palette, a different first series). */\n recolor(key: string): void;\n /** Hides the key's groups, and any it gets later, or shows them again: a line chart's points past its reveal. */\n hide(key: string, hidden: boolean): void;\n}\n\nexport function svgSurface(options: SvgSurfaceOptions): SvgSurface {\n const { overlay } = options;\n const orders = new WeakMap<Element, number>();\n /** Live groups by mark key. */\n const groups = new Map<string, Set<SVGGElement>>();\n const hidden = new Set<string>();\n return {\n group(key, slot, order) {\n const group = svgElement(\"g\", { class: \"ec-run\", \"data-key\": key, \"data-slot\": slot, visibility: hidden.has(key) ? \"hidden\" : undefined }, overlay);\n setStyles(group, markColorStyles(options.colors(key)));\n orders.set(group, order);\n // Stacked by start order, not by when the group was asked for: a decoration may first draw late.\n const above = Array.from(overlay.children).find((child) => (orders.get(child) ?? -Infinity) > order);\n overlay.insertBefore(group, above ?? null);\n let live = groups.get(key);\n if (!live) groups.set(key, (live = new Set()));\n live.add(group);\n const owner = live;\n return {\n ...svgLayer(group),\n clear() {\n group.remove();\n owner.delete(group);\n if (owner.size === 0 && groups.get(key) === owner) groups.delete(key);\n }\n };\n },\n mark: (key) => options.mark(key),\n recolor(key) {\n const live = groups.get(key);\n if (!live) return;\n const styles = markColorStyles(options.colors(key));\n for (const group of live) setStyles(group, styles);\n },\n hide(key, hide) {\n if (hide) hidden.add(key);\n else hidden.delete(key);\n for (const group of groups.get(key) ?? []) setAttributes(group, { visibility: hide ? \"hidden\" : undefined });\n }\n };\n}\n","// Series names for people. A series is named after its field (\"goals\"; a value read by a function is\n// \"value\"); `seriesLabels` gives it a name to show instead, used as given wherever the chart names it.\n\nimport type { ChartOptions } from \"./types\";\n\n/** The `seriesLabels` option. */\nexport type SeriesLabels = ChartOptions<unknown>[\"seriesLabels\"];\n\n/** The series' name for people: its label, or its own name. Only the object's own keys count, so \"constructor\" is just a series. */\nexport function seriesLabel(labels: SeriesLabels, series: string): string {\n return labels !== undefined && Object.prototype.hasOwnProperty.call(labels, series) ? (labels[series] ?? series) : series;\n}\n\n/** Throws on a `seriesLabels` option that isn't an object of names. `chart` names the chart in the message. */\nexport function checkSeriesLabels(option: unknown, chart: string): void {\n if (option === undefined) return;\n if (typeof option !== \"object\" || option === null || Array.isArray(option)) throw new TypeError(`${chart}: seriesLabels must be an object of names by series, as { goals: \"Goals\" }.`);\n for (const [series, label] of Object.entries(option)) {\n if (typeof label !== \"string\" || label.trim() === \"\") throw new TypeError(`${chart}: seriesLabels.${series} must be a name, not ${typeof label === \"string\" ? \"blank\" : String(label)}.`);\n }\n}\n","// A chart's mark events: the listeners `on()` adds, and emitting to them. A listener that throws is\n// reported, and the others still hear the event.\n\nimport { report } from \"../../core/report\";\nimport type { Chart, MarkEvents } from \"../types\";\n\ntype Listeners<D> = { [K in keyof MarkEvents<D>]: Set<(event: MarkEvents<D>[K]) => void> };\n\nexport interface ChartEvents<D> {\n emit<K extends keyof MarkEvents<D>>(type: K, event: MarkEvents<D>[K]): void;\n /** One event per mark, each given its place in the batch. `read` makes each one as it's emitted. */\n emitEach<K extends keyof MarkEvents<D>, T>(type: K, marks: readonly T[], read: (mark: T) => Omit<MarkEvents<D>[K], \"batch\">): void;\n /** The chart's `on()`: throws on an event it doesn't have. */\n readonly on: Chart<D, unknown>[\"on\"];\n /** Drops every listener. */\n clear(): void;\n}\n\n/** `chart` names the chart in errors. */\nexport function chartEvents<D>(chart: string): ChartEvents<D> {\n const listeners: Listeners<D> = { enter: new Set(), update: new Set(), exit: new Set(), hover: new Set(), leave: new Set() };\n\n function emit<K extends keyof MarkEvents<D>>(type: K, event: MarkEvents<D>[K]): void {\n for (const listener of [...listeners[type]]) {\n try {\n listener(event);\n } catch (error) {\n report(error);\n }\n }\n }\n\n return {\n emit,\n emitEach(type, marks, read) {\n marks.forEach((mark, index) => emit(type, { ...read(mark), batch: { index, count: marks.length } } as MarkEvents<D>[typeof type]));\n },\n on(type, listener) {\n const set = listeners[type] as Set<typeof listener> | undefined;\n if (!set) throw new TypeError(`${chart}: unknown event \"${String(type)}\". Use one of: ${Object.keys(listeners).join(\", \")}.`);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n },\n clear() {\n for (const set of Object.values(listeners)) set.clear();\n }\n };\n}\n","// Numbers as a chart shows them: the `format` option or its default, the rounding a counting label\n// uses between two values, and a share as a percent.\n\n/** The chart's `format`, or the default: the locale's, to at most 2 decimals. */\nexport function format(options: { readonly format?: ((value: number) => string) | undefined }): (value: number) => string {\n return options.format ?? defaultFormat;\n}\n\nlet numberFormat: Intl.NumberFormat | undefined;\nfunction defaultFormat(value: number): string {\n numberFormat ??= new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });\n return numberFormat.format(value);\n}\n\n/** Decimal places a value is given to, up to 6: a counting label shows whole numbers between whole totals. */\nexport function decimals(value: number): number {\n const text = String(Number(value.toPrecision(12)));\n if (/e/i.test(text)) return 6;\n const point = text.indexOf(\".\");\n return point < 0 ? 0 : Math.min(6, text.length - point - 1);\n}\n\nexport function round(value: number, digits: number): number {\n const factor = 10 ** digits;\n const rounded = Math.round(value * factor) / factor;\n // No \"-0\" on a label counting down to zero.\n return rounded === 0 ? 0 : rounded;\n}\n\n/** A share, from 0 to 1, as a whole percent: \"28%\". */\nexport function percent(share: number): string {\n return `${round(share * 100, 0)}%`;\n}\n","// Pointer hover for a chart's marks, delegated from the root <svg>. A mouse or pen hovers; a touch tap\n// acts as hover until a tap somewhere else. While a tooltip shows, the pointer on it is on the target\n// it's for, so it can be read, selected and magnified without the hover ending (WCAG 1.4.13).\n\nexport interface HoverTarget {\n readonly key: string;\n /** The segment's series under the pointer, if it's over one. */\n readonly segment?: string;\n}\n\n/** The chart's own hovered target, and its tooltip's element while that shows. */\nexport interface HoverTooltip {\n readonly key: string;\n readonly element: HTMLElement | undefined;\n}\n\nexport interface PointerHoverOptions {\n /** The mark an event target belongs to, if any (leaving marks don't count). */\n find(target: EventTarget | null): HoverTarget | undefined;\n hover(target: HoverTarget, source: \"pointer\" | \"touch\"): void;\n leave(): void;\n /**\n * The chart's own hover, if any, and its tooltip while that shows: the pointer on the tooltip is on\n * the hovered target. Undefined with no hover, or a link's.\n */\n tooltip?(): HoverTooltip | undefined;\n}\n\nexport interface PointerHover {\n /** The hovered key, if any: the target the pointer is on, or whose tooltip it's on. */\n readonly current: string | undefined;\n /**\n * Leaves the hovered mark, for example because it's being removed. A pointer resting on its tooltip\n * hovers again only once it moves, though the browser may hit-test the mark under it at once.\n */\n clear(): void;\n destroy(): void;\n}\n\nexport function pointerHover(svg: SVGSVGElement, options: PointerHoverOptions): PointerHover {\n const doc = svg.ownerDocument;\n let current: string | undefined;\n let lastPointer = \"mouse\";\n /** The tooltip the pointer is on, and where the pointer is there, in client px. */\n let held: { readonly element: HTMLElement; x: number; y: number } | undefined;\n /** Watches the held tooltip for a change that moves it, or hides it, from under the pointer. */\n let watcher: MutationObserver | undefined;\n /**\n * Where the pointer rested on a tooltip whose hover ended there. With the tooltip gone, a browser may\n * hit-test again and send the mark under it a pointerover, though the pointer hasn't moved: until it\n * moves, that doesn't hover it, or a dismissed tooltip would come back at once.\n */\n let still: { readonly x: number; readonly y: number } | undefined;\n\n const enter = (target: HoverTarget | undefined, source: \"pointer\" | \"touch\"): void => {\n if (target?.key === current) return;\n leave();\n if (!target) return;\n current = target.key;\n options.hover(target, source);\n };\n\n const leave = (): void => {\n letGo();\n if (current === undefined) return;\n current = undefined;\n options.leave();\n };\n\n /** The tooltip's element while it shows, if it holds `node`. */\n const tooltipHolding = (node: Node | null): HoverTooltip | undefined => {\n const tip = options.tooltip?.();\n return tip?.element && node && tip.element.contains(node) ? tip : undefined;\n };\n\n /** The element at a point in client px, in the chart's document or shadow root; undefined where that can't be found. */\n const elementAt = (x: number, y: number): Element | null | undefined => {\n const root = svg.getRootNode() as Document | ShadowRoot;\n return typeof root.elementFromPoint === \"function\" ? root.elementFromPoint(x, y) : undefined;\n };\n\n /** Where the pointer went from an element it left: the event's related target or, without one, what's under it. */\n const landing = (event: PointerEvent): Element | null => (event.relatedTarget as Element | null) ?? elementAt(event.clientX, event.clientY) ?? null;\n\n /** The pointer is now over `element`: the tooltip, whose target it holds; a mark, which it hovers; or anything else, which ends the hover. */\n const arrive = (element: Element | null, x: number, y: number): void => {\n const tip = tooltipHolding(element);\n if (tip) hold(tip, x, y);\n else enter(element && svg.contains(element) ? options.find(element) : undefined, \"pointer\");\n };\n\n /** The pointer is on the tooltip, on its target: keyboard focus may have put it there. */\n const hold = (tip: HoverTooltip, x: number, y: number): void => {\n enter({ key: tip.key }, \"pointer\");\n const element = tip.element!;\n if (held?.element === element) {\n held.x = x;\n held.y = y;\n return;\n }\n letGo();\n held = { element, x, y };\n element.addEventListener(\"pointermove\", track);\n element.addEventListener(\"pointerleave\", off);\n watcher = new MutationObserver(recheck);\n watcher.observe(element, { attributes: true, childList: true, characterData: true, subtree: true });\n };\n\n const letGo = (): void => {\n if (!held) return;\n held.element.removeEventListener(\"pointermove\", track);\n held.element.removeEventListener(\"pointerleave\", off);\n watcher?.disconnect();\n watcher = undefined;\n held = undefined;\n };\n\n const track = (event: PointerEvent): void => {\n if (!held || event.pointerType === \"touch\") return;\n held.x = event.clientX;\n held.y = event.clientY;\n };\n\n /** Off the tooltip: onto a mark, which it hovers, or anywhere else, which ends the hover. */\n const off = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\") return;\n letGo();\n arrive(landing(event), event.clientX, event.clientY);\n };\n\n /**\n * The held tooltip changed. If it has moved from under the pointer, the pointer is on whatever it's\n * over now. If it shows another target now (focus moved the hover), the pointer isn't on the\n * hovered target any more, and hovers again when it next moves onto a mark.\n */\n const recheck = (): void => {\n if (!held) return;\n const { x, y } = held;\n const under = elementAt(x, y);\n if (under === undefined) return;\n const tip = options.tooltip?.();\n const onTip = tip?.element !== undefined && under !== null && tip.element.contains(under);\n if (onTip && tip.key === current) return;\n letGo();\n if (!onTip && tip?.key !== current) {\n still = { x, y };\n leave();\n return;\n }\n arrive(under, x, y);\n };\n\n /** Whether the pointer is still where a hover ended on its tooltip; once it has moved, it isn't. */\n const resting = (event: PointerEvent): boolean => {\n if (still && Math.abs(event.clientX - still.x) < 1 && Math.abs(event.clientY - still.y) < 1) return true;\n still = undefined;\n return false;\n };\n // Touch fires pointerover and pointerleave around every tap; taps are handled on click instead.\n const over = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\" || resting(event)) return;\n letGo();\n enter(options.find(event.target), \"pointer\");\n };\n // Off the <svg>, onto the tooltip the pointer stays on the hovered target; anywhere else it leaves.\n const out = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\") return;\n still = undefined;\n arrive(landing(event), event.clientX, event.clientY);\n };\n const move = (event: PointerEvent): void => {\n if (event.pointerType !== \"touch\") resting(event);\n };\n const down = (event: PointerEvent): void => {\n lastPointer = event.pointerType;\n };\n // A click follows a tap but not a scroll, so scrolling past the chart doesn't hover anything.\n const click = (event: MouseEvent): void => {\n if (lastPointer === \"touch\") enter(options.find(event.target), \"touch\");\n };\n // A tap on the tooltip isn't a tap elsewhere: the hover stays. The document hears a chart in a\n // shadow root's events from its host, so the target is the first in the event's path.\n const elsewhere = (event: PointerEvent): void => {\n if (current === undefined || event.pointerType !== \"touch\") return;\n const target = (event.composedPath()[0] ?? event.target) as Node | null;\n if (!svg.contains(target) && !tooltipHolding(target)) leave();\n };\n\n svg.addEventListener(\"pointerover\", over);\n svg.addEventListener(\"pointerleave\", out);\n svg.addEventListener(\"pointermove\", move);\n svg.addEventListener(\"pointerdown\", down);\n svg.addEventListener(\"click\", click);\n doc.addEventListener(\"pointerdown\", elsewhere, true);\n\n return {\n get current() {\n return current;\n },\n clear() {\n if (held) still = { x: held.x, y: held.y };\n leave();\n },\n destroy() {\n letGo();\n current = undefined;\n svg.removeEventListener(\"pointerover\", over);\n svg.removeEventListener(\"pointerleave\", out);\n svg.removeEventListener(\"pointermove\", move);\n svg.removeEventListener(\"pointerdown\", down);\n svg.removeEventListener(\"click\", click);\n doc.removeEventListener(\"pointerdown\", elsewhere, true);\n }\n };\n}\n","// Keyboard focus for a chart's marks, delegated from the root <svg> like pointer hover. The chart is\n// one tab stop (a roving tabindex): arrow keys move between marks in visual order, Page Up and Page\n// Down by a page, Home and End jump to the ends, and Escape leaves. Focus that follows a key press\n// shows the ring and plays the hover story; focus from a click or tap does neither (the pointer's own\n// hover is playing), as with :focus-visible. The charts (through shell/hover.ts) and expressive()\n// share it.\n\nexport interface KeyboardFocusOptions {\n /** The mark an event target belongs to, if any (leaving marks don't count). */\n find(target: EventTarget | null): string | undefined;\n /** The marks that can take focus, in visual order. */\n order(): readonly string[];\n /** The element that takes a mark's focus. Leaving marks' too, unless `tabIndex` is given. */\n element(key: string): SVGElement | undefined;\n /**\n * Sets a mark's tabindex: \"0\" for the tab stop, \"-1\" for the others, and undefined once the mark\n * has left. By default it's set on `element(key)`; the adapter sets it on the host's elements itself,\n * so it can put back what they had.\n */\n tabIndex?(key: string, value: \"0\" | \"-1\" | undefined): void;\n /** A mark took focus. `visible`: it followed a key press, so it shows the ring. */\n focus(key: string, visible: boolean): void;\n /** Focus left the chart's marks. */\n blur(key: string): void;\n /** Escape on a focused mark. Returns whether it did anything. */\n escape(key: string): boolean;\n /**\n * Where a page goes from `key`: on (`by` 1, Page Down) or back (-1, Page Up), for an axis whose page\n * isn't a count of marks. A line chart's time axis gives the first x a calendar month or more away.\n * Undefined, or a key not in the order, keeps the default: a tenth of the marks, rounded up.\n */\n page?(key: string, by: 1 | -1): string | undefined;\n}\n\nexport interface KeyboardFocus {\n /** The element with focus in the chart's document or shadow root, even while the window is in the background. */\n active(): Element | null;\n /** Moves the tab stop and focus to a mark as a key press would, whatever the last input was: it shows the ring and plays the hover. */\n focus(key: string): void;\n /**\n * After the marks changed: keeps the tab stop on its key, or, when that mark left, moves it to its\n * nearest neighbour; then sets every mark's tabindex. Focus follows the tab stop if its mark left,\n * and goes to the mark's new element if the host replaced the focused one. It also listens on the\n * <svg> as it is now: a host may draw a new one, or move it into or out of a shadow root.\n */\n sync(): void;\n destroy(): void;\n}\n\nexport function keyboardFocus(svg: () => SVGSVGElement | undefined, options: KeyboardFocusOptions): KeyboardFocus {\n /** What the listeners are on. Focus is heard on the document or shadow root, not on the <svg>. */\n let on: { readonly svg: SVGSVGElement; readonly doc: Document; readonly scope: Document | ShadowRoot } | undefined;\n /** The mark with focus, as focusin and focusout tell it. */\n let current: string | undefined;\n /** The element that last took a mark's focus, and its mark. */\n let focused: { readonly key: string; readonly element: SVGElement } | undefined;\n /** A mark's element that focus left for nowhere in this task: maybe the host removing it. */\n let dropped: SVGElement | undefined;\n let tabStop: string | undefined;\n /** The order sync() last saw, to find a leaving mark's neighbours. */\n let last: readonly string[] = [];\n /** Whether the last input was a key (or there's been none), as :focus-visible decides. */\n let keyboardInput = true;\n\n const setTabIndex =\n options.tabIndex ??\n ((key: string, value: \"0\" | \"-1\" | undefined): void => {\n const element = options.element(key);\n if (value === undefined) element?.removeAttribute(\"tabindex\");\n else element?.setAttribute(\"tabindex\", value);\n });\n\n /** One mark is in the tab order; the others take focus from the arrow keys. */\n const applyTabIndex = (keys: readonly string[]): void => {\n for (const key of keys) setTabIndex(key, key === tabStop ? \"0\" : \"-1\");\n };\n\n const focusKey = (key: string): void => {\n tabStop = key;\n applyTabIndex(options.order());\n options.element(key)?.focus();\n };\n\n const leave = (): void => {\n const key = current;\n current = undefined;\n if (key !== undefined) options.blur(key);\n };\n\n // On the whole document: a Tab from outside the chart has to count, and so does a click anywhere.\n const anyKey = (event: KeyboardEvent): void => {\n if (!event.metaKey && !event.altKey && !event.ctrlKey) keyboardInput = true;\n };\n const anyPointer = (): void => {\n keyboardInput = false;\n dropped = undefined;\n };\n\n const focusIn = (event: FocusEvent): void => {\n dropped = undefined;\n const key = options.find(event.target);\n if (key === undefined) {\n // Focus moved on from an element the host removed, which brings no focusout.\n leave();\n return;\n }\n // Focus on a mark's element that screen readers can't see (a click on a stack's other segment,\n // which the adapter's markLabel hides) goes on to the element that carries the mark's name.\n const own = options.element(key);\n if (own && own !== event.target && (event.target as Element).getAttribute(\"aria-hidden\") === \"true\") {\n own.focus();\n if (on?.scope.activeElement === own) return;\n }\n focused = { key, element: event.target as SVGElement };\n if (key === current) return;\n current = key;\n tabStop = key;\n applyTabIndex(options.order());\n options.focus(key, keyboardInput);\n };\n\n const focusOut = (event: FocusEvent): void => {\n const element = focused?.element;\n if (current === undefined || !element || event.target !== element) return;\n // Moving to another mark: its focusin takes over.\n if (options.find(event.relatedTarget) !== undefined) return;\n leave();\n if (event.relatedTarget !== null) return;\n // Focus going nowhere may be the host removing the element: Chrome tells that as a blur while the\n // element is still in the page. If it's gone once this task is done, sync() brings focus back.\n dropped = element;\n queueMicrotask(() => {\n if (dropped === element && element.isConnected) dropped = undefined;\n });\n };\n\n const keyDown = (event: KeyboardEvent): void => {\n const key = options.find(event.target);\n if (key === undefined || event.altKey || event.ctrlKey || event.metaKey) return;\n const keys = options.order();\n const index = keys.indexOf(key);\n let next: string | undefined;\n switch (event.key) {\n // Down or right is next whatever the orientation: rows run top to bottom, columns left to right.\n case \"ArrowDown\":\n case \"ArrowRight\":\n next = keys[Math.min(keys.length - 1, index + 1)];\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n next = keys[Math.max(0, index - 1)];\n break;\n case \"PageDown\":\n case \"PageUp\": {\n const by = event.key === \"PageDown\" ? 1 : -1;\n const paged = options.page?.(key, by);\n next = paged !== undefined && keys.includes(paged) ? paged : keys[Math.min(keys.length - 1, Math.max(0, index + by * Math.ceil(keys.length / 10)))];\n break;\n }\n case \"Home\":\n next = keys[0];\n break;\n case \"End\":\n next = keys[keys.length - 1];\n break;\n case \"Escape\":\n if (options.escape(key)) event.preventDefault();\n return;\n default:\n return;\n }\n // Arrows and pages at either end stay put, without scrolling the page.\n event.preventDefault();\n if (next !== undefined && next !== key) focusKey(next);\n };\n\n const unlisten = (): void => {\n if (!on) return;\n on.doc.removeEventListener(\"keydown\", anyKey, true);\n on.doc.removeEventListener(\"pointerdown\", anyPointer, true);\n on.scope.removeEventListener(\"focusin\", focusIn as EventListener, true);\n on.scope.removeEventListener(\"focusout\", focusOut as EventListener, true);\n on.svg.removeEventListener(\"keydown\", keyDown);\n on = undefined;\n };\n\n /** Listens on the <svg> as it is now, if it or its document or shadow root changed. */\n const listen = (): void => {\n const next = svg();\n const node = next?.getRootNode();\n // Not on the <svg>: Chrome makes an SVG element with focus listeners of its own a tab stop.\n const scope = node && \"host\" in node ? (node as ShadowRoot) : next?.ownerDocument;\n if (next === on?.svg && scope === on?.scope) return;\n unlisten();\n if (!next || !scope) return;\n on = { svg: next, doc: next.ownerDocument, scope };\n on.doc.addEventListener(\"keydown\", anyKey, true);\n on.doc.addEventListener(\"pointerdown\", anyPointer, true);\n on.scope.addEventListener(\"focusin\", focusIn as EventListener, true);\n on.scope.addEventListener(\"focusout\", focusOut as EventListener, true);\n on.svg.addEventListener(\"keydown\", keyDown);\n };\n\n listen();\n\n return {\n active: () => on?.scope.activeElement ?? null,\n focus(key) {\n keyboardInput = true;\n // Already focused (from a click, say): no focusin comes, so it's told here.\n if (key === current && focused?.element === on?.scope.activeElement) options.focus(key, true);\n else focusKey(key);\n },\n sync() {\n listen();\n const keys = options.order();\n const live = new Set(keys);\n const gone = last.filter((key) => !live.has(key));\n if (tabStop === undefined || !live.has(tabStop)) tabStop = neighbour(last, tabStop, live) ?? keys[0];\n // The mark with focus: its element is active (even while the window is in the background, when\n // no focus events come), or the host removed its element while it had focus. Browsers tell that\n // differently: Chrome with a blur just before, which left focus nowhere; others not at all.\n const nowhere = !on?.doc.activeElement || on.doc.activeElement === on.doc.body;\n const removed = focused !== undefined && !focused.element.isConnected && (current !== undefined || (focused.element === dropped && nowhere));\n const had = focused && (focused.element === on?.scope.activeElement || removed) ? focused : undefined;\n dropped = undefined;\n if (had && !live.has(had.key)) {\n // It left: focus goes to its neighbour, or, with no marks left, out of the chart.\n if (tabStop !== undefined) focusKey(tabStop);\n else if (had.element.isConnected) had.element.blur();\n else leave();\n } else if (had && options.find(had.element) !== had.key) {\n // The host replaced its element (Vega does), even if the old one is still in the page, as in a\n // D3 exit transition: focus the new one.\n focusKey(had.key);\n }\n applyTabIndex(keys);\n for (const key of gone) setTabIndex(key, undefined);\n last = keys;\n },\n destroy() {\n current = undefined;\n focused = undefined;\n dropped = undefined;\n unlisten();\n }\n };\n}\n\n/** The nearest key to `key` in `order` that's still live: the one after it first, then the one before, and outwards. */\nfunction neighbour(order: readonly string[], key: string | undefined, live: ReadonlySet<string>): string | undefined {\n const index = key === undefined ? -1 : order.indexOf(key);\n if (index < 0) return undefined;\n for (let step = 1; step < order.length; step++) {\n for (const at of [index + step, index - step]) {\n const candidate = order[at];\n if (candidate !== undefined && live.has(candidate)) return candidate;\n }\n }\n return undefined;\n}\n","// Hover for a reference chart's marks. Pointer, touch and keyboard focus share one hover: the marks'\n// emphasis (`ec-hot`), the others' dimming (`ec-hovering` on the <svg>), the tooltip, the runner's\n// hover and leave, and the events. Focus from a key press, or from the chart's focus(key), shows the\n// focus ring and plays the hover; focus from a click or tap moves the tab stop but leaves the hover to\n// the pointer.\n//\n// What's hovered is a target: what the pointer is over and what takes focus. A target stands for one\n// mark or several, hovered together in one batch: a bar or a slice is its own mark, while a line\n// chart's x stands for every series' point there. The keyboard moves between targets.\n//\n// The chart says which targets and marks there are and draws them: it finds a live target from an\n// event target, gives a target's marks, their elements and how they are on screen, draws the ring\n// and shows the tooltip. The pointer on the tooltip stays on the hovered target (../interaction.ts).\n//\n// A link (../link.ts) hovers targets too, as \"linked\": their marks' emphasis, the dimming and their\n// hover runs, with no tooltip, ring or focus. It hears the chart's own hovers, and Escape on a linked\n// hover ends the link's, where it started.\n\nimport type { RunInput, Runner } from \"../../core/runner\";\nimport { pointerHover, type HoverTarget } from \"../interaction\";\nimport { keyboardFocus } from \"../keyboard\";\nimport { own, type LinkListener, type LinkPort } from \"../link\";\nimport type { MarkEvents } from \"../types\";\nimport type { ChartEvents } from \"./events\";\n\ntype HoverSource = MarkEvents<unknown>[\"hover\"][\"source\"];\n\nexport interface ChartHoverOptions<D> {\n readonly svg: SVGSVGElement;\n readonly runner: Pick<Runner<D>, \"hover\" | \"leave\">;\n readonly events: Pick<ChartEvents<D>, \"emit\">;\n /** Whether the other marks dim while one is hovered: the `dim` option as it is now. */\n dim(): boolean;\n /** The live target an event target belongs to, with the segment under the pointer; leaving ones don't count. */\n find(target: EventTarget | null): HoverTarget | undefined;\n /** Whether the target `key` is live: on screen and not leaving. */\n live(key: string): boolean;\n /** The live targets' keys, in visual order: the keyboard's order. */\n order(): readonly string[];\n /** Where Page Down (`by` 1) or Page Up (-1) goes from the target `key`. Default, or undefined: a tenth of the targets on or back (../keyboard.ts). */\n page?(key: string, by: 1 | -1): string | undefined;\n /**\n * The keys of the marks a live target stands for, in the batch's order: a line chart's x gives each\n * series' point there. Default: the target alone, as a bar or a slice is its own mark.\n */\n marks?(key: string): readonly string[];\n /** A target's element, live or leaving: it takes focus and, for a target that is its own mark, the hover's emphasis. */\n element(key: string): SVGElement | undefined;\n /** A mark's element, live or leaving: it takes the hover's emphasis (`ec-hot`). Default: `element`, for targets that are their own marks. */\n markElement?(key: string): SVGElement | undefined;\n /** A mark as it is on screen, live or leaving: what hover and leave report, so mid-change they match what's under the pointer. */\n onScreen(key: string): RunInput<D> | undefined;\n /** Draws the focus ring around the live target `key` as it is on screen, or hides it. */\n ring(key: string | undefined): void;\n readonly tooltip: {\n /** Shows the tooltip for the live target `key` as it is on screen, or moves it there. */\n show(key: string): void;\n hide(): void;\n /** The tooltip's element while it shows: the pointer on it stays on the hovered target. */\n element?(): HTMLElement | undefined;\n };\n}\n\nexport interface ChartHover {\n /** The hovered target's key, when the hover is the chart's own: a link's shows no tooltip. */\n readonly key: string | undefined;\n /** The target showing the focus ring: focused from the keyboard. */\n readonly ringKey: string | undefined;\n /** The chart's hover as a link drives it, for the chart to register with its handle. */\n readonly link: LinkPort;\n /** The element with focus in the chart's document or shadow root. */\n active(): Element | null;\n /** An effect restyled a mark: the focus ring and the tooltip of the target it belongs to follow its transform. */\n restyled(key: string): void;\n /** After `dim` changed: the others dim, or stop dimming, now. */\n syncDim(): void;\n /**\n * After the marks changed: ends the hover if its targets have left. Otherwise the hover follows the\n * marks its targets stand for now: those it no longer has are left, and new ones are hovered, their\n * events placed in the whole batch, as the runner's runs are.\n */\n dropGone(): void;\n /** After the marks changed: the tab stop stays on its key, or moves to its nearest neighbour, and focus follows. */\n sync(): void;\n /** Moves focus to the live target `key` as a key press would: the ring shows and its hover plays. Does nothing for a key that isn't live. */\n focus(key: string): void;\n /**\n * Ends the hover, the pointer's or focus's, as the viewer moving away would: the emphasis, the\n * dimming, the tooltip and the hover runs end, with their leave events. Focus stays where it is,\n * with its ring, as after Escape; the pointer hovers again when it next moves onto a mark.\n */\n leave(): void;\n destroy(): void;\n}\n\ninterface Hovered {\n /** The targets' keys: one for the chart's own hover, any number for a link's. */\n readonly keys: readonly string[];\n readonly source: HoverSource;\n /** The marks hovered for them, in the batch's order. */\n readonly marks: readonly string[];\n /** Whether their hover runs play: a link with `effects: false` keeps its marks to emphasis and dimming. */\n readonly effects: boolean;\n}\n\nexport function chartHover<D>(options: ChartHoverOptions<D>): ChartHover {\n const { svg, runner, events } = options;\n const marksOf = (key: string): readonly string[] => options.marks?.(key) ?? [key];\n const markElement = (key: string): SVGElement | undefined => (options.markElement ?? options.element)(key);\n let hovered: Hovered | undefined;\n let ringKey: string | undefined;\n /** The link the chart is in, which hears its own hovers. */\n let linked: LinkListener | undefined;\n let destroyed = false;\n\n /** The marks among `keys` that are on screen, with how they are there. */\n const onScreen = (keys: readonly string[]): { readonly key: string; readonly input: RunInput<D> }[] =>\n keys.flatMap((key) => {\n const input = options.onScreen(key);\n return input ? [{ key, input }] : [];\n });\n /** The marks the targets `keys` stand for, each once. */\n const marksFor = (keys: readonly string[]): readonly string[] => (keys.length === 1 ? marksOf(keys[0]!) : [...new Set(keys.flatMap(marksOf))]);\n\n /** The marks' hover runs, in one batch, and an event for each with its place in it. */\n function hoverMarks(marks: ReturnType<typeof onScreen>, source: HoverSource, effects: boolean, segment?: string): void {\n if (marks.length === 0) return;\n if (effects) runner.hover(marks.map(({ input }) => input));\n const count = marks.length;\n marks.forEach(({ input }, index) => events.emit(\"hover\", { ...input, batch: { index, count }, source, ...(segment === undefined ? {} : { segment }) }));\n }\n\n /** The marks lose their emphasis, their hover runs end in one batch, and each gets a leave event. */\n function leaveMarks(keys: readonly string[]): void {\n const marks = onScreen(keys);\n if (marks.length === 0) return;\n for (const { key } of marks) markElement(key)?.classList.remove(\"ec-hot\");\n runner.leave(marks.map(({ key }) => key));\n const count = marks.length;\n marks.forEach(({ input }, index) => events.emit(\"leave\", { ...input, batch: { index, count } }));\n }\n\n /**\n * Pointer, keyboard and link hover share this: the marks' emphasis, the others' dimming, the hover\n * runs and the events. The chart's own adds the tooltip and Escape, and tells its link.\n */\n function startHover(keys: readonly string[], source: HoverSource, segment?: string, effects = true): void {\n const marks = onScreen(marksFor(keys));\n const started: Hovered = { keys, source, marks: marks.map((mark) => mark.key), effects };\n hovered = started;\n for (const { key: mark } of marks) markElement(mark)?.classList.add(\"ec-hot\");\n if (options.dim()) svg.classList.add(\"ec-hovering\");\n if (source !== \"linked\") {\n options.tooltip.show(keys[0]!);\n listenForEscape(true);\n }\n hoverMarks(marks, source, effects, segment);\n // A listener may have ended it (leave()) or started another, which told the link itself.\n if (source !== \"linked\" && hovered === started) linked?.hover(marks.map(({ input }) => input));\n }\n\n function endHover(): void {\n const ended = hovered;\n hovered = undefined;\n listenForEscape(false);\n svg.classList.remove(\"ec-hovering\");\n options.tooltip.hide();\n leaveMarks(ended?.marks ?? []);\n if (own(ended)) linked?.leave();\n }\n\n /** The document listening for Escape while something is hovered. */\n let escapeDoc: Document | undefined;\n /**\n * Escape anywhere ends the hover, the pointer's too, as leave() does: its tooltip covers other marks,\n * so it can be dismissed without moving the pointer (WCAG 1.4.13). With focus on a mark, the\n * keyboard's own Escape has ended it first.\n */\n const dismiss = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\" && !event.defaultPrevented && hovered !== undefined) leave();\n };\n function listenForEscape(on: boolean): void {\n escapeDoc?.removeEventListener(\"keydown\", dismiss);\n escapeDoc = on ? svg.ownerDocument : undefined;\n escapeDoc?.addEventListener(\"keydown\", dismiss);\n }\n\n function leave(): void {\n // The pointer lets go first, so it hovers again when it next moves onto a mark.\n interaction.clear();\n if (hovered !== undefined) endHover();\n }\n\n /** Whether the mark `key` is, or belongs to, the target `target`. */\n const within = (target: string, key: string): boolean => key === target || (options.live(target) && marksOf(target).includes(key));\n\n const interaction = pointerHover(svg, {\n find: options.find,\n hover(target: HoverTarget, source) {\n // Already playing for keyboard focus: it goes on.\n if (!options.live(target.key) || (own(hovered) && hovered.keys[0] === target.key)) return;\n endHover();\n startHover([target.key], source, target.segment);\n },\n leave() {\n // Focus holds a keyboard hover until blur or Escape, and a link holds its own.\n if (hovered?.source === \"pointer\" || hovered?.source === \"touch\") endHover();\n },\n // The pointer can move onto the tooltip of the chart's own hover. A link's has none.\n tooltip: () => (own(hovered) ? { key: hovered.keys[0]!, element: options.tooltip.element?.() } : undefined)\n });\n\n const keyboard = keyboardFocus(() => svg, {\n find: (eventTarget) => options.find(eventTarget)?.key,\n order: options.order,\n page: (key, by) => options.page?.(key, by),\n element: options.element,\n focus(key, visible) {\n ringKey = visible ? key : undefined;\n options.ring(ringKey);\n if (!options.live(key)) return;\n if (!visible) {\n // Focus from a click or tap: the pointer's own hover plays.\n if (hovered?.source === \"keyboard\" && hovered.keys[0] !== key) endHover();\n return;\n }\n if (own(hovered) && hovered.keys[0] === key) {\n // Already playing for the pointer: it goes on, held by focus now.\n hovered = { ...hovered, source: \"keyboard\" };\n return;\n }\n endHover();\n startHover([key], \"keyboard\");\n },\n blur() {\n ringKey = undefined;\n options.ring(ringKey);\n if (hovered?.source !== \"keyboard\") return;\n // The pointer is still over it: the hover goes on, held by the pointer now.\n if (interaction.current === hovered.keys[0]) hovered = { ...hovered, source: \"pointer\" };\n else endHover();\n },\n escape() {\n if (!hovered) return false;\n // A link's hover ends where it started, and with it every chart's in the link.\n if (hovered.source === \"linked\" && linked) linked.dismiss();\n else endHover();\n return true;\n }\n });\n\n const link: LinkPort = {\n targets: () => options.order().map((key) => ({ key, marks: onScreen(marksOf(key)).map(({ input }) => input) })),\n hover(keys, effects) {\n if (hovered !== undefined) endHover();\n const live = keys.filter(options.live);\n if (live.length > 0) startHover(live, \"linked\", undefined, effects);\n },\n unlink() {\n if (hovered?.source === \"linked\") endHover();\n },\n leave,\n listen(listener) {\n if (destroyed) return false;\n linked = listener;\n return true;\n }\n };\n\n return {\n get key() {\n return own(hovered) ? hovered.keys[0] : undefined;\n },\n get ringKey() {\n return ringKey;\n },\n link,\n active: () => keyboard.active(),\n restyled(key) {\n if (ringKey !== undefined && within(ringKey, key)) options.ring(ringKey);\n // A link's hover has no tooltip.\n const target = own(hovered) ? hovered.keys[0]! : undefined;\n if (target !== undefined && (hovered?.marks.includes(key) || key === target) && options.live(target)) options.tooltip.show(target);\n },\n syncDim() {\n if (!options.dim()) svg.classList.remove(\"ec-hovering\");\n else if (hovered !== undefined) svg.classList.add(\"ec-hovering\");\n },\n dropGone() {\n if (hovered === undefined) return;\n const keys = hovered.keys.filter(options.live);\n if (keys.length === 0) {\n interaction.clear();\n endHover();\n return;\n }\n const { source, marks: before, effects } = hovered;\n const now = onScreen(marksFor(keys));\n hovered = { ...hovered, keys };\n if (now.length === before.length && now.every((mark, i) => mark.key === before[i])) return;\n const had = new Set(before);\n const kept = new Set(now.map((mark) => mark.key));\n const gone = onScreen(before.filter((key) => !kept.has(key)));\n hovered = { ...hovered, marks: now.map((mark) => mark.key) };\n for (const { key } of gone) markElement(key)?.classList.remove(\"ec-hot\");\n for (const { key } of now) if (!had.has(key)) markElement(key)?.classList.add(\"ec-hot\");\n // The runner hears the targets' whole new batch, in order. Mid-change (playUpdate interrupts\n // first), it holds hovers and replays every hovered mark as one batch when the change settles, so\n // a joined mark's run gets the place its event gives; at rest, the marks that stayed start again\n // with their new places.\n runner.leave(before);\n if (effects) runner.hover(now.map(({ input }) => input));\n gone.forEach(({ input }, index) => events.emit(\"leave\", { ...input, batch: { index, count: gone.length } }));\n const count = now.length;\n now.forEach(({ key, input }, index) => {\n if (!had.has(key)) events.emit(\"hover\", { ...input, batch: { index, count }, source });\n });\n },\n sync: () => keyboard.sync(),\n focus(key) {\n if (options.live(key)) keyboard.focus(key);\n },\n leave,\n destroy() {\n destroyed = true;\n linked?.gone();\n linked = undefined;\n listenForEscape(false);\n interaction.destroy();\n keyboard.destroy();\n }\n };\n}\n","// What a chart's labels() reports: each mark's labels as drawn, by key and role, with their text,\n// where they sit in the chart's <svg>, and their <text>.\n\nimport type { TextPlacement } from \"../render/text\";\nimport type { ChartLabel } from \"../types\";\n\n/** The label `element` drawn as `placement`, in a list for flatMap: empty when it isn't shown (no placement) or has no text. */\nexport function chartLabel(key: string, role: ChartLabel[\"role\"], placement: TextPlacement | undefined, element: SVGTextElement): ChartLabel[] {\n if (!placement || placement.text === \"\") return [];\n return [{ key, role, text: placement.text, x: placement.x, y: placement.y, anchor: placement.anchor, element }];\n}\n","// Marks on their way out. A leaving mark stays, unhoverable and no longer read, until it has faded out\n// and its exit effects are done; one that comes back meanwhile keeps its element and grows back from\n// where it is.\n\n/** One departure: a fresh one each time, so a mark that comes back and leaves again starts over. */\nexport interface Leave {\n /** Its exit effects are done. */\n exited: boolean;\n /** Resolves when its element is removed, or the mark comes back. */\n readonly gone: Promise<void>;\n readonly resolve: () => void;\n}\n\n/** What a chart's mark record needs for leaving. */\nexport interface LeavingMark {\n readonly key: string;\n /** The mark's element: hidden from screen readers while it leaves, and removed once it's gone. */\n readonly group: SVGElement;\n /** Set while the mark leaves. */\n leave: Leave | undefined;\n}\n\nexport interface LeavingMarks<R extends LeavingMark> {\n get(key: string): R | undefined;\n /** In the order they started leaving. */\n values(): Iterable<R>;\n /** Starts a mark leaving, once the chart has taken it out of its live marks. */\n start(record: R): void;\n /** Brings back the mark leaving under `key`, if there is one: it keeps its element, and the runner cancels its exit. */\n recall(key: string): R | undefined;\n /** Removes the marks whose exit effects are done and which have stopped `fading`. */\n sweep(): void;\n clear(): void;\n}\n\n/** `fading(record)`: the mark is still animating its way out. */\nexport function leavingMarks<R extends LeavingMark>(fading: (record: R) => boolean): LeavingMarks<R> {\n const marks = new Map<string, R>();\n return {\n get: (key) => marks.get(key),\n values: () => marks.values(),\n start(record) {\n marks.set(record.key, record);\n record.group.classList.add(\"ec-leaving\");\n // On its way out: no longer read.\n record.group.setAttribute(\"aria-hidden\", \"true\");\n record.leave = leave();\n },\n recall(key) {\n const record = marks.get(key);\n if (!record) return undefined;\n marks.delete(key);\n record.group.classList.remove(\"ec-leaving\");\n record.group.removeAttribute(\"aria-hidden\");\n record.leave?.resolve();\n record.leave = undefined;\n return record;\n },\n sweep() {\n for (const record of [...marks.values()]) {\n const { leave } = record;\n if (!leave?.exited || fading(record)) continue;\n marks.delete(record.key);\n record.leave = undefined;\n record.group.remove();\n leave.resolve();\n }\n },\n clear: () => marks.clear()\n };\n}\n\nfunction leave(): Leave {\n let resolve!: () => void;\n const gone = new Promise<void>((r) => {\n resolve = r;\n });\n return { exited: false, gone, resolve };\n}\n","// DOM order follows visual order, so screen readers read the marks as they're seen.\n\n/**\n * Moves the marks' elements in `layer` from `previous` into `next` order, when it changed. The element\n * with focus (`active`) stays put and the others move around it, because moving a focused element blurs it.\n */\nexport function orderElements(layer: Element, previous: readonly Element[], next: readonly Element[], active: () => Element | null): void {\n if (!next.some((element, i) => previous[i] !== element)) return;\n const focused = active();\n const pivot = next.findIndex((element) => element === focused);\n const anchor = next[pivot] ?? null;\n next.forEach((element, i) => {\n if (i < pivot) layer.insertBefore(element, anchor);\n else if (i > pivot) layer.appendChild(element);\n });\n}\n","// The chart's data table: the fallback that every screen reader can read, whatever it makes of ARIA\n// in SVG. A closed <details> \"Data table\" after the chart, or, with `table: \"hidden\"`, a table that's\n// visually hidden but still read. Its rows are the chart's, in visual order, so it follows the sort;\n// its columns are the category (each row's header), any extra columns the page lists, each series,\n// and the total of a stack, in the chart's format, then any columns the page puts after the values.\n// A donut adds each row's share and a total row. A line's missing value says \"missing\". Text is only\n// ever set as text, never parsed as HTML.\n\nimport { percent } from \"./shell/format\";\nimport type { ChartOptions, TableColumn, TableOptions } from \"./types\";\n\n/** The `table` option. */\nexport type TableOption<D> = ChartOptions<D>[\"table\"];\n\n/** A row as the chart has it. */\nexport interface TableRow<D> {\n readonly key: string;\n readonly category: string;\n readonly datum: D;\n /** Its index in `data`. */\n readonly index: number;\n readonly values: readonly { readonly series: string; readonly value: number }[];\n /** The series with no value in this row, a line chart's gaps: their cells say \"missing\". */\n readonly missing?: ReadonlySet<string>;\n readonly total: number;\n}\n\nexport interface TableInput<D> {\n readonly option: TableOption<D>;\n /** The chart's label. */\n readonly caption: string;\n /** The category's field name, when a field gives it: the column's default header. */\n readonly category: string | undefined;\n /** In stack order. */\n readonly series: readonly string[];\n /** A series' column header when `table.series` has none: its label. Default: the series' own name. */\n readonly label?: (series: string) => string;\n /** In visual order. */\n readonly rows: readonly TableRow<D>[];\n readonly format: (value: number) => string;\n /**\n * Whether there's a Total column after the series, each row's values added up. Default: when\n * there's more than one series, as a stack has. A line chart's series don't add up, so it has none.\n */\n readonly total?: boolean;\n /**\n * A donut's: a Share column after the values, each row's share of the rows' total as a whole\n * percent, and a total row in <tfoot>: \"Total\", the values added up, and 100%.\n */\n readonly shares?: boolean;\n}\n\nexport interface TableCell {\n readonly text: string;\n /** Right-aligned. */\n readonly numeric: boolean;\n}\n\n/** What the table shows: headers, then each row's cells, the first of which is the row's header. */\nexport interface TableModel {\n readonly hidden: boolean;\n readonly summary: string;\n readonly caption: string;\n readonly headers: readonly TableCell[];\n readonly rows: readonly { readonly key: string; readonly cells: readonly TableCell[] }[];\n /** The total row's cells, in <tfoot>; the first is its header. */\n readonly footer?: readonly TableCell[];\n}\n\nexport interface ChartTable {\n /**\n * Shows `model` after the chart's <svg>, or removes the table when it's undefined. Rows are kept by\n * key and only what changed is written, so an open table, and a screen reader's place in it, stay.\n */\n render(model: TableModel | undefined): void;\n destroy(): void;\n}\n\n/** Throws on a `table` option that isn't true, false, \"hidden\" or a valid object. `chart` names the chart in the message. */\nexport function checkTableOption(option: unknown, chart: string): void {\n if (option === undefined || typeof option === \"boolean\" || option === \"hidden\") return;\n const fail = (what: string): never => {\n throw new TypeError(`${chart}: ${what}`);\n };\n if (typeof option !== \"object\" || option === null) fail('table must be true, false, \"hidden\" or an object of table options.');\n const { hidden, columns, category, total, share, summary, series } = option as TableOptions<unknown>;\n if (hidden !== undefined && typeof hidden !== \"boolean\") fail(\"table.hidden must be true or false.\");\n for (const [name, text] of Object.entries({ category, total, share, summary })) {\n if (text !== undefined && typeof text !== \"string\") fail(`table.${name} must be a string.`);\n }\n if (series !== undefined) {\n if (typeof series !== \"object\" || series === null || Array.isArray(series)) fail('table.series must be an object of headers by series, as { shots: \"Shots\" }.');\n for (const [name, header] of Object.entries(series)) {\n if (typeof header !== \"string\") fail(`table.series.${name} must be a string: the column's header.`);\n }\n }\n if (columns === undefined) return;\n if (!Array.isArray(columns)) fail(\"table.columns must be an array of { label, field }.\");\n columns.forEach((entry: Partial<TableColumn<unknown>> | null, i: number) => {\n const column = typeof entry === \"object\" && entry !== null ? entry : fail(`table.columns[${i}] must be an object with a label and a field.`);\n if (typeof column.label !== \"string\") fail(`table.columns[${i}].label must be a string: the column's header.`);\n if (typeof column.field !== \"string\" && typeof column.field !== \"function\") fail(`table.columns[${i}].field must be a field name or a function of the row.`);\n if (column.format !== undefined && typeof column.format !== \"function\") fail(`table.columns[${i}].format must be a function.`);\n if (column.after !== undefined && column.after !== \"category\" && column.after !== \"values\") fail(`table.columns[${i}].after must be \"category\" or \"values\".`);\n });\n}\n\n/** A missing value's cell: a word, so it's heard as missing, not as an empty cell. */\nconst MISSING = \"missing\";\n\n/** What the table shows, or undefined with `table: false`. Reads every cell, so a column that throws throws here. */\nexport function tableModel<D>(input: TableInput<D>): TableModel | undefined {\n const { option, format } = input;\n if (option === false) return undefined;\n const options: TableOptions<D> = typeof option === \"object\" ? option : {};\n const columns = options.columns ?? [];\n const first = columns.filter((column) => column.after !== \"values\");\n const last = columns.filter((column) => column.after === \"values\");\n const totals = input.total ?? input.series.length > 1;\n const number = (value: number): TableCell => ({ text: format(value), numeric: true });\n const grand = input.rows.reduce((sum, row) => sum + row.total, 0);\n const share = (value: number): TableCell[] => (input.shares ? [{ text: percent(grand > 0 ? value / grand : 0), numeric: true }] : []);\n const header = (column: TableColumn<D>): TableCell => ({ text: column.label, numeric: false });\n // Only the option's own keys count, so \"constructor\" is just a series.\n const own = (series: string): string | undefined => (options.series && Object.prototype.hasOwnProperty.call(options.series, series) ? options.series[series] : undefined);\n const blank = (): TableCell => ({ text: \"\", numeric: false });\n\n const headers: TableCell[] = [\n { text: options.category ?? input.category ?? \"Category\", numeric: false },\n ...first.map(header),\n ...input.series.map((series) => ({ text: own(series) ?? input.label?.(series) ?? series, numeric: true })),\n ...(totals ? [{ text: options.total ?? \"Total\", numeric: true }] : []),\n ...(input.shares ? [{ text: options.share ?? \"Share\", numeric: true }] : []),\n ...last.map(header)\n ];\n const rows = input.rows.map((row) => {\n const values = new Map(row.values.map((v) => [v.series, v.value]));\n return {\n key: row.key,\n cells: [\n { text: row.category, numeric: false },\n ...first.map((column) => columnCell(column, row, format)),\n ...input.series.map((series) => (row.missing?.has(series) ? { text: MISSING, numeric: true } : number(values.get(series) ?? 0))),\n ...(totals ? [number(row.total)] : []),\n ...share(row.total),\n ...last.map((column) => columnCell(column, row, format))\n ]\n };\n });\n const sum = (series: string): number => input.rows.reduce((total, row) => total + (row.values.find((v) => v.series === series)?.value ?? 0), 0);\n const footer: TableCell[] | undefined = input.shares\n ? [\n { text: options.total ?? \"Total\", numeric: false },\n ...first.map(blank),\n ...input.series.map((series) => number(sum(series))),\n ...(totals ? [number(grand)] : []),\n ...share(grand),\n ...last.map(blank)\n ]\n : undefined;\n // A column of numbers is right-aligned, header and all.\n const lastAt = headers.length - last.length;\n const pageColumns = [...first.map((_, i) => 1 + i), ...last.map((_, i) => lastAt + i)];\n for (const at of pageColumns) {\n const cells = rows.map((row) => row.cells[at]!).filter((cell) => cell.text !== \"\");\n if (cells.length > 0 && cells.every((cell) => cell.numeric)) headers[at] = { ...headers[at]!, numeric: true };\n }\n return {\n hidden: option === \"hidden\" || options.hidden === true,\n summary: options.summary ?? \"Data table\",\n caption: input.caption,\n headers,\n rows,\n ...(footer ? { footer } : {})\n };\n}\n\nfunction columnCell<D>(column: TableColumn<D>, row: TableRow<D>, format: (value: number) => string): TableCell {\n const value = typeof column.field === \"function\" ? column.field(row.datum, row.index) : (row.datum as Record<string, unknown> | null | undefined)?.[column.field];\n if (column.format) return { text: String(column.format(value)), numeric: typeof value === \"number\" };\n if (value === null || value === undefined) return { text: \"\", numeric: false };\n if (typeof value === \"number\") return { text: format(value), numeric: true };\n return { text: String(value), numeric: false };\n}\n\n/** The data table for a chart's <svg>: made the first time there's something to show, just after the <svg>. */\nexport function chartTable(svg: SVGSVGElement): ChartTable {\n const doc = svg.ownerDocument;\n /** The <details>, or the visually hidden <div>, around the table. */\n let wrapper: HTMLElement | undefined;\n let summary: HTMLElement | undefined;\n let table: HTMLTableElement | undefined;\n let caption: HTMLTableCaptionElement | undefined;\n let head: HTMLTableRowElement | undefined;\n let body: HTMLTableSectionElement | undefined;\n /** The total row's <tfoot>, while the model has one. */\n let foot: HTMLTableSectionElement | undefined;\n /** The body's rows by key. */\n const rows = new Map<string, HTMLTableRowElement>();\n /** The headers drawn, so a change of columns redraws the rows. */\n let drawn = \"\";\n\n const element = <K extends keyof HTMLElementTagNameMap>(tag: K, className?: string): HTMLElementTagNameMap[K] => {\n const made = doc.createElement(tag);\n if (className) made.className = className;\n return made;\n };\n\n function build(): HTMLTableElement {\n table = element(\"table\");\n caption = element(\"caption\", \"ec-table-caption\");\n const thead = element(\"thead\");\n head = element(\"tr\");\n thead.appendChild(head);\n body = element(\"tbody\");\n table.append(caption, thead, body);\n return table;\n }\n\n /** The wrapper for `hidden`, made or swapped in place, holding the table. */\n function place(hidden: boolean, text: string): void {\n const want = hidden ? \"DIV\" : \"DETAILS\";\n if (wrapper?.tagName !== want) {\n const next = hidden ? element(\"div\", \"ec-table ec-visually-hidden\") : element(\"details\", \"ec-table\");\n const content = table ?? build();\n if (hidden) {\n summary = undefined;\n next.appendChild(content);\n } else {\n summary = element(\"summary\");\n const scroll = element(\"div\", \"ec-table-scroll\");\n scroll.appendChild(content);\n next.append(summary, scroll);\n }\n if (wrapper?.isConnected) wrapper.replaceWith(next);\n wrapper = next;\n }\n if (!wrapper.isConnected) svg.after(wrapper);\n if (summary && summary.textContent !== text) summary.textContent = text;\n }\n\n function fill(cell: HTMLTableCellElement, { text, numeric }: TableCell): void {\n if (cell.textContent !== text) cell.textContent = text;\n cell.classList.toggle(\"ec-num\", numeric);\n }\n\n function remove(): void {\n wrapper?.remove();\n wrapper = summary = table = caption = head = body = foot = undefined;\n rows.clear();\n drawn = \"\";\n }\n\n return {\n render(model) {\n if (!model) {\n remove();\n return;\n }\n place(model.hidden, model.summary);\n if (caption!.textContent !== model.caption) caption!.textContent = model.caption;\n\n const headers = JSON.stringify(model.headers);\n if (headers !== drawn) {\n drawn = headers;\n head!.replaceChildren(\n ...model.headers.map((header) => {\n const th = element(\"th\");\n th.scope = \"col\";\n fill(th, header);\n return th;\n })\n );\n // Other columns: every row is drawn again.\n rows.clear();\n body!.replaceChildren();\n }\n\n const keep = new Set(model.rows.map((row) => row.key));\n for (const [key, tr] of rows) {\n if (keep.has(key)) continue;\n tr.remove();\n rows.delete(key);\n }\n model.rows.forEach((row, i) => {\n let tr = rows.get(row.key);\n if (!tr) {\n tr = element(\"tr\");\n tr.setAttribute(\"data-key\", row.key);\n row.cells.forEach((_, j) => {\n const cell = element(j === 0 ? \"th\" : \"td\");\n if (j === 0) (cell as HTMLTableCellElement).scope = \"row\";\n tr!.appendChild(cell);\n });\n rows.set(row.key, tr);\n }\n row.cells.forEach((cell, j) => fill(tr!.cells[j]!, cell));\n // In visual order, moving only rows that are out of place.\n if (body!.children[i] !== tr) body!.insertBefore(tr, body!.children[i] ?? null);\n });\n\n if (!model.footer) {\n foot?.remove();\n foot = undefined;\n return;\n }\n const cells = model.footer;\n let total = foot?.rows[0];\n if (!foot || !total || total.cells.length !== cells.length) {\n foot?.remove();\n foot = element(\"tfoot\");\n total = element(\"tr\");\n cells.forEach((_, j) => {\n const cell = element(j === 0 ? \"th\" : \"td\");\n if (j === 0) (cell as HTMLTableCellElement).scope = \"row\";\n total!.appendChild(cell);\n });\n foot.appendChild(total);\n table!.appendChild(foot);\n }\n cells.forEach((cell, j) => fill(total!.cells[j]!, cell));\n },\n destroy: remove\n };\n}\n","// What a reference chart needs before it draws: the environment the composition root hands it, its\n// container and width, its accessible name, and a check that data effects find the series they read.\n// And its effects when update() gives it a new `on`.\n\nimport type { Clock, EffectSlot, EffectSlots, IconSource, Motion } from \"../../core\";\nimport { EFFECT_SLOTS, resolveEffects, type PresetFactory, type Registry } from \"../../core/registry\";\nimport type { SlotEffects } from \"../../core/runner\";\nimport { checkLegendOption } from \"../legend\";\nimport { svgElement } from \"../render/svg\";\nimport { checkSeriesLabels } from \"../series\";\nimport { checkTableOption } from \"../table\";\n\n/** What the composition root hands every chart, so charts never import the registries or effects. */\nexport interface ChartEnv {\n /** Resolves preset names in `on`. */\n readonly presets: Pick<Registry<PresetFactory>, \"resolve\">;\n /** Resolves icon names for effects. */\n readonly icons: IconSource;\n /** The page-wide motion: the default, and what a mode given as a string follows. */\n readonly motion: Motion;\n /** Default: the page-wide clock. */\n readonly clock?: Clock;\n}\n\n/** Used when the container has no width yet (hidden, or no layout as in jsdom); the prototype's width. */\nconst FALLBACK_WIDTH = 640;\n\n/** The container: the element, or the one a selector matches. `chart` names the chart in errors. */\nexport function resolveTarget(target: string | Element, chart: string): Element {\n if (typeof target === \"string\") {\n const found = typeof document === \"undefined\" ? null : document.querySelector(target);\n if (!found) throw new TypeError(`${chart}: no element matches \"${target}\".`);\n return found;\n }\n if (!target || typeof (target as Element).appendChild !== \"function\") throw new TypeError(`${chart} needs a container element or a selector.`);\n return target;\n}\n\n/** The container's content width in px; a fallback when it has none (hidden, or no layout). */\nexport function containerWidth(container: Element): number {\n const style = container.ownerDocument.defaultView?.getComputedStyle(container);\n const padding = (parseFloat(style?.paddingLeft ?? \"\") || 0) + (parseFloat(style?.paddingRight ?? \"\") || 0);\n const width = container.clientWidth - padding;\n return width > 0 ? width : FALLBACK_WIDTH;\n}\n\n/** The <svg>'s accessible name (`label`) and description (`description`, in a <desc>). */\nexport function describeChart(svg: SVGSVGElement, options: { readonly label: string; readonly description?: string | undefined }): void {\n svg.setAttribute(\"aria-label\", options.label);\n let desc = svg.querySelector(\":scope > desc\");\n if (options.description) {\n desc ??= svg.insertBefore(svgElement(\"desc\", {}, svg), svg.firstChild);\n desc.textContent = options.description;\n } else {\n desc?.remove();\n }\n}\n\n/**\n * Data effects name the series they read through `needs.related`. A chart without one of them\n * throws when it's created or updated, rather than the effect finding nothing when it runs.\n */\nexport function checkNeeds<D>(effects: SlotEffects<D>, series: readonly string[], chart: string): void {\n for (const slot of EFFECT_SLOTS) {\n const effect = effects[slot];\n if (effect?.kind !== \"data\") continue;\n for (const name of effect.needs?.related ?? []) {\n if (series.includes(name)) continue;\n throw new RangeError(`${chart}: on.${slot} needs the series \"${name}\", but the chart's series are ${series.map((s) => `\"${s}\"`).join(\", \")}.`);\n }\n }\n}\n\n/**\n * The effects for a new `on` (update({ on })), resolved as a chart resolves them when it's made, so an\n * unknown preset name or slot throws before anything changes. A slot given the same preset name or\n * effect as before keeps the effect it has, so its runs go on; a preset name makes a fresh effect only\n * when it's new to the slot.\n */\nexport function nextEffects<D>(effects: SlotEffects<D>, from: EffectSlots<D> | undefined, to: EffectSlots<D> | undefined, presets: ChartEnv[\"presets\"]): SlotEffects<D> {\n const kept = (slot: string): boolean => (EFFECT_SLOTS as readonly string[]).includes(slot) && to?.[slot as EffectSlot] !== undefined && to[slot as EffectSlot] === from?.[slot as EffectSlot];\n // Everything else is resolved, unknown slots included, so they throw.\n const resolved = resolveEffects(Object.fromEntries(Object.entries(to ?? {}).filter(([slot]) => !kept(slot))) as EffectSlots<D>, presets);\n const next: { -readonly [S in EffectSlot]?: SlotEffects<D>[S] } = {};\n for (const slot of EFFECT_SLOTS) {\n const effect = kept(slot) ? effects[slot] : resolved[slot];\n if (effect) next[slot] = effect;\n }\n return next;\n}\n\n/** The options every chart takes, as checkChartOptions reads them. */\ntype CommonOptions = { readonly [K in \"label\" | \"data\" | \"width\" | \"height\" | \"format\" | \"tooltip\" | \"markLabel\" | \"markDescription\" | \"legend\" | \"seriesLabels\" | \"table\" | \"announce\"]?: unknown };\n\n/** Throws on the options every chart shares when they're the wrong kind of thing. `chart` names the chart in the message. */\nexport function checkChartOptions(options: CommonOptions, chart: string): void {\n if (typeof options !== \"object\" || options === null) throw new TypeError(`${chart} needs options.`);\n if (typeof options.label !== \"string\" || options.label.trim() === \"\") throw new TypeError(`${chart} needs a label: the chart's accessible name.`);\n if (!Array.isArray(options.data)) throw new TypeError(`${chart}: data must be an array of rows.`);\n for (const field of [\"width\", \"height\"] as const) {\n const value = options[field];\n if (value !== undefined && !(typeof value === \"number\" && Number.isFinite(value) && value > 0)) throw new RangeError(`${chart}: ${field} must be a positive number of px, got ${String(value)}.`);\n }\n const { format, tooltip, markLabel, markDescription, legend, announce } = options;\n if (format !== undefined && typeof format !== \"function\") throw new TypeError(`${chart}: format must be a function that turns a value into text.`);\n if (tooltip !== undefined && typeof tooltip !== \"boolean\" && typeof tooltip !== \"function\") throw new TypeError(`${chart}: tooltip must be true, false or a function that returns a row's text.`);\n if (markLabel !== undefined && typeof markLabel !== \"function\") throw new TypeError(`${chart}: markLabel must be a function that returns a mark's accessible name.`);\n if (markDescription !== undefined && markDescription !== false && typeof markDescription !== \"function\") {\n throw new TypeError(`${chart}: markDescription must be false or a function that returns a mark's accessible description.`);\n }\n checkLegendOption(legend, chart);\n checkSeriesLabels(options.seriesLabels, chart);\n checkTableOption(options.table, chart);\n if (announce !== undefined && typeof announce !== \"boolean\" && typeof announce !== \"function\") throw new TypeError(`${chart}: announce must be true, false or a function that returns the text to announce.`);\n}\n","// A chart's transitions: one in flight at a time, drawn every frame until its tweens settle, then landed\n// exactly on the layout. An update's change, played through the runner in the order it expects. And\n// the small tests a chart's retarget makes: whether a value still has to move, whether a mark moved.\n\nimport type { Animated, Clock, MarkGeometry } from \"../../core\";\nimport type { RunInput, Runner } from \"../../core/runner\";\nimport type { ChartEvents } from \"./events\";\nimport type { ChartHover } from \"./hover\";\nimport type { Leave, LeavingMark, LeavingMarks } from \"./leaving\";\n\nexport interface ChartTransitionsOptions {\n readonly clock: Clock;\n readonly runner: Pick<Runner, \"settle\">;\n readonly leaving: Pick<LeavingMarks<LeavingMark>, \"sweep\">;\n /** Draws what moved since the last frame. */\n draw(): void;\n /** Draws exactly the layout once a transition settles: the frames in between are computed, this is laid out. */\n land(): void;\n}\n\nexport interface ChartTransitions {\n /**\n * Draws the first frame of a transition whose tweens, `running`, have just started, then every frame\n * until they've all settled. Resolves when it settles. One still in flight is taken over: its waiters\n * wait for this one instead.\n */\n run(running: readonly Promise<unknown>[]): Promise<void>;\n /** Resolves the latest update()'s promise early: another update() supersedes it. */\n supersede(): void;\n /**\n * The promise update() returns: it resolves once `settled` has and the marks the update removed are\n * gone (their exit effects done), or as soon as another update() supersedes it.\n */\n wait(settled: Promise<void>, leaves: readonly Leave[]): Promise<void>;\n destroy(): void;\n}\n\nexport function chartTransitions(options: ChartTransitionsOptions): ChartTransitions {\n const { clock } = options;\n /** The transition in flight: resolved when it settles. */\n let transition: { readonly id: number; readonly waiters: readonly (() => void)[] } | undefined;\n let transitions = 0;\n let unfollow: (() => void) | undefined;\n /** Resolves the latest update()'s promise early, when another update() supersedes it. */\n let supersede: (() => void) | undefined;\n let destroyed = false;\n\n function settle(id: number): void {\n if (destroyed || transition?.id !== id) return;\n const { waiters } = transition;\n transition = undefined;\n unfollow?.();\n unfollow = undefined;\n options.land();\n options.runner.settle();\n options.leaving.sweep();\n for (const resolve of waiters) resolve();\n }\n\n return {\n run(running) {\n options.draw();\n const id = ++transitions;\n return new Promise<void>((resolve) => {\n transition = { id, waiters: [...(transition?.waiters ?? []), resolve] };\n if (running.length === 0) {\n settle(id);\n return;\n }\n // Subscribed after the tweens just started, so each frame draws once they've all moved.\n unfollow?.();\n unfollow = clock.onFrame(() => options.draw());\n void Promise.all(running).then(() => settle(id));\n });\n },\n supersede: () => supersede?.(),\n wait(settled, leaves) {\n return new Promise<void>((resolve) => {\n supersede = resolve;\n void settled.then(() => Promise.all(leaves.map((leave) => leave.gone))).then(() => resolve());\n });\n },\n destroy() {\n destroyed = true;\n transition = undefined;\n unfollow?.();\n supersede?.();\n }\n };\n}\n\n/** What an update changed, in the chart's own mark records. */\nexport interface ChartDiff<R> {\n readonly entering: R[];\n readonly exiting: R[];\n /** Values changed: update effects run. A move alone (a re-sort, a new scale) isn't a change. */\n readonly changed: { readonly record: R; readonly from: MarkGeometry }[];\n}\n\nexport interface PlayUpdateOptions<D, R extends LeavingMark> {\n readonly runner: Runner<D>;\n readonly events: ChartEvents<D>;\n readonly hover: Pick<ChartHover, \"dropGone\" | \"sync\">;\n readonly leaving: Pick<LeavingMarks<R>, \"sweep\">;\n /** Where a mark is heading: what enter and update report as a change starts. */\n input(record: R): RunInput<D>;\n /** The mark as it is on screen: what exit reports, so it matches what's on its way out. */\n onScreen(record: R): RunInput<D>;\n /**\n * Whether update() was given `data`. Then it's an update even if no value changed (a matchweek where\n * nobody scores), so the runner ends the update runs of the marks it leaves alone. Without `data`,\n * it's one only if a value changed or a mark came or went: `update({ on })` alone keeps them.\n */\n readonly data: boolean;\n /**\n * With a new `on`: swaps the runner's effects once `arrange` has matched the new layout to the\n * marks, before the runner hears the change, so the new effects start on the marks as the update\n * leaves them and play its exit, update and enter. Given what changed, so it can leave out the\n * marks entering, which enter() starts.\n */\n swap?(diff: ChartDiff<R>): void;\n}\n\n/**\n * Plays an update's change through the runner, in the order it expects: interrupt; `arrange` matches\n * the new layout to the marks; new effects, if any, are swapped in; a hover whose mark has left ends; then exit, update and enter, each\n * followed by its events; `announce`; and the tab stop follows its key. The runner hears update() only\n * for an update (see `data`), so `update({ on })` alone keeps what the last one explained. The runner\n * then hears change() on every frame, and settle() once the transition settles. Returns the leaves to wait for.\n */\nexport function playUpdate<D, R extends LeavingMark>(\n options: PlayUpdateOptions<D, R>,\n arrange: () => ChartDiff<R>,\n announce: (diff: ChartDiff<R>) => void\n): Leave[] {\n const { runner, events, input, onScreen } = options;\n runner.interrupt();\n const diff = arrange();\n options.swap?.(diff);\n options.hover.dropGone();\n const leaves = diff.exiting.map((record) => record.leave!);\n const exited = runner.exit(diff.exiting.map(onScreen));\n void exited.then(() => {\n for (const leave of leaves) leave.exited = true;\n options.leaving.sweep();\n });\n events.emitEach(\"exit\", diff.exiting, onScreen);\n if (options.data || diff.changed.length > 0 || diff.entering.length > 0 || diff.exiting.length > 0) {\n runner.update(diff.changed.map(({ record, from }) => ({ ...input(record), from })));\n }\n events.emitEach(\"update\", diff.changed, ({ record, from }) => ({ ...input(record), from }));\n runner.enter(diff.entering.map(input));\n events.emitEach(\"enter\", diff.entering, input);\n announce(diff);\n // Focus stayed with its key. If that mark is leaving, focus moves to its nearest neighbour, whose\n // hover the runner holds until the change settles.\n options.hover.sync();\n return leaves;\n}\n\n/** Still animating, or resting somewhere else than `to`. */\nexport function busy<T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean): boolean {\n return value.animating || !equal(value.value, to);\n}\n\nexport const same = (a: number, b: number): boolean => a === b;\n\n/** The same fields with the same values. */\nexport function sameFields<T extends object>(a: T, b: T): boolean {\n const keys = Object.keys(a) as (keyof T)[];\n return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);\n}\n\n/** Whether a mark looks different: its outline, its segments, or its labels' boxes. Its runs hear about it through change(). */\nexport function geometryChanged(from: MarkGeometry, to: MarkGeometry): boolean {\n if (from.outline.d !== to.outline.d || labelsMoved(from, to)) return true;\n const a = from.segments ?? [];\n const b = to.segments ?? [];\n return a.length !== b.length || a.some((segment, i) => segment.key !== b[i]!.key || segment.outline.d !== b[i]!.outline.d);\n}\n\n/** Whether a mark's `labelBounds` differ: text placed past them has to follow. */\nexport function labelsMoved(from: MarkGeometry, to: MarkGeometry): boolean {\n const a = from.labelBounds;\n const b = to.labelBounds;\n if (a === b) return false;\n if (!a || !b || a.length !== b.length) return true;\n return a.some((box, i) => box.x !== b[i]!.x || box.y !== b[i]!.y || box.width !== b[i]!.width || box.height !== b[i]!.height);\n}\n","// What a chart follows on the page besides its options: its container's width, web fonts arriving,\n// and the motion that times its CSS hover transitions. Each returns its stop.\n\nimport type { Clock } from \"../../core\";\nimport type { ChartMotion } from \"../motion\";\n\n/**\n * Follows the container's width with a ResizeObserver, from `width`, the one laid out at. `resize`\n * hears of a change of half a px or more, at most once a frame.\n */\nexport function watchWidth(container: Element, clock: Clock, width: number, resize: (width: number) => void): () => void {\n if (typeof ResizeObserver !== \"function\") return () => {};\n let measured = width;\n let pending = width;\n let stopFrame: (() => void) | undefined;\n const observer = new ResizeObserver((entries) => {\n const next = entries[entries.length - 1]?.contentRect.width ?? 0;\n if (!(next > 0) || Math.abs(next - pending) < 0.5) return;\n pending = next;\n // Once per frame, outside the observer callback, so the new height can't loop back into it.\n stopFrame ??= clock.onFrame(() => {\n stopFrame?.();\n stopFrame = undefined;\n if (Math.abs(pending - measured) < 0.5) return;\n measured = pending;\n resize(measured);\n });\n });\n observer.observe(container);\n return () => {\n observer.disconnect();\n stopFrame?.();\n };\n}\n\n/** Calls `loaded` each time web fonts finish loading: text measured before then was measured in a fallback font. */\nexport function watchFonts(doc: Document, loaded: () => void): () => void {\n const fonts = (doc as Document & { fonts?: EventTarget }).fonts;\n fonts?.addEventListener?.(\"loadingdone\", loaded);\n return () => fonts?.removeEventListener?.(\"loadingdone\", loaded);\n}\n\n/** CSS hover transitions read their duration, `--ec-hover-duration`, from motion, like everything else. */\nexport function watchHoverDuration(svg: SVGSVGElement, motion: ChartMotion): () => void {\n const sync = (): void => svg.style.setProperty(\"--ec-hover-duration\", `${motion.duration(100, \"feedback\")}ms`);\n sync();\n return motion.subscribe(sync);\n}\n","// The chart's tooltip: an HTML box beside the hovered or focused mark, placed from the mark's bounds\n// and centre, or at a point, such as a crosshair over the points it crosses. The box is aria-hidden, so it isn't read twice: each mark's aria-label has the values,\n// and its accessible description is `markDescription`'s text or, by default, a tooltip function's.\n// Its text is only ever set as text, never parsed as HTML, so a tooltip function can't inject markup.\n// While it shows it takes the pointer, so it can be hovered (WCAG 1.4.13): beside a mark, a clear\n// bridge spans the gap to the mark, so the pointer can cross from one to the other. One that comes up\n// under a pointer that didn't move onto it lets the pointer through until the pointer is off it.\n\nimport { matrix, type Matrix, type MarkGeometry, type MotionView } from \"../core\";\nimport { report } from \"../core/report\";\nimport { svgElement } from \"./render/svg\";\n\n/** The `tooltip` option: on (the default text), off, or a function giving a row's text. */\nexport type TooltipOption<D> = boolean | ((d: D) => string);\n\n/** Plain text (a function's, with \"\\n\" for line breaks), or a bold title over lines. */\nexport type TooltipContent = string | { readonly title: string; readonly lines: readonly string[] };\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\n/** What the box is placed against, in the chart box's px: the x to centre on, and the mark's top and bottom edges. */\nexport interface TooltipAnchor {\n readonly x: number;\n readonly top: number;\n readonly bottom: number;\n}\n\n/** A point the box is placed at instead of a mark, in the <svg>'s viewBox units: the x to centre on, and the top and bottom to keep clear. */\nexport interface TooltipPoint {\n readonly x: number;\n readonly top: number;\n readonly bottom: number;\n}\n\nexport interface TooltipPlacement {\n /** The box's top-left corner, in the chart box's px. */\n readonly x: number;\n readonly y: number;\n readonly side: \"above\" | \"below\";\n}\n\nexport interface Tooltip {\n /**\n * Shows the tooltip beside `mark` (in the <svg>'s viewBox units), or moves it there. `transform` is\n * an effect's transform on the mark, which the tooltip follows. Its text is worked out again only\n * when `row` or the option changes: the default `summary`, a function's result, or nothing with\n * `tooltip: false`.\n */\n show(mark: MarkGeometry, row: { readonly datum: unknown }, summary: () => TooltipContent, transform?: Matrix): void;\n /**\n * Shows the tooltip at `point` instead of beside a mark, or moves it there: centred on its x, above\n * its top or, without room there, below its bottom. A line chart's crosshair gives its x and the\n * highest and lowest points it crosses. The text is worked out as show()'s is.\n */\n showAt(point: TooltipPoint, row: { readonly datum: unknown }, summary: () => TooltipContent): void;\n /**\n * Gives the mark's `element` its accessible description for `row` (aria-describedby, to a <desc>\n * inside it): `markDescription`'s text when it's a function, nothing when it's false, and otherwise\n * a tooltip function's text, so what a custom tooltip adds beyond the values reaches screen readers.\n * The default tooltip text says nothing the mark's aria-label doesn't, so it describes nothing.\n */\n describe(element: SVGElement, row: { readonly datum: unknown }): void;\n /**\n * The tooltip while it shows, or undefined: its layer, holding the box and, beside a mark, the\n * bridge to it. Both take the pointer.\n */\n element(): HTMLElement | undefined;\n hide(): void;\n destroy(): void;\n}\n\n/** Px between the mark and the box, as in the prototype. */\nconst GAP = 12;\n/** Px the bridge reaches into the mark, so no sliver is left between them. */\nconst OVERLAP = 1;\n/** Base ms for showing and hiding: hover feedback. */\nconst FADE = 100;\n/** For description ids, unique in the page. */\nlet described = 0;\n\n/**\n * Where the box goes: centred on the mark, above it, or below it when there isn't room above. When\n * neither side has room it takes the side with more. `side` picks it instead. It's clamped to the\n * box's left and right edges (to the left edge when it's wider), but never moved over the mark it\n * describes.\n */\nexport function placeTooltip(anchor: TooltipAnchor, size: Size, box: Size, side?: TooltipPlacement[\"side\"]): TooltipPlacement {\n const above = anchor.top - GAP;\n const below = box.height - anchor.bottom - GAP;\n side ??= size.height <= above || above >= below ? \"above\" : \"below\";\n return {\n x: Math.max(0, Math.min(box.width - size.width, anchor.x - size.width / 2)),\n y: side === \"above\" ? above - size.height : anchor.bottom + GAP,\n side\n };\n}\n\n/**\n * The default text: the category, then each series' value in `format` with its label, or its name\n * when it has none (\"16 goals · 4 assists\"), then the total when there's more than one. A lone value\n * read by a function (its series is \"value\") goes unnamed unless it's labelled, as in the marks' names.\n * `total: false` leaves the total out, for series that don't add up (goals and xG at one x).\n */\nexport function summaryContent(\n category: string,\n values: readonly { readonly series: string; readonly label?: string; readonly value: number }[],\n format: (value: number) => string,\n options: { readonly total?: boolean } = {}\n): TooltipContent {\n const lone = values.length === 1 && values[0]!.series === \"value\" && (values[0]!.label ?? \"value\") === \"value\";\n const lines = [values.map((v) => (lone ? format(v.value) : `${format(v.value)} ${v.label ?? v.series}`)).join(\" · \")];\n if (values.length > 1 && options.total !== false) lines.push(`${format(values.reduce((sum, v) => sum + v.value, 0))} total`);\n return { title: category, lines };\n}\n\n/**\n * The tooltip for a chart's <svg>. The box is made the first time it shows, in a positioned layer\n * just after the <svg>, and placed in px from both elements' boxes, so it lands right whatever the\n * page's layout. Showing and hiding fade over `feedback` timing, so they're instant with motion off.\n */\nexport function chartTooltip<D>(\n svg: SVGSVGElement,\n options: {\n readonly motion: Pick<MotionView, \"duration\">;\n readonly option: () => TooltipOption<D> | undefined;\n /** The `markDescription` option: a function, false, or unset (a tooltip function's text). */\n readonly description?: () => false | ((d: D) => string) | undefined;\n }\n): Tooltip {\n let layer: HTMLDivElement | undefined;\n let box: HTMLDivElement | undefined;\n let bridge: HTMLDivElement | undefined;\n /** Each row's text, and the option it was worked out with: a function is called once per row. */\n let texts = new WeakMap<object, { readonly option: TooltipOption<D> | undefined; readonly content: TooltipContent | undefined }>();\n /** The text the box shows. */\n let rendered: string | undefined;\n /** Where a mouse or pen last was, in client px. */\n let pointer: { readonly x: number; readonly y: number } | undefined;\n /**\n * Whether it came up, or moved, under a pointer that hadn't moved onto it: a crosshair's column\n * reaches it, so it can. Then it lets the pointer through, so it doesn't catch a pointer running\n * along the chart, until the pointer is off it.\n */\n let through = false;\n /** The bridge's trapezoid in the layer's px, while there's one. */\n let shape: Trapezoid | undefined;\n\n const timing = (element: HTMLElement): void => element.style.setProperty(\"--ec-hover-duration\", `${options.motion.duration(FADE, \"feedback\")}ms`);\n\n const shown = (): boolean => box?.classList.contains(\"ec-tooltip-shown\") ?? false;\n /** Whether the pointer is over the box or the bridge. */\n const under = (): boolean => {\n if (!pointer || !box || !layer) return false;\n const { x, y } = pointer;\n const { left, right, top, bottom } = box.getBoundingClientRect();\n if (x > left && x < right && y > top && y < bottom) return true;\n if (!shape) return false;\n const origin = layer.getBoundingClientRect();\n return inside(shape, x - origin.left, y - origin.top);\n };\n const letThrough = (on: boolean): void => {\n through = on;\n layer?.classList.toggle(\"ec-tooltip-through\", on);\n };\n /** The document's pointer, heard before the chart hears it. */\n const track = (event: PointerEvent): void => {\n pointer = event.pointerType === \"touch\" ? undefined : { x: event.clientX, y: event.clientY };\n if (through && !under()) letThrough(false);\n };\n\n svg.ownerDocument.addEventListener(\"pointerover\", track, true);\n svg.ownerDocument.addEventListener(\"pointermove\", track, true);\n\n /** The box, in its layer just after the <svg>, with the bridge after it. */\n function made(): HTMLDivElement {\n if (!layer || !box || !bridge) {\n const doc = svg.ownerDocument;\n layer = doc.createElement(\"div\");\n layer.className = \"ec-tooltip-layer\";\n box = doc.createElement(\"div\");\n box.className = \"ec-tooltip\";\n box.setAttribute(\"aria-hidden\", \"true\");\n bridge = doc.createElement(\"div\");\n bridge.className = \"ec-tooltip-bridge\";\n bridge.setAttribute(\"aria-hidden\", \"true\");\n layer.append(box, bridge);\n }\n if (layer.previousSibling !== svg) svg.after(layer);\n return box;\n }\n\n function contentFor(row: { readonly datum: unknown }, summary: () => TooltipContent): TooltipContent | undefined {\n const option = options.option();\n const known = texts.get(row);\n if (known && known.option === option) return known.content;\n const content = text(option, row.datum as D, summary);\n texts.set(row, { option, content });\n return content;\n }\n\n function hide(): void {\n if (!box) return;\n timing(box);\n box.classList.remove(\"ec-tooltip-shown\");\n letThrough(false);\n }\n\n /**\n * Shows the box with `row`'s text, placed against `anchor`: it turns viewBox units into the chart\n * box's px with `toPx`, at rest or, with `moved`, as an effect has moved the mark. An anchor with a\n * left and right edge is a mark, and gets a bridge.\n */\n function place(row: { readonly datum: unknown }, summary: () => TooltipContent, anchor: (toPx: ToPx, moved: boolean) => Anchored, moved: boolean): void {\n const content = contentFor(row, summary);\n if (content === undefined) {\n hide();\n return;\n }\n const tip = made();\n // The pointer on it, having moved onto it, stays on it wherever it goes.\n const held = shown() && !through && under();\n const key = typeof content === \"string\" ? `text:${content}` : JSON.stringify(content);\n if (key !== rendered) {\n render(tip, content);\n rendered = key;\n }\n // The <svg> may be scaled to fit its container: its viewBox units become px by its width.\n const view = viewBox(svg);\n const chart = svg.getBoundingClientRect();\n const k = chart.width > 0 && view.width > 0 ? chart.width / view.width : 1;\n const toPx: ToPx = { x: (x) => (x - view.x) * k, y: (y) => (y - view.y) * k };\n const area = chart.width > 0 ? { width: chart.width, height: chart.height } : { width: view.width, height: view.height };\n const size = { width: tip.offsetWidth, height: tip.offsetHeight };\n const near = anchor(toPx, moved);\n // The side is the mark's at rest, so an effect moving it (a wiggle) can't flip the box back and forth.\n const placed = placeTooltip(near, size, area, moved ? placeTooltip(anchor(toPx, false), size, area).side : undefined);\n const origin = layer!.getBoundingClientRect();\n // From the chart box's px to the layer's.\n const dx = chart.left - origin.left;\n const dy = chart.top - origin.top;\n const left = Math.round(dx + placed.x);\n const top = Math.round(dy + placed.y);\n tip.style.left = `${left}px`;\n tip.style.top = `${top}px`;\n tip.setAttribute(\"data-side\", placed.side);\n const mark = near.left === undefined || near.right === undefined ? undefined : { left: dx + near.left, right: dx + near.right, top: dy + near.top, bottom: dy + near.bottom };\n shape = span(bridge!, { left, top, ...size }, mark, placed.side);\n timing(tip);\n tip.classList.add(\"ec-tooltip-shown\");\n letThrough(!held && under());\n }\n\n return {\n show(mark, row, summary, transform) {\n const anchor = (toPx: ToPx, moved: boolean): Anchored => {\n const m = moved ? transform : undefined;\n const { x, y, width, height } = mark.bounds;\n const corners = [{ x, y }, { x: x + width, y }, { x, y: y + height }, { x: x + width, y: y + height }].map((corner) => (m ? matrix.apply(m, corner) : corner));\n const xs = corners.map((corner) => corner.x);\n const ys = corners.map((corner) => corner.y);\n const center = m ? matrix.apply(m, mark.center) : mark.center;\n return { x: toPx.x(center.x), top: toPx.y(Math.min(...ys)), bottom: toPx.y(Math.max(...ys)), left: toPx.x(Math.min(...xs)), right: toPx.x(Math.max(...xs)) };\n };\n place(row, summary, anchor, transform !== undefined);\n },\n showAt(point, row, summary) {\n place(row, summary, (toPx) => ({ x: toPx.x(point.x), top: toPx.y(point.top), bottom: toPx.y(point.bottom) }), false);\n },\n describe(element, row) {\n const own = options.description?.();\n let content: TooltipContent | undefined;\n if (own === false) content = undefined;\n else if (typeof own === \"function\") {\n try {\n const text: unknown = own(row.datum as D);\n content = typeof text === \"string\" && text !== \"\" ? text : undefined;\n } catch (error) {\n report(error);\n content = undefined;\n }\n } else content = typeof options.option() === \"function\" ? contentFor(row, () => \"\") : undefined;\n let desc = element.querySelector<SVGDescElement>(\":scope > desc.ec-description\");\n if (typeof content !== \"string\") {\n if (!desc) return;\n if (element.getAttribute(\"aria-describedby\") === desc.id) element.removeAttribute(\"aria-describedby\");\n desc.remove();\n return;\n }\n desc ??= svgElement(\"desc\", { class: \"ec-description\", id: `ec-description-${++described}` }, element);\n if (desc.textContent !== content) desc.textContent = content;\n element.setAttribute(\"aria-describedby\", desc.id);\n },\n element: () => (shown() ? layer : undefined),\n hide,\n destroy() {\n svg.ownerDocument.removeEventListener(\"pointerover\", track, true);\n svg.ownerDocument.removeEventListener(\"pointermove\", track, true);\n layer?.remove();\n layer = undefined;\n box = undefined;\n bridge = undefined;\n shape = undefined;\n through = false;\n texts = new WeakMap();\n rendered = undefined;\n }\n };\n}\n\n/** A mark's edges in px. */\ninterface Edges {\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly bottom: number;\n}\n\n/** What the box is placed against in the chart box's px and, for a mark, its left and right edges. */\ninterface Anchored extends TooltipAnchor {\n readonly left?: number;\n readonly right?: number;\n}\n\n/** A trapezoid with level top and bottom edges: their y's, and each edge's left and right. */\ninterface Trapezoid {\n readonly top: number;\n readonly bottom: number;\n readonly upper: { readonly left: number; readonly right: number };\n readonly lower: { readonly left: number; readonly right: number };\n}\n\n/** Whether a point is inside a trapezoid, off its edges. */\nfunction inside({ top, bottom, upper, lower }: Trapezoid, x: number, y: number): boolean {\n if (y <= top || y >= bottom) return false;\n const t = (y - top) / (bottom - top);\n return x > upper.left + (lower.left - upper.left) * t && x < upper.right + (lower.right - upper.right) * t;\n}\n\n/**\n * Spans the bridge across the gap between the box and `mark`, in the layer's px: a trapezoid from the\n * box's edge to the mark's, a px into it, so the pointer can go straight from one to the other without\n * leaving the hover. It's clear, and takes only the pointer. At a point there's none: a crosshair's\n * target is its whole column, which reaches the box. Gives the trapezoid, if there's one.\n */\nfunction span(bridge: HTMLElement, box: { readonly left: number; readonly top: number; readonly width: number; readonly height: number }, mark: Edges | undefined, side: TooltipPlacement[\"side\"]): Trapezoid | undefined {\n bridge.hidden = mark === undefined;\n if (!mark) return undefined;\n const edge = { left: box.left, right: box.left + box.width };\n // The upper edge and the lower one, with their y's.\n const [upper, lower, top, bottom] =\n side === \"above\" ? [edge, mark, box.top + box.height, Math.round(mark.top + OVERLAP)] : [mark, edge, Math.round(mark.bottom - OVERLAP), box.top];\n const left = Math.round(Math.min(upper.left, lower.left));\n const width = Math.round(Math.max(upper.right, lower.right)) - left;\n const height = Math.max(0, bottom - top);\n const x = (value: number): string => `${Math.round(value) - left}px`;\n bridge.style.left = `${left}px`;\n bridge.style.top = `${top}px`;\n bridge.style.width = `${width}px`;\n bridge.style.height = `${height}px`;\n bridge.style.setProperty(\"clip-path\", `polygon(${x(upper.left)} 0px, ${x(upper.right)} 0px, ${x(lower.right)} ${height}px, ${x(lower.left)} ${height}px)`);\n const round = (edge: { readonly left: number; readonly right: number }) => ({ left: Math.round(edge.left), right: Math.round(edge.right) });\n return { top, bottom: top + height, upper: round(upper), lower: round(lower) };\n}\n\n/** None with `false`; a function's text, where an empty string or a throw shows none; otherwise the default. */\nfunction text<D>(option: TooltipOption<D> | undefined, datum: D, summary: () => TooltipContent): TooltipContent | undefined {\n if (option === false) return undefined;\n if (typeof option !== \"function\") return summary();\n try {\n const result = option(datum);\n return result === undefined || result === null || result === \"\" ? undefined : String(result);\n } catch (error) {\n report(error);\n return undefined;\n }\n}\n\nfunction render(box: HTMLDivElement, content: TooltipContent): void {\n if (typeof content === \"string\") {\n box.textContent = content;\n return;\n }\n const doc = box.ownerDocument;\n const line = (value: string, className?: string): HTMLDivElement => {\n const div = doc.createElement(\"div\");\n if (className) div.className = className;\n div.textContent = value;\n return div;\n };\n box.replaceChildren(line(content.title, \"ec-tooltip-title\"), ...content.lines.map((value) => line(value)));\n}\n\n/** Turns viewBox units into px in the chart's box. */\ninterface ToPx {\n x(x: number): number;\n y(y: number): number;\n}\n\n/** The <svg>'s viewBox, or its size from 0, 0 when it has none. */\nfunction viewBox(svg: SVGSVGElement): { readonly x: number; readonly y: number; readonly width: number; readonly height: number } {\n const parts = (svg.getAttribute(\"viewBox\") ?? \"\").split(/[\\s,]+/).map(Number);\n if (parts.length === 4 && parts.every(Number.isFinite)) return { x: parts[0]!, y: parts[1]!, width: parts[2]!, height: parts[3]! };\n return { x: 0, y: 0, width: Number(svg.getAttribute(\"width\")) || 0, height: Number(svg.getAttribute(\"height\")) || 0 };\n}\n","// barChart: the thin reference bar chart. Horizontal bars or vertical columns, plain or stacked; keyed\n// marks described with describe.bar; a measured layout; axis, grid and labels in theme colours;\n// colours by series or, with one series, by category; built-in hover dimming; pointer, touch and\n// keyboard hover with a tooltip; a legend for stacks or categories; a data table and, with `announce`, a\n// live region for screen readers. update() animates the change: staged in presentation (values, then positions), in one short stage\n// in analysis, at once when motion is off.\n//\n// The chart never names an effect: it resolves `on` through the presets it's handed and plays them\n// through the runner, which draws on the SVG surface. What doesn't depend on bars (events, hover and\n// focus, transitions and leaving marks, DOM order, size and fonts) is in shell/.\n\nimport type { AnimateOptions, Animated, TweenResult } from \"../core\";\nimport { animated, defaultClock, interpolateNumber, interpolateRecord } from \"../core\";\nimport { resolveEffects } from \"../core/registry\";\nimport { report } from \"../core/report\";\nimport { createRunner, type RunInput } from \"../core/runner\";\nimport { chartAnnouncer, changeText, type Announcer, type SortName } from \"./announce\";\nimport { barEncoding, layoutBars, placeRow, placeTick, type BarFrame, type BarLayout, type BarRow, type BarValue } from \"./bar-layout\";\nimport { toColorAssignment } from \"./colors\";\nimport { chartLegend } from \"./legend\";\nimport { linkable } from \"./link\";\nimport { chartMotion } from \"./motion\";\nimport { svgMarkHandle, type StyledPart, type SvgMarkHandle } from \"./render/mark-style\";\nimport { svgSurface } from \"./render/surface\";\nimport { setAttributes, setStyles, sizeAttributes, svgElement, transformAttribute } from \"./render/svg\";\nimport { placeText, textMeasure } from \"./render/text\";\nimport { injectStyles, markColorStyles, seriesColors } from \"./render/theme\";\nimport { seriesLabel } from \"./series\";\nimport { chartEvents } from \"./shell/events\";\nimport { decimals, format, round } from \"./shell/format\";\nimport { chartHover } from \"./shell/hover\";\nimport { chartLabel } from \"./shell/labels\";\nimport { leavingMarks, type Leave } from \"./shell/leaving\";\nimport { orderElements } from \"./shell/order\";\nimport { checkChartOptions, checkNeeds, containerWidth, describeChart, nextEffects, resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport { busy, chartTransitions, geometryChanged, playUpdate, same, sameFields, type ChartDiff } from \"./shell/transitions\";\nimport { watchFonts, watchHoverDuration, watchWidth } from \"./shell/watch\";\nimport { chartTable, tableModel, type TableModel } from \"./table\";\nimport { chartTooltip, summaryContent } from \"./tooltip\";\nimport type { BarChartOptions, Chart } from \"./types\";\n\nexport type { ChartEnv } from \"./shell/setup\";\n\nexport type BarChart<D> = Chart<D, BarChartOptions<D>>;\n\n/** Signed values by series, in data units. */\ntype Values = Readonly<Record<string, number>>;\n\ninterface MarkRecord<D> {\n readonly key: string;\n /** Where the mark is heading, or rests: its row in the latest layout (its last one while it leaves). */\n row: BarRow<D>;\n /** What's on screen now. */\n shown: BarRow<D>;\n readonly group: SVGGElement;\n readonly hit: SVGRectElement;\n readonly label: SVGTextElement;\n /** Holds the segments; effects' transform and opacity go here. */\n readonly body: SVGGElement;\n readonly value: SVGTextElement;\n readonly paths: Map<string, SVGPathElement>;\n parts: StyledPart[];\n readonly handle: SvgMarkHandle;\n /** In data units, so the bar's length follows the animated scale and always reads true against the axis. */\n readonly values: Animated<Values>;\n /** The order segments are drawn in: the layout's, with series on their way out kept where they were. */\n series: readonly string[];\n /** Position along the category axis, in bands. */\n readonly slot: Animated<number>;\n /** 0 to 1. A mark entering or leaving fades its labels; its bar grows or shrinks. */\n readonly presence: Animated<number>;\n /** The value label counts between totals, rounded to this many decimals; undefined shows the row's own text. */\n count: number | undefined;\n /** Set while the mark leaves. */\n leave: Leave | undefined;\n}\n\ninterface TickRecord {\n readonly value: number;\n readonly line: SVGLineElement;\n readonly label: SVGTextElement;\n /** Ticks the scale gains fade in, and ones it loses fade out. */\n readonly opacity: Animated<number>;\n /** In the latest layout. */\n wanted: boolean;\n}\n\n/** What an update changed. A re-sort or a new scale only moves a mark: its values didn't change. */\ntype Diff<D> = ChartDiff<MarkRecord<D>>;\n\n/** Base ms for each stage of a data change: values, then positions. Unstaged, a change takes as long as its stages together, which analysis scales down. */\nconst STAGE = 500;\n/** The focus ring's px: a gap in the surface colour around the mark, then the ring. */\nconst RING_GAP = 2;\nconst RING = 2;\n\nexport function barChart<D>(target: string | Element, options: BarChartOptions<D>, env: ChartEnv): BarChart<D> {\n const container = resolveTarget(target, \"barChart\");\n checkOptions(options);\n let current = options;\n const motion = chartMotion(options.motion, env.motion);\n let effects = resolveEffects(options.on, env.presets);\n let colors = toColorAssignment(options.colors);\n const clock = env.clock ?? defaultClock;\n const doc = container.ownerDocument;\n injectStyles(doc);\n\n // A named group of marks, each an image with its own name: see \"ARIA structure\" in docs/architecture.md.\n const svg = svgElement(\"svg\", { class: \"ec-chart ec-bar-chart\", role: \"group\" }, container);\n const grid = svgElement(\"g\", { class: \"ec-grid\", \"aria-hidden\": \"true\" }, svg);\n const axis = svgElement(\"g\", { class: \"ec-axis\", \"aria-hidden\": \"true\" }, svg);\n // Behind the marks, so it can't cover them; the gap keeps it apart from a bar in the same colour.\n const ring = svgElement(\"g\", { class: \"ec-focus\", \"aria-hidden\": \"true\", visibility: \"hidden\" }, svg);\n const ringPaths = [\n svgElement(\"path\", { class: \"ec-focus-ring\", \"stroke-width\": 2 * (RING_GAP + RING), \"stroke-linejoin\": \"round\" }, ring),\n svgElement(\"path\", { class: \"ec-focus-gap\", \"stroke-width\": 2 * RING_GAP, \"stroke-linejoin\": \"round\" }, ring)\n ];\n const marksLayer = svgElement(\"g\", { class: \"ec-marks\" }, svg);\n const overlay = svgElement(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" }, svg);\n const measure = textMeasure(svg);\n\n /** Marks on screen, in visual order. */\n let order: MarkRecord<D>[] = [];\n const records = new Map<string, MarkRecord<D>>();\n /** Marks on their way out: fading, or waiting for their exit effects. */\n const leaving = leavingMarks<MarkRecord<D>>((record) => record.values.animating || record.presence.animating);\n const byGroup = new WeakMap<Element, MarkRecord<D>>();\n const events = chartEvents<D>(\"barChart\");\n let measuredWidth = containerWidth(container);\n let destroyed = false;\n\n let laidOut: BarLayout<D>;\n let firstTable: TableModel | undefined;\n try {\n // Throws on data it can't draw, or a table column it can't read. Nothing but the <svg> is in\n // place yet (no listeners, observers or elements beside it), so that's all to undo.\n laidOut = layout(current);\n firstTable = tableFor(current, laidOut);\n } catch (error) {\n svg.remove();\n throw error;\n }\n\n const find = (key: string): MarkRecord<D> | undefined => records.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay,\n // Looked up on each call, so the handle follows the mark's record.\n mark: (key) => ({\n set: (style) => {\n find(key)?.handle.set(style);\n hover.restyled(key);\n },\n reset: () => {\n find(key)?.handle.reset();\n hover.restyled(key);\n }\n }),\n colors: (key) => find(key)?.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const tooltip = chartTooltip<D>(svg, { motion, option: () => current.tooltip, description: () => current.markDescription });\n const legend = chartLegend(svg);\n const table = chartTable(svg);\n let announcer: Announcer | undefined = current.announce ? chartAnnouncer(svg) : undefined;\n\n // ── Animated state ─────────────────────────────────────────────────────────\n // One animated value per mark property (values, slot, presence) plus the scale and the bands, so a\n // new update() mid-flight retargets each from where it is and nothing jumps.\n\n let orientation = laidOut.orientation;\n const ticks = new Map<number, TickRecord>();\n /** What changed since the last frame was drawn. */\n const dirty = new Set<MarkRecord<D>>();\n let frameMoved = false;\n let ticksFaded = false;\n const scale = animated(laidOut.frame.scale, interpolateRecord, { clock, motion, onChange: () => (frameMoved = true) });\n const bands = animated(laidOut.frame.bands, interpolateRecord, { clock, motion, onChange: () => (frameMoved = true) });\n\n const transitions = chartTransitions({ clock, runner, leaving, draw, land });\n\n // ── Drawing ────────────────────────────────────────────────────────────────\n\n function layout(opts: BarChartOptions<D>, using = effects): BarLayout<D> {\n const encoding = barEncoding(opts);\n checkNeeds(using, encoding.series.map((s) => s.series), \"barChart\");\n return layoutBars({\n data: opts.data,\n encoding,\n sort: opts.sort,\n width: opts.width ?? measuredWidth,\n height: opts.height,\n format: format(opts),\n measure,\n room: opts.room ?? 0\n });\n }\n\n /** A new mark: drawn as laid out, or, when it enters, at its slot with nothing showing yet. */\n function createRecord(row: BarRow<D>, entering: boolean): MarkRecord<D> {\n // An image: its aria-label says it all, and its text and shapes aren't read on their own.\n const group = svgElement(\"g\", { class: \"ec-mark\", \"data-key\": row.key, role: \"img\" }, marksLayer);\n const env = { clock, motion, onChange: () => dirty.add(record) };\n const values = valuesOf(row);\n const record: MarkRecord<D> = {\n key: row.key,\n row,\n shown: row,\n group,\n hit: svgElement(\"rect\", { class: \"ec-hit\" }, group),\n label: svgElement(\"text\", { class: \"ec-label\", \"aria-hidden\": \"true\" }, group),\n body: svgElement(\"g\", { class: \"ec-body\" }, group),\n value: svgElement(\"text\", { class: \"ec-value\", \"aria-hidden\": \"true\" }, group),\n paths: new Map(),\n parts: [],\n handle: svgMarkHandle(() => record),\n values: animated(entering ? zeros(values) : values, interpolateRecord, env),\n series: row.values.map((v) => v.series),\n slot: animated(row.slot, interpolateNumber, env),\n presence: animated(entering ? 0 : 1, interpolateNumber, env),\n count: undefined,\n leave: undefined\n };\n byGroup.set(group, record);\n drawMark(record, entering ? currentRow(record, currentFrame()) : row);\n return record;\n }\n\n function drawMark(record: MarkRecord<D>, row: BarRow<D>): void {\n const before = record.parts[0]?.colors.color;\n record.shown = row;\n setAttributes(record.hit, { ...row.hit });\n placeText(record.label, row.label);\n placeText(record.value, row.value);\n const presence = record.presence.value;\n const opacity = presence < 1 ? presence : undefined;\n setAttributes(record.label, { opacity });\n setAttributes(record.value, { opacity });\n const segments = row.geometry.segments ?? [];\n const keep = new Set<string>();\n // By category, the bar's own slot: the assignment never hears the series' name, so a shared one\n // keeps every slot for the categories.\n const ownColors = byCategory(current) ? seriesColors(colors.slot(record.key)) : undefined;\n record.parts = segments.map((segment) => {\n const series = segment.series ?? segment.key;\n keep.add(series);\n let element = record.paths.get(series);\n if (!element) {\n element = svgElement(\"path\", { class: \"ec-segment\", \"data-series\": series }, record.body);\n record.paths.set(series, element);\n }\n const partColors = ownColors ?? seriesColors(colors.slot(series));\n element.setAttribute(\"d\", segment.outline.d);\n setStyles(element, markColorStyles(partColors));\n return { element, d: segment.outline.d, colors: partColors, visible: segment.length >= 0.5 };\n });\n for (const [series, element] of record.paths) {\n if (keep.has(series)) continue;\n element.remove();\n record.paths.delete(series);\n }\n // Stack order, from the baseline, after the halo.\n const drawn = Array.from(record.body.children).filter((child) => child.classList.contains(\"ec-segment\"));\n if (record.parts.some((part, i) => drawn[i] !== part.element)) for (const part of record.parts) record.body.appendChild(part.element);\n record.handle.repaint();\n // A new palette or a different first series: overlays already drawn in \"mark\" follow.\n if (record.parts[0]?.colors.color !== before) surface.recolor(record.key);\n if (record.key === hover.ringKey) drawRing(record.key);\n }\n\n /** The focus ring follows the outline of the mark as it is on screen, moved with its body when an effect moves it. */\n function drawRing(key: string | undefined): void {\n const record = key === undefined ? undefined : records.get(key);\n if (!record) {\n ring.setAttribute(\"visibility\", \"hidden\");\n return;\n }\n for (const path of ringPaths) path.setAttribute(\"d\", record.shown.geometry.outline.d);\n const { transform } = record.handle.style;\n setAttributes(ring, { transform: transform && transformAttribute(transform), visibility: undefined });\n }\n\n /**\n * Draws the mark as `row`. Its runs hear about it when its geometry or its row changed, so\n * decorations follow: a label from a field the bar doesn't plot too.\n */\n function show(record: MarkRecord<D>, row: BarRow<D>): void {\n const moved = geometryChanged(record.shown.geometry, row.geometry) || record.shown.datum !== row.datum;\n drawMark(record, row);\n if (moved) runner.change(row.geometry, row.data);\n if (record.key === hover.key) showTooltip(record);\n }\n\n /** The tooltip beside the hovered mark as it is on screen, moved with its effects, with the text for where it's heading. */\n function showTooltip(record: MarkRecord<D>): void {\n const { row } = record;\n tooltip.show(record.shown.geometry, row, () => summaryContent(row.category, labelled(row.values, current), format(current)), record.handle.style.transform);\n }\n\n /** The legend for `next`: the series or, coloured by category, each bar's category in visual order. */\n function syncLegend(next: BarLayout<D>): void {\n if (byCategory(current)) {\n legend.categories(\n next.rows.map((row) => ({ key: row.key, label: row.category })),\n colors,\n current.legend\n );\n return;\n }\n legend.update(\n barEncoding(current).series.map((s) => ({ series: s.series, label: seriesLabel(current.seriesLabels, s.series) })),\n colors,\n current.legend\n );\n }\n\n /** The data table for `opts`, laid out as `next`: its rows in visual order. Throws on a column it can't read. */\n function tableFor(opts: BarChartOptions<D>, next: BarLayout<D>): TableModel | undefined {\n const encoding = barEncoding(opts);\n const field = encoding.orientation === \"horizontal\" ? opts.y : opts.x;\n return tableModel({\n option: opts.table,\n caption: opts.label,\n category: typeof field === \"string\" ? field : undefined,\n series: encoding.series.map((s) => s.series),\n label: (series) => seriesLabel(opts.seriesLabels, series),\n rows: next.rows.map((row) => ({ key: row.key, category: row.category, datum: row.datum, index: row.index, values: row.values, total: row.total })),\n format: format(opts)\n });\n }\n\n /** Says what an update changed, in the live region: the chart's summary, or the page's text from it. */\n function announceChange(previous: BarChartOptions<D>, diff: Diff<D>): void {\n const option = current.announce;\n if (!announcer || !option) return;\n const series = barEncoding(current).series.map((s) => s.series);\n const before = barEncoding(previous).series.map((s) => s.series);\n const sort = sortName(current.sort);\n const name = (record: MarkRecord<D>): string => record.row.category;\n const changed = diff.changed.map(({ record }) => record);\n const text = changeText({\n ...(current.label !== previous.label ? { label: current.label } : {}),\n // New series are said by their labels; new labels alone show the same view, so say nothing.\n ...(series.join(\"\\n\") !== before.join(\"\\n\") ? { series: series.map((s) => seriesLabel(current.seriesLabels, s)) } : {}),\n ...(sort !== sortName(previous.sort) || (sort === \"custom\" && current.sort !== previous.sort) ? { sort } : {}),\n changed: changed.map(name),\n added: diff.entering.map(name),\n removed: diff.exiting.map(name),\n count: order.length\n });\n if (typeof option !== \"function\") {\n announcer.say(text);\n return;\n }\n const key = (record: MarkRecord<D>): string => record.key;\n try {\n const said = option({ text, changed: changed.map(key), added: diff.entering.map(key), removed: diff.exiting.map(key) });\n if (said !== undefined && said !== null) announcer.say(String(said));\n } catch (error) {\n report(error);\n }\n }\n\n const currentFrame = (): BarFrame => ({ orientation, scale: scale.value, bands: bands.value });\n\n /** The mark as it is now, part way through a transition. */\n function currentRow(record: MarkRecord<D>, frame: BarFrame): BarRow<D> {\n const { row } = record;\n const now = record.values.value;\n const values = record.series.map((series) => ({ series, value: now[series] ?? 0 }));\n const total = values.reduce((sum, v) => sum + v.value, 0);\n const text = record.count === undefined ? row.value.text : format(current)(round(total, record.count));\n return placeRow(frame, { key: row.key, datum: row.datum, index: row.index, category: row.category, values, slot: record.slot.value, text, drawn: row.drawn }, measure);\n }\n\n function addTick(value: number, opacity: number): void {\n const tick: TickRecord = {\n value,\n line: svgElement(\"line\", { class: value === 0 ? \"ec-baseline\" : \"ec-gridline\" }, grid),\n label: svgElement(\"text\", { class: \"ec-tick\" }, axis),\n opacity: animated(opacity, interpolateNumber, { clock, motion, onChange: () => (ticksFaded = true) }),\n wanted: true\n };\n ticks.set(value, tick);\n // In value order, as the layout lists them.\n for (const t of [...ticks.values()].sort((a, b) => a.value - b.value)) {\n grid.appendChild(t.line);\n axis.appendChild(t.label);\n }\n }\n\n function drawTick(tick: TickRecord, frame: BarFrame): void {\n const placed = placeTick(frame, tick.value, format(current)(tick.value));\n const opacity = tick.opacity.value < 1 ? tick.opacity.value : undefined;\n setAttributes(tick.line, { ...placed.line, opacity });\n placeText(tick.label, placed.label);\n setAttributes(tick.label, { opacity });\n }\n\n /** Draws what moved since the last frame. */\n function draw(): void {\n const frame = currentFrame();\n if (frameMoved) setAttributes(svg, sizeAttributes(frame.bands));\n if (frameMoved || ticksFaded) for (const tick of ticks.values()) drawTick(tick, frame);\n for (const record of [...order, ...leaving.values()]) {\n if (frameMoved || dirty.has(record)) show(record, currentRow(record, frame));\n }\n frameMoved = false;\n ticksFaded = false;\n dirty.clear();\n }\n\n /** Draws exactly the layout once a transition settles: the frames in between are computed, this is laid out. */\n function land(): void {\n setAttributes(svg, sizeAttributes(laidOut.frame.bands));\n for (const tick of [...ticks.values()]) {\n if (tick.wanted) continue;\n tick.line.remove();\n tick.label.remove();\n ticks.delete(tick.value);\n }\n for (const placed of laidOut.ticks) {\n const tick = ticks.get(placed.value);\n if (!tick) continue;\n setAttributes(tick.line, { ...placed.line, opacity: undefined });\n placeText(tick.label, placed.label);\n tick.label.removeAttribute(\"opacity\");\n }\n for (const record of order) {\n record.series = record.row.values.map((v) => v.series);\n record.count = undefined;\n show(record, record.row);\n }\n frameMoved = false;\n ticksFaded = false;\n dirty.clear();\n }\n\n /** Matches the layout's rows to marks by key. New marks start at their slot with nothing showing; marks without a row start to leave. */\n function arrange(next: BarLayout<D>): Diff<D> {\n const keys = new Set(next.rows.map((row) => row.key));\n const diff: Diff<D> = { entering: [], exiting: [], changed: [] };\n for (const record of order) {\n if (keys.has(record.key)) continue;\n records.delete(record.key);\n leaving.start(record);\n record.count = undefined;\n diff.exiting.push(record);\n }\n const previous = order;\n order = next.rows.map((row) => {\n let record = records.get(row.key);\n if (record) {\n if (valuesChanged(record.row, row)) diff.changed.push({ record, from: record.shown.geometry });\n record.count = Math.max(decimals(record.row.total), decimals(row.total));\n } else {\n // A mark that comes back mid-exit keeps its element; the runner cancels its exit.\n record = leaving.recall(row.key) ?? createRecord(row, true);\n record.count = undefined;\n records.set(row.key, record);\n diff.entering.push(record);\n }\n record.row = row;\n record.series = mergeSeries(record.series, row.values.map((v) => v.series));\n labelMark(record);\n return record;\n });\n // DOM order follows visual order, for screen readers.\n orderElements(\n marksLayer,\n previous.map((record) => record.group),\n order.map((record) => record.group),\n hover.active\n );\n return diff;\n }\n\n /** The mark's accessible name, from where it's heading, and its description (`markDescription`, or a tooltip function's text). */\n function labelMark(record: MarkRecord<D>): void {\n record.group.setAttribute(\"aria-label\", markLabel(record.row, current));\n tooltip.describe(record.group, record.row);\n }\n\n /**\n * Sends every animated value toward `next`, and returns the animations started. Presentation stages\n * the change: values first (bars resize, leaving bars shrink, the scale and ticks retarget), then\n * positions (rows move to their slots; new bars grow in during the second half). A stage with\n * nothing to do is skipped. Analysis runs it all as one stage, which its scaling keeps short. A\n * jump (motion off, a new orientation, a resize) lands at once.\n */\n function retarget(next: BarLayout<D>, jump: boolean): Promise<TweenResult>[] {\n const { frame } = next;\n if (jump) orientation = next.orientation;\n const wanted = new Set(next.ticks.map((tick) => tick.value));\n for (const value of wanted) if (!ticks.has(value)) addTick(value, 0);\n for (const tick of ticks.values()) tick.wanted = wanted.has(tick.value);\n\n // New marks, and ones back after fading out completely, grow in at their slot.\n const arriving = new Set(order.filter((record) => record.presence.value === 0));\n const staying = order.filter((record) => !arriving.has(record));\n const gone = [...leaving.values()];\n\n const values =\n busy(scale, frame.scale, sameFields) ||\n [...ticks.values()].some((tick) => busy(tick.opacity, tick.wanted ? 1 : 0, same)) ||\n staying.some((record) => busy(record.values, valuesOf(record.row), sameFields) || busy(record.presence, 1, same)) ||\n gone.some((record) => busy(record.values, zeros(record.values.value), sameFields) || busy(record.presence, 0, same));\n const positions = arriving.size > 0 || busy(bands, frame.bands, sameFields) || staying.some((record) => busy(record.slot, record.row.slot, same));\n\n let first: AnimateOptions | undefined;\n let second: AnimateOptions | undefined;\n let grow: AnimateOptions | undefined;\n if (!jump && motion.staged) {\n const wait = values ? STAGE : 0;\n first = { duration: STAGE };\n second = { duration: STAGE, delay: wait };\n grow = { duration: STAGE / 2, delay: wait + STAGE / 2 };\n } else if (!jump) {\n first = second = grow = { duration: (values && positions ? 2 : 1) * STAGE };\n }\n\n const running: Promise<TweenResult>[] = [];\n const move = <T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean, timing: AnimateOptions | undefined): void => {\n if (!busy(value, to, equal)) return;\n if (timing) running.push(value.to(to, timing));\n else value.set(to);\n };\n move(scale, frame.scale, sameFields, first);\n move(bands, frame.bands, sameFields, second);\n for (const tick of ticks.values()) move(tick.opacity, tick.wanted ? 1 : 0, same, first);\n for (const record of staying) {\n move(record.values, valuesOf(record.row), sameFields, first);\n move(record.presence, 1, same, first);\n move(record.slot, record.row.slot, same, second);\n }\n for (const record of arriving) {\n record.slot.set(record.row.slot);\n move(record.values, valuesOf(record.row), sameFields, grow);\n move(record.presence, 1, same, grow);\n }\n for (const record of gone) {\n move(record.values, zeros(record.values.value), sameFields, first);\n move(record.presence, 0, same, first);\n }\n return running;\n }\n\n /**\n * Moves to `next`, animated or at once, drawing every frame. Resolves when the transition settles.\n * One still in flight is taken over: its waiters wait for this one instead.\n */\n function transitionTo(next: BarLayout<D>, jump: boolean): Promise<void> {\n laidOut = next;\n return transitions.run(retarget(next, jump));\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /** Where a mark is heading: what enter and update report as a change starts. */\n const input = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.row.geometry, data: record.row.data });\n /** The mark as it is on screen: what hover, leave and exit report, so mid-change they match what's under the pointer or on its way out. */\n const onScreen = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.shown.geometry, data: record.shown.data });\n\n /** The mark an event target belongs to; leaving marks don't count. */\n function liveRecordOf(eventTarget: EventTarget | null): MarkRecord<D> | undefined {\n const element = eventTarget as Element | null;\n const group = typeof element?.closest === \"function\" ? element.closest(\".ec-mark\") : null;\n const record = group ? byGroup.get(group) : undefined;\n return record && records.get(record.key) === record ? record : undefined;\n }\n\n // Pointer, touch and keyboard focus share one hover: see shell/hover.ts.\n const hover = chartHover<D>({\n svg,\n runner,\n events,\n dim: () => current.dim !== false,\n find(eventTarget) {\n const record = liveRecordOf(eventTarget);\n if (!record) return undefined;\n const segment = (eventTarget as Element).closest(\".ec-segment\")?.getAttribute(\"data-series\") ?? undefined;\n return segment === undefined ? { key: record.key } : { key: record.key, segment };\n },\n live: (key) => records.has(key),\n order: () => order.map((record) => record.key),\n element: (key) => find(key)?.group,\n onScreen(key) {\n const record = find(key);\n return record && onScreen(record);\n },\n ring: drawRing,\n tooltip: {\n show(key) {\n const record = records.get(key);\n if (record) showTooltip(record);\n },\n hide: () => tooltip.hide(),\n element: () => tooltip.element()\n }\n });\n\n // ── Motion, size and fonts ─────────────────────────────────────────────────\n\n const unwatchHoverDuration = watchHoverDuration(svg, motion);\n\n /** Re-lays out without animating: a resize or fonts loading. A transition in flight lands at once. Effects follow through change(). */\n function relayout(): void {\n if (destroyed) return;\n const next = layout(current);\n // The same rows as now: only the sizes changed.\n const rows = new Map(next.rows.map((row) => [row.key, row]));\n for (const record of order) record.row = rows.get(record.key) ?? record.row;\n void transitionTo(next, true);\n }\n\n const unwatchWidth = watchWidth(container, clock, measuredWidth, (width) => {\n measuredWidth = width;\n // A fixed `width` ignores the container.\n if (current.width === undefined) relayout();\n });\n\n // Label margins are measured; measure again once web fonts arrive.\n const unwatchFonts = watchFonts(doc, () => {\n measure.clear();\n relayout();\n });\n\n // ── First render ───────────────────────────────────────────────────────────\n\n describeChart(svg, current);\n syncLegend(laidOut);\n table.render(firstTable);\n setAttributes(svg, sizeAttributes(laidOut.frame.bands));\n for (const tick of laidOut.ticks) addTick(tick.value, 1);\n for (const tick of ticks.values()) drawTick(tick, laidOut.frame);\n order = laidOut.rows.map((row) => {\n const record = createRecord(row, false);\n records.set(row.key, record);\n labelMark(record);\n return record;\n });\n hover.sync();\n runner.enter(order.map(input));\n\n return linkable(hover.link, {\n element: svg,\n\n async update(next) {\n if (destroyed) return;\n if (next.motion !== undefined && next.motion !== current.motion) throw new TypeError(\"barChart: `motion` can't be changed by update() yet.\");\n const merged: BarChartOptions<D> = { ...current, ...next };\n checkOptions(merged);\n // Throws on an effect it can't resolve, data it can't draw, or a table column it can't read,\n // before anything changes.\n const swapped = \"on\" in next ? nextEffects(effects, current.on, merged.on, env.presets) : effects;\n const nextLayout = layout(merged, swapped);\n const nextTable = tableFor(merged, nextLayout);\n if (\"colors\" in next) colors = toColorAssignment(merged.colors);\n const previous = current;\n current = merged;\n describeChart(svg, current);\n syncLegend(nextLayout);\n table.render(nextTable);\n // A region that appears with its first text is often missed: it announces from the next update.\n const announcing = announcer !== undefined;\n if (current.announce && !announcer) announcer = chartAnnouncer(svg);\n else if (!current.announce && announcer) {\n announcer.destroy();\n announcer = undefined;\n }\n hover.syncDim();\n transitions.supersede();\n const swapping = swapped !== effects;\n effects = swapped;\n\n // The runner hears exit / update / enter now, then change() on every frame, then settle(). New\n // effects start where the old ones were, on the bars staying, as this update leaves them; a held\n // hover replays with them once the change settles.\n const leaves = playUpdate(\n {\n runner,\n events,\n hover,\n leaving,\n input,\n onScreen,\n data: \"data\" in next,\n ...(swapping\n ? {\n swap: (diff: Diff<D>) => {\n const entering = new Set(diff.entering);\n runner.swap(swapped, order.filter((record) => !entering.has(record)).map(input));\n }\n }\n : {})\n },\n () => arrange(nextLayout),\n (diff) => {\n if (announcing) announceChange(previous, diff);\n }\n );\n // Coloured the other way now: every bar takes its new colour on the change's first frame.\n if (byCategory(current) !== byCategory(previous)) for (const record of [...order, ...leaving.values()]) dirty.add(record);\n const settled = transitionTo(nextLayout, motion.mode === \"off\" || nextLayout.orientation !== orientation);\n await transitions.wait(settled, leaves);\n },\n\n on: events.on,\n\n marks: () => order.map((record) => record.shown.geometry),\n\n focus(key) {\n if (!destroyed) hover.focus(key);\n },\n\n leave() {\n if (!destroyed) hover.leave();\n },\n\n labels: () =>\n order.flatMap((record) => [\n ...chartLabel(record.key, \"category\", record.shown.label, record.label),\n ...chartLabel(record.key, \"value\", record.shown.value, record.value)\n ]),\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n // Ends the transition in flight, and resolves the latest update()'s promise.\n transitions.destroy();\n hover.destroy();\n runner.destroy();\n tooltip.destroy();\n legend.destroy();\n table.destroy();\n announcer?.destroy();\n unwatchHoverDuration();\n unwatchWidth();\n unwatchFonts();\n for (const record of [...order, ...leaving.values()]) {\n for (const value of [record.values, record.slot, record.presence]) value.stop();\n record.leave?.resolve();\n }\n scale.stop();\n bands.stop();\n for (const tick of ticks.values()) tick.opacity.stop();\n events.clear();\n records.clear();\n leaving.clear();\n order = [];\n svg.remove();\n }\n });\n}\n\n/** The options every chart shares, then `room`, and `colorBy`: \"category\" needs one series, so a stack throws. */\nfunction checkOptions<D>(options: BarChartOptions<D>): void {\n checkChartOptions(options, \"barChart\");\n const { colorBy, room } = options;\n if (room !== undefined && !(typeof room === \"number\" && Number.isFinite(room) && room >= 0)) throw new RangeError(`barChart: room must be a number of px, 0 or more, got ${String(room)}.`);\n if (colorBy !== undefined && colorBy !== \"series\" && colorBy !== \"category\") throw new TypeError(`barChart: colorBy must be \"series\" or \"category\", got ${String(colorBy)}.`);\n if (colorBy === \"category\" && options.stack !== undefined) {\n throw new TypeError('barChart: colorBy: \"category\" gives each bar one colour, so it needs one series, not a stack. A stack colours its segments by series.');\n }\n}\n\n/** Each bar takes its own slot, by key, rather than each segment its series'. */\nfunction byCategory<D>(options: BarChartOptions<D>): boolean {\n return options.colorBy === \"category\";\n}\n\n/**\n * \"Okafor: 16 goals, 4 assists\", each series said by its label, or the page's wording from `markLabel`.\n * A lone value read by a function (its series is \"value\") goes unnamed unless it's labelled: \"Okafor:\n * 16\". An empty name, or a throw (reported), keeps the default, so a focusable mark is never left unnamed.\n */\nfunction markLabel<D>(row: BarRow<D>, options: BarChartOptions<D>): string {\n const formatted = format(options);\n const values = labelled(row.values, options);\n const lone = values.length === 1 && values[0]!.series === \"value\" && values[0]!.label === \"value\";\n const text = `${row.category}: ${values.map((v) => (lone ? formatted(v.value) : `${formatted(v.value)} ${v.label}`)).join(\", \")}`;\n if (!options.markLabel) return text;\n try {\n const named: unknown = options.markLabel(row.datum, { key: row.key, category: row.category, values, total: row.total, format: formatted, text });\n if (named !== undefined && named !== null && String(named).trim() !== \"\") return String(named);\n } catch (error) {\n report(error);\n }\n return text;\n}\n\n/** The row's values, each with its series' label: what the tooltip and the mark's name say. Copies, so a page can't change the layout's. */\nfunction labelled<D>(values: readonly BarValue[], options: BarChartOptions<D>): { series: string; label: string; value: number }[] {\n return values.map((v) => ({ series: v.series, label: seriesLabel(options.seriesLabels, v.series), value: v.value }));\n}\n\nfunction valuesChanged<D>(from: BarRow<D>, to: BarRow<D>): boolean {\n return from.values.length !== to.values.length || from.values.some((v, i) => v.series !== to.values[i]!.series || v.value !== to.values[i]!.value);\n}\n\nfunction valuesOf<D>(row: BarRow<D>): Values {\n return Object.fromEntries(row.values.map((v) => [v.series, v.value]));\n}\n\nfunction zeros(values: Values): Values {\n return Object.fromEntries(Object.keys(values).map((series) => [series, 0]));\n}\n\n/**\n * The layout's series order, with series on their way out kept where they were: just after the\n * series they followed, or first. So a stack that loses its base shrinks it in place.\n */\nfunction mergeSeries(shown: readonly string[], next: readonly string[]): string[] {\n const out = [...next];\n shown.forEach((series, i) => {\n if (out.includes(series)) return;\n let at = 0;\n for (let j = i - 1; j >= 0; j--) {\n const found = out.indexOf(shown[j]!);\n if (found >= 0) {\n at = found + 1;\n break;\n }\n }\n out.splice(at, 0, series);\n });\n return out;\n}\n\nfunction sortName<D>(sort: BarChartOptions<D>[\"sort\"]): SortName {\n return typeof sort === \"function\" ? \"custom\" : (sort ?? \"none\");\n}\n","// The donut chart's layout: pure, so it's tested without a DOM. Options in, slices (described with\n// describe.arc), outside labels, the centre text and the size out. Sizes follow the prototype's card 3\n// (demo/lab.html): a ring whose inner radius is 0.6 × the outer, with labels outside it.\n//\n// A layout is drawn from a few numbers: the frame (the chart's size, the ring's centre and radii) and\n// each slice's value and angles. Transitions interpolate those, and placeSlice, placeLabels and\n// placeCenter draw any state in between the same way the layout draws its own.\n\nimport { describe, type MarkData, type MarkGeometry, type Rect } from \"../core\";\nimport { textBox, type TextPlacement } from \"./render/text\";\nimport { percent } from \"./shell/format\";\nimport type { DonutChartOptions } from \"./types\";\n\nexport interface DonutEncoding<D> {\n /** Names each slice. */\n readonly category: (d: D, i: number) => unknown;\n /** The category unless `key` is given. */\n readonly key: (d: D, i: number) => unknown;\n /** The slices' series: the value field's name, or \"value\" when a function reads it. */\n readonly series: string;\n readonly value: (d: D, i: number) => unknown;\n}\n\n/** Where the ring is: the chart's size, the ring's centre and its radii, all in px. */\nexport interface DonutFrame {\n readonly width: number;\n readonly height: number;\n readonly cx: number;\n readonly cy: number;\n readonly inner: number;\n readonly outer: number;\n}\n\n/** What placeSlice draws a slice from: a laid-out slice, or a state in between two. */\nexport interface SliceState<D> {\n readonly key: string;\n readonly datum: D;\n /** The row's index in `data`. */\n readonly index: number;\n readonly category: string;\n readonly series: string;\n /** In data units, 0 or more. */\n readonly value: number;\n /** The value's share of the total, from 0 to 1. */\n readonly share: number;\n /** Radians, 0 at 12 o'clock and clockwise: d3.pie()'s convention, as describe.arc takes them. */\n readonly start: number;\n readonly end: number;\n}\n\nexport interface DonutSlice<D> extends SliceState<D> {\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n}\n\n/** A slice's label outside the ring: its category over its share. */\nexport interface SliceLabel {\n readonly category: TextPlacement;\n readonly share: TextPlacement;\n /** Both lines' box, for overlaps. */\n readonly box: Rect;\n}\n\n/** A line of the centre's text. The first is drawn large, at `size` px. */\nexport interface CenterLine extends TextPlacement {\n readonly size: number;\n}\n\nexport interface DonutLayout<D> {\n readonly frame: DonutFrame;\n /** The values added up. */\n readonly total: number;\n /** Clockwise from 12 o'clock: the visual order. */\n readonly slices: readonly DonutSlice<D>[];\n /** Each slice's label, in the same order; undefined where none is shown. */\n readonly labels: readonly (SliceLabel | undefined)[];\n /** The centre's text, with \"\\n\" between lines; \"\" for none. */\n readonly centerText: string;\n readonly center: readonly CenterLine[];\n}\n\nexport interface DonutLayoutInput<D> {\n readonly data: readonly D[];\n readonly encoding: DonutEncoding<D>;\n readonly sort: DonutChartOptions<D>[\"sort\"];\n readonly width: number;\n readonly height: number | undefined;\n /** The centre's text for a total (\"\\n\" between lines), or \"\" for none. */\n readonly center: (total: number) => string;\n /** Text width in px, for the labels' room. */\n readonly measure: Measure;\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\nconst TAU = 2 * Math.PI;\nconst HEIGHT = 300;\n/** The inner radius, as a share of the outer: the prototype's 70 / 116. */\nconst HOLE = 0.6;\n/** Between the chart's edge and anything drawn. */\nconst PAD = 4;\n/** Between the ring and its labels. */\nconst GAP = 10;\n/** Slices narrower than this get no label: 15°. */\nconst LABEL_ANGLE = Math.PI / 12;\nconst LABEL_SIZE = 12.5;\nconst VALUE_SIZE = 12.5;\n/** A label's lines: the category's baseline sits this far below the block's top, the share's a line lower. */\nconst ASCENT = 10;\nconst LINE = 15;\n/** A label block's height: two lines and the share's descent. */\nconst BLOCK = ASCENT + LINE + 3;\n/** Labels keep at least this far apart. */\nconst LABEL_SPACE = 2;\n/** The centre's first line, in px, unless it's shrunk to fit the hole. */\nexport const CENTER_SIZE = 26;\nconst CENTER_MIN = 14;\n/** Baselines below the centre's first line: 20 px to the second (as in the prototype), 16 px after that. */\nconst CENTER_STEP = 20;\nconst CENTER_LINE = 16;\n/** Moves a text baseline down by this share of the font size to centre the text on a line. */\nconst CENTRE = 0.36;\n\n/** Reads the options: which accessor names the slices, which sizes them. Throws on what it can't draw. */\nexport function donutEncoding<D>(options: DonutChartOptions<D>): DonutEncoding<D> {\n const { category, value, key } = options;\n if (typeof category !== \"string\" && typeof category !== \"function\") {\n throw new TypeError(\"donutChart needs a category: the field, or a function, that names each slice.\");\n }\n if (typeof value !== \"string\" && typeof value !== \"function\") {\n throw new TypeError(\"donutChart needs a value: the numeric field, or a function, that sizes each slice.\");\n }\n if (key !== undefined && typeof key !== \"string\" && typeof key !== \"function\") throw new TypeError(\"donutChart: key must be a field name or a function.\");\n const name = accessor<D, unknown>(category);\n return {\n category: name,\n key: key === undefined ? name : accessor(key),\n series: typeof value === \"string\" ? value : \"value\",\n value: accessor(value)\n };\n}\n\nexport function layoutDonut<D>(input: DonutLayoutInput<D>): DonutLayout<D> {\n const rows = sortSlices(prepareSlices(input), input.sort);\n const frame = donutFrame(input, rows);\n const total = rows.reduce((sum, row) => sum + row.value, 0);\n const starts = joinedStarts(rows.map((row) => row.value));\n const states = rows.map((row, i): SliceState<D> => {\n const share = total > 0 ? row.value / total : 0;\n // The last slice ends exactly at 12 o'clock again.\n const end = i + 1 < rows.length && total > 0 ? starts[i + 1]! : total > 0 ? 1 : 0;\n return { ...row, series: input.encoding.series, share, start: starts[i]! * TAU, end: end * TAU };\n });\n const labels = placeLabels(frame, states, input.measure);\n const centerText = input.center(total);\n return {\n frame,\n total,\n slices: states.map((state, i) => placeSlice(frame, state, labels[i], input.measure)),\n labels,\n centerText,\n center: placeCenter(frame, centerText, input.measure)\n };\n}\n\n/**\n * Where each slice starts, in turns from 12 o'clock, laid end to end in order: values in data units,\n * so every start is a true share of the total. All 0 when the total is.\n */\nexport function joinedStarts(values: readonly number[]): number[] {\n const total = values.reduce((sum, v) => sum + v, 0);\n let before = 0;\n return values.map((value) => {\n const start = total > 0 ? before / total : 0;\n before += value;\n return start;\n });\n}\n\n/**\n * Draws a slice in a frame: its arc, described with describe.arc, and its data. With its label\n * (and `measure`), the boxes of the label's two lines are its `labelBounds`; with no label, none.\n */\nexport function placeSlice<D>(frame: DonutFrame, state: SliceState<D>, label?: SliceLabel, measure?: Measure): DonutSlice<D> {\n const geometry = describe.arc({\n key: state.key,\n series: state.series,\n cx: frame.cx,\n cy: frame.cy,\n inner: frame.inner,\n outer: frame.outer,\n start: state.start,\n end: state.end,\n labelBounds: label && measure ? labelBoxes(label, measure) : []\n });\n return { ...state, geometry, data: sliceData(state.datum, state.share, state.series) };\n}\n\n/**\n * The labels outside the ring, in the slices' order: each slice's category over its share, on slices\n * of 15° or more. A label sits just outside the ring at the slice's middle angle, and leans away from\n * it the way the slice points: beside the ring at 3 and 9 o'clock, above it at 12, below it at 6, and\n * smoothly in between, so a label never jumps as its slice turns. A label that would overlap the one\n * before it (or, going round, the first) or leave the chart is dropped; the legend, the tooltip, the\n * data table and the slice's name still say it.\n */\nexport function placeLabels<D>(frame: DonutFrame, slices: readonly SliceState<D>[], measure: Measure): (SliceLabel | undefined)[] {\n let previous: Rect | undefined;\n let first: number | undefined;\n const labels = slices.map((slice, i): SliceLabel | undefined => {\n if (slice.end - slice.start < LABEL_ANGLE - 1e-9) return undefined;\n const label = labelAt(frame, slice, measure);\n const { box } = label;\n if (box.x < 0 || box.y < 0 || box.x + box.width > frame.width || box.y + box.height > frame.height) return undefined;\n if (previous && overlaps(previous, box)) return undefined;\n previous = box;\n first ??= i;\n return label;\n });\n // Going round, the first label comes after the last: the later one gives way.\n for (let i = labels.length - 1; first !== undefined && i > first; i--) {\n const label = labels[i];\n if (!label) continue;\n if (!overlaps(labels[first]!.box, label.box)) break;\n labels[i] = undefined;\n }\n return labels;\n}\n\n/**\n * The centre's text, one line per \"\\n\", in the hole: the first line large (shrunk to fit the hole when\n * it's wide), the others below it. The lines are centred on the ring's centre together.\n */\nexport function placeCenter(frame: DonutFrame, text: string, measure: Measure): CenterLine[] {\n if (text === \"\") return [];\n const lines = text.split(\"\\n\");\n const room = 2 * frame.inner * 0.85;\n const width = measure(lines[0]!, \"ec-center-value\", CENTER_SIZE);\n const size = width > room && width > 0 ? Math.max(CENTER_MIN, (CENTER_SIZE * room) / width) : CENTER_SIZE;\n const offsets = lines.map((_, i) => (i === 0 ? 0 : CENTER_STEP + (i - 1) * CENTER_LINE));\n const last = offsets[offsets.length - 1]!;\n // The first line's cap height (about 0.72 em) down to the last line's baseline, centred.\n const top = frame.cy + (2 * CENTRE * size - last) / 2;\n return lines.map((line, i) => ({ x: frame.cx, y: top + offsets[i]!, anchor: \"middle\", text: line, size: i === 0 ? size : LABEL_SIZE }));\n}\n\ninterface Prepared<D> {\n readonly key: string;\n readonly category: string;\n readonly datum: D;\n readonly index: number;\n readonly value: number;\n}\n\nfunction prepareSlices<D>({ data, encoding }: DonutLayoutInput<D>): Prepared<D>[] {\n const keys = new Set<string>();\n return data.map((datum, index) => {\n const key = String(encoding.key(datum, index));\n if (keys.has(key)) throw new Error(`donutChart: two rows have the key \"${key}\". Keys must be unique; pass a key accessor if categories repeat.`);\n keys.add(key);\n const value = numberOf(encoding.value(datum, index), encoding.series, key);\n return { key, category: String(encoding.category(datum, index) ?? \"\"), datum, index, value };\n });\n}\n\nfunction sortSlices<D>(rows: Prepared<D>[], sort: DonutLayoutInput<D>[\"sort\"]): Prepared<D>[] {\n if (sort === undefined || sort === \"none\") return rows;\n // Array.prototype.sort is stable, so ties keep data order.\n if (sort === \"value\") return [...rows].sort((a, b) => b.value - a.value);\n throw new TypeError(`donutChart: sort must be \"value\" or \"none\", got ${String(sort)}.`);\n}\n\n/**\n * The ring is as large as the room left for labels allows, wherever they land: the widest label beside\n * it, and a label's height above and below it. So the ring keeps its size as values change. When that\n * leaves less than half the radius the chart could have, the ring takes half, and labels that don't\n * fit are dropped.\n */\nfunction donutFrame<D>(input: DonutLayoutInput<D>, rows: readonly Prepared<D>[]): DonutFrame {\n const { width, measure } = input;\n const height = input.height ?? HEIGHT;\n const cx = width / 2;\n const cy = height / 2;\n const share = measure(\"100%\", \"ec-value\", VALUE_SIZE);\n const widest = rows.reduce((max, row) => Math.max(max, measure(row.category, \"ec-label\", LABEL_SIZE)), share);\n const room = Math.min(cx - PAD - GAP - widest, cy - PAD - GAP - BLOCK);\n const most = Math.max(0, Math.min(cx, cy) - PAD);\n const outer = Math.max(0, room, most / 2);\n return { width, height, cx, cy, inner: outer * HOLE, outer };\n}\n\n/** A slice's label, placed at its middle angle. */\nfunction labelAt<D>(frame: DonutFrame, slice: SliceState<D>, measure: Measure): SliceLabel {\n const middle = (slice.start + slice.end) / 2;\n const sin = Math.sin(middle);\n const cos = Math.cos(middle);\n const r = frame.outer + GAP;\n const x = frame.cx + r * sin;\n const y = frame.cy - r * cos;\n const share = percent(slice.share);\n const widths = [measure(slice.category, \"ec-label\", LABEL_SIZE), measure(share, \"ec-value\", VALUE_SIZE)] as const;\n const width = Math.max(...widths);\n // Above the point at 12 o'clock, below it at 6, centred on it at 3 and 9.\n const top = y - (BLOCK * (cos + 1)) / 2;\n // Each line starts at the point at 3 o'clock, ends there at 9, and is centred on it at 12 and 6.\n const along = (w: number): number => x + (sin * w) / 2;\n return {\n category: { x: along(widths[0]), y: top + ASCENT, anchor: \"middle\", text: slice.category },\n share: { x: along(widths[1]), y: top + ASCENT + LINE, anchor: \"middle\", text: share },\n box: { x: along(width) - width / 2, y: top, width, height: BLOCK }\n };\n}\n\n/** The boxes of a label's two lines, leaving out a line with no text. */\nfunction labelBoxes(label: SliceLabel, measure: Measure): Rect[] {\n const out: Rect[] = [];\n if (label.category.text !== \"\") out.push(textBox(label.category, measure, \"ec-label\", LABEL_SIZE));\n if (label.share.text !== \"\") out.push(textBox(label.share, measure, \"ec-value\", VALUE_SIZE));\n return out;\n}\n\nfunction overlaps(a: Rect, b: Rect): boolean {\n return a.x < b.x + b.width + LABEL_SPACE && b.x < a.x + a.width + LABEL_SPACE && a.y < b.y + b.height + LABEL_SPACE && b.y < a.y + a.height + LABEL_SPACE;\n}\n\n/** Values along the walk, from 0 at the start to the slice's share at the end. Its own series is the only one related. */\nfunction sliceData<D>(datum: D, share: number, series: string): MarkData<D> {\n const data: MarkData<D> = {\n datum,\n samples: [\n { t: 0, value: 0 },\n { t: 1, value: share }\n ],\n related: (name) => (name === series ? data : undefined)\n };\n return data;\n}\n\nfunction accessor<D, T>(option: string | ((d: D, i: number) => T)): (d: D, i: number) => T {\n if (typeof option === \"function\") return option;\n return (d) => (d as Record<string, unknown>)[option] as T;\n}\n\n/** Missing values (null, undefined) count as 0; negative and non-finite ones throw. */\nfunction numberOf(value: unknown, series: string, key: string): number {\n if (value === null || value === undefined) return 0;\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) return value;\n throw new RangeError(\n `donutChart: \"${series}\" for \"${key}\" must be a finite number of 0 or more, got ${typeof value === \"string\" ? JSON.stringify(value) : String(value)}.`\n );\n}\n","// donutChart: the reference donut. Keyed slices described with describe.arc, from 12 o'clock and\n// clockwise, separated by strokes in the surface colour; labels outside the ring and the total in its\n// hole; a legend per category; built-in hover dimming; pointer, touch and keyboard hover with a\n// tooltip; a data table with each share and the total and, with `announce`, a live region for screen\n// readers. update() animates the values in data units, so every frame's angles are true shares:\n// staged in presentation (values, then slices turning to their new places), in one short stage in\n// analysis, at once when motion is off.\n//\n// The chart never names an effect: it resolves `on` through the presets it's handed and plays them\n// through the runner, which draws on the SVG surface. What doesn't depend on slices (events, hover and\n// focus, transitions and leaving marks, DOM order, size and fonts) is in shell/. The focus ring and\n// halos are drawn above the slices, masked to outside them (render/outside.ts), since slices touch.\n\nimport type { AnimateOptions, Animated, TweenResult } from \"../core\";\nimport { animated, defaultClock, interpolateNumber, interpolateRecord } from \"../core\";\nimport { resolveEffects } from \"../core/registry\";\nimport { report } from \"../core/report\";\nimport { createRunner, type RunInput } from \"../core/runner\";\nimport { chartAnnouncer, changeText, type Announcer } from \"./announce\";\nimport { toColorAssignment } from \"./colors\";\nimport { CENTER_SIZE, donutEncoding, layoutDonut, placeCenter, placeLabels, placeSlice, type CenterLine, type DonutFrame, type DonutLayout, type DonutSlice, type SliceLabel, type SliceState } from \"./donut-layout\";\nimport { chartLegend } from \"./legend\";\nimport { linkable } from \"./link\";\nimport { chartMotion } from \"./motion\";\nimport { svgMarkHandle, type StyledPart, type SvgMarkHandle } from \"./render/mark-style\";\nimport { maskedRing } from \"./render/outside\";\nimport { svgSurface } from \"./render/surface\";\nimport { setAttributes, setStyles, sizeAttributes, svgElement } from \"./render/svg\";\nimport { placeText, textMeasure } from \"./render/text\";\nimport { injectStyles, markColorStyles, seriesColors } from \"./render/theme\";\nimport { seriesLabel } from \"./series\";\nimport { chartEvents } from \"./shell/events\";\nimport { decimals, format, percent, round } from \"./shell/format\";\nimport { chartHover } from \"./shell/hover\";\nimport { chartLabel } from \"./shell/labels\";\nimport { leavingMarks, type Leave } from \"./shell/leaving\";\nimport { orderElements } from \"./shell/order\";\nimport { checkChartOptions, checkNeeds, containerWidth, describeChart, nextEffects, resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport { busy, chartTransitions, geometryChanged, playUpdate, same, sameFields, type ChartDiff } from \"./shell/transitions\";\nimport { watchFonts, watchHoverDuration, watchWidth } from \"./shell/watch\";\nimport { chartTable, tableModel, type TableModel } from \"./table\";\nimport { chartTooltip } from \"./tooltip\";\nimport type { Chart, DonutChartOptions } from \"./types\";\n\nexport type DonutChart<D> = Chart<D, DonutChartOptions<D>>;\n\ninterface SliceRecord<D> {\n readonly key: string;\n /** Where the slice is heading, or rests: its slice in the latest layout (its last one while it leaves). */\n row: DonutSlice<D>;\n /** What's on screen now. */\n shown: DonutSlice<D>;\n readonly group: SVGGElement;\n /** The pointer target, which stays put while an effect moves the slice. */\n readonly hit: SVGPathElement;\n /** Holds the slice; effects' transform and opacity go here. */\n readonly body: SVGGElement;\n readonly path: SVGPathElement;\n /** The label outside the ring: the category over the share. */\n readonly label: SVGTextElement;\n readonly share: SVGTextElement;\n /** Where the label is drawn now; undefined while it's dropped for room. */\n drawnLabel: SliceLabel | undefined;\n parts: StyledPart[];\n readonly handle: SvgMarkHandle;\n /** In data units, so every frame's angles are true shares. */\n readonly value: Animated<number>;\n /** 0 to 1: how far the slice has turned from where it was to its place in the ring. */\n readonly turn: Animated<number>;\n /** Where it turns from, in turns: its start in the order it turns from, plus this. */\n offset: number;\n /** How far it turns, in turns, at the targets: the shorter way, chosen once so it can't flip mid-turn. */\n planned: number;\n /** 0 to 1. A slice entering or leaving fades its label in or out. */\n readonly presence: Animated<number>;\n /** Set while the slice leaves. */\n leave: Leave | undefined;\n}\n\n/** What an update changed. A re-sort only turns a slice, and a new total only resizes it: its value didn't change. */\ntype Diff<D> = ChartDiff<SliceRecord<D>>;\n\n/** Base ms for each stage of a data change: values, then the turn to new places. Unstaged, a change takes as long as its stages together, which analysis scales down. */\nconst STAGE = 500;\nconst TAU = 2 * Math.PI;\n/** A walk shorter than this draws nothing, as effects treat it. */\nconst VISIBLE = 0.5;\n\nexport function donutChart<D>(target: string | Element, options: DonutChartOptions<D>, env: ChartEnv): DonutChart<D> {\n const container = resolveTarget(target, \"donutChart\");\n checkOptions(options);\n let current = options;\n const motion = chartMotion(options.motion, env.motion);\n let effects = resolveEffects(options.on, env.presets);\n let colors = toColorAssignment(options.colors);\n const clock = env.clock ?? defaultClock;\n const doc = container.ownerDocument;\n injectStyles(doc);\n\n // A named group of slices, each an image with its own name: see \"ARIA structure\" in docs/architecture.md.\n const svg = svgElement(\"svg\", { class: \"ec-chart ec-donut-chart\", role: \"group\" }, container);\n // Read through the chart's description instead.\n const center = svgElement(\"g\", { class: \"ec-center\", \"aria-hidden\": \"true\" }, svg);\n const marksLayer = svgElement(\"g\", { class: \"ec-marks\" }, svg);\n const overlay = svgElement(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" }, svg);\n // Above the slices, masked to outside the slice: slices touch, so anything behind one would hide\n // under its neighbour on one side.\n const halos = svgElement(\"g\", { class: \"ec-halos\" }, overlay);\n const focusRing = maskedRing(overlay);\n const runs = svgElement(\"g\", { class: \"ec-runs\" }, overlay);\n const measure = textMeasure(svg);\n\n /** Live slices, in the layout's order: clockwise from 12 o'clock. */\n let order: SliceRecord<D>[] = [];\n const records = new Map<string, SliceRecord<D>>();\n /** Slices on their way out: shrinking, or waiting for their exit effects. */\n const leaving = leavingMarks<SliceRecord<D>>((record) => record.value.animating || record.presence.animating);\n const byGroup = new WeakMap<Element, SliceRecord<D>>();\n const events = chartEvents<D>(\"donutChart\");\n let measuredWidth = containerWidth(container);\n let destroyed = false;\n\n let laidOut: DonutLayout<D>;\n let firstTable: TableModel | undefined;\n /** Each slice's accessible name, by key, for the latest layout. */\n let names: ReadonlyMap<string, string>;\n try {\n // Throws on data it can't draw, a table column it can't read, or a `format` that throws. Nothing\n // but the <svg> is in place yet (no listeners, observers or elements beside it), so that's all to undo.\n laidOut = layout(current);\n firstTable = tableFor(current, laidOut);\n // Last, so a markLabel that throws is reported only for a layout the chart draws.\n names = namesFor(current, laidOut);\n } catch (error) {\n svg.remove();\n throw error;\n }\n\n const find = (key: string): SliceRecord<D> | undefined => records.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay: runs,\n // Looked up on each call, so the handle follows the slice's record.\n mark: (key) => ({\n set: (style) => {\n find(key)?.handle.set(style);\n hover.restyled(key);\n },\n reset: () => {\n find(key)?.handle.reset();\n hover.restyled(key);\n }\n }),\n colors: (key) => find(key)?.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const tooltip = chartTooltip<D>(svg, { motion, option: () => current.tooltip, description: () => current.markDescription });\n const legend = chartLegend(svg);\n const table = chartTable(svg);\n let announcer: Announcer | undefined = current.announce ? chartAnnouncer(svg) : undefined;\n\n // ── Animated state ─────────────────────────────────────────────────────────\n // Each slice has its value, how far it has turned and its presence, and the chart has the frame, so\n // a new update() mid-flight retargets each from where it is and nothing jumps. Where a slice is comes\n // from them: the slices in `ring` are laid end to end from their values, and a slice still turning\n // is part way from its start in `from` (plus its offset) to its start in `ring`.\n\n /** Every slice drawn, live and leaving, in the order they're joined in: the layout's, with leaving slices kept where they were. */\n let ring: SliceRecord<D>[] = [];\n /** The order slices turn from: where they were joined before the latest change. */\n let from: SliceRecord<D>[] = [];\n /** Something moved since the last frame was drawn. Every slice's angles depend on every value, so a frame draws them all. */\n let dirty = false;\n const frame = animated(laidOut.frame, interpolateRecord, { clock, motion, onChange: () => (dirty = true) });\n /** The centre's total counts between totals, rounded to this many decimals; undefined shows the layout's text. */\n let count: number | undefined;\n /** The centre's text for the total last shown while counting. */\n let counted: { readonly total: number; readonly text: string } | undefined;\n\n const transitions = chartTransitions({ clock, runner, leaving, draw, land });\n\n // ── Drawing ────────────────────────────────────────────────────────────────\n\n function layout(opts: DonutChartOptions<D>, using = effects): DonutLayout<D> {\n const encoding = donutEncoding(opts);\n checkNeeds(using, [encoding.series], \"donutChart\");\n return layoutDonut({\n data: opts.data,\n encoding,\n sort: opts.sort,\n width: opts.width ?? measuredWidth,\n height: opts.height,\n center: (total) => centerText(opts, encoding.series, total),\n measure\n });\n }\n\n /** A new slice, drawn when it's first shown. One that enters grows from nothing. */\n function createRecord(row: DonutSlice<D>, entering: boolean): SliceRecord<D> {\n // An image: its aria-label says it all, and its text and shapes aren't read on their own.\n const group = svgElement(\"g\", { class: \"ec-mark\", \"data-key\": row.key, role: \"img\" }, marksLayer);\n const env = { clock, motion, onChange: () => (dirty = true) };\n const body = svgElement(\"g\", { class: \"ec-body\" }, group);\n const record: SliceRecord<D> = {\n key: row.key,\n row,\n shown: row,\n group,\n hit: svgElement(\"path\", { class: \"ec-hit\" }, group),\n body,\n path: svgElement(\"path\", { class: \"ec-slice\", \"data-series\": row.series }, body),\n label: svgElement(\"text\", { class: \"ec-label\", \"aria-hidden\": \"true\" }, group),\n share: svgElement(\"text\", { class: \"ec-value\", \"aria-hidden\": \"true\" }, group),\n drawnLabel: undefined,\n parts: [],\n handle: svgMarkHandle(() => record, { halos: () => halos }),\n value: animated(entering ? 0 : row.value, interpolateNumber, env),\n turn: animated(1, interpolateNumber, env),\n offset: 0,\n planned: 0,\n presence: animated(entering ? 0 : 1, interpolateNumber, env),\n leave: undefined\n };\n // The pointer target first, under the slice.\n group.insertBefore(record.hit, body);\n byGroup.set(group, record);\n return record;\n }\n\n /** Draws the slice as `slice`, with its label outside the ring or none. */\n function drawMark(record: SliceRecord<D>, slice: DonutSlice<D>, label: SliceLabel | undefined): void {\n const before = record.parts[0]?.colors.color;\n record.shown = slice;\n const { outline } = slice.geometry;\n // A slice with no angle draws nothing: not even its separator.\n const visible = slice.geometry.length >= VISIBLE;\n const hidden = visible ? undefined : \"hidden\";\n setAttributes(record.path, { d: outline.d, visibility: hidden });\n setAttributes(record.hit, { d: outline.d, visibility: hidden });\n const sliceColors = seriesColors(colors.slot(record.key));\n setStyles(record.path, markColorStyles(sliceColors));\n record.parts = [{ element: record.path, d: outline.d, colors: sliceColors, visible }];\n const presence = record.presence.value;\n const opacity = presence < 1 ? presence : undefined;\n record.drawnLabel = label;\n for (const [text, placement] of [\n [record.label, label?.category],\n [record.share, label?.share]\n ] as const) {\n if (placement) placeText(text, placement);\n setAttributes(text, { visibility: placement ? undefined : \"hidden\", opacity });\n }\n record.handle.repaint();\n // A new palette: overlays already drawn in \"mark\" follow.\n if (sliceColors.color !== before) surface.recolor(record.key);\n if (record.key === hover.ringKey) drawRing(record.key);\n }\n\n /** The focus ring follows the slice's outline as it is on screen, moved with its body when an effect moves it. */\n function drawRing(key: string | undefined): void {\n const record = key === undefined ? undefined : records.get(key);\n focusRing.draw(record && { outline: record.shown.geometry.outline, thickness: record.shown.geometry.thickness, transform: record.handle.style.transform });\n }\n\n /**\n * Draws the slice as `slice`. Its runs hear about it when its geometry or its row changed, so\n * decorations follow: a label from a field the slice doesn't plot too.\n */\n function show(record: SliceRecord<D>, slice: DonutSlice<D>, label: SliceLabel | undefined): void {\n const moved = geometryChanged(record.shown.geometry, slice.geometry) || record.shown.datum !== slice.datum;\n drawMark(record, slice, label);\n if (moved) runner.change(slice.geometry, slice.data);\n if (record.key === hover.key) showTooltip(record);\n }\n\n /** The tooltip beside the hovered slice as it is on screen, moved with its effects, with the text for where it's heading. */\n function showTooltip(record: SliceRecord<D>): void {\n const { row } = record;\n tooltip.show(record.shown.geometry, row, () => ({ title: row.category, lines: [`${valueText(row, current)} · ${percent(row.share)}`] }), record.handle.style.transform);\n }\n\n /** The text in the hole, a line per <text>: the first large. */\n function drawCenter(lines: readonly CenterLine[]): void {\n while (center.childElementCount > lines.length) center.lastElementChild!.remove();\n lines.forEach((line, i) => {\n const text = (center.children[i] as SVGTextElement | undefined) ?? svgElement(\"text\", {}, center);\n setAttributes(text, { class: i === 0 ? \"ec-center-value\" : \"ec-center-label\" });\n placeText(text, line);\n // Shrunk to fit the hole; otherwise the stylesheet's size.\n setStyles(text, { \"font-size\": i === 0 && line.size !== CENTER_SIZE ? `${line.size}px` : undefined });\n });\n }\n\n const syncLegend = (): void =>\n legend.categories(\n laidOut.slices.map((slice) => ({ key: slice.key, label: slice.category })),\n colors,\n current.legend\n );\n\n /** The data table for `opts`, laid out as `next`: its rows in the slices' order, each share, and the total. Throws on a column it can't read. */\n function tableFor(opts: DonutChartOptions<D>, next: DonutLayout<D>): TableModel | undefined {\n const { series } = donutEncoding(opts);\n return tableModel({\n option: opts.table,\n caption: opts.label,\n category: typeof opts.category === \"string\" ? opts.category : undefined,\n series: [series],\n label: (name) => seriesLabel(opts.seriesLabels, name),\n rows: next.slices.map((slice) => ({ key: slice.key, category: slice.category, datum: slice.datum, index: slice.index, values: [{ series, value: slice.value }], total: slice.value })),\n format: format(opts),\n shares: true\n });\n }\n\n /** The chart's description: its own, then the centre's text, so the total is heard on entering the chart. */\n function describeDonut(): void {\n describeChart(svg, { label: current.label, description: description(current.description, laidOut.centerText) });\n }\n\n /** Says what an update changed, in the live region: the chart's summary, or the page's text from it. */\n function announceChange(previous: DonutChartOptions<D>, diff: Diff<D>): void {\n const option = current.announce;\n if (!announcer || !option) return;\n const series = donutEncoding(current).series;\n const before = donutEncoding(previous).series;\n const sort = current.sort ?? \"none\";\n const name = (record: SliceRecord<D>): string => record.row.category;\n const changed = diff.changed.map(({ record }) => record);\n const text = changeText({\n ...(current.label !== previous.label ? { label: current.label } : {}),\n // A new series is said by its label; a new label alone shows the same view, so say nothing.\n ...(series !== before ? { series: [seriesLabel(current.seriesLabels, series)] } : {}),\n ...(sort !== (previous.sort ?? \"none\") ? { sort } : {}),\n changed: changed.map(name),\n added: diff.entering.map(name),\n removed: diff.exiting.map(name),\n count: order.length\n });\n if (typeof option !== \"function\") {\n announcer.say(text);\n return;\n }\n const key = (record: SliceRecord<D>): string => record.key;\n try {\n const said = option({ text, changed: changed.map(key), added: diff.entering.map(key), removed: diff.exiting.map(key) });\n if (said !== undefined && said !== null) announcer.say(String(said));\n } catch (error) {\n report(error);\n }\n }\n\n /** On screen: live, or leaving and not yet gone. */\n const drawn = (record: SliceRecord<D>): boolean => records.get(record.key) === record || leaving.get(record.key) === record;\n const valueOf = (record: SliceRecord<D>): number => Math.max(0, record.value.value);\n\n /** Each slice's start, in turns, laid end to end from 12 o'clock in the order given, as shares of `total`. */\n function startsIn(slices: readonly SliceRecord<D>[], total: number, value = valueOf): Map<SliceRecord<D>, number> {\n const starts = new Map<SliceRecord<D>, number>();\n let before = 0;\n for (const record of slices) {\n starts.set(record, total > 0 ? before / total : 0);\n before += value(record);\n }\n return starts;\n }\n\n /** Where every slice drawn is now, in turns: its start, and its span (its true share). */\n function angles(): Map<SliceRecord<D>, { readonly start: number; readonly span: number }> {\n ring = ring.filter(drawn);\n from = from.filter(drawn);\n const total = ring.reduce((sum, record) => sum + valueOf(record), 0);\n const to = startsIn(ring, total);\n const was = startsIn(from, total);\n const out = new Map<SliceRecord<D>, { readonly start: number; readonly span: number }>();\n for (const record of ring) {\n const start = to.get(record)!;\n const turned = record.turn.value;\n const origin = was.get(record);\n let at = start;\n if (origin !== undefined && turned < 1) {\n // The way it has to go now, kept to the side it set off on.\n const raw = origin + record.offset - start;\n at = start + (1 - turned) * (raw - Math.round(raw - record.planned));\n }\n out.set(record, { start: at, span: total > 0 ? valueOf(record) / total : 0 });\n }\n return out;\n }\n\n /** Every slice as it is now, part way through a transition, in the ring's order, with its label or none. */\n function currentSlices(f: DonutFrame): { readonly record: SliceRecord<D>; readonly slice: DonutSlice<D>; readonly label: SliceLabel | undefined }[] {\n const now = [...angles()].map(([record, { start, span }]) => {\n const { row } = record;\n const state: SliceState<D> = {\n key: row.key,\n datum: row.datum,\n index: row.index,\n category: row.category,\n series: row.series,\n value: valueOf(record),\n share: span,\n start: start * TAU,\n end: (start + span) * TAU\n };\n return { record, state };\n });\n const labels = placeLabels(\n f,\n now.map(({ state }) => state),\n measure\n );\n return now.map(({ record, state }, i) => ({ record, slice: placeSlice(f, state, labels[i], measure), label: labels[i] }));\n }\n\n /** Draws every slice as it is now, its label, and the total counting in the hole. */\n function draw(): void {\n if (!dirty) return;\n dirty = false;\n const f = frame.value;\n setAttributes(svg, sizeAttributes(f));\n const slices = currentSlices(f);\n for (const { record, slice, label } of slices) show(record, slice, label);\n const total = slices.reduce((sum, { slice }) => sum + slice.value, 0);\n drawCenter(placeCenter(f, count === undefined ? laidOut.centerText : counting(round(total, count)), measure));\n }\n\n /** The centre's text for a total on its way to the layout's, worked out once per total shown. */\n function counting(total: number): string {\n if (counted?.total !== total) counted = { total, text: centerText(current, donutEncoding(current).series, total) };\n return counted.text;\n }\n\n /** Draws exactly the layout once a transition settles: the frames in between are computed, this is laid out. */\n function land(): void {\n ring = ring.filter(drawn);\n from = ring;\n for (const record of ring) {\n record.turn.set(1);\n record.offset = 0;\n record.planned = 0;\n }\n count = undefined;\n counted = undefined;\n setAttributes(svg, sizeAttributes(laidOut.frame));\n laidOut.slices.forEach((slice, i) => show(records.get(slice.key)!, slice, laidOut.labels[i]));\n drawCenter(laidOut.center);\n dirty = false;\n }\n\n /** Matches the layout's slices to records by key. New slices start with nothing showing; slices without one start to leave. */\n function arrange(next: DonutLayout<D>): Diff<D> {\n const keys = new Set(next.slices.map((slice) => slice.key));\n const diff: Diff<D> = { entering: [], exiting: [], changed: [] };\n for (const record of order) {\n if (keys.has(record.key)) continue;\n records.delete(record.key);\n leaving.start(record);\n diff.exiting.push(record);\n }\n const previous = order;\n order = next.slices.map((slice) => {\n let record = records.get(slice.key);\n if (record) {\n // Its own value: a share that moved because others changed isn't an update.\n if (record.row.value !== slice.value || record.row.series !== slice.series) diff.changed.push({ record, from: record.shown.geometry });\n } else {\n // A slice that comes back mid-exit keeps its element; the runner cancels its exit.\n record = leaving.recall(slice.key) ?? createRecord(slice, true);\n records.set(slice.key, record);\n diff.entering.push(record);\n }\n record.row = slice;\n record.path.setAttribute(\"data-series\", slice.series);\n labelMark(record);\n return record;\n });\n // DOM order follows visual order, for screen readers.\n orderElements(\n marksLayer,\n previous.map((record) => record.group),\n order.map((record) => record.group),\n hover.active\n );\n return diff;\n }\n\n /** The slice's accessible name, from where it's heading, and its description (`markDescription`, or a tooltip function's text). */\n function labelMark(record: SliceRecord<D>): void {\n record.group.setAttribute(\"aria-label\", names.get(record.key)!);\n tooltip.describe(record.group, record.row);\n }\n\n /**\n * Sends every animated value toward `next`, and returns the animations started. Presentation stages\n * the change: values first (slices resize, staying joined in the order they're in, and leaving slices\n * shrink to nothing), then the turn (slices turn the shorter way to their places in the new order,\n * the ring resizes, and new slices grow in at their places in the second half). A stage with nothing\n * to do is skipped. Analysis runs it all as one stage, which its scaling keeps short. A jump (motion\n * off, a resize) lands at once.\n */\n function retarget(next: DonutLayout<D>, jump: boolean): Promise<TweenResult>[] {\n dirty = true;\n // Where every slice is now, before the orders change, so nothing jumps.\n const now = angles();\n // New slices, and ones back after fading out completely, grow in at their places.\n const arriving = new Set(order.filter((record) => record.presence.value === 0));\n const staying = order.filter((record) => !arriving.has(record));\n const gone = [...leaving.values()];\n\n // Still joined in `from` and not turning yet (stopped in the values stage): they go on from there.\n // Otherwise they turn from the ring they're in, each from where it is now.\n const waiting = from.length > 0 && from.every((record) => record.turn.value === 0);\n const before = ring;\n ring = mergeRing(before, order);\n if (!waiting) {\n from = before;\n const total = before.reduce((sum, record) => sum + valueOf(record), 0);\n const joined = startsIn(before, total);\n for (const record of before) record.offset = now.get(record)!.start - joined.get(record)!;\n }\n from = from.filter((record) => !arriving.has(record));\n\n // The shorter way round, at the targets: where it's heading in the ring against where it turns from.\n const target = (record: SliceRecord<D>): number => (records.get(record.key) === record ? record.row.value : 0);\n const total = ring.reduce((sum, record) => sum + target(record), 0);\n const ends = startsIn(ring, total, target);\n const starts = startsIn(from, total, target);\n let turns = false;\n for (const record of from) {\n const raw = starts.get(record)! + record.offset - ends.get(record)!;\n record.planned = raw - Math.round(raw);\n if (Math.abs(record.planned) > 1e-9) turns = true;\n }\n\n const values =\n staying.some((record) => busy(record.value, record.row.value, same) || busy(record.presence, 1, same)) ||\n gone.some((record) => busy(record.value, 0, same) || busy(record.presence, 0, same));\n const positions = turns || arriving.size > 0 || busy(frame, next.frame, sameFields);\n\n let first: AnimateOptions | undefined;\n let second: AnimateOptions | undefined;\n let grow: AnimateOptions | undefined;\n if (!jump && motion.staged) {\n const wait = values ? STAGE : 0;\n first = { duration: STAGE };\n second = { duration: STAGE, delay: wait };\n grow = { duration: STAGE / 2, delay: wait + STAGE / 2 };\n } else if (!jump) {\n first = second = grow = { duration: (values && positions ? 2 : 1) * STAGE };\n }\n\n const running: Promise<TweenResult>[] = [];\n const move = <T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean, timing: AnimateOptions | undefined): void => {\n if (!busy(value, to, equal)) return;\n if (timing) running.push(value.to(to, timing));\n else value.set(to);\n };\n move(frame, next.frame, sameFields, second);\n for (const record of staying) {\n move(record.value, record.row.value, same, first);\n move(record.presence, 1, same, first);\n }\n for (const record of arriving) {\n move(record.value, record.row.value, same, grow);\n move(record.presence, 1, same, grow);\n }\n for (const record of gone) {\n move(record.value, 0, same, first);\n move(record.presence, 0, same, first);\n }\n if (jump) {\n from = ring;\n for (const record of ring) {\n record.turn.set(1);\n record.offset = 0;\n record.planned = 0;\n }\n return running;\n }\n // Joined where they were until their turn starts.\n const turning = new Set(from);\n for (const record of ring) record.turn.set(turning.has(record) ? 0 : 1);\n if (turns) for (const record of from) move(record.turn, 1, same, second);\n return running;\n }\n\n /**\n * Moves to `next`, animated or at once, drawing every frame. Resolves when the transition settles.\n * One still in flight is taken over: its waiters wait for this one instead.\n */\n function transitionTo(next: DonutLayout<D>, jump: boolean): Promise<void> {\n laidOut = next;\n return transitions.run(retarget(next, jump));\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /** Where a slice is heading: what enter and update report as a change starts. */\n const input = (record: SliceRecord<D>): RunInput<D> => ({ mark: record.row.geometry, data: record.row.data });\n /** The slice as it is on screen: what hover, leave and exit report, so mid-change they match what's under the pointer or on its way out. */\n const onScreen = (record: SliceRecord<D>): RunInput<D> => ({ mark: record.shown.geometry, data: record.shown.data });\n\n /** The slice an event target belongs to (its label too); leaving slices don't count. */\n function liveRecordOf(eventTarget: EventTarget | null): SliceRecord<D> | undefined {\n const element = eventTarget as Element | null;\n const group = typeof element?.closest === \"function\" ? element.closest(\".ec-mark\") : null;\n const record = group ? byGroup.get(group) : undefined;\n return record && records.get(record.key) === record ? record : undefined;\n }\n\n // Pointer, touch and keyboard focus share one hover: see shell/hover.ts. A slice is its own target,\n // so a hover event has no segment.\n const hover = chartHover<D>({\n svg,\n runner,\n events,\n dim: () => current.dim !== false,\n find(eventTarget) {\n const record = liveRecordOf(eventTarget);\n return record && { key: record.key };\n },\n live: (key) => records.has(key),\n order: () => order.map((record) => record.key),\n element: (key) => find(key)?.group,\n onScreen(key) {\n const record = find(key);\n return record && onScreen(record);\n },\n ring: drawRing,\n tooltip: {\n show(key) {\n const record = records.get(key);\n if (record) showTooltip(record);\n },\n hide: () => tooltip.hide(),\n element: () => tooltip.element()\n }\n });\n\n // ── Motion, size and fonts ─────────────────────────────────────────────────\n\n const unwatchHoverDuration = watchHoverDuration(svg, motion);\n\n /** Re-lays out without animating: a resize or fonts loading. A transition in flight lands at once. Effects follow through change(). */\n function relayout(): void {\n if (destroyed) return;\n const next = layout(current);\n // The same slices as now: only the sizes changed.\n const slices = new Map(next.slices.map((slice) => [slice.key, slice]));\n for (const record of order) record.row = slices.get(record.key) ?? record.row;\n void transitionTo(next, true);\n }\n\n const unwatchWidth = watchWidth(container, clock, measuredWidth, (width) => {\n measuredWidth = width;\n // A fixed `width` ignores the container.\n if (current.width === undefined) relayout();\n });\n\n // Labels' room is measured; measure again once web fonts arrive.\n const unwatchFonts = watchFonts(doc, () => {\n measure.clear();\n relayout();\n });\n\n // ── First render ───────────────────────────────────────────────────────────\n\n describeDonut();\n syncLegend();\n table.render(firstTable);\n setAttributes(svg, sizeAttributes(laidOut.frame));\n order = laidOut.slices.map((slice) => {\n const record = createRecord(slice, false);\n records.set(slice.key, record);\n labelMark(record);\n return record;\n });\n ring = from = order;\n laidOut.slices.forEach((slice, i) => drawMark(order[i]!, slice, laidOut.labels[i]));\n drawCenter(laidOut.center);\n hover.sync();\n runner.enter(order.map(input));\n\n return linkable(hover.link, {\n element: svg,\n\n async update(next) {\n if (destroyed) return;\n if (next.motion !== undefined && next.motion !== current.motion) throw new TypeError(\"donutChart: `motion` can't be changed by update() yet.\");\n const merged: DonutChartOptions<D> = { ...current, ...next };\n checkOptions(merged);\n // Throws on an effect it can't resolve, data it can't draw, a table column it can't read, or a\n // `format` that throws, before anything changes.\n const swapped = \"on\" in next ? nextEffects(effects, current.on, merged.on, env.presets) : effects;\n const nextLayout = layout(merged, swapped);\n const nextTable = tableFor(merged, nextLayout);\n const nextNames = namesFor(merged, nextLayout);\n if (\"colors\" in next) colors = toColorAssignment(merged.colors);\n const previous = current;\n const totalBefore = laidOut.total;\n current = merged;\n laidOut = nextLayout;\n names = nextNames;\n describeDonut();\n syncLegend();\n table.render(nextTable);\n // A region that appears with its first text is often missed: it announces from the next update.\n const announcing = announcer !== undefined;\n if (current.announce && !announcer) announcer = chartAnnouncer(svg);\n else if (!current.announce && announcer) {\n announcer.destroy();\n announcer = undefined;\n }\n hover.syncDim();\n transitions.supersede();\n const swapping = swapped !== effects;\n effects = swapped;\n\n // The runner hears exit / update / enter now, then change() on every frame, then settle(). New\n // effects start where the old ones were, on the slices staying, as this update leaves them; a\n // held hover replays with them once the change settles.\n const leaves = playUpdate(\n {\n runner,\n events,\n hover,\n leaving,\n input,\n onScreen,\n data: \"data\" in next,\n ...(swapping\n ? {\n swap: (diff: Diff<D>) => {\n const entering = new Set(diff.entering);\n runner.swap(swapped, order.filter((record) => !entering.has(record)).map(input));\n }\n }\n : {})\n },\n () => arrange(nextLayout),\n (diff) => {\n if (announcing) announceChange(previous, diff);\n }\n );\n count = nextLayout.total === totalBefore ? undefined : Math.max(decimals(totalBefore), decimals(nextLayout.total));\n const settled = transitionTo(nextLayout, motion.mode === \"off\");\n await transitions.wait(settled, leaves);\n },\n\n on: events.on,\n\n marks: () => order.map((record) => record.shown.geometry),\n\n focus(key) {\n if (!destroyed) hover.focus(key);\n },\n\n leave() {\n if (!destroyed) hover.leave();\n },\n\n // Outside the ring, the category over the share; the centre's text isn't a slice's.\n labels: () =>\n order.flatMap((record) => [\n ...chartLabel(record.key, \"category\", record.drawnLabel?.category, record.label),\n ...chartLabel(record.key, \"value\", record.drawnLabel?.share, record.share)\n ]),\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n // Ends the transition in flight, and resolves the latest update()'s promise.\n transitions.destroy();\n hover.destroy();\n runner.destroy();\n tooltip.destroy();\n legend.destroy();\n table.destroy();\n announcer?.destroy();\n unwatchHoverDuration();\n unwatchWidth();\n unwatchFonts();\n for (const record of [...order, ...leaving.values()]) {\n for (const value of [record.value, record.turn, record.presence]) value.stop();\n record.leave?.resolve();\n }\n frame.stop();\n events.clear();\n records.clear();\n leaving.clear();\n order = ring = from = [];\n svg.remove();\n }\n });\n}\n\nfunction checkOptions<D>(options: DonutChartOptions<D>): void {\n checkChartOptions(options, \"donutChart\");\n const { center, sort } = options;\n if (center !== undefined && center !== false && typeof center !== \"function\") throw new TypeError(\"donutChart: center must be false or a function that returns the text for the total.\");\n if (sort !== undefined && sort !== \"none\" && sort !== \"value\") throw new TypeError(`donutChart: sort must be \"value\" or \"none\", got ${String(sort)}.`);\n}\n\n/** The value in `format` with its series' label: \"112 shots\". A lone value read by a function goes unnamed unless it's labelled: \"112\". */\nfunction valueText<D>(slice: DonutSlice<D>, options: DonutChartOptions<D>): string {\n const formatted = format(options)(slice.value);\n const label = seriesLabel(options.seriesLabels, slice.series);\n return slice.series === \"value\" && label === \"value\" ? formatted : `${formatted} ${label}`;\n}\n\n/**\n * Every slice's name in `layout`, by key. Worked out before anything changes, since `format` may\n * first run here: with no table and no centre text, nothing else calls it.\n */\nfunction namesFor<D>(options: DonutChartOptions<D>, layout: DonutLayout<D>): ReadonlyMap<string, string> {\n return new Map(layout.slices.map((slice) => [slice.key, markLabel(slice, options)]));\n}\n\n/**\n * \"Saved: 112 shots, 28%\", the value said with its series' label, or the page's wording from\n * `markLabel`. An empty name, or a throw (reported), keeps the default, so a focusable slice is never\n * left unnamed.\n */\nfunction markLabel<D>(slice: DonutSlice<D>, options: DonutChartOptions<D>): string {\n const text = `${slice.category}: ${valueText(slice, options)}, ${percent(slice.share)}`;\n if (!options.markLabel) return text;\n try {\n const value = { series: slice.series, label: seriesLabel(options.seriesLabels, slice.series), value: slice.value };\n const named: unknown = options.markLabel(slice.datum, {\n key: slice.key,\n category: slice.category,\n values: [value],\n total: slice.value,\n share: slice.share,\n format: format(options),\n text\n });\n if (named !== undefined && named !== null && String(named).trim() !== \"\") return String(named);\n } catch (error) {\n report(error);\n }\n return text;\n}\n\n/**\n * The text in the hole for a total: `center`'s, or by default the total in `format` over the value's\n * series label (\"406\" over \"shots\"; the total alone for an unlabelled value read by a function). \"\"\n * for none, with `center: false`, and when the function throws (reported).\n */\nfunction centerText<D>(options: DonutChartOptions<D>, series: string, total: number): string {\n const { center } = options;\n const formatted = format(options);\n if (center === false) return \"\";\n if (center === undefined) {\n const label = seriesLabel(options.seriesLabels, series);\n return series === \"value\" && label === \"value\" ? formatted(total) : `${formatted(total)}\\n${label}`;\n }\n try {\n const text: unknown = center(total, formatted);\n return text === undefined || text === null ? \"\" : String(text);\n } catch (error) {\n report(error);\n return \"\";\n }\n}\n\n/** The chart's own description, then the centre's text on one line. */\nfunction description(own: string | undefined, center: string): string | undefined {\n const text = center.split(\"\\n\").join(\" \").trim();\n const mine = own?.trim();\n if (text === \"\") return own;\n if (!mine) return text;\n return /[.!?:;]$/.test(mine) ? `${mine} ${text}` : `${mine}. ${text}`;\n}\n\n/**\n * The ring's order: the layout's, with slices on their way out kept where they were, just after the\n * slice they followed, or first. So a leaving slice shrinks in place.\n */\nfunction mergeRing<R>(shown: readonly R[], next: readonly R[]): R[] {\n const out = [...next];\n shown.forEach((record, i) => {\n if (out.includes(record)) return;\n let at = 0;\n for (let j = i - 1; j >= 0; j--) {\n const found = out.indexOf(shown[j]!);\n if (found >= 0) {\n at = found + 1;\n break;\n }\n }\n out.splice(at, 0, record);\n });\n return out;\n}\n","// Time on the line chart's x: the steps between ticks, where ticks fall, and how a time is worded.\n// Pure, and with no dependency: boundaries are found with Date's own UTC or local getters and setters,\n// which handle daylight saving, and times are worded through Intl.DateTimeFormat in the page's locale.\n// A time is in ms, as Date.getTime() gives it.\n\nimport { niceStep } from \"./bar-layout\";\n\n/** The zone a time axis is in: UTC, or the viewer's clock. Named as Intl's option is, so IANA names can join it. */\nexport type TimeZone = \"UTC\" | \"local\";\n\nexport const TIME_ZONES: readonly TimeZone[] = [\"UTC\", \"local\"];\n\n/** How fine a time is: the coarsest boundary it falls on in its zone. Midnight on 1 January is a year. */\nexport type TimeLevel = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\" | \"millisecond\";\n\ntype Unit = \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n\n/** A step between ticks: `count` of a unit, on that unit's boundaries. */\nexport interface TimeStep {\n readonly unit: Unit;\n readonly count: number;\n}\n\n/** An x tick on a time axis: where it is, and its text. */\nexport interface TimeTick {\n readonly value: number;\n readonly text: string;\n}\n\nconst SECOND = 1000;\nconst MINUTE = 60 * SECOND;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/**\n * Each unit at its longest, for choosing a step (never for placing a tick): a day of 25 hours when\n * the clocks go back, a month of 31 days, a year of 366. So a range of whole months or years gets\n * the step that fits it, whatever its leap days and clock changes.\n */\nconst LONGEST: Readonly<Record<Unit, number>> = { second: SECOND, minute: MINUTE, hour: HOUR, day: DAY + HOUR, week: 7 * DAY + HOUR, month: 31 * DAY, year: 366 * DAY };\n\n/** The steps shorter than a year, in order. Years go on in the number axis's nice steps. */\nconst STEPS: readonly TimeStep[] = [\n ...[1, 5, 15, 30].map((count) => ({ unit: \"second\" as const, count })),\n ...[1, 5, 15, 30].map((count) => ({ unit: \"minute\" as const, count })),\n ...[1, 3, 6, 12].map((count) => ({ unit: \"hour\" as const, count })),\n { unit: \"day\", count: 1 },\n { unit: \"day\", count: 2 },\n { unit: \"week\", count: 1 },\n { unit: \"month\", count: 1 },\n { unit: \"month\", count: 3 }\n];\n\n/** From the coarsest. */\nconst LEVELS: readonly TimeLevel[] = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n/** The level a step's boundaries are at, at least: a week starts on a day. */\nconst UNIT_LEVEL: Readonly<Record<Unit, TimeLevel>> = { second: \"second\", minute: \"minute\", hour: \"hour\", day: \"day\", week: \"day\", month: \"month\", year: \"year\" };\n\n/** Milliseconds, as a fraction of a second (\"1:00:00.100 PM\"). ES2021's option, so it isn't in this build's lib. */\nconst FRACTION = { fractionalSecondDigits: 3 } as Intl.DateTimeFormatOptions;\n\n/** What a time at each level says: the year on a year, the month on a month (\"Feb\"), the day on a day (\"Feb 8\"), the time within a day. */\nconst FIELDS: Readonly<Record<TimeLevel, Intl.DateTimeFormatOptions>> = {\n year: { year: \"numeric\" },\n month: { month: \"short\" },\n day: { month: \"short\", day: \"numeric\" },\n hour: { hour: \"numeric\", minute: \"2-digit\" },\n minute: { hour: \"numeric\", minute: \"2-digit\" },\n second: { hour: \"numeric\", minute: \"2-digit\", second: \"2-digit\" },\n millisecond: { hour: \"numeric\", minute: \"2-digit\", second: \"2-digit\", ...FRACTION }\n};\n\n/** The smallest step that can be `span` ms long, as the number axis rounds its step up. */\nexport function timeStep(span: number): TimeStep {\n for (const step of STEPS) if (LONGEST[step.unit] * step.count >= span) return step;\n return { unit: \"year\", count: Math.max(1, niceStep(span / LONGEST.year)) };\n}\n\n/**\n * The x ticks for times from `lo` to `hi`: both ends, and the boundaries strictly between them at a\n * step of about a quarter of the range (the smallest that can be that long, as on a number axis), each\n * on its boundary in the zone (a day at midnight, a month on its first). Each is worded for its own\n * level: \"2026\", \"Feb\", \"Feb 8\" (\"8 Feb\" in en-GB), \"3:00 PM\". The ends needn't be on a boundary, so\n * each also says the levels up to the step's and up to the coarsest the axis crosses, to be placed\n * even when the ticks between are dropped for room: \"Jan 5, 2026\" on an axis of years, or of months\n * into the next year; \"Feb 5, 3:00 PM\" on one of hours past midnight. A lone time says everything up\n * to its year.\n */\nexport function timeTicks(lo: number, hi: number, zone: TimeZone): TimeTick[] {\n const word = tickWording(zone);\n if (!(hi > lo)) return [{ value: lo, text: word(lo, \"year\") }];\n const step = timeStep((hi - lo) / 4);\n const ends = LEVELS[Math.min(LEVELS.indexOf(UNIT_LEVEL[step.unit]), LEVELS.indexOf(crossed(lo, hi, zone)))]!;\n const between = boundaries(lo, hi, step, zone).map((value) => ({ value, text: word(value, \"millisecond\") }));\n return [{ value: lo, text: word(lo, ends) }, ...between, { value: hi, text: word(hi, ends) }];\n}\n\n/** The coarsest boundary between `lo` and `hi`: the first of their fields that differs, from the year down. */\nfunction crossed(lo: number, hi: number, zone: TimeZone): TimeLevel {\n const [a, b] = [partsOf(lo, zone), partsOf(hi, zone)];\n if (a.year !== b.year) return \"year\";\n if (a.month !== b.month) return \"month\";\n if (a.date !== b.date) return \"day\";\n if (a.hours !== b.hours) return \"hour\";\n return a.minutes !== b.minutes ? \"minute\" : \"second\";\n}\n\n/** The step's boundaries strictly between `lo` and `hi`, in the zone, in order. */\nexport function boundaries(lo: number, hi: number, step: TimeStep, zone: TimeZone): number[] {\n const { unit, count } = step;\n const out: number[] = [];\n const start = partsOf(lo, zone);\n if (unit === \"second\" || unit === \"minute\" || unit === \"hour\") {\n // Whole units by the zone's clock, found by stepping through elapsed time and kept where the clock\n // shows a whole unit whose field is a multiple of `count`: an hour the clocks repeat has a tick each\n // time, and one they skip has none. Hours are stepped a quarter of an hour at a time, since clocks\n // change by whole quarter hours (Lord Howe Island's by half an hour), so a tick after the change is\n // still on the hour.\n const grain = unit === \"hour\" ? 15 * MINUTE : LONGEST[unit];\n let t = lo - start.ms - (unit === \"second\" ? 0 : start.seconds * SECOND) - (unit === \"hour\" ? (start.minutes % 15) * MINUTE : 0);\n for (; t < hi; t += grain) {\n const parts = partsOf(t, zone);\n const whole = unit !== \"hour\" || parts.minutes === 0;\n const field = unit === \"second\" ? parts.seconds : unit === \"minute\" ? parts.minutes : parts.hours;\n if (t > lo && whole && field % count === 0) out.push(t);\n }\n return out;\n }\n // Calendar units: each boundary is made from its fields, so a day is a day however long it is.\n const nth: (i: number) => number =\n unit === \"day\"\n ? (i) => midnight(zone, start.year, start.month, start.date + i)\n : unit === \"week\"\n ? // Weeks start on Monday, as ISO 8601's do.\n (i) => midnight(zone, start.year, start.month, start.date - ((start.weekday + 6) % 7) + 7 * i)\n : unit === \"month\"\n ? (i) => midnight(zone, start.year, Math.floor(start.month / count) * count + count * i, 1)\n : (i) => midnight(zone, Math.floor(start.year / count) * count + count * i, 0, 1);\n let previous = -Infinity;\n for (let i = 0; ; i++) {\n const t = nth(i);\n // A boundary always moves on; the check only guards against a zone that doesn't.\n if (t >= hi || t <= previous) break;\n previous = t;\n // Every other day counts from the 1st of each month.\n if (t > lo && (unit !== \"day\" || (partsOf(t, zone).date - 1) % count === 0)) out.push(t);\n }\n return out;\n}\n\n/**\n * `months` calendar months on from `t`, or back when it's negative, in the zone: the same day of the\n * month at the same time of day, or the month's last day when it's shorter, as Temporal's `add`\n * constrains it (31 January a month on is 28 February, or the 29th in a leap year). A time the\n * clocks skip there comes out just after the change, as Date's setters move it.\n */\nexport function monthsOn(t: number, months: number, zone: TimeZone): number {\n const { year, month, date, hours, minutes, seconds, ms } = partsOf(t, zone);\n // Day 0 of the month after is the last of the month: every zone's calendar has the same months.\n const last = new Date(0);\n last.setUTCFullYear(year, month + months + 1, 0);\n const day = Math.min(date, last.getUTCDate());\n const d = new Date(0);\n if (zone === \"UTC\") {\n d.setUTCFullYear(year, month + months, day);\n d.setUTCHours(hours, minutes, seconds, ms);\n } else {\n d.setFullYear(year, month + months, day);\n d.setHours(hours, minutes, seconds, ms);\n }\n return d.getTime();\n}\n\n/** The coarsest boundary `t` falls on, in the zone. */\nexport function timeLevel(t: number, zone: TimeZone): TimeLevel {\n const { ms, seconds, minutes, hours, date, month } = partsOf(t, zone);\n if (ms !== 0) return \"millisecond\";\n if (seconds !== 0) return \"second\";\n if (minutes !== 0) return \"minute\";\n if (hours !== 0) return \"hour\";\n if (date !== 1) return \"day\";\n return month !== 0 ? \"month\" : \"year\";\n}\n\n/**\n * How the chart says an x for people: a medium date in the page's locale (\"Jan 5, 2026\", or \"5 Jan\n * 2026\" in en-GB), with the time when any of `times` has one (\"Jan 5, 2026, 3:00 PM\"), its seconds\n * when any has those, and its milliseconds when any has those (\"Jan 5, 2026, 3:00:00.100 PM\"), so\n * every x is said differently.\n */\nexport function timeName(times: readonly number[], zone: TimeZone): (t: number) => string {\n const finest = times.reduce((max, t) => Math.max(max, LEVELS.indexOf(timeLevel(t, zone))), 0);\n const timeZone = zoneOption(zone);\n const timeStyle = finest >= LEVELS.indexOf(\"second\") ? \"medium\" : finest >= LEVELS.indexOf(\"hour\") ? \"short\" : undefined;\n // Intl's styles can't say a fraction of a second, so a time to the millisecond is said field by\n // field, as the medium styles say the rest.\n const options: Intl.DateTimeFormatOptions =\n finest === LEVELS.indexOf(\"millisecond\")\n ? { year: \"numeric\", ...FIELDS.day, ...FIELDS.millisecond, timeZone }\n : { dateStyle: \"medium\", ...(timeStyle ? { timeStyle } : {}), timeZone };\n const format = new Intl.DateTimeFormat(undefined, options);\n return (t) => format.format(t);\n}\n\n/** Words a time for its own level, with every level up to `upTo` when it's finer than that (\"millisecond\" adds none). A formatter per set of fields, made when first needed. */\nfunction tickWording(zone: TimeZone): (t: number, upTo: TimeLevel) => string {\n const formats = new Map<string, Intl.DateTimeFormat>();\n return (t, upTo) => {\n const own = LEVELS.indexOf(timeLevel(t, zone));\n const fields: Intl.DateTimeFormatOptions = {};\n for (let i = Math.min(own, LEVELS.indexOf(upTo)); i <= own; i++) Object.assign(fields, FIELDS[LEVELS[i]!]);\n const id = JSON.stringify(fields);\n let format = formats.get(id);\n if (!format) formats.set(id, (format = new Intl.DateTimeFormat(undefined, { ...fields, timeZone: zoneOption(zone) })));\n return format.format(t);\n };\n}\n\n/** Intl's timeZone for the zone: undefined is the viewer's own. */\nconst zoneOption = (zone: TimeZone): string | undefined => (zone === \"UTC\" ? \"UTC\" : undefined);\n\ninterface Parts {\n readonly year: number;\n /** 0 to 11. */\n readonly month: number;\n /** The day of the month, from 1. */\n readonly date: number;\n /** 0 is Sunday. */\n readonly weekday: number;\n readonly hours: number;\n readonly minutes: number;\n readonly seconds: number;\n readonly ms: number;\n}\n\nfunction partsOf(t: number, zone: TimeZone): Parts {\n const d = new Date(t);\n return zone === \"UTC\"\n ? { year: d.getUTCFullYear(), month: d.getUTCMonth(), date: d.getUTCDate(), weekday: d.getUTCDay(), hours: d.getUTCHours(), minutes: d.getUTCMinutes(), seconds: d.getUTCSeconds(), ms: d.getUTCMilliseconds() }\n : { year: d.getFullYear(), month: d.getMonth(), date: d.getDate(), weekday: d.getDay(), hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds(), ms: d.getMilliseconds() };\n}\n\n/**\n * The start of a day in the zone: midnight, or the first time after it when the clocks skip it. The\n * month and the day may run over, as Date's setters allow (day 32 of January is 1 February). The\n * setters take any year, unlike Date.UTC, which reads 0 to 99 as 1900 to 1999.\n */\nfunction midnight(zone: TimeZone, year: number, month: number, date: number): number {\n const d = new Date(0);\n if (zone === \"UTC\") {\n d.setUTCFullYear(year, month, date);\n d.setUTCHours(0, 0, 0, 0);\n } else {\n d.setFullYear(year, month, date);\n d.setHours(0, 0, 0, 0);\n }\n return d.getTime();\n}\n","// The line chart's layout: pure, so it's tested without a DOM. Options in, the frame, ticks and size\n// out; placeLines and placePoints then draw the marks (lines described with describe.line, points\n// with describe.point) for any state of the rows and any reveal. Pixel sizes follow the prototype's\n// card 2 (demo/lab.html).\n//\n// A layout is drawn from a few numbers: the frame (the value scale, and the box: the x range and where\n// the plot sits) and each row's x and values. Transitions interpolate those numbers, and the place\n// functions draw any state in between, and any reveal, the same way the layout draws its own. On a\n// time axis an x is its Date's time in ms, and only its ticks, its wording and the samples' `at` know.\n// A missing value (null or undefined) is a gap in its line: the line runs on from the value after it.\n\nimport { describe, type MarkData, type MarkGeometry, type Rect, type Sample } from \"../core\";\nimport { clean, niceDomain, niceStep, type Tick } from \"./bar-layout\";\nimport { textBox, type TextPlacement } from \"./render/text\";\nimport { decimals } from \"./shell/format\";\nimport { TIME_ZONES, timeName, timeTicks, type TimeZone } from \"./time\";\nimport type { Accessor, LineChartOptions } from \"./types\";\n\nexport type { Tick } from \"./bar-layout\";\n\nexport interface LineSeries<D> {\n /** The series' name: its field. */\n readonly series: string;\n readonly value: (d: D, i: number) => unknown;\n}\n\n/** Which accessor gives the x, which the key, which the values; and how an x is said. */\nexport interface LineEncoding<D> {\n readonly x: (d: D, i: number) => unknown;\n /** Undefined: the key is the x. */\n readonly key: ((d: D, i: number) => unknown) | undefined;\n readonly series: readonly LineSeries<D>[];\n /** A time axis's zone. */\n readonly timeZone: TimeZone;\n /** Words an x for people instead of the default. */\n readonly xFormat: ((x: Date | number) => string) | undefined;\n}\n\nexport interface LineValue {\n readonly series: string;\n /** Undefined where the series has no value (null or undefined in the data): a gap in its line. */\n readonly value: number | undefined;\n}\n\nexport interface LineRow<D> {\n readonly key: string;\n readonly datum: D;\n /** The row's index in `data`. */\n readonly index: number;\n /** A number, or on a time axis its Date's time in ms. */\n readonly x: number;\n /** The x as text: the tooltip's title, the table's row header and the start of the x's name. */\n readonly label: string;\n /** In series order. */\n readonly values: readonly LineValue[];\n /** The series with no value here. */\n readonly missing: ReadonlySet<string>;\n /**\n * Each series' level here, which a change animates: its value, or for a missing one where its line\n * runs past this x (across the gap, or level with its nearest value; 0 with none), so a value that\n * comes grows out of the line.\n */\n readonly levels: Readonly<Record<string, number>>;\n}\n\n/** The value axis: data `lo` sits at the box's `bottom`, data `hi` at its `top`. */\nexport interface LineScale {\n readonly lo: number;\n readonly hi: number;\n}\n\n/**\n * The x axis and where the plot sits, in px: data `xLo` at `left`, `xHi` at `right`, the value scale\n * between `bottom` and `top`. Plus the chart's size.\n */\nexport interface LineBox {\n readonly xLo: number;\n readonly xHi: number;\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly bottom: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** A change animates the scale in its values stage and the box in its positions stage. */\nexport interface LineFrame {\n readonly scale: LineScale;\n readonly box: LineBox;\n}\n\n/** An x tick: a label under the plot, with no gridline. */\nexport interface XTick {\n readonly value: number;\n readonly label: TextPlacement;\n}\n\nexport interface LineLayout<D> {\n readonly width: number;\n readonly height: number;\n readonly frame: LineFrame;\n /** In ascending x. */\n readonly rows: readonly LineRow<D>[];\n /** Whether x is a time axis: the data gives Dates. */\n readonly time: boolean;\n readonly series: readonly string[];\n /** Gridlines and labels for the values, from the bottom. */\n readonly yTicks: readonly Tick[];\n readonly xTicks: readonly XTick[];\n /** Per series, the decimals its values are given to: an end label counts rounded to these. */\n readonly decimals: Readonly<Record<string, number>>;\n}\n\nexport interface LineLayoutInput<D> {\n readonly data: readonly D[];\n readonly encoding: LineEncoding<D>;\n readonly width: number;\n readonly height: number | undefined;\n readonly format: (value: number) => string;\n /** Text width in px, for margins. */\n readonly measure: Measure;\n /** A line's end label for a value, measured for the right margin; undefined with `labels: false`. */\n readonly label: ((series: string, value: number) => string) | undefined;\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\n/** How placeLines words the lines' end labels, and measures them for their boxes. */\nexport interface EndLabels {\n /** A line's end label for its value at its end; \"\" for none. */\n readonly text: (series: string, value: number) => string;\n readonly measure: Measure;\n}\n\n/** A row as it's drawn now, part way through a change: where it is, and its values by series. */\nexport interface RowState<D> {\n readonly key: string;\n readonly datum: D;\n readonly x: number;\n readonly values: Readonly<Record<string, number>>;\n /** The series with no value here: no point, and a gap in the line. Their `values` aren't drawn. */\n readonly missing?: ReadonlySet<string>;\n}\n\nexport interface PlacedLine<D> {\n readonly series: string;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n /** The line's revealed end, in px, where its end dot and label go, and its value there. */\n readonly end: { readonly x: number; readonly y: number; readonly value: number };\n /** Its end label, placed with the others' (its text \"\" for none); undefined without `labels`. */\n readonly label: TextPlacement | undefined;\n}\n\nexport interface PlacedPoint<D> {\n readonly key: string;\n readonly series: string;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n}\n\n// From the prototype: 2.25 px lines, dots of radius 4.5, 300 px high, labels 10 px past the end and\n// 16 px apart.\nexport const LINE_WIDTH = 2.25;\nexport const DOT_RADIUS = 4.5;\nconst HEIGHT = 300;\nconst TOP = 12;\n/** Space under the plot for the x labels. */\nconst AXIS = 32;\n/** Gridlines reach this far past the last x, so the end dots sit inside the grid. */\nconst GRID_PAST = 8;\nconst TICK_SIZE = 11;\nconst VALUE_SIZE = 12.5;\n/** Between a line's end and its label. */\nconst LABEL_GAP = 10;\n/** Between the centres of two end labels. */\nconst LABEL_SPACING = 16;\n/** Between two x labels. */\nconst TICK_GAP = 8;\n/** Moves a text baseline down by this share of the font size to centre the text on a line. */\nconst CENTRE = 0.36;\n\n/** Reads the options: the x, the key and the series. Throws on what it can't draw. */\nexport function lineEncoding<D>(options: LineChartOptions<D>): LineEncoding<D> {\n const { x, series, key } = options;\n if (typeof x !== \"string\" && typeof x !== \"function\") throw new TypeError(\"lineChart needs x: a field of numbers or Dates, or a function that returns each row's x.\");\n if (!Array.isArray(series) || series.length === 0) throw new TypeError(\"lineChart needs series: the numeric fields to draw as lines.\");\n const seen = new Set<string>();\n for (const field of series as readonly unknown[]) {\n if (typeof field !== \"string\" || field === \"\") throw new TypeError(`lineChart: each series must be a field name, got ${show(field)}.`);\n if (seen.has(field)) throw new TypeError(`lineChart: \"${field}\" appears twice in series.`);\n seen.add(field);\n }\n if (key !== undefined && typeof key !== \"string\" && typeof key !== \"function\") throw new TypeError(\"lineChart: key must be a field name or a function.\");\n const labels: unknown = options.labels;\n if (labels !== undefined && labels !== false && typeof labels !== \"function\") throw new TypeError(\"lineChart: labels must be false or a function that returns a line's end label.\");\n const timeZone: unknown = options.timeZone ?? \"UTC\";\n if (!TIME_ZONES.includes(timeZone as TimeZone)) throw new TypeError(`lineChart: timeZone must be \"UTC\" or \"local\", got ${show(timeZone)}.`);\n const xFormat: unknown = options.xFormat;\n if (xFormat !== undefined && typeof xFormat !== \"function\") throw new TypeError(\"lineChart: xFormat must be a function that turns an x into text.\");\n return {\n x: accessor(x),\n key: key === undefined ? undefined : accessor(key),\n series: series.map((field) => ({ series: field, value: accessor<D, unknown>(field) })),\n timeZone: timeZone as TimeZone,\n xFormat: options.xFormat\n };\n}\n\nexport function layoutLines<D>(input: LineLayoutInput<D>): LineLayout<D> {\n const { width, measure } = input;\n const height = input.height ?? HEIGHT;\n const { rows, time } = prepareRows(input);\n const series = input.encoding.series.map((s) => s.series);\n const domain = niceDomain(rows.flatMap((row) => row.values.flatMap((v) => (v.value === undefined ? [] : [v.value]))));\n const yTexts = domain.ticks.map(input.format);\n const xLo = rows[0]?.x ?? 0;\n const xHi = rows[rows.length - 1]?.x ?? 0;\n const ticked = rows.length === 0 ? [] : time ? timeTicks(xLo, xHi, input.encoding.timeZone) : xTickValues(xLo, xHi).map((value) => ({ value, text: xText(value) }));\n const xValues = ticked.map((tick) => tick.value);\n const xTexts = ticked.map((tick) => tick.text);\n const xWidths = xTexts.map((text) => measure(text, \"ec-tick\", TICK_SIZE));\n\n // The values' labels on the left; the end labels, or the last x label, on the right.\n const labelWidth = input.label ? widest(distinctLabels(rows, input.label), \"ec-value\", VALUE_SIZE, measure) : 0;\n const left = Math.max(widest(yTexts, \"ec-tick\", TICK_SIZE, measure) + 10, (xWidths[0] ?? 0) / 2 + 2);\n const right = Math.max(GRID_PAST + 2, (xWidths[xWidths.length - 1] ?? 0) / 2 + 2, labelWidth > 0 ? LABEL_GAP + labelWidth + 4 : 0);\n const frame: LineFrame = {\n scale: { lo: domain.lo, hi: domain.hi },\n box: { xLo, xHi, left, right: Math.max(left, width - right), top: TOP, bottom: Math.max(TOP, height - AXIS), width, height }\n };\n\n const decimalsBy: Record<string, number> = {};\n for (const name of series) decimalsBy[name] = 0;\n for (const row of rows) for (const v of row.values) if (v.value !== undefined) decimalsBy[v.series] = Math.max(decimalsBy[v.series]!, decimals(v.value));\n\n const xTicks = xValues.map((value, i) => placeXTick(frame, value, xTexts[i]!));\n return {\n width,\n height,\n frame,\n rows,\n time,\n series,\n yTicks: domain.ticks.map((value, i) => placeYTick(frame, value, yTexts[i]!)),\n xTicks: spaced(xTicks, xWidths),\n decimals: decimalsBy\n };\n}\n\n/** Data to px. With a single x, it sits in the middle of the plot. */\nexport function positions(frame: LineFrame): { x(value: number): number; y(value: number): number } {\n const { scale, box } = frame;\n const xSpan = box.xHi - box.xLo;\n const ySpan = scale.hi - scale.lo;\n return {\n x: (value) => (xSpan > 0 ? box.left + ((value - box.xLo) / xSpan) * (box.right - box.left) : (box.left + box.right) / 2),\n y: (value) => (ySpan > 0 ? box.bottom - ((value - scale.lo) / ySpan) * (box.bottom - box.top) : box.bottom)\n };\n}\n\n/**\n * Draws each series' line through `rows` (in ascending x) up to `through`: a vertex per row at or\n * before it, plus the point part way to the next row when `through` falls between two. With no row\n * at or before it, a line is its first point. Each line's data has the row at its revealed end, a\n * sample per vertex (`t` by distance along the walk, `at` its x: a Date on a `time` axis), and the\n * other lines as `related`. With `labels`, the end labels are placed together (placeEndLabels), and\n * each line's geometry has its own label's box as `labelBounds`: none when its text is \"\".\n *\n * A row missing a series is no vertex of its line: the line breaks there (`breaks`, so its geometry\n * has a gap from the value before to the value after, and the sample after it has `gapBefore`), and\n * a line revealed into a gap ends at its last value. Missing values before a line's first value or\n * after its last are no gap. A line with no value up to the reveal is empty: no length, no samples\n * and no label, at its level at the first x, and its datum the row at the reveal.\n */\nexport function placeLines<D>(frame: LineFrame, rows: readonly RowState<D>[], series: readonly string[], through: number, time = false, labels?: EndLabels): PlacedLine<D>[] {\n const first = rows[0];\n if (!first) return [];\n const at = positions(frame);\n let last = 0;\n while (last + 1 < rows.length && rows[last + 1]!.x <= through) last++;\n const end = rows[last]!;\n const next = rows[last + 1];\n const share = next && next.x > end.x && through > end.x ? (through - end.x) / (next.x - end.x) : undefined;\n const shown = rows.slice(0, last + 1);\n\n const datas = new Map<string, MarkData<D>>();\n const related = (own: string) => (name: string) => (name === own ? undefined : datas.get(name));\n const traced = series.map((name) => {\n const has = (row: RowState<D>): boolean => !row.missing?.has(name);\n const vertices: { at: number; value: number; datum: D; gapBefore: boolean }[] = [];\n let gap = false;\n for (const row of shown) {\n // A gap is only between values: none before the first.\n if (!has(row)) gap = vertices.length > 0;\n else {\n vertices.push({ at: row.x, value: row.values[name] ?? 0, datum: row.datum, gapBefore: gap });\n gap = false;\n }\n }\n if (share !== undefined && has(end) && has(next!)) {\n const from = end.values[name] ?? 0;\n vertices.push({ at: through, value: from + share * ((next!.values[name] ?? 0) - from), datum: end.datum, gapBefore: false });\n }\n const points = vertices.length > 0 ? vertices.map((v) => ({ x: at.x(v.at), y: at.y(v.value) })) : [{ x: at.x(first.x), y: at.y(first.values[name] ?? 0) }];\n return { name, vertices, points };\n });\n // An empty line has no label, and takes no room from the others'.\n const named = traced.filter(({ vertices }) => vertices.length > 0);\n const placed = labels\n ? placeEndLabels(\n frame,\n named.map(({ name, vertices, points }) => ({ ...points[points.length - 1]!, text: labels.text(name, vertices[vertices.length - 1]!.value) }))\n )\n : [];\n const lines = traced.map(({ name, vertices, points }): PlacedLine<D> => {\n const tip = points[points.length - 1]!;\n const label = labels ? (placed[named.findIndex((line) => line.name === name)] ?? { x: tip.x + LABEL_GAP, y: tip.y + VALUE_SIZE * CENTRE, anchor: \"start\", text: \"\" }) : undefined;\n const labelBounds = labels ? (label && label.text !== \"\" ? [textBox(label, labels.measure, \"ec-value\", VALUE_SIZE)] : []) : undefined;\n const breaks = vertices.flatMap((v, j) => (v.gapBefore ? [j] : []));\n const geometry = describe.line({ key: name, series: name, points, width: LINE_WIDTH, ...(breaks.length > 0 ? { breaks } : {}), ...(labelBounds ? { labelBounds } : {}) });\n // By distance, as the walk measures it, gaps and all; the last is exactly 1.\n let distance = 0;\n const samples: Sample[] = vertices.map((v, j) => {\n if (j > 0) distance += Math.hypot(points[j]!.x - points[j - 1]!.x, points[j]!.y - points[j - 1]!.y);\n const t = geometry.length > 0 ? (j === vertices.length - 1 ? 1 : Math.min(1, distance / geometry.length)) : 0;\n return { t, value: v.value, at: sampleAt(v.at, time), ...(v.gapBefore ? { gapBefore: true } : {}) };\n });\n const last = vertices[vertices.length - 1];\n const data: MarkData<D> = { datum: last ? last.datum : end.datum, samples, related: related(name) };\n datas.set(name, data);\n return { series: name, geometry, data, end: { ...tip, value: last ? last.value : (first.values[name] ?? 0) }, label };\n });\n return lines;\n}\n\n/**\n * The points that show at rest: each value next to a gap with no other value beside it, so it has\n * no stroke. Keyed as points are, from `rows` as they're drawn, in ascending x.\n */\nexport function loneValues<D>(rows: readonly RowState<D>[], series: readonly string[]): Set<string> {\n const lone = new Set<string>();\n // Every frame of a change asks: a chart with no gaps answers at once.\n if (!rows.some((row) => row.missing !== undefined && row.missing.size > 0)) return lone;\n const has = (row: RowState<D> | undefined, name: string): boolean => row !== undefined && !row.missing?.has(name);\n rows.forEach((row, i) => {\n for (const name of series) {\n const before = rows[i - 1];\n const after = rows[i + 1];\n if (has(row, name) && !has(before, name) && !has(after, name) && (before !== undefined || after !== undefined)) lone.add(pointKey(name, row.key));\n }\n });\n return lone;\n}\n\n/** The point mark's key: \"<series>@<row key>\". */\nexport function pointKey(series: string, row: string): string {\n return `${series}@${row}`;\n}\n\n/** Each series' point at the row, but those missing there: a dot, with the row's value as its one sample (`at` its x: a Date on a `time` axis) and the other series' points as `related`. */\nexport function placePoints<D>(frame: LineFrame, row: RowState<D>, series: readonly string[], time = false): PlacedPoint<D>[] {\n const at = positions(frame);\n const x = at.x(row.x);\n const datas = new Map<string, MarkData<D>>();\n return series.filter((name) => !row.missing?.has(name)).map((name) => {\n const value = row.values[name] ?? 0;\n const key = pointKey(name, row.key);\n const data: MarkData<D> = { datum: row.datum, samples: [{ t: 0, value, at: sampleAt(row.x, time) }], related: (other) => (other === name ? undefined : datas.get(other)) };\n datas.set(name, data);\n return { key, series: name, geometry: describe.point({ key, series: name, x, y: at.y(value), r: DOT_RADIUS }), data };\n });\n}\n\n/**\n * Each revealed x's hit column, given their px in ascending order: from halfway to the x before it to\n * halfway to the x after it, the first from the chart's left edge and the last to its right edge, so\n * the pointer hovers the nearest revealed x anywhere over the chart.\n */\nexport function placeColumns(frame: LineFrame, xs: readonly number[]): Rect[] {\n const { width, height } = frame.box;\n return xs.map((x, i) => {\n const from = i === 0 ? 0 : (xs[i - 1]! + x) / 2;\n const to = i === xs.length - 1 ? width : (x + xs[i + 1]!) / 2;\n return { x: from, y: 0, width: Math.max(0, to - from), height };\n });\n}\n\n/** The dashed line across the plot at x px, for the hovered x. */\nexport function placeCrosshair(frame: LineFrame, x: number): { readonly x1: number; readonly y1: number; readonly x2: number; readonly y2: number } {\n return { x1: x, y1: frame.box.top, x2: x, y2: frame.box.bottom };\n}\n\n/**\n * Each line's end label, in the order given: 10 px past its end, centred on its end's y but kept at\n * least 16 px from the others (the prototype's rule) and inside the chart.\n */\nexport function placeEndLabels(frame: LineFrame, ends: readonly { readonly x: number; readonly y: number; readonly text: string }[]): TextPlacement[] {\n const half = VALUE_SIZE / 2;\n const ys = spread(\n ends.map((end) => end.y),\n LABEL_SPACING,\n half,\n frame.box.height - half\n );\n return ends.map((end, i) => ({ x: end.x + LABEL_GAP, y: ys[i]! + VALUE_SIZE * CENTRE, anchor: \"start\", text: end.text }));\n}\n\n/**\n * Moves values apart so neighbours are at least `gap` apart, keeping them within [min, max] where\n * there's room. Values that would come too close form a cluster spaced `gap` apart and centred on\n * where its members would be, so two labels too close move apart equally. In the order given.\n */\nexport function spread(values: readonly number[], gap: number, min: number, max: number): number[] {\n const order = values.map((value, index) => ({ value, index })).sort((a, b) => a.value - b.value || a.index - b.index);\n const clusters: { members: { value: number; index: number }[]; start: number }[] = [];\n const place = (members: { value: number }[]): number => {\n const mean = members.reduce((sum, m) => sum + m.value, 0) / members.length;\n const span = (members.length - 1) * gap;\n return Math.max(min, Math.min(max - span, mean - span / 2));\n };\n for (const item of order) {\n clusters.push({ members: [item], start: place([item]) });\n // Merges with the cluster above while they'd overlap.\n while (clusters.length > 1) {\n const below = clusters[clusters.length - 1]!;\n const above = clusters[clusters.length - 2]!;\n if (below.start - (above.start + (above.members.length - 1) * gap) >= gap) break;\n clusters.pop();\n above.members.push(...below.members);\n above.start = place(above.members);\n }\n }\n const out = new Array<number>(values.length);\n for (const cluster of clusters) cluster.members.forEach((member, i) => (out[member.index] = cluster.start + i * gap));\n return out;\n}\n\n/** A value's gridline across the plot (and a little past the last x) and its label on the left. */\nexport function placeYTick(frame: LineFrame, value: number, text: string): Tick {\n const { box } = frame;\n const y = positions(frame).y(value);\n return { value, line: { x1: box.left, y1: y, x2: box.right + GRID_PAST, y2: y }, label: { x: box.left - 8, y: y + TICK_SIZE * CENTRE, anchor: \"end\", text } };\n}\n\n/** An x's label under the plot. */\nexport function placeXTick(frame: LineFrame, value: number, text: string): XTick {\n return { value, label: { x: positions(frame).x(value), y: frame.box.bottom + 18, anchor: \"middle\", text } };\n}\n\n/** Where x labels go: both ends of the rows' range, and round steps (1, 2 or 5 × a power of 10) between them, about four apart. */\nexport function xTickValues(lo: number, hi: number): number[] {\n if (!(hi > lo)) return [lo];\n const step = niceStep((hi - lo) / 4);\n const ticks = [lo];\n for (let i = Math.floor(lo / step) + 1; clean(i * step) < hi; i++) {\n const value = clean(i * step);\n if (value > lo) ticks.push(value);\n }\n ticks.push(hi);\n return ticks;\n}\n\n/** An x as text: as given, with no grouping (a year stays \"2024\"). */\nexport function xText(x: number): string {\n return String(x);\n}\n\n/** The ticks whose labels don't collide: both ends, and the steps between that clear their neighbours by 8 px. With no room for both ends, the first. */\nfunction spaced(ticks: readonly XTick[], widths: readonly number[]): XTick[] {\n if (ticks.length <= 1) return [...ticks];\n const edges = ticks.map((tick, i) => ({ tick, from: tick.label.x - widths[i]! / 2, to: tick.label.x + widths[i]! / 2 }));\n const last = edges[edges.length - 1]!;\n const kept = [edges[0]!];\n for (const edge of edges.slice(1, -1)) {\n if (edge.from - kept[kept.length - 1]!.to >= TICK_GAP && last.from - edge.to >= TICK_GAP) kept.push(edge);\n }\n if (last.from - kept[kept.length - 1]!.to >= TICK_GAP) kept.push(last);\n return kept.map((edge) => edge.tick);\n}\n\n/** The rows in ascending x, and whether x is a time axis: the first row's x is a Date. */\nfunction prepareRows<D>({ data, encoding }: LineLayoutInput<D>): { rows: LineRow<D>[]; time: boolean } {\n const keys = new Set<string>();\n let time = false;\n const read = data.map((datum, index) => {\n const raw = encoding.x(datum, index);\n if (index === 0) time = raw instanceof Date;\n const x = xOf(raw, index, time);\n // A date is keyed by its ISO string, which says the same instant the same way on every machine.\n const key = String(encoding.key ? encoding.key(datum, index) : time ? new Date(x).toISOString() : x);\n if (keys.has(key)) throw new Error(`lineChart: two rows have the key \"${key}\". Keys must be unique.`);\n keys.add(key);\n const values = encoding.series.map(({ series, value }) => ({ series, value: numberOf(value(datum, index), series, key) }));\n return { key, datum, index, x, values };\n });\n // Array.prototype.sort is stable, so the error below names the rows in data order.\n read.sort((a, b) => a.x - b.x);\n for (let i = 1; i < read.length; i++) {\n const [a, b] = [read[i - 1]!, read[i]!];\n if (a.x === b.x) {\n const x = time ? new Date(a.x).toISOString() : xText(a.x);\n throw new Error(`lineChart: the rows \"${a.key}\" and \"${b.key}\" have the same x, ${x}. Each x is one point on every line, so x values must be unique.`);\n }\n }\n const word = xWording(encoding, time, read.map((row) => row.x));\n const levels = levelsOf(read, encoding.series.length);\n return {\n rows: read.map((row, i) => ({ ...row, label: word(row.x), missing: new Set(row.values.flatMap((v) => (v.value === undefined ? [v.series] : []))), levels: levels[i]! })),\n time\n };\n}\n\n/**\n * Each row's level for each series, by series name: its value, or for a missing one where its line\n * runs past the row's x: across the gap, in proportion to x, or level with its nearest value before\n * its first or after its last. A series with no values is at 0.\n */\nfunction levelsOf(rows: readonly { readonly x: number; readonly values: readonly LineValue[] }[], count: number): Record<string, number>[] {\n const levels = rows.map((): Record<string, number> => ({}));\n for (let s = 0; s < count; s++) {\n let before = -1;\n let after = -1;\n rows.forEach((row, i) => {\n const { series, value } = row.values[s]!;\n if (value !== undefined) {\n levels[i]![series] = value;\n before = i;\n return;\n }\n // The next value, found once for each run of missing ones, so a long run stays linear.\n if (after <= i) {\n after = i + 1;\n while (after < rows.length && rows[after]!.values[s]!.value === undefined) after++;\n }\n const a = rows[before]?.values[s]!.value;\n const b = rows[after]?.values[s]!.value;\n levels[i]![series] =\n a !== undefined && b !== undefined ? a + ((row.x - rows[before]!.x) / (rows[after]!.x - rows[before]!.x)) * (b - a) : (a ?? b ?? 0);\n });\n }\n return levels;\n}\n\n/** A row's x as a number: a finite number, or on a time axis a valid Date's time. Every row's x is the same kind as the first's. */\nfunction xOf(x: unknown, index: number, time: boolean): number {\n if (x instanceof Date) {\n if (!time) throw new TypeError(`lineChart: x must be all numbers or all Dates, but row 0's is a number and row ${index}'s a Date.`);\n const t = x.getTime();\n if (Number.isNaN(t)) throw new TypeError(`lineChart: x must be a valid Date, got an invalid Date in row ${index}.`);\n return t;\n }\n if (time) {\n if (typeof x === \"number\") throw new TypeError(`lineChart: x must be all numbers or all Dates, but row 0's is a Date and row ${index}'s a number.`);\n throw new TypeError(`lineChart: x must be a valid Date, got ${show(x)} in row ${index}.`);\n }\n if (typeof x !== \"number\" || !Number.isFinite(x)) throw new RangeError(`lineChart: x must be a finite number, got ${show(x)} in row ${index}.`);\n return x;\n}\n\n/** How an x is said for people: `xFormat`'s words, given the x as the data has it; or a time axis's medium date; or a number as given. */\nfunction xWording<D>(encoding: LineEncoding<D>, time: boolean, xs: readonly number[]): (x: number) => string {\n const { xFormat } = encoding;\n if (xFormat) return (x) => xFormat(time ? new Date(x) : x);\n return time ? timeName(xs, encoding.timeZone) : xText;\n}\n\n/** A sample's `at` for an x: on a time axis, a Date of its own, so an effect that changes it changes nothing else. */\nfunction sampleAt(x: number, time: boolean): number | Date {\n return time ? new Date(x) : x;\n}\n\n/**\n * A value, or undefined for a missing one: null or undefined, a gap in the line. A line doesn't count\n * a missing value as 0 as a bar does, and NaN and the infinities still throw: they're usually a mistake.\n */\nfunction numberOf(value: unknown, series: string, key: string): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (value === null || value === undefined) return undefined;\n throw new RangeError(`lineChart: \"${series}\" for \"${key}\" must be a finite number, or null or undefined where it has no value, got ${show(value)}.`);\n}\n\n/**\n * The end labels worth measuring: one of each shape, its digits aside. Chart text has tabular digits,\n * so \"23 goals\" and \"48 goals\" are as wide, and a long series isn't measured row by row in the DOM.\n */\nfunction distinctLabels<D>(rows: readonly LineRow<D>[], label: (series: string, value: number) => string): string[] {\n const shapes = new Map<string, string>();\n for (const row of rows) {\n for (const { series, value } of row.values) {\n if (value === undefined) continue;\n const text = label(series, value);\n const shape = text.replace(/\\d/g, \"0\");\n if (!shapes.has(shape)) shapes.set(shape, text);\n }\n }\n return [...shapes.values()];\n}\n\nfunction widest(texts: readonly string[], className: string, size: number, measure: Measure): number {\n return texts.reduce((max, text) => Math.max(max, measure(text, className, size)), 0);\n}\n\nfunction accessor<D, T>(option: Accessor<D, T> | string): (d: D, i: number) => T {\n if (typeof option === \"function\") return option;\n return (d) => (d as Record<string, unknown>)[option] as T;\n}\n\nconst show = (value: unknown): string => (typeof value === \"string\" ? JSON.stringify(value) : String(value));\n","// lineChart: the reference line chart. A line per series through one row per x (described with\n// describe.line), with a dot at its end and a label in the right margin, and a point per row and series\n// (describe.point), shown where its x is hovered or focused; a measured layout with gridlines and ticks\n// in theme colours; a crosshair that hovers every series at the nearest x, from the pointer, touch or\n// keyboard, with a tooltip; a legend, a data table and, with `announce`, a live region for screen\n// readers. A missing value (null or undefined) is a gap in its line, with no point; the x is still a\n// stop. reveal(x) shows the data up to x, as playback drives it. update() animates the change:\n// staged in presentation (values, then positions), in one short stage in analysis, at once when\n// motion is off. x is numbers or Dates: a time axis has its own ticks and wording (time.ts), and is\n// otherwise drawn in ms like any number.\n//\n// The chart never names an effect: it resolves `on` through the presets it's handed and plays them\n// through the runner, which draws on the SVG surface. What doesn't depend on lines (events, hover and\n// focus, transitions and leaving marks, DOM order, size and fonts) is in shell/. Each x is a hover\n// target standing for every series' point there; the lines themselves are never hovered.\n\nimport type { AnimateOptions, Animated, MarkData, MarkGeometry, Sample, TweenResult } from \"../core\";\nimport { animated, defaultClock, interpolateNumber, interpolateRecord, matrix } from \"../core\";\nimport { resolveEffects } from \"../core/registry\";\nimport { report } from \"../core/report\";\nimport { createRunner, type RunInput } from \"../core/runner\";\nimport { chartAnnouncer, changeText, type Announcer } from \"./announce\";\nimport { toColorAssignment } from \"./colors\";\nimport { chartLegend } from \"./legend\";\nimport {\n DOT_RADIUS,\n LINE_WIDTH,\n layoutLines,\n lineEncoding,\n loneValues,\n placeColumns,\n placeCrosshair,\n placeLines,\n placePoints,\n placeXTick,\n placeYTick,\n pointKey,\n positions,\n type EndLabels,\n type LineFrame,\n type LineLayout,\n type LineRow,\n type LineValue,\n type PlacedLine,\n type PlacedPoint,\n type RowState\n} from \"./line-layout\";\nimport { linkable } from \"./link\";\nimport { chartMotion } from \"./motion\";\nimport { svgMarkHandle, type StyledPart, type SvgMarkHandle } from \"./render/mark-style\";\nimport { svgSurface } from \"./render/surface\";\nimport { setAttributes, setStyles, sizeAttributes, svgElement, transformAttribute } from \"./render/svg\";\nimport { placeText, textMeasure, type TextPlacement } from \"./render/text\";\nimport { injectStyles, markColorStyles, seriesColors, type SeriesColors } from \"./render/theme\";\nimport { seriesLabel } from \"./series\";\nimport { chartEvents } from \"./shell/events\";\nimport { decimals, format, round } from \"./shell/format\";\nimport { chartHover } from \"./shell/hover\";\nimport { chartLabel } from \"./shell/labels\";\nimport { leavingMarks, type Leave } from \"./shell/leaving\";\nimport { orderElements } from \"./shell/order\";\nimport { checkChartOptions, checkNeeds, containerWidth, describeChart, nextEffects, resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport { busy, chartTransitions, geometryChanged, playUpdate, same, sameFields, type ChartDiff } from \"./shell/transitions\";\nimport { watchFonts, watchHoverDuration, watchWidth } from \"./shell/watch\";\nimport { chartTable, tableModel, type TableModel } from \"./table\";\nimport { monthsOn } from \"./time\";\nimport { chartTooltip, summaryContent, type TooltipContent } from \"./tooltip\";\nimport type { LineChart, LineChartOptions } from \"./types\";\n\nexport type { LineChart } from \"./types\";\n\n/** Values by series, in data units. */\ntype Values = Readonly<Record<string, number>>;\n\n/** A mark as it's laid out or drawn: its geometry, and the data effects get with it. */\ninterface Placed<D> {\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n}\n\n/** One x: a focus stop with its hit column, and a point per series. A row isn't a mark itself. */\ninterface RowRecord<D> {\n readonly key: string;\n /** Where the row is heading, or rests: its row in the latest layout (its last one while it folds away). */\n row: LineRow<D>;\n /** In data units, so every frame reads true against the axes. */\n readonly x: Animated<number>;\n readonly values: Animated<Values>;\n /** 0 to 1: how far it has grown out of its anchor, or is left before it has folded into it. */\n readonly presence: Animated<number>;\n /** The row it grows out of or folds into: the nearest row that stays, before it or else after it. */\n anchor: RowRecord<D> | undefined;\n /** The focus stop: an image named for the x, holding the hit column. */\n readonly column: SVGGElement;\n readonly hit: SVGRectElement;\n /** Its points, live or leaving, live ones in series order first. */\n points: PointRecord<D>[];\n /** Set while it folds away. */\n leaving: boolean;\n /** Whether its column is shown: live and revealed. */\n shown: boolean;\n /** Where its x is drawn now, px: the crosshair's place when it has no point. */\n px: number;\n}\n\ninterface MarkBase<D> {\n readonly key: string;\n readonly series: string;\n readonly group: SVGGElement;\n /** Holds the stroke or the dot; effects' transform and opacity go here. */\n readonly body: SVGGElement;\n readonly path: SVGPathElement;\n parts: StyledPart[];\n readonly handle: SvgMarkHandle;\n /** Where it's heading, as laid out at the reveal: what enter and update report as a change starts. */\n target: Placed<D>;\n /** What's on screen now. */\n shown: Placed<D>;\n /** Set while it leaves. */\n leave: Leave | undefined;\n}\n\ninterface LineRecord<D> extends MarkBase<D> {\n readonly kind: \"line\";\n /** The dot at its revealed end. */\n readonly end: SVGCircleElement;\n readonly label: SVGTextElement;\n /** Where the end label is drawn now; undefined while it shows none. */\n drawnLabel: TextPlacement | undefined;\n /** 0 to 1: a series entering or leaving fades its line in or out. */\n readonly presence: Animated<number>;\n}\n\ninterface PointRecord<D> extends MarkBase<D> {\n readonly kind: \"point\";\n row: RowRecord<D>;\n /**\n * Past the reveal: hidden, overlays and all. Undefined until it's first drawn, so a new point sets\n * its overlays' visibility whatever a gone point with its key left there.\n */\n hidden: boolean | undefined;\n}\n\ntype MarkRecord<D> = LineRecord<D> | PointRecord<D>;\n\ninterface TickRecord {\n readonly value: number;\n /** A value's gridline; x ticks have none. */\n readonly line: SVGLineElement | undefined;\n readonly label: SVGTextElement;\n /** An x tick's text in its latest layout: a time's depends on the step. A value's is worded by `format` as it's drawn. */\n text: string;\n /** Ticks a scale gains fade in, and ones it loses fade out. */\n readonly opacity: Animated<number>;\n /** In the latest layout. */\n wanted: boolean;\n}\n\n/** What an update changed, by mark. */\ntype Diff<D> = ChartDiff<MarkRecord<D>>;\n\n/** What an update changed, by x: what the announcement says. */\ninterface RowChanges<D> {\n readonly changed: RowRecord<D>[];\n readonly added: RowRecord<D>[];\n readonly removed: RowRecord<D>[];\n}\n\n/** Base ms for each stage of a data change: values, then positions. Unstaged, a change takes as long as its stages together, which analysis scales down. */\nconst STAGE = 500;\n/** The focus ring's px: a gap in the surface colour around the point, then the ring. */\nconst RING_GAP = 2;\nconst RING = 2;\n/** A walk shorter than this draws nothing, as effects treat it. */\nconst VISIBLE = 0.5;\n\nexport function lineChart<D>(target: string | Element, options: LineChartOptions<D>, env: ChartEnv): LineChart<D> {\n const container = resolveTarget(target, \"lineChart\");\n checkChartOptions(options, \"lineChart\");\n let current = options;\n const motion = chartMotion(options.motion, env.motion);\n let effects = resolveEffects(options.on, env.presets);\n let colors = toColorAssignment(options.colors);\n const clock = env.clock ?? defaultClock;\n const doc = container.ownerDocument;\n injectStyles(doc);\n\n // A named group of x's, each an image with its own name; the lines and points are aria-hidden:\n // see \"ARIA structure\" in docs/architecture.md.\n const svg = svgElement(\"svg\", { class: \"ec-chart ec-line-chart\", role: \"group\" }, container);\n const grid = svgElement(\"g\", { class: \"ec-grid\", \"aria-hidden\": \"true\" }, svg);\n const axis = svgElement(\"g\", { class: \"ec-axis\", \"aria-hidden\": \"true\" }, svg);\n const crosshair = svgElement(\"line\", { class: \"ec-crosshair\", \"aria-hidden\": \"true\", visibility: \"hidden\" }, svg);\n // Behind the marks, so it can't cover them; the gap keeps it apart from a point in the same colour.\n const ring = svgElement(\"g\", { class: \"ec-focus\", \"aria-hidden\": \"true\", visibility: \"hidden\" }, svg);\n const marksLayer = svgElement(\"g\", { class: \"ec-marks\", \"aria-hidden\": \"true\" }, svg);\n const linesLayer = svgElement(\"g\", { class: \"ec-lines\" }, marksLayer);\n const pointsLayer = svgElement(\"g\", { class: \"ec-points\" }, marksLayer);\n // Above the marks: the pointer's targets and the focus stops.\n const columnsLayer = svgElement(\"g\", { class: \"ec-columns\" }, svg);\n const overlay = svgElement(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" }, svg);\n const measure = textMeasure(svg);\n\n /** Live rows, in ascending x. */\n let rowOrder: RowRecord<D>[] = [];\n const rows = new Map<string, RowRecord<D>>();\n /** Rows folding away: drawn until the change lands. */\n const leavingRows = new Map<string, RowRecord<D>>();\n const byColumn = new WeakMap<Element, RowRecord<D>>();\n /** Live lines, in series order. */\n let lineOrder: LineRecord<D>[] = [];\n const lines = new Map<string, LineRecord<D>>();\n const points = new Map<string, PointRecord<D>>();\n /** Lines and points on their way out: fading, or waiting for their exit effects. */\n const leaving = leavingMarks<MarkRecord<D>>((record) =>\n record.kind === \"line\" ? record.presence.animating : record.row.presence.animating || record.row.values.animating || record.row.x.animating\n );\n const events = chartEvents<D>(\"lineChart\");\n let measuredWidth = containerWidth(container);\n let destroyed = false;\n /** The x the page last revealed to, unclamped: Infinity shows every row, rows added later too. */\n let through = Infinity;\n /** Labels whose function threw, reported once: they're worded on every frame. */\n const labelFailures = new WeakSet<object>();\n\n let laidOut: LineLayout<D>;\n let firstTable: TableModel | undefined;\n /** Each x's accessible name, by row key, for the latest layout. */\n let names: ReadonlyMap<string, string>;\n try {\n // Throws on data it can't draw, a table column it can't read, or a `format` that throws. Nothing\n // but the <svg> is in place yet (no listeners, observers or elements beside it), so that's all to undo.\n laidOut = layout(current);\n firstTable = tableFor(current, laidOut);\n names = namesFor(current, laidOut);\n } catch (error) {\n svg.remove();\n throw error;\n }\n\n const findMark = (key: string): MarkRecord<D> | undefined => points.get(key) ?? lines.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay,\n // Looked up on each call, so the handle follows the mark's record.\n mark: (key) => ({\n set: (style) => {\n findMark(key)?.handle.set(style);\n hover.restyled(key);\n },\n reset: () => {\n findMark(key)?.handle.reset();\n hover.restyled(key);\n }\n }),\n colors: (key) => findMark(key)?.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const tooltip = chartTooltip<D>(svg, { motion, option: () => current.tooltip, description: () => current.markDescription });\n const legend = chartLegend(svg);\n const table = chartTable(svg);\n let announcer: Announcer | undefined = current.announce ? chartAnnouncer(svg) : undefined;\n\n // ── Animated state ─────────────────────────────────────────────────────────\n // Each row has its x, its values and its presence, and the chart has the scale and the box, so a\n // new update() mid-flight retargets each from where it is and nothing jumps. Where a line is comes\n // from them: through every row as it is now, up to the reveal.\n\n /** Something moved since the last frame was drawn. A line depends on every row, so a frame draws everything. */\n let dirty = false;\n const changed = (): void => {\n dirty = true;\n };\n const scale = animated(laidOut.frame.scale, interpolateRecord, { clock, motion, onChange: changed });\n const box = animated(laidOut.frame.box, interpolateRecord, { clock, motion, onChange: changed });\n const yTicks = new Map<number, TickRecord>();\n const xTicks = new Map<number, TickRecord>();\n /** Per series, the decimals an end label counts in: the values' own, or both sides' while a change plays. */\n let counting: Readonly<Record<string, number>> = laidOut.decimals;\n /** What the latest update changed, by x, for its announcement. */\n let rowChanges: RowChanges<D> = { changed: [], added: [], removed: [] };\n /** The frame last drawn, for the crosshair. */\n let drawnFrame: LineFrame = laidOut.frame;\n\n const transitions = chartTransitions({ clock, runner, leaving, draw, land });\n\n // ── Layout ─────────────────────────────────────────────────────────────────\n\n function layout(opts: LineChartOptions<D>, using = effects): LineLayout<D> {\n const encoding = lineEncoding(opts);\n const series = encoding.series.map((s) => s.series);\n checkNeeds(using, series, \"lineChart\");\n const next = layoutLines({ data: opts.data, encoding, width: opts.width ?? measuredWidth, height: opts.height, format: format(opts), measure, label: labeler(opts, true) });\n // A series named \"a@b\" and a key \"c\" make the same point key as \"a\" and \"b@c\".\n const keys = new Set(next.series);\n for (const row of next.rows) {\n for (const name of next.series) {\n const key = pointKey(name, row.key);\n if (keys.has(key)) throw new RangeError(`lineChart: two marks would have the key \"${key}\". Series and keys joined with \"@\" must be unique.`);\n keys.add(key);\n }\n }\n // focus(key) takes an x's key or a point's: a row keyed \"goals@2\" beside a row \"2\" would make the point ambiguous.\n for (const row of next.rows) {\n if (keys.has(row.key)) throw new RangeError(`lineChart: the key \"${row.key}\" would name both an x and a line or point. A row's key can't be a series, or a series and a key joined with \"@\".`);\n }\n return next;\n }\n\n /**\n * A line's end label for a value: `labels`' text, or by default the value in `format` with its\n * series' label (\"52 goals\"). Undefined with `labels: false`. A function that throws keeps the\n * default, and is reported once, unless `quiet` (the layout measuring).\n */\n function labeler(opts: LineChartOptions<D>, quiet = false): ((series: string, value: number) => string) | undefined {\n const { labels } = opts;\n if (labels === false) return undefined;\n const formatted = format(opts);\n return (series, value) => {\n const text = `${formatted(value)} ${seriesLabel(opts.seriesLabels, series)}`;\n if (typeof labels !== \"function\") return text;\n try {\n const own: unknown = labels(value, series, formatted);\n return own === undefined || own === null ? \"\" : String(own);\n } catch (error) {\n if (!quiet && !labelFailures.has(labels)) {\n labelFailures.add(labels);\n report(error);\n }\n return text;\n }\n };\n }\n\n /**\n * The end labels' wording for placeLines, each value rounded to its series' decimals in `given`:\n * `counting` while a change plays, or a layout's own at rest, which `counting` becomes when it\n * lands. So a line revealed part way between rows says the same at rest as in the frame before.\n * Undefined with `labels: false`.\n */\n function endLabels(given: Readonly<Record<string, number>>): EndLabels | undefined {\n const label = labeler(current);\n if (!label) return undefined;\n return { text: (series, value) => label(series, round(value, given[series] ?? decimals(value))), measure };\n }\n\n /** Each line and point as laid out in `next`, at the reveal, the lines with their end labels. */\n function placedFor(next: LineLayout<D>): { readonly lines: Map<string, PlacedLine<D>>; readonly points: Map<string, PlacedPoint<D>> } {\n const states = next.rows.map(restState);\n return {\n lines: new Map(placeLines(next.frame, states, next.series, drawnThrough(next), next.time, endLabels(next.decimals)).map((line) => [line.series, line])),\n points: new Map(states.flatMap((state) => placePoints(next.frame, state, next.series, next.time)).map((point) => [point.key, point]))\n };\n }\n\n /** The reveal in `next`: clamped to its rows' range. */\n function revealedIn(next: LineLayout<D>): number {\n const first = next.rows[0];\n const last = next.rows[next.rows.length - 1];\n return first && last ? Math.min(Math.max(through, first.x), last.x) : through;\n }\n\n /**\n * Where lines end: at the reveal, or with every row drawn when it's at the end of `next`'s rows,\n * so rows that fold away past the new last one stay drawn while they fold.\n */\n function drawnThrough(next: LineLayout<D>): number {\n const last = next.rows[next.rows.length - 1];\n return last && through < last.x ? revealedIn(next) : Infinity;\n }\n\n /** Live, and at or before the reveal. */\n const revealed = (record: RowRecord<D>): boolean => !record.leaving && record.row.x <= revealedIn(laidOut);\n\n // ── Records ────────────────────────────────────────────────────────────────\n\n /** A new row: at its place or, when it enters, waiting to grow out of its anchor. */\n function createRow(row: LineRow<D>, entering: boolean): RowRecord<D> {\n const column = svgElement(\"g\", { class: \"ec-column\", \"data-key\": row.key, role: \"img\" }, columnsLayer);\n const env = { clock, motion, onChange: changed };\n const record: RowRecord<D> = {\n key: row.key,\n row,\n column,\n hit: svgElement(\"rect\", { class: \"ec-hit\" }, column),\n x: animated(row.x, interpolateNumber, env),\n values: animated(row.levels, interpolateRecord, env),\n presence: animated(entering ? 0 : 1, interpolateNumber, env),\n anchor: undefined,\n points: [],\n leaving: false,\n shown: true,\n px: 0\n };\n byColumn.set(column, record);\n return record;\n }\n\n function createLine(series: string, placed: PlacedLine<D>, entering: boolean): LineRecord<D> {\n const group = svgElement(\"g\", { class: \"ec-line\", \"data-key\": series, \"data-series\": series }, linesLayer);\n const body = svgElement(\"g\", { class: \"ec-body\" }, group);\n const record: LineRecord<D> = {\n kind: \"line\",\n key: series,\n series,\n group,\n body,\n path: svgElement(\"path\", { class: \"ec-stroke\", \"stroke-width\": LINE_WIDTH }, body),\n end: svgElement(\"circle\", { class: \"ec-end\", r: DOT_RADIUS }, body),\n label: svgElement(\"text\", { class: \"ec-value ec-end-label\" }, group),\n drawnLabel: undefined,\n parts: [],\n handle: svgMarkHandle(() => record),\n target: placed,\n shown: placed,\n presence: animated(entering ? 0 : 1, interpolateNumber, { clock, motion, onChange: changed }),\n leave: undefined\n };\n return record;\n }\n\n function createPoint(row: RowRecord<D>, placed: PlacedPoint<D>): PointRecord<D> {\n const group = svgElement(\"g\", { class: \"ec-point\", \"data-key\": placed.key, \"data-series\": placed.series }, pointsLayer);\n const body = svgElement(\"g\", { class: \"ec-body\" }, group);\n const record: PointRecord<D> = {\n kind: \"point\",\n key: placed.key,\n series: placed.series,\n row,\n group,\n body,\n path: svgElement(\"path\", { class: \"ec-dot\" }, body),\n parts: [],\n handle: svgMarkHandle(() => record),\n target: placed,\n shown: placed,\n hidden: undefined,\n leave: undefined\n };\n return record;\n }\n\n /** On screen: live, or leaving and not yet gone. */\n const drawn = (record: MarkRecord<D>): boolean => findMark(record.key) === record;\n /** The row's live points, in series order. */\n const livePoints = (record: RowRecord<D>): PointRecord<D>[] => record.points.filter((point) => points.get(point.key) === point);\n const leavingLines = (): LineRecord<D>[] => [...leaving.values()].filter((record): record is LineRecord<D> => record.kind === \"line\");\n\n // ── Drawing ────────────────────────────────────────────────────────────────\n\n const currentFrame = (): LineFrame => ({ scale: scale.value, box: box.value });\n\n /**\n * Every row drawn, as it is now, in ascending x: a row growing in or folding away is part way\n * between its anchor and its own place. A row that has folded away, or leaves with nothing to fold\n * into, isn't drawn.\n */\n function currentRows(): { readonly record: RowRecord<D>; readonly state: RowState<D> }[] {\n const own = (record: RowRecord<D>): { x: number; values: Values } => ({ x: record.x.value, values: record.values.value });\n const states = new Map<RowRecord<D>, { x: number; values: Values }>();\n const visiting = new Set<RowRecord<D>>();\n const stateOf = (record: RowRecord<D>): { x: number; values: Values } => {\n const known = states.get(record);\n if (known) return known;\n const p = record.presence.value;\n let state = own(record);\n // An anchor chain can loop back (a row folding into one that grew out of it): the loop's start is drawn at its own place.\n if (record.anchor && p < 1 && !visiting.has(record)) {\n visiting.add(record);\n const from = stateOf(record.anchor);\n visiting.delete(record);\n state = { x: from.x + p * (state.x - from.x), values: interpolateRecord(from.values, state.values)(p) };\n }\n states.set(record, state);\n return state;\n };\n const drawnRows = [...rowOrder, ...[...leavingRows.values()].filter((record) => record.presence.value > 0 && record.anchor)];\n // A gap opens or closes as the change starts: the rows' missing values are where they're heading.\n return drawnRows\n .map((record) => {\n const { x, values } = stateOf(record);\n return { record, state: { key: record.key, datum: record.row.datum, x, values, missing: record.row.missing } };\n })\n .sort((a, b) => a.state.x - b.state.x);\n }\n\n /** Draws a frame of the change in flight. */\n function draw(): void {\n if (!dirty) return;\n dirty = false;\n const frame = currentFrame();\n const states = currentRows();\n paintFrame(frame);\n paintLines(frame, states.map((s) => s.state));\n for (const { record, state } of states) {\n const placed = new Map(placePoints(frame, state, record.points.map((point) => point.series), laidOut.time).map((point) => [point.key, point]));\n // A point whose value went missing stays where it was while it leaves.\n showAll(record.points.filter(drawn).flatMap((point) => (placed.has(point.key) ? [{ record: point, placed: placed.get(point.key)! }] : [])));\n }\n paintAlone(states.map((s) => s.state));\n paintColumns(frame, states);\n followHover();\n }\n\n /** Draws a new reveal: the lines and their labels end at it, and the x's past it are hidden. Nothing else moves. */\n function drawReveal(): void {\n const frame = currentFrame();\n const states = currentRows();\n paintLines(frame, states.map((s) => s.state));\n paintColumns(frame, states);\n followHover();\n }\n\n /** Draws exactly the layout once a change settles: the frames in between are computed, this is laid out. */\n function land(): void {\n for (const record of leavingRows.values()) {\n for (const value of [record.x, record.values, record.presence]) value.stop();\n record.column.remove();\n }\n leavingRows.clear();\n for (const record of rowOrder) {\n record.anchor = undefined;\n record.points = record.points.filter(drawn);\n }\n for (const [ticks, placedTicks] of [\n [yTicks, laidOut.yTicks],\n [xTicks, laidOut.xTicks]\n ] as const) {\n for (const tick of [...ticks.values()]) {\n if (tick.wanted) continue;\n tick.line?.remove();\n tick.label.remove();\n ticks.delete(tick.value);\n }\n for (const placed of placedTicks) {\n const tick = ticks.get(placed.value);\n if (!tick) continue;\n if (tick.line && \"line\" in placed) setAttributes(tick.line, { ...placed.line, opacity: undefined });\n placeText(tick.label, placed.label);\n tick.label.removeAttribute(\"opacity\");\n }\n }\n counting = laidOut.decimals;\n const { frame } = laidOut;\n setAttributes(svg, sizeAttributes(frame.box));\n drawnFrame = frame;\n // As laid out, keeping the objects enter and update reported while they're the same. Marks whose\n // data link to each other through `related` (the lines; a row's points) are kept or replaced together.\n const placed = placedFor(laidOut);\n const settle = <R extends MarkRecord<D>>(records: readonly R[], next: (record: R) => Placed<D> | undefined): void => {\n const pairs = records.flatMap((record) => {\n const to = next(record);\n return to ? [{ record, to }] : [];\n });\n const kept = pairs.every(({ record, to }) => sameGeometry(record.target.geometry, to.geometry) && sameData(record.target.data, to.data));\n if (!kept) for (const { record, to } of pairs) record.target = to;\n showAll(pairs.map(({ record }) => ({ record, placed: record.target })));\n };\n settle(lineOrder, (line) => placed.lines.get(line.series));\n paintLabels(new Map(lineOrder.flatMap((line) => (placed.lines.has(line.series) ? [[line, placed.lines.get(line.series)!] as const] : []))));\n const states = rowOrder.map((record) => ({ record, state: restState(record.row) }));\n for (const { record } of states) settle(livePoints(record), (point) => placed.points.get(point.key));\n paintAlone(states.map((s) => s.state));\n paintColumns(frame, states);\n followHover();\n dirty = false;\n }\n\n /** The <svg>'s size and the ticks, as the frame has them. */\n function paintFrame(frame: LineFrame): void {\n drawnFrame = frame;\n setAttributes(svg, sizeAttributes(frame.box));\n const formatted = format(current);\n for (const tick of yTicks.values()) {\n const placed = placeYTick(frame, tick.value, formatted(tick.value));\n const opacity = tick.opacity.value < 1 ? tick.opacity.value : undefined;\n setAttributes(tick.line!, { ...placed.line, opacity });\n placeText(tick.label, placed.label);\n setAttributes(tick.label, { opacity });\n }\n for (const tick of xTicks.values()) {\n placeText(tick.label, placeXTick(frame, tick.value, tick.text).label);\n setAttributes(tick.label, { opacity: tick.opacity.value < 1 ? tick.opacity.value : undefined });\n }\n }\n\n /** Draws the lines (live and leaving) through the rows as they are, up to the reveal, and their end labels. */\n function paintLines(frame: LineFrame, states: readonly RowState<D>[]): void {\n const drawnLines = [...lineOrder, ...leavingLines()];\n if (states.length === 0 || drawnLines.length === 0) return;\n const placed = placeLines(frame, states, drawnLines.map((line) => line.series), drawnThrough(laidOut), laidOut.time, endLabels(counting));\n showAll(drawnLines.map((line, i) => ({ record: line, placed: placed[i]! })));\n paintLabels(new Map(drawnLines.map((line, i) => [line, placed[i]!])));\n }\n\n /** Each line's end label as placeLines placed it, counting between values, kept 16 px apart; or none with `labels: false`. */\n function paintLabels(ends: ReadonlyMap<LineRecord<D>, PlacedLine<D>>): void {\n for (const [line, { label: text }] of ends) {\n if (text) placeText(line.label, text);\n line.drawnLabel = text && text.text !== \"\" ? text : undefined;\n setAttributes(line.label, { visibility: line.drawnLabel ? undefined : \"hidden\" });\n }\n }\n\n /**\n * Draws each mark as placed. Their data link to each other through `related` (the lines; a row's\n * points), so when any one's data changed, every one's runs hear about it with the new data: a\n * threshold on the goals line follows a change to xG alone.\n */\n function showAll(marks: readonly { readonly record: MarkRecord<D>; readonly placed: Placed<D> }[]): void {\n const related = marks.some(({ record, placed }) => !sameData(record.shown.data, placed.data));\n for (const { record, placed } of marks) {\n if (record.kind === \"line\") showLine(record, placed, related);\n else showPoint(record, placed, related);\n }\n }\n\n /** Draws the line as `placed`, with its end dot. Its runs hear about it when it moved or `related` data changed, so decorations follow. */\n function showLine(record: LineRecord<D>, placed: Placed<D>, related: boolean): void {\n const moved = related || geometryChanged(record.shown.geometry, placed.geometry);\n record.shown = placed;\n const { geometry } = placed;\n paint(record, seriesColors(colors.slot(record.series)), { visible: geometry.length >= VISIBLE, open: { width: geometry.thickness } });\n // A line with no value up to the reveal is empty: no end dot.\n setAttributes(record.end, { cx: geometry.end.x, cy: geometry.end.y, visibility: placed.data.samples.length === 0 ? \"hidden\" : undefined });\n const presence = record.presence.value;\n setAttributes(record.group, { opacity: presence < 1 ? presence : undefined });\n if (moved) runner.change(geometry, placed.data);\n }\n\n /** Draws the point as `placed`. Its runs hear about it when it moved or `related` data changed. */\n function showPoint(record: PointRecord<D>, placed: Placed<D>, related: boolean): void {\n const moved = related || geometryChanged(record.shown.geometry, placed.geometry);\n record.shown = placed;\n paint(record, seriesColors(colors.slot(record.series)), { visible: true });\n if (moved) runner.change(placed.geometry, placed.data);\n }\n\n /** Writes the mark's outline and colours, and applies its style again, when either changed. */\n function paint(record: MarkRecord<D>, markColors: SeriesColors, part: Pick<StyledPart, \"visible\" | \"open\">): void {\n const before = record.parts[0];\n const { d } = record.shown.geometry.outline;\n const recolored = before?.colors.color !== markColors.color;\n if (!recolored && before?.d === d && before.visible === part.visible && before.open?.width === part.open?.width) return;\n if (record.path.getAttribute(\"d\") !== d) record.path.setAttribute(\"d\", d);\n if (recolored) setStyles(record.group, markColorStyles(markColors));\n record.parts = [{ element: record.path, d, colors: markColors, ...part }];\n record.handle.repaint();\n // A new palette: overlays already drawn in \"mark\" follow.\n if (before && recolored) surface.recolor(record.key);\n }\n\n /** Whether a point showed at rest in the frame before: a chart with no gaps skips the points. */\n let anyAlone = false;\n\n /** A value with a gap on either side and no other value beside it has no stroke, so its point shows at rest. */\n function paintAlone(states: readonly RowState<D>[]): void {\n const lone = loneValues(states, laidOut.series);\n if (lone.size === 0 && !anyAlone) return;\n for (const point of points.values()) point.group.classList.toggle(\"ec-alone\", lone.has(point.key));\n anyAlone = lone.size > 0;\n }\n\n /**\n * Each revealed x's hit column, halfway to its neighbours, at the rows as they are; and the points\n * past the reveal hidden, their overlays too. A column that isn't live or revealed is hidden, so it\n * can't be hovered or focused.\n */\n function paintColumns(frame: LineFrame, states: readonly { readonly record: RowRecord<D>; readonly state: RowState<D> }[]): void {\n const { x } = positions(frame);\n const shown = states.filter(({ record }) => revealed(record));\n const columns = placeColumns(frame, shown.map(({ state }) => x(state.x)));\n shown.forEach(({ record, state }, i) => {\n setAttributes(record.hit, { ...columns[i]! });\n record.px = x(state.x);\n });\n const visible = new Set(shown.map(({ record }) => record));\n for (const record of [...rowOrder, ...leavingRows.values()]) {\n const show = visible.has(record);\n if (record.shown !== show) {\n record.shown = show;\n setAttributes(record.column, { visibility: show ? undefined : \"hidden\", \"aria-hidden\": record.leaving ? \"true\" : undefined });\n }\n const hidden = !revealed(record);\n for (const point of record.points) {\n if (point.hidden === hidden) continue;\n point.hidden = hidden;\n setAttributes(point.group, { visibility: hidden ? \"hidden\" : undefined });\n surface.hide(point.key, hidden);\n }\n }\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /**\n * The crosshair at the hovered x, and the tooltip above its highest point, as they are on screen.\n * An x with every value missing has no point: the tooltip sits at the crosshair's top.\n */\n function showHover(key: string): void {\n const record = rows.get(key);\n if (!record || !revealed(record)) return;\n const marks = livePoints(record);\n const x = marks[0]?.shown.geometry.center.x ?? record.px;\n setAttributes(crosshair, { ...placeCrosshair(drawnFrame, x), visibility: undefined });\n // Moved with each point's effects, as the focus ring is.\n const ys = marks.map((point) => {\n const { transform } = point.handle.style;\n const { center } = point.shown.geometry;\n return (transform ? matrix.apply(transform, center) : center).y;\n });\n const { row } = record;\n const at = ys.length > 0 ? { top: Math.min(...ys) - DOT_RADIUS, bottom: Math.max(...ys) + DOT_RADIUS } : { top: drawnFrame.box.top, bottom: drawnFrame.box.top };\n tooltip.showAt({ x, ...at }, row, () => summary(row, current));\n }\n\n function hideHover(): void {\n crosshair.setAttribute(\"visibility\", \"hidden\");\n tooltip.hide();\n }\n\n /** The focus at an x with every value missing, in `ring` while it shows there. */\n let ringLine: SVGLineElement | undefined;\n\n /**\n * A ring round each point at the focused x, as it is on screen, moved with its body when an effect\n * moves it. An x with every value missing has no point to ring: a line in the ring's colour shows\n * its focus where the crosshair is, and stays when Escape hides the crosshair.\n */\n function drawRing(key: string | undefined): void {\n const record = key === undefined ? undefined : rows.get(key);\n const live = record !== undefined && revealed(record);\n const marks = live ? livePoints(record) : [];\n if (live && marks.length === 0) {\n ringLine ??= svgElement(\"line\", { class: \"ec-focus-ring\", \"stroke-width\": RING }, ring);\n if (ring.childElementCount > 1 || ring.firstElementChild !== ringLine) ring.replaceChildren(ringLine);\n setAttributes(ringLine, placeCrosshair(drawnFrame, record.px));\n ring.removeAttribute(\"visibility\");\n return;\n }\n ringLine?.remove();\n while (ring.childElementCount > marks.length) ring.lastElementChild!.remove();\n marks.forEach((point, i) => {\n let group = ring.children[i] as SVGGElement | undefined;\n if (!group) {\n group = svgElement(\"g\", {}, ring);\n svgElement(\"path\", { class: \"ec-focus-ring\", \"stroke-width\": 2 * (RING_GAP + RING) }, group);\n svgElement(\"path\", { class: \"ec-focus-gap\", \"stroke-width\": 2 * RING_GAP }, group);\n }\n for (const path of Array.from(group.children)) path.setAttribute(\"d\", point.shown.geometry.outline.d);\n const { transform } = point.handle.style;\n setAttributes(group, { transform: transform && transformAttribute(transform) });\n });\n setAttributes(ring, { visibility: marks.length > 0 ? undefined : \"hidden\" });\n }\n\n /** The tooltip, crosshair and ring follow the hovered and focused x as it moves. */\n function followHover(): void {\n if (hover.key !== undefined) showHover(hover.key);\n if (hover.ringKey !== undefined) drawRing(hover.ringKey);\n }\n\n /** Where a mark is heading: what enter and update report as a change starts. */\n const input = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.target.geometry, data: record.target.data });\n /** The mark as it is on screen: what hover, leave and exit report, so mid-change they match what's under the pointer or on its way out. */\n const onScreen = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.shown.geometry, data: record.shown.data });\n\n /** The row a column belongs to; leaving and hidden rows don't count. */\n function liveRowOf(eventTarget: EventTarget | null): RowRecord<D> | undefined {\n const element = eventTarget as Element | null;\n const column = typeof element?.closest === \"function\" ? element.closest(\".ec-column\") : null;\n const record = column ? byColumn.get(column) : undefined;\n return record && rows.get(record.key) === record && revealed(record) ? record : undefined;\n }\n\n // Pointer, touch and keyboard focus share one hover: see shell/hover.ts. An x is the target, and\n // stands for each series' point there. Nothing dims: every series is read at once.\n const hover = chartHover<D>({\n svg,\n runner,\n events,\n dim: () => false,\n find(eventTarget) {\n const record = liveRowOf(eventTarget);\n return record && { key: record.key };\n },\n live(key) {\n const record = rows.get(key);\n return record !== undefined && revealed(record);\n },\n order: () => rowOrder.filter(revealed).map((record) => record.key),\n // On a time axis a page is a calendar month in its zone: the first x a month or more on, or back,\n // or the last one that way. On numbers it's the keyboard's own.\n page(key, by) {\n const from = rows.get(key);\n if (!laidOut.time || !from) return undefined;\n const stops = rowOrder.filter(revealed);\n const to = monthsOn(from.row.x, by, lineEncoding(current).timeZone);\n if (by > 0) return (stops.find((record) => record.row.x >= to) ?? stops[stops.length - 1])?.key;\n for (let i = stops.length - 1; i >= 0; i--) if (stops[i]!.row.x <= to) return stops[i]!.key;\n return stops[0]?.key;\n },\n marks: (key) => {\n const record = rows.get(key);\n return record ? livePoints(record).map((point) => point.key) : [];\n },\n element: (key) => (rows.get(key) ?? leavingRows.get(key))?.column,\n markElement: (key) => findMark(key)?.group,\n onScreen(key) {\n const record = findMark(key);\n return record && onScreen(record);\n },\n ring: drawRing,\n tooltip: { show: showHover, hide: hideHover, element: () => tooltip.element() }\n });\n\n // ── Changes ────────────────────────────────────────────────────────────────\n\n const syncLegend = (): void =>\n legend.update(\n laidOut.series.map((series) => ({ series, label: seriesLabel(current.seriesLabels, series) })),\n colors,\n current.legend\n );\n\n /** The data table for `opts`, laid out as `next`: a row per x, the x, each series and no total. Throws on a column it can't read. */\n function tableFor(opts: LineChartOptions<D>, next: LineLayout<D>): TableModel | undefined {\n return tableModel({\n option: opts.table,\n caption: opts.label,\n category: typeof opts.x === \"string\" ? opts.x : undefined,\n series: next.series,\n label: (series) => seriesLabel(opts.seriesLabels, series),\n rows: next.rows.map((row) => ({ key: row.key, category: row.label, datum: row.datum, index: row.index, values: present(row.values), missing: row.missing, total: total(row.values) })),\n format: format(opts),\n total: false\n });\n }\n\n /** The x's accessible name, from where it's heading, and its description (`markDescription`, or a tooltip function's text). */\n function labelColumn(record: RowRecord<D>): void {\n record.column.setAttribute(\"aria-label\", names.get(record.key)!);\n tooltip.describe(record.column, record.row);\n }\n\n /** Says what an update changed, in the live region: the chart's summary, or the page's text from it. */\n function announceChange(previous: LineChartOptions<D>, before: readonly string[]): void {\n const option = current.announce;\n if (!announcer || !option) return;\n const series = laidOut.series;\n const name = (record: RowRecord<D>): string => record.row.label;\n const { changed: values, added, removed } = rowChanges;\n const text = changeText({\n ...(current.label !== previous.label ? { label: current.label } : {}),\n // New series are said by their labels; new labels alone show the same view, so say nothing.\n ...(series.join(\"\\n\") !== before.join(\"\\n\") ? { series: series.map((s) => seriesLabel(current.seriesLabels, s)) } : {}),\n changed: values.map(name),\n added: added.map(name),\n removed: removed.map(name),\n count: rowOrder.length\n });\n if (typeof option !== \"function\") {\n announcer.say(text);\n return;\n }\n const key = (record: RowRecord<D>): string => record.key;\n try {\n const said = option({ text, changed: values.map(key), added: added.map(key), removed: removed.map(key) });\n if (said !== undefined && said !== null) announcer.say(String(said));\n } catch (error) {\n report(error);\n }\n }\n\n /**\n * Matches the layout's rows, series and points to records by key. New rows grow out of the nearest\n * row that stays (before them, or else after), and rows that go fold into theirs. A line gets\n * `update` when any of its values or rows changed, a point when its own value did; a new row's\n * points enter, a removed row's exit, and so do a series' line and points.\n */\n function arrange(next: LineLayout<D>): Diff<D> {\n laidOut = next;\n const placed = placedFor(next);\n const diff: Diff<D> = { entering: [], exiting: [], changed: [] };\n const keys = new Set(next.rows.map((row) => row.key));\n const series = next.rows.length > 0 ? next.series : [];\n const changes: RowChanges<D> = { changed: [], added: [], removed: [] };\n\n // What goes: lines first, then points by x.\n const before = rowOrder;\n const was = new Map(before.map((record) => [record, record.row]));\n const nextRows = new Map(next.rows.map((row) => [row.key, row]));\n const exitingLines = lineOrder.filter((line) => !series.includes(line.series));\n const exitingPoints: PointRecord<D>[] = [];\n for (const record of before) {\n const goes = !keys.has(record.key);\n const missing = nextRows.get(record.key)?.missing;\n if (goes) {\n rows.delete(record.key);\n record.leaving = true;\n leavingRows.set(record.key, record);\n changes.removed.push(record);\n }\n // A point goes with its row, its series, or its value.\n for (const point of livePoints(record)) if (goes || !series.includes(point.series) || missing?.has(point.series)) exitingPoints.push(point);\n }\n for (const line of exitingLines) lines.delete(line.series);\n for (const point of exitingPoints) points.delete(point.key);\n for (const record of [...exitingLines, ...exitingPoints]) leaving.start(record);\n diff.exiting.push(...exitingLines, ...exitingPoints);\n\n // The rows, matched by key.\n const stayed = new Set<RowRecord<D>>();\n let rowsMoved = changes.removed.length > 0;\n rowOrder = next.rows.map((row) => {\n let record = rows.get(row.key);\n if (record) {\n stayed.add(record);\n if (record.row.x !== row.x) rowsMoved = true;\n if (row.values.some((v, i) => record!.row.values[i]?.series !== v.series || record!.row.values[i]?.value !== v.value)) changes.changed.push(record);\n } else {\n // A row that comes back mid-fold keeps its record, and grows back from where it is.\n record = leavingRows.get(row.key) ?? createRow(row, true);\n leavingRows.delete(row.key);\n record.leaving = false;\n record.x.set(row.x);\n record.values.set(row.levels);\n rows.set(row.key, record);\n changes.added.push(record);\n rowsMoved = true;\n }\n record.row = row;\n return record;\n });\n rowOrder.forEach((record, i) => {\n if (!stayed.has(record)) record.anchor = nearest(rowOrder, i, stayed);\n else if (record.presence.value === 1) record.anchor = undefined;\n });\n for (const record of changes.removed) record.anchor ??= nearest(before, before.indexOf(record), stayed);\n\n // The lines: a line changed when its rows did, or any of its values.\n const previousLines = lineOrder;\n lineOrder = series.map((name) => {\n let line = lines.get(name);\n const target = placed.lines.get(name)!;\n if (line) {\n const values = [...stayed].some((record) => valueIn(was.get(record)!, name) !== valueIn(record.row, name));\n if (rowsMoved || values) diff.changed.push({ record: line, from: line.shown.geometry });\n } else {\n line = recall<LineRecord<D>>(name, \"line\") ?? createLine(name, target, true);\n lines.set(name, line);\n diff.entering.push(line);\n }\n line.target = target;\n return line;\n });\n\n // The points, by x: a point changed when its own value did. A missing value has none.\n for (const record of rowOrder) {\n const old = stayed.has(record) ? was.get(record) : undefined;\n const live = series.filter((name) => !record.row.missing.has(name)).map((name) => {\n const key = pointKey(name, record.key);\n const target = placed.points.get(key)!;\n let point = points.get(key);\n if (point) {\n if (old && valueIn(old, name) !== valueIn(record.row, name)) diff.changed.push({ record: point, from: point.shown.geometry });\n } else {\n point = recall<PointRecord<D>>(key, \"point\") ?? createPoint(record, target);\n point.row = record;\n points.set(key, point);\n diff.entering.push(point);\n }\n point.target = target;\n return point;\n });\n const kept = new Set(live);\n record.points = [...live, ...record.points.filter((point) => !kept.has(point) && drawn(point))];\n }\n\n for (const record of rowOrder) labelColumn(record);\n // DOM order follows visual order, for screen readers.\n orderElements(\n columnsLayer,\n before.filter((record) => !record.leaving).map((record) => record.column),\n rowOrder.map((record) => record.column),\n hover.active\n );\n orderElements(linesLayer, previousLines.map((line) => line.group), lineOrder.map((line) => line.group), () => null);\n rowChanges = changes;\n // New marks are drawn where they start, so hover and exit report them as they are on screen.\n dirty = true;\n draw();\n return diff;\n }\n\n /** Brings back the mark leaving under `key`, if there is one and it's the kind wanted: it keeps its element, and the runner cancels its exit. */\n function recall<R extends MarkRecord<D>>(key: string, kind: R[\"kind\"]): R | undefined {\n return leaving.get(key)?.kind === kind ? (leaving.recall(key) as R) : undefined;\n }\n\n /**\n * Sends every animated value toward `next`, and returns the animations started. Presentation stages\n * the change: values first (the rows' values and the value scale, ticks fading, series' lines fading\n * in or out), then positions (rows move along x, new rows grow out of their anchors and leaving rows\n * fold into theirs, the x range and the box follow). A stage with nothing to do is skipped. Analysis\n * runs it all as one stage, which its scaling keeps short. A jump (motion off, a resize) lands at once.\n */\n function retarget(next: LineLayout<D>, jump: boolean): Promise<TweenResult>[] {\n dirty = true;\n const { frame } = next;\n for (const [ticks, placed, lined] of [\n [yTicks, next.yTicks, true],\n [xTicks, next.xTicks, false]\n ] as const) {\n const wanted = new Set(placed.map((tick) => tick.value));\n for (const value of wanted) if (!ticks.has(value)) addTick(ticks, value, 0, lined);\n for (const tick of ticks.values()) tick.wanted = wanted.has(tick.value);\n }\n for (const tick of next.xTicks) xTicks.get(tick.value)!.text = tick.label.text;\n const goingLines = leavingLines();\n const folding = [...leavingRows.values()];\n\n const values =\n busy(scale, frame.scale, sameFields) ||\n [...yTicks.values()].some((tick) => busy(tick.opacity, tick.wanted ? 1 : 0, same)) ||\n rowOrder.some((record) => busy(record.values, record.row.levels, sameFields)) ||\n lineOrder.some((line) => busy(line.presence, 1, same)) ||\n goingLines.some((line) => busy(line.presence, 0, same));\n const positions =\n busy(box, frame.box, sameFields) ||\n [...xTicks.values()].some((tick) => busy(tick.opacity, tick.wanted ? 1 : 0, same)) ||\n rowOrder.some((record) => busy(record.x, record.row.x, same) || (record.anchor !== undefined && busy(record.presence, 1, same))) ||\n folding.some((record) => record.anchor !== undefined && busy(record.presence, 0, same));\n\n let first: AnimateOptions | undefined;\n let second: AnimateOptions | undefined;\n if (!jump && motion.staged) {\n first = { duration: STAGE };\n second = { duration: STAGE, delay: values ? STAGE : 0 };\n } else if (!jump) {\n first = second = { duration: (values && positions ? 2 : 1) * STAGE };\n }\n\n const running: Promise<TweenResult>[] = [];\n const move = <T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean, timing: AnimateOptions | undefined): void => {\n if (!busy(value, to, equal)) return;\n if (timing) running.push(value.to(to, timing));\n else value.set(to);\n };\n move(scale, frame.scale, sameFields, first);\n move(box, frame.box, sameFields, second);\n for (const tick of yTicks.values()) move(tick.opacity, tick.wanted ? 1 : 0, same, first);\n for (const tick of xTicks.values()) move(tick.opacity, tick.wanted ? 1 : 0, same, second);\n for (const record of rowOrder) {\n move(record.values, record.row.levels, sameFields, first);\n move(record.x, record.row.x, same, second);\n // With nothing to grow out of, a row is in place at once.\n move(record.presence, 1, same, record.anchor ? second : undefined);\n }\n for (const record of folding) move(record.presence, 0, same, record.anchor ? second : undefined);\n for (const line of lineOrder) move(line.presence, 1, same, first);\n for (const line of goingLines) move(line.presence, 0, same, first);\n return running;\n }\n\n function addTick(ticks: Map<number, TickRecord>, value: number, opacity: number, lined: boolean, text = \"\"): void {\n const tick: TickRecord = {\n value,\n line: lined ? svgElement(\"line\", { class: value === 0 ? \"ec-baseline\" : \"ec-gridline\" }, grid) : undefined,\n label: svgElement(\"text\", { class: \"ec-tick\" }, axis),\n text,\n opacity: animated(opacity, interpolateNumber, { clock, motion, onChange: changed }),\n wanted: true\n };\n ticks.set(value, tick);\n // In value order, as the layout lists them.\n for (const t of [...ticks.values()].sort((a, b) => a.value - b.value)) {\n if (t.line) grid.appendChild(t.line);\n axis.appendChild(t.label);\n }\n }\n\n /**\n * Moves to `next`, animated or at once, drawing every frame. Resolves when the change settles.\n * One still in flight is taken over: its waiters wait for this one instead.\n */\n function transitionTo(next: LineLayout<D>, jump: boolean): Promise<void> {\n laidOut = next;\n counting = Object.fromEntries(next.series.map((name) => [name, Math.max(counting[name] ?? 0, next.decimals[name] ?? 0)]));\n return transitions.run(retarget(next, jump));\n }\n\n // ── Motion, size and fonts ─────────────────────────────────────────────────\n\n const unwatchHoverDuration = watchHoverDuration(svg, motion);\n\n /** Re-lays out without animating: a resize or fonts loading. A change in flight lands at once. Effects follow through change(). */\n function relayout(): void {\n if (destroyed) return;\n const next = layout(current);\n // The same rows as now: only the sizes changed.\n const byKey = new Map(next.rows.map((row) => [row.key, row]));\n for (const record of rowOrder) record.row = byKey.get(record.key) ?? record.row;\n const placed = placedFor(next);\n for (const line of lineOrder) line.target = placed.lines.get(line.series) ?? line.target;\n for (const point of points.values()) point.target = placed.points.get(point.key) ?? point.target;\n void transitionTo(next, true);\n }\n\n const unwatchWidth = watchWidth(container, clock, measuredWidth, (width) => {\n measuredWidth = width;\n // A fixed `width` ignores the container.\n if (current.width === undefined) relayout();\n });\n\n // Margins are measured; measure again once web fonts arrive.\n const unwatchFonts = watchFonts(doc, () => {\n measure.clear();\n relayout();\n });\n\n // ── First render ───────────────────────────────────────────────────────────\n\n describeChart(svg, current);\n syncLegend();\n table.render(firstTable);\n {\n const placed = placedFor(laidOut);\n for (const tick of laidOut.yTicks) addTick(yTicks, tick.value, 1, true);\n for (const tick of laidOut.xTicks) addTick(xTicks, tick.value, 1, false, tick.label.text);\n rowOrder = laidOut.rows.map((row) => {\n const record = createRow(row, false);\n rows.set(row.key, record);\n record.points = laidOut.series.filter((name) => !row.missing.has(name)).map((name) => {\n const point = createPoint(record, placed.points.get(pointKey(name, row.key))!);\n points.set(point.key, point);\n return point;\n });\n labelColumn(record);\n return record;\n });\n lineOrder = laidOut.rows.length > 0 ? laidOut.series.map((name) => createLine(name, placed.lines.get(name)!, false)) : [];\n for (const line of lineOrder) lines.set(line.series, line);\n land();\n }\n /** The live marks as they're heading, in the runner's order: the lines, then each x's points. */\n const liveMarks = (): MarkRecord<D>[] => [...lineOrder, ...rowOrder.flatMap(livePoints)];\n hover.sync();\n runner.enter(liveMarks().map(input));\n\n return linkable(hover.link, {\n element: svg,\n\n async update(next) {\n if (destroyed) return;\n if (next.motion !== undefined && next.motion !== current.motion) throw new TypeError(\"lineChart: `motion` can't be changed by update() yet.\");\n const merged: LineChartOptions<D> = { ...current, ...next };\n checkChartOptions(merged, \"lineChart\");\n // Throws on an effect it can't resolve, data it can't draw, a table column it can't read, or a\n // `format` that throws, before anything changes.\n const swapped = \"on\" in next ? nextEffects(effects, current.on, merged.on, env.presets) : effects;\n const nextLayout = layout(merged, swapped);\n const nextTable = tableFor(merged, nextLayout);\n const nextNames = namesFor(merged, nextLayout);\n if (\"colors\" in next) colors = toColorAssignment(merged.colors);\n const previous = current;\n const seriesBefore = laidOut.series;\n current = merged;\n names = nextNames;\n describeChart(svg, current);\n table.render(nextTable);\n // A region that appears with its first text is often missed: it announces from the next update.\n const announcing = announcer !== undefined;\n if (current.announce && !announcer) announcer = chartAnnouncer(svg);\n else if (!current.announce && announcer) {\n announcer.destroy();\n announcer = undefined;\n }\n transitions.supersede();\n const swapping = swapped !== effects;\n effects = swapped;\n\n // The runner hears exit / update / enter now, then change() on every frame, then settle(). New\n // effects start where the old ones were, on the marks staying, as this update leaves them; a\n // held hover replays with them once the change settles.\n const leaves = playUpdate(\n {\n runner,\n events,\n hover,\n leaving,\n input,\n onScreen,\n data: \"data\" in next,\n ...(swapping\n ? {\n swap: (diff: Diff<D>) => {\n const entering = new Set(diff.entering);\n runner.swap(swapped, liveMarks().filter((record) => !entering.has(record)).map(input));\n }\n }\n : {})\n },\n () => arrange(nextLayout),\n () => {\n if (announcing) announceChange(previous, seriesBefore);\n }\n );\n syncLegend();\n const settled = transitionTo(nextLayout, motion.mode === \"off\");\n await transitions.wait(settled, leaves);\n },\n\n reveal(x) {\n if (destroyed) return;\n // A Date is its time in ms, which is how a time axis has its x's.\n if (x instanceof Date && Number.isNaN(x.getTime())) throw new RangeError(\"lineChart: reveal(x) needs a valid Date, got an invalid Date.\");\n const at: unknown = x instanceof Date ? x.getTime() : x;\n if (typeof at !== \"number\" || Number.isNaN(at)) throw new RangeError(`lineChart: reveal(x) needs a number, got ${typeof at === \"string\" ? JSON.stringify(at) : String(at)}.`);\n const before = revealedIn(laidOut);\n through = at;\n if (revealedIn(laidOut) === before) return;\n // A view, not a data change: no events. The lines (and their decorations, through change())\n // end at x, and the x's past it are hidden.\n drawReveal();\n hover.dropGone();\n hover.sync();\n },\n\n on: events.on,\n\n marks: () => [...lineOrder.map((line) => line.shown.geometry), ...rowOrder.filter(revealed).flatMap((record) => livePoints(record).map((point) => point.shown.geometry))],\n\n focus(key) {\n if (destroyed) return;\n // An x takes focus, for its own key or one of its points'.\n const record = rows.get(key) ?? points.get(key)?.row;\n if (record) hover.focus(record.key);\n },\n\n leave() {\n if (!destroyed) hover.leave();\n },\n\n // A line's end label is its value; points have none.\n labels: () => lineOrder.flatMap((line) => chartLabel(line.key, \"value\", line.drawnLabel, line.label)),\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n // Ends the change in flight, and resolves the latest update()'s promise.\n transitions.destroy();\n hover.destroy();\n runner.destroy();\n tooltip.destroy();\n legend.destroy();\n table.destroy();\n announcer?.destroy();\n unwatchHoverDuration();\n unwatchWidth();\n unwatchFonts();\n for (const record of [...rowOrder, ...leavingRows.values()]) for (const value of [record.x, record.values, record.presence]) value.stop();\n for (const line of [...lineOrder, ...leavingLines()]) line.presence.stop();\n for (const record of leaving.values()) record.leave?.resolve();\n scale.stop();\n box.stop();\n for (const tick of [...yTicks.values(), ...xTicks.values()]) tick.opacity.stop();\n events.clear();\n rows.clear();\n leavingRows.clear();\n lines.clear();\n points.clear();\n leaving.clear();\n rowOrder = [];\n lineOrder = [];\n svg.remove();\n }\n });\n}\n\n/** A row at rest, as laid out: its values, and its levels where it has none. */\nfunction restState<D>(row: LineRow<D>): RowState<D> {\n return { key: row.key, datum: row.datum, x: row.x, values: row.levels, missing: row.missing };\n}\n\n/** The values a row has, leaving out the missing ones. */\nfunction present(values: readonly LineValue[]): { series: string; value: number }[] {\n return values.flatMap((v) => (v.value === undefined ? [] : [{ series: v.series, value: v.value }]));\n}\n\nfunction valueIn<D>(row: LineRow<D>, series: string): number | undefined {\n return row.values.find((v) => v.series === series)?.value;\n}\n\nfunction total(values: readonly LineValue[]): number {\n return values.reduce((sum, v) => sum + (v.value ?? 0), 0);\n}\n\n/** The nearest record to index `i` in `order` that's in `among`: before it first, then after it. */\nfunction nearest<R>(order: readonly R[], i: number, among: ReadonlySet<R>): R | undefined {\n for (let j = i - 1; j >= 0; j--) if (among.has(order[j]!)) return order[j];\n for (let j = i + 1; j < order.length; j++) if (among.has(order[j]!)) return order[j];\n return undefined;\n}\n\n/** The same walk and outline. */\nfunction sameGeometry(a: MarkGeometry, b: MarkGeometry): boolean {\n return a.key === b.key && !geometryChanged(a, b) && a.start.x === b.start.x && a.start.y === b.start.y && a.end.x === b.end.x && a.end.y === b.end.y;\n}\n\n/** The same row and samples. */\nfunction sameData<D>(a: MarkData<D>, b: MarkData<D>): boolean {\n if (a.datum !== b.datum || a.samples.length !== b.samples.length) return false;\n return a.samples.every((s, i) => {\n const o = b.samples[i]!;\n return s.t === o.t && s.value === o.value && sameAt(s.at, o.at) && s.gapBefore === o.gapBefore;\n });\n}\n\n/** The same x: Dates by their time, since each placing makes its own. */\nfunction sameAt(a: Sample[\"at\"], b: Sample[\"at\"]): boolean {\n return a === b || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime());\n}\n\n/** Each series' value with its label, leaving out the missing ones: what `markLabel` is given. Copies, so a page can't change the layout's. */\nfunction labelled<D>(values: readonly LineValue[], options: LineChartOptions<D>): { series: string; label: string; value: number }[] {\n return present(values).map((v) => ({ series: v.series, label: seriesLabel(options.seriesLabels, v.series), value: v.value }));\n}\n\n/** Each series at the row, as the x's name and the tooltip say it: its value with its label (\"15 goals\"), or \"xg missing\". */\nfunction said<D>(values: readonly LineValue[], options: LineChartOptions<D>): string[] {\n const formatted = format(options);\n return values.map((v) => {\n const label = seriesLabel(options.seriesLabels, v.series);\n return v.value === undefined ? `${label} missing` : `${formatted(v.value)} ${label}`;\n });\n}\n\n/** The default tooltip: the x, then each series' value or that it's missing. */\nfunction summary<D>(row: LineRow<D>, options: LineChartOptions<D>): TooltipContent {\n if (row.missing.size === 0) return summaryContent(row.label, labelled(row.values, options), format(options), { total: false });\n return { title: row.label, lines: [said(row.values, options).join(\" · \")] };\n}\n\n/**\n * Every x's name in `layout`, by key, worked out before anything changes: \"12: 15 goals, 14.2 xg\",\n * each series' value with its label, or the page's wording from `markLabel`. An empty name, or a throw\n * (reported), keeps the default, so a focus stop is never left unnamed.\n */\nfunction namesFor<D>(options: LineChartOptions<D>, layout: LineLayout<D>): ReadonlyMap<string, string> {\n const formatted = format(options);\n return new Map(\n layout.rows.map((row) => {\n const values = labelled(row.values, options);\n const text = `${row.label}: ${said(row.values, options).join(\", \")}`;\n if (!options.markLabel) return [row.key, text];\n try {\n const named: unknown = options.markLabel(row.datum, { key: row.key, category: row.label, values, total: total(row.values), format: formatted, text });\n if (named !== undefined && named !== null && String(named).trim() !== \"\") return [row.key, String(named)];\n } catch (error) {\n report(error);\n }\n return [row.key, text];\n })\n );\n}\n","// Whether a mark goes round a centre, read from its geometry alone: a slice does, a bar doesn't. The\n// adapter orders a ring of marks with it, and morph's \"drop\" turns its pairing by it.\n\nimport type { MarkGeometry, Point } from \"../contracts/geometry\";\n\n/** px: the same distance from the pivot give or take this much, and further from it than this. */\nconst ROUND = 0.5;\n\n/**\n * Whether the mark's walk goes round its pivot: its start, centre and end all the same distance from\n * the pivot, give or take 0.5 px, and more than 0.5 px away. An arc's pivot is the donut's centre; a\n * line's, a bar's and a point's is on its own walk, so lines that start at one point aren't a ring.\n */\nexport function goesRound(mark: Pick<MarkGeometry, \"start\" | \"center\" | \"end\" | \"pivot\">): boolean {\n const radius = distance(mark.start, mark.pivot);\n return radius > ROUND && Math.abs(distance(mark.center, mark.pivot) - radius) <= ROUND && Math.abs(distance(mark.end, mark.pivot) - radius) <= ROUND;\n}\n\nconst distance = (a: Point, b: Point): number => Math.hypot(b.x - a.x, b.y - a.y);\n","// Bars from rectangles someone else drew: which edge each grows from, and the segments of a stack,\n// described with describe.bar. Pure: the rectangles are already in the marks' common coordinates.\n\nimport type { Baseline, MarkGeometry, Rect } from \"../../core\";\nimport { describe } from \"../../core\";\n\n/** One `<rect>` of a mark, in the marks' common coordinates. */\nexport interface RectPart {\n readonly box: Rect;\n /** The segment's series, from the `segment` option. */\n readonly series: string | undefined;\n /** Corner radius (the rect's rx), used for the tip. */\n readonly radius: number;\n}\n\n/** Edges this close (px) count as the same line. */\nconst SAME = 0.5;\n\nconst BASELINES: readonly string[] = [\"left\", \"right\", \"top\", \"bottom\"];\n\nexport function isBaseline(value: unknown): value is Baseline {\n return typeof value === \"string\" && BASELINES.includes(value);\n}\n\n/**\n * Each mark's baseline. \"auto\" finds a line every mark has an edge on: a mark whose near edge\n * (left, or bottom for columns) is on it grows away from it, and one whose far edge is grows the\n * other way, like a negative bar. When both directions fit (one mark, or marks of one size), marks\n * spread down the page are bars and marks spread across are columns.\n */\nexport function baselines(boxes: readonly Rect[], option: Baseline | \"auto\"): Baseline[] {\n if (option !== \"auto\") return boxes.map(() => option);\n if (boxes.length === 0) return [];\n const horizontal = commonLine(boxes, (b) => b.x, (b) => b.x + b.width, \"left\", \"right\");\n const vertical = commonLine(boxes, (b) => b.y + b.height, (b) => b.y, \"bottom\", \"top\");\n if (horizontal && vertical) return rows(boxes) ? horizontal : vertical;\n const found = horizontal ?? vertical;\n if (!found) {\n throw new RangeError('expressive: baseline \"auto\" found no edge that every mark grows from. Pass baseline: \"left\", \"right\", \"top\" or \"bottom\".');\n }\n return found;\n}\n\n/**\n * The mark's geometry from its rects, ordered from the baseline. Each segment ends where its rect\n * ends; a gap the host left between segments becomes describe.bar's `gap`, which comes out of the\n * start of the later segment.\n */\nexport function describeRects(key: string, parts: readonly RectPart[], baseline: Baseline): { geometry: MarkGeometry; order: number[] } {\n const box = union(parts.map((part) => part.box));\n const span = spanFrom(box, baseline);\n const order = parts\n .map((part, index) => ({ index, ...span(part.box) }))\n .sort((a, b) => a.near - b.near || a.far - b.far || a.index - b.index);\n\n let reached = 0;\n let gap = Infinity;\n const segments = order.map(({ index, near, far }) => {\n // Only between parts you can see: a zero-length segment sits right where the one before ends.\n if (reached > 0 && far > near) gap = Math.min(gap, near - reached);\n const size = Math.max(0, far - reached);\n reached = Math.max(reached, far);\n return { series: parts[index]!.series, size };\n });\n\n const tip = parts[order[order.length - 1]!.index]!;\n const single = parts.length === 1 ? parts[0]!.series : undefined;\n const geometry = describe.bar({\n key,\n ...(single === undefined ? {} : { series: single }),\n ...box,\n baseline,\n radius: tip.radius,\n gap: Number.isFinite(gap) ? Math.max(0, round(gap)) : 0,\n // Without `segment` there's one part and no series to name: describe.bar's default segment.\n ...(segments.every((s) => s.series !== undefined) ? { segments: segments.map((s) => ({ series: s.series!, size: round(s.size) })) } : {})\n });\n return { geometry, order: order.map((o) => o.index) };\n}\n\n/** Indices in visual order: bars top to bottom, columns left to right. */\nexport function visualOrder(boxes: readonly Rect[], baseline: readonly Baseline[]): number[] {\n const horizontal = baseline[0] === \"left\" || baseline[0] === \"right\";\n const along = (b: Rect): number => (horizontal ? b.y : b.x);\n const across = (b: Rect): number => (horizontal ? b.x : b.y);\n return boxes.map((_, index) => index).sort((a, b) => along(boxes[a]!) - along(boxes[b]!) || across(boxes[a]!) - across(boxes[b]!) || a - b);\n}\n\nexport function union(boxes: readonly Rect[]): Rect {\n const x = Math.min(...boxes.map((b) => b.x));\n const y = Math.min(...boxes.map((b) => b.y));\n return { x, y, width: round(Math.max(...boxes.map((b) => b.x + b.width)) - x), height: round(Math.max(...boxes.map((b) => b.y + b.height)) - y) };\n}\n\nfunction commonLine(\n boxes: readonly Rect[],\n nearEdge: (box: Rect) => number,\n farEdge: (box: Rect) => number,\n near: Baseline,\n far: Baseline\n): Baseline[] | undefined {\n const first = boxes[0];\n if (!first) return [];\n for (const line of [nearEdge(first), farEdge(first)]) {\n const found: Baseline[] = [];\n for (const box of boxes) {\n if (Math.abs(nearEdge(box) - line) < SAME) found.push(near);\n else if (Math.abs(farEdge(box) - line) < SAME) found.push(far);\n else break;\n }\n if (found.length === boxes.length) return found;\n }\n return undefined;\n}\n\n/** True when the marks look like rows (bars), false for columns. */\nfunction rows(boxes: readonly Rect[]): boolean {\n const spread = (values: number[]): number => Math.max(...values) - Math.min(...values);\n const down = spread(boxes.map((b) => b.y + b.height / 2));\n const across = spread(boxes.map((b) => b.x + b.width / 2));\n if (down !== across) return down > across;\n // One mark, or marks on top of each other: the longer side is the bar's length.\n return boxes[0]!.width >= boxes[0]!.height;\n}\n\n/** A part's start and end along the walk, in px from the mark's baseline. */\nfunction spanFrom(mark: Rect, baseline: Baseline): (box: Rect) => { near: number; far: number } {\n switch (baseline) {\n case \"left\":\n return (b) => ({ near: b.x - mark.x, far: b.x + b.width - mark.x });\n case \"right\":\n return (b) => ({ near: mark.x + mark.width - (b.x + b.width), far: mark.x + mark.width - b.x });\n case \"top\":\n return (b) => ({ near: b.y - mark.y, far: b.y + b.height - mark.y });\n case \"bottom\":\n return (b) => ({ near: mark.y + mark.height - (b.y + b.height), far: mark.y + mark.height - b.y });\n }\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n","// Every change the adapter makes to the host's elements, with what was there before, so it can all\n// be undone: attributes (tabindex, ARIA), inline style properties and classes. Touching el.style or\n// el.classList rewrites the whole attribute, so once the last of our changes is undone, an attribute\n// that reads the same as before gets its exact text back (or goes away, if it wasn't there).\n//\n// A host that reuses its elements may rewrite an attribute we also write (its own aria-label, as the\n// data changes). Its latest value is the one to put back, so an attribute that no longer reads as we\n// left it takes the host's value as its new original, and undoing our change leaves the host's alone.\n\n/** An attribute we changed. null: absent. */\ninterface SavedAttribute {\n /** What to put back: the host's value from before our first change, or the one it wrote since. */\n original: string | null;\n /** What we last left it as. */\n written: string | null;\n}\n\ninterface Saved {\n readonly attributes: Map<string, SavedAttribute>;\n /** Inline style properties we changed: their value and priority before. */\n readonly styles: Map<string, { readonly value: string; readonly priority: string }>;\n /** Classes we added (ones the element already had are left alone). */\n readonly classes: Set<string>;\n /** The style and class attributes' text from before our first change to each. */\n readonly before: { style?: { readonly text: string | null; readonly css: string }; class?: string | null };\n}\n\nexport interface HostEdits {\n /** Sets an attribute; null puts back the host's value, unless the host has written its own since. */\n attribute(element: Element, name: string, value: string | null): void;\n /** Removes an attribute; `attribute(element, name, null)` puts it back. */\n remove(element: Element, name: string): void;\n /** Sets an inline style property; undefined puts back what was there before. */\n style(element: Element, property: string, value: string | undefined): void;\n /** Whether we're overriding the property now. */\n styled(element: Element, property: string): boolean;\n /** Adds (true) or removes (false) a class we add; classes the element had stay. */\n toggleClass(element: Element, name: string, on: boolean): void;\n /** Undoes every change to the element. */\n restore(element: Element): void;\n /** Undoes every change to every element. */\n restoreAll(): void;\n /** Elements with changes. */\n elements(): Element[];\n}\n\nexport function hostEdits(): HostEdits {\n const saved = new Map<Element, Saved>();\n\n const entry = (element: Element): Saved => {\n let found = saved.get(element);\n if (!found) {\n found = { attributes: new Map(), styles: new Map(), classes: new Set(), before: {} };\n saved.set(element, found);\n }\n return found;\n };\n\n const styleOf = (element: Element): CSSStyleDeclaration | undefined => (element as SVGElement).style;\n\n const put = (element: Element, name: string, text: string | null): void => {\n if (text === null) element.removeAttribute(name);\n else if (element.getAttribute(name) !== text) element.setAttribute(name, text);\n };\n\n /** After the last of our style changes is undone: the exact text, if nothing else changed meanwhile. */\n const settleStyle = (element: Element, found: Saved): void => {\n const before = found.before.style;\n if (found.styles.size > 0 || !before) return;\n found.before.style = undefined;\n if (styleOf(element)?.cssText === before.css) put(element, \"style\", before.text);\n };\n\n const settleClass = (element: Element, found: Saved): void => {\n const before = found.before.class;\n if (found.classes.size > 0 || before === undefined) return;\n found.before.class = undefined;\n const tokens = (text: string | null | undefined): string => [...new Set((text ?? \"\").split(/\\s+/).filter(Boolean))].sort().join(\" \");\n if (tokens(element.getAttribute(\"class\")) === tokens(before)) put(element, \"class\", before);\n };\n\n /** Sets (text) or removes (null) an attribute, keeping the host's value to put back. */\n function write(element: Element, name: string, text: string | null): void {\n const now = element.getAttribute(name);\n const kept = entry(element).attributes;\n const found = kept.get(name);\n if (!found) kept.set(name, { original: now, written: text });\n else {\n // The host changed it since we last wrote it: that's its value now.\n if (now !== found.written) found.original = now;\n found.written = text;\n }\n put(element, name, text);\n }\n\n function attribute(element: Element, name: string, value: string | null): void {\n if (value !== null) {\n write(element, name, value);\n return;\n }\n const kept = saved.get(element)?.attributes;\n const found = kept?.get(name);\n if (!kept || !found) return;\n // Unless the host has written its own since, which stays.\n if (element.getAttribute(name) === found.written) put(element, name, found.original);\n kept.delete(name);\n }\n\n function style(element: Element, property: string, value: string | undefined): void {\n const declaration = styleOf(element);\n if (!declaration) return;\n const found = entry(element);\n const original = found.styles.get(property);\n if (value === undefined) {\n if (!original) return;\n if (original.value === \"\") declaration.removeProperty(property);\n else declaration.setProperty(property, original.value, original.priority);\n found.styles.delete(property);\n settleStyle(element, found);\n return;\n }\n if (!original) {\n if (found.styles.size === 0) found.before.style = { text: element.getAttribute(\"style\"), css: declaration.cssText };\n found.styles.set(property, { value: declaration.getPropertyValue(property), priority: declaration.getPropertyPriority(property) });\n }\n if (declaration.getPropertyValue(property) !== value) declaration.setProperty(property, value);\n }\n\n function toggleClass(element: Element, name: string, on: boolean): void {\n const list = element.classList;\n if (on) {\n if (list.contains(name)) return;\n const found = entry(element);\n if (found.classes.size === 0) found.before.class = element.getAttribute(\"class\");\n found.classes.add(name);\n list.add(name);\n return;\n }\n const found = saved.get(element);\n if (!found?.classes.delete(name)) return;\n list.remove(name);\n settleClass(element, found);\n }\n\n function restore(element: Element): void {\n const found = saved.get(element);\n if (!found) return;\n for (const property of [...found.styles.keys()]) style(element, property, undefined);\n for (const name of [...found.classes]) toggleClass(element, name, false);\n for (const name of [...found.attributes.keys()]) attribute(element, name, null);\n saved.delete(element);\n }\n\n return {\n attribute,\n remove: (element, name) => write(element, name, null),\n style,\n styled: (element, property) => saved.get(element)?.styles.has(property) ?? false,\n toggleClass,\n restore,\n restoreAll() {\n for (const element of [...saved.keys()]) restore(element);\n },\n elements: () => [...saved.keys()]\n };\n}\n","// Coordinates in someone else's SVG. Matrices between elements' user spaces come from the browser's\n// CTMs where there's layout, and from the transform attributes where there isn't (jsdom, a chart\n// that isn't rendered yet).\n\nimport type { Matrix, Point, Rect } from \"../../core\";\nimport { matrix } from \"../../core\";\nimport { invert, parseTransform } from \"../../core/geometry\";\n\n/** An element's screen CTM as a matrix, or undefined where there's no layout. */\nexport type ScreenMatrix = (element: Element) => Matrix | undefined;\n\n/**\n * Screen CTMs remembered per element, for one read while nothing changes: every mark of a read asks\n * for the common ancestor's and its parent's, which most marks share.\n */\nexport function screenMatrices(): ScreenMatrix {\n const known = new Map<Element, Matrix | undefined>();\n return (element) => {\n if (!known.has(element)) known.set(element, screenMatrix(element));\n return known.get(element);\n };\n}\n\n/**\n * Maps points in `inner`'s user space (after its own transform) into `outer`'s. Both are inside\n * `root`. Without CTMs, nested `<svg>` viewports and CSS transforms aren't seen.\n */\nexport function between(outer: Element, inner: Element, root: Element, screen: ScreenMatrix = screenMatrix): Matrix {\n const a = screen(outer);\n const b = a && screen(inner);\n if (a && b) return matrix.multiply(invert(a), b);\n return matrix.multiply(invert(fromRoot(outer, root)), fromRoot(inner, root));\n}\n\n/** The element's own transform attribute. */\nexport function ownTransform(element: Element): Matrix {\n return parseTransform(element.getAttribute(\"transform\") ?? \"\");\n}\n\n/**\n * Whether the transform keeps rectangles upright: scales, flips and quarter turns, with any\n * translation. Only then is the box a rect covers exactly the rect.\n */\nexport function axisAligned(m: Matrix): boolean {\n const [a, b, c, d] = m;\n const tiny = 1e-9 * Math.max(Math.abs(a), Math.abs(b), Math.abs(c), Math.abs(d));\n return (Math.abs(b) <= tiny && Math.abs(c) <= tiny) || (Math.abs(a) <= tiny && Math.abs(d) <= tiny);\n}\n\n/** The box a transformed rectangle covers, rounded to 0.001 px like path data. */\nexport function boxIn(m: Matrix, rect: Rect): Rect {\n const corners: Point[] = [\n { x: rect.x, y: rect.y },\n { x: rect.x + rect.width, y: rect.y },\n { x: rect.x, y: rect.y + rect.height },\n { x: rect.x + rect.width, y: rect.y + rect.height }\n ].map((corner) => matrix.apply(m, corner));\n const xs = corners.map((p) => p.x);\n const ys = corners.map((p) => p.y);\n const x = round(Math.min(...xs));\n const y = round(Math.min(...ys));\n return { x, y, width: round(round(Math.max(...xs)) - x), height: round(round(Math.max(...ys)) - y) };\n}\n\n/** A `<rect>`'s rectangle in its own user space. A negative size draws nothing, so it counts as 0. */\nexport function rectOf(element: Element): Rect {\n const read = (name: \"x\" | \"y\" | \"width\" | \"height\"): number => {\n // Browsers resolve percentages and CSS geometry; jsdom has only the attribute.\n const animated = (element as unknown as Record<string, { baseVal?: { value?: unknown } } | undefined>)[name];\n const value = typeof animated?.baseVal?.value === \"number\" ? animated.baseVal.value : Number.parseFloat(element.getAttribute(name) ?? \"\");\n return Number.isFinite(value) ? value : 0;\n };\n return { x: read(\"x\"), y: read(\"y\"), width: Math.max(0, read(\"width\")), height: Math.max(0, read(\"height\")) };\n}\n\nfunction screenMatrix(element: Element): Matrix | undefined {\n const ctm = typeof (element as SVGGraphicsElement).getScreenCTM === \"function\" ? (element as SVGGraphicsElement).getScreenCTM() : null;\n return ctm ? [ctm.a, ctm.b, ctm.c, ctm.d, ctm.e, ctm.f] : undefined;\n}\n\n/** The element's transform attributes, its own included, down from `root` (whose own is left out). */\nfunction fromRoot(element: Element, root: Element): Matrix {\n let m: Matrix = [1, 0, 0, 1, 0, 0];\n for (let node: Element | null = element; node && node !== root; node = node.parentElement) m = matrix.multiply(ownTransform(node), m);\n return m;\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n","// The drawing API's MarkHandle on elements someone else drew. Every change goes through HostEdits, so\n// a reset (or destroy) puts back exactly what the host had, and the host's own attributes are never\n// written: the transform is an inline style composed with the element's own transform attribute.\n\nimport type { MarkHandle, MarkStyle, Matrix } from \"../../core\";\nimport { matrix } from \"../../core\";\nimport { mergeFields } from \"../../core/merge\";\nimport { maskedHalo, type HaloPart } from \"../render/outside\";\nimport { cssColor, type SeriesColors } from \"../render/theme\";\nimport type { HostEdits } from \"./edits\";\nimport { ownTransform } from \"./space\";\n\n/** The host's colours for an element, and the property they're from, which emphasis and the hover colour write. */\nexport interface HostColors extends SeriesColors {\n /** \"stroke\" when the fill is none, as on a line. */\n readonly paint: \"fill\" | \"stroke\";\n}\n\n/** One element of a mark, as the style handle needs it. */\nexport interface HostPart {\n readonly element: Element;\n /** From the element's parent's user space into the marks' common ancestor's, and back. */\n readonly parent: Matrix;\n readonly parentInverse: Matrix | undefined;\n /** The host's colour for the element, which `emphasis`, the hover colour and the \"mark\" token start from. */\n readonly colors: HostColors | undefined;\n /**\n * The part's outline in the common ancestor's space, for the halo, with an open outline's stroke\n * width; undefined when it's too short to see.\n */\n readonly outline: Omit<HaloPart, \"color\"> | undefined;\n}\n\nexport interface HostMarkHandle extends MarkHandle {\n readonly style: MarkStyle;\n /** Applies the current style again, after a refresh (new elements or outlines). */\n repaint(): void;\n /** Gives the mark its strong colour while it's hovered, under `dim`, as our charts do. */\n hot(on: boolean): void;\n}\n\n/**\n * - `transform` is in the common ancestor's space. Each element gets an inline CSS transform that\n * moves it by that much, composed with its own transform attribute, with origin 0 0 in its user space.\n * - `opacity` and `emphasis` are inline styles; emphasis mixes the host's colour (its fill, or its\n * stroke on a line) toward its strong colour. A hot mark takes the strong one, unless an effect sets emphasis.\n * - `halo` strokes each visible part's outline in the overlay, masked to outside the mark, so it\n * shows only where it would behind the mark.\n */\nexport function hostMarkHandle(parts: () => readonly HostPart[], edits: HostEdits, halos: () => SVGGElement | undefined): HostMarkHandle {\n let style: MarkStyle = {};\n let hot = false;\n const halo = maskedHalo();\n\n const repaint = (): void => {\n const { transform, opacity, emphasis } = style;\n for (const part of parts()) {\n const { element, colors } = part;\n const moved = transform && part.parentInverse ? matrix.multiply(part.parentInverse, transform, part.parent, ownTransform(element)) : undefined;\n edits.style(element, \"transform\", moved && cssMatrix(moved));\n edits.style(element, \"transform-origin\", moved && \"0 0\");\n edits.style(element, \"transform-box\", moved && \"view-box\");\n edits.style(element, \"opacity\", opacity === undefined ? undefined : String(opacity));\n const shade = !colors ? undefined : emphasis !== undefined ? mix(colors, emphasis) : hot ? colors.strong : undefined;\n edits.style(element, \"fill\", colors?.paint === \"fill\" ? shade : undefined);\n edits.style(element, \"stroke\", colors?.paint === \"stroke\" ? shade : undefined);\n // The effect animates emphasis itself; a host transition on the colour would smear it.\n edits.style(element, \"transition\", emphasis === undefined || !colors ? undefined : \"none\");\n }\n paintHalo();\n };\n\n const paintHalo = (): void => {\n const visible = parts().flatMap((part) => (part.outline === undefined ? [] : [{ ...part.outline, color: part.colors?.color }]));\n halo.paint(halos(), visible, style.halo, style.transform);\n };\n\n return {\n get style() {\n return style;\n },\n set(next) {\n style = mergeFields(style, next);\n repaint();\n },\n reset() {\n style = {};\n repaint();\n },\n repaint,\n hot(on) {\n if (on === hot) return;\n hot = on;\n repaint();\n }\n };\n}\n\n/**\n * The host's colours for an element: its fill, or its stroke when the fill is none (a line). Each is\n * the computed value where there's styling. jsdom computes no presentation attributes (every fill is\n * black and every stroke none), so a computed value that's the property's initial one gives way to\n * the nearest value declared on the element or above it. A gradient or pattern gives no colours.\n *\n * The strong colour is our charts' kind of -strong: the colour stepped toward the text colour, in\n * OKLab so the hue stays, so a hovered mark gets darker in the light theme and lighter in the dark.\n * Our palette's -strong colours sit 20% of the way in light and 29% in dark; a host's colour goes 25%.\n */\nexport function hostColors(element: Element, root: Element): HostColors | undefined {\n const fill = paintOf(element, root, \"fill\");\n const paint = fill === NONE ? \"stroke\" : \"fill\";\n const color = paint === \"fill\" ? fill : paintOf(element, root, \"stroke\");\n if (color === undefined || color === NONE) return undefined;\n return { color, strong: `color-mix(in oklab, ${color}, ${cssColor(\"text\")} ${STRONG})`, paint };\n}\n\n/** How far a host's colour steps toward the text colour for its strong colour. */\nconst STRONG = \"25%\";\n\nconst NONE = \"none\";\n\n/** A paint property's colour, NONE for no paint (or a transparent one), or undefined when it isn't a colour. */\nfunction paintOf(element: Element, root: Element, property: \"fill\" | \"stroke\"): string | undefined {\n let declared: string | undefined;\n for (let node: Element | null = element; node && declared === undefined; node = node === root ? null : node.parentElement) {\n const value = (node as SVGElement).style?.getPropertyValue(property) || node.getAttribute(property);\n if (value) declared = value;\n }\n const computed = kind(element.ownerDocument.defaultView?.getComputedStyle?.(element).getPropertyValue(property));\n const initial = property === \"fill\" ? computed?.replace(/\\s/g, \"\") === \"rgb(0,0,0)\" : computed === NONE;\n return computed !== undefined && !(initial && declared !== undefined) ? computed : kind(declared);\n}\n\n/** NONE for no paint or a transparent one, the colour as given, or undefined for anything else (a url(), inherit). */\nfunction kind(value: string | null | undefined): string | undefined {\n const v = value?.trim().toLowerCase();\n if (!v || v === \"inherit\" || v.startsWith(\"url(\")) return undefined;\n if (v === NONE || v === \"transparent\" || /^rgba\\((?:[^,]+,){3}\\s*0(?:\\.0*)?\\s*\\)$/.test(v)) return NONE;\n return value!.trim();\n}\n\nfunction mix(colors: SeriesColors, emphasis: number): string {\n const amount = Math.min(1, Math.max(0, emphasis));\n if (amount === 0) return colors.color;\n if (amount === 1) return colors.strong;\n return `color-mix(in srgb, ${colors.strong} ${Math.round(amount * 1000) / 10}%, ${colors.color})`;\n}\n\n/** CSS needs commas in matrix(); the SVG attribute doesn't mind them. */\nfunction cssMatrix(m: Matrix): string {\n return `matrix(${m.map((v, i) => (i < 4 ? Math.round(v * 1e6) / 1e6 : Math.round(v * 1000) / 1000)).join(\", \")})`;\n}\n","// Where an adapter's marks come from: a selector, elements, or a D3-style selection. And the two\n// elements every mark's coordinates hang off: the root <svg> and the marks' nearest common ancestor.\n\nimport type { MarkSource } from \"./types\";\n\nexport interface SourceMarks<D> {\n readonly elements: readonly Element[];\n /** A selection's data(), when it lines up with its nodes(). */\n readonly data: readonly D[] | undefined;\n}\n\nexport function readSource<D>(source: MarkSource<D>): SourceMarks<D> {\n if (typeof source === \"string\") {\n if (typeof document === \"undefined\") throw new TypeError(\"expressive: a selector needs a document.\");\n return { elements: Array.from(document.querySelectorAll(source)), data: undefined };\n }\n if (isElement(source)) return { elements: [source], data: undefined };\n if (isSelection<D>(source)) {\n const elements = Array.from(source.nodes());\n const data = Array.from(source.data());\n return { elements, data: data.length === elements.length ? data : undefined };\n }\n if (source !== null && typeof source === \"object\" && typeof (source as ArrayLike<Element>).length === \"number\") {\n return { elements: Array.from(source as ArrayLike<Element>), data: undefined };\n }\n throw new TypeError(\"expressive needs marks: a selector, an element, a list of elements or a D3 selection.\");\n}\n\n/** A selection's rows by element, when its data() lines up with its nodes(); otherwise undefined, and each element's own `__data__` is its row. */\nexport function boundRows<D>(source: MarkSource<D>): Map<Element, D> | undefined {\n if (!isSelection<D>(source)) return undefined;\n const { elements, data } = readSource(source);\n return data && new Map(elements.map((element, i) => [element, data[i]!]));\n}\n\n/** The outermost <svg> around the elements, which must all share it. */\nexport function rootOf(elements: readonly Element[]): SVGSVGElement {\n let root: SVGSVGElement | undefined;\n for (const element of elements) {\n if (!isElement(element)) throw new TypeError(`expressive: marks must be elements, got ${String(element)}.`);\n let svg = (element as SVGElement).ownerSVGElement ?? null;\n if (!svg) {\n const tag = element.localName;\n throw new TypeError(\n tag === \"svg\"\n ? \"expressive: got an <svg>, not its marks. Pass the marks, for example svg.querySelectorAll(\\\"rect\\\").\"\n : `expressive: marks must be SVG elements inside an <svg>, got <${tag}>.`\n );\n }\n while (svg.ownerSVGElement) svg = svg.ownerSVGElement;\n if (root && svg !== root) throw new TypeError(\"expressive: all marks must be in the same <svg>.\");\n root = svg;\n }\n if (!root) throw new TypeError(\"expressive: no marks.\");\n return root;\n}\n\n/** The deepest element containing every mark (a lone mark's parent). Geometry is in its coordinates. */\nexport function commonAncestor(elements: readonly Element[], root: Element): Element {\n let ancestor = elements[0]!.parentElement ?? root;\n while (ancestor !== root && !elements.every((element) => element !== ancestor && ancestor.contains(element))) {\n ancestor = ancestor.parentElement ?? root;\n }\n return ancestor;\n}\n\nfunction isElement(value: unknown): value is Element {\n return typeof value === \"object\" && value !== null && (value as Node).nodeType === 1;\n}\n\nfunction isSelection<D>(value: unknown): value is { nodes(): Element[]; data(): D[] } {\n return typeof value === \"object\" && value !== null && typeof (value as { nodes?: unknown }).nodes === \"function\" && typeof (value as { data?: unknown }).data === \"function\";\n}\n","// Following the host's own changes (`watch`, M4 decision 14). A MutationObserver notes changes to\n// the marks' geometry attributes, and to transform and style on every ancestor from the marks up to\n// the root <svg>: a host that animates a parent <g transform> changes none of the marks' own\n// attributes. What changed is handed on once a frame, on the chart's clock, however many\n// attributes the host wrote in between.\n//\n// The marks' own style isn't watched: the adapter writes it (effects' transforms, emphasis, the hover\n// colour), so it would hear itself.\n\nimport type { Clock } from \"../../core\";\n\n/** Attributes that move or reshape a mark. */\nconst GEOMETRY = [\"d\", \"x\", \"y\", \"width\", \"height\", \"cx\", \"cy\", \"r\", \"points\", \"transform\"];\n/** Attributes that move everything inside an ancestor. */\nconst ANCESTOR = [\"transform\", \"style\"];\n\n/** What changed since the last frame. */\nexport interface WatchedChanges {\n /** Mark elements whose geometry attributes changed. */\n readonly marks: ReadonlySet<Element>;\n /** Ancestors of the marks whose transform or style changed. */\n readonly ancestors: ReadonlySet<Element>;\n}\n\nexport interface HostWatch {\n /**\n * Watches these mark elements, and their ancestors up to `root`, instead of what it watched\n * before. Changes not handed on yet are dropped: the caller has just read everything.\n */\n observe(elements: readonly Element[], root: Element | undefined): void;\n /** Stops watching; nothing more is handed on. */\n destroy(): void;\n}\n\nexport function watchHost(doc: Document, clock: Clock, onChanges: (changes: WatchedChanges) => void): HostWatch {\n const Observer = doc.defaultView?.MutationObserver ?? (typeof MutationObserver === \"undefined\" ? undefined : MutationObserver);\n if (!Observer) throw new TypeError(\"expressive: watch needs MutationObserver, which this DOM doesn't have.\");\n\n let marks = new Set<Element>();\n let ancestors = new Set<Element>();\n /** The elements watched now: the marks', and their ancestors'. */\n let watchedMarks = new Set<Element>();\n let watchedAncestors = new Set<Element>();\n let cancelFrame: (() => void) | undefined;\n\n const collect = (records: readonly MutationRecord[]): void => {\n for (const { target, attributeName } of records) {\n const element = target as Element;\n if (watchedMarks.has(element)) marks.add(element);\n if (watchedAncestors.has(element) && (attributeName === \"transform\" || attributeName === \"style\")) ancestors.add(element);\n }\n };\n\n const observer = new Observer((records) => {\n collect(records);\n if ((marks.size > 0 || ancestors.size > 0) && !cancelFrame) cancelFrame = clock.onFrame(frame);\n });\n\n /**\n * Hands on what changed, and stays on the clock until a frame with no changes. A host that draws in\n * its own frame callback asks for its next frame there, and the clock, still on, asks after it at\n * the end of its own, so each of the host's frames is read in the frame it's drawn. Leaving after\n * every frame, the clock would ask again only on hearing the next changes, too late for that frame,\n * and the effects would trail the marks every other frame.\n */\n function frame(): void {\n // Changes the observer hasn't handed over yet, made earlier in this frame.\n collect(observer.takeRecords());\n if (marks.size === 0 && ancestors.size === 0) {\n cancelFrame?.();\n cancelFrame = undefined;\n return;\n }\n const changes: WatchedChanges = { marks, ancestors };\n marks = new Set();\n ancestors = new Set();\n onChanges(changes);\n }\n\n function drop(): void {\n observer.takeRecords();\n cancelFrame?.();\n cancelFrame = undefined;\n marks = new Set();\n ancestors = new Set();\n }\n\n return {\n observe(elements, root) {\n drop();\n observer.disconnect();\n watchedMarks = new Set(elements);\n watchedAncestors = new Set();\n for (const element of elements) {\n // Ancestors are shared: stop at one already seen, since everything above it is too.\n for (let node = element.parentElement; node && !watchedAncestors.has(node); node = node === root ? null : node.parentElement) {\n watchedAncestors.add(node);\n }\n }\n // An element that is a mark and also holds marks keeps the mark's list, which has transform but\n // not style: the adapter writes its style.\n for (const element of watchedAncestors) if (!watchedMarks.has(element)) observer.observe(element, { attributes: true, attributeFilter: ANCESTOR });\n for (const element of watchedMarks) observer.observe(element, { attributes: true, attributeFilter: GEOMETRY });\n },\n\n destroy() {\n drop();\n observer.disconnect();\n watchedMarks = new Set();\n watchedAncestors = new Set();\n }\n };\n}\n","// expressive(): effects on SVG marks drawn by other code (M1 step 10, for rects). It reads keys, rows\n// and geometry from the host's elements, plays the effect slots through the runner on an overlay at\n// the end of the root <svg>, and listens for pointer events once, on that <svg>. Keyboard focus is\n// barChart's (../keyboard.ts), on the host's elements. Like the charts it never names an effect, and\n// destroy() leaves the host's DOM as it found it.\n//\n// Geometry is in the marks' nearest common ancestor's coordinates. The overlay carries that\n// ancestor's transform but sits on the root, because some hosts (Vega) remove foreign children from\n// their own groups when they redraw. See docs/ideas/adapter-spike.md.\n//\n// With `watch`, the host's own transitions are followed frame by frame (./watch.ts): the marks that\n// changed are read again and the runner hears change(), as on our charts' frames, with no events.\n//\n// A link (../link.ts) hovers marks too, as \"linked\": the dimming and emphasis with `dim`, and their\n// hover runs, with no focus ring or focus. It hears the attachment's own hovers.\n\nimport type { Baseline, MarkData, MarkGeometry, Matrix, Point, Rect, Sample } from \"../../core\";\nimport { defaultClock, matrix } from \"../../core\";\nimport { invert } from \"../../core/geometry\";\nimport { goesRound } from \"../../core/geometry/ring\";\nimport { EFFECT_SLOTS, resolveEffects } from \"../../core/registry\";\nimport { report } from \"../../core/report\";\nimport { createRunner, type RunInput } from \"../../core/runner\";\nimport type { ChartEnv } from \"../bar\";\nimport { pointerHover, type PointerHover } from \"../interaction\";\nimport { keyboardFocus } from \"../keyboard\";\nimport { linkable, own, type LinkListener, type LinkPort } from \"../link\";\nimport { chartMotion } from \"../motion\";\nimport { maskedRing } from \"../render/outside\";\nimport { svgSurface } from \"../render/surface\";\nimport { setAttributes, setStyles, transformAttribute } from \"../render/svg\";\nimport { injectStyles } from \"../render/theme\";\nimport { labelsMoved } from \"../shell/transitions\";\nimport type { MarkEvents } from \"../types\";\nimport { baselines, describeRects, isBaseline, union, visualOrder, type RectPart } from \"./bars\";\nimport { hostEdits } from \"./edits\";\nimport { hostColors, hostMarkHandle, type HostMarkHandle, type HostPart } from \"./host-style\";\nimport { boundRows, commonAncestor, readSource, rootOf } from \"./source\";\nimport { axisAligned, between, boxIn, ownTransform, rectOf, screenMatrices, type ScreenMatrix } from \"./space\";\nimport type { Attachment, ExpressiveOptions, MarkSource } from \"./types\";\nimport { watchHost, type WatchedChanges } from \"./watch\";\n\ninterface Part<D> extends HostPart {\n readonly datum: D;\n readonly series: string | undefined;\n /** What `value` returned for it; undefined without `value`. */\n readonly value: unknown;\n}\n\n/** A mark as read from the host's elements. */\ninterface ReadMark<D> {\n readonly key: string;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n /** From the baseline for bars; in source order for marks described with `geometry`. */\n readonly parts: readonly Part<D>[];\n /** `markLabel`'s name for it; undefined leaves its ARIA as the host drew it. */\n readonly label: string | undefined;\n /** Its place in the source, by its first element: document order, for marks described with `geometry`. */\n readonly index: number;\n /** A rect mark's baseline and the box its rects cover, which watch keeps and orders by. */\n readonly rect?: { readonly edge: Baseline; readonly box: Rect };\n}\n\n/** A mark before its data. */\ntype Drawn<D> = Omit<ReadMark<D>, \"data\">;\n/** A mark before its name: watch keeps the one the last full read gave it. */\ntype Unnamed<D> = Omit<Drawn<D>, \"label\">;\n\n/** Where marks are read: the root and the marks' common ancestor, with the elements' screen CTMs and colours. */\ninterface ReadContext {\n readonly svg: SVGSVGElement;\n readonly common: Element;\n /** Screen CTMs, each read once. */\n readonly screen: ScreenMatrix;\n /** Computed on a full read; watch keeps the last ones, since it doesn't watch colours. */\n readonly colors: (element: Element) => HostPart[\"colors\"];\n}\n\n/** An element of a mark as read from the source, before its geometry. */\ninterface Piece<D> {\n readonly element: Element;\n readonly datum: D;\n readonly series: string | undefined;\n readonly value: unknown;\n}\n\ninterface Reading<D> {\n readonly root: SVGSVGElement | undefined;\n readonly ancestor: Element | undefined;\n /** In visual order. */\n readonly marks: readonly ReadMark<D>[];\n}\n\ninterface MarkRecord<D> {\n readonly key: string;\n mark: ReadMark<D>;\n readonly handle: HostMarkHandle;\n}\n\ninterface Owner<D> {\n readonly record: MarkRecord<D>;\n readonly part: Part<D>;\n}\n\ninterface Diff<D> {\n readonly entering: MarkRecord<D>[];\n readonly exiting: MarkRecord<D>[];\n /** Values changed: a part's `value`, or without `value` the length, or the segments. */\n readonly changed: { readonly record: MarkRecord<D>; readonly from: MarkGeometry }[];\n /** Only moved, or got a new row: the runner follows without an update. */\n readonly moved: MarkRecord<D>[];\n /** Whether a mark got a new row. With a value changed or a mark come or gone, that makes the read an update. */\n newRow: boolean;\n}\n\ntype HoverSource = MarkEvents<unknown>[\"hover\"][\"source\"];\ntype Listeners<D> = { [K in keyof MarkEvents<D>]: Set<(event: MarkEvents<D>[K]) => void> };\n\ninterface Hovered {\n /** The marks' keys: one for the attachment's own hover, any number for a link's. */\n readonly keys: readonly string[];\n readonly source: HoverSource;\n /** Whether their hover runs play: a link with `effects: false` keeps its marks to emphasis and dimming. */\n readonly effects: boolean;\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n/**\n * Host roles around named marks that unwrapNames takes off when they have no name: images, read as\n * one picture whose children screen readers may skip (`image` is ARIA 1.3's name for `img`), and\n * `graphics-object`, which takes its name from its contents, so the marks' names would be read twice.\n */\nconst WRAPPING_ROLES = new Set([\"img\", \"image\", \"graphics-symbol\", \"graphics-object\"]);\n\nexport function expressive<D>(target: MarkSource<D>, options: ExpressiveOptions<D>, env: ChartEnv): Attachment<D> {\n checkOptions(options);\n const motion = chartMotion(options.motion, env.motion);\n const effects = resolveEffects(options.on, env.presets);\n const clock = env.clock ?? defaultClock;\n const dim = options.dim === true;\n const edits = hostEdits();\n /** The host's colours per element, kept while an effect or the hover colour overrides them. */\n const colorCache = new WeakMap<Element, ReturnType<typeof hostColors>>();\n let source = target;\n let warnedIndex = false;\n let warnedImage = false;\n\n // ── Reading the host's marks ───────────────────────────────────────────────\n\n /** Reads every mark from `from`, changing nothing: it throws on marks it can't read. */\n function read(from: MarkSource<D>): Reading<D> {\n const { elements, data } = readSource(from);\n if (elements.length === 0) return { root: undefined, ancestor: undefined, marks: [] };\n const svg = rootOf(elements);\n const common = commonAncestor(elements, svg);\n\n const groups = new Map<string, Piece<D>[]>();\n elements.forEach((element, index) => {\n const datum = datumOf(element, index, data);\n const raw: unknown = options.key(datum, element);\n if (raw === undefined || raw === null || raw === \"\") {\n throw new TypeError(`expressive: key returned ${JSON.stringify(raw) ?? String(raw)} for a <${element.localName}>. Every mark needs a key.`);\n }\n const key = String(raw);\n const series = segmentOf(datum, element, key);\n let group = groups.get(key);\n if (!group) groups.set(key, (group = []));\n else if (series === undefined) throw new RangeError(`expressive: two elements have the key \"${key}\". Keys must be unique, or name each part with segment.`);\n else if (group.some((part) => part.series === series)) throw new RangeError(`expressive: the mark \"${key}\" has two \"${series}\" segments.`);\n group.push({ element, datum, series, value: options.value?.(datum, element) });\n });\n\n const at: ReadContext = { svg, common, screen: screenMatrices(), colors: (element) => colorsOf(element, svg) };\n const named = (mark: Unnamed<D>): Drawn<D> => ({ ...mark, label: labelOf(mark.key, mark.parts) });\n const keys = [...groups.keys()];\n\n if (options.geometry) {\n const marks = keys.map((key, index) => named(shapeMark(key, groups.get(key)!, index, at)));\n return { root: svg, ancestor: common, marks: checkNeeds(withData(ringOrder(marks, (mark) => mark.geometry))) };\n }\n\n const rects = keys.map((key) => groups.get(key)!.map((piece) => rectPiece(key, piece, at)));\n const boxes = rects.map((pieces) => union(pieces.map((p) => p.rect.box)));\n const edges = baselines(boxes, options.baseline ?? \"auto\");\n const marks = visualOrder(boxes, edges).map((i) => named(rectMark(keys[i]!, rects[i]!, edges[i]!, i, at)));\n return { root: svg, ancestor: common, marks: checkNeeds(withData(marks)) };\n }\n\n /** A mark described with `geometry`, from its elements in source order. */\n function shapeMark(key: string, pieces: readonly Piece<D>[], index: number, at: ReadContext): Unnamed<D> {\n const first = pieces[0]!;\n const geometry = options.geometry!(first.element, first.datum, key);\n if (typeof geometry !== \"object\" || geometry === null || geometry.key !== key) {\n throw new TypeError(`expressive: geometry for \"${key}\" must be a MarkGeometry with the key \"${key}\". Build it with describe and the key passed in.`);\n }\n const parts = pieces.map((p) => part(p, outlineOf(geometry, p.series, pieces.length), at));\n return { key, geometry, parts, index };\n }\n\n /**\n * A <rect>'s box in the marks' common coordinates, through its parent's coordinates and its own\n * transform attribute. Its own CSS transform is the adapter's (an effect's), so it isn't read back.\n * Other elements, and rects that aren't upright, throw.\n */\n function rectPiece(key: string, piece: Piece<D>, at: ReadContext): Piece<D> & { readonly rect: RectPart } {\n if (piece.element.localName !== \"rect\") {\n throw new TypeError(`expressive: can't read the geometry of a <${piece.element.localName}> (mark \"${key}\"). Only <rect> marks are read; describe others with the geometry option.`);\n }\n const m = matrix.multiply(between(at.common, piece.element.parentElement ?? at.svg, at.svg, at.screen), ownTransform(piece.element));\n if (!axisAligned(m)) {\n throw new TypeError(`expressive: the <rect> of \"${key}\" is rotated or skewed, so it isn't an upright bar. Describe it with the geometry option.`);\n }\n return { ...piece, rect: { box: boxIn(m, rectOf(piece.element)), series: piece.series, radius: radiusOf(piece.element) } };\n }\n\n /** A bar from its rects, growing from `edge`: its parts go from the baseline. */\n function rectMark(key: string, pieces: readonly (Piece<D> & { readonly rect: RectPart })[], edge: Baseline, index: number, at: ReadContext): Unnamed<D> {\n const { geometry, order } = describeRects(key, pieces.map((p) => p.rect), edge);\n const segments = geometry.segments ?? [];\n const parts = order.map((j, n) => {\n const segment = segments[n];\n return part(pieces[j]!, segment && segment.length >= 0.5 ? { d: segment.outline.d } : undefined, at);\n });\n return { key, geometry, parts, index, rect: { edge, box: union(pieces.map((p) => p.rect.box)) } };\n }\n\n function part(piece: Piece<D>, outline: Part<D>[\"outline\"], at: ReadContext): Part<D> {\n const parent = between(at.common, piece.element.parentElement ?? at.svg, at.svg, at.screen);\n return { element: piece.element, datum: piece.datum, series: piece.series, value: piece.value, parent, parentInverse: tryInvert(parent), colors: at.colors(piece.element), outline };\n }\n\n /**\n * Each mark's data, in the order given: its first part's row and its samples. `related(series)` is\n * the mark's own segment of that series, or else the first other live mark, in visual order, whose\n * series has that name, such as another of a D3 chart's line paths. It's looked up when called, so\n * it sees that mark as last read, by refresh() or by watch. Samples are read and checked here, so\n * bad ones throw before anything changes.\n */\n function withData(marks: readonly Drawn<D>[]): ReadMark<D>[] {\n return marks.map((mark): ReadMark<D> => {\n const { key, geometry, parts } = mark;\n const total = mark.rect ? totalOf(parts) : undefined;\n const samplesOf = (datum: D, of: MarkGeometry, series?: string): readonly Sample[] => {\n if (options.samples) return checkSamples(options.samples(datum, of), series === undefined ? `\"${key}\"` : `\"${key}\" (${series})`);\n return total === undefined ? [] : barSamples(geometry, of, total);\n };\n const own = new Map<string, MarkData<D>>();\n const related = (series: string): MarkData<D> | undefined => own.get(series) ?? relatedOf(series, key);\n for (const series of ownSeries(mark)) {\n const datum = (parts.find((p) => p.series === series) ?? parts[0]!).datum;\n own.set(series, { datum, samples: samplesOf(datum, geometry.segments?.find((s) => s.series === series) ?? geometry, series), related });\n }\n return { ...mark, data: { datum: parts[0]!.datum, samples: samplesOf(parts[0]!.datum, geometry), related } };\n });\n }\n\n /**\n * Data effects name the series they read through `needs.related`, and the marks must have them, so\n * a missing series throws instead of the effect drawing nothing. With no marks yet, there's nothing to check.\n */\n function checkNeeds(marks: ReadMark<D>[]): ReadMark<D>[] {\n if (marks.length === 0) return marks;\n const series = new Set(marks.flatMap((mark) => [...(mark.geometry.series === undefined ? [] : [mark.geometry.series]), ...ownSeries(mark)]));\n for (const slot of EFFECT_SLOTS) {\n const effect = effects[slot];\n if (effect?.kind !== \"data\") continue;\n for (const name of effect.needs?.related ?? []) {\n if (series.has(name)) continue;\n const known = series.size > 0 ? `the marks' series are ${[...series].map((s) => `\"${s}\"`).join(\", \")}` : \"the marks have no series\";\n throw new RangeError(\n `expressive: on.${slot} needs the series \"${name}\", but ${known}. Name each mark's series in its geometry (describe.line({ key, series, … })), or a stack's parts with segment.`\n );\n }\n }\n return marks;\n }\n\n function datumOf(element: Element, index: number, data: readonly D[] | undefined): D {\n if (options.datum) return options.datum(element);\n if (data) return data[index]!;\n const bound = (element as Element & { __data__?: unknown }).__data__;\n if (typeof bound === \"number\" && !warnedIndex) {\n warnedIndex = true;\n console.warn(\"expressive: element.__data__ is a number, which looks like Observable Plot's row index. Pass datum: (el) => rows[el.__data__].\");\n }\n return bound as D;\n }\n\n function segmentOf(datum: D, element: Element, key: string): string | undefined {\n if (!options.segment) return undefined;\n const series: unknown = options.segment(datum, element);\n if (series === undefined || series === null || series === \"\") throw new TypeError(`expressive: segment returned ${String(series)} for a part of \"${key}\".`);\n return String(series);\n }\n\n /** `markLabel`'s name for a mark. Empty, or a throw (reported), is undefined: the host's own ARIA stays. */\n function labelOf(key: string, parts: readonly Part<D>[]): string | undefined {\n if (!options.markLabel) return undefined;\n try {\n const text = String(options.markLabel(parts[0]!.datum, { key, parts: parts.map(({ series, datum }) => ({ series, datum })) }) ?? \"\");\n return text.trim() === \"\" ? undefined : text;\n } catch (error) {\n report(error);\n return undefined;\n }\n }\n\n function colorsOf(element: Element, svg: Element): HostPart[\"colors\"] {\n // While an effect or the hover colour sets it, the computed one is ours: keep the host's from before.\n if ((edits.styled(element, \"fill\") || edits.styled(element, \"stroke\")) && colorCache.has(element)) return colorCache.get(element);\n const colors = hostColors(element, svg);\n colorCache.set(element, colors);\n return colors;\n }\n\n // ── State and the overlay ──────────────────────────────────────────────────\n\n const first = read(source);\n const doc = first.root?.ownerDocument ?? (typeof document === \"undefined\" ? undefined : document);\n if (!doc) throw new TypeError(\"expressive needs a DOM.\");\n // The theme tokens the overlay and the focus ring draw in, and the dimming rules: shared, so it stays.\n injectStyles(doc);\n\n let root: SVGSVGElement | undefined;\n let ancestor: Element | undefined;\n /** Live marks by key, and in visual order. */\n const records = new Map<string, MarkRecord<D>>();\n let order: MarkRecord<D>[] = [];\n /** Marks whose exit effects are still running. */\n const leaving = new Map<string, MarkRecord<D>>();\n /** Every live mark's elements. Events find their mark through it. */\n let owners = new Map<Element, Owner<D>>();\n /** The host's elements around named marks whose role we took off (unwrapNames). */\n let unwrapped = new Set<Element>();\n const listeners: Listeners<D> = { enter: new Set(), update: new Set(), exit: new Set(), hover: new Set(), leave: new Set() };\n let hovered: Hovered | undefined;\n /** The mark showing the focus ring. */\n let ringKey: string | undefined;\n let interaction: PointerHover | undefined;\n /** The link the attachment is in, which hears its own hovers. */\n let linked: LinkListener | undefined;\n let destroyed = false;\n\n const make = <K extends keyof SVGElementTagNameMap>(tag: K, attributes: Record<string, string>, parent?: Element): SVGElementTagNameMap[K] => {\n const created = doc.createElementNS(SVG_NS, tag) as SVGElementTagNameMap[K];\n setAttributes(created, attributes);\n parent?.appendChild(created);\n return created;\n };\n const overlay = make(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" });\n setStyles(overlay, { \"pointer-events\": \"none\" });\n const halos = make(\"g\", { class: \"ec-halos\" }, overlay);\n const runs = make(\"g\", { class: \"ec-runs\" }, overlay);\n // The overlay is above the marks, so the ring is masked to outside the mark and its gap: it can't\n // cover data or merge with a bar in the focus colour. The gap is left clear rather than painted in\n // --ec-surface as on barChart, since a host's background may be another colour.\n const ring = maskedRing(overlay);\n\n const find = (key: string): MarkRecord<D> | undefined => records.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay: runs,\n // Looked up on each call, so the handle follows the mark's record.\n mark: (key) => ({\n set: (style) => find(key)?.handle.set(style),\n reset: () => find(key)?.handle.reset()\n }),\n colors: (key) => find(key)?.mark.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const input = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.mark.geometry, data: record.mark.data });\n\n function createRecord(mark: ReadMark<D>): MarkRecord<D> {\n const record: MarkRecord<D> = {\n key: mark.key,\n mark,\n // A leaving mark's elements may already belong to another mark (a join by index): leave those alone.\n handle: hostMarkHandle(() => record.mark.parts.filter((p) => (owners.get(p.element)?.record ?? record) === record), edits, () => halos)\n };\n return record;\n }\n\n // ── Applying a reading ─────────────────────────────────────────────────────\n\n /** Brings the attachment to `reading` and says what changed. Leaving marks stay until their exit is done. */\n function apply(reading: Reading<D>): Diff<D> {\n if (reading.root && reading.root !== root) moveTo(reading.root);\n ancestor = reading.ancestor ?? ancestor;\n const keys = new Set(reading.marks.map((mark) => mark.key));\n const diff: Diff<D> = { entering: [], exiting: [], changed: [], moved: [], newRow: false };\n const recolor: string[] = [];\n for (const record of order) {\n if (keys.has(record.key)) continue;\n records.delete(record.key);\n leaving.set(record.key, record);\n diff.exiting.push(record);\n }\n const before = owners;\n owners = new Map();\n order = reading.marks.map((mark) => {\n let record = records.get(mark.key);\n if (record) {\n const from = record.mark;\n // With `value`, a resize or a new axis maximum only moves marks, as on our charts.\n const changed = options.value ? valuesChanged(from.parts, mark.parts) : lengthsChanged(from.geometry, mark.geometry);\n const newRow = from.data.datum !== mark.data.datum;\n if (newRow) diff.newRow = true;\n if (changed) diff.changed.push({ record, from: from.geometry });\n else if (newRow || geometryChanged(from.geometry, mark.geometry) || samplesChanged(from.data.samples, mark.data.samples)) {\n diff.moved.push(record);\n }\n if (from.parts[0]?.colors?.color !== mark.parts[0]?.colors?.color) recolor.push(mark.key);\n record.mark = mark;\n } else {\n // A mark that comes back mid-exit keeps its record; the runner cancels its exit.\n record = leaving.get(mark.key);\n if (record) {\n leaving.delete(mark.key);\n record.mark = mark;\n } else {\n record = createRecord(mark);\n }\n records.set(mark.key, record);\n diff.entering.push(record);\n }\n for (const part of mark.parts) owners.set(part.element, { record, part });\n return record;\n });\n // Elements that left their mark, or moved to another one, get back what the host had.\n for (const [el, owner] of before) if (owners.get(el)?.record !== owner.record) edits.restore(el);\n for (const record of order) nameMark(record);\n unwrapNames();\n\n placeOverlay();\n applyDim();\n for (const record of order) record.handle.repaint();\n for (const key of recolor) surface.recolor(key);\n drawRing();\n return diff;\n }\n\n /**\n * With `markLabel`, a mark is read as one item: the element that takes its focus is an image named\n * by it (and shown, even if the host hid it), and its other parts are hidden. Each is written again\n * on every read, since a part can become the first (a stack gains a segment) or stop being it.\n */\n function nameMark(record: MarkRecord<D>): void {\n if (!options.markLabel) return;\n const { label, parts } = record.mark;\n parts.forEach((part, index) => {\n const named = label !== undefined && index === 0;\n edits.attribute(part.element, \"role\", named ? \"img\" : null);\n edits.attribute(part.element, \"aria-label\", named ? label : null);\n if (named) edits.remove(part.element, \"aria-hidden\");\n else edits.attribute(part.element, \"aria-hidden\", label === undefined ? null : \"true\");\n });\n }\n\n /**\n * With `markLabel`, the host's unnamed elements around a named mark's parts lose a wrapping role\n * (WRAPPING_ROLES) and its `aria-roledescription`, so the marks are read as the host's own `<g>`s\n * would leave them: once each, by name. Vega gives the group around each line `graphics-symbol`, an\n * image with no name (which fails WCAG 1.1.1), and the groups above it `graphics-object`. It writes\n * them again when it redraws, so they're taken off on every read, and an element with no named mark\n * inside any more gets its role back.\n */\n function unwrapNames(): void {\n const svg = root;\n const next = new Set<Element>();\n for (const record of options.markLabel && svg ? order : []) {\n if (record.mark.label === undefined) continue;\n for (const part of record.mark.parts) {\n for (let element: Element | null = part.element.parentElement; element && element !== svg && svg?.contains(element); element = element.parentElement) {\n if (next.has(element) || element.hasAttribute(\"aria-label\") || element.hasAttribute(\"aria-labelledby\")) continue;\n const role = element.getAttribute(\"role\")?.trim().split(/\\s+/)[0];\n if ((role !== undefined && WRAPPING_ROLES.has(role)) || (role === undefined && unwrapped.has(element))) next.add(element);\n }\n }\n }\n for (const element of unwrapped) {\n if (next.has(element)) continue;\n edits.attribute(element, \"role\", null);\n edits.attribute(element, \"aria-roledescription\", null);\n }\n for (const element of next) {\n edits.remove(element, \"role\");\n edits.remove(element, \"aria-roledescription\");\n }\n unwrapped = next;\n }\n\n /** The overlay is the root's last child, in the common ancestor's coordinates. */\n function placeOverlay(): void {\n if (!root || !ancestor) return;\n if (root.lastElementChild !== overlay) root.appendChild(overlay);\n overlay.removeAttribute(\"transform\");\n const m = between(overlay, ancestor, root);\n if (!isIdentity(m)) overlay.setAttribute(\"transform\", transformAttribute(m));\n }\n\n /** Listens on a new root <svg> (Plot draws a new one each time) and moves the overlay there. */\n function moveTo(next: SVGSVGElement): void {\n detach();\n root = next;\n root.appendChild(overlay);\n if ((options.keyboard === true || options.markLabel) && root.getAttribute(\"role\") === \"img\" && !warnedImage) {\n warnedImage = true;\n console.warn('expressive: the <svg> is role=\"img\", so screen readers read it as one picture and skip the marks inside, with their names and keyboard focus. Make it role=\"group\"; its aria-label can stay.');\n }\n interaction = pointerHover(root, {\n find(eventTarget) {\n const owner = ownerOf(eventTarget);\n if (!owner) return undefined;\n const { key } = owner.record;\n return owner.part.series === undefined ? { key } : { key, segment: owner.part.series };\n },\n hover(hoverTarget, from) {\n const record = records.get(hoverTarget.key);\n // Already playing for keyboard focus: let it go on.\n if (!record || (own(hovered) && hovered.keys[0] === hoverTarget.key)) return;\n endHover();\n startHover([record], from, hoverTarget.segment);\n },\n leave() {\n // Focus holds a keyboard hover until blur or Escape, and a link holds its own.\n if (hovered?.source === \"pointer\" || hovered?.source === \"touch\") endHover();\n }\n });\n }\n\n /** Stops listening on the current root. */\n function detach(): void {\n if (!root) return;\n endHover();\n interaction?.destroy();\n interaction = undefined;\n }\n\n function ownerOf(eventTarget: EventTarget | null): Owner<D> | undefined {\n for (let node = eventTarget as Element | null; node && node !== root; node = node.parentElement) {\n const owner = owners.get(node);\n if (owner) return owner;\n }\n return undefined;\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /** Pointer, keyboard and link hover share this; the attachment's own tells its link. */\n function startHover(marks: readonly MarkRecord<D>[], from: HoverSource, segment?: string, effects = true): void {\n const started: Hovered = { keys: marks.map((record) => record.key), source: from, effects };\n hovered = started;\n applyDim();\n if (effects) runner.hover(marks.map(input));\n marks.forEach((record, index) => emit(\"hover\", { ...input(record), batch: { index, count: marks.length }, source: from, ...(segment === undefined ? {} : { segment }) }));\n // A listener may have ended it (a refresh() that removed the mark) or started another (focus()), which told the link itself.\n if (from !== \"linked\" && hovered === started) linked?.hover(marks.map(input));\n }\n\n function endHover(): void {\n const current = hovered;\n if (!current) return;\n hovered = undefined;\n applyDim();\n leaveMarks(current.keys);\n if (own(current)) linked?.leave();\n }\n\n /** The marks' hover runs end in one batch, and each gets a leave event. */\n function leaveMarks(keys: readonly string[]): void {\n const marks = keys.flatMap((key) => find(key) ?? []);\n runner.leave(keys);\n marks.forEach((record, index) => emit(\"leave\", { ...input(record), batch: { index, count: marks.length } }));\n }\n\n /** After a read: a hover whose marks have all left ends, and a link's goes on with those still here. */\n function dropGone(): void {\n if (hovered === undefined) return;\n const keys = hovered.keys.filter((key) => records.has(key));\n if (keys.length === hovered.keys.length) return;\n if (keys.length === 0) {\n interaction?.clear();\n endHover();\n return;\n }\n const gone = hovered.keys.filter((key) => !records.has(key));\n hovered = { ...hovered, keys };\n leaveMarks(gone);\n }\n\n /**\n * With `dim`, this attachment's other marks fade while one is hovered, and the hovered one takes its\n * strong colour (its fill, or its stroke on a line), as on our charts. The fade is classes, so host\n * CSS can override it, and only on its own marks, so attachments sharing an <svg> leave each other alone.\n * Both are CSS transitions timed by motion, like the charts'.\n */\n function applyDim(): void {\n if (!dim) return;\n const duration = `${motion.duration(100, \"feedback\")}ms`;\n for (const record of order) {\n const hot = hovered?.keys.includes(record.key) === true;\n for (const part of record.mark.parts) {\n edits.toggleClass(part.element, \"ec-attached\", true);\n edits.toggleClass(part.element, \"ec-dimmed\", hovered !== undefined && !hot);\n edits.style(part.element, \"--ec-hover-duration\", duration);\n }\n record.handle.hot(hot);\n }\n for (const record of leaving.values()) record.handle.hot(false);\n }\n\n const unsubscribeMotion = dim ? motion.subscribe(applyDim) : undefined;\n\n /** The series data effects read through `related`, maybe from other marks. */\n const needed = new Set(\n EFFECT_SLOTS.flatMap((slot) => {\n const effect = effects[slot];\n return effect?.kind === \"data\" ? (effect.needs?.related ?? []) : [];\n })\n );\n\n // ── Keyboard ───────────────────────────────────────────────────────────────\n\n /** The focus ring follows the mark's outline, drawn in the overlay. An open outline (a line from `geometry`) is ringed outside its stroke. */\n function drawRing(): void {\n const record = ringKey === undefined ? undefined : records.get(ringKey);\n ring.draw(record?.mark.geometry);\n }\n\n // barChart's keyboard focus, with the same hover rules: on the host's elements, written through\n // the edits so destroy() puts back what they had.\n const keyboard =\n options.keyboard === true\n ? keyboardFocus(() => root, {\n find: (eventTarget) => ownerOf(eventTarget)?.record.key,\n order: () => order.map((record) => record.key),\n element: (key) => records.get(key)?.mark.parts[0]?.element as SVGElement | undefined,\n tabIndex(key, value) {\n // A mark that left: apply() already gave its elements back what the host had.\n const record = records.get(key);\n if (!record || value === undefined) return;\n // The first element takes the mark's focus; a click can focus the others. The ring stands in for their own outline.\n record.mark.parts.forEach((part, index) => {\n edits.attribute(part.element, \"tabindex\", index === 0 ? value : \"-1\");\n edits.style(part.element, \"outline\", \"none\");\n });\n },\n focus(key, visible) {\n ringKey = visible ? key : undefined;\n drawRing();\n const record = records.get(key);\n if (!record) return;\n if (!visible) {\n // Focus from a click or tap: the pointer's own hover plays.\n if (hovered?.source === \"keyboard\" && hovered.keys[0] !== key) endHover();\n return;\n }\n if (own(hovered) && hovered.keys[0] === key) {\n // Already playing for the pointer: it goes on, held by focus now.\n hovered = { ...hovered, source: \"keyboard\" };\n return;\n }\n endHover();\n startHover([record], \"keyboard\");\n },\n blur() {\n ringKey = undefined;\n drawRing();\n if (hovered?.source !== \"keyboard\") return;\n // The pointer is still over it: the hover goes on, held by the pointer now.\n if (interaction?.current === hovered.keys[0]) hovered = { ...hovered, source: \"pointer\" };\n else endHover();\n },\n escape() {\n if (!hovered) return false;\n // A link's hover ends where it started, and with it every chart's in the link.\n if (hovered.source === \"linked\" && linked) linked.dismiss();\n else endHover();\n return true;\n }\n })\n : undefined;\n\n // ── Watching the host ──────────────────────────────────────────────────────\n\n const watching = options.watch === true ? watchHost(doc, clock, follow) : undefined;\n\n /** Watches the live marks' elements from now on, and drops changes not followed yet: the caller has just read them all. */\n function watchMarks(): void {\n watching?.observe(\n order.flatMap((record) => record.mark.parts.map((part) => part.element)),\n root\n );\n }\n\n /**\n * A frame's changes, with `watch`. The marks whose geometry attributes changed, and every mark inside\n * an ancestor that moved below the marks' common ancestor, are read again, put in visual order again\n * and followed through change(), with no events and no interrupt, as on our charts' frames. An\n * ancestor at or above the common ancestor moves the overlay: the marks' geometry is in that\n * ancestor's coordinates, so it hasn't changed.\n */\n function follow(changes: WatchedChanges): void {\n if (destroyed || !ancestor) return;\n const changed = new Set<MarkRecord<D>>();\n for (const element of changes.marks) {\n const record = owners.get(element)?.record;\n if (record) changed.add(record);\n }\n let overlayMoved = false;\n for (const element of changes.ancestors) {\n if (element.contains(ancestor)) overlayMoved = true;\n else for (const record of order) if (record.mark.parts.some((part) => element.contains(part.element))) changed.add(record);\n }\n if (overlayMoved) placeOverlay();\n if (changed.size === 0) return;\n\n // Throws (reported by the clock) on marks it can't read, before anything changes.\n const { records, marks } = reread([...changed]);\n records.forEach((record, i) => {\n const mark = marks[i]!;\n record.mark = mark;\n for (const part of mark.parts) owners.set(part.element, { record, part });\n record.handle.repaint();\n });\n order = visual(order);\n if (records.some((record) => record.key === ringKey)) drawRing();\n // As in refresh(): when a mark of a series a data effect needs moves, every other live mark follows too.\n const following = new Set(records);\n if (records.some((record) => needed.has(record.mark.geometry.series ?? \"\"))) for (const record of order) following.add(record);\n for (const record of following) runner.change(record.mark.geometry, record.mark.data);\n }\n\n /**\n * The marks that changed again, as the host draws them now: their rows, geometry and samples, in the\n * coordinates of the last full read. Their values, colours and names stay as that read found them,\n * and so do their elements. Bars whose baseline changed come too, though they didn't move. Throws,\n * changing nothing, on marks it can't read.\n */\n function reread(changed: readonly MarkRecord<D>[]): { readonly records: MarkRecord<D>[]; readonly marks: ReadMark<D>[] } {\n const at: ReadContext = { svg: root!, common: ancestor!, screen: screenMatrices(), colors: (element) => owners.get(element)?.part.colors };\n const rowOf = rowsNow();\n const piecesOf = ({ parts }: ReadMark<D>): Piece<D>[] => parts.map((part) => ({ element: part.element, datum: rowOf(part.element), series: part.series, value: part.value }));\n if (options.geometry) {\n const marks = changed.map(({ mark }): Drawn<D> => ({ ...shapeMark(mark.key, piecesOf(mark), mark.index, at), label: mark.label }));\n return { records: [...changed], marks: withData(marks) };\n }\n const rects = new Map(changed.map((record) => [record, piecesOf(record.mark).map((piece) => rectPiece(record.key, piece, at))]));\n const edges = edgesNow(rects);\n for (const record of order) {\n if (!rects.has(record) && edges.get(record) !== record.mark.rect!.edge) rects.set(record, piecesOf(record.mark).map((piece) => rectPiece(record.key, piece, at)));\n }\n const records = [...rects.keys()];\n const marks = records.map((record): Drawn<D> => ({ ...rectMark(record.key, rects.get(record)!, edges.get(record)!, record.mark.index, at), label: record.mark.label }));\n return { records, marks: withData(marks) };\n }\n\n /**\n * Each live bar's baseline now. With \"auto\", the edge every bar shares is found again from their\n * boxes (the new ones of the bars read this frame), as a full read would, so a bar that ends a\n * transition on the other side of the line grows from it the other way. In a frame where no edge is\n * shared (a bar crossing the line), each keeps the one it had.\n */\n function edgesNow(rects: ReadonlyMap<MarkRecord<D>, readonly (Piece<D> & { readonly rect: RectPart })[]>): Map<MarkRecord<D>, Baseline> {\n const kept = new Map(order.map((record) => [record, record.mark.rect!.edge]));\n if (options.baseline !== undefined && options.baseline !== \"auto\") return kept;\n const boxes = order.map((record) => {\n const pieces = rects.get(record);\n return pieces ? union(pieces.map((p) => p.rect.box)) : record.mark.rect!.box;\n });\n try {\n const found = baselines(boxes, \"auto\");\n return new Map(order.map((record, i) => [record, found[i]!]));\n } catch {\n return kept;\n }\n }\n\n /** Each element's row now: `datum`'s, a selection's data(), or the element's own `__data__`. */\n function rowsNow(): (element: Element) => D {\n if (options.datum) return options.datum;\n const bound = boundRows(source);\n return (element) => (bound?.has(element) ? bound.get(element)! : datumOf(element, 0, undefined));\n }\n\n /** The records in visual order, as read() orders marks: by their place in the source and, for bars, their boxes. */\n function visual(records: readonly MarkRecord<D>[]): MarkRecord<D>[] {\n const bySource = [...records].sort((a, b) => a.mark.index - b.mark.index);\n if (options.geometry) return [...ringOrder(bySource, (record) => record.mark.geometry)];\n const boxes = bySource.map((record) => record.mark.rect!.box);\n const edges = bySource.map((record) => record.mark.rect!.edge);\n return visualOrder(boxes, edges).map((i) => bySource[i]!);\n }\n\n /** The first other live mark of that series, in visual order: another of a D3 chart's line paths. */\n function relatedOf(series: string, key: string): MarkData<D> | undefined {\n return order.find((record) => record.key !== key && record.mark.geometry.series === series)?.mark.data;\n }\n\n // ── Events ─────────────────────────────────────────────────────────────────\n\n function emit<K extends keyof MarkEvents<D>>(type: K, event: MarkEvents<D>[K]): void {\n for (const listener of [...listeners[type]]) {\n try {\n listener(event);\n } catch (error) {\n report(error);\n }\n }\n }\n\n function emitEach(type: \"enter\" | \"exit\", marks: readonly MarkRecord<D>[]): void {\n marks.forEach((record, index) => emit(type, { ...input(record), batch: { index, count: marks.length } }));\n }\n\n // ── First read ─────────────────────────────────────────────────────────────\n\n runner.enter(apply(first).entering.map(input));\n keyboard?.sync();\n watchMarks();\n\n const link: LinkPort = {\n targets: () => order.map((record) => ({ key: record.key, marks: [input(record)] })),\n hover(keys, effects) {\n endHover();\n const marks = keys.flatMap((key) => records.get(key) ?? []);\n if (marks.length > 0) startHover(marks, \"linked\", undefined, effects);\n },\n unlink() {\n if (hovered?.source === \"linked\") endHover();\n },\n leave() {\n interaction?.clear();\n endHover();\n },\n listen(listener) {\n if (destroyed) return false;\n linked = listener;\n return true;\n }\n };\n\n return linkable(link, {\n refresh(next) {\n if (destroyed) return;\n // Throws on marks it can't read, before anything changes.\n const reading = read(next ?? source);\n if (next !== undefined) source = next;\n\n // The order the runner expects: interrupt, then exit / update / enter, then change, then settle.\n runner.interrupt();\n const diff = apply(reading);\n watchMarks();\n dropGone();\n const exited = runner.exit(diff.exiting.map(input));\n emitEach(\"exit\", diff.exiting);\n // A new row, a new value, or a mark come or gone is an update: it ends the update runs of the\n // marks it leaves alone. A read that finds none (a Vega render for a hover signal) keeps them.\n if (diff.newRow || diff.changed.length > 0 || diff.entering.length > 0 || diff.exiting.length > 0) {\n runner.update(diff.changed.map(({ record, from }) => ({ ...input(record), from })));\n }\n diff.changed.forEach(({ record, from }, index) => emit(\"update\", { ...input(record), from, batch: { index, count: diff.changed.length } }));\n runner.enter(diff.entering.map(input));\n emitEach(\"enter\", diff.entering);\n // A data effect can read another mark through related(series): when a mark of a series one needs\n // changes, moves, comes or goes, every other live mark follows too, with data that sees it.\n const following = new Set([...diff.changed.map((c) => c.record), ...diff.moved]);\n if ([...following, ...diff.entering, ...diff.exiting].some((record) => needed.has(record.mark.geometry.series ?? \"\"))) {\n const entering = new Set(diff.entering);\n for (const record of order) if (!entering.has(record)) following.add(record);\n }\n for (const record of following) runner.change(record.mark.geometry, record.mark.data);\n runner.settle();\n // Focus stays with its key, on the mark's new element if the host replaced it (Vega does). If the\n // mark left, focus moves to its nearest neighbour. Every mark's tabindex is set again.\n keyboard?.sync();\n\n void exited.then(() => {\n for (const record of diff.exiting) if (leaving.get(record.key) === record) leaving.delete(record.key);\n });\n },\n\n on(type, listener) {\n const set = listeners[type] as Set<typeof listener> | undefined;\n if (!set) throw new TypeError(`expressive: unknown event \"${String(type)}\". Use one of: ${Object.keys(listeners).join(\", \")}.`);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n },\n\n marks: () => order.map((record) => record.mark.geometry),\n\n focus(key) {\n if (records.has(key) && !destroyed) keyboard?.focus(key);\n },\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n hovered = undefined;\n linked?.gone();\n linked = undefined;\n watching?.destroy();\n // The runner resets every mark it styled, through the records, so it goes first.\n runner.destroy();\n unsubscribeMotion?.();\n keyboard?.destroy();\n detach();\n overlay.remove();\n edits.restoreAll();\n for (const set of Object.values(listeners)) set.clear();\n records.clear();\n leaving.clear();\n order = [];\n owners = new Map();\n }\n });\n}\n\nfunction checkOptions<D>(options: ExpressiveOptions<D>): void {\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"expressive needs options, with at least a key: { key: (d) => d.name }.\");\n if (typeof options.key !== \"function\") throw new TypeError(\"expressive needs a key function, for example key: (d) => d.name. Marks are matched by key.\");\n for (const name of [\"datum\", \"segment\", \"value\", \"geometry\", \"markLabel\"] as const) {\n if (options[name] !== undefined && typeof options[name] !== \"function\") throw new TypeError(`expressive: ${name} must be a function.`);\n }\n if (options.baseline !== undefined && options.baseline !== \"auto\" && !isBaseline(options.baseline)) {\n throw new RangeError(`expressive: baseline must be \"left\", \"right\", \"top\", \"bottom\" or \"auto\", got ${String(options.baseline)}.`);\n }\n}\n\n/** The series a mark has of its own: its segments' and its parts'. */\nfunction ownSeries<D>(mark: Drawn<D>): string[] {\n const names = [...(mark.geometry.segments ?? []).map((s) => s.series), ...mark.parts.map((p) => p.series)];\n return [...new Set(names.filter((name): name is string => name !== undefined))];\n}\n\n/** A rect mark's total: the sum of its parts' values when every one is a finite number (from `value`), else undefined. */\nfunction totalOf<D>(parts: readonly Part<D>[]): number | undefined {\n let total = 0;\n for (const { value } of parts) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n total += value;\n }\n return total;\n}\n\n/**\n * The bar chart's samples: from 0 at the baseline to the total at the tip, values in proportion to\n * distance along the bar. A segment's run over its own span of it.\n */\nfunction barSamples(bar: MarkGeometry, of: MarkGeometry, total: number): Sample[] {\n const valueAt = (along: number): number => (bar.length > 0 ? (total * along) / bar.length : 0);\n if (of === bar) {\n return [\n { t: 0, value: 0 },\n { t: 1, value: total }\n ];\n }\n const from = distance(bar.start, of.start);\n return [\n { t: 0, value: valueAt(from) },\n { t: 1, value: valueAt(from + of.length) }\n ];\n}\n\n/** A copy of the page's samples, checked: t in [0, 1] and never decreasing, and finite values. */\nfunction checkSamples(samples: unknown, mark: string): Sample[] {\n if (!Array.isArray(samples)) throw new TypeError(`expressive: samples for ${mark} must return an array of { t, value }, got ${describeValue(samples)}.`);\n let last = 0;\n return samples.map((sample: unknown, i): Sample => {\n const { t, value, at, gapBefore } = (typeof sample === \"object\" && sample !== null ? sample : {}) as Partial<Sample>;\n if (typeof t !== \"number\" || !(t >= 0 && t <= 1)) throw new RangeError(`expressive: samples for ${mark}: samples[${i}].t must be in [0, 1], got ${describeValue(t)}.`);\n if (t < last) throw new RangeError(`expressive: samples for ${mark} must be in t order: samples[${i}].t is ${t}, after ${last}.`);\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new RangeError(`expressive: samples for ${mark}: samples[${i}].value must be a finite number, got ${describeValue(value)}.`);\n }\n if (gapBefore !== undefined && typeof gapBefore !== \"boolean\") {\n throw new RangeError(`expressive: samples for ${mark}: samples[${i}].gapBefore must be true or false, got ${describeValue(gapBefore)}.`);\n }\n last = t;\n return { t, value, ...(at === undefined ? {} : { at }), ...(gapBefore ? { gapBefore } : {}) };\n });\n}\n\nfunction describeValue(value: unknown): string {\n return typeof value === \"string\" ? JSON.stringify(value) : String(value);\n}\n\n/**\n * The visual order of marks described with `geometry`. Marks that go round one pivot (a pie's\n * slices) are ordered clockwise from 12 o'clock, by the angle of each mark's centre about the pivot,\n * as a ring is read: d3.pie() sorts slices by value but returns them in data order, so document\n * order jumps around the ring. Otherwise it's document order.\n */\nfunction ringOrder<T>(marks: readonly T[], geometryOf: (mark: T) => MarkGeometry): readonly T[] {\n const pivot = marks[0] && geometryOf(marks[0]).pivot;\n if (!pivot || !marks.every((mark) => distance(geometryOf(mark).pivot, pivot) <= 0.5 && goesRound(geometryOf(mark)))) return marks;\n const TURN = 2 * Math.PI;\n const clockwise = (mark: T): number => {\n const { center } = geometryOf(mark);\n // In [0, 2π): 0 straight up (y points down), turning towards +x.\n const angle = Math.atan2(center.x - pivot.x, pivot.y - center.y);\n const turned = angle < 0 ? angle + TURN : angle;\n return turned >= TURN ? 0 : turned;\n };\n // A stable sort: marks at one angle (dots on the pivot) keep document order.\n return marks\n .map((mark) => ({ mark, angle: clockwise(mark) }))\n .sort((a, b) => a.angle - b.angle)\n .map(({ mark }) => mark);\n}\n\nfunction distance(a: Point, b: Point): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\n/**\n * For a mark described with `geometry`: the part's own segment, or the whole mark for a lone part,\n * with the stroke's width when the outline is open (a line).\n */\nfunction outlineOf(geometry: MarkGeometry, series: string | undefined, parts: number): HostPart[\"outline\"] {\n const segment = series === undefined ? undefined : geometry.segments?.find((s) => s.series === series);\n const shape = segment ?? (parts === 1 ? geometry : undefined);\n if (!shape || (segment && segment.length < 0.5)) return undefined;\n return shape.outline.closed ? { d: shape.outline.d } : { d: shape.outline.d, stroke: shape.thickness };\n}\n\n/** The rect's corner radius: rx, or ry when only that is given. */\nfunction radiusOf(element: Element): number {\n const rx = Number.parseFloat(element.getAttribute(\"rx\") ?? \"\");\n const ry = Number.parseFloat(element.getAttribute(\"ry\") ?? \"\");\n const radius = Number.isFinite(rx) ? rx : ry;\n return Number.isFinite(radius) && radius > 0 ? radius : 0;\n}\n\nfunction tryInvert(m: Matrix): Matrix | undefined {\n try {\n return invert(m);\n } catch {\n return undefined;\n }\n}\n\nfunction isIdentity(m: Matrix): boolean {\n return Math.abs(m[0] - 1) < 1e-9 && Math.abs(m[1]) < 1e-9 && Math.abs(m[2]) < 1e-9 && Math.abs(m[3] - 1) < 1e-9 && Math.abs(m[4]) < 1e-6 && Math.abs(m[5]) < 1e-6;\n}\n\n/** A part's value changed, or the mark gained or lost a segment. Values compare like ===, but NaN equals NaN. */\nfunction valuesChanged<D>(from: readonly Part<D>[], to: readonly Part<D>[]): boolean {\n if (from.length !== to.length) return true;\n const before = new Map(from.map((part) => [part.series, part.value]));\n return to.some((part) => {\n const was = before.get(part.series);\n return !before.has(part.series) || !(was === part.value || Object.is(was, part.value));\n });\n}\n\n/** What the adapter can see of a change in values without `value`: a mark's length, or its segments' lengths. */\nfunction lengthsChanged(from: MarkGeometry, to: MarkGeometry): boolean {\n const a = from.segments ?? [];\n const b = to.segments ?? [];\n if (Math.abs(from.length - to.length) > 0.01 || a.length !== b.length) return true;\n return a.some((segment, i) => segment.key !== b[i]!.key || Math.abs(segment.length - b[i]!.length) > 0.01);\n}\n\n/** The page's samples changed, though the geometry and the row may not have. */\nfunction samplesChanged(from: readonly Sample[], to: readonly Sample[]): boolean {\n const sameAt = (a: Sample[\"at\"], b: Sample[\"at\"]): boolean => a === b || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime());\n return from.length !== to.length || from.some((a, i) => a.t !== to[i]!.t || a.value !== to[i]!.value || !sameAt(a.at, to[i]!.at));\n}\n\n/** Whether a mark moved: its outline, its segments, its thickness (which a line's stroke width changes alone), or its labels' boxes. */\nfunction geometryChanged(from: MarkGeometry, to: MarkGeometry): boolean {\n if (from.outline.d !== to.outline.d || from.thickness !== to.thickness || labelsMoved(from, to)) return true;\n const a = from.segments ?? [];\n const b = to.segments ?? [];\n return a.length !== b.length || a.some((segment, i) => segment.key !== b[i]!.key || segment.outline.d !== b[i]!.outline.d);\n}\n","// Vega and Vega-Lite views through expressive(): the marks Vega's SVG renderer draws, described from\n// its scenegraph rather than from the DOM. Each item Vega renders is bound to its element as\n// `__data__` (an internal the adapter spike found, so the tests pin Vega's version), the row is\n// `item.datum`, and the item's numbers give the geometry: rects become bars, arcs slices, symbols\n// points and lines lines, whose items give each vertex with its row, so samples come with them.\n// Duck-typed on the View: nothing here imports Vega, so it stays a dev dependency.\n\nimport type { Baseline, MarkGeometry, Matrix, Point, Rect, Sample } from \"../../core\";\nimport { defaultClock, describe, matrix, samplesAlong } from \"../../core\";\nimport { report } from \"../../core/report\";\nimport { linkable, portOf } from \"../link\";\nimport type { ChartEnv } from \"../shell/setup\";\nimport { baselines, describeRects, union, visualOrder, type RectPart } from \"./bars\";\nimport { expressive } from \"./expressive\";\nimport { commonAncestor, rootOf } from \"./source\";\nimport { between, boxIn, screenMatrices } from \"./space\";\nimport type { Attachment, ExpressiveOptions } from \"./types\";\n\n/**\n * What fromVegaView() uses of a Vega View: its renderer, its scenegraph and the element it renders\n * into. The scenegraph is read as `{ root }` (what Vega returns) or as the root mark itself (what\n * vega-typings declare), so a View fits whichever the types say.\n */\nexport interface VegaViewLike {\n renderer(): string;\n scenegraph(): object;\n container(): Element | null;\n}\n\n/** A mark in Vega's scenegraph: its type, its name, and its items. */\nexport interface VegaMark {\n readonly marktype?: string;\n readonly name?: string;\n readonly items?: readonly VegaItem[];\n}\n\n/** An item of a Vega mark, as its encoders left it. A group's items hold the marks inside it. */\nexport interface VegaItem {\n readonly mark?: VegaMark;\n readonly datum?: unknown;\n readonly items?: readonly VegaMark[];\n readonly x?: number;\n readonly y?: number;\n readonly width?: number;\n readonly height?: number;\n readonly startAngle?: number;\n readonly endAngle?: number;\n readonly innerRadius?: number;\n readonly outerRadius?: number;\n readonly size?: number;\n readonly strokeWidth?: number;\n readonly cornerRadius?: number;\n readonly defined?: boolean;\n /** How a line is drawn between its points: only \"linear\" (or unset) can be read. */\n readonly interpolate?: string;\n}\n\n/** A value for data effects: alone, or with where it is along x (`at`), which threshold matches series by. */\nexport type VegaSample = number | { readonly value: number; readonly at?: string | number | Date };\n\nexport interface VegaOptions<D> extends Omit<ExpressiveOptions<D>, \"datum\" | \"geometry\" | \"watch\"> {\n /** The Vega mark to read, by name. Default \"marks\", the name Vega-Lite gives a chart's data mark. */\n readonly mark?: string;\n /**\n * For data effects: the value an item's row shows, and optionally where it is along x. A line gets a\n * sample at each of its points, a bar from 0 at its baseline to its value (a stack's segments each over\n * their own range), a slice from 0 to its value, and a point its value. `samples` replaces this.\n * Unless `value` is given, it's also what each element shows (a line: every point's), so a re-render\n * that only moves marks, such as a resize, isn't an update.\n */\n readonly sample?: (row: D) => VegaSample;\n}\n\n/** fromVegaView()'s attachment: refresh() reads the View again (it refreshes itself after each render too). */\nexport interface VegaAttachment<D> extends Omit<Attachment<D>, \"refresh\"> {\n refresh(): void;\n}\n\nconst MARK_TYPES = [\"line\", \"rect\", \"arc\", \"symbol\"] as const;\ntype MarkType = (typeof MARK_TYPES)[number];\n\n/**\n * Attributes Vega writes when it draws marks somewhere new (a data change, a resize, a signal), and\n * `stroke-width`, which a line's thickness, and so its decorations and focus ring, are read from.\n */\nconst DRAWN = [\"d\", \"transform\", \"x\", \"y\", \"width\", \"height\", \"stroke-width\"];\n\n/** One read of the View: the elements to attach, in visual order, and each mark's geometry and samples. */\ninterface ViewRead {\n readonly root: SVGSVGElement | undefined;\n readonly elements: readonly Element[];\n readonly items: ReadonlyMap<Element, VegaItem>;\n readonly geometry: ReadonlyMap<string, MarkGeometry>;\n readonly samples: ReadonlyMap<MarkGeometry, readonly Sample[]>;\n /** What each element shows, from `sample`: a line's every point, so a resize isn't an update. */\n readonly values: ReadonlyMap<Element, string>;\n}\n\n/** A read being made. */\ninterface Reading {\n readonly root: SVGSVGElement;\n readonly elements: Element[];\n readonly items: Map<Element, VegaItem>;\n readonly geometry: Map<string, MarkGeometry>;\n readonly samples: Map<MarkGeometry, readonly Sample[]>;\n readonly values: Map<Element, string>;\n}\n\n/**\n * Effects on a Vega or Vega-Lite chart rendered as SVG: reads the named mark's items from the View's\n * scenegraph and attaches to the elements Vega drew for them, as expressive() would with `datum` and\n * `geometry` written for Vega. It reads the View again after every render that moves or replaces\n * those elements (a data change, a resize), so the page never calls refresh().\n */\nexport function fromVegaView<D = Record<string, unknown>>(view: VegaViewLike, options: VegaOptions<D>, env: ChartEnv): VegaAttachment<D> {\n checkView(view);\n if (typeof options !== \"object\" || options === null || typeof options.key !== \"function\") {\n throw new TypeError(\"fromVegaView needs options with a key: { key: (d) => d.series }. Marks are matched by key.\");\n }\n const name = options.mark ?? \"marks\";\n if (typeof name !== \"string\" || name === \"\") throw new TypeError(`fromVegaView: mark must be a mark's name, got ${String(name)}.`);\n if (options.sample !== undefined && typeof options.sample !== \"function\") throw new TypeError(\"fromVegaView: sample must be a function.\");\n\n let current = readView();\n const { mark: _mark, sample: _sample, ...rest } = options;\n const attachment = expressive<D>(\n current.elements,\n {\n ...rest,\n datum: (element) => itemOf(element).datum as D,\n geometry: (_element, _datum, key) => {\n const geometry = current.geometry.get(key);\n if (!geometry) throw new TypeError(`fromVegaView: no geometry for \"${key}\". Its key must be the same for every item of a mark.`);\n return geometry;\n },\n ...(options.samples || !options.sample ? {} : { samples: (_datum: D, mark: MarkGeometry) => current.samples.get(mark) ?? [] }),\n ...(options.value || !options.sample ? {} : { value: (_datum: D, element: Element) => current.values.get(element) })\n },\n env\n );\n\n // Vega's data and resize listeners run before it renders, so the elements they'd read are the old\n // ones. What Vega draws is watched instead, and read again on the next frame.\n const clock = env.clock ?? defaultClock;\n let observed: SVGSVGElement | undefined;\n let stopFrame: (() => void) | undefined;\n let destroyed = false;\n const observer = typeof MutationObserver === \"function\" ? new MutationObserver((records) => records.some(drawn) && schedule()) : undefined;\n observe(current.root);\n\n function itemOf(element: Element): VegaItem {\n const item = current.items.get(element);\n if (!item) throw new TypeError(\"fromVegaView: an element that isn't one of the View's items.\");\n return item;\n }\n\n function readView(): ViewRead {\n const marks = findMarks(sceneRoot(view), name);\n const type = markType(marks, name, view);\n const host = view.container();\n const root = (host?.localName === \"svg\" ? host : host?.querySelector(\"svg\")) as SVGSVGElement | null | undefined;\n const empty: ViewRead = { root: root ?? undefined, elements: [], items: new Map(), geometry: new Map(), samples: new Map(), values: new Map() };\n if (!type || !root) return empty;\n\n // The element Vega drew for each item: a line's one path is bound to its first item.\n const wanted = new Set<unknown>(type === \"line\" ? marks.flatMap((mark) => (mark.items?.length ? [mark.items[0]] : [])) : marks.flatMap((mark) => mark.items ?? []));\n const items = new Map<Element, VegaItem>();\n for (const element of Array.from(root.querySelectorAll(\"*\"))) {\n const bound = (element as Element & { __data__?: unknown }).__data__;\n if (wanted.has(bound)) items.set(element, bound as VegaItem);\n }\n const elements = [...items.keys()];\n if (elements.length === 0) return empty;\n\n const svg = rootOf(elements);\n const common = commonAncestor(elements, svg);\n const screen = screenMatrices();\n const toCommon = (element: Element): Matrix => between(common, element.parentElement ?? svg, svg, screen);\n const keyOf = (element: Element): string => String(options.key(items.get(element)!.datum as D, element));\n const seriesOf = (element: Element): string | undefined => (options.segment ? String(options.segment(items.get(element)!.datum as D, element)) : undefined);\n\n const read: Reading = { root: svg, items, elements, geometry: new Map(), samples: new Map(), values: new Map() };\n if (options.sample) {\n for (const [element, item] of items) {\n const points = type === \"line\" ? pointsOf(item).map((p) => p.item) : [item];\n read.values.set(element, points.map((point) => valueOf(point).value).join(\",\"));\n }\n }\n if (type === \"rect\") return readBars(read, toCommon, keyOf, seriesOf);\n for (const element of elements) {\n const item = items.get(element)!;\n const key = keyOf(element);\n if (read.geometry.has(key)) continue; // a second part of a mark: expressive() says whether that's allowed\n const m = toCommon(element);\n const geometry = type === \"line\" ? lineOf(key, element, item, m) : type === \"arc\" ? sliceOf(key, item, m) : pointOf(key, item, m);\n read.geometry.set(key, geometry);\n if (options.sample) read.samples.set(geometry, type === \"line\" ? lineSamples(geometry, item, m) : oneSample(geometry, item, type));\n }\n return read;\n }\n\n /** Bars from rect items, grouped by key into stacks (named by `segment`), in visual order. */\n function readBars(read: Reading, toCommon: (element: Element) => Matrix, keyOf: (element: Element) => string, seriesOf: (element: Element) => string | undefined): ViewRead {\n const groups = new Map<string, { element: Element; part: RectPart }[]>();\n for (const element of read.elements) {\n const item = read.items.get(element)!;\n const key = keyOf(element);\n const part: RectPart = { box: boxIn(toCommon(element), boxOf(item)), series: seriesOf(element), radius: Math.max(0, item.cornerRadius ?? 0) };\n const group = groups.get(key);\n if (group) group.push({ element, part });\n else groups.set(key, [{ element, part }]);\n }\n const keys = [...groups.keys()];\n const boxes = keys.map((key) => union(groups.get(key)!.map((p) => p.part.box)));\n const edges: Baseline[] = baselines(boxes, options.baseline ?? \"auto\");\n const elements: Element[] = [];\n for (const i of visualOrder(boxes, edges)) {\n const key = keys[i]!;\n const parts = groups.get(key)!;\n const { geometry, order } = describeRects(key, parts.map((p) => p.part), edges[i]!);\n read.geometry.set(key, geometry);\n // From the baseline, so the mark's first part (its row, its focus) is the one at the baseline.\n elements.push(...order.map((j) => parts[j]!.element));\n if (options.sample) {\n const values = order.map((j) => valueOf(read.items.get(parts[j]!.element)!).value);\n const total = values.reduce((sum, v) => sum + v, 0);\n read.samples.set(geometry, [{ t: 0, value: 0 }, { t: 1, value: total }]);\n let reached = 0;\n (geometry.segments ?? []).forEach((segment, n) => {\n const from = reached;\n reached += values[n] ?? 0;\n read.samples.set(segment, [{ t: 0, value: from }, { t: 1, value: reached }]);\n });\n }\n }\n return { ...read, elements };\n }\n\n function valueOf(item: VegaItem): { value: number; at?: string | number | Date } {\n const given = options.sample!(item.datum as D);\n const sample = typeof given === \"number\" ? { value: given } : given;\n if (typeof sample !== \"object\" || sample === null || !Number.isFinite(sample.value)) {\n throw new RangeError(`fromVegaView: sample must give a finite number, or { value, at }, got ${JSON.stringify(given)}.`);\n }\n return sample.at === undefined ? { value: sample.value } : { value: sample.value, at: sample.at };\n }\n\n /** A line's samples, one per point, where each point is along the walk its points drew. */\n function lineSamples(geometry: MarkGeometry, first: VegaItem, m: Matrix): Sample[] {\n return samplesAlong(\n geometry,\n pointsOf(first).map(({ item, point }) => ({ ...matrix.apply(m, point), ...valueOf(item) }))\n );\n }\n\n function oneSample(geometry: MarkGeometry, item: VegaItem, type: MarkType): Sample[] {\n const { value, at } = valueOf(item);\n const end = at === undefined ? { t: 1, value } : { t: 1, value, at };\n return type === \"symbol\" ? [{ ...end, t: 0 }] : geometry.length > 0 ? [{ t: 0, value: 0 }, end] : [{ ...end, t: 0 }];\n }\n\n // ── Following the View ─────────────────────────────────────────────────────\n\n /** A change Vega made to its marks: not one the adapter made in its overlay, nor its own attributes. */\n function drawn(record: MutationRecord): boolean {\n const overlay = observed?.querySelector(\":scope > .ec-overlay\");\n const ours = (node: Node): boolean => node === overlay || (overlay?.contains(node) ?? false);\n if (ours(record.target)) return false;\n if (record.type === \"childList\") return [...Array.from(record.addedNodes), ...Array.from(record.removedNodes)].some((node) => !ours(node));\n return true;\n }\n\n function schedule(): void {\n if (stopFrame || destroyed) return;\n const stop = clock.onFrame(() => {\n stop();\n stopFrame = undefined;\n try {\n refresh();\n } catch (error) {\n report(error);\n }\n });\n stopFrame = stop;\n }\n\n function observe(root: SVGSVGElement | undefined): void {\n if (!observer || root === observed) return;\n observer.disconnect();\n observed = root;\n if (root) observer.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: DRAWN });\n }\n\n function refresh(): void {\n if (destroyed) return;\n const next = readView();\n const previous = current;\n current = next;\n try {\n attachment.refresh(next.elements);\n } catch (error) {\n current = previous;\n throw error;\n }\n observe(next.root);\n }\n\n // Linked through the attachment's hover.\n return linkable(portOf(attachment)!, {\n refresh,\n on: attachment.on,\n marks: attachment.marks,\n focus: attachment.focus,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n observer?.disconnect();\n stopFrame?.();\n stopFrame = undefined;\n attachment.destroy();\n }\n });\n}\n\nfunction checkView(view: VegaViewLike): void {\n if (typeof view !== \"object\" || view === null || typeof view.renderer !== \"function\" || typeof view.scenegraph !== \"function\" || typeof view.container !== \"function\") {\n throw new TypeError(\"fromVegaView needs a Vega View: new vega.View(runtime, { renderer: \\\"svg\\\", container }), or vega-embed's result.view.\");\n }\n const renderer = view.renderer();\n if (renderer !== \"svg\") {\n throw new TypeError(\n `fromVegaView: the View renders with \"${renderer}\", which draws no SVG elements to attach to. Use renderer: \"svg\" (vega-embed's default; a bare vega.View uses canvas).`\n );\n }\n}\n\nfunction sceneRoot(view: VegaViewLike): VegaMark {\n const graph = view.scenegraph() as { readonly root?: VegaMark } & VegaMark;\n return graph.root ?? graph;\n}\n\n/** Every mark of that name in the scenegraph: Vega-Lite draws one per series for a line with a colour field. */\nfunction findMarks(root: VegaMark, name: string): VegaMark[] {\n const found: VegaMark[] = [];\n const visit = (mark: VegaMark): void => {\n if (mark.name === name && mark.marktype !== \"group\") found.push(mark);\n if (mark.marktype !== \"group\") return;\n for (const item of mark.items ?? []) for (const inner of item.items ?? []) visit(inner);\n };\n visit(root);\n return found;\n}\n\nfunction markType(marks: readonly VegaMark[], name: string, view: VegaViewLike): MarkType | undefined {\n if (marks.length === 0) {\n const names = namesIn(sceneRoot(view));\n // Before the View first runs there are no marks yet; it's read again once Vega draws them.\n if (names.length === 0) return undefined;\n throw new RangeError(`fromVegaView: the View has no mark named \"${name}\". Its named marks: ${names.map((n) => `\"${n}\"`).join(\", \")}.`);\n }\n const type = marks[0]!.marktype;\n if (!marks.every((mark) => mark.marktype === type) || !MARK_TYPES.includes(type as MarkType)) {\n throw new TypeError(`fromVegaView: \"${name}\" is a ${String(type)} mark. Rects, arcs, symbols and lines can be read; describe others with expressive()'s geometry option.`);\n }\n return type as MarkType;\n}\n\nfunction namesIn(root: VegaMark): string[] {\n const names = new Set<string>();\n const visit = (mark: VegaMark): void => {\n if (mark.name && mark.marktype !== \"group\") names.add(mark.name);\n for (const item of mark.items ?? []) for (const inner of item.items ?? []) visit(inner);\n };\n visit(root);\n return [...names];\n}\n\n/**\n * A line's points, from its mark's items. Lines are straight between their points (M4 decision 5),\n * so a curve Vega interpolates (monotone, basis, step and the rest; it reads the first item's) would\n * be described as a different path from the one drawn, and throws instead. So does a point Vega\n * leaves out (`defined: false`), which would be a gap, which lines can't have yet.\n */\nfunction pointsOf(first: VegaItem): { item: VegaItem; point: Point }[] {\n const items = first.mark?.items ?? [first];\n const interpolate = items[0]?.interpolate;\n if (interpolate !== undefined && interpolate !== \"linear\") {\n throw new TypeError(\n `fromVegaView: a line is drawn with interpolate \"${interpolate}\", but only straight lines can be read. Use interpolate \"linear\" (the default), or describe the curve with expressive()'s geometry option.`\n );\n }\n if (items.some((item) => item.defined === false)) {\n throw new TypeError(\"fromVegaView: a line has a gap (a point with defined: false). Lines with gaps can't be read yet.\");\n }\n return items.map((item) => ({ item, point: { x: number(item.x), y: number(item.y) } }));\n}\n\nfunction lineOf(key: string, element: Element, first: VegaItem, m: Matrix): MarkGeometry {\n const width = first.strokeWidth ?? Number.parseFloat(element.getAttribute(\"stroke-width\") ?? \"1\");\n return describe.line({\n key,\n series: key,\n points: pointsOf(first).map(({ point }) => matrix.apply(m, point)),\n width: (Number.isFinite(width) ? width : 1) * scaleOf(m)\n });\n}\n\n/** A slice: Vega-Lite's arcs can run anticlockwise (start > end), so the angles are put in order. */\nfunction sliceOf(key: string, item: VegaItem, m: Matrix): MarkGeometry {\n const center = matrix.apply(m, { x: number(item.x), y: number(item.y) });\n const s = scaleOf(m);\n const [start, end] = [number(item.startAngle), number(item.endAngle)].sort((a, b) => a - b) as [number, number];\n return describe.arc({ key, cx: center.x, cy: center.y, inner: number(item.innerRadius) * s, outer: number(item.outerRadius) * s, start, end });\n}\n\n/** A point: Vega's symbol `size` is its area in px², 64 by default. */\nfunction pointOf(key: string, item: VegaItem, m: Matrix): MarkGeometry {\n const center = matrix.apply(m, { x: number(item.x), y: number(item.y) });\n return describe.point({ key, x: center.x, y: center.y, r: Math.sqrt(Math.max(0, item.size ?? 64) / Math.PI) * scaleOf(m) });\n}\n\n/** A rect item's box in its group's coordinates, with a negative width or height turned round. */\nfunction boxOf(item: VegaItem): Rect {\n const x = number(item.x);\n const y = number(item.y);\n const width = number(item.width);\n const height = number(item.height);\n return { x: Math.min(x, x + width), y: Math.min(y, y + height), width: Math.abs(width), height: Math.abs(height) };\n}\n\nfunction scaleOf(m: Matrix): number {\n return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n}\n\nfunction number(value: number | undefined): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n","// Any SVG path data: read it, move it through a transform, and write it back out. iconFromSvg reads\n// icons' markup with it, and a chart switch moves marks' outlines between coordinate spaces. What's\n// written is built from numbers only, so nothing from the input passes through.\n\nimport type { Matrix } from \"../contracts/drawing\";\nimport type { Point } from \"../contracts/geometry\";\nimport { formatNumber } from \"./path-data\";\n\n/** Absolute commands only: H and V become L, S becomes C, T becomes Q. */\nexport type PathCommand =\n | { readonly op: \"M\" | \"L\" | \"Z\"; readonly to: Point }\n | { readonly op: \"C\"; readonly c1: Point; readonly c2: Point; readonly to: Point }\n | { readonly op: \"Q\"; readonly c: Point; readonly to: Point }\n | {\n readonly op: \"A\";\n readonly rx: number;\n readonly ry: number;\n /** Degrees, as in path data. */\n readonly rotation: number;\n readonly large: boolean;\n readonly sweep: boolean;\n readonly to: Point;\n };\n\nconst ARITY: Readonly<Record<string, number>> = { M: 2, L: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, T: 2, A: 7 };\n/** Separators, then a command letter or a number. Reading stops at anything else. */\nconst TOKEN = /[\\s,]*([A-Za-z]|[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)/y;\nconst LETTER = /^[A-Za-z]$/;\n\n/** Reads path data as SVG does: up to the first error, which ends the path. */\nexport function parsePath(d: string): PathCommand[] {\n const tokens: string[] = [];\n TOKEN.lastIndex = 0;\n for (let match = TOKEN.exec(d); match; match = TOKEN.exec(d)) tokens.push(match[1]!);\n const out: PathCommand[] = [];\n let pen: Point = { x: 0, y: 0 };\n let start = pen;\n /** The last command's second control point, which S and T reflect. */\n let control: Point | undefined;\n let command = \"\";\n let i = 0;\n\n while (i < tokens.length) {\n if (LETTER.test(tokens[i]!)) command = tokens[i++]!;\n else if (command === \"\" || command === \"Z\" || command === \"z\") break; // numbers with no command\n const upper = command.toUpperCase();\n if (upper === \"Z\") {\n out.push({ op: \"Z\", to: start });\n pen = start;\n control = undefined;\n continue;\n }\n const arity = ARITY[upper];\n if (arity === undefined) break;\n const args: number[] = [];\n let flagError = false;\n while (args.length < arity && i < tokens.length && !LETTER.test(tokens[i]!)) {\n const token = tokens[i]!;\n // An arc's flags are one character each, and can run into each other and into the next\n // number: \"a1 1 0 0110 10\", \"A5 5 0 01.5 .5\". Anything but 0 or 1 there is an error.\n if (upper === \"A\" && (args.length === 3 || args.length === 4)) {\n const flag = token[0];\n if (flag !== \"0\" && flag !== \"1\") {\n flagError = true;\n break;\n }\n args.push(Number(flag));\n if (token.length > 1) tokens[i] = token.slice(1);\n else i++;\n continue;\n }\n args.push(Number(token));\n i++;\n }\n if (flagError || args.length < arity || !args.every(Number.isFinite)) break;\n\n const relative = command !== upper;\n const at = (x: number, y: number): Point => (relative ? { x: pen.x + x, y: pen.y + y } : { x, y });\n const [a = 0, b = 0, c = 0, e = 0, f = 0, g = 0, h = 0] = args;\n let next: Point | undefined;\n switch (upper) {\n case \"M\":\n pen = start = at(a, b);\n out.push({ op: \"M\", to: pen });\n // Further pairs after a move are lines.\n command = relative ? \"l\" : \"L\";\n break;\n case \"L\":\n out.push({ op: \"L\", to: (pen = at(a, b)) });\n break;\n case \"H\":\n out.push({ op: \"L\", to: (pen = { x: relative ? pen.x + a : a, y: pen.y }) });\n break;\n case \"V\":\n out.push({ op: \"L\", to: (pen = { x: pen.x, y: relative ? pen.y + a : a }) });\n break;\n case \"C\":\n case \"S\": {\n const smooth = upper === \"S\";\n const c1 = smooth ? (control && lastIs(out, \"C\") ? reflect(control, pen) : pen) : at(a, b);\n next = smooth ? at(a, b) : at(c, e);\n out.push({ op: \"C\", c1, c2: next, to: (pen = smooth ? at(c, e) : at(f, g)) });\n break;\n }\n case \"Q\":\n case \"T\": {\n const smooth = upper === \"T\";\n next = smooth ? (control && lastIs(out, \"Q\") ? reflect(control, pen) : pen) : at(a, b);\n out.push({ op: \"Q\", c: next, to: (pen = smooth ? at(a, b) : at(c, e)) });\n break;\n }\n case \"A\":\n out.push({ op: \"A\", rx: Math.abs(a), ry: Math.abs(b), rotation: c, large: e !== 0, sweep: f !== 0, to: (pen = at(g, h)) });\n break;\n }\n control = next;\n }\n return out;\n}\n\nconst lastIs = (commands: readonly PathCommand[], op: PathCommand[\"op\"]): boolean => commands[commands.length - 1]?.op === op;\nconst reflect = (control: Point, about: Point): Point => ({ x: 2 * about.x - control.x, y: 2 * about.y - control.y });\n\n/** Moves path commands through an affine transform. Arcs stay arcs: their ellipse is transformed too. */\nexport function transformPath(commands: readonly PathCommand[], m: Matrix): PathCommand[] {\n const p = (point: Point): Point => ({ x: m[0] * point.x + m[2] * point.y + m[4], y: m[1] * point.x + m[3] * point.y + m[5] });\n const mirrored = m[0] * m[3] - m[1] * m[2] < 0;\n return commands.map((command): PathCommand => {\n switch (command.op) {\n case \"M\":\n case \"L\":\n case \"Z\":\n return { op: command.op, to: p(command.to) };\n case \"C\":\n return { op: \"C\", c1: p(command.c1), c2: p(command.c2), to: p(command.to) };\n case \"Q\":\n return { op: \"Q\", c: p(command.c), to: p(command.to) };\n case \"A\":\n return { ...command, ...transformEllipse(command, m), sweep: mirrored !== command.sweep, to: p(command.to) };\n }\n });\n}\n\n/**\n * The arc's ellipse after the linear part of `m`. With E = M · R(rotation) · diag(rx, ry), the new\n * radii are E's singular values (the square roots of the eigenvalues of E·Eᵀ) and the new rotation\n * is the direction of the larger one's eigenvector.\n */\nfunction transformEllipse({ rx, ry, rotation }: { rx: number; ry: number; rotation: number }, m: Matrix): { rx: number; ry: number; rotation: number } {\n const r = (rotation * Math.PI) / 180;\n const cos = Math.cos(r);\n const sin = Math.sin(r);\n const e11 = (m[0] * cos + m[2] * sin) * rx;\n const e12 = (m[2] * cos - m[0] * sin) * ry;\n const e21 = (m[1] * cos + m[3] * sin) * rx;\n const e22 = (m[3] * cos - m[1] * sin) * ry;\n // E·Eᵀ = [[a, b], [b, c]].\n const a = e11 * e11 + e12 * e12;\n const b = e11 * e21 + e12 * e22;\n const c = e21 * e21 + e22 * e22;\n const mean = (a + c) / 2;\n const spread = Math.hypot((a - c) / 2, b);\n const major = mean + spread;\n const angle = Math.abs(b) < 1e-12 ? (a >= c ? 0 : Math.PI / 2) : Math.atan2(major - a, b);\n return { rx: Math.sqrt(major), ry: Math.sqrt(Math.max(0, mean - spread)), rotation: (angle * 180) / Math.PI };\n}\n\n/** Absolute path data with numbers rounded to 0.001 px. */\nexport function formatPath(commands: readonly PathCommand[]): string {\n const n = formatNumber;\n const pt = (point: Point): string => `${n(point.x)},${n(point.y)}`;\n return commands\n .map((command) => {\n switch (command.op) {\n case \"M\":\n case \"L\":\n return `${command.op}${pt(command.to)}`;\n case \"C\":\n return `C${pt(command.c1)} ${pt(command.c2)} ${pt(command.to)}`;\n case \"Q\":\n return `Q${pt(command.c)} ${pt(command.to)}`;\n case \"A\":\n return `A${n(command.rx)},${n(command.ry)} ${n(command.rotation)} ${command.large ? 1 : 0} ${command.sweep ? 1 : 0} ${pt(command.to)}`;\n case \"Z\":\n return \"Z\";\n }\n })\n .join(\"\");\n}\n","// A chart switch: views of the same data in one place, one shown at a time, and a transition effect\n// that turns each mark of one view into its own mark in the next, as the lab's donut turns into\n// columns. It reads only what a chart's handle reports (marks and labels by key, focus by key, and\n// its <svg>), so it never names a chart type, and it plays whatever transition effect it's given:\n// the composition root (src/index.ts) fills in morph() when the page leaves it out.\n//\n// A switch runs along one line, s, from 0 (the view it began in, `a`) to 1 (the view it went to,\n// `b`). The pairs morph at s; the labels move and swap their text, the unmatched marks fade, and the\n// views' other parts fade, each as a function of s, as the lab draws its centre and baseline from\n// its one `t`. So a switch back mid-way plays the same picture backwards from where it is.\n\nimport { defaultClock, easeInOutCubic, linear, matrix, tween, type Clock, type MarkGeometry, type Matrix, type MotionEnv, type Point, type TransitionEffect, type Tween } from \"../core\";\nimport { unease } from \"../core/easing\";\nimport { formatPath, parsePath, transformPath } from \"../core/geometry/path\";\nimport { isTransitionEffect, playTransition, type Transition, type TransitionPair, type TransitionSurface } from \"../core/transition\";\nimport { between, boxIn } from \"./adapter/space\";\nimport { chartAnnouncer, type Announcer } from \"./announce\";\nimport { toColorAssignment, type ColorAssignment } from \"./colors\";\nimport { svgLayer } from \"./render/layer\";\nimport { setAttributes, setStyles, svgElement } from \"./render/svg\";\nimport { injectStyles, markColorStyles, seriesColors } from \"./render/theme\";\nimport { resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport type { ChartLabel } from \"./types\";\n\n/**\n * What a chart switch uses of each view's chart. A reference chart's handle has all of it: its\n * `<svg>` (which takes `ec-morphing` while its marks morph in the switch's overlay), its marks and\n * labels as drawn, focus by key, leave() to end its hover, and destroy().\n */\nexport interface ChartSwitchView {\n readonly element: SVGSVGElement;\n marks(): readonly MarkGeometry[];\n labels(): readonly ChartLabel[];\n focus(key: string): void;\n leave(): void;\n destroy(): void;\n}\n\n/**\n * Draws one view's chart in `container` and returns it. `colors` is the switch's assignment: pass it\n * to the chart as its `colors`, so a key has the same colour in every view and in the overlay.\n */\nexport type ChartSwitchViewFactory = (container: HTMLElement, colors: ColorAssignment) => ChartSwitchView;\n\n/** The views by name, each a function that draws its chart. */\nexport type ChartSwitchViews = Readonly<Record<string, ChartSwitchViewFactory>>;\n\n/** A view's name. */\nexport type ChartSwitchViewName<T extends ChartSwitchViews> = keyof T & string;\n\nexport interface ChartSwitchOptions<T extends ChartSwitchViews> {\n /** The views by name. Each is drawn once, when the switch is created, in a container of its own; they share one grid cell. */\n readonly views: T;\n /** The view shown first. */\n readonly initial: NoInfer<ChartSwitchViewName<T>>;\n /**\n * Plays each pair of marks, matched by key. Default: morph(). The switch draws the labels and the\n * fades, and starts a reverse, on morph's schedule: 950 ms base with transition timing, eased in\n * and out (easeInOutCubic), and from `start` the rest of a full run's time. A transition effect\n * can't report how far its shapes have got, so one with other timing still plays, but its shapes\n * drift from the labels and a switch back can jump.\n */\n readonly transition?: TransitionEffect;\n /** Palette slots by key, shared by every view (each view's function is given it). Default: a new assignment. */\n readonly colors?: ColorAssignment | Readonly<Record<string, number>>;\n /** A polite live region that says the new view's label (its chart's `label`) after each switch. Default false. */\n readonly announce?: boolean;\n}\n\nexport interface ChartSwitch<T extends ChartSwitchViews> {\n /** The view shown, or the one a switch is heading for. */\n readonly current: ChartSwitchViewName<T>;\n /**\n * Switches to `view`: each mark morphs into the mark with its key, by the motion mode. Resolves\n * when the switch has landed, or as soon as another show() replaces it. A show() back to the view\n * a switch is leaving reverses it from where the shapes are; one to a third view lands the switch\n * first. With motion off, the switch has landed when show() returns. Rejects for an unknown view.\n */\n show(view: ChartSwitchViewName<T>): Promise<void>;\n /** The chart a view's function returned: for update(), on() and the rest. */\n chart<K extends ChartSwitchViewName<T>>(view: K): ReturnType<T[K]>;\n /** Ends any switch, destroys every view's chart and removes everything the switch added. */\n destroy(): void;\n}\n\n/** The lab's morph: 950 ms base, with transition timing, in one stage. */\nconst DURATION = 950;\n/** The old view's other parts are gone by here. */\nconst OUT_BY = 0.4;\n/** The new view's other parts start to show here; labels swap their text, and unmatched marks hand over. */\nconst HALF = 0.5;\n\ninterface View {\n readonly name: string;\n readonly container: HTMLDivElement;\n readonly chart: ChartSwitchView;\n}\n\n/** Where focus was when a switch began, if it was in the view it left: on a mark (its key) or elsewhere. */\ninterface FocusMemory {\n readonly key: string | undefined;\n}\n\n/** What a switch draws in its overlay besides the pairs, at each s. */\ninterface Scene {\n draw(s: number): void;\n clear(): void;\n}\n\ninterface Switch {\n /** Where s is 0: the view the switch began in. */\n readonly a: View;\n /** Where s is 1: the view it went to. */\n readonly b: View;\n /** Heading for b. A show() back flips it. */\n forward: boolean;\n /** From a to b, in b's order; `reversed` is the same pairs from b to a, in the same order, so the overlay stacks the same way back. */\n readonly pairs: readonly TransitionPair[];\n readonly reversed: readonly TransitionPair[];\n readonly scene: Scene;\n readonly focus: FocusMemory | undefined;\n /** The run's eased progress from where it began to where it's heading, as last drawn: the shapes' progress, as morph draws them. */\n progress: number;\n transition: Transition | undefined;\n driver: Tween | undefined;\n /** Counts runs, so a run that was replaced or landed doesn't land the switch. */\n run: number;\n /** What the latest show() returned, and its resolve. */\n done: Promise<void>;\n settle: () => void;\n}\n\n/**\n * Views of the same data in `target` (an element or a selector), one shown at a time. Each view's\n * chart is drawn once, in its own container; the containers share one grid cell, so a view keeps\n * its layout while it's hidden. `show(view)` hides both views' marks and plays `transition` on each\n * pair of marks with the same key in an overlay above them, while the labels move to their places\n * in the new view and swap their text half way, marks with no partner fade, and the old view's other\n * parts (axes, centre text, legend, table) fade out as the new one's fade in.\n */\nexport function chartSwitch<T extends ChartSwitchViews>(\n target: string | Element,\n options: ChartSwitchOptions<T> & { readonly transition: TransitionEffect },\n env: Pick<ChartEnv, \"icons\" | \"motion\" | \"clock\">\n): ChartSwitch<T> {\n const host = resolveTarget(target, \"chartSwitch\");\n const names = checkOptions(options);\n const effect = options.transition;\n const colors = toColorAssignment(options.colors);\n const motion = env.motion;\n const clock = env.clock ?? defaultClock;\n const doc = host.ownerDocument;\n injectStyles(doc);\n\n const wrapper = doc.createElement(\"div\");\n wrapper.className = \"ec-switch\";\n host.appendChild(wrapper);\n const views = new Map<string, View>();\n try {\n for (const name of names) {\n const container = doc.createElement(\"div\");\n container.className = \"ec-switch-view\";\n container.setAttribute(\"data-view\", name);\n wrapper.appendChild(container);\n // Hidden before its chart is drawn, so it never shows; it still lays out at the cell's width.\n setActive(container, name === options.initial);\n const chart: unknown = options.views[name]!(container, colors);\n if (!isView(chart, container)) {\n (chart as Partial<ChartSwitchView> | null)?.destroy?.();\n throw new TypeError(`chartSwitch: views.${name} must return the chart it draws in the container it's given (with element, marks(), labels(), focus(), leave() and destroy()), such as donutChart(container, { ... }).`);\n }\n views.set(name, { name, container, chart });\n }\n } catch (error) {\n for (const view of views.values()) view.chart.destroy();\n wrapper.remove();\n throw error;\n }\n\n // Above the views: the pairs, the marks fading, and the labels, in px from the cell's top left.\n // `ec-chart` gives the copied labels the stylesheet's text sizes.\n const overlay = svgElement(\"svg\", { class: \"ec-chart ec-switch-overlay\", \"aria-hidden\": \"true\" }, wrapper);\n const fadesLayer = svgElement(\"g\", { class: \"ec-switch-fades\" }, overlay);\n const runsLayer = svgElement(\"g\", { class: \"ec-switch-runs\" }, overlay);\n const labelsLayer = svgElement(\"g\", { class: \"ec-switch-labels\" }, overlay);\n // Made now: screen readers miss text in a region that appears with it.\n const announcer: Announcer | undefined = options.announce ? chartAnnouncer(overlay) : undefined;\n\n /** Each pair's run draws in a group of its own, in its key's colour, stacked by the pair's place. */\n const orders = new WeakMap<Element, number>();\n const surface: TransitionSurface = {\n group(key, order) {\n const group = svgElement(\"g\", { class: \"ec-run\", \"data-key\": key }, runsLayer);\n setStyles(group, markColorStyles(seriesColors(colors.slot(key))));\n orders.set(group, order);\n const above = Array.from(runsLayer.children).find((child) => (orders.get(child) ?? -Infinity) > order);\n runsLayer.insertBefore(group, above ?? null);\n return { ...svgLayer(group), clear: () => group.remove() };\n }\n };\n\n let current: string = options.initial;\n let active: Switch | undefined;\n let destroyed = false;\n\n // Turning motion off mid-switch lands it, as every animation jumps to its end.\n const stopMotion = motion.subscribe(() => {\n if (motion.mode === \"off\" && active) land(active, true);\n });\n\n // A resize lands a switch: the charts lay out again, and the shapes it began with are stale. The\n // first observation, which comes after observe(), is the width to compare with.\n let width: number | undefined;\n const observer =\n typeof ResizeObserver === \"function\"\n ? new ResizeObserver((entries) => {\n const next = entries[entries.length - 1]?.contentRect.width ?? 0;\n if (width !== undefined && Math.abs(next - width) < 0.5) return;\n const first = width === undefined;\n width = next;\n if (!first && active) land(active, true);\n })\n : undefined;\n observer?.observe(wrapper);\n\n const view = (name: string): View => views.get(name)!;\n\n /** The element with focus in the switch's document or shadow root. */\n function focused(): Element | null {\n return (wrapper.getRootNode() as Document | ShadowRoot).activeElement ?? null;\n }\n\n /** Read before anything is hidden: a browser may move focus off an element that turns hidden. */\n function readFocus(from: View): FocusMemory | undefined {\n const element = focused();\n if (!element || !from.container.contains(element)) return undefined;\n const keyed = element.closest(\"[data-key]\");\n return { key: keyed && from.chart.element.contains(keyed) ? (keyed.getAttribute(\"data-key\") ?? undefined) : undefined };\n }\n\n /** Focus that was in the old view goes to the same key in the new one, or to its first mark, unless it has moved on outside the switch. */\n function restoreFocus(to: View, memory: FocusMemory | undefined): void {\n if (!memory) return;\n const now = focused();\n if (now && now !== doc.body && now !== doc.documentElement && !wrapper.contains(now)) return;\n const inside = (): boolean => to.chart.element.contains(focused());\n if (memory.key !== undefined) to.chart.focus(memory.key);\n if (inside()) return;\n for (const mark of to.chart.marks()) {\n to.chart.focus(mark.key);\n if (inside()) return;\n }\n }\n\n function say(to: View): void {\n announcer?.say(to.chart.element.getAttribute(\"aria-label\") ?? \"\");\n }\n\n function start(from: View, to: View, carried?: { readonly focus: FocusMemory | undefined }): Promise<void> {\n current = to.name;\n const memory = carried ? carried.focus : readFocus(from);\n // The old view's hover ends as the viewer's would. Focus stays where it is, already read, until\n // the view turns inert, which takes it off in a browser.\n from.chart.leave();\n if (motion.mode === \"off\") {\n for (const each of views.values()) setActive(each.container, each === to);\n restoreFocus(to, memory);\n say(to);\n return Promise.resolve();\n }\n // Both views' marks and labels hide, and neither can be reached until the switch lands; the\n // new view shows, its other parts faded out.\n for (const each of [from, to]) {\n each.container.classList.remove(\"ec-switch-inactive\");\n each.container.classList.add(\"ec-switching\");\n each.container.setAttribute(\"inert\", \"\");\n each.chart.element.classList.add(\"ec-morphing\");\n }\n const { pairs, scene } = prepare(from, to);\n const { done, settle } = deferred();\n const session: Switch = {\n a: from,\n b: to,\n forward: true,\n pairs,\n reversed: pairs.map(({ from: a, to: b }) => ({ from: b, to: a })),\n scene,\n focus: memory,\n progress: 0,\n transition: undefined,\n driver: undefined,\n run: 0,\n done,\n settle\n };\n active = session;\n play(session, 0);\n return session.done;\n }\n\n /** Plays the pairs toward where the switch is heading, from `begin` in the shapes' progress, and the scene with them. */\n function play(session: Switch, begin: number): void {\n const run = ++session.run;\n if (begin >= 1) {\n land(session, true);\n return;\n }\n const at = (progress: number): void => {\n session.progress = progress;\n session.scene.draw(session.forward ? progress : 1 - progress);\n };\n // The pairs' runs and the switch's own tween start at one time, on the same clock and with\n // morph's timing, so `progress` is the progress morph draws the shapes at, frame by frame, and a\n // reverse begins exactly where they are. An effect can't say how far it has got, so this schedule\n // is the switch's: an effect that keeps to it stays in step.\n const started = startClock(clock);\n session.transition = playTransition(session.forward ? session.pairs : session.reversed, { effect, surface, start: begin, motion, clock: started.clock, icons: env.icons });\n session.driver = drive(begin, at, { clock: started.clock, motion });\n started.release();\n void Promise.all([session.driver.finished, session.transition.finished]).then(([result]) => {\n if (active === session && session.run === run && result === \"done\") land(session, true);\n });\n }\n\n /** A show() back mid-way: the pairs play back from where the shapes are, and so does everything drawn with them. */\n function reverse(session: Switch): Promise<void> {\n session.driver?.cancel();\n session.transition?.clear();\n session.forward = !session.forward;\n current = (session.forward ? session.b : session.a).name;\n session.settle();\n ({ done: session.done, settle: session.settle } = deferred());\n play(session, 1 - session.progress);\n return session.done;\n }\n\n /**\n * Ends the switch where it's heading: the overlay empties, that view's marks show and it becomes\n * the active view, every other view inactive. `settle`: focus follows its key and the new view is\n * announced; a switch landed for one to a third view hands its focus on instead.\n */\n function land(session: Switch, settle: boolean): void {\n if (active !== session) return;\n active = undefined;\n session.run++;\n session.driver?.cancel();\n session.transition?.clear();\n session.scene.clear();\n const to = session.forward ? session.b : session.a;\n for (const each of [session.a, session.b]) {\n each.chart.element.classList.remove(\"ec-morphing\");\n each.container.classList.remove(\"ec-switching\");\n each.container.style.removeProperty(\"opacity\");\n }\n for (const each of views.values()) setActive(each.container, each === to);\n if (settle) {\n restoreFocus(to, session.focus);\n say(to);\n }\n session.settle();\n }\n\n /** Both views' marks and labels in overlay px, the pairs matched by key, and what's drawn with them. */\n function prepare(a: View, b: View): { pairs: TransitionPair[]; scene: Scene } {\n const toA = between(overlay, a.chart.element, wrapper);\n const toB = between(overlay, b.chart.element, wrapper);\n const from = a.chart.marks().map((mark) => mapMark(mark, toA));\n const to = b.chart.marks().map((mark) => mapMark(mark, toB));\n const fromByKey = new Map(from.map((mark) => [mark.key, mark]));\n const toKeys = new Set(to.map((mark) => mark.key));\n const pairs = to.flatMap((mark) => {\n const partner = fromByKey.get(mark.key);\n return partner ? [{ from: partner, to: mark }] : [];\n });\n\n const drawings: ((s: number) => void)[] = [];\n // Marks with no partner fade where they stand: out over the first half, in over the second.\n for (const mark of from) if (!toKeys.has(mark.key)) drawings.push(fadeMark(mark, fadeOut));\n for (const mark of to) if (!fromByKey.has(mark.key)) drawings.push(fadeMark(mark, fadeIn));\n\n // Labels match by key and role. A pair moves from one place to the other and swaps its text half\n // way; a label with no partner fades, as a mark does.\n const id = (label: ChartLabel): string => `${label.role}\\n${label.key}`;\n const labelsA = a.chart.labels();\n const labelsB = b.chart.labels();\n const byId = new Map(labelsA.map((label) => [id(label), label]));\n const matched = new Set<string>();\n for (const label of labelsB) {\n const partner = byId.get(id(label));\n if (!partner) continue;\n matched.add(id(label));\n drawings.push(moveLabel(copyLabel(partner, toA), copyLabel(label, toB)));\n }\n for (const label of labelsA) if (!matched.has(id(label))) drawings.push(fadeLabel(copyLabel(label, toA), fadeOut));\n for (const label of labelsB) if (!byId.has(id(label))) drawings.push(fadeLabel(copyLabel(label, toB), fadeIn));\n\n // The views' other parts: the old one's gone by 40% of the way, the new one's in from half way.\n drawings.push((s) => {\n setOpacity(a.container, 1 - clamp(s / OUT_BY));\n setOpacity(b.container, clamp((s - HALF) / (1 - HALF)));\n });\n\n return {\n pairs,\n scene: {\n draw: (s) => {\n for (const draw of drawings) draw(s);\n },\n clear: () => {\n fadesLayer.replaceChildren();\n runsLayer.replaceChildren();\n labelsLayer.replaceChildren();\n }\n }\n };\n }\n\n /** A mark with no partner, drawn as its outline in its key's colour. */\n function fadeMark(mark: MarkGeometry, opacity: (s: number) => number): (s: number) => void {\n const group = svgElement(\"g\", { class: \"ec-switch-fade\", \"data-key\": mark.key }, fadesLayer);\n setStyles(group, markColorStyles(seriesColors(colors.slot(mark.key))));\n svgLayer(group).path(mark.outline.d, mark.outline.closed ? { fill: \"mark\" } : { stroke: \"mark\", width: mark.thickness });\n return (s) => setAttributes(group, { opacity: opacity(s) });\n }\n\n /** A copy of the label's <text> in the overlay, with its classes, and where it sits there. */\n function copyLabel(label: ChartLabel, m: Matrix): { readonly text: SVGTextElement; readonly at: Point } {\n const text = label.element.cloneNode(true) as SVGTextElement;\n for (const name of [\"id\", \"opacity\", \"visibility\", \"aria-hidden\"]) text.removeAttribute(name);\n text.textContent = label.text;\n const at = matrix.apply(m, label);\n setAttributes(text, { x: at.x, y: at.y, \"text-anchor\": label.anchor });\n labelsLayer.appendChild(text);\n return { text, at };\n }\n\n const api: ChartSwitch<T> = {\n get current() {\n return current as ChartSwitchViewName<T>;\n },\n show(name) {\n if (!views.has(name)) return Promise.reject(new TypeError(`chartSwitch: there's no view ${JSON.stringify(name)}. The views are ${names.map((n) => JSON.stringify(n)).join(\", \")}.`));\n if (destroyed) return Promise.resolve();\n const session = active;\n if (!session) return name === current ? Promise.resolve() : start(view(current), view(name));\n const heading = session.forward ? session.b : session.a;\n const leaving = session.forward ? session.a : session.b;\n if (name === heading.name) return session.done;\n if (name === leaving.name) return reverse(session);\n // A third view: this switch lands first, and its focus goes on with the next.\n land(session, false);\n return start(heading, view(name), { focus: session.focus });\n },\n chart(name) {\n const found = views.get(name);\n if (!found) throw new TypeError(`chartSwitch: there's no view ${JSON.stringify(name)}. The views are ${names.map((n) => JSON.stringify(n)).join(\", \")}.`);\n return found.chart as ReturnType<T[typeof name]>;\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n const session = active;\n if (session) {\n active = undefined;\n session.run++;\n session.driver?.cancel();\n session.transition?.clear();\n session.scene.clear();\n session.settle();\n }\n stopMotion();\n observer?.disconnect();\n announcer?.destroy();\n for (const each of views.values()) each.chart.destroy();\n wrapper.remove();\n }\n };\n return api;\n}\n\n/**\n * A tween with morph's timing, from `begin` in the shapes' eased progress: 950 ms base with\n * transition timing, of which it takes the rest from where easeInOutCubic reaches `begin`, as morph\n * does. `at` gets the eased progress, `begin` itself first.\n */\nfunction drive(begin: number, at: (progress: number) => void, env: MotionEnv): Tween {\n const begun = unease(begin);\n let running: Tween | undefined;\n running = tween(\n {\n duration: DURATION,\n timing: \"transition\",\n ease: linear,\n update: (k) => {\n const u = Math.min(1, begun + k);\n at(k === 0 ? begin : easeInOutCubic(u));\n if (u >= 1 && k < 1) running?.finish();\n }\n },\n env\n );\n return running;\n}\n\n/**\n * The clock, with its time held at one reading until release(): what everything started before then\n * takes as its start. A live clock (performance.now()) moves while the pairs' runs sample their\n * outlines and draw their first frame, so a tween made after them would start a little later\n * (a fraction of a millisecond in Chromium) and lag the shapes. After release() it reads the clock, so a tween an\n * effect starts later starts when it does.\n */\nfunction startClock(clock: Clock): { readonly clock: Clock; release(): void } {\n let held: number | undefined = clock.now();\n return {\n clock: { now: () => held ?? clock.now(), onFrame: (callback) => clock.onFrame(callback) },\n release() {\n held = undefined;\n }\n };\n}\n\n/** The inactive view can't be seen, reached or read, but keeps its layout, so its geometry is ready for a switch. */\nfunction setActive(container: HTMLElement, active: boolean): void {\n container.classList.toggle(\"ec-switch-inactive\", !active);\n container.toggleAttribute(\"inert\", !active);\n if (active) container.removeAttribute(\"aria-hidden\");\n else container.setAttribute(\"aria-hidden\", \"true\");\n}\n\nfunction setOpacity(container: HTMLElement, opacity: number): void {\n container.style.setProperty(\"opacity\", String(Math.round(opacity * 1000) / 1000));\n}\n\n/** A matched label at s: both copies at the same place along the way, the old text before half way and the new from there. */\nfunction moveLabel(a: { readonly text: SVGTextElement; readonly at: Point }, b: { readonly text: SVGTextElement; readonly at: Point }): (s: number) => void {\n return (s) => {\n const x = mix(a.at.x, b.at.x, s);\n const y = mix(a.at.y, b.at.y, s);\n const second = s >= HALF;\n setAttributes(a.text, { x, y, visibility: second ? \"hidden\" : undefined });\n setAttributes(b.text, { x, y, visibility: second ? undefined : \"hidden\" });\n };\n}\n\nfunction fadeLabel(label: { readonly text: SVGTextElement }, opacity: (s: number) => number): (s: number) => void {\n return (s) => setAttributes(label.text, { opacity: opacity(s) });\n}\n\nconst fadeOut = (s: number): number => 1 - clamp(s / HALF);\nconst fadeIn = (s: number): number => clamp((s - HALF) / (1 - HALF));\nconst clamp = (value: number): number => Math.min(1, Math.max(0, value));\n/** Weighted on both sides, as morph mixes, so a switch back puts a label where the switch forward had it. */\nconst mix = (x: number, y: number, s: number): number => x * (1 - s) + y * s;\n\nconst isIdentity = (m: Matrix): boolean => m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;\n\n/**\n * The mark in another coordinate space: a view's <svg> units to the overlay's px. A switch maps by\n * where each <svg> sits and how it's scaled, so the transform keeps angles; its outline's path data\n * is moved through it, arcs and all.\n */\nfunction mapMark(mark: MarkGeometry, m: Matrix): MarkGeometry {\n if (isIdentity(m)) return mark;\n const point = (p: Point): Point => matrix.apply(m, p);\n const path = (d: string): string => formatPath(transformPath(parsePath(d), m));\n const scale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n const { outline } = mark;\n return {\n key: mark.key,\n ...(mark.series === undefined ? {} : { series: mark.series }),\n start: point(mark.start),\n end: point(mark.end),\n length: mark.length * scale,\n path: (t) => point(mark.path(t)),\n angle: (t) => {\n const angle = mark.angle(t);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n return Math.atan2(m[1] * cos + m[3] * sin, m[0] * cos + m[2] * sin);\n },\n slice: (t0, t1) => path(mark.slice(t0, t1)),\n thickness: mark.thickness * scale,\n outline: { d: path(outline.d), closed: outline.closed, sample: (n) => outline.sample(n).map(point) },\n bounds: boxIn(m, mark.bounds),\n center: point(mark.center),\n pivot: point(mark.pivot),\n ...(mark.segments === undefined ? {} : { segments: mark.segments.map((segment) => mapMark(segment, m)) })\n };\n}\n\nfunction deferred(): { done: Promise<void>; settle: () => void } {\n let settle!: () => void;\n const done = new Promise<void>((resolve) => {\n settle = resolve;\n });\n return { done, settle };\n}\n\nfunction isView(value: unknown, container: Element): value is ChartSwitchView {\n if (typeof value !== \"object\" || value === null) return false;\n const view = value as Partial<Record<keyof ChartSwitchView, unknown>>;\n const element = view.element as Node | undefined;\n return (\n ([\"marks\", \"labels\", \"focus\", \"leave\", \"destroy\"] as const).every((method) => typeof view[method] === \"function\") &&\n element?.nodeType === 1 &&\n container.contains(element)\n );\n}\n\n/** Throws on options that aren't a switch's; returns the views' names. */\nfunction checkOptions(options: ChartSwitchOptions<ChartSwitchViews>): string[] {\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"chartSwitch needs options.\");\n const { views, initial, transition, announce } = options;\n if (typeof views !== \"object\" || views === null) throw new TypeError(\"chartSwitch needs views: by name, a function that draws each view's chart in the container it's given.\");\n const names = Object.keys(views);\n if (names.length === 0) throw new TypeError(\"chartSwitch needs at least one view.\");\n for (const name of names) {\n if (typeof views[name] !== \"function\") throw new TypeError(`chartSwitch: views.${name} must be a function that draws the view's chart in the container it's given.`);\n }\n if (typeof initial !== \"string\" || !names.includes(initial)) {\n throw new TypeError(`chartSwitch: initial must be one of the views (${names.map((n) => JSON.stringify(n)).join(\", \")}), got ${typeof initial === \"string\" ? JSON.stringify(initial) : String(initial)}.`);\n }\n if (!isTransitionEffect(transition)) throw new TypeError(\"chartSwitch: transition must be a transition effect, such as morph().\");\n if (announce !== undefined && typeof announce !== \"boolean\") throw new TypeError(\"chartSwitch: announce must be true or false.\");\n return names;\n}\n","// motionSwitch: the viewer's own motion control, the prototype's Presentation / Analysis / Off\n// segmented buttons. The viewer operates it, so it calls motion.chooseMode(), the one call that\n// overrides the device's reduced-motion setting. It imports only core (and the shared stylesheet).\n\nimport type { Motion, MotionMode } from \"../../core\";\nimport { injectStyles } from \"../render/theme\";\n\nexport interface MotionSwitchOptions {\n /** The group's visible label, which is also its accessible name. Default \"Motion\". */\n readonly label?: string;\n /** Button text by mode. Default \"Presentation\", \"Analysis\", \"Off\". */\n readonly labels?: Partial<Readonly<Record<MotionMode, string>>>;\n /**\n * The note beside the buttons, by effective mode, and `reduced` for while the device asks for\n * reduced motion and the viewer hasn't picked a mode.\n */\n readonly hints?: Partial<Readonly<Record<MotionMode | \"reduced\", string>>>;\n /**\n * A localStorage key. Opt-in: the viewer's choice is saved under it, and restored when the switch\n * is made, so it carries across pages and visits. Storage that's blocked or full is ignored.\n */\n readonly persist?: string;\n}\n\nexport interface MotionSwitch {\n /** The switch's root, a `role=\"group\"` element appended to the target. */\n readonly element: HTMLElement;\n /** Removes the switch and stops following the motion. The viewer's choice stays. */\n destroy(): void;\n}\n\nconst MODES: readonly MotionMode[] = [\"presentation\", \"analysis\", \"off\"];\n\nconst LABELS: Readonly<Record<MotionMode, string>> = {\n presentation: \"Presentation\",\n analysis: \"Analysis\",\n off: \"Off\"\n};\n\nconst HINTS: Readonly<Record<MotionMode | \"reduced\", string>> = {\n presentation: \"Staged, unhurried motion. Best for walking someone through a change.\",\n analysis: \"Quick, unstaged motion. Best for exploring.\",\n off: \"No motion: charts jump straight to their end state.\",\n reduced: \"Your device asks for reduced motion, so motion is off. Picking a mode here overrides it.\"\n};\n\nlet switches = 0;\n\n/**\n * Builds the motion switch in `target` (an element or a selector): a group of real buttons with\n * `aria-pressed`, one per mode, and a note on what the mode does. The pressed button is the effective\n * mode, so while the device asks for reduced motion and the viewer hasn't picked, Off is pressed and\n * the note says why. It follows `motion.subscribe`, so it stays right whoever changes the mode.\n */\nexport function motionSwitch(target: string | Element, motion: Motion, options: MotionSwitchOptions = {}): MotionSwitch {\n const parent = resolveTarget(target);\n checkMotion(motion);\n checkOptions(options);\n const labels = { ...LABELS, ...options.labels };\n const hints = { ...HINTS, ...options.hints };\n const { persist } = options;\n const doc = parent.ownerDocument;\n injectStyles(doc);\n\n const id = `ec-motion-${++switches}`;\n const root = doc.createElement(\"div\");\n root.className = \"ec-motion-switch\";\n root.setAttribute(\"role\", \"group\");\n root.setAttribute(\"aria-labelledby\", `${id}-label`);\n root.setAttribute(\"aria-describedby\", `${id}-hint`);\n\n const label = root.appendChild(doc.createElement(\"span\"));\n label.className = \"ec-motion-label\";\n label.id = `${id}-label`;\n label.textContent = options.label ?? \"Motion\";\n\n const modes = root.appendChild(doc.createElement(\"span\"));\n modes.className = \"ec-motion-modes\";\n const buttons = MODES.map((mode) => {\n const button = modes.appendChild(doc.createElement(\"button\"));\n button.type = \"button\";\n button.dataset.mode = mode;\n button.textContent = labels[mode];\n button.addEventListener(\"click\", () => motion.chooseMode(mode));\n return button;\n });\n\n // Polite: the note changes when the viewer picks a mode, or when the device setting changes.\n const hint = root.appendChild(doc.createElement(\"span\"));\n hint.className = \"ec-motion-hint\";\n hint.id = `${id}-hint`;\n hint.setAttribute(\"aria-live\", \"polite\");\n\n const render = (): void => {\n const mode = motion.mode;\n for (const button of buttons) button.setAttribute(\"aria-pressed\", String(button.dataset.mode === mode));\n hint.textContent = motion.prefersReduced && motion.viewerChoice === undefined ? hints.reduced : hints[mode];\n };\n\n if (persist !== undefined) {\n const saved = storage(doc, (store) => store.getItem(persist));\n if (MODES.includes(saved as MotionMode)) motion.chooseMode(saved as MotionMode);\n }\n // Drawn before it's in the page, so the live region doesn't announce the first note.\n render();\n parent.appendChild(root);\n\n const unsubscribe = motion.subscribe(() => {\n render();\n if (persist === undefined) return;\n const choice = motion.viewerChoice;\n storage(doc, (store) => (choice === undefined ? store.removeItem(persist) : store.setItem(persist, choice)));\n });\n\n let destroyed = false;\n return {\n element: root,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n unsubscribe();\n root.remove();\n }\n };\n}\n\n/** Runs `use` on the document's localStorage; anything that throws (blocked, full, sandboxed) is ignored. */\nfunction storage<T>(doc: Document, use: (store: Storage) => T): T | undefined {\n try {\n const store = doc.defaultView?.localStorage;\n return store ? use(store) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveTarget(target: string | Element): Element {\n if (typeof target === \"string\") {\n const found = typeof document === \"undefined\" ? null : document.querySelector(target);\n if (!found) throw new TypeError(`motionSwitch: no element matches \"${target}\".`);\n return found;\n }\n if (typeof target !== \"object\" || target === null || typeof (target as Element).appendChild !== \"function\") {\n throw new TypeError(\"motionSwitch needs an element or a selector to build the switch in.\");\n }\n return target;\n}\n\nfunction checkMotion(motion: Motion): void {\n if (typeof motion !== \"object\" || motion === null || typeof motion.chooseMode !== \"function\" || typeof motion.subscribe !== \"function\") {\n throw new TypeError(\"motionSwitch needs a Motion, such as the page-wide `motion` or one from createMotion().\");\n }\n}\n\nfunction checkOptions(options: MotionSwitchOptions): void {\n const { label, labels, hints, persist } = options;\n if (label !== undefined && typeof label !== \"string\") throw new TypeError(`motionSwitch: label must be a string, got ${typeof label}.`);\n for (const [name, texts] of [[\"labels\", labels], [\"hints\", hints]] as const) {\n if (texts === undefined) continue;\n for (const [key, text] of Object.entries(texts)) {\n if (typeof text !== \"string\") throw new TypeError(`motionSwitch: ${name}.${key} must be a string, got ${typeof text}.`);\n }\n }\n if (persist !== undefined && (typeof persist !== \"string\" || persist === \"\")) {\n throw new TypeError(`motionSwitch: persist must be a localStorage key, got ${JSON.stringify(persist) ?? String(persist)}.`);\n }\n}\n","// playButton: Play and Pause for a playback() (WCAG 2.2.2: anything that plays for more than 5 s can be\n// paused). One real button whose text, and so its name, says what a click does. It has no aria-pressed:\n// a toggle button keeps one name, and this one's name changes. It imports only core (and the shared\n// stylesheet).\n\nimport type { Playback } from \"../../core\";\nimport { injectStyles } from \"../render/theme\";\n\nexport interface PlayButtonOptions {\n /** The button's text, which is its accessible name, by what a click does. Default \"Play\" and \"Pause\". */\n readonly labels?: Partial<Readonly<Record<\"play\" | \"pause\", string>>>;\n}\n\nexport interface PlayButton {\n /** The `<button type=\"button\">` appended to the target. */\n readonly element: HTMLButtonElement;\n /** Removes the button and stops following the playback, which carries on as it is. */\n destroy(): void;\n}\n\nconst LABELS: Readonly<Record<\"play\" | \"pause\", string>> = { play: \"Play\", pause: \"Pause\" };\n\n/**\n * Builds a Play/Pause button in `target` (an element or a selector) for `playback`. A click plays or\n * pauses; the text says Pause while it plays and goes back to Play when it pauses, seeks or ends. It\n * follows `playback.subscribe`, so it stays right whoever drives the playback, and it's the same\n * element throughout, so focus stays on it.\n */\nexport function playButton(target: string | Element, playback: Playback, options: PlayButtonOptions = {}): PlayButton {\n const parent = resolveTarget(target);\n checkPlayback(playback);\n checkOptions(options);\n const labels = { ...LABELS, ...options.labels };\n const doc = parent.ownerDocument;\n injectStyles(doc);\n\n const button = doc.createElement(\"button\");\n button.type = \"button\";\n button.className = \"ec-play\";\n button.addEventListener(\"click\", () => (playback.playing ? playback.pause() : playback.play()));\n\n const render = (): void => {\n const text = playback.playing ? labels.pause : labels.play;\n // Only when it changes, so assistive technology doesn't hear the same name again.\n if (button.textContent !== text) button.textContent = text;\n };\n render();\n parent.appendChild(button);\n const unsubscribe = playback.subscribe(render);\n\n let destroyed = false;\n return {\n element: button,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n unsubscribe();\n button.remove();\n }\n };\n}\n\nfunction resolveTarget(target: string | Element): Element {\n if (typeof target === \"string\") {\n const found = typeof document === \"undefined\" ? null : document.querySelector(target);\n if (!found) throw new TypeError(`playButton: no element matches \"${target}\".`);\n return found;\n }\n if (typeof target !== \"object\" || target === null || typeof (target as Element).appendChild !== \"function\") {\n throw new TypeError(\"playButton needs an element or a selector to build the button in.\");\n }\n return target;\n}\n\nfunction checkPlayback(playback: Playback): void {\n if (\n typeof playback !== \"object\" ||\n playback === null ||\n typeof playback.play !== \"function\" ||\n typeof playback.pause !== \"function\" ||\n typeof playback.subscribe !== \"function\"\n ) {\n throw new TypeError(\"playButton needs a Playback, from playback().\");\n }\n}\n\nfunction checkOptions(options: PlayButtonOptions): void {\n const { labels } = options;\n if (labels === undefined) return;\n for (const [key, text] of Object.entries(labels)) {\n // Only spaces would collapse to a blank button with no accessible name.\n if (typeof text !== \"string\" || text.trim() === \"\") {\n throw new TypeError(`playButton: labels.${key} must be a string with some text, got ${JSON.stringify(text) ?? String(text)}.`);\n }\n }\n}\n","// Gaits: how an icon moves while travel carries it along a walk. A gait is a small function from how\n// far the icon has gone to its pose. Gaits never name icons, and icons only name a gait.\n\nimport { easeInOutCubic, type Easing } from \"../core\";\n\n/** Where the icon is on its trip. Distances are in the icon's own units (px at its natural size), so a gait looks the same at any size. */\nexport interface GaitState {\n /** How far the icon has gone. */\n readonly distance: number;\n /** The whole trip; 0 when the icon doesn't move. */\n readonly length: number;\n /** distance ÷ length, 0 to 1 (1 for a trip of length 0). */\n readonly progress: number;\n /** The icon's rolling radius. */\n readonly radius: number;\n}\n\n/** How the icon is held, relative to its place on the walk. */\nexport interface GaitPose {\n /** Raised this far towards the icon's up side, in icon units. */\n readonly lift: number;\n /** Rolling rotation about the icon's pivot, in radians; positive rolls forward (clockwise when facing +x). */\n readonly spin: number;\n /** Rocking rotation about the icon's pivot, in radians; positive raises the front. */\n readonly tilt: number;\n}\n\nexport interface Gait {\n (state: GaitState): GaitPose;\n /** The trip's easing. Default easeOutCubic. */\n readonly ease?: Easing;\n /** Multiplies the trip's duration. Default 1. */\n readonly pace?: number;\n}\n\nexport interface StepOptions {\n /** Distance per step, in icon units. Default 42. */\n readonly stride?: number;\n /** Height of each step, in icon units. Default 3.2. */\n readonly lift?: number;\n /** Most the front is raised during a step, in degrees. Default 9. */\n readonly tilt?: number;\n}\n\nconst STILL: GaitPose = Object.freeze({ lift: 0, spin: 0, tilt: 0 });\n\n/** Rolls without slipping: the spin is the distance over the radius. */\nfunction roll(): Gait {\n return (state) => ({ lift: 0, spin: state.distance / state.radius, tilt: 0 });\n}\n\n/**\n * Steps along, the prototype's cleat: a whole number of steps (at least one), each lifting and\n * tilting the front up and setting it down again, a little less as the trip goes on. A step takes 15%\n * longer than a roll over the same distance and eases in and out.\n */\nfunction step(options: StepOptions = {}): Gait {\n const stride = options.stride ?? 42;\n const lift = options.lift ?? 3.2;\n const tilt = options.tilt ?? 9;\n if (!(stride > 0) || !Number.isFinite(stride)) throw new RangeError(`gaits.step: stride must be more than 0, got ${stride}.`);\n if (!(lift >= 0) || !Number.isFinite(lift)) throw new RangeError(`gaits.step: lift can't be negative, got ${lift}.`);\n if (!Number.isFinite(tilt)) throw new RangeError(`gaits.step: tilt must be a finite number of degrees, got ${tilt}.`);\n const peak = (tilt * Math.PI) / 180;\n const gait = (state: GaitState): GaitPose => {\n const steps = Math.max(1, Math.round(state.length / stride));\n // Exactly 0 at the start and end of every step, so the boot rests flat when it arrives.\n const phase = Math.abs(Math.sin(Math.PI * ((state.progress * steps) % 1)));\n return { lift: phase * lift, spin: 0, tilt: phase * peak * (1 - 0.3 * state.progress) };\n };\n return Object.assign(gait, { ease: easeInOutCubic, pace: 1.15 });\n}\n\n/** Slides along without turning. */\nfunction slide(): Gait {\n return () => STILL;\n}\n\nexport const gaits = { roll, step, slide };\n\n/** The gaits icons and options name. */\nexport type GaitName = keyof typeof gaits;\n","// travel: carries an icon along a mark's walk (the ball rolling out a bar, the boot stepping along\n// the assists). It reads only the walk, the thickness and the segments, so it runs on any mark.\n\nimport { easeOutCubic, matrix, offset } from \"../core\";\nimport type { EffectContext, GeometryEffect, Icon, IconHandle, MarkGeometry, Matrix, Point } from \"../core\";\nimport { normalizeAngle } from \"../core/geometry\";\nimport { gaits, type Gait, type GaitName } from \"./gaits\";\n\nexport interface TravelOptions {\n /**\n * A segment's series (\"goals\"); the whole walk if omitted. A mark with no segments counts as its\n * own one segment. A missing segment, or one shorter than 0.5 px, makes travel a no-op.\n */\n readonly along?: string;\n /** How the icon moves. Default: the icon's own gait, else \"slide\". */\n readonly gait?: Gait | GaitName;\n /** Length along the walk in px, or \"fit\": scaled so the icon is 85% of the mark's thickness across. Default: the icon's own size. */\n readonly size?: number | \"fit\";\n /** \"follow\" turns with the walk, \"level\" never turns, \"auto\" (default) follows but mirrors an upright icon instead of turning it upside down. */\n readonly orient?: \"auto\" | \"follow\" | \"level\";\n /** \"center\" (default) puts the icon's anchor on the walk; \"on\" sits the icon on top of it (a ball riding a line). */\n readonly ride?: \"center\" | \"on\";\n}\n\n/** Base duration: max(260 ms, distance ÷ 360 px/s) times the gait's pace, at most 4 s, with effect timing. */\nconst SPEED = 360;\nconst SHORTEST = 260;\n/**\n * The longest trip, base ms, after the gait's pace: past 1,440 px at pace 1 the icon goes faster,\n * not longer. With stagger's longest spread (500 ms) in front, it still ends within 5 s (WCAG 2.2.2).\n */\nconst LONGEST = 4000;\n/** A walk shorter than this draws nothing. */\nconst MIN_WALK = 0.5;\n/** \"fit\" makes the icon this much of the mark's thickness. */\nconst FIT = 0.85;\n/** The heading is smoothed over at least this many px either side, so corners don't snap. */\nconst MIN_SMOOTHING = 2;\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];\nconst ORIENTS: readonly string[] = [\"auto\", \"follow\", \"level\"];\nconst RIDES: readonly string[] = [\"center\", \"on\"];\n\n/** One trip of an icon along one walk. */\ninterface Trip {\n readonly icon: Icon;\n /** Drawn length along the walk, px. */\n readonly size: number;\n /** How far the anchor moves, px, across no gap; 0 when every part of the walk is shorter than the icon. */\n readonly span: number;\n /** Base ms, before the motion mode scales it. */\n readonly duration: number;\n readonly gait: Gait;\n /** Where the icon is at eased progress p: the place() transform for its natural size. */\n transform(progress: number): Matrix;\n}\n\n/**\n * Moves an icon along the walk, or along one segment, inset by the icon's footprint so it stays\n * inside the mark. Its end state is the icon resting at the end. An icon given by name is looked up\n * in `ctx.icons` when it runs, and an unknown name throws there.\n *\n * Across a gap in the walk it jumps: it's inset from each part's ends as from the walk's, and goes\n * from one part to the next at once, so it's never drawn over a gap. The trip's time counts only the\n * parts it's drawn on, and a part shorter than the icon is skipped, unless it's the last: the icon\n * rests there, at the last value.\n */\nexport function travel(icon: Icon | string, options: TravelOptions = {}): GeometryEffect {\n checkOptions(icon, options);\n\n /** Plans the trip on the mark's current geometry; undefined when there's nothing to travel along. */\n function plan(mark: MarkGeometry, ctx: EffectContext): Trip | undefined {\n const resolved = typeof icon === \"string\" ? ctx.icons.get(icon) : icon;\n if (!resolved) throw new RangeError(`travel: unknown icon \"${String(icon)}\". Register it with registerIcon(icon), or pass the icon itself.`);\n const walk = pick(mark, options.along);\n if (!walk || !(drawn(walk) >= MIN_WALK)) return undefined;\n const scale =\n options.size === undefined ? 1 : options.size === \"fit\" ? (FIT * walk.thickness) / resolved.box.height : options.size / resolved.size;\n if (!(scale > 0)) return undefined;\n return trip(walk, resolved, scale, options);\n }\n\n /** Draws the trip at a progress, and follows the geometry when it moves (a resize, a transition). */\n function rider(mark: MarkGeometry, ctx: EffectContext): { readonly trip: Trip | undefined; show(progress: number): void } {\n let current = plan(mark, ctx);\n let handle: IconHandle | undefined;\n let drawn: { icon: Icon; size: number } | undefined;\n let progress = 0;\n const draw = (): void => {\n if (!current) {\n handle?.remove();\n handle = drawn = undefined;\n return;\n }\n if (!handle || drawn?.icon !== current.icon || drawn.size !== current.size) {\n handle?.remove();\n handle = ctx.layer.icon(current.icon, { size: current.size });\n drawn = { icon: current.icon, size: current.size };\n }\n handle.place(current.transform(progress));\n };\n ctx.onChange((next) => {\n current = plan(next, ctx);\n draw();\n });\n return {\n get trip() {\n return current;\n },\n show(p) {\n progress = p;\n draw();\n }\n };\n }\n\n return {\n kind: \"geometry\",\n async run(mark, ctx) {\n if (ctx.signal.aborted) return;\n const ride = rider(mark, ctx);\n const planned = ride.trip;\n // Nothing to travel along, or no room to move: draw the end state at once.\n if (!planned || planned.span <= 0) {\n ride.show(1);\n return;\n }\n await ctx.tween({\n duration: planned.duration,\n timing: \"effect\",\n ease: planned.gait.ease ?? easeOutCubic,\n update: (p) => ride.show(p)\n }).finished;\n },\n end(mark, ctx) {\n rider(mark, ctx).show(1);\n },\n clear() {}\n };\n}\n\n/** A part of the walk between gaps, in px along it, with how far the icon's anchor moves along it. */\ninterface Leg {\n readonly from: number;\n readonly to: number;\n readonly span: number;\n /** The span of the legs before it. */\n readonly before: number;\n}\n\nfunction trip(walk: MarkGeometry, icon: Icon, scale: number, options: TravelOptions): Trip {\n const gait = typeof options.gait === \"function\" ? options.gait : gaits[options.gait ?? icon.gait ?? \"slide\"]();\n const length = walk.length;\n const behind = icon.footprint[0] * scale;\n const ahead = icon.footprint[1] * scale;\n // A part shorter than the icon: the icon rests at its start (which may hang past its end) and doesn't move along it.\n let span = 0;\n const legs: Leg[] = parts(walk).map(([from, to]) => {\n const leg = { from, to, span: Math.max(0, to - from - behind - ahead), before: span };\n span += leg.span;\n return leg;\n });\n const smoothing = Math.max(MIN_SMOOTHING, (behind + ahead) / 2);\n const radius = icon.radius ?? icon.box.height / 2;\n const { anchor } = icon;\n // The drawing layer scales the icon about its anchor before place(), so the pivot moves with it.\n const pivot = { x: anchor.x + scale * (icon.pivot.x - anchor.x), y: anchor.y + scale * (icon.pivot.y - anchor.y) };\n // Riding on the walk: half the stroke, plus the anchor's height above the icon's bottom.\n const ride = options.ride === \"on\" ? walk.thickness / 2 + (icon.box.y + icon.box.height - anchor.y) * scale : 0;\n const orient = options.orient ?? \"auto\";\n\n return {\n icon,\n size: icon.size * scale,\n span,\n duration: Math.min(LONGEST, Math.max(SHORTEST, (span / SPEED) * 1000) * (gait.pace ?? 1)),\n gait,\n transform(progress) {\n const travelled = progress * span;\n // The last leg the icon has reached: a leg it can't move along is passed at once, unless it's the last.\n let index = legs.length - 1;\n while (index > 0 && legs[index]!.before > travelled) index--;\n const leg = legs[index]!;\n const distance = leg.from + behind + Math.min(leg.span, travelled - leg.before);\n const pose = gait({ distance: travelled / scale, length: span / scale, progress, radius });\n const at = pointAt(walk, distance);\n const direction = heading(walk, Math.min(distance, length), smoothing, leg);\n // Mirroring keeps an upright icon's top up when the walk heads left.\n const mirror = orient === \"auto\" && icon.upright === true && Math.cos(direction) < -1e-9;\n const turn = orient === \"level\" ? 0 : mirror ? normalizeAngle(direction - Math.PI) : direction;\n return matrix.multiply(\n matrix.translate(at.x, at.y),\n matrix.rotate(turn),\n mirror ? matrix.scale(-1, 1) : IDENTITY,\n matrix.translate(-anchor.x, -anchor.y - pose.lift * scale - ride),\n matrix.rotate(pose.spin - pose.tilt, pivot)\n );\n }\n };\n}\n\n/** The walk to travel along: the named segment, or the mark itself. */\nfunction pick(mark: MarkGeometry, along: string | undefined): MarkGeometry | undefined {\n if (along === undefined) return mark;\n if (mark.segments) return mark.segments.find((segment) => segment.series === along);\n return mark.series === along ? mark : undefined;\n}\n\n/** The walk's parts between its gaps, as [from, to] px along it, in order. A walk with no gaps is one part. */\nfunction parts(walk: MarkGeometry): [number, number][] {\n const { length } = walk;\n const found: [number, number][] = [];\n let at = 0;\n for (const [from, to] of walk.gaps ?? []) {\n // Taken as the contract has them, in order and apart; any that aren't are read as far as they go.\n if (!(to > from) || !(to > at)) continue;\n if (from > at) found.push([at * length, Math.min(1, from) * length]);\n at = Math.min(1, to);\n }\n found.push([at * length, length]);\n return found;\n}\n\n/** How much of the walk is drawn: its length less its gaps. */\nfunction drawn(walk: MarkGeometry): number {\n return parts(walk).reduce((sum, [from, to]) => sum + (to - from), 0);\n}\n\n/** The point `distance` px along the walk; past the end, it carries on in the end's direction. */\nfunction pointAt(walk: MarkGeometry, distance: number): Point {\n const { length } = walk;\n return distance <= length ? walk.path(distance / length) : offset(walk.end, walk.angle(1), distance - length);\n}\n\n/**\n * The direction of travel at `distance`, smoothed over a window either side: the chord between the\n * window's ends. On straight legs and circular arcs the chord is exactly the tangent; across a\n * polyline corner it turns gradually. The window shrinks near the ends of the leg so it stays on it,\n * never across a gap.\n */\nfunction heading(walk: MarkGeometry, distance: number, window: number, leg: Leg): number {\n const { length } = walk;\n const reach = Math.min(window, distance - leg.from, leg.to - distance);\n if (reach > 1e-6) {\n const a = walk.path((distance - reach) / length);\n const b = walk.path((distance + reach) / length);\n if (Math.hypot(b.x - a.x, b.y - a.y) > 1e-9) return Math.atan2(b.y - a.y, b.x - a.x);\n }\n return walk.angle(distance / length);\n}\n\nfunction checkOptions(icon: Icon | string, options: TravelOptions): void {\n const named = typeof icon === \"string\" && icon !== \"\";\n if (!named && (typeof icon !== \"object\" || icon === null || typeof icon.name !== \"string\")) {\n throw new TypeError(`travel needs an icon or an icon's name, got ${icon === null ? \"null\" : typeof icon}.`);\n }\n const { along, gait, size, orient, ride } = options;\n if (along !== undefined && typeof along !== \"string\") throw new RangeError(`travel: along must be a series name, got ${String(along)}.`);\n if (gait !== undefined && typeof gait !== \"function\" && !Object.prototype.hasOwnProperty.call(gaits, gait)) {\n throw new RangeError(`travel: gait must be a gait or one of roll, step, slide, got ${String(gait)}.`);\n }\n if (size !== undefined && size !== \"fit\" && !(typeof size === \"number\" && size > 0 && Number.isFinite(size))) {\n throw new RangeError(`travel: size must be more than 0 px, or \"fit\", got ${String(size)}.`);\n }\n if (orient !== undefined && !ORIENTS.includes(orient)) throw new RangeError(`travel: orient must be auto, follow or level, got ${String(orient)}.`);\n if (ride !== undefined && !RIDES.includes(ride)) throw new RangeError(`travel: ride must be center or on, got ${String(ride)}.`);\n}\n","// flash: one halo blink along the mark's outline, for \"this changed\" (`on: { update: \"flash\" }`). It\n// reads nothing of the geometry: the halo is a mark style, which the renderer strokes along the outline\n// as it is on screen, so it follows the mark through the transition it runs alongside.\n\nimport { linear } from \"../core\";\nimport type { Color, EffectContext, GeometryEffect } from \"../core\";\n\nexport interface FlashOptions {\n /** The halo's widest stroke, px; half of it shows outside the mark. Default 8, as in the prototype. */\n readonly width?: number;\n /** Default 0.35. */\n readonly opacity?: number;\n /** A theme token or any CSS colour. Default: the mark's own colour. */\n readonly color?: Color;\n}\n\n/** Base duration, with effect timing. */\nconst DURATION = 900;\n/** The prototype's keyframes: the stroke is widest a quarter of the way through. */\nconst PEAK = 0.25;\nconst WIDTH = 8;\nconst OPACITY = 0.35;\n\n/**\n * One blink of a halo along the mark's outline: the stroke grows from 0 to `width` and back over a\n * 900 ms base, as the prototype's CSS flash does.\n *\n * Its end state is nothing, on purpose. A flash is emphasis, not information: the change it points\n * at (the bar's new length, its new value label) stays on the chart, so with motion off or reduced\n * the viewer still sees everything the flash would have drawn attention to.\n */\nexport function flash(options: FlashOptions = {}): GeometryEffect {\n checkOptions(options);\n const width = options.width ?? WIDTH;\n const opacity = options.opacity ?? OPACITY;\n const { color } = options;\n\n const show = (ctx: EffectContext, progress: number): void => {\n const stroke = width * blink(progress);\n ctx.mark.set({ halo: stroke > 0 ? { width: stroke, opacity, ...(color === undefined ? {} : { color }) } : undefined });\n };\n\n return {\n kind: \"geometry\",\n async run(_mark, ctx) {\n if (ctx.signal.aborted) return;\n // Linear here: the keyframes ease each half themselves.\n await ctx.tween({ duration: DURATION, timing: \"effect\", ease: linear, update: (p) => show(ctx, p) }).finished;\n },\n end() {},\n clear() {}\n };\n}\n\n/** The halo's width at linear progress t, 0–1: up to 1 by PEAK, back to 0 at the end, each half eased out. */\nfunction blink(t: number): number {\n if (!(t > 0) || t >= 1) return 0;\n return t < PEAK ? easeOut(t / PEAK) : 1 - easeOut((t - PEAK) / (1 - PEAK));\n}\n\n/** CSS's `ease-out`, cubic-bezier(0, 0, 0.58, 1), which the prototype's keyframes use. */\nfunction easeOut(x: number): number {\n if (!(x > 0)) return 0;\n if (x >= 1) return 1;\n // x(s) = 1.74·s²(1 − s) + s³ rises with s, so bisection finds the curve's parameter.\n let lo = 0;\n let hi = 1;\n for (let i = 0; i < 24; i++) {\n const s = (lo + hi) / 2;\n if (1.74 * s * s * (1 - s) + s * s * s < x) lo = s;\n else hi = s;\n }\n const s = (lo + hi) / 2;\n return 3 * s * s - 2 * s * s * s;\n}\n\nfunction checkOptions(options: FlashOptions): void {\n const { width, opacity, color } = options;\n if (width !== undefined && !(typeof width === \"number\" && width > 0 && Number.isFinite(width))) {\n throw new RangeError(`flash: width must be more than 0 px, got ${String(width)}.`);\n }\n if (opacity !== undefined && !(typeof opacity === \"number\" && opacity > 0 && opacity <= 1)) {\n throw new RangeError(`flash: opacity must be more than 0 and at most 1, got ${String(opacity)}.`);\n }\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`flash: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n}\n","// wiggle: a short damped rotation of the mark about its pivot, for hover (`on: { hover: \"wiggle\" }`).\n// It reads only the pivot and the outline, so a bar rocks on its baseline and a donut slice about the\n// donut's centre, and the angle is capped so no part of the mark moves more than a few px.\n\nimport { linear, matrix } from \"../core\";\nimport type { EffectContext, GeometryEffect, MarkGeometry } from \"../core\";\n\nexport interface WiggleOptions {\n /** How far the point of the mark farthest from its pivot may move, px: more than 0, at most 3. Default 3. */\n readonly swing?: number;\n}\n\n/** Base duration, with effect timing. */\nconst DURATION = 450;\n/** Each half-swing's share of the cap, alternating sides: three, each smaller than the last. */\nconst SWINGS = [1, -0.5, 0.25];\nconst SWING = 3;\n/** A mark whose outline is all within this of its pivot doesn't move. */\nconst MIN_REACH = 0.5;\n/** Outline points measured to find the reach. */\nconst SAMPLES = 64;\n/** Never more than 15°, so a tiny mark nods instead of spinning, however little it moves. */\nconst MAX_ANGLE = Math.PI / 12;\n\n/**\n * Rocks the mark about `mark.pivot` in three decaying half-swings over a 450 ms base. The angle is\n * capped so the outline point farthest from the pivot moves at most `swing` px: effects never\n * distort data, and a few px of movement reads as emphasis, not as a change of value.\n *\n * Its end state is no transform: the mark rests where the chart drew it.\n */\nexport function wiggle(options: WiggleOptions = {}): GeometryEffect {\n checkOptions(options);\n const swing = options.swing ?? SWING;\n\n return {\n kind: \"geometry\",\n async run(mark, ctx) {\n if (ctx.signal.aborted) return;\n // Follow the geometry, so a wiggle running alongside a transition rocks about the pivot as it is now.\n let current = mark;\n let cap = limit(mark, swing);\n let progress = 0;\n const show = (): void => {\n const angle = cap * rock(progress);\n ctx.mark.set({ transform: angle === 0 ? undefined : matrix.rotate(angle, current.pivot) });\n };\n ctx.onChange((next) => {\n current = next;\n cap = limit(next, swing);\n show();\n });\n // Linear here: each half-swing eases itself.\n await ctx.tween({\n duration: DURATION,\n timing: \"effect\",\n ease: linear,\n update: (p) => {\n progress = p;\n show();\n }\n }).finished;\n },\n end() {},\n clear() {}\n };\n}\n\n/**\n * The largest angle, in radians, that moves no outline point more than `swing` px. A point at\n * distance r from the pivot, turned by θ, moves along a chord of 2r·sin(θ/2).\n */\nfunction limit(mark: MarkGeometry, swing: number): number {\n const { pivot } = mark;\n let reach = 0;\n for (const point of mark.outline.sample(SAMPLES)) reach = Math.max(reach, Math.hypot(point.x - pivot.x, point.y - pivot.y));\n if (!(reach >= MIN_REACH)) return 0;\n return Math.min(MAX_ANGLE, 2 * Math.asin(Math.min(1, swing / (2 * reach))));\n}\n\n/** The share of the cap at linear progress t, 0–1: each half-swing a sine arch, 0 at both ends. */\nfunction rock(t: number): number {\n if (!(t > 0) || t >= 1) return 0;\n const position = t * SWINGS.length;\n const index = Math.floor(position);\n return SWINGS[index]! * Math.sin(Math.PI * (position - index));\n}\n\nfunction checkOptions(options: WiggleOptions): void {\n const { swing } = options;\n if (swing !== undefined && !(typeof swing === \"number\" && swing > 0 && swing <= SWING)) {\n throw new RangeError(`wiggle: swing must be more than 0 and at most ${SWING} px, got ${String(swing)}.`);\n }\n}\n","// pulse: a halo that grows out from the mark's outline and fades, a few times over, for \"look here\"\n// (`on: { enter: \"pulse\" }`). Like flash it reads nothing of the geometry: the renderer strokes the\n// halo along the outline as it is on screen.\n\nimport { easeOutCubic, linear } from \"../core\";\nimport type { Color, EffectContext, GeometryEffect } from \"../core\";\n\nexport interface PulseOptions {\n /** How many pulses, a whole number from 1 to 6. Fewer play if they wouldn't finish within 5 s. Default 2. */\n readonly times?: number;\n /** The halo's widest stroke, px; half of it shows outside the mark. Default 12. */\n readonly width?: number;\n /** A theme token or any CSS colour. Default: the mark's own colour. */\n readonly color?: Color;\n}\n\n/** Base duration of each pulse, with effect timing. */\nconst DURATION = 600;\nconst TIMES = 2;\nconst MAX_TIMES = 6;\nconst WIDTH = 12;\n/** The halo's opacity as it starts; it fades to 0 as it widens. */\nconst OPACITY = 0.4;\n/** Every pulse ends before this, in ms after scaling: anything longer needs a pause control (WCAG 2.2.2). */\nconst LIMIT = 5000;\n\n/**\n * Halos that widen from 0 to `width` while fading from 40% to nothing, 600 ms base each, `times`\n * over. Each pulse is its own tween, so Analysis shortens every pulse rather than dropping any; a\n * page whose scaling stretches pulses past 5 s in all gets fewer of them instead.\n *\n * It never changes the mark's size, so a value never looks bigger than it is. Its end state is\n * nothing: a pulse draws attention, and what it points at stays on the chart.\n */\nexport function pulse(options: PulseOptions = {}): GeometryEffect {\n checkOptions(options);\n const times = options.times ?? TIMES;\n const width = options.width ?? WIDTH;\n const { color } = options;\n\n // The ring rushes out and slows, while it fades steadily.\n const show = (ctx: EffectContext, t: number): void => {\n const visible = t > 0 && t < 1;\n ctx.mark.set({\n halo: visible ? { width: width * easeOutCubic(t), opacity: OPACITY * (1 - t), ...(color === undefined ? {} : { color }) } : undefined\n });\n };\n\n return {\n kind: \"geometry\",\n async run(_mark, ctx) {\n let total = 0;\n for (let i = 0; i < times; i++) {\n if (ctx.signal.aborted) return;\n // Each pulse's length as the motion scales it now; drop the ones that would end at 5 s or later.\n const length = ctx.motion.duration(DURATION, \"effect\");\n if (total + length >= LIMIT) return;\n total += length;\n // Linear here: show() eases the width itself.\n await ctx.tween({ duration: DURATION, timing: \"effect\", ease: linear, update: (t) => show(ctx, t) }).finished;\n }\n },\n end() {},\n clear() {}\n };\n}\n\nfunction checkOptions(options: PulseOptions): void {\n const { times, width, color } = options;\n if (times !== undefined && !(Number.isInteger(times) && times >= 1 && times <= MAX_TIMES)) {\n throw new RangeError(`pulse: times must be a whole number from 1 to ${MAX_TIMES}, got ${String(times)}.`);\n }\n if (width !== undefined && !(typeof width === \"number\" && width > 0 && Number.isFinite(width))) {\n throw new RangeError(`pulse: width must be more than 0 px, got ${String(width)}.`);\n }\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`pulse: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n}\n","// trace: a highlighter stroke that draws itself along the mark's walk and stays (the effects guide's\n// sketch, grown). It reads only the walk, so it runs on any mark, and it leaves the mark itself\n// untouched, so it's safe in any slot.\n\nimport { easeInOutCubic } from \"../core\";\nimport type { Color, EffectContext, GeometryEffect, MarkGeometry, Paint, PathHandle } from \"../core\";\n\nexport interface TraceOptions {\n /** A theme token or any CSS colour. Default \"mark\", the mark's own colour (a stack's first segment's). */\n readonly color?: Color;\n /** The stroke's width, px. Default 3. */\n readonly width?: number;\n /** From 0 to 1. Default 0.5. */\n readonly opacity?: number;\n /** Base ms to draw the stroke, before the motion mode scales it, with effect timing. Default 500. */\n readonly duration?: number;\n}\n\nconst DURATION = 500;\nconst WIDTH = 3;\nconst OPACITY = 0.5;\n/** A walk shorter than this draws nothing. */\nconst MIN_WALK = 0.5;\n\n/**\n * Draws an overlay stroke along the mark's walk, from its start to its end, eased in and out over\n * `duration`, with round caps. On a stack it runs the whole walk, across every segment. A walk under\n * 0.5 px (a point) draws nothing, and a run on one finishes at once.\n *\n * The stroke stays, and follows `onChange`, so it keeps to the mark through a transition or a\n * resize. Its end state is the whole stroke, so reduced motion shows what a full run ends with.\n */\nexport function trace(options: TraceOptions = {}): GeometryEffect {\n checkOptions(options);\n const duration = options.duration ?? DURATION;\n const paint: Paint = { stroke: options.color ?? \"mark\", width: options.width ?? WIDTH, opacity: options.opacity ?? OPACITY, linecap: \"round\" };\n\n /** Draws the stroke up to progress p along the walk, and keeps it on the mark when the mark moves. */\n const stroke = (mark: MarkGeometry, ctx: EffectContext): ((p: number) => void) => {\n let current = mark;\n let progress = 0;\n let path: PathHandle | undefined;\n const draw = (): void => {\n if (!(current.length >= MIN_WALK)) {\n path?.remove();\n path = undefined;\n return;\n }\n // At progress 0 this is a lone moveto, which SVG doesn't stroke, even with round caps.\n const d = current.slice(0, progress);\n if (path) path.update(d);\n else path = ctx.layer.path(d, paint);\n };\n ctx.onChange((next) => {\n current = next;\n draw();\n });\n // Drawn now, so a run stacks the stroke where end() does among the other parts of a combination.\n draw();\n return (p) => {\n progress = p;\n draw();\n };\n };\n\n return {\n kind: \"geometry\",\n async run(mark, ctx) {\n if (ctx.signal.aborted) return;\n const show = stroke(mark, ctx);\n // No walk to draw along: the end state at once, so the stroke is whole if the mark grows one.\n if (!(mark.length >= MIN_WALK)) {\n show(1);\n return;\n }\n await ctx.tween({ duration, timing: \"effect\", ease: easeInOutCubic, update: show }).finished;\n },\n end(mark, ctx) {\n stroke(mark, ctx)(1);\n },\n clear() {}\n };\n}\n\nfunction checkOptions(options: TraceOptions): void {\n const { color, width, opacity, duration } = options;\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`trace: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n if (width !== undefined && !(typeof width === \"number\" && width >= 0 && Number.isFinite(width))) {\n throw new RangeError(`trace: width must be 0 px or more, got ${String(width)}.`);\n }\n if (opacity !== undefined && !(typeof opacity === \"number\" && opacity >= 0 && opacity <= 1)) {\n throw new RangeError(`trace: opacity must be from 0 to 1, got ${String(opacity)}.`);\n }\n if (duration !== undefined && !(typeof duration === \"number\" && duration >= 0 && Number.isFinite(duration))) {\n throw new RangeError(`trace: duration must be 0 ms or more, got ${String(duration)}.`);\n }\n}\n","// A caption: text past the end of a mark's walk, or past its own labels (`labelBounds`), rising into\n// place. delta and label draw through it, so they place and rise the same way. Internal:\n// it reads only the geometry, and draws only through the context's layer.\n\nimport { offset } from \"../core\";\nimport type { Color, EffectContext, MarkData, MarkGeometry, Point, Rect, TextHandle } from \"../core\";\n\n/** Past the end of the walk, with no label in the way. */\nconst PAST_END = 10;\n/** Past the farthest of the mark's labels in the way; a label is in the way when the line it's placed along passes within this of it, since the text has height. */\nconst PAST_LABEL = 6;\n/** How far it rises into place, across the way it's placed. */\nconst RISE = 8;\n/** The overlay's text size (the theme's `.ec-text`), for where the baseline goes. */\nconst TEXT = 12.5;\n/** Shares of the text size from the anchor point down to the baseline: text read sideways is centred on the walk's line, as the charts' labels are; text read downwards hangs from it. */\nconst CENTRE = 0.36;\nconst HANG = 0.8;\n\nexport type CaptionAnchor = \"start\" | \"middle\" | \"end\";\n\nexport interface CaptionPlace {\n /** The text's anchor point, on its baseline. */\n readonly at: Point;\n readonly anchor: CaptionAnchor;\n /** The way it was placed, in radians: the walk's heading, or the mark's up side. */\n readonly toward: number;\n}\n\n/**\n * Where a caption goes on `mark`.\n *\n * - **Along the heading,** from the end of the walk: 10 px past the end, or 6 px past the farthest of\n * its `labelBounds` the heading meets, whichever is further. The heading meets a box when it passes\n * within 6 px of it: the text has height, and a heading that just misses a label would put the\n * text on it.\n * - **Up from its centre,** when the heading meets none of its labels but its up side does: 6 px past\n * the farthest of them. A slice's heading runs along the ring, and its up side goes out through its\n * label outside it.\n *\n * It's anchored by the way it was placed: at its start reading rightwards, its end leftwards, and its\n * middle within 45° of vertical, so a column's sits centred above its value. Its baseline is a little\n * below the point: read sideways, the text is centred on the line it was placed along, as the\n * charts' labels are; read upwards, it stands on it; read downwards, it hangs from it.\n */\nexport function captionPlace(mark: MarkGeometry): CaptionPlace {\n const boxes = mark.labelBounds ?? [];\n const heading = mark.angle(1);\n const along = farthest(mark.end, heading, boxes);\n if (along === undefined && boxes.length > 0) {\n const up = mark.angle(0.5) - Math.PI / 2;\n const out = farthest(mark.center, up, boxes);\n if (out !== undefined) return placed(mark.center, up, out);\n }\n return placed(mark.end, heading, Math.max(PAST_END, along ?? -Infinity));\n}\n\n/** The caption `distance` px from `from` towards `toward`, anchored and dropped to its baseline by that direction. */\nfunction placed(from: Point, toward: number, distance: number): CaptionPlace {\n const cos = Math.cos(toward);\n const sin = Math.sin(toward);\n const point = offset(from, toward, distance);\n const drop = TEXT * (sin < 0 ? CENTRE * (1 + sin) : CENTRE + (HANG - CENTRE) * sin);\n const anchor: CaptionAnchor = Math.abs(cos) <= Math.SQRT1_2 + 1e-9 ? \"middle\" : cos > 0 ? \"start\" : \"end\";\n return { at: { x: point.x, y: point.y + drop }, anchor, toward };\n}\n\n/**\n * How far from `from` towards `toward` the ray leaves the farthest of `boxes` it meets, each grown by\n * 6 px on every side, so it's 6 px past the box itself; or undefined when it meets none.\n */\nfunction farthest(from: Point, toward: number, boxes: readonly Rect[]): number | undefined {\n const cos = Math.cos(toward);\n const sin = Math.sin(toward);\n let exit: number | undefined;\n for (const { x, y, width, height } of boxes) {\n const grown = { x: x - PAST_LABEL, y: y - PAST_LABEL, width: width + 2 * PAST_LABEL, height: height + 2 * PAST_LABEL };\n const leaving = leaves(from, cos, sin, grown);\n if (leaving !== undefined) exit = Math.max(exit ?? leaving, leaving);\n }\n return exit;\n}\n\n/** How far along the ray from `from` (direction cos, sin) it leaves `box`, or undefined when it never meets it. */\nfunction leaves(from: Point, cos: number, sin: number, box: Rect): number | undefined {\n let near = 0;\n let far = Infinity;\n for (const [origin, step, lo, hi] of [\n [from.x, cos, box.x, box.x + box.width],\n [from.y, sin, box.y, box.y + box.height]\n ] as const) {\n if (Math.abs(step) < 1e-12) {\n if (origin < lo || origin > hi) return undefined;\n continue;\n }\n const a = (lo - origin) / step;\n const b = (hi - origin) / step;\n near = Math.max(near, Math.min(a, b));\n far = Math.min(far, Math.max(a, b));\n }\n return far >= near ? far : undefined;\n}\n\n/**\n * Draws a caption on the mark now, at rise 0, and returns how to draw it at rise p: from 0 (8 px\n * across the way it was placed, on that way's down side, unseen) to 1 (in place, at full strength). It keeps to the mark\n * through `onChange`, its text worded again by `words` from the moved mark and its latest data. No\n * text (undefined or \"\") draws nothing.\n */\nexport function caption<D>(\n mark: MarkGeometry,\n data: MarkData<D>,\n ctx: EffectContext,\n color: Color,\n words: (mark: MarkGeometry, data: MarkData<D>) => string | undefined\n): (p: number) => void {\n let current = mark;\n let content = words(mark, data) ?? \"\";\n let latest = data;\n let progress = 0;\n let handle: TextHandle | undefined;\n const draw = (): void => {\n if (content === \"\") {\n handle?.remove();\n handle = undefined;\n return;\n }\n const { at, anchor, toward } = captionPlace(current);\n // Rising across the way it was placed, towards that way's up side, so it never crosses the labels it's placed past.\n const style = { at: offset(at, toward - Math.PI / 2, -RISE * (1 - progress)), anchor, color, opacity: progress };\n if (handle) handle.update(style, content);\n else handle = ctx.layer.text(content, style);\n };\n ctx.onChange((next, nextData) => {\n current = next;\n // The runner tells a run its own mark's data, so it has the run's rows.\n latest = (nextData as MarkData<D> | undefined) ?? latest;\n content = words(current, latest) ?? \"\";\n draw();\n });\n draw();\n return (p) => {\n progress = p;\n draw();\n };\n}\n","// delta: the change since the last update (\"+2\"), past the end of the mark and clear of its own labels,\n// for the update slot (`on: { update: delta() }`). A data effect: it compares the mark's value with its\n// value before the update, and draws the change as text that rises into place and stays.\n\nimport type { Color, DataEffect, MarkData } from \"../core\";\nimport { caption } from \"./caption\";\n\nexport interface DeltaOptions<D = unknown> {\n /** The mark's value. Default: its last sample's, so a bar's total, a line's value at its revealed end, a slice's share. */\n readonly value?: (data: MarkData<D>) => number;\n /** Words the change. Default: the page's locale, with its sign and at most two decimals (\"+2\", \"-0.3\"). */\n readonly format?: (change: number) => string;\n /** A theme token or any CSS colour. Default \"text\", never the series' colour. */\n readonly color?: Color;\n}\n\n/** Base duration of the rise, with effect timing. */\nconst DURATION = 400;\n/** A change this small, relative to the values, is float noise (0.1 + 0.2 against 0.3), not a change. */\nconst TIE = 1e-9;\n\nconst lastSample = (data: MarkData<unknown>): number => {\n const { samples } = data;\n return samples[samples.length - 1]?.value ?? Number.NaN;\n};\n\nlet wording: Intl.NumberFormat | undefined;\nconst signed = (change: number): string => {\n wording ??= new Intl.NumberFormat(undefined, { signDisplay: \"always\", maximumFractionDigits: 2 });\n return wording.format(change);\n};\n\n/**\n * The change since the last update, `value(data) − value(data.previous)`, as text past the end of the\n * mark: 10 px past the end of its walk, or 6 px past the farthest of its own labels its heading meets.\n * It rises 8 px into place and fades in over 400 ms base, then stays until the next update clears it,\n * following the mark as it moves. Its end state is the text in place, so reduced motion shows the\n * change. With no `previous`, or no change, it draws nothing.\n *\n * The text is in the overlay, which screen readers don't read: a page that relies on it says the same\n * in its table or its announcement.\n */\nexport function delta<D = unknown>(options: DeltaOptions<D> = {}): DataEffect<D> {\n checkOptions(options);\n const value = options.value ?? lastSample;\n const format = options.format ?? signed;\n const color = options.color ?? \"text\";\n\n /** The change in words, or undefined for none. */\n const words = (data: MarkData<D>): string | undefined => {\n if (!data.previous) return undefined;\n const now = value(data);\n const before = value(data.previous);\n const change = now - before;\n if (!Number.isFinite(change) || Math.abs(change) <= TIE * Math.max(Math.abs(now), Math.abs(before))) return undefined;\n return format(change);\n };\n\n return {\n kind: \"data\",\n run: async (mark, data, ctx) => {\n if (ctx.signal.aborted) return;\n // Worked out once: the change is this update's, wherever the mark moves after.\n const text = words(data);\n if (text === undefined || text === \"\") return;\n const show = caption(mark, data, ctx, color, () => text);\n await ctx.tween({ duration: DURATION, timing: \"effect\", update: show }).finished;\n },\n end: (mark, data, ctx) => {\n const text = words(data);\n if (text !== undefined && text !== \"\") caption(mark, data, ctx, color, () => text)(1);\n },\n clear() {}\n };\n}\n\nfunction checkOptions<D>(options: DeltaOptions<D>): void {\n const { value, format, color } = options;\n if (value !== undefined && typeof value !== \"function\") throw new TypeError(`delta: value must be a function that reads the mark's value from its data, got ${typeof value}.`);\n if (format !== undefined && typeof format !== \"function\") throw new TypeError(`delta: format must be a function that words the change, got ${typeof format}.`);\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`delta: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n}\n","// label: text worked out from the mark's own data, past the end of the mark and clear of its own\n// labels, usually for the decorate slot: a slope's change from first to last, a step's signed value, a\n// field such as `vsLastMonth`. A data effect: it reads the mark's data, and words it again on every change.\n\nimport type { Color, DataEffect, MarkData, MarkGeometry } from \"../core\";\nimport { caption } from \"./caption\";\n\nexport interface LabelOptions {\n /** A theme token or any CSS colour. Default \"text\", never the series' colour. */\n readonly color?: Color;\n}\n\n/** Base duration of the rise, with effect timing, as delta's. */\nconst DURATION = 400;\n\n/**\n * Text from `text(data, mark)` past the end of the mark: 10 px past the end of its walk, or 6 px\n * past the farthest of its own labels its heading meets. `text` returns the words, or undefined or\n * \"\" for none. It's typed by the rows it reads, so a label written for one kind of row is a type\n * error on a chart of another.\n *\n * It rises 8 px into place and fades in over 400 ms base, as delta does, then follows every change,\n * its text worked out again from the new data. Its end state is the text in place. The text is in\n * the overlay, which screen readers don't read: a page that relies on it says the same in its table\n * or its announcement.\n */\nexport function label<D = unknown>(text: (data: MarkData<D>, mark: MarkGeometry) => string | undefined, options: LabelOptions = {}): DataEffect<D> {\n if (typeof text !== \"function\") throw new TypeError(`label needs a function that returns the text from the mark's data, got ${typeof text}.`);\n const { color = \"text\" } = options;\n if (typeof color !== \"string\" || color === \"\") throw new RangeError(`label: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n const words = (mark: MarkGeometry, data: MarkData<D>): string | undefined => {\n const said: unknown = text(data, mark);\n return said === undefined || said === null ? undefined : String(said);\n };\n\n return {\n kind: \"data\",\n run: async (mark, data, ctx) => {\n if (ctx.signal.aborted) return;\n const show = caption(mark, data, ctx, color, words);\n await ctx.tween({ duration: DURATION, timing: \"effect\", update: show }).finished;\n },\n end: (mark, data, ctx) => caption(mark, data, ctx, color, words)(1),\n clear() {}\n };\n}\n","// threshold: colours the parts of a mark's walk where its values are below a reference (or above it),\n// as the lab's goals line turns red wherever it's under xG. A data effect: it reads the mark's samples\n// and, for a series, the related series' samples, and draws along the walk, so it runs on any mark\n// that has samples. It's an encoding, not motion: it draws at once and redraws on every change.\n\nimport type { Color, DataEffect, EffectContext, MarkData, MarkGeometry, Paint, PathHandle, Sample } from \"../core\";\n\nexport interface ThresholdOptions {\n /**\n * The reference: a constant, or the name of a related series (\"xg\"), which goes in `needs.related`\n * so a chart without that series throws when it's created.\n */\n readonly compareTo: number | string;\n /** Colour where the mark's values are \"below\" the reference (default) or \"above\" it. Equal values aren't coloured. */\n readonly when?: \"below\" | \"above\";\n /** A theme token or any CSS colour. Default \"negative\". */\n readonly color?: Color;\n}\n\n/** A walk shorter than this draws nothing. */\nconst MIN_WALK = 0.5;\n/** Values this close, relative to their size, count as equal, so float noise in a sum colours nothing. */\nconst TIE = 1e-9;\nconst WHENS: readonly string[] = [\"below\", \"above\"];\n\n/**\n * Colours the parts of the walk where the mark's values are below `compareTo` (or above it, with\n * `when: \"above\"`): one overlay path per run, `mark.slice(t0, t1)` stroked in `color` at the mark's\n * thickness with butt caps, so a coloured part ends exactly at its crossing.\n *\n * - **A constant** is compared with every sample as it is.\n * - **A series** is compared by `at` when every sample of both has a number or a Date there, the\n * reference interpolated between its samples and nothing coloured outside its range. Otherwise by `t`.\n * - **Crossings** are interpolated linearly in `t` between samples (and between the reference's\n * samples, where it bends), so they're exact where the walk is straight between samples: our lines,\n * and a host polyline sampled at its vertices. Along a curve they're approximate; denser samples\n * narrow the error.\n * - **Gaps.** Nothing is interpolated across a sample with `gapBefore`, the mark's or the reference's:\n * where either has no value, nothing is coloured. `slice()` leaves the mark's own gaps out too.\n *\n * It draws at once, with no animation, and redraws on every `onChange`, so it follows a line as it's\n * revealed. Its end state is the same picture, so the colour shows with motion off.\n */\nexport function threshold(options: ThresholdOptions): DataEffect {\n checkOptions(options);\n const { compareTo } = options;\n const when = options.when ?? \"below\";\n const color = options.color ?? \"negative\";\n\n /** Draws the runs on the mark, and again whenever it or its data change. */\n const follow = (mark: MarkGeometry, data: MarkData, ctx: EffectContext): void => {\n const paths: PathHandle[] = [];\n let latest = data;\n const draw = (current: MarkGeometry): void => {\n const parts = current.length >= MIN_WALK ? runs(latest.samples, reference(compareTo, latest), when) : [];\n const paint: Paint = { stroke: color, width: current.thickness, linecap: \"butt\" };\n parts.forEach(([t0, t1], i) => {\n const d = current.slice(t0, t1);\n const path = paths[i];\n if (path) path.update(d, paint);\n else paths.push(ctx.layer.path(d, paint));\n });\n for (const path of paths.splice(parts.length)) path.remove();\n };\n ctx.onChange((next, nextData) => {\n latest = nextData ?? latest;\n draw(next);\n });\n draw(mark);\n };\n\n return {\n kind: \"data\",\n ...(typeof compareTo === \"string\" ? { needs: Object.freeze({ related: Object.freeze([compareTo]) }) } : {}),\n run: async (mark, data, ctx) => {\n if (!ctx.signal.aborted) follow(mark, data, ctx);\n },\n end: (mark, data, ctx) => follow(mark, data, ctx),\n clear() {}\n };\n}\n\n/** What the mark's values are compared with, along some axis `u`: the samples' `at`, or their `t`. */\ninterface Reference {\n /** Where a mark's sample sits on the reference's axis. */\n place(sample: Sample): number;\n /** The reference at u, or undefined outside its range and inside its gaps (their ends have values). */\n valueAt(u: number): number | undefined;\n /** Where the reference bends, in u: its samples' places. */\n readonly bends: readonly number[];\n}\n\n/** The reference for the mark's data, or undefined when the related series is missing. */\nfunction reference(compareTo: number | string, data: MarkData): Reference | undefined {\n if (typeof compareTo === \"number\") return { place: (sample) => sample.t, valueAt: () => compareTo, bends: [] };\n const related = data.related(compareTo);\n if (!related) return undefined;\n const byAt = data.samples.every((sample) => numeric(sample.at) !== undefined) && related.samples.every((sample) => numeric(sample.at) !== undefined);\n const place = byAt ? (sample: Sample) => numeric(sample.at)! : (sample: Sample) => sample.t;\n const points = related.samples\n .map((sample) => ({ u: place(sample), value: sample.value }))\n .filter((point) => Number.isFinite(point.u))\n .sort((a, b) => a.u - b.u);\n const gaps = gapsOf(related.samples, place);\n return { place, valueAt: (u) => (inside(gaps, u) ? undefined : interpolate(points, u)), bends: points.map((point) => point.u) };\n}\n\n/** Where the samples have no value, in u: from the sample before each `gapBefore` to it, merged and in order. */\nfunction gapsOf(samples: readonly Sample[], place: (sample: Sample) => number): [number, number][] {\n const gaps: [number, number][] = [];\n samples.forEach((sample, i) => {\n const before = samples[i - 1];\n if (sample.gapBefore !== true || !before) return;\n const u = place(before);\n const v = place(sample);\n if (Number.isFinite(u) && Number.isFinite(v) && u !== v) gaps.push([Math.min(u, v), Math.max(u, v)]);\n });\n gaps.sort((a, b) => a[0] - b[0]);\n const merged: [number, number][] = [];\n for (const gap of gaps) {\n const last = merged[merged.length - 1];\n if (last && gap[0] < last[1]) last[1] = Math.max(last[1], gap[1]);\n else merged.push(gap);\n }\n return merged;\n}\n\n/** Whether u is strictly inside one of the gaps (merged and in order). */\nfunction inside(gaps: readonly (readonly [number, number])[], u: number): boolean {\n // The gap after the last one that starts before u.\n let lo = 0;\n let hi = gaps.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (gaps[mid]![0] < u) lo = mid + 1;\n else hi = mid;\n }\n const gap = gaps[lo - 1];\n return gap !== undefined && u < gap[1];\n}\n\n/** A sample's `at` as a number: a finite number, or a valid Date's time. Labels have none. */\nfunction numeric(at: Sample[\"at\"]): number | undefined {\n const value = typeof at === \"number\" ? at : at instanceof Date ? at.getTime() : undefined;\n return value !== undefined && Number.isFinite(value) ? value : undefined;\n}\n\n/** The value at u, linear between the points around it (sorted by u); undefined outside them. */\nfunction interpolate(points: readonly { readonly u: number; readonly value: number }[], u: number): number | undefined {\n const first = points[0];\n const last = points[points.length - 1];\n if (!first || !last || u < first.u || u > last.u) return undefined;\n // The first point at u or past it.\n let lo = 0;\n let hi = points.length - 1;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (points[mid]!.u < u) lo = mid + 1;\n else hi = mid;\n }\n const b = points[lo]!;\n if (lo === 0 || b.u === u) return b.value;\n const a = points[lo - 1]!;\n return a.value + ((u - a.u) / (b.u - a.u)) * (b.value - a.value);\n}\n\n/** A place along the walk, with how far past the reference the mark is there: more than 0 is coloured. */\ninterface Station {\n readonly t: number;\n /** Where it is on the reference's axis. */\n readonly u: number;\n /** Undefined where there's no reference or no finite value. */\n readonly past: number | undefined;\n /** False after a gap in the mark's values: nothing is coloured between it and the station before. */\n readonly joined: boolean;\n}\n\n/**\n * The parts of the walk, as [t0, t1] in order, where the mark's values are past the reference on the\n * `when` side. Between neighbouring stations (the samples, plus the places where the reference bends\n * between them) both are linear in t, so each crossing is where that difference reaches 0. Stations\n * either side of a gap, the mark's or the reference's, aren't joined.\n */\nfunction runs(samples: readonly Sample[], ref: Reference | undefined, when: \"below\" | \"above\"): [number, number][] {\n if (!ref) return [];\n const sign = when === \"below\" ? 1 : -1;\n const station = (t: number, u: number, value: number, joined = true): Station => {\n const level = ref.valueAt(u);\n if (level === undefined || !Number.isFinite(level) || !Number.isFinite(value) || !Number.isFinite(t)) return { t, u, past: undefined, joined };\n const past = sign * (level - value);\n return { t, u, past: Math.abs(past) <= TIE * Math.max(Math.abs(level), Math.abs(value)) ? 0 : past, joined };\n };\n\n const stations: Station[] = [];\n samples.forEach((sample, i) => {\n const u = ref.place(sample);\n stations.push(station(sample.t, u, sample.value, sample.gapBefore !== true));\n const next = samples[i + 1];\n // No bends across a gap in the mark's values: there's nothing there to compare.\n if (!next || next.gapBefore === true) return;\n // Where the reference bends between this sample and the next, in the order the walk meets them.\n const v = ref.place(next);\n if (u === v || !Number.isFinite(u) || !Number.isFinite(v)) return;\n const shares: number[] = [];\n const { bends } = ref;\n for (let j = firstAbove(bends, Math.min(u, v)); j < bends.length && bends[j]! < Math.max(u, v); j++) shares.push((bends[j]! - u) / (v - u));\n if (v < u) shares.reverse();\n for (const share of shares) {\n stations.push(station(sample.t + share * (next.t - sample.t), u + share * (v - u), sample.value + share * (next.value - sample.value)));\n }\n });\n\n const parts: [number, number][] = [];\n const add = (t0: number, t1: number): void => {\n const from = clamp(t0);\n const to = clamp(t1);\n if (!(to > from)) return;\n const last = parts[parts.length - 1];\n if (last && last[1] >= from) last[1] = Math.max(last[1], to);\n else parts.push([from, to]);\n };\n for (let i = 1; i < stations.length; i++) {\n const a = stations[i - 1]!;\n const b = stations[i]!;\n if (a.past === undefined || b.past === undefined || !b.joined || !(b.t > a.t)) continue;\n // Between two stations the reference doesn't bend, so it's in a gap there if it is halfway.\n if (a.u !== b.u && ref.valueAt((a.u + b.u) / 2) === undefined) continue;\n if (a.past > 0 && b.past > 0) add(a.t, b.t);\n else if (a.past > 0) add(a.t, a.t + (b.t - a.t) * (a.past / (a.past - b.past)));\n else if (b.past > 0) add(a.t + (b.t - a.t) * (a.past / (a.past - b.past)), b.t);\n }\n return parts;\n}\n\nconst clamp = (t: number): number => Math.min(1, Math.max(0, t));\n\n/** The index of the first value more than x, in ascending values. */\nfunction firstAbove(values: readonly number[], x: number): number {\n let lo = 0;\n let hi = values.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (values[mid]! <= x) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\nfunction checkOptions(options: ThresholdOptions): void {\n const { compareTo, when, color } = (options ?? {}) as Partial<ThresholdOptions>;\n if (!(typeof compareTo === \"string\" ? compareTo !== \"\" : typeof compareTo === \"number\" && Number.isFinite(compareTo))) {\n throw new RangeError(`threshold: compareTo must be a finite number or a series name, got ${show(compareTo)}.`);\n }\n if (when !== undefined && !WHENS.includes(when)) throw new RangeError(`threshold: when must be \"below\" or \"above\", got ${show(when)}.`);\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`threshold: color must be a theme token or a CSS colour, got ${show(color)}.`);\n }\n}\n\nconst show = (value: unknown): string => (typeof value === \"string\" ? JSON.stringify(value) : String(value));\n","// morph: the transition effect that turns one mark's shape into another's, as the lab's donut turns\n// into columns. Both outlines are sampled at the same number of points and each point moves in a\n// straight line to its partner. It reads only the two geometries, so it morphs any mark into any\n// other: bars, slices and points (closed outlines) and lines (open ones).\n\nimport { easeInOutCubic, linear } from \"../core\";\nimport type { Layer, MarkGeometry, Paint, PathHandle, Point, TransitionEffect, Tween } from \"../core\";\nimport { unease } from \"../core/easing\";\nimport { formatNumber } from \"../core/geometry\";\nimport { goesRound } from \"../core/geometry/ring\";\n\n/** How two closed outlines' sides are matched. */\nexport type MorphAlign = \"unroll\" | \"drop\";\n\nexport interface MorphOptions {\n /** Points sampled on each outline, a whole multiple of 4 (a quarter on each side of a closed one). Default 160, the lab's 40 a side. */\n readonly points?: number;\n /**\n * How two closed outlines' sides are matched:\n * - \"unroll\" matches each side with the same side. A slice's walk becomes a column's, so the slice\n * stands up: its outer arc becomes the column's left side, and the angle it spans its height.\n * - \"drop\" turns the matching by one side, as the lab does: a slice's outer arc becomes a column's\n * top, so it settles onto the baseline.\n *\n * Default \"unroll\", picked over \"drop\" by comparing the two in the morph demo (demo/morph.html).\n */\n readonly align?: MorphAlign;\n}\n\n/** The lab's morph: 950 ms base, with transition timing. */\nconst DURATION = 950;\nconst POINTS = 160;\nconst ALIGNS: readonly string[] = [\"unroll\", \"drop\"];\n\n/** Draws the morph at eased progress p, from 0 (`from`) to 1 (`to`), creating or updating its paths. */\ntype Draw = (p: number) => void;\n\n/**\n * Morphs `from` into `to` over 950 ms base (`transition` timing: at most 200 ms in Analysis, a jump\n * in Off), eased in and out.\n *\n * - **Two closed outlines** (bars, slices, points): both are sampled at `points`, and each point\n * moves in a straight line to its partner, drawn as one filled path in the mark's colour. With\n * `align: \"drop\"` the pairing is turned by a quarter, from a mark that goes round its pivot (a\n * slice) to one that doesn't (a bar), whichever is `from`: so a switch back retraces the same\n * pairing instead of twisting. Between two marks of the same kind, \"drop\" pairs as \"unroll\" does.\n * - **Two open outlines** (lines): both strokes are sampled along their length, and the stroke's\n * width moves from one thickness to the other.\n * - **A closed and an open outline** crossfade: the first fades out as the second fades in.\n *\n * A run from `ctx.start` begins with the shapes there, in their eased progress, and takes the rest\n * of the time a full run would. The end state is the target's own outline.\n */\nexport function morph(options: MorphOptions = {}): TransitionEffect {\n checkOptions(options);\n const points = options?.points ?? POINTS;\n const align = options?.align ?? \"unroll\";\n\n return {\n kind: \"transition\",\n async run(from, to, ctx) {\n if (ctx.signal.aborted) return;\n const draw = drawing(from, to, ctx.layer, points, align);\n const start = startOf(ctx.start);\n if (start >= 1) {\n draw(1);\n return;\n }\n // When a full run's shapes are at `start`: the run plays from there, so it takes the rest of\n // the full run's time, whatever the motion mode scales that to.\n const begun = unease(start);\n let running: Tween | undefined;\n running = ctx.tween({\n duration: DURATION,\n timing: \"transition\",\n ease: linear,\n update: (k) => {\n const u = Math.min(1, begun + k);\n draw(k === 0 ? start : easeInOutCubic(u));\n if (u >= 1 && k < 1) running?.finish();\n }\n });\n await running.finished;\n },\n end(from, to, ctx) {\n drawing(from, to, ctx.layer, points, align)(1);\n },\n clear() {}\n };\n}\n\nfunction drawing(from: MarkGeometry, to: MarkGeometry, layer: Layer, points: number, align: MorphAlign): Draw {\n const closed = from.outline.closed;\n if (closed !== to.outline.closed) return crossfade(from, to, layer);\n const a = from.outline.sample(points);\n const b = to.outline.sample(points);\n if (!closed) return stroke(from, to, layer, a, b);\n const [shiftA, shiftB] = align === \"drop\" ? turn(from, to, points) : [0, 0];\n let path: PathHandle | undefined;\n return (p) => {\n const d = p <= 0 ? from.outline.d : p >= 1 ? to.outline.d : between(a, b, shiftA, shiftB, p, true);\n if (path) path.update(d);\n else path = layer.path(d, { fill: \"mark\" });\n };\n}\n\n/** One stroke whose points and width move between the two lines'. */\nfunction stroke(from: MarkGeometry, to: MarkGeometry, layer: Layer, a: readonly Point[], b: readonly Point[]): Draw {\n let path: PathHandle | undefined;\n return (p) => {\n const d = p <= 0 ? from.outline.d : p >= 1 ? to.outline.d : between(a, b, 0, 0, p, false);\n const width = p <= 0 ? from.thickness : p >= 1 ? to.thickness : mix(from.thickness, to.thickness, p);\n if (path) path.update(d, { width });\n else path = layer.path(d, { stroke: \"mark\", width });\n };\n}\n\n/** The two outlines as they are, the closed one below the open one, whichever is leaving: so a switch back draws the same picture. */\nfunction crossfade(from: MarkGeometry, to: MarkGeometry, layer: Layer): Draw {\n const paint = (mark: MarkGeometry, opacity?: number): Paint => ({\n ...(mark.outline.closed ? { fill: \"mark\" } : { stroke: \"mark\", width: mark.thickness }),\n ...(opacity === undefined ? {} : { opacity })\n });\n let leaving: PathHandle | undefined;\n let coming: PathHandle | undefined;\n return (p) => {\n if (p >= 1) {\n leaving?.remove();\n leaving = undefined;\n if (coming) coming.update(to.outline.d, { opacity: undefined });\n else coming = layer.path(to.outline.d, paint(to));\n return;\n }\n if (coming) {\n leaving?.update(from.outline.d, { opacity: 1 - p });\n coming.update(to.outline.d, { opacity: p });\n } else if (from.outline.closed) {\n leaving = layer.path(from.outline.d, paint(from, 1 - p));\n coming = layer.path(to.outline.d, paint(to, p));\n } else {\n coming = layer.path(to.outline.d, paint(to, p));\n leaving = layer.path(from.outline.d, paint(from, 1 - p));\n }\n };\n}\n\n/**\n * Path data for the shape at p: point i is a[i + shiftA] moved toward b[i + shiftB] (indices wrap).\n * The shifts start the path at the same pair whichever mark is `from`, so a run back from 1 - p\n * draws exactly what the run forward drew at p.\n */\nfunction between(a: readonly Point[], b: readonly Point[], shiftA: number, shiftB: number, p: number, closed: boolean): string {\n const n = a.length;\n let d = \"\";\n for (let i = 0; i < n; i++) {\n const from = a[(i + shiftA) % n]!;\n const to = b[(i + shiftB) % n]!;\n d += `${i === 0 ? \"M\" : \"L\"}${formatNumber(mix(from.x, to.x, p))},${formatNumber(mix(from.y, to.y, p))}`;\n }\n return closed ? `${d}Z` : d;\n}\n\n/**\n * x moved toward y by p, weighted on both sides so that mix(y, x, 1 - p) is the same number: a run\n * back rounds every coordinate as the run forward did, even on a half (36.5625 at 0.001).\n */\nconst mix = (x: number, y: number, p: number): number => x * (1 - p) + y * p;\n\n/**\n * \"drop\"'s quarter turn, as [shift into from's samples, shift into to's]: the round mark's point i\n * pairs with the other's point i + n/4, so its first side (a slice's outer arc) meets the other's\n * end side (a column's top). Fixed by the marks' geometry, never by which one is `from`: whether a\n * walk goes round its pivot (a slice's does, a bar's doesn't), the test the adapter orders a ring by.\n */\nfunction turn(from: MarkGeometry, to: MarkGeometry, points: number): [number, number] {\n const quarter = points / 4;\n const roundFrom = goesRound(from);\n if (roundFrom === goesRound(to)) return [0, 0];\n return roundFrom ? [0, quarter] : [quarter, 0];\n}\n\n/** `ctx.start` clamped to 0–1; anything else is 0, so a context without one plays it all. */\nfunction startOf(start: unknown): number {\n return typeof start === \"number\" && start > 0 ? Math.min(1, start) : 0;\n}\n\nfunction checkOptions(options: MorphOptions): void {\n const { points, align } = (options ?? {}) as MorphOptions;\n if (points !== undefined && !(Number.isInteger(points) && points >= 4 && points % 4 === 0)) {\n throw new RangeError(`morph: points must be a whole multiple of 4, got ${String(points)}.`);\n }\n if (align !== undefined && !ALIGNS.includes(align)) throw new RangeError(`morph: align must be \"unroll\" or \"drop\", got ${typeof align === \"string\" ? JSON.stringify(align) : String(align)}.`);\n}\n","// Combinators: small effects put together. Every part shares the run's context (its layer, mark\n// handle and signal), and a combination is a data effect when any part is one.\n\nimport type { AnyMarkEffect, Combined, DataEffect, EffectContext, GeometryEffect, MarkData, MarkGeometry } from \"../core\";\nimport { describeValue, isMarkEffect } from \"../core/registry\";\n\n/**\n * Runs the parts one after another, each on the geometry and data as they are when it starts, since\n * the mark may move while an earlier part runs (a transition, a line being revealed). An abort stops\n * the chain, and `end()` draws every part's end state in order. A part with nothing to do (a travel\n * along a missing segment) finishes at once, so one sequence tells the whole story whatever the chart\n * shows.\n */\nexport function sequence<E extends readonly AnyMarkEffect[]>(...effects: E): Combined<E> {\n const parts = check(\"sequence\", effects);\n return combine<E>(parts, async (start, ctx) => {\n for (const part of parts) {\n if (ctx.signal.aborted) return;\n await start(part);\n }\n });\n}\n\n/** Runs the parts together and finishes when they all have. `end()` draws every part's end state, in order. */\nexport function parallel<E extends readonly AnyMarkEffect[]>(...effects: E): Combined<E> {\n const parts = check(\"parallel\", effects);\n return combine<E>(parts, async (start) => {\n await Promise.all(parts.map(start));\n });\n}\n\n/**\n * What `only` and `stagger` return: a new effect of the same kind, needing the same rows. Only the\n * effect interface is kept, not any other members the effect has.\n */\ntype Filtered<E extends AnyMarkEffect> = E extends DataEffect<infer D> ? DataEffect<D> : GeometryEffect;\n\n/** Runs the effect only on matching marks: a key, a series name, or a predicate. Elsewhere it does nothing. */\nexport function only<E extends AnyMarkEffect>(filter: string | ((mark: MarkGeometry) => boolean), effect: E): Filtered<E> {\n if (typeof filter !== \"string\" && typeof filter !== \"function\") throw new TypeError(`only needs a key, a series name or a predicate, got ${describeValue(filter)}.`);\n const [part] = check(\"only\", [effect]);\n const matches = typeof filter === \"string\" ? (mark: MarkGeometry) => mark.key === filter || mark.series === filter : filter;\n if (part!.kind === \"data\") {\n const inner = part as DataEffect<unknown>;\n const filtered: DataEffect<unknown> = {\n kind: \"data\",\n ...(inner.needs ? { needs: inner.needs } : {}),\n run: (mark, data, ctx) => (matches(mark) ? inner.run(mark, data, ctx) : Promise.resolve()),\n end: (mark, data, ctx) => {\n if (matches(mark)) inner.end(mark, data, ctx);\n },\n clear: (ctx) => inner.clear(ctx)\n };\n return filtered as Filtered<E>;\n }\n const inner = part as GeometryEffect;\n const filtered: GeometryEffect = {\n kind: \"geometry\",\n run: (mark, ctx) => (matches(mark) ? inner.run(mark, ctx) : Promise.resolve()),\n end(mark, ctx) {\n if (matches(mark)) inner.end(mark, ctx);\n },\n clear: (ctx) => inner.clear(ctx)\n };\n return filtered as Filtered<E>;\n}\n\nexport interface StaggerOptions {\n /** Base ms between one mark's start and the next's, 0 or more. Default 50. */\n readonly delay?: number;\n}\n\n/** Default base delay between marks, ms. */\nconst STAGGER_DELAY = 50;\n/** The last mark of a batch starts at most this long (base ms) after the first. */\nconst STAGGER_SPREAD = 500;\n\n/**\n * Starts each mark of a batch a little after the one before: mark i waits `i × delay` (base ms,\n * with \"stagger\" timing, so none at all in analysis or off), then runs the effect. The whole spread\n * is capped at 500 ms base, so a big batch's delay shrinks. A batch of one (a hover) never waits.\n *\n * Never a default: research finds little benefit in staggering, and it can hurt. It keeps the\n * effect's kind and `needs`, and `end()` draws the effect's end state at once.\n */\nexport function stagger<E extends AnyMarkEffect>(effect: E, options: StaggerOptions = {}): Filtered<E> {\n const [part] = check(\"stagger\", [effect]);\n const delay = options.delay ?? STAGGER_DELAY;\n if (!(typeof delay === \"number\" && delay >= 0 && Number.isFinite(delay))) {\n throw new RangeError(`stagger: delay must be 0 ms or more, got ${String(delay)}.`);\n }\n\n /**\n * Waits this mark's turn. The geometry and data may move meanwhile (marks growing in on enter), so\n * it resolves with the latest of each; undefined if the run was aborted while it waited.\n */\n const wait = async <M>(mark: MarkGeometry, data: M, ctx: EffectContext): Promise<Latest<M> | undefined> => {\n if (ctx.signal.aborted) return undefined;\n const { index, count } = ctx.batch;\n const step = count > 1 ? Math.min(delay, STAGGER_SPREAD / (count - 1)) : 0;\n const base = index > 0 ? index * step : 0;\n if (!(base > 0)) return { mark, data };\n const now = follow(mark, data, ctx);\n await ctx.tween({ duration: base, timing: \"stagger\", update: () => {} }).finished;\n return ctx.signal.aborted ? undefined : now();\n };\n\n if (part!.kind === \"data\") {\n const inner = part as DataEffect<unknown>;\n const staggered: DataEffect<unknown> = {\n kind: \"data\",\n ...(inner.needs ? { needs: inner.needs } : {}),\n run: async (mark, data, ctx) => {\n const turn = await wait(mark, data, ctx);\n if (turn) await inner.run(turn.mark, turn.data, ctx);\n },\n end: (mark, data, ctx) => inner.end(mark, data, ctx),\n clear: (ctx) => inner.clear(ctx)\n };\n return staggered as Filtered<E>;\n }\n const inner = part as GeometryEffect;\n const staggered: GeometryEffect = {\n kind: \"geometry\",\n async run(mark, ctx) {\n const turn = await wait(mark, undefined, ctx);\n if (turn) await inner.run(turn.mark, ctx);\n },\n end: (mark, ctx) => inner.end(mark, ctx),\n clear: (ctx) => inner.clear(ctx)\n };\n return staggered as Filtered<E>;\n}\n\n/** A mark's geometry and data as they are now. */\ninterface Latest<M> {\n readonly mark: MarkGeometry;\n readonly data: M;\n}\n\n/** The geometry and data as they are now: those given, until onChange brings newer ones. */\nfunction follow<M>(mark: MarkGeometry, data: M, ctx: EffectContext): () => Latest<M> {\n let latest: Latest<M> = { mark, data };\n ctx.onChange((next, nextData) => {\n latest = { mark: next, data: (nextData as M | undefined) ?? latest.data };\n });\n return () => latest;\n}\n\ntype Start = (part: AnyMarkEffect) => Promise<void>;\n\n/** Builds the combination's effect object, of the kind its parts make it. */\nfunction combine<E extends readonly AnyMarkEffect[]>(parts: readonly AnyMarkEffect[], play: (start: Start, ctx: EffectContext) => Promise<void>): Combined<E> {\n // Each part starts on the latest geometry and data, so a sequence's later parts don't start where the mark was.\n const starter = (mark: MarkGeometry, data: MarkData<unknown> | undefined, ctx: EffectContext): Start => {\n const now = follow(mark, data, ctx);\n return (part) => {\n const { mark: latest, data: values } = now();\n return part.kind === \"data\" ? part.run(latest, values!, ctx) : part.run(latest, ctx);\n };\n };\n const end = (mark: MarkGeometry, data: MarkData<unknown> | undefined, ctx: EffectContext): void => {\n for (const part of parts) {\n if (part.kind === \"data\") part.end(mark, data!, ctx);\n else part.end(mark, ctx);\n }\n };\n // Every part gets to clean up, even if one throws; the first error is passed on.\n const clear = (ctx: EffectContext): void => {\n let failure: { error: unknown } | undefined;\n for (const part of parts) {\n try {\n part.clear(ctx);\n } catch (error) {\n failure ??= { error };\n }\n }\n if (failure) throw failure.error;\n };\n\n if (parts.some((part) => part.kind === \"data\")) {\n const related = [...new Set(parts.flatMap((part) => (part.kind === \"data\" ? (part.needs?.related ?? []) : [])))];\n const effect: DataEffect<unknown> = {\n kind: \"data\",\n ...(related.length > 0 ? { needs: { related } } : {}),\n run: (mark, data, ctx) => play(starter(mark, data, ctx), ctx),\n end: (mark, data, ctx) => end(mark, data, ctx),\n clear\n };\n return effect as unknown as Combined<E>;\n }\n const effect: GeometryEffect = {\n kind: \"geometry\",\n run: (mark, ctx) => play(starter(mark, undefined, ctx), ctx),\n end: (mark, ctx) => end(mark, undefined, ctx),\n clear\n };\n return effect as unknown as Combined<E>;\n}\n\nfunction check(name: string, effects: readonly unknown[]): readonly AnyMarkEffect[] {\n effects.forEach((effect, index) => {\n if (!isMarkEffect(effect)) throw new TypeError(`${name}: part ${index + 1} needs to be a mark effect (kind \"geometry\" or \"data\"), got ${describeValue(effect)}.`);\n });\n return [...(effects as readonly AnyMarkEffect[])];\n}\n","// defineEffect and defineDataEffect: how effects written outside the library are made. They fill in\n// the kind and a no-op clear(), check that the effect can run and has an end state, and freeze it,\n// since one effect object runs on many marks at once (effects are stateless).\n\nimport type { DataEffect, EffectContext, GeometryEffect, MarkData, MarkGeometry } from \"../core\";\n\n/** What defineEffect takes: a geometry effect without its `kind`, `clear()` optional. */\nexport interface GeometryEffectSpec {\n /** Animates the mark; resolves when done or cancelled (ctx.signal aborted). */\n run(mark: MarkGeometry, ctx: EffectContext): Promise<void>;\n /** Draws the state a full run ends in, at once. Reduced motion shows only this. */\n end(mark: MarkGeometry, ctx: EffectContext): void;\n /** Cleanup beyond the runner's own (it empties the layer and resets the mark anyway). */\n clear?(ctx: EffectContext): void;\n}\n\n/**\n * What defineDataEffect takes: a data effect without its `kind`, `clear()` optional. As on\n * DataEffect, the functions are properties rather than methods, so the row type is checked strictly:\n * methods would let a spec that reads fields `D` doesn't have through.\n */\nexport interface DataEffectSpec<D> {\n /** Series the effect reads through data.related(), checked when a chart is created. */\n readonly needs?: { readonly related?: readonly string[] };\n readonly run: (mark: MarkGeometry, data: MarkData<D>, ctx: EffectContext) => Promise<void>;\n readonly end: (mark: MarkGeometry, data: MarkData<D>, ctx: EffectContext) => void;\n readonly clear?: (ctx: EffectContext) => void;\n}\n\nconst nothing = (): void => {};\n\n/**\n * A geometry effect from its `run` and `end`: `kind` is filled in and `clear` defaults to doing\n * nothing. Only `run`, `end` and `clear` are kept, and the effect is frozen. A spec without `run` or\n * `end` functions throws a TypeError: every effect needs an end state, since reduced motion shows\n * only that.\n */\nexport function defineEffect(spec: GeometryEffectSpec): GeometryEffect {\n check(\"defineEffect\", spec);\n const effect: GeometryEffect = { kind: \"geometry\", run: spec.run, end: spec.end, clear: spec.clear ?? nothing };\n return Object.freeze(effect);\n}\n\n/**\n * A data effect from its `run` and `end`, which also get the mark's data (`MarkData<D>`): its row,\n * values along the walk, related series and the values before an update. `needs.related` lists the\n * series it reads through `data.related()`, so a chart without them throws when it's created.\n * Otherwise as defineEffect.\n */\nexport function defineDataEffect<D = unknown>(spec: DataEffectSpec<D>): DataEffect<D> {\n check(\"defineDataEffect\", spec);\n const needs = checkNeeds(spec.needs);\n const effect: DataEffect<D> = { kind: \"data\", ...(needs ? { needs } : {}), run: spec.run, end: spec.end, clear: spec.clear ?? nothing };\n return Object.freeze(effect);\n}\n\nfunction check(name: string, spec: unknown): void {\n if (typeof spec !== \"object\" || spec === null) throw new TypeError(`${name} needs a spec object { run, end }, got ${spec === null ? \"null\" : typeof spec}.`);\n const { run, end, clear } = spec as Record<string, unknown>;\n if (typeof run !== \"function\") throw new TypeError(`${name}: run must be a function that animates the mark, got ${typeof run}.`);\n if (typeof end !== \"function\") {\n throw new TypeError(`${name}: end must be a function that draws the final state, got ${typeof end}. Every effect needs one: reduced motion shows only end states.`);\n }\n if (clear !== undefined && typeof clear !== \"function\") throw new TypeError(`${name}: clear must be a function if it's given, got ${typeof clear}.`);\n}\n\n/** A copy of `needs`, frozen, or undefined when it names no series. */\nfunction checkNeeds(needs: unknown): DataEffect[\"needs\"] {\n if (needs === undefined) return undefined;\n const related = typeof needs === \"object\" && needs !== null ? (needs as { related?: unknown }).related : undefined;\n const valid = typeof needs === \"object\" && needs !== null && (related === undefined || (Array.isArray(related) && related.every((s) => typeof s === \"string\" && s !== \"\")));\n if (!valid) throw new TypeError(`defineDataEffect: needs must be { related: [series names] }, got ${JSON.stringify(needs) ?? String(needs)}.`);\n return related === undefined ? undefined : Object.freeze({ related: Object.freeze([...(related as string[])]) });\n}\n","// iconFromSvg: turns SVG markup into an icon's shapes, keeping only plain drawing. It reads the\n// markup as text (no DOM, no parser that could load anything), so it's safe for untrusted input.\n\nimport type { Icon, IconShape, Matrix, Point, Rect } from \"../core\";\nimport { matrix } from \"../core\";\nimport { parseTransform } from \"../core/geometry\";\nimport { formatPath, parsePath, transformPath, type PathCommand } from \"../core/geometry/path\";\nimport { defineIcon, type IconSpec } from \"./define\";\n\n/**\n * What iconFromSvg takes besides the markup. `anchor`, `pivot`, `footprint` and `radius` are in the\n * SVG's own units (its viewBox). `size` is the natural length in px: the whole icon is scaled so its\n * box is that wide. Default: the viewBox's width, unscaled.\n */\nexport type SvgIconSpec = Omit<IconSpec, \"shapes\" | \"box\">;\n\n/** Elements whose children are drawn. Every other element that isn't a shape is dropped with its children. */\nconst CONTAINERS = new Set([\"svg\", \"g\", \"a\"]);\nconst SHAPES = new Set([\"path\", \"circle\", \"rect\", \"ellipse\", \"line\", \"polyline\", \"polygon\"]);\n// No part of a tag can contain \"<\" (XML doesn't allow it in attribute values), so a scan never runs\n// past the next tag and unclosed tags can't make matching slow.\nconst TAG = /<![^<>]*>|<(\\/?)([A-Za-z][\\w:.-]*)((?:\\s+[^\\s=/<>]+(?:\\s*=\\s*(?:\"[^\"<]*\"|'[^'<]*'|[^\\s\"'<>]+))?)*)\\s*(\\/?)>/g;\nconst ATTRIBUTE = /([^\\s=/<>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'<>]+)))?/g;\n/** Plain colours and theme tokens. url() paint servers and anything with quotes or brackets are not kept. */\nconst COLOR = /^(?:#[0-9a-fA-F]{3,8}|[a-zA-Z][a-zA-Z0-9-]*|(?:rgba?|hsla?)\\([\\d\\s.,%+\\-/]*\\))$/;\n\ninterface Inherited {\n readonly fill: string;\n readonly stroke: string;\n readonly width: number;\n readonly linecap: IconShape[\"linecap\"];\n readonly linejoin: IconShape[\"linejoin\"];\n readonly fillRule: NonNullable<IconShape[\"fillRule\"]>;\n /** The shape's own opacity times its groups'. */\n readonly opacity: number;\n readonly transform: Matrix;\n}\n\n/**\n * Converts `path`, `circle`, `rect`, `ellipse`, `line`, `polyline` and `polygon` elements into shapes,\n * with their fill, stroke, stroke width, line caps and joins, fill rule and opacity (as attributes or in\n * `style`, inherited from `<g>`, a group's opacity multiplied into its shapes') and transforms applied.\n * `currentColor` becomes the theme's `text` colour, so an icon from an icon set follows the chart's\n * theme. Everything else is dropped: scripts, event handlers, `<use>`, text, images, what's inside\n * `<defs>`, `<clipPath>` and the like, and shapes with an opacity of 0. Gradients, patterns, `fill-opacity`,\n * `stroke-opacity` and CSS classes aren't kept; a shape painted with a gradient or pattern falls back to\n * its inherited colour.\n */\nexport function iconFromSvg(markup: string, spec: SvgIconSpec): Icon {\n if (typeof markup !== \"string\") throw new TypeError(\"iconFromSvg needs SVG markup as a string.\");\n const label = typeof spec?.name === \"string\" ? `\"${spec.name}\"` : \"an icon\";\n const fail = (problem: string): never => {\n throw new RangeError(`iconFromSvg: ${label} ${problem}.`);\n };\n\n let box: Rect | undefined;\n let scale = 1;\n const shapes: IconShape[] = [];\n // One entry per open element; undefined while inside something dropped.\n const stack: { readonly tag: string; readonly state: Inherited | undefined }[] = [];\n let root: Inherited | undefined;\n\n for (const match of withoutComments(markup).matchAll(TAG)) {\n const [, closing, rawTag, rawAttributes = \"\", selfClosing] = match;\n if (rawTag === undefined) continue; // a doctype\n const tag = rawTag.toLowerCase();\n if (closing) {\n const index = findLast(stack, tag);\n if (index >= 0) stack.length = index;\n continue;\n }\n const attributes = readAttributes(rawAttributes);\n const first = !box && tag === \"svg\";\n if (first) {\n box = viewBox(attributes) ?? fail(\"needs a viewBox, or a width and height in px, on its <svg>\");\n if (spec.size !== undefined) {\n if (typeof spec.size !== \"number\" || !(spec.size > 0) || !Number.isFinite(spec.size)) fail(`size must be more than 0, got ${String(spec.size)}`);\n scale = spec.size / box.width;\n }\n root = { fill: \"#000000\", stroke: \"none\", width: 1, linecap: undefined, linejoin: undefined, fillRule: \"nonzero\", opacity: 1, transform: matrix.scale(scale) };\n }\n // Only what's inside the first <svg> is drawn.\n const parent = stack.length > 0 ? stack[stack.length - 1]!.state : first ? root : undefined;\n const state = parent && !hidden(attributes) ? inherit(parent, attributes) : undefined;\n if (state && SHAPES.has(tag)) {\n const shape = toShape(tag, attributes, state);\n if (shape) shapes.push(shape);\n }\n if (!selfClosing) stack.push({ tag, state: CONTAINERS.has(tag) ? state : undefined });\n }\n\n if (!box) fail(\"needs an <svg> element\");\n if (shapes.length === 0) fail(\"has nothing to draw: no path, circle, rect, ellipse, line, polyline or polygon with a fill or stroke\");\n const sized: Rect = { x: box!.x * scale, y: box!.y * scale, width: box!.width * scale, height: box!.height * scale };\n const at = (point: Point): Point => (point && typeof point === \"object\" ? { x: point.x * scale, y: point.y * scale } : point);\n return defineIcon({\n ...spec,\n shapes,\n box: sized,\n anchor: at(spec.anchor),\n ...(spec.pivot ? { pivot: at(spec.pivot) } : {}),\n ...(Array.isArray(spec.footprint) ? { footprint: [spec.footprint[0] * scale, spec.footprint[1] * scale] as const } : {}),\n ...(typeof spec.radius === \"number\" ? { radius: spec.radius * scale } : {})\n });\n}\n\n/** Removes comments, CDATA sections and processing instructions in one pass; an unclosed one runs to the end. */\nfunction withoutComments(markup: string): string {\n const pairs: readonly (readonly [open: string, close: string])[] = [[\"<!--\", \"-->\"], [\"<![CDATA[\", \"]]>\"], [\"<?\", \"?>\"]];\n // Where each kind next opens; found again only once the reading has passed it, so this stays linear.\n const opens = pairs.map(([open]) => markup.indexOf(open));\n let out = \"\";\n let i = 0;\n for (;;) {\n let kind = -1;\n opens.forEach((at, k) => {\n if (at >= 0 && (kind < 0 || at < opens[kind]!)) kind = k;\n });\n if (kind < 0) return out + markup.slice(i);\n const at = opens[kind]!;\n const close = pairs[kind]![1];\n out += markup.slice(i, at);\n const end = markup.indexOf(close, at + pairs[kind]![0].length);\n if (end < 0) return out;\n i = end + close.length;\n opens.forEach((open, k) => {\n if (open >= 0 && open < i) opens[k] = markup.indexOf(pairs[k]![0], i);\n });\n }\n}\n\nfunction readAttributes(source: string): Map<string, string> {\n const attributes = new Map<string, string>();\n for (const [, name, double, single, bare] of source.matchAll(ATTRIBUTE)) {\n if (name !== undefined) attributes.set(name, double ?? single ?? bare ?? \"\");\n }\n // Declarations in `style` win over attributes, as in CSS.\n for (const declaration of (attributes.get(\"style\") ?? \"\").split(\";\")) {\n const colon = declaration.indexOf(\":\");\n if (colon > 0) attributes.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).replace(/!important/i, \"\").trim());\n }\n return attributes;\n}\n\nfunction viewBox(attributes: Map<string, string>): Rect | undefined {\n const values = (attributes.get(\"viewBox\") ?? \"\").trim().split(/[\\s,]+/).map(Number);\n if (values.length === 4 && values.every(Number.isFinite) && values[2]! > 0 && values[3]! > 0) {\n return { x: values[0]!, y: values[1]!, width: values[2]!, height: values[3]! };\n }\n const width = pixels(attributes.get(\"width\"));\n const height = pixels(attributes.get(\"height\"));\n return width !== undefined && height !== undefined ? { x: 0, y: 0, width, height } : undefined;\n}\n\nfunction pixels(value: string | undefined): number | undefined {\n const match = /^\\s*(\\d*\\.?\\d+(?:e[+-]?\\d+)?)\\s*(px)?\\s*$/i.exec(value ?? \"\");\n const number = match ? Number(match[1]) : NaN;\n return number > 0 && Number.isFinite(number) ? number : undefined;\n}\n\n/** An opacity as a number or a percentage, one past 0 or 1 counting as 0 or 1, as in CSS. Anything else counts as 1. */\nfunction alpha(value: string | undefined): number {\n const match = /^\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)(%?)\\s*$/i.exec(value ?? \"\");\n return match ? Math.min(1, Math.max(0, Number(match[1]) / (match[2] ? 100 : 1))) : 1;\n}\n\nfunction hidden(attributes: Map<string, string>): boolean {\n return attributes.get(\"display\")?.trim() === \"none\" || attributes.get(\"visibility\")?.trim() === \"hidden\";\n}\n\nfunction inherit(parent: Inherited, attributes: Map<string, string>): Inherited {\n const paint = (name: string, current: string): string => {\n const value = attributes.get(name)?.trim();\n if (value === undefined || !COLOR.test(value)) return current;\n // Keywords are any case. currentColor would follow the page's `color`; the text token follows the chart's theme.\n const keyword = value.toLowerCase();\n return keyword === \"inherit\" ? current : keyword === \"currentcolor\" ? \"text\" : keyword === \"none\" ? keyword : value;\n };\n const width = Number.parseFloat(attributes.get(\"stroke-width\") ?? \"\");\n const linecap = attributes.get(\"stroke-linecap\")?.trim();\n const linejoin = attributes.get(\"stroke-linejoin\")?.trim();\n const fillRule = attributes.get(\"fill-rule\")?.trim().toLowerCase();\n const transform = attributes.get(\"transform\");\n return {\n fill: paint(\"fill\", parent.fill),\n stroke: paint(\"stroke\", parent.stroke),\n width: width >= 0 ? width : parent.width,\n linecap: linecap === \"butt\" || linecap === \"round\" ? linecap : parent.linecap,\n linejoin: linejoin === \"miter\" || linejoin === \"round\" ? linejoin : parent.linejoin,\n fillRule: fillRule === \"nonzero\" || fillRule === \"evenodd\" ? fillRule : parent.fillRule,\n // Opacity isn't inherited in SVG: a group is drawn and then faded. Multiplying is the same unless its shapes overlap.\n opacity: parent.opacity * alpha(attributes.get(\"opacity\")),\n transform: transform ? matrix.multiply(parent.transform, parseTransform(transform)) : parent.transform\n };\n}\n\nfunction toShape(tag: string, attributes: Map<string, string>, state: Inherited): IconShape | undefined {\n const fill = state.fill === \"none\" ? undefined : state.fill;\n const stroke = state.stroke === \"none\" || !(state.width > 0) ? undefined : state.stroke;\n const opacity = round(state.opacity);\n if ((fill === undefined && stroke === undefined) || !(opacity > 0)) return undefined;\n const commands = outline(tag, attributes);\n if (!commands.some((command) => command.op !== \"M\")) return undefined;\n const m = state.transform;\n return {\n d: formatPath(transformPath(commands, m)),\n ...(fill !== undefined ? { fill, ...(state.fillRule === \"evenodd\" ? { fillRule: state.fillRule } : {}) } : {}),\n ...(stroke !== undefined\n ? {\n stroke,\n // A stroke scales with the transform; for an uneven scale this is the average.\n width: round(state.width * Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]))),\n ...(state.linecap ? { linecap: state.linecap } : {}),\n ...(state.linejoin ? { linejoin: state.linejoin } : {})\n }\n : {}),\n ...(opacity < 1 ? { opacity } : {})\n };\n}\n\n/** The element's outline as path commands, in its own coordinates. */\nfunction outline(tag: string, attributes: Map<string, string>): PathCommand[] {\n const num = (name: string): number => {\n const value = Number.parseFloat(attributes.get(name) ?? \"\");\n return Number.isFinite(value) ? value : 0;\n };\n switch (tag) {\n case \"path\":\n return parsePath(attributes.get(\"d\") ?? \"\");\n case \"circle\":\n return ellipse(num(\"cx\"), num(\"cy\"), num(\"r\"), num(\"r\"));\n case \"ellipse\":\n return ellipse(num(\"cx\"), num(\"cy\"), num(\"rx\"), num(\"ry\"));\n case \"line\":\n return [\n { op: \"M\", to: { x: num(\"x1\"), y: num(\"y1\") } },\n { op: \"L\", to: { x: num(\"x2\"), y: num(\"y2\") } }\n ];\n case \"polyline\":\n case \"polygon\": {\n const values = (attributes.get(\"points\") ?? \"\").trim().split(/[\\s,]+/).filter(Boolean).map(Number);\n const points: Point[] = [];\n for (let i = 0; i + 1 < values.length && Number.isFinite(values[i]) && Number.isFinite(values[i + 1]); i += 2) {\n points.push({ x: values[i]!, y: values[i + 1]! });\n }\n if (points.length < 2) return [];\n const lines = points.map((to, i): PathCommand => ({ op: i === 0 ? \"M\" : \"L\", to }));\n // A polyline is a polygon left open: no closing segment, and filled as any open path is.\n return tag === \"polygon\" ? [...lines, { op: \"Z\", to: points[0]! }] : lines;\n }\n case \"rect\":\n return rect(num(\"x\"), num(\"y\"), num(\"width\"), num(\"height\"), attributes);\n default:\n return [];\n }\n}\n\nfunction ellipse(cx: number, cy: number, rx: number, ry: number): PathCommand[] {\n if (!(rx > 0 && ry > 0)) return [];\n const arc = (x: number): PathCommand => ({ op: \"A\", rx, ry, rotation: 0, large: false, sweep: true, to: { x, y: cy } });\n return [{ op: \"M\", to: { x: cx + rx, y: cy } }, arc(cx - rx), arc(cx + rx), { op: \"Z\", to: { x: cx + rx, y: cy } }];\n}\n\nfunction rect(x: number, y: number, w: number, h: number, attributes: Map<string, string>): PathCommand[] {\n if (!(w > 0 && h > 0)) return [];\n const corner = (name: string): number | undefined => {\n const value = Number.parseFloat(attributes.get(name) ?? \"\");\n return value >= 0 ? value : undefined;\n };\n // A missing rx or ry takes the other's value, and both are capped at half the side.\n const rx = Math.min(corner(\"rx\") ?? corner(\"ry\") ?? 0, w / 2);\n const ry = Math.min(corner(\"ry\") ?? corner(\"rx\") ?? 0, h / 2);\n const line = (px: number, py: number): PathCommand => ({ op: \"L\", to: { x: px, y: py } });\n if (!(rx > 0 && ry > 0)) return [{ op: \"M\", to: { x, y } }, line(x + w, y), line(x + w, y + h), line(x, y + h), { op: \"Z\", to: { x, y } }];\n const arc = (px: number, py: number): PathCommand => ({ op: \"A\", rx, ry, rotation: 0, large: false, sweep: true, to: { x: px, y: py } });\n return [\n { op: \"M\", to: { x: x + rx, y } },\n line(x + w - rx, y),\n arc(x + w, y + ry),\n line(x + w, y + h - ry),\n arc(x + w - rx, y + h),\n line(x + rx, y + h),\n arc(x, y + h - ry),\n line(x, y + ry),\n arc(x + rx, y),\n { op: \"Z\", to: { x: x + rx, y } }\n ];\n}\n\nfunction findLast(stack: readonly { readonly tag: string }[], tag: string): number {\n for (let i = stack.length - 1; i >= 0; i--) if (stack[i]!.tag === tag) return i;\n return -1;\n}\n\nconst round = (value: number): number => Math.round(value * 1000) / 1000;\n","// The neutral icons that ship with the core. They're drawn in theme colours, so they read in light\n// and dark themes and on any series colour. Domain icons live in optional packs (./sport).\n\nimport type { Icon } from \"../core\";\nimport { defineIcon } from \"./define\";\n\n/** A plain marker, outlined so it shows on any bar. */\nconst dot = /* @__PURE__ */ defineIcon({\n name: \"dot\",\n shapes: [{ d: \"M4,0A4,4 0 0 1 -4,0A4,4 0 0 1 4,0Z\", fill: \"surface\", stroke: \"text\", width: 1.5 }],\n box: { x: -5, y: -5, width: 10, height: 10 },\n anchor: { x: 0, y: 0 }\n});\n\n/** Points the way it travels, with a halo in the surface colour. */\nconst arrow = /* @__PURE__ */ defineIcon({\n name: \"arrow\",\n shapes: [{ d: \"M-7,-1.5L1,-1.5L1,-5L7,0L1,5L1,1.5L-7,1.5Z\", fill: \"text\", stroke: \"surface\", width: 1.5, linejoin: \"round\" }],\n box: { x: -8, y: -6, width: 16, height: 12 },\n anchor: { x: 0, y: 0 }\n});\n\n/** A light-weight pointer: a stroked \">\" over a wider halo. */\nconst chevron = /* @__PURE__ */ defineIcon({\n name: \"chevron\",\n shapes: [\n { d: \"M-2.5,-5L2.5,0L-2.5,5\", stroke: \"surface\", width: 4.5, linecap: \"round\", linejoin: \"round\" },\n { d: \"M-2.5,-5L2.5,0L-2.5,5\", stroke: \"text\", width: 2, linecap: \"round\", linejoin: \"round\" }\n ],\n box: { x: -5, y: -7.5, width: 10, height: 15 },\n anchor: { x: 0, y: 0 }\n});\n\n/** The built-in icons, registered by name in every chart: `travel(\"arrow\")` or `travel(icons.arrow)`. */\nexport const icons: { readonly dot: Icon; readonly arrow: Icon; readonly chevron: Icon } = /* @__PURE__ */ Object.freeze({ dot, arrow, chevron });\n","// The page-wide registries. The composition root (src/index.ts) hands them to every chart and\n// adapter, which resolve preset and icon names through them. The neutral core icons are registered\n// here; the sport pack is opt-in, with registerIcons(sport). The built-in presets are exactly flash,\n// wiggle and pulse: none combines effects, draws an icon or staggers.\n\nimport type { Icon, MarkEffect } from \"./core\";\nimport { createRegistry, type PresetFactory } from \"./core/registry\";\nimport { flash, pulse, wiggle } from \"./effects\";\nimport { icons } from \"./icons\";\n\nexport const presetRegistry = /* @__PURE__ */ createRegistry<PresetFactory>({\n kind: \"preset\",\n entries: { flash: () => flash(), wiggle: () => wiggle(), pulse: () => pulse() },\n hint: \"Register custom presets with registerPreset(name, factory).\"\n});\n\nexport const iconRegistry = /* @__PURE__ */ createRegistry<Icon>({\n kind: \"icon\",\n entries: icons,\n hint: \"Register icons with registerIcon(icon) or registerIcons(icons).\"\n});\n\n/** Makes `name` usable in any chart's `on` slots, e.g. `on: { hover: \"nudge\" }`. A later registration replaces an earlier one. */\nexport function registerPreset(name: string, factory: () => MarkEffect): void {\n if (typeof factory !== \"function\") throw new TypeError(`registerPreset(\"${name}\") needs a function that returns an effect.`);\n presetRegistry.register(name, factory);\n}\n\n/** Makes an icon usable by name, e.g. `travel(\"cleat\")`. A later icon with the same name replaces an earlier one. */\nexport function registerIcon(icon: Icon): void {\n if (typeof icon !== \"object\" || icon === null || typeof icon.name !== \"string\") {\n throw new TypeError(\"registerIcon needs an icon with a name.\");\n }\n iconRegistry.register(icon.name, icon);\n}\n\nexport function registerIcons(icons: readonly Icon[]): void {\n for (const icon of icons) registerIcon(icon);\n}\n","// Page-wide settings. For now they say how the stylesheet reaches the page. The stylesheet is one\n// <style> per document, injected by whatever is created first (a chart, an adapter, a control), so\n// these can't be chart options: a nonce passed to one chart would only count if that chart came\n// first, and one chart's injectStyles: false couldn't stop the next one injecting. A CSP nonce is per\n// page response anyway, so it's set once.\n\nimport { styleOptions, type StyleOptions } from \"./charts\";\n\n/**\n * Sets how charts, adapters and controls get their stylesheet, page-wide. Call it before creating\n * any: the stylesheet is injected once, by the first one. Options left out keep their current value.\n *\n * - `nonce`: set on the injected `<style>`, for a Content-Security-Policy with a `style-src` nonce.\n * - `injectStyles: false`: inject nothing; the page loads `expressive-charts/style.css` itself, which\n * has the same rules. For a CSP that allows no inline styles at all.\n */\nexport function configure(options: StyleOptions): void {\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"configure needs an options object.\");\n if (\"nonce\" in options) {\n if (options.nonce !== undefined && (typeof options.nonce !== \"string\" || options.nonce === \"\")) {\n throw new TypeError(\"configure: nonce must be a non-empty string.\");\n }\n styleOptions.nonce = options.nonce;\n }\n if (\"injectStyles\" in options) {\n if (options.injectStyles !== undefined && typeof options.injectStyles !== \"boolean\") {\n throw new TypeError(\"configure: injectStyles must be true or false.\");\n }\n styleOptions.injectStyles = options.injectStyles;\n }\n}\n","// Public entry point and composition root: the only file that brings charts and effects together.\n// Exports are added here as each layer is built. See docs/architecture.md for the design.\n\nimport { motion as pageMotion, type Motion, type TransitionEffect } from \"./core\";\nimport {\n barChart as drawBarChart,\n chartSwitch as buildChartSwitch,\n donutChart as drawDonutChart,\n expressive as attach,\n fromVegaView as attachVega,\n lineChart as drawLineChart,\n type Attachment,\n type BarChart,\n type BarChartOptions,\n type ChartEnv,\n type ChartSwitch,\n type ChartSwitchOptions,\n type ChartSwitchViews,\n type DonutChart,\n type DonutChartOptions,\n type ExpressiveOptions,\n type LineChart,\n type LineChartOptions,\n type MarkSource,\n type VegaAttachment,\n type VegaOptions,\n type VegaViewLike\n} from \"./charts\";\nimport { motionSwitch as buildMotionSwitch, type MotionSwitch, type MotionSwitchOptions } from \"./charts/controls\";\nimport { morph } from \"./effects\";\nimport { iconRegistry, presetRegistry } from \"./registries\";\n\nexport const VERSION = \"0.3.0\";\n\nexport * from \"./core\";\nexport * from \"./effects\";\nexport * from \"./icons\";\nexport { registerIcon, registerIcons, registerPreset } from \"./registries\";\nexport { configure } from \"./settings\";\nexport { colorAssignment, link } from \"./charts\";\nexport type {\n Accessor,\n Attachment,\n BarChart,\n BarChartOptions,\n Chart,\n ChartChange,\n ChartLabel,\n ChartOptions,\n ChartSwitch,\n ChartSwitchOptions,\n ChartSwitchView,\n ChartSwitchViewFactory,\n ChartSwitchViewName,\n ChartSwitchViews,\n ColorAssignment,\n DonutChart,\n DonutChartOptions,\n ExpressiveOptions,\n HostMark,\n KeyOfType,\n LegendEntry,\n LegendOptions,\n LineChart,\n Link,\n LinkOptions,\n LinkSource,\n LineChartOptions,\n MarkEvent,\n MarkEvents,\n MarkSource,\n MarkSummary,\n NumericKey,\n SliceSummary,\n StyleOptions,\n TableColumn,\n TableOptions,\n VegaAttachment,\n VegaItem,\n VegaMark,\n VegaOptions,\n VegaSample,\n VegaViewLike\n} from \"./charts\";\nexport { playButton } from \"./charts/controls\";\nexport type { MotionSwitch, MotionSwitchOptions, PlayButton, PlayButtonOptions } from \"./charts/controls\";\n\n/** Charts resolve preset and icon names through the page-wide registries and follow the page-wide motion. */\nconst env: ChartEnv = { presets: presetRegistry, icons: iconRegistry, motion: pageMotion };\n\n/**\n * A bar chart in `target` (an element or a selector). The axis whose values aren't numbers is the\n * category; `stack` stacks numeric fields; `on` attaches effects by slot.\n */\nexport function barChart<D>(target: string | Element, options: BarChartOptions<D>): BarChart<D> {\n return drawBarChart(target, options, env);\n}\n\n/**\n * A donut chart in `target` (an element or a selector). `category` names each slice and `value` sizes\n * it; slices go clockwise from 12 o'clock, in data order or largest first with `sort: \"value\"`; `on`\n * attaches effects by slot.\n */\nexport function donutChart<D>(target: string | Element, options: DonutChartOptions<D>): DonutChart<D> {\n return drawDonutChart(target, options, env);\n}\n\n/**\n * A line chart in `target` (an element or a selector): one row per `x`, a number or a Date, a line\n * per field in `series`, with a point per row and series that shows where its x is hovered or\n * focused. `reveal(x)` shows the data up to x, as `playback()` drives it; `on` attaches effects by slot.\n */\nexport function lineChart<D>(target: string | Element, options: LineChartOptions<D>): LineChart<D> {\n return drawLineChart(target, options, env);\n}\n\n/**\n * Views of the same data in `target` (an element or a selector), one shown at a time: `show(view)`\n * turns each mark into the mark with its key in the other view with `transition`, morph() by default,\n * while the labels move and swap their text. Each view's function draws its chart in the container\n * it's given; pass it the `colors` it's given too, so a key keeps its colour from view to view.\n */\nexport function chartSwitch<T extends ChartSwitchViews>(target: string | Element, options: ChartSwitchOptions<T>): ChartSwitch<T> {\n // Charts never import effects: the default transition is filled in here.\n const filled = typeof options === \"object\" && options !== null && options.transition === undefined ? { ...options, transition: morph() } : options;\n return buildChartSwitch(target, filled as ChartSwitchOptions<T> & { readonly transition: TransitionEffect }, env);\n}\n\n/**\n * Adds effects to SVG marks drawn by other code: a selector, elements, or a D3 selection (whose data\n * types the callbacks). `key` is required; `on` attaches effects by slot, as on the charts. Call\n * `refresh()` after the host re-renders.\n */\nexport function expressive<D = unknown>(target: MarkSource<D>, options: ExpressiveOptions<D>): Attachment<D> {\n return attach(target, options, env);\n}\n\n/**\n * Adds effects to a Vega or Vega-Lite chart rendered as SVG (vega-embed's default): the View's mark\n * named `mark` (\"marks\", Vega-Lite's data mark, by default), read from its scenegraph. Rects are bars,\n * arcs slices, symbols points and lines lines; `sample` gives data effects their values. It follows\n * the View's own renders, so there's no refresh() to call. `key` is required, as for expressive().\n */\nexport function fromVegaView<D = Record<string, unknown>>(view: VegaViewLike, options: VegaOptions<D>): VegaAttachment<D> {\n return attachVega(view, options, env);\n}\n\n/**\n * The viewer's motion control in `target` (an element or a selector): Presentation, Analysis and Off\n * as buttons with `aria-pressed`, and a note on what the mode does. A click is the viewer's own\n * choice (`motion.chooseMode()`), so it overrides the device's reduced-motion setting. Default: the\n * page-wide `motion`. `persist: \"key\"` saves the choice in localStorage.\n */\nexport function motionSwitch(target: string | Element, motion: Motion = pageMotion,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QAAQ,UAAU,KAAK;AAC9F,YAAM,IAAI,UAAU,8CAA8C;AAAA,IACpE;AACA,iBAAa,QAAQ,QAAQ;AAAA,EAC/B;AACA,MAAI,kBAAkB,SAAS;AAC7B,QAAI,QAAQ,iBAAiB,UAAa,OAAO,QAAQ,iBAAiB,WAAW;AACnF,YAAM,IAAI,UAAU,gDAAgD;AAAA,IACtE;AACA,iBAAa,eAAe,QAAQ;AAAA,EACtC;AACF;;;ACEO,IAAM,UAAU;AAwDvB,IAAM,MAAgB,EAAE,SAAS,gBAAgB,OAAO,cAAc,OAAmB;AAMlF,SAASC,UAAY,QAA0B,SAA0C;AAC9F,SAAO,SAAa,QAAQ,SAAS,GAAG;AAC1C;AAOO,SAASC,YAAc,QAA0B,SAA8C;AACpG,SAAO,WAAe,QAAQ,SAAS,GAAG;AAC5C;AAOO,SAASC,WAAa,QAA0B,SAA4C;AACjG,SAAO,UAAc,QAAQ,SAAS,GAAG;AAC3C;AAQO,SAASC,aAAwC,QAA0B,SAAgD;AAEhI,QAAM,SAAS,OAAO,YAAY,YAAY,YAAY,QAAQ,QAAQ,eAAe,SAAY,EAAE,GAAG,SAAS,YAAY,MAAM,EAAE,IAAI;AAC3I,SAAO,YAAiB,QAAQ,QAA6E,GAAG;AAClH;AAOO,SAASC,YAAwB,QAAuB,SAA8C;AAC3G,SAAO,WAAO,QAAQ,SAAS,GAAG;AACpC;AAQO,SAASC,cAA0C,MAAoB,SAA4C;AACxH,SAAO,aAAW,MAAM,SAAS,GAAG;AACtC;AAQO,SAASC,cAAa,QAA0BC,UAAiB,QAAY,SAA6C;AAC/H,SAAO,aAAkB,QAAQA,SAAQ,OAAO;AAClD;","names":["parts","text","linear","text","rows","placed","label","total","text","drawn","geometry","step","span","distance","label","drawn","text","number","outline","stroke","parts","parts","visible","placed","hidden","label","text","leave","leave","own","step","linked","leave","link","leave","hidden","total","summary","text","format","number","sum","own","rows","caption","drawn","numeric","format","markLabel","leaves","leave","motion","GAP","format","summary","placed","own","text","round","edge","parts","RING_GAP","RING","env","motion","drawn","show","text","said","total","placed","positions","rows","leaves","PAD","GAP","LABEL_SIZE","VALUE_SIZE","ASCENT","CENTRE","accessor","rows","total","placeLabels","centerText","label","overlaps","text","numberOf","widest","STAGE","TAU","env","checkOptions","motion","runs","total","label","outline","hidden","text","show","said","drawn","span","placeLabels","target","positions","leaves","markLabel","own","span","step","between","parts","format","own","HEIGHT","TOP","AXIS","TICK_SIZE","VALUE_SIZE","CENTRE","accessor","rows","prepareRows","text","widest","own","placed","label","distance","last","span","step","numberOf","STAGE","RING_GAP","RING","VISIBLE","env","motion","rows","namesFor","text","own","label","placed","drawn","show","hidden","said","target","kind","positions","leaves","labelled","parts","span","round","spread","text","list","found","rect","round","animated","parts","mix","SVG_NS","env","checkOptions","motion","part","marks","checkNeeds","first","parts","order","outline","total","own","text","linked","runs","valuesChanged","geometryChanged","label","effects","follow","records","link","distance","describeValue","sameAt","env","drawn","parts","total","interpolate","spread","env","checkOptions","motion","view","inside","label","text","heading","mix","isIdentity","outline","MODES","motion","resolveTarget","checkOptions","label","render","text","LABELS","playback","resolveTarget","checkOptions","render","text","LONGEST","checkOptions","drawn","span","distance","turn","reach","DURATION","checkOptions","show","stroke","s","DURATION","checkOptions","show","reach","position","DURATION","WIDTH","OPACITY","checkOptions","show","total","DURATION","WIDTH","OPACITY","MIN_WALK","checkOptions","stroke","show","CENTRE","heading","distance","step","DURATION","checkOptions","format","text","show","DURATION","text","said","show","MIN_WALK","TIE","checkOptions","follow","parts","numeric","inside","clamp","show","DURATION","checkOptions","between","mix","parts","inner","filtered","step","staggered","turn","effect","check","checkNeeds","label","viewBox","kind","at","number","stroke","round","icons","barChart","donutChart","lineChart","chartSwitch","expressive","fromVegaView","motionSwitch","motion"]}
1
+ {"version":3,"file":"index.js","names":["pageMotion","checkOptions","nearest","SVG_NS","linear","ASCENT","GAP","LABEL_SIZE","VALUE_SIZE","TICK_SIZE","AXIS","TOP","PAD","CENTRE","numeric","accessor","prepareRows","placeLabels","overlaps","numberOf","widest","partsOf","MODES","mix","round","resolveTarget","checkNeeds","geometryChanged","GAP","inside","viewBox","STAGE","barChart","resolveTarget","geometryChanged","labelled","round","valuesChanged","markLabel","checkOptions","TAU","HEIGHT","VALUE_SIZE","CENTRE","accessor","numberOf","STAGE","VISIBLE","donutChart","resolveTarget","namesFor","geometryChanged","round","checkOptions","LONGEST","CENTRE","show","lineChart","resolveTarget","round","geometryChanged","distance","round","between","scaleOf","round","mix","SVG_NS","pixels","SHAPES","expressive","round","scaleOf","between","isIdentity","checkOptions","fromVegaView","expressive","between","DURATION","chartSwitch","resolveTarget","checkOptions","between","clamp","mix","LABELS","motionSwitch","resolveTarget","checkOptions","checkOptions","MIN_WALK","checkOptions","DURATION","WIDTH","OPACITY","checkOptions","DURATION","checkOptions","DURATION","WIDTH","OPACITY","checkOptions","DURATION","MIN_WALK","checkOptions","DURATION","TIE","checkOptions","DURATION","checkOptions","check","describeValue","pageMotion","drawBarChart","drawDonutChart","drawLineChart","buildChartSwitch","attach","attachVega","buildMotionSwitch","motion"],"sources":["../src/core/animated.ts","../src/core/playback.ts","../src/core/geometry/matrix.ts","../src/core/geometry/samples.ts","../src/charts/announce.ts","../src/charts/render/svg.ts","../src/charts/render/text.ts","../src/charts/bar-layout.ts","../src/charts/render/theme.ts","../src/charts/colors.ts","../src/charts/legend.ts","../src/charts/link.ts","../src/charts/motion.ts","../src/charts/render/outside.ts","../src/charts/render/mark-style.ts","../src/charts/render/layer.ts","../src/charts/render/surface.ts","../src/charts/series.ts","../src/charts/shell/events.ts","../src/charts/shell/format.ts","../src/charts/interaction.ts","../src/charts/keyboard.ts","../src/charts/shell/hover.ts","../src/charts/shell/labels.ts","../src/charts/shell/leaving.ts","../src/charts/shell/order.ts","../src/charts/table.ts","../src/charts/shell/setup.ts","../src/charts/shell/transitions.ts","../src/charts/shell/watch.ts","../src/charts/tooltip.ts","../src/charts/bar.ts","../src/charts/donut-layout.ts","../src/charts/donut.ts","../src/charts/time.ts","../src/charts/line-layout.ts","../src/charts/line.ts","../src/core/geometry/ring.ts","../src/charts/adapter/bars.ts","../src/charts/adapter/edits.ts","../src/charts/adapter/space.ts","../src/charts/adapter/host-style.ts","../src/charts/adapter/source.ts","../src/charts/adapter/watch.ts","../src/charts/adapter/expressive.ts","../src/charts/adapter/vega.ts","../src/charts/switch.ts","../src/charts/controls/motion-switch.ts","../src/charts/controls/play-button.ts","../src/effects/gaits.ts","../src/effects/travel.ts","../src/effects/flash.ts","../src/effects/wiggle.ts","../src/effects/pulse.ts","../src/effects/trace.ts","../src/effects/caption.ts","../src/effects/delta.ts","../src/effects/label.ts","../src/effects/threshold.ts","../src/effects/morph.ts","../src/effects/combinators.ts","../src/effects/define.ts","../src/icons/svg.ts","../src/icons/core.ts","../src/registries.ts","../src/settings.ts","../src/index.ts"],"sourcesContent":["import type { Point } from \"./contracts/geometry\";\nimport { easeInOutCubic, easeOutCubic, type Easing } from \"./easing\";\nimport type { Timing } from \"./motion\";\nimport { tween, type MotionEnv, type Tween, type TweenResult } from \"./tween\";\n\n/** Builds a function that blends `from` into `to` as t goes from 0 to 1. */\nexport type Interpolator<T> = (from: T, to: T) => (t: number) => T;\n\n/** Exact at both ends, so a finished animation lands on its target. */\nexport const interpolateNumber: Interpolator<number> = (a, b) => (t) => a * (1 - t) + b * t;\n\nexport const interpolatePoint: Interpolator<Point> = (a, b) => (t) => ({\n x: a.x * (1 - t) + b.x * t,\n y: a.y * (1 - t) + b.y * t\n});\n\n/**\n * Blends every key. A key missing on one side counts as 0 there, so a series\n * that appears grows from 0, and one that disappears shrinks to 0 and is gone at t = 1.\n */\nexport function interpolateRecord<K extends string>(\n a: Readonly<Record<K, number>>,\n b: Readonly<Record<K, number>>\n): (t: number) => Record<K, number> {\n const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])] as K[];\n return (t) => {\n if (t === 1) return { ...b };\n const out = {} as Record<K, number>;\n for (const key of keys) out[key] = (a[key] ?? 0) * (1 - t) + (b[key] ?? 0) * t;\n return out;\n };\n}\n\nexport interface AnimateOptions {\n /** Base duration in ms, scaled by the motion mode. */\n readonly duration: number;\n /** Default \"transition\". */\n readonly timing?: Timing;\n /** Default easeInOutCubic, or easeOutCubic when this interrupts a moving value and starts at once (no delay). */\n readonly ease?: Easing;\n readonly delay?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface AnimatedOptions<T> extends Partial<MotionEnv> {\n /** Called whenever the value changes, including every animation frame. */\n readonly onChange?: (value: T) => void;\n}\n\n/** A value that can be retargeted mid-flight. */\nexport interface Animated<T> {\n /** The current value, in between while animating. */\n readonly value: T;\n /** Where the value is heading (equal to `value` when at rest). */\n readonly target: T;\n readonly animating: boolean;\n /** Animate from the current value, cancelling any animation already running. */\n to(target: T, options: AnimateOptions): Promise<TweenResult>;\n /** Jump to a value, cancelling any running animation. */\n set(value: T): void;\n /** Stop where it is; the current value becomes the target. */\n stop(): void;\n}\n\nexport function animated<T>(initial: T, interpolate: Interpolator<T>, options: AnimatedOptions<T> = {}): Animated<T> {\n const { onChange, ...env } = options;\n let value = initial;\n let target = initial;\n let running: Tween | undefined;\n /** The running animation is past its delay: its value is on the move. */\n let moving = false;\n\n const assign = (next: T): void => {\n value = next;\n onChange?.(next);\n };\n\n const halt = (): void => {\n const current = running;\n running = undefined;\n moving = false;\n current?.cancel();\n };\n\n return {\n get value() {\n return value;\n },\n get target() {\n // Cancelled from outside (its signal aborted, or onChange threw): it's at rest where it stopped.\n return running?.state === \"cancelled\" ? value : target;\n },\n get animating() {\n return running?.state === \"running\";\n },\n to(next, animate) {\n // Restarting an ease-in-out from a moving value would stall; ease out instead. A value still\n // waiting out a delay isn't moving, and one told to wait first starts from rest anyway.\n const interrupted = running?.state === \"running\" && moving && !(animate.delay && animate.delay > 0);\n halt();\n target = next;\n const blend = interpolate(value, next);\n // The tween's first update is its start value; any later one means it's past its delay.\n let started = false;\n const current = tween(\n {\n duration: animate.duration,\n timing: animate.timing,\n ease: animate.ease ?? (interrupted ? easeOutCubic : easeInOutCubic),\n delay: animate.delay,\n signal: animate.signal,\n update: (progress) => {\n if (started) moving = true;\n started = true;\n assign(blend(progress));\n }\n },\n env\n );\n // Kept even if already settled, so `target` can tell an outside cancellation from a finish.\n running = current;\n return current.finished;\n },\n set(next) {\n halt();\n target = next;\n assign(next);\n },\n stop() {\n halt();\n target = value;\n }\n };\n}\n","// playback: a clock-driven controller for anything that plays through a range of values, such as a season\n// revealed week by week. It owns a position and moves it; the page draws each position in onFrame. It has\n// no DOM: playButton() (src/charts/controls) and the page's own scrubber drive it.\n\nimport { defaultClock } from \"./clock\";\nimport { easeInOutCubic, easeOutCubic, linear, type Easing } from \"./easing\";\nimport { motion as pageMotion, TIMINGS, type Timing } from \"./motion\";\nimport { report } from \"./report\";\nimport type { MotionEnv } from \"./tween\";\n\nexport interface PlaybackOptions extends Partial<MotionEnv> {\n /** Where a play starts again once it's at the end. */\n readonly from: number;\n /** Where a play ends. The playback starts here, at rest, as a chart shows all its data until something reveals less. */\n readonly to: number;\n /** Base ms for a play from `from` to `to`, scaled by `timing`. A play from part way takes its share, so the speed stays the same. */\n readonly duration: number;\n /** How a play moves. Default linear: constant speed. Seeks ease on their own. */\n readonly ease?: Easing;\n /** Default \"playback\": ×1 in Presentation, ×0.3 in Analysis, a jump in Off. */\n readonly timing?: Timing;\n /** Draws a position. Called whenever the position changes: every frame of a play or a seek, and every jump. */\n readonly onFrame: (position: number) => void;\n}\n\n/** What `subscribe` hears. Frames go to `onFrame` instead. */\nexport type PlaybackEvent = \"play\" | \"pause\" | \"end\" | \"seek\";\n\nexport interface SeekOptions {\n /** Default true: move over 350 ms base transition timing (at most 200 ms in Analysis, a jump in Off). false jumps. */\n readonly animate?: boolean;\n}\n\nexport interface Playback {\n /** Plays on from where it is to `to`, or from `from` when it's at the end. Does nothing while playing. */\n play(): void;\n /** Stops a play where it is. Does nothing unless it's playing, so a seek on its way still lands. */\n pause(): void;\n /** Pauses, and moves to `x`, clamped to the range. A seek while it's moving starts from where it is. */\n seek(x: number, options?: SeekOptions): void;\n /** Where it is now, in between while it moves. */\n readonly position: number;\n /** True from `play()` until a pause, a seek or the end. */\n readonly playing: boolean;\n /** Hears play, pause, the end and seeks, not every frame. Returns a function that stops listening. */\n subscribe(listener: (event: PlaybackEvent) => void): () => void;\n /** Pauses it, if it's playing, and stops it for good: later calls do nothing. */\n destroy(): void;\n}\n\n/** The lab's scrubber: a seek takes 350 ms base, with \"transition\" timing. */\nconst SEEK_MS = 350;\n\n/** A move under way: a play or a seek. `moved` once a frame has moved it, so a retarget eases out. */\ninterface Move {\n moved: boolean;\n readonly stop: () => void;\n}\n\n/**\n * A playback through `from`…`to`. `play()` moves the position at constant speed (with the default\n * `linear`), over `duration` scaled by the motion mode, and `onFrame` draws each position. With motion\n * off, a play jumps to the end, and motion turning off mid-play jumps there too, as tweens do. Nothing\n * plays by itself. Uses the page-wide motion and clock unless given its own.\n */\nexport function playback(options: PlaybackOptions): Playback {\n checkOptions(options);\n const { from, to, duration, onFrame } = options;\n const ease = options.ease ?? linear;\n const timing = options.timing ?? \"playback\";\n const clock = options.clock ?? defaultClock;\n const view = options.motion ?? pageMotion;\n const low = Math.min(from, to);\n const high = Math.max(from, to);\n\n let position = to;\n let playing = false;\n let destroyed = false;\n let move: Move | undefined;\n // Bumped by every play, pause, seek and destroy. Anything that calls out (to onFrame or a listener)\n // checks it afterwards, so it stops if that call started something else.\n let generation = 0;\n const listeners = new Set<(event: PlaybackEvent) => void>();\n\n const notify = (event: PlaybackEvent): void => {\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue;\n try {\n listener(event);\n } catch (error) {\n report(error);\n }\n }\n };\n\n /** Stops the move under way, where it is. True if it had moved. */\n const halt = (): boolean => {\n const current = move;\n move = undefined;\n current?.stop();\n return current?.moved ?? false;\n };\n\n /** Ends a play that didn't reach the end: halted by a pause, a seek, destroy(), or a failing onFrame or ease. */\n const stopPlaying = (): void => {\n if (!playing) return;\n playing = false;\n notify(\"pause\");\n };\n\n // When the page's onFrame or ease throws, everything stops where it is and the error goes on to the\n // caller (or to the clock, which reports it), so a broken callback is reported once rather than every frame.\n const fail = (error: unknown): never => {\n generation++;\n halt();\n stopPlaying();\n throw error;\n };\n\n /** Draws a new position. */\n const assign = (x: number): void => {\n if (x === position) return;\n position = x;\n try {\n onFrame(x);\n } catch (error) {\n fail(error);\n }\n };\n\n /** Moves to `target` over `ms`, eased, then calls `landed`. 0 ms jumps, before it returns. */\n const glide = (target: number, ms: number, curve: Easing, landed: () => void): void => {\n const mine = generation;\n if (!(ms > 0)) {\n assign(target);\n if (generation === mine) landed();\n return;\n }\n const origin = position;\n const start = clock.now();\n const current: Move = {\n moved: false,\n stop: clock.onFrame((now) => {\n // The effective mode can turn off mid-move (the device switches to reduced motion, or the\n // viewer picks Off). The move then jumps to its end, as tweens do.\n const t = view.mode === \"off\" ? 1 : (now - start) / ms;\n if (t < 1) {\n current.moved = true;\n let progress: number;\n try {\n progress = curve(t);\n } catch (error) {\n return fail(error);\n }\n assign(origin + (target - origin) * progress);\n return;\n }\n halt();\n assign(target);\n if (generation === mine) landed();\n })\n };\n move = current;\n };\n\n const landedAtEnd = (): void => {\n playing = false;\n notify(\"end\");\n };\n\n return {\n get position() {\n return position;\n },\n get playing() {\n return playing;\n },\n play() {\n if (destroyed || playing) return;\n const mine = ++generation;\n halt();\n playing = true;\n notify(\"play\");\n if (generation !== mine) return;\n // Scaled once for the whole range, then shared out, so a play from part way keeps the same speed.\n const whole = view.duration(duration, timing);\n // At the end, a play starts again from `from`. With motion off it just shows the end, which is already there.\n if (whole > 0 && position === to) {\n assign(from);\n if (generation !== mine) return;\n }\n glide(to, (whole * Math.abs(to - position)) / Math.abs(to - from), ease, landedAtEnd);\n },\n pause() {\n if (destroyed || !playing) return;\n generation++;\n halt();\n stopPlaying();\n },\n seek(x, seekOptions = {}) {\n checkSeek(x, seekOptions);\n if (destroyed) return;\n const mine = ++generation;\n const moving = halt();\n stopPlaying();\n if (generation !== mine) return;\n notify(\"seek\");\n if (generation !== mine) return;\n const ms = seekOptions.animate === false ? 0 : view.duration(SEEK_MS, \"transition\");\n // Retargeting a moving position eases out, so the motion doesn't stall; from rest it eases in and\n // out. The same rule as animated values.\n glide(Math.min(Math.max(x, low), high), ms, moving ? easeOutCubic : easeInOutCubic, () => {});\n },\n subscribe(listener) {\n if (typeof listener !== \"function\") throw new TypeError(`playback.subscribe needs a function, got ${typeof listener}.`);\n if (destroyed) return () => {};\n // Wrapped so the same function can be subscribed twice and unsubscribed independently.\n const entry = (event: PlaybackEvent): void => listener(event);\n listeners.add(entry);\n return () => {\n listeners.delete(entry);\n };\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n generation++;\n halt();\n // Heard before the listeners go, so a play button still on the page goes back to Play.\n stopPlaying();\n listeners.clear();\n }\n };\n}\n\nfunction checkOptions(options: PlaybackOptions): void {\n if (typeof options !== \"object\" || options === null) {\n throw new TypeError(\"playback needs options: { from, to, duration, onFrame }.\");\n }\n const { from, to, duration, ease, timing, onFrame, clock, motion } = options;\n for (const [name, value] of [[\"from\", from], [\"to\", to]] as const) {\n if (!isFiniteNumber(value)) throw new RangeError(`playback: ${name} must be a finite number, got ${String(value)}.`);\n }\n if (from === to) throw new RangeError(`playback: from and to must differ, got ${from} for both.`);\n if (!isFiniteNumber(duration) || duration < 0) {\n throw new RangeError(`playback: duration must be a non-negative number of ms, got ${String(duration)}.`);\n }\n if (typeof onFrame !== \"function\") throw new TypeError(`playback: onFrame must be a function, got ${typeof onFrame}.`);\n if (ease !== undefined && typeof ease !== \"function\") throw new TypeError(`playback: ease must be a function, got ${typeof ease}.`);\n if (timing !== undefined && !TIMINGS.includes(timing)) {\n throw new RangeError(`playback: timing must be one of ${TIMINGS.join(\", \")}, got ${JSON.stringify(timing) ?? String(timing)}.`);\n }\n if (clock !== undefined && (typeof clock?.now !== \"function\" || typeof clock.onFrame !== \"function\")) {\n throw new TypeError(\"playback: clock must be a Clock, such as one from createClock() or manualClock().\");\n }\n if (motion !== undefined && typeof motion?.duration !== \"function\") {\n throw new TypeError(\"playback: motion must be a Motion, such as the page-wide `motion` or one from createMotion().\");\n }\n}\n\nfunction checkSeek(x: number, options: SeekOptions): void {\n if (!isFiniteNumber(x)) throw new RangeError(`playback.seek needs a finite number, got ${String(x)}.`);\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"playback.seek's options must be an object, such as { animate: false }.\");\n if (options.animate !== undefined && typeof options.animate !== \"boolean\") {\n throw new TypeError(`playback.seek: animate must be true or false, got ${String(options.animate)}.`);\n }\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n","// Transform helpers for effect authors: matrix and offset are public (docs/effects-guide.md).\n\nimport type { Matrix } from \"../contracts/drawing\";\nimport type { Point } from \"../contracts/geometry\";\n\nfunction translate(x: number, y: number): Matrix {\n return [1, 0, 0, 1, x, y];\n}\n\n/** Positive radians turn clockwise on screen, like SVG's rotate(). */\nfunction rotate(radians: number, about?: Point): Matrix {\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n return around([cos, sin, -sin, cos, 0, 0], about);\n}\n\nfunction scale(sx: number, sy: number = sx, about?: Point): Matrix {\n return around([sx, 0, 0, sy, 0, 0], about);\n}\n\n/** Composes like an SVG transform list: multiply(a, b) applies b first, then a. No arguments gives the identity. */\nfunction multiply(...matrices: Matrix[]): Matrix {\n let result: Matrix = [1, 0, 0, 1, 0, 0];\n for (const m of matrices) result = product(result, m);\n return result;\n}\n\n/** Where the transform takes a point. */\nfunction apply(m: Matrix, point: Point): Point {\n const [a, b, c, d, e, f] = m;\n return { x: a * point.x + c * point.y + e, y: b * point.x + d * point.y + f };\n}\n\nfunction product(l: Matrix, r: Matrix): Matrix {\n const [a1, b1, c1, d1, e1, f1] = l;\n const [a2, b2, c2, d2, e2, f2] = r;\n return [\n a1 * a2 + c1 * b2,\n b1 * a2 + d1 * b2,\n a1 * c2 + c1 * d2,\n b1 * c2 + d1 * d2,\n a1 * e2 + c1 * f2 + e1,\n b1 * e2 + d1 * f2 + f1\n ];\n}\n\n/** A linear transform (no translation) moved so it keeps `about` fixed. */\nfunction around(m: Matrix, about: Point | undefined): Matrix {\n if (!about) return m;\n const [a, b, c, d] = m;\n return [a, b, c, d, about.x - a * about.x - c * about.y, about.y - b * about.x - d * about.y];\n}\n\n/** Builds and applies 2D transforms in SVG order, for `mark.set({ transform })` and `IconHandle.place()`. */\nexport const matrix: {\n translate: typeof translate;\n rotate: typeof rotate;\n scale: typeof scale;\n multiply: typeof multiply;\n apply: typeof apply;\n} = { translate, rotate, scale, multiply, apply };\n\n// Internal: iconFromSvg and the adapter read SVG transforms with these.\n\n/** The inverse transform. A singular matrix (it squashes everything onto a line) throws a RangeError. */\nexport function invert(m: Matrix): Matrix {\n const [a, b, c, d, e, f] = m;\n const det = a * d - b * c;\n if (!Number.isFinite(det) || Math.abs(det) < 1e-12) throw new RangeError(\"This transform can't be inverted: it has no area.\");\n return [d / det, -b / det, -c / det, a / det, (c * f - d * e) / det, (b * e - a * f) / det];\n}\n\n/** An SVG transform list, as in the transform attribute. An unknown or malformed function is skipped. */\nexport function parseTransform(source: string): Matrix {\n const parts: Matrix[] = [];\n for (const [, name, rawArgs = \"\"] of source.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\\s*\\(([^)]*)\\)/g)) {\n const args = rawArgs.trim().split(/[\\s,]+/).filter(Boolean).map(Number);\n if (!args.every(Number.isFinite)) continue;\n const [a = 0, b, c, d = 0, e = 0, f = 0] = args;\n const radians = (degrees: number): number => (degrees * Math.PI) / 180;\n switch (name) {\n case \"matrix\":\n if (args.length === 6) parts.push([a, b!, c!, d, e, f]);\n break;\n case \"translate\":\n parts.push(translate(a, b ?? 0));\n break;\n case \"scale\":\n parts.push(scale(a, b ?? a));\n break;\n case \"rotate\":\n parts.push(rotate(radians(a), b !== undefined && c !== undefined ? { x: b, y: c } : undefined));\n break;\n case \"skewX\":\n parts.push([1, 0, Math.tan(radians(a)), 1, 0, 0]);\n break;\n case \"skewY\":\n parts.push([1, Math.tan(radians(a)), 0, 1, 0, 0]);\n break;\n }\n }\n return multiply(...parts);\n}\n\n/** A point `distance` px from `point` in direction `angle` (screen radians). */\nexport function offset(point: Point, angle: number, distance: number): Point {\n return { x: point.x + distance * Math.cos(angle), y: point.y + distance * Math.sin(angle) };\n}\n","// samplesAlong: data points placed on a mark's walk, as data effects' samples. A page gives a host's\n// line its values this way: the points that drew it, projected onto the walk that describes it.\n// It reads only the MarkGeometry contract (path and length), so it works on any mark.\n\nimport type { Sample } from \"../contracts/data\";\nimport type { MarkGeometry, Point } from \"../contracts/geometry\";\n\n/** A data point in the mark's coordinates, with its value and, optionally, the x value behind it. */\nexport interface SamplePoint {\n readonly x: number;\n readonly y: number;\n readonly value: number;\n readonly at?: string | number | Date;\n}\n\n/** The grid that finds each point's nearest stretch of the walk: a point every px, up to this many. */\nconst MAX_GRID = 4096;\n/**\n * Golden-section steps that narrow a stretch of 2 grid steps down: to about 1e-12 px for a point on\n * the walk, and to well under 1e-6 px for one off it, where the nearest point is a flat minimum.\n */\nconst REFINE = 48;\nconst GOLDEN = (Math.sqrt(5) - 1) / 2;\n\n/**\n * Projects each point onto the nearest point of the mark's walk and returns the samples in `t` order\n * (points at the same `t` keep their order). A point on the walk, such as a vertex of the polyline it\n * drew, lands exactly where it is. Where the mark has gaps, the first sample past each gap's middle\n * has `gapBefore`, so a data effect doesn't join it to the one before. Throws a RangeError on a point\n * whose x, y or value isn't finite.\n */\nexport function samplesAlong(mark: MarkGeometry, points: readonly SamplePoint[]): Sample[] {\n if (typeof mark !== \"object\" || mark === null || typeof mark.path !== \"function\" || !Number.isFinite(mark.length)) {\n throw new TypeError(\"samplesAlong needs a MarkGeometry, as describe builds it.\");\n }\n if (!Array.isArray(points)) throw new TypeError(\"samplesAlong needs an array of points { x, y, value, at? }.\");\n points.forEach((p, i) => {\n for (const field of [\"x\", \"y\", \"value\"] as const) {\n const value: unknown = (p as Partial<SamplePoint> | null)?.[field];\n if (typeof value !== \"number\" || !Number.isFinite(value)) throw new RangeError(`samplesAlong: points[${i}].${field} must be a finite number, got ${String(value)}.`);\n }\n });\n\n const n = mark.length > 0 ? Math.min(MAX_GRID, Math.ceil(mark.length) + 1) : 1;\n const grid = Array.from({ length: n }, (_, i): Point => mark.path(n === 1 ? 0 : i / (n - 1)));\n const samples = points\n .map((p, index) => ({ index, sample: { t: nearest(mark, grid, p), value: p.value, ...(p.at === undefined ? {} : { at: p.at }) } }))\n .sort((a, b) => a.sample.t - b.sample.t || a.index - b.index)\n .map(({ sample }): Sample => sample);\n return mark.gaps && mark.gaps.length > 0 ? gapped(samples, mark.gaps) : samples;\n}\n\n/**\n * The samples with `gapBefore` on each that a gap's middle lies before, past the sample before it. A\n * gap's ends are values, so samples there project to within float noise of them, either side: its\n * middle is far from both.\n */\nfunction gapped(samples: readonly Sample[], gaps: NonNullable<MarkGeometry[\"gaps\"]>): Sample[] {\n const middles = gaps.map(([from, to]) => (from + to) / 2).sort((a, b) => a - b);\n let next = 0;\n return samples.map((sample, k) => {\n if (k === 0) return sample;\n const before = samples[k - 1]!.t;\n while (next < middles.length && middles[next]! <= before) next++;\n return next < middles.length && middles[next]! <= sample.t ? { ...sample, gapBefore: true } : sample;\n });\n}\n\n/** The t of the walk's nearest point to `p`: the nearest grid point, then a golden-section search on the stretch either side of it. */\nfunction nearest(mark: MarkGeometry, grid: readonly Point[], p: Point): number {\n const n = grid.length;\n if (n === 1) return 0;\n let best = 0;\n let bestDistance = Infinity;\n grid.forEach((q, i) => {\n const d = squared(q, p);\n if (d < bestDistance) {\n best = i;\n bestDistance = d;\n }\n });\n const f = (t: number): number => squared(mark.path(t), p);\n let lo = Math.max(0, best - 1) / (n - 1);\n let hi = Math.min(n - 1, best + 1) / (n - 1);\n let a = hi - GOLDEN * (hi - lo);\n let b = lo + GOLDEN * (hi - lo);\n let fa = f(a);\n let fb = f(b);\n for (let step = 0; step < REFINE; step++) {\n if (fa <= fb) {\n hi = b;\n b = a;\n fb = fa;\n a = hi - GOLDEN * (hi - lo);\n fa = f(a);\n } else {\n lo = a;\n a = b;\n fa = fb;\n b = lo + GOLDEN * (hi - lo);\n fb = f(b);\n }\n }\n const t = (lo + hi) / 2;\n // The grid point itself unless the search found somewhere nearer, so a point at either end lands\n // on exactly 0 or 1, and a stretch that isn't one dip can't make it worse.\n const found = f(t) < bestDistance ? t : best / (n - 1);\n return found > 0 ? (found < 1 ? found : 1) : 0;\n}\n\nfunction squared(a: Point, b: Point): number {\n return (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n}\n","// Announcements: with `announce`, a polite live region that sums up each update for screen readers.\n// The chart writes the generic part (\"Sorted A to Z\", \"Okafor and Tanaka changed\"); a page that knows\n// more (\"Matchweek 25\") passes a function that writes its own text from the chart's.\n\nexport type SortName = \"value\" | \"key\" | \"none\" | \"custom\";\n\n/** What changed in an update, as the chart sees it. Names are the marks' categories, in visual order. */\nexport interface ChangeFacts {\n /** The chart's new label, when it changed. */\n readonly label?: string;\n /** The new series, by their labels, when they changed. */\n readonly series?: readonly string[];\n /** The new sort, when it changed. */\n readonly sort?: SortName;\n readonly changed: readonly string[];\n readonly added: readonly string[];\n readonly removed: readonly string[];\n /** Marks after the update. */\n readonly count: number;\n}\n\nexport interface Announcer {\n /** Announces `text`, politely. Saying the same thing twice in a row is announced twice. */\n say(text: string): void;\n destroy(): void;\n}\n\nconst SORTED: Record<SortName, string> = {\n value: \"Sorted highest first\",\n key: \"Sorted A to Z\",\n none: \"In data order\",\n custom: \"Sorted\"\n};\n\n/** Lists more than this many marks as a count: \"5 of 8 changed\". */\nconst NAMED = 3;\n\n/**\n * The chart's own summary, a sentence for each kind of change, or \"\" when nothing it reports changed.\n * A new label stands for the view it names; otherwise new series are named. A change of series\n * changes every value, so the marks that changed are counted only when the series stayed.\n */\nexport function changeText(facts: ChangeFacts): string {\n const parts: string[] = [];\n const { series } = facts;\n if (facts.label !== undefined) parts.push(facts.label);\n // A lone value read by a function has no name worth saying.\n else if (series && !(series.length === 1 && series[0] === \"value\")) parts.push(`Showing ${list(series)}`);\n if (facts.sort) parts.push(SORTED[facts.sort]);\n const { changed, added, removed } = facts;\n if (!series && changed.length > 0) parts.push(changed.length <= NAMED ? `${list(changed)} changed` : `${changed.length} of ${facts.count} changed`);\n if (added.length > 0) parts.push(`Added ${added.length <= NAMED ? list(added) : added.length}`);\n if (removed.length > 0) parts.push(`Removed ${removed.length <= NAMED ? list(removed) : removed.length}`);\n return parts.join(\". \");\n}\n\n/** \"a\", \"a and b\", \"a, b and c\". */\nfunction list(names: readonly string[]): string {\n if (names.length <= 1) return names.join(\"\");\n return `${names.slice(0, -1).join(\", \")} and ${names[names.length - 1]}`;\n}\n\n/**\n * The live region for a chart's <svg>: a visually hidden role=\"status\" just after it. Make it before\n * the first announcement: screen readers miss text in a region that appears with it.\n */\nexport function chartAnnouncer(svg: SVGSVGElement): Announcer {\n const region = svg.ownerDocument.createElement(\"div\");\n region.className = \"ec-announcer ec-visually-hidden\";\n region.setAttribute(\"role\", \"status\");\n region.setAttribute(\"aria-live\", \"polite\");\n region.setAttribute(\"aria-atomic\", \"true\");\n svg.after(region);\n /** Alternates, so the same text twice is still a change the region announces. */\n let odd = false;\n return {\n say(text) {\n if (text === \"\") return;\n odd = !odd;\n region.textContent = odd ? text : `${text} `;\n },\n destroy() {\n region.remove();\n }\n };\n}\n","// Small helpers for building SVG. Nothing here runs at import time, so the package still loads in Node.\n\nimport type { Matrix } from \"../../core\";\nimport { formatNumber } from \"../../core/geometry\";\n\nexport const SVG_NS = \"http://www.w3.org/2000/svg\";\n\nexport type Attributes = Readonly<Record<string, string | number | undefined>>;\n\n/** Creates an SVG element in `parent`'s document (or the global one), sets its attributes and appends it to `parent` if given. */\nexport function svgElement<K extends keyof SVGElementTagNameMap>(tag: K, attributes: Attributes = {}, parent?: Element): SVGElementTagNameMap[K] {\n const doc = parent?.ownerDocument ?? document;\n const element = doc.createElementNS(SVG_NS, tag) as SVGElementTagNameMap[K];\n setAttributes(element, attributes);\n parent?.appendChild(element);\n return element;\n}\n\n/** Sets attributes; a value of undefined removes the attribute. Numbers are rounded to 0.001. */\nexport function setAttributes(element: Element, attributes: Attributes): void {\n for (const [name, value] of Object.entries(attributes)) {\n if (value === undefined) element.removeAttribute(name);\n else element.setAttribute(name, typeof value === \"number\" ? formatNumber(value) : value);\n }\n}\n\n/** Sets CSS properties through the CSSOM (allowed under a strict CSP); undefined removes one. */\nexport function setStyles(element: SVGElement, styles: Readonly<Record<string, string | undefined>>): void {\n for (const [name, value] of Object.entries(styles)) {\n if (value === undefined) element.style.removeProperty(name);\n else element.style.setProperty(name, value);\n }\n}\n\n/** A chart's <svg> size and viewBox, in px. */\nexport function sizeAttributes({ width, height }: { readonly width: number; readonly height: number }): Record<string, string | number> {\n return { width, height, viewBox: `0 0 ${formatNumber(width)} ${formatNumber(height)}` };\n}\n\n/**\n * A Matrix as an SVG transform attribute. The linear part keeps 6 decimals, so a small rotation of a\n * long bar stays exact at its far end; the translation is rounded to 0.001 px like path data.\n */\nexport function transformAttribute(m: Matrix): string {\n const [a, b, c, d, e, f] = m;\n return `matrix(${[a, b, c, d].map(linear).join(\" \")} ${formatNumber(e)} ${formatNumber(f)})`;\n}\n\nfunction linear(value: number): string {\n const rounded = Math.round(value * 1e6) / 1e6;\n return rounded === 0 ? \"0\" : String(rounded);\n}\n","// Text widths for layout (label margins). Measured in the chart's own SVG, so the page's font and the\n// chart's CSS apply. Where there's no layout (jsdom, a hidden container), widths are estimated from\n// the character count.\n\nimport type { Rect } from \"../../core\";\nimport { setAttributes, svgElement } from \"./svg\";\n\n/** Where a piece of text goes: its baseline's anchor point, and how it's anchored there. */\nexport interface TextPlacement {\n readonly x: number;\n readonly y: number;\n readonly anchor: \"start\" | \"middle\" | \"end\";\n readonly text: string;\n}\n\n/**\n * How far text reaches, as shares of its size: above its baseline (an accented capital's top), below\n * it (a descender's foot), and past its measured width at either side (a W's lean, an f's hook). So a\n * box holds the text's getBBox() in Chrome with Segoe UI, Arial, Georgia, Verdana and Consolas; a\n * Times New Roman \"ff\" reaches 0.8 px past it.\n */\nconst ASCENT = 1.05;\nconst DESCENT = 0.25;\nconst SIDE = 0.16;\n\n/**\n * The box `placement`'s text covers, drawn with `className` at `size` px: a mark's `labelBounds`.\n * Chart text has tabular digits, so it's measured with its digits as 0s, and text that counts\n * through values while a change plays is measured once for each shape.\n */\nexport function textBox(placement: TextPlacement, measure: Measure, className: string, size: number): Rect {\n const width = measure(placement.text.replace(/\\d/g, \"0\"), className, size);\n const start = placement.anchor === \"start\" ? placement.x : placement.anchor === \"end\" ? placement.x - width : placement.x - width / 2;\n return { x: start - SIDE * size, y: placement.y - ASCENT * size, width: width + 2 * SIDE * size, height: (ASCENT + DESCENT) * size };\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\n/** Moves a <text> to `placement` and sets its text, when it changed. */\nexport function placeText(element: SVGTextElement, placement: TextPlacement): void {\n setAttributes(element, { x: placement.x, y: placement.y, \"text-anchor\": placement.anchor });\n if (element.textContent !== placement.text) element.textContent = placement.text;\n}\n\nexport interface TextMeasure {\n /** Width in px of `text` drawn with `className` at `size` px (the size is only used for estimates). */\n (text: string, className: string, size: number): number;\n /** Forget measured widths, for example once web fonts have loaded. */\n clear(): void;\n}\n\n/** An estimate of the average glyph width, in em. */\nconst AVERAGE_WIDTH = 0.6;\n\nexport function textMeasure(svg: SVGSVGElement): TextMeasure {\n const cache = new Map<string, number>();\n const measure = (text: string, className: string, size: number): number => {\n if (text === \"\") return 0;\n const id = `${className}\\n${size}\\n${text}`;\n const cached = cache.get(id);\n if (cached !== undefined) return cached;\n let width = 0;\n const probe = svgElement(\"text\", { class: className, visibility: \"hidden\", \"aria-hidden\": \"true\" }, svg);\n if (typeof probe.getComputedTextLength === \"function\" && svg.isConnected) {\n probe.textContent = text;\n width = probe.getComputedTextLength();\n }\n probe.remove();\n // Only real measurements are kept: a hidden chart measures again once it's shown.\n if (!(width > 0)) return text.length * size * AVERAGE_WIDTH;\n cache.set(id, width);\n return width;\n };\n return Object.assign(measure, { clear: () => cache.clear() });\n}\n","// The bar chart's layout: pure, so it's tested without a DOM. Options in, marks (described with\n// describe.bar), labels, ticks and size out. Pixel sizes follow the prototype (demo/lab.html).\n//\n// A layout is drawn from a few numbers: the frame (the value scale and the category bands) and each\n// row's values and slot. Transitions interpolate those numbers, and placeRow and placeTick draw any\n// state in between the same way the layout draws its own.\n//\n// Labels that would overlap are thinned: every nth category label is drawn, and the value labels all\n// or none. The frame keeps room for every label, so thinning moves nothing.\n\nimport type { MarkData, MarkGeometry, Rect } from \"../core\";\nimport { describeBar } from \"../core/geometry/describe/bar\";\nimport { textBox, type TextPlacement } from \"./render/text\";\nimport type { Accessor, BarChartOptions } from \"./types\";\n\nexport type { TextPlacement } from \"./render/text\";\n\nexport type Orientation = \"horizontal\" | \"vertical\";\n\nexport interface BarSeries<D> {\n /** The segment's name: the stacked field, or the value field. */\n readonly series: string;\n readonly value: (d: D, i: number) => unknown;\n}\n\n/** Which accessor is the category, which give the values. */\nexport interface BarEncoding<D> {\n readonly orientation: Orientation;\n readonly category: (d: D, i: number) => unknown;\n readonly key: (d: D, i: number) => unknown;\n readonly series: readonly BarSeries<D>[];\n}\n\nexport interface BarValue {\n readonly series: string;\n readonly value: number;\n}\n\n/** Which of a row's labels are drawn. */\nexport interface DrawnLabels {\n readonly label: boolean;\n readonly value: boolean;\n}\n\nexport interface BarRow<D> {\n readonly key: string;\n readonly datum: D;\n /** The row's index in `data`. */\n readonly index: number;\n /** Its position along the category axis, in bands: 0 is the first. */\n readonly slot: number;\n readonly values: readonly BarValue[];\n readonly total: number;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n /** The row's name, which the tooltip, the mark's name and the table say, its label drawn or not. */\n readonly category: string;\n /** Which of its labels are drawn: thinning leaves some out. */\n readonly drawn: DrawnLabels;\n /** The category label: its text is empty when it isn't drawn. */\n readonly label: TextPlacement;\n /** The total, at the bar's tip: its text is empty when it isn't drawn. */\n readonly value: TextPlacement;\n /** The pointer target: the row's whole band. */\n readonly hit: Rect;\n}\n\nexport interface Tick {\n readonly value: number;\n readonly line: { readonly x1: number; readonly y1: number; readonly x2: number; readonly y2: number };\n readonly label: TextPlacement;\n}\n\n/**\n * The value axis. Data `lo` sits at px `from`, and each unit of data is `extent / (hi - lo)` px along\n * the axis (`extent` is negative for columns, which grow up). `label` is where the category labels\n * sit across it: their x for bars, their y for columns.\n */\nexport interface BarScale {\n readonly lo: number;\n readonly hi: number;\n readonly from: number;\n readonly extent: number;\n readonly label: number;\n}\n\n/**\n * The category axis. Slot 0's band starts at px `start`; each band is `band` px, with a bar\n * `thickness` px across in it; the plot is `span` px along the axis. Plus the chart's size.\n */\nexport interface BarBands {\n readonly start: number;\n readonly band: number;\n readonly thickness: number;\n readonly span: number;\n readonly width: number;\n readonly height: number;\n}\n\nexport interface BarFrame {\n readonly orientation: Orientation;\n readonly scale: BarScale;\n readonly bands: BarBands;\n}\n\n/** Which labels a layout draws, so that no two overlap. */\nexport interface BarLabels {\n /** Every nth category label is drawn, from the first: n is 1, 2, 5, 10, 20, 50 and so on. */\n readonly every: number;\n /** Whether the value labels are drawn: none are when any two would overlap. */\n readonly values: boolean;\n}\n\nexport interface BarLayout<D> {\n readonly width: number;\n readonly height: number;\n readonly orientation: Orientation;\n readonly frame: BarFrame;\n /** In visual order: top to bottom, or left to right. A row's slot is its index here. */\n readonly rows: readonly BarRow<D>[];\n readonly ticks: readonly Tick[];\n readonly labels: BarLabels;\n}\n\n/** What placeRow draws a row from: a laid-out row, or a state in between two. */\nexport interface BarRowState<D> {\n readonly key: string;\n readonly datum: D;\n readonly index: number;\n /** The row's name: its category label's text. */\n readonly category: string;\n /** Signed, from the baseline. */\n readonly values: readonly BarValue[];\n /** Fractional in between. */\n readonly slot: number;\n /** The value label's text. */\n readonly text: string;\n /** Which of its labels are drawn, as its layout thinned them. Default: both. */\n readonly drawn?: DrawnLabels;\n}\n\nexport interface BarLayoutInput<D> {\n readonly data: readonly D[];\n readonly encoding: BarEncoding<D>;\n readonly sort: BarChartOptions<D>[\"sort\"];\n readonly width: number;\n readonly height: number | undefined;\n readonly format: (value: number) => string;\n /** Text width in px, for margins and the labels' boxes. */\n readonly measure: Measure;\n /** Px kept clear past the labels at each end of the value axis that bars reach. Default 0. */\n readonly room?: number;\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\n// From the prototype: 34 px rows with 20 px bars, a 2 px gap between segments, rounded tips.\nconst ROW = 34;\nconst BAR = 20;\nconst RADIUS = 4;\nconst GAP = 2;\nconst MAX_COLUMN = 72;\nconst VERTICAL_HEIGHT = 300;\nconst LABEL_SIZE = 12.5;\nconst VALUE_SIZE = 12.5;\nconst TICK_SIZE = 11;\n/** Space under the plot for tick (or category) labels. */\nconst AXIS = 26;\nconst TOP = 4;\n/** Between a label and what it labels. */\nconst PAD = 6;\n/** A row's labels when its layout didn't thin them. */\nconst BOTH: DrawnLabels = { label: true, value: true };\n/** Moves a text baseline down by this share of the font size to centre the text on a line. */\nconst CENTRE = 0.36;\n\n/** Reads the options: which axis is the category, which fields are the values. Throws on what it can't draw. */\nexport function barEncoding<D>(options: BarChartOptions<D>): BarEncoding<D> {\n const { x, y, stack, data } = options;\n let orientation = options.orientation;\n if (orientation !== undefined && orientation !== \"horizontal\" && orientation !== \"vertical\") {\n throw new TypeError(`barChart: orientation must be \"horizontal\" or \"vertical\", got ${String(orientation)}.`);\n }\n if (stack !== undefined) {\n if (!Array.isArray(stack) || stack.length === 0) throw new TypeError(\"barChart: stack needs at least one numeric field.\");\n const seen = new Set<string>();\n for (const field of stack) {\n if (seen.has(field)) throw new TypeError(`barChart: \"${field}\" appears twice in stack.`);\n seen.add(field);\n }\n }\n if (orientation === undefined) {\n if (x !== undefined && y !== undefined) {\n const xNumbers = numeric(data, accessor(x));\n const yNumbers = numeric(data, accessor(y));\n if (xNumbers !== yNumbers) orientation = xNumbers ? \"horizontal\" : \"vertical\";\n else if (data.length === 0) orientation = \"horizontal\";\n else {\n throw new RangeError(\n `barChart: ${xNumbers ? \"x and y both hold numbers\" : \"neither x nor y holds numbers\"}, so it can't tell which is the category. ` +\n `Set orientation: \"horizontal\" (categories along y) or \"vertical\" (categories along x).`\n );\n }\n } else if (stack !== undefined && (x !== undefined || y !== undefined)) {\n orientation = y !== undefined ? \"horizontal\" : \"vertical\";\n } else {\n throw new TypeError(\"barChart needs x and y (the axis whose values aren't numbers is the category), or one of them plus stack.\");\n }\n }\n const horizontal = orientation === \"horizontal\";\n const categoryOption = horizontal ? y : x;\n const valueOption = horizontal ? x : y;\n if (categoryOption === undefined) throw new TypeError(`barChart: a ${orientation} chart takes its categories from ${horizontal ? \"y\" : \"x\"}.`);\n const category = accessor(categoryOption);\n\n let series: BarSeries<D>[];\n if (stack !== undefined) series = stack.map((field) => ({ series: field, value: accessor<D, unknown>(field) }));\n else if (valueOption !== undefined) series = [{ series: typeof valueOption === \"string\" ? valueOption : \"value\", value: accessor(valueOption) }];\n else throw new TypeError(`barChart needs values: ${horizontal ? \"x\" : \"y\"} set to a numeric field, or stack.`);\n\n return { orientation, category, key: options.key === undefined ? category : accessor(options.key), series };\n}\n\nexport function layoutBars<D>(input: BarLayoutInput<D>): BarLayout<D> {\n const rows = sortRows(prepareRows(input), input.sort);\n const domain = niceDomain(rows.map((row) => row.total));\n const texts = rows.map((row) => input.format(row.total));\n const ticks = domain.ticks.map(input.format);\n const frame = (input.encoding.orientation === \"horizontal\" ? horizontalFrame : verticalFrame)(input, rows, domain, texts, ticks);\n const labels = thinLabels(frame, rows, texts, input.measure);\n return {\n width: frame.bands.width,\n height: frame.bands.height,\n orientation: frame.orientation,\n frame,\n rows: rows.map((row, slot) => placeRow(frame, { ...row, slot, text: texts[slot]!, drawn: { label: slot % labels.every === 0, value: labels.values } }, input.measure)),\n ticks: domain.ticks.map((value, i) => placeTick(frame, value, ticks[i]!)),\n labels\n };\n}\n\n/**\n * Which labels to draw so that no two overlap, by their boxes as `labelBounds` gives them: every nth\n * category label from the first, with n the smallest of 1, 2, 5, 10, 20, 50 and so on that leaves none\n * overlapping, and the value labels only if no two would overlap. A category label and a value label\n * aren't compared: within a row they sit apart.\n */\nfunction thinLabels<D>(frame: BarFrame, rows: readonly Prepared<D>[], texts: readonly string[], measure: Measure): BarLabels {\n const placed = rows.map((row, slot) => placeLabels(frame, slot, row.total, row.category, texts[slot]!));\n const horizontal = frame.orientation === \"horizontal\";\n const values = !overlaps(boxesOf(placed.map(({ value }) => value), measure, \"ec-value\", VALUE_SIZE), horizontal);\n const categories = (every: number): Rect[] =>\n boxesOf(\n placed.filter((_, slot) => slot % every === 0).map(({ label }) => label),\n measure,\n \"ec-label\",\n LABEL_SIZE\n );\n let k = 0;\n // Past the last row only the first is drawn, and one label can't overlap.\n while (thinStep(k) < rows.length && overlaps(categories(thinStep(k)), horizontal)) k++;\n return { every: thinStep(k), values };\n}\n\n/** The kth n thinning tries: 1, 2, 5, 10, 20, 50 and so on. */\nconst thinStep = (k: number): number => [1, 2, 5][k % 3]! * 10 ** Math.floor(k / 3);\n\n/** The boxes of the labels that have text. */\nfunction boxesOf(labels: readonly TextPlacement[], measure: Measure, className: string, size: number): Rect[] {\n return labels.filter((label) => label.text !== \"\").map((label) => textBox(label, measure, className, size));\n}\n\n/**\n * Whether any two boxes overlap (touching doesn't count). A sweep along the category axis (y for\n * bars, x for columns), so each box is checked only against those it reaches along it.\n */\nfunction overlaps(boxes: readonly Rect[], horizontal: boolean): boolean {\n // Columns as given; bars turned on their side, so the sweep runs along x either way.\n const along = horizontal ? boxes.map(({ x, y, width, height }) => ({ x: y, y: x, width: height, height: width })) : [...boxes];\n along.sort((a, b) => a.x - b.x);\n const open: Rect[] = [];\n for (const box of along) {\n for (let i = open.length - 1; i >= 0; i--) if (open[i]!.x + open[i]!.width <= box.x) open.splice(i, 1);\n if (open.some((other) => other.y < box.y + box.height && box.y < other.y + other.height)) return true;\n open.push(box);\n }\n return false;\n}\n\n/** A row's labels in a frame: its category beside the axis, and its value past the bar's tip. */\nfunction placeLabels(frame: BarFrame, slot: number, total: number, category: string, text: string): { readonly label: TextPlacement; readonly value: TextPlacement } {\n const { scale, bands } = frame;\n const negative = total < 0;\n const tip = position(scale)(total);\n const band = bands.start + slot * bands.band;\n if (frame.orientation === \"horizontal\") {\n const line = band + bands.band / 2 + LABEL_SIZE * CENTRE;\n return {\n label: { x: scale.label, y: line, anchor: \"end\", text: category },\n value: { x: negative ? tip - PAD : tip + PAD, y: line, anchor: negative ? \"end\" : \"start\", text }\n };\n }\n const centre = band + bands.band / 2;\n return {\n label: { x: centre, y: scale.label, anchor: \"middle\", text: category },\n value: { x: centre, y: negative ? tip + PAD + VALUE_SIZE * 0.8 : tip - PAD, anchor: \"middle\", text }\n };\n}\n\n/**\n * Draws a row in a frame: its bar (described with describe.bar, its drawn labels' boxes as\n * `labelBounds`), labels and pointer target. In between two states of opposite sign a stack can mix\n * signs; values against the total's sign then draw as 0.\n */\nexport function placeRow<D>(frame: BarFrame, row: BarRowState<D>, measure: Measure): BarRow<D> {\n const { scale, bands } = frame;\n const at = position(scale);\n const unit = Math.abs(scale.extent / (scale.hi - scale.lo));\n const total = row.values.reduce((sum, v) => sum + v.value, 0);\n const negative = total < 0;\n const zero = at(0);\n const tip = at(total);\n const band = bands.start + row.slot * bands.band;\n const bar = {\n key: row.key,\n ...(row.values.length === 1 ? { series: row.values[0]!.series } : {}),\n radius: RADIUS,\n gap: GAP,\n segments: row.values.map((v) => ({ series: v.series, size: Math.max(0, negative ? -v.value : v.value) * unit }))\n };\n const drawn = row.drawn ?? BOTH;\n const fields = { key: row.key, datum: row.datum, index: row.index, slot: row.slot, values: row.values, total, category: row.category, drawn };\n const { label, value } = placeLabels(frame, row.slot, total, drawn.label ? row.category : \"\", drawn.value ? row.text : \"\");\n /** The labels' boxes, leaving out a label with no text. */\n const boxes = (): Rect[] => [...boxesOf([label], measure, \"ec-label\", LABEL_SIZE), ...boxesOf([value], measure, \"ec-value\", VALUE_SIZE)];\n\n if (frame.orientation === \"horizontal\") {\n const geometry = describeBar({\n ...bar,\n x: Math.min(zero, tip),\n y: band + (bands.band - bands.thickness) / 2,\n width: Math.abs(tip - zero),\n height: bands.thickness,\n baseline: negative ? \"right\" : \"left\",\n labelBounds: boxes()\n });\n return {\n ...fields,\n geometry,\n data: barData(row.datum, total, geometry),\n label,\n value,\n hit: { x: 0, y: band, width: bands.width, height: bands.band }\n };\n }\n\n const centre = band + bands.band / 2;\n const geometry = describeBar({\n ...bar,\n x: centre - bands.thickness / 2,\n y: Math.min(zero, tip),\n width: bands.thickness,\n height: Math.abs(tip - zero),\n baseline: negative ? \"top\" : \"bottom\",\n labelBounds: boxes()\n });\n return {\n ...fields,\n geometry,\n data: barData(row.datum, total, geometry),\n label,\n value,\n hit: { x: band, y: 0, width: bands.band, height: bands.height }\n };\n}\n\n/** Draws a tick's gridline and label in a frame. */\nexport function placeTick(frame: BarFrame, value: number, text: string): Tick {\n const { bands } = frame;\n const at = position(frame.scale)(value);\n if (frame.orientation === \"horizontal\") {\n const bottom = bands.start + bands.span;\n return { value, line: { x1: at, y1: bands.start, x2: at, y2: bottom }, label: { x: at, y: bottom + 16, anchor: \"middle\", text } };\n }\n return {\n value,\n line: { x1: bands.start, y1: at, x2: bands.start + bands.span, y2: at },\n label: { x: bands.start - 8, y: at + TICK_SIZE * CENTRE, anchor: \"end\", text }\n };\n}\n\n/** Data value to px along the value axis. */\nfunction position(scale: BarScale): (value: number) => number {\n const perUnit = scale.extent / (scale.hi - scale.lo);\n return (value) => scale.from + (value - scale.lo) * perUnit;\n}\n\ninterface Prepared<D> {\n readonly key: string;\n readonly category: string;\n readonly datum: D;\n readonly index: number;\n readonly values: readonly { readonly series: string; readonly value: number }[];\n readonly total: number;\n}\n\ninterface Domain {\n readonly lo: number;\n readonly hi: number;\n readonly ticks: readonly number[];\n}\n\nfunction prepareRows<D>({ data, encoding }: BarLayoutInput<D>): Prepared<D>[] {\n const keys = new Set<string>();\n return data.map((datum, index) => {\n const key = String(encoding.key(datum, index));\n if (keys.has(key)) throw new Error(`barChart: two rows have the key \"${key}\". Keys must be unique; pass a key accessor if categories repeat.`);\n keys.add(key);\n const values = encoding.series.map(({ series, value }) => ({ series, value: numberOf(value(datum, index), series, key) }));\n if (values.some((v) => v.value > 0) && values.some((v) => v.value < 0)) {\n throw new RangeError(`barChart: the stack for \"${key}\" mixes positive and negative values, which isn't supported yet.`);\n }\n const total = values.reduce((sum, v) => sum + v.value, 0);\n return { key, category: String(encoding.category(datum, index) ?? \"\"), datum, index, values, total };\n });\n}\n\nfunction sortRows<D>(rows: Prepared<D>[], sort: BarLayoutInput<D>[\"sort\"]): Prepared<D>[] {\n if (sort === undefined || sort === \"none\") return rows;\n // Array.prototype.sort is stable, so ties keep data order.\n if (sort === \"value\") return [...rows].sort((a, b) => b.total - a.total);\n if (sort === \"key\") return [...rows].sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));\n if (typeof sort === \"function\") return [...rows].sort((a, b) => sort(a.datum, b.datum));\n throw new TypeError(`barChart: sort must be \"value\", \"key\", \"none\" or a comparator, got ${String(sort)}.`);\n}\n\n/** Zero is always in the domain; the ends are rounded out to a 1, 2 or 5 step, about four ticks apart (as in the prototype). */\nexport function niceDomain(values: readonly number[]): Domain {\n let lo = values.reduce((min, v) => Math.min(min, v), 0);\n let hi = values.reduce((max, v) => Math.max(max, v), 0);\n if (lo === hi) hi = 1;\n const step = niceStep((hi - lo) / 4);\n lo = clean(Math.floor(lo / step) * step);\n hi = clean(Math.ceil(hi / step) * step);\n const count = Math.round((hi - lo) / step);\n const ticks = Array.from({ length: count + 1 }, (_, i) => clean(lo + i * step));\n return { lo, hi, ticks };\n}\n\n/** A round step near `span`: 1, 2, 5 or 10 times a power of 10. */\nexport function niceStep(span: number): number {\n const power = 10 ** Math.floor(Math.log10(span));\n const f = span / power;\n return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * power;\n}\n\nfunction horizontalFrame<D>(input: BarLayoutInput<D>, rows: readonly Prepared<D>[], domain: Domain, values: readonly string[], ticks: readonly string[]): BarFrame {\n const { width, measure } = input;\n const n = rows.length;\n const labelWidth = widest(rows.map((row) => row.category), \"ec-label\", LABEL_SIZE, measure);\n const valueWidth = widest(values, \"ec-value\", VALUE_SIZE, measure);\n const tickWidth = widest(ticks, \"ec-tick\", TICK_SIZE, measure);\n const { positive, negative } = reach(input, rows);\n // Value labels sit past the tip, so negative bars need room on the left as well.\n const negativeRoom = domain.lo < 0 ? valueWidth + PAD : 0;\n // `room` is outermost: past the names on the left, which negative bars' text goes past too.\n const left = Math.max(labelWidth + 10 + negativeRoom + negative, tickWidth / 2 + 2);\n const right = Math.max(valueWidth + PAD + 4 + positive, tickWidth / 2 + 2);\n const rowSize = input.height === undefined || n === 0 ? ROW : Math.max(0, input.height - TOP - AXIS) / n;\n return {\n orientation: \"horizontal\",\n scale: { lo: domain.lo, hi: domain.hi, from: left, extent: Math.max(0, width - left - right), label: left - 10 - negativeRoom },\n bands: { start: TOP, band: rowSize, thickness: (rowSize * BAR) / ROW, span: n * rowSize, width, height: input.height ?? TOP + n * rowSize + AXIS }\n };\n}\n\nfunction verticalFrame<D>(input: BarLayoutInput<D>, rows: readonly Prepared<D>[], domain: Domain, _values: readonly string[], ticks: readonly string[]): BarFrame {\n const { width, measure } = input;\n const n = rows.length;\n const height = input.height ?? VERTICAL_HEIGHT;\n const tickWidth = widest(ticks, \"ec-tick\", TICK_SIZE, measure);\n const { positive, negative } = reach(input, rows);\n // Room above positive columns (and below negative ones) for their value labels, and `room` past them.\n const top = (domain.hi > 0 ? VALUE_SIZE + PAD + 2 : TOP) + positive;\n const bottom = AXIS + (domain.lo < 0 ? VALUE_SIZE + PAD : 0) + negative;\n const left = tickWidth + 8 + 2;\n const plot = { x: left, y: top, width: Math.max(0, width - left - 8), height: Math.max(0, height - top - bottom) };\n const band = n > 0 ? plot.width / n : 0;\n const base = plot.y + plot.height;\n return {\n orientation: \"vertical\",\n scale: { lo: domain.lo, hi: domain.hi, from: base, extent: -plot.height, label: base + 18 },\n bands: { start: plot.x, band, thickness: Math.min((band * BAR) / ROW, MAX_COLUMN), span: plot.width, width, height }\n };\n}\n\n/**\n * `room` at each end of the value axis that bars reach: the positive end if a total is above 0, the\n * negative end if one is below. An end no bar reaches gets none, so nothing moves for it.\n */\nfunction reach<D>(input: BarLayoutInput<D>, rows: readonly Prepared<D>[]): { readonly positive: number; readonly negative: number } {\n const room = input.room ?? 0;\n return {\n positive: rows.some((row) => row.total > 0) ? room : 0,\n negative: rows.some((row) => row.total < 0) ? room : 0\n };\n}\n\n/**\n * Values along the walk: from 0 at the baseline to the total at the tip. `related(series)` is that\n * series' segment in the same row, its samples running over the segment's own span.\n */\nfunction barData<D>(datum: D, total: number, geometry: MarkGeometry): MarkData<D> {\n const valueAt = (distance: number): number => (geometry.length > 0 ? (total * distance) / geometry.length : 0);\n const data: MarkData<D> = {\n datum,\n samples: [\n { t: 0, value: 0 },\n { t: 1, value: total }\n ],\n related(series) {\n const segment = geometry.segments?.find((s) => s.series === series);\n if (!segment) return undefined;\n const from = Math.hypot(segment.start.x - geometry.start.x, segment.start.y - geometry.start.y);\n return {\n datum,\n samples: [\n { t: 0, value: valueAt(from) },\n { t: 1, value: valueAt(from + segment.length) }\n ],\n related: data.related\n };\n }\n };\n return data;\n}\n\nfunction widest(texts: readonly string[], className: string, size: number, measure: Measure): number {\n return texts.reduce((max, text) => Math.max(max, measure(text, className, size)), 0);\n}\n\nfunction accessor<D, T>(option: Accessor<D, T> | string): (d: D, i: number) => T {\n if (typeof option === \"function\") return option;\n return (d) => (d as Record<string, unknown>)[option] as T;\n}\n\n/** Every value is a number (or missing), and at least one is there. */\nfunction numeric<D>(data: readonly D[], read: (d: D, i: number) => unknown): boolean {\n let found = false;\n for (let i = 0; i < data.length; i++) {\n const value = read(data[i]!, i);\n if (value === null || value === undefined) continue;\n if (typeof value !== \"number\") return false;\n found = true;\n }\n return found;\n}\n\n/** Missing values (null, undefined) count as 0. */\nfunction numberOf(value: unknown, series: string, key: string): number {\n if (value === null || value === undefined) return 0;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new RangeError(`barChart: \"${series}\" for \"${key}\" must be a finite number, got ${typeof value === \"string\" ? JSON.stringify(value) : String(value)}.`);\n}\n\n/** Rounds away float noise (0.30000000000000004 is 0.3), and -0 to 0. */\nexport function clean(value: number): number {\n const rounded = Number(value.toPrecision(12));\n return rounded === 0 ? 0 : rounded;\n}\n","// Theme tokens: `--ec-*` CSS custom properties with light and dark defaults, and the small stylesheet\n// every chart shares. The stylesheet sets the defaults on the root element, following\n// prefers-color-scheme, and on any element with data-theme=\"light\" or \"dark\". Hosts theme a chart by\n// setting the custom properties; every default rule uses :where(), so host CSS overrides it without\n// specificity fights. The same text is injected as a <style> and shipped as dist/expressive-charts.css.\n\nimport type { Color } from \"../../core\";\n\n/** Palette slots run 1–8 and wrap after that. */\nexport const PALETTE_SIZE = 8;\n\n/** A theme's default token values. */\nexport interface Theme {\n readonly surface: string;\n readonly text: string;\n readonly \"text-muted\": string;\n readonly grid: string;\n readonly axis: string;\n readonly focus: string;\n readonly negative: string;\n /** Hairline borders on controls and the tooltip. */\n readonly ring: string;\n /** Opacity of the other marks' bodies while one is hovered: a number, not a colour. Their labels keep theirs. */\n readonly \"dim-opacity\": string;\n /** Slots 1–8: the mark colour, and its -strong variant for hover emphasis. */\n readonly series: readonly (readonly [color: string, strong: string])[];\n}\n\n/**\n * The defaults, validated in theme.test.ts: every mark colour has at least 3:1 contrast against the\n * surface, neighbouring slots stay apart under protanopia, deuteranopia and tritanopia, and each\n * -strong variant is its colour stepped toward the text colour. Slots 1–4 are the prototype's, except\n * that light 3 and 4 are darkened just enough to reach 3:1.\n */\nexport const themes: { readonly light: Theme; readonly dark: Theme } = {\n light: {\n surface: \"#fcfcfb\",\n text: \"#0b0b0b\",\n \"text-muted\": \"#75736d\",\n grid: \"#e1e0d9\",\n axis: \"#c3c2b7\",\n focus: \"#2a78d6\",\n negative: \"#d03b3b\",\n ring: \"rgba(11, 11, 11, 0.1)\",\n \"dim-opacity\": \"0.3\",\n series: [\n [\"#2a78d6\", \"#1c5cab\"],\n [\"#eb6834\", \"#c24d1d\"],\n [\"#02a471\", \"#07835a\"],\n [\"#c28409\", \"#9d6a07\"],\n [\"#8966da\", \"#6e49ba\"],\n [\"#0096b0\", \"#05778c\"],\n [\"#7a8a05\", \"#606d03\"],\n [\"#c34e97\", \"#a32f7a\"]\n ]\n },\n dark: {\n surface: \"#1a1a19\",\n text: \"#f0efec\",\n \"text-muted\": \"#8f8d86\",\n grid: \"#2c2c2a\",\n axis: \"#45453f\",\n focus: \"#3987e5\",\n negative: \"#e66767\",\n ring: \"rgba(255, 255, 255, 0.1)\",\n // Dimmed marks keep about the contrast they have in light (1.5:1 against 1.4:1 on average).\n \"dim-opacity\": \"0.3\",\n series: [\n [\"#3987e5\", \"#6da7ec\"],\n [\"#d95926\", \"#fb7747\"],\n [\"#199e70\", \"#45bc8c\"],\n [\"#c98500\", \"#eda100\"],\n [\"#936fe4\", \"#af8ffe\"],\n [\"#0b99b3\", \"#40b7d2\"],\n [\"#829401\", \"#9eb237\"],\n [\"#c8529c\", \"#e970ba\"]\n ]\n }\n};\n\n/** The colour tokens a drawing can name, besides the series. */\nconst COLOR_TOKENS = [\"surface\", \"text\", \"text-muted\", \"grid\", \"axis\", \"focus\", \"negative\"] as const;\ntype ColorToken = (typeof COLOR_TOKENS)[number];\n\n/** Light's colour tokens: the fallbacks in rules and inline styles, for a page that sets some tokens but has no stylesheet. */\nconst TOKENS: Readonly<Record<string, string>> = Object.fromEntries(COLOR_TOKENS.map((name) => [name, themes.light[name]])) as Record<ColorToken, string>;\n\n/** A series' colours as CSS: the mark colour and the stronger one used for hover emphasis. */\nexport interface SeriesColors {\n readonly color: string;\n readonly strong: string;\n}\n\n/** The CSS colours for a palette slot (1-based; wraps after PALETTE_SIZE), with light's as fallbacks. */\nexport function seriesColors(slot: number): SeriesColors {\n const n = ((Math.max(1, Math.floor(slot)) - 1) % PALETTE_SIZE) + 1;\n const [color, strong] = themes.light.series[n - 1]!;\n return { color: `var(--ec-series-${n}, ${color})`, strong: `var(--ec-series-${n}-strong, ${strong})` };\n}\n\n/**\n * A drawing-API colour as CSS. Theme tokens become custom properties with fallbacks; \"mark\" and\n * \"mark-strong\" are the colours of the mark a run belongs to (set on its overlay group as --ec-mark);\n * anything else passes through as a CSS colour.\n */\nexport function cssColor(color: Color): string {\n if (color === \"mark\") return `var(--ec-mark, ${seriesColors(1).color})`;\n if (color === \"mark-strong\") return `var(--ec-mark-strong, ${seriesColors(1).strong})`;\n const fallback = TOKENS[color];\n if (fallback !== undefined) return `var(--ec-${color}, ${fallback})`;\n const series = /^series-(\\d+)(-strong)?$/.exec(color);\n if (series) {\n const colors = seriesColors(Number(series[1]));\n return series[2] ? colors.strong : colors.color;\n }\n return color;\n}\n\n/** Sets --ec-mark and --ec-mark-strong, which the stylesheet and the \"mark\" token read. */\nexport function markColorStyles(colors: SeriesColors | undefined): Record<string, string | undefined> {\n return { \"--ec-mark\": colors?.color, \"--ec-mark-strong\": colors?.strong };\n}\n\n/** A theme as custom property declarations, one per line. */\nfunction declarations(theme: Theme, indent: string): string {\n const names = [...COLOR_TOKENS, \"ring\", \"dim-opacity\"] as const;\n const lines = names.map((name) => `--ec-${name}: ${theme[name]};`);\n theme.series.forEach(([color, strong], i) => lines.push(`--ec-series-${i + 1}: ${color};`, `--ec-series-${i + 1}-strong: ${strong};`));\n return lines.map((line) => indent + line).join(\"\\n\");\n}\n\n/**\n * The tokens: light on the root and on data-theme=\"light\"; dark when the device prefers it, unless the\n * root says data-theme=\"light\"; dark on data-theme=\"dark\". In that order, so data-theme on any element\n * sets its subtree's theme. :where() keeps all of it at zero specificity.\n */\nconst TOKEN_RULES = `:where(:root, [data-theme=\"light\"]) {\n${declarations(themes.light, \" \")}\n}\n@media (prefers-color-scheme: dark) {\n :where(:root:not([data-theme=\"light\"])) {\n${declarations(themes.dark, \" \")}\n }\n}\n:where([data-theme=\"dark\"]) {\n${declarations(themes.dark, \" \")}\n}`;\n\n// Hover dims the parts in each other mark's body, not the whole mark, so its labels keep their\n// contrast. Not the body itself either: an effect's opacity is an attribute there, which a rule would\n// override. On the parts, the two multiply. The paths and icons the mark's runs draw in the overlay\n// dim with it, through their group (render/surface.ts); their text keeps its contrast, as labels do.\nconst STYLES = `/* expressive-charts: theme tokens and default styles. Every rule has zero specificity, so your CSS wins. */\n${TOKEN_RULES}\n:where(.ec-chart) { display: block; max-width: 100%; height: auto; overflow: visible; touch-action: pan-y; -webkit-tap-highlight-color: transparent; }\n:where(.ec-chart text) { font-variant-numeric: tabular-nums; }\n:where(.ec-chart .ec-gridline) { stroke: var(--ec-grid, ${TOKENS.grid}); stroke-width: 1; }\n:where(.ec-chart .ec-baseline) { stroke: var(--ec-axis, ${TOKENS.axis}); stroke-width: 1; }\n:where(.ec-chart .ec-tick) { fill: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-size: 11px; }\n:where(.ec-chart .ec-label) { fill: var(--ec-text, ${TOKENS.text}); font-size: 12.5px; }\n:where(.ec-chart .ec-value, .ec-chart .ec-text) { fill: var(--ec-text, ${TOKENS.text}); font-size: 12.5px; font-weight: 600; }\n:where(.ec-overlay .ec-text) { fill: var(--ec-text, ${TOKENS.text}); font-size: 12.5px; font-weight: 600; font-variant-numeric: tabular-nums; }\n:where(.ec-chart .ec-hit) { fill: transparent; }\n:where(.ec-chart .ec-mark:focus) { outline: none; }\n:where(.ec-chart .ec-focus) { pointer-events: none; }\n:where(.ec-chart .ec-focus-ring) { fill: none; stroke: var(--ec-focus, ${TOKENS.focus}); }\n:where(.ec-chart .ec-focus-gap) { fill: var(--ec-surface, ${TOKENS.surface}); stroke: var(--ec-surface, ${TOKENS.surface}); }\n:where(.ec-chart .ec-body > *) { transition: opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-segment) { fill: var(--ec-mark); transition: fill var(--ec-hover-duration, 100ms) ease-out, opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-segment) { fill: var(--ec-mark-strong); }\n:where(.ec-chart .ec-stroke) { fill: none; stroke: var(--ec-mark); stroke-linejoin: round; transition: stroke var(--ec-hover-duration, 100ms) ease-out, opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-stroke) { stroke: var(--ec-mark-strong); }\n:where(.ec-chart .ec-end) { fill: var(--ec-mark); stroke: var(--ec-surface, ${TOKENS.surface}); stroke-width: 2; }\n:where(.ec-chart .ec-dot) { fill: var(--ec-mark); stroke: var(--ec-surface, ${TOKENS.surface}); stroke-width: 2; opacity: 0; transition: opacity var(--ec-hover-duration, 100ms) ease-out, fill var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-dot) { fill: var(--ec-mark-strong); opacity: 1; }\n:where(.ec-chart .ec-alone .ec-dot) { opacity: 1; }\n:where(.ec-chart .ec-crosshair) { stroke: var(--ec-axis, ${TOKENS.axis}); stroke-width: 1; stroke-dasharray: 3 3; pointer-events: none; }\n:where(.ec-chart .ec-column:focus) { outline: none; }\n:where(.ec-chart .ec-lines, .ec-chart .ec-points) { pointer-events: none; }\n:where(.ec-chart .ec-slice) { fill: var(--ec-mark); stroke: var(--ec-surface, ${TOKENS.surface}); stroke-width: 2; stroke-linejoin: round; transition: fill var(--ec-hover-duration, 100ms) ease-out, opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart .ec-hot .ec-slice) { fill: var(--ec-mark-strong); }\n:where(.ec-chart .ec-center-value) { fill: var(--ec-text, ${TOKENS.text}); font-size: 26px; font-weight: 600; }\n:where(.ec-chart .ec-center-label) { fill: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-size: 12.5px; }\n:where(.ec-chart.ec-hovering .ec-mark:not(.ec-hot) > .ec-body > *) { opacity: var(--ec-dim-opacity, 0.3); }\n:where(.ec-hovering .ec-run:not(.ec-hot) > .ec-follow) { opacity: var(--ec-dim-opacity, 0.3); }\n:where(.ec-follow) { transition: opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-chart.ec-morphing .ec-marks) { visibility: hidden; }\n:where(.ec-switch) { display: grid; grid-template-columns: minmax(0, 1fr); position: relative; }\n:where(.ec-switch-view) { grid-area: 1 / 1; min-width: 0; }\n:where(.ec-switch-view.ec-switch-inactive) { visibility: hidden; }\n:where(.ec-switch-view.ec-switching .ec-focus, .ec-switch-view.ec-switching .ec-overlay, .ec-switch-view.ec-switching .ec-columns) { visibility: hidden; }\n:where(.ec-switch-overlay) { position: absolute; left: 0; top: 0; width: 100%; height: 100%; pointer-events: none; }\n:where(.ec-motion-switch) { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; color: var(--ec-text, ${TOKENS.text}); font-size: 13px; }\n:where(.ec-motion-label) { font-weight: 600; }\n:where(.ec-motion-modes) { display: inline-flex; gap: 2px; padding: 2px; border: 1px solid var(--ec-ring, color-mix(in srgb, currentColor 12%, transparent)); border-radius: 8px; background: var(--ec-surface, ${TOKENS.surface}); }\n:where(.ec-motion-modes button) { font: inherit; color: inherit; border: 0; background: transparent; padding: 5px 10px; border-radius: 6px; cursor: pointer; }\n:where(.ec-motion-modes button:hover, .ec-motion-modes button[aria-pressed=\"true\"]) { background: color-mix(in srgb, var(--ec-focus, ${TOKENS.focus}) 12%, transparent); }\n:where(.ec-motion-modes button[aria-pressed=\"true\"]) { font-weight: 600; }\n:where(.ec-motion-modes button:focus-visible) { outline: 2px solid var(--ec-focus, ${TOKENS.focus}); outline-offset: 2px; }\n@media (forced-colors: active) {\n /* Forced colours drop the pressed mode's tint, which leaves only its weight: it takes the viewer's selection colours. */\n :where(.ec-motion-modes button[aria-pressed=\"true\"]) { background: Highlight; color: HighlightText; }\n}\n:where(.ec-motion-hint) { flex: 1 1 220px; min-width: 0; color: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); }\n:where(.ec-play) { font: inherit; font-size: 13px; font-weight: 600; color: var(--ec-text, ${TOKENS.text}); border: 1px solid var(--ec-ring, color-mix(in srgb, currentColor 12%, transparent)); background: var(--ec-surface, ${TOKENS.surface}); padding: 6px 12px; border-radius: 8px; cursor: pointer; }\n:where(.ec-play:hover) { background: color-mix(in srgb, var(--ec-focus, ${TOKENS.focus}) 12%, var(--ec-surface, ${TOKENS.surface})); }\n:where(.ec-play:focus-visible) { outline: 2px solid var(--ec-focus, ${TOKENS.focus}); outline-offset: 2px; }\n:where(.ec-chart .ec-leaving, .ec-chart .ec-overlay) { pointer-events: none; }\n:where(.ec-attached.ec-dimmed) { opacity: var(--ec-dim-opacity, 0.3); }\n:where(.ec-attached) { transition: opacity var(--ec-hover-duration, 100ms) ease-out, fill var(--ec-hover-duration, 100ms) ease-out, stroke var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-tooltip-layer) { position: relative; height: 0; }\n:where(.ec-tooltip) { position: absolute; left: 0; top: 0; z-index: 3; box-sizing: border-box; width: max-content; max-width: 24em; padding: 8px 10px; border: 1px solid var(--ec-ring, color-mix(in srgb, currentColor 12%, transparent)); border-radius: 8px; background: var(--ec-surface, ${TOKENS.surface}); color: var(--ec-text, ${TOKENS.text}); box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12); font-size: 13px; line-height: 1.35; white-space: pre-line; font-variant-numeric: tabular-nums; pointer-events: none; opacity: 0; visibility: hidden; transition: opacity var(--ec-hover-duration, 100ms) ease-out, visibility 0s linear var(--ec-hover-duration, 100ms); }\n:where(.ec-tooltip.ec-tooltip-shown) { opacity: 1; visibility: visible; pointer-events: auto; transition: opacity var(--ec-hover-duration, 100ms) ease-out; }\n:where(.ec-tooltip-bridge) { position: absolute; left: 0; top: 0; z-index: 3; pointer-events: none; }\n:where(.ec-tooltip-shown + .ec-tooltip-bridge) { pointer-events: auto; }\n:where(.ec-tooltip-through > .ec-tooltip, .ec-tooltip-through > .ec-tooltip-bridge) { pointer-events: none; }\n:where(.ec-tooltip-title) { font-weight: 600; }\n:where(.ec-legend) { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-bottom: 8px; font-size: 13px; line-height: 1.4; color: var(--ec-text, ${TOKENS.text}); }\n:where(.ec-legend-item) { display: inline-flex; align-items: center; gap: 6px; }\n:where(.ec-legend-swatch) { flex: none; width: 10px; height: 10px; border-radius: 3px; background: var(--ec-mark); forced-color-adjust: none; }\n:where(.ec-table) { margin-top: 8px; font-size: 13px; line-height: 1.4; color: var(--ec-text, ${TOKENS.text}); }\n:where(.ec-table summary) { cursor: pointer; color: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-weight: 600; }\n:where(.ec-table summary:focus-visible) { outline: 2px solid var(--ec-focus, ${TOKENS.focus}); outline-offset: 2px; border-radius: 2px; }\n:where(.ec-table-scroll) { overflow-x: auto; margin-top: 8px; }\n:where(.ec-table table) { border-collapse: collapse; width: 100%; font-variant-numeric: tabular-nums; }\n:where(.ec-table th, .ec-table td) { text-align: left; padding: 4px 10px 4px 0; border-bottom: 1px solid var(--ec-grid, ${TOKENS.grid}); font-weight: 400; }\n:where(.ec-table thead th) { color: var(--ec-text-muted, ${TOKENS[\"text-muted\"]}); font-size: 12px; font-weight: 600; }\n:where(.ec-table .ec-num) { text-align: right; }\n:where(.ec-table-caption, .ec-visually-hidden) { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; border: 0; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }\n`;\n\nconst MARKER = \"data-expressive-charts\";\n\n/** The stylesheet's text: what's injected, and what the build writes to dist/expressive-charts.css. */\nexport const stylesheet: string = STYLES;\n\n/** How the stylesheet reaches the page. */\nexport interface StyleOptions {\n /** Set on the injected `<style>`, for a Content-Security-Policy that allows styles by nonce. */\n readonly nonce?: string | undefined;\n /** false: inject nothing; the page loads expressive-charts/style.css itself. Default true. */\n readonly injectStyles?: boolean | undefined;\n}\n\n/**\n * Page-wide, like the stylesheet itself, which is injected once per document by whatever is created\n * first (a chart, an adapter, a control). Set with configure().\n */\nexport const styleOptions: { nonce?: string | undefined; injectStyles?: boolean | undefined } = {};\n\n/** Adds the shared stylesheet to the document once, unless the page loads it itself. */\nexport function injectStyles(doc: Document): void {\n if (styleOptions.injectStyles === false || doc.querySelector(`style[${MARKER}]`)) return;\n const style = doc.createElement(\"style\");\n style.setAttribute(MARKER, \"\");\n // Before the element is connected: CSP checks the nonce when the stylesheet is created.\n if (styleOptions.nonce) style.setAttribute(\"nonce\", styleOptions.nonce);\n style.textContent = STYLES;\n (doc.head ?? doc.documentElement).appendChild(style);\n}\n","// Categorical colours follow the entity: a key keeps its palette slot through sorts, filters and\n// updates, and charts can share an assignment so the same entity has the same colour in both.\n\nimport { PALETTE_SIZE } from \"./render/theme\";\n\nexport interface ColorAssignment {\n /** The palette slot (1–8) for a key: its pinned slot, or the next free one the first time it's seen. Never reassigned. */\n slot(key: string): number;\n}\n\n/** `fixed` pins slots, as in the prototype's `{ goals: 1, assists: 4 }`. Other keys take free slots in the order they're first seen. */\nexport function colorAssignment(fixed: Readonly<Record<string, number>> = {}): ColorAssignment {\n const slots = new Map<string, number>();\n for (const [key, slot] of Object.entries(fixed)) {\n if (!Number.isInteger(slot) || slot < 1 || slot > PALETTE_SIZE) {\n throw new RangeError(`colorAssignment: the slot for \"${key}\" must be a whole number from 1 to ${PALETTE_SIZE}, got ${String(slot)}.`);\n }\n slots.set(key, slot);\n }\n return {\n slot(key) {\n let slot = slots.get(key);\n if (slot === undefined) {\n const used = new Set(slots.values());\n slot = 1;\n while (used.has(slot) && slot <= PALETTE_SIZE) slot++;\n // Every slot taken: reuse them in turn.\n if (slot > PALETTE_SIZE) slot = (slots.size % PALETTE_SIZE) + 1;\n slots.set(key, slot);\n }\n return slot;\n }\n };\n}\n\n/** The `colors` option as an assignment: a shared one as is, a record as pinned slots. */\nexport function toColorAssignment(colors: ColorAssignment | Readonly<Record<string, number>> | undefined): ColorAssignment {\n if (colors && typeof (colors as ColorAssignment).slot === \"function\") return colors as ColorAssignment;\n return colorAssignment(colors as Readonly<Record<string, number>> | undefined);\n}\n","// The chart's legend: a swatch and a name for each series (bars, when there's more than one) or each\n// category (a donut's slices), above the chart, then any entries the page adds for colours its effects\n// draw. Swatches take their colours from the chart's ColorAssignment, so an entry keeps its colour\n// through every change, and a page's entries from their own colour; the names (the series' labels, the\n// categories or the page's labels) are in the theme's text colour, never a series colour.\n\nimport type { ColorAssignment } from \"./colors\";\nimport { cssColor, markColorStyles, seriesColors } from \"./render/theme\";\nimport type { ChartOptions, LegendEntry, LegendOptions } from \"./types\";\n\n/** The `legend` option. */\nexport type LegendOption = ChartOptions<unknown>[\"legend\"];\n\nexport interface Legend {\n /**\n * Shows `series` in order, each named by its label, then the page's entries from `option`; or\n * removes the legend when `option` is false, or when it would list fewer than two entries in all.\n */\n update(series: readonly { readonly series: string; readonly label: string }[], colors: ColorAssignment, option: LegendOption): void;\n /**\n * Shows `categories` in order, each coloured by its key and named by its category, then the page's\n * entries; or removes the legend when there are no categories or `option` is false. One category is\n * listed too: it names the colour.\n */\n categories(categories: readonly { readonly key: string; readonly label: string }[], colors: ColorAssignment, option: LegendOption): void;\n destroy(): void;\n}\n\n/** Throws on a `legend` option that isn't true, false or an object of valid entries. `chart` names the chart in the message. */\nexport function checkLegendOption(option: unknown, chart: string): void {\n if (option === undefined || typeof option === \"boolean\") return;\n const fail = (what: string): never => {\n throw new TypeError(`${chart}: ${what}`);\n };\n if (typeof option !== \"object\" || option === null || Array.isArray(option)) fail(\"legend must be true or false, or an object with the entries the page adds.\");\n const { entries } = option as LegendOptions;\n if (entries === undefined) return;\n if (!Array.isArray(entries)) fail(\"legend.entries must be an array of { label, color }.\");\n entries.forEach((entry: Partial<LegendEntry> | null, i: number) => {\n const { label, color } = typeof entry === \"object\" && entry !== null ? entry : fail(`legend.entries[${i}] must be an object with a label and a color.`);\n if (typeof label !== \"string\" || label.trim() === \"\") fail(`legend.entries[${i}].label must be a non-empty string: the entry's name.`);\n if (typeof color !== \"string\" || color.trim() === \"\") fail(`legend.entries[${i}].color must be a theme token or a CSS colour.`);\n if (color === \"mark\" || color === \"mark-strong\") fail(`legend.entries[${i}].color can't be \"${color}\": an entry has no mark. Use a theme token or a CSS colour.`);\n });\n}\n\n/** The entries the page adds, from the option. */\nconst extras = (option: LegendOption): readonly LegendEntry[] => (typeof option === \"object\" ? (option.entries ?? []) : []);\n\n/** The legend for a chart's <svg>: made when it's first needed, just before the <svg>. */\nexport function chartLegend(svg: SVGSVGElement): Legend {\n let legend: HTMLDivElement | undefined;\n /** What the legend shows: the entries, their names and their colours. */\n let drawn = \"\";\n\n const remove = (): void => {\n legend?.remove();\n legend = undefined;\n drawn = \"\";\n };\n\n /**\n * Draws the chart's entries, then the page's; `attribute` names each of the chart's entries' key on\n * its element (data-series or data-key).\n */\n const draw = (entries: readonly { readonly key: string; readonly label: string }[], colors: ColorAssignment, attribute: string, more: readonly LegendEntry[]): void => {\n const items = [\n ...entries.map(({ key, label }) => ({ key, label, styles: markColorStyles(seriesColors(colors.slot(key))) })),\n ...more.map(({ label, color }) => ({ key: undefined, label, styles: { \"--ec-mark\": cssColor(color) } }))\n ];\n const doc = svg.ownerDocument;\n legend ??= Object.assign(doc.createElement(\"div\"), { className: \"ec-legend\" });\n if (legend.nextSibling !== svg) svg.before(legend);\n const id = JSON.stringify([attribute, items]);\n if (id === drawn) return;\n drawn = id;\n legend.replaceChildren(\n ...items.map(({ key, label: text, styles }) => {\n const item = doc.createElement(\"span\");\n item.className = \"ec-legend-item\";\n if (key !== undefined) item.setAttribute(attribute, key);\n // The swatch reads --ec-mark, as a mark's segments do.\n for (const [property, value] of Object.entries(styles)) if (value !== undefined) item.style.setProperty(property, value);\n const swatch = doc.createElement(\"span\");\n swatch.className = \"ec-legend-swatch\";\n const label = doc.createElement(\"span\");\n label.className = \"ec-legend-label\";\n label.textContent = text;\n item.append(swatch, label);\n return item;\n })\n );\n };\n\n return {\n update(series, colors, option) {\n const more = extras(option);\n if (option === false || series.length + more.length < 2) remove();\n else draw(series.map(({ series: key, label }) => ({ key, label })), colors, \"data-series\", more);\n },\n categories(categories, colors, option) {\n if (option === false || categories.length === 0) remove();\n else draw(categories, colors, \"data-key\", extras(option));\n },\n destroy: remove\n };\n}\n","// Linked hover (M7 step 4): hovering a mark in one chart or attachment hovers the marks that share its\n// linking value in the others, with `source: \"linked\"`. It isn't an effect, since it hovers other\n// marks: it lives with the charts, as hover dimming does. Each chart and attachment registers its hover\n// here when it's made, keyed by its handle, so a link can hover given marks without focus. A chart\n// switch (M9 step 2) registers one made of its views' charts' hovers: the view on show's, while it\n// rests. Nothing link-specific is public on the handles.\n\nimport type { MarkGeometry } from \"../core\";\nimport { report } from \"../core/report\";\nimport type { RunInput } from \"../core/runner\";\nimport type { MarkEvent, MarkEvents } from \"./types\";\n\n/** What a link takes: a chart (barChart, donutChart, lineChart), a chartSwitch or an attachment (expressive, fromVegaView), with rows D. */\nexport interface LinkSource<D> {\n on(type: \"hover\", listener: (event: MarkEvents<D>[\"hover\"]) => void): () => void;\n marks(): readonly MarkGeometry[];\n}\n\n/** The rows of the sources in S: each chart's, switch's and attachment's, as a union. */\nexport type RowsOf<S> = S extends LinkSource<infer D> ? D : never;\n\nexport interface LinkOptions<D> {\n /**\n * A mark's linking value, given the mark and its data as a hover event has them. Default: its last\n * sample's `at` if it has one (a line point's x), else its key (a bar's or a slice's category).\n * Values are compared as strings, a Date by its ISO string, as keys are. Undefined or null links\n * nothing, and so does a throw (reported).\n */\n readonly by?: (event: Pick<MarkEvent<D>, \"mark\" | \"data\">) => unknown;\n /** Whether linked marks play their chart's hover effect. Default true; false keeps them to emphasis and dimming. */\n readonly effects?: boolean;\n}\n\nexport interface Link {\n /** Ends the link: linked hovers end, and each source can be linked again. The sources' own hovers go on. */\n destroy(): void;\n}\n\n/** A source's hover as a link drives it: what chartHover and expressive() register for their handle. */\nexport interface LinkPort {\n /** The live targets, in visual order, each with its marks as on screen: what their linking values are read from. */\n targets(): readonly { readonly key: string; readonly marks: readonly RunInput[] }[];\n /**\n * Ends the hover there was, then hovers the live targets `keys` for a link: their marks' emphasis,\n * the others' dimming and, with `effects`, their hover effects, with \"linked\" events. No tooltip,\n * focus ring or focus, and nothing is announced. With no keys it only ends the hover.\n */\n hover(keys: readonly string[], effects: boolean): void;\n /** Ends a link's hover. The source's own goes on. */\n unlink(): void;\n /** Ends the hover, its own or a link's, as the source's leave() does. */\n leave(): void;\n /** Sets the link that hears its own hovers, or none. False, setting nothing, once the source is destroyed. */\n listen(listener: LinkListener | undefined): boolean;\n /** The hovers it drives, a chart switch's views' charts': while it's in a link, none of them can be in another. */\n readonly parts?: readonly LinkPort[];\n}\n\n/** What a source tells its link. */\nexport interface LinkListener {\n /** Its own hover started, from the pointer, touch or the keyboard, on these marks. */\n hover(marks: readonly RunInput[]): void;\n /** Its own hover ended. */\n leave(): void;\n /** Escape, with focus on it while it shows a link's hover: the link's hover ends, where it started. */\n dismiss(): void;\n /** Its marks can be reached again, in other targets (a chart switch landed): the link's hover from another source, if there is one, shows in them. */\n shown(): void;\n /** It was destroyed. */\n gone(): void;\n}\n\n/** Whether a hover is the source's own, from the pointer, touch or the keyboard: not a link's. */\nexport const own = <H extends { readonly source: string }>(hovered: H | undefined): hovered is H => hovered !== undefined && hovered.source !== \"linked\";\n\nconst ports = new WeakMap<object, LinkPort>();\n/** Ports in a link now, with their parts: a source can be in one at a time. */\nconst linked = new WeakSet<LinkPort>();\n\n/** A port and the ports it drives, which go into a link with it. */\nconst partsOf = (port: LinkPort): readonly LinkPort[] => (port.parts ? [port, ...port.parts] : [port]);\n\n/** Registers a chart's or attachment's hover for its handle, and returns the handle. */\nexport function linkable<T extends object>(port: LinkPort, handle: T): T {\n ports.set(handle, port);\n return handle;\n}\n\n/** The hover registered for a handle: for a handle that wraps another, as fromVegaView's wraps expressive()'s. */\nexport const portOf = (handle: object): LinkPort | undefined => ports.get(handle);\n\n/**\n * Links hover across `sources`: when one is hovered by the pointer, touch or the keyboard, every other\n * hovers its targets with that linking value (a line chart its x, a bar chart its bar), as `source:\n * \"linked\"`, and leaves them when it leaves. The newest hover anywhere in the link is the one shown.\n * A chart switch takes part through its view on show. Throws a TypeError, linking nothing, on a source\n * that isn't a chart, a chart switch or an attachment, or one that's in a link already, a switch's\n * views' charts going with it. A destroyed source drops out.\n */\nexport function link<S extends LinkSource<unknown>>(sources: readonly S[], options: LinkOptions<RowsOf<S>> = {}): Link {\n if (!Array.isArray(sources)) throw new TypeError(\"link needs an array of charts, chart switches and attachments: link([columns, line]).\");\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"link: options must be an object, such as { by: (event) => event.data.datum.week }.\");\n const { by, effects = true } = options;\n if (by !== undefined && typeof by !== \"function\") throw new TypeError(\"link: by must be a function, such as (event) => event.data.datum.week.\");\n if (typeof effects !== \"boolean\") throw new TypeError(`link: effects must be true or false, got ${String(effects)}.`);\n const members: LinkPort[] = [];\n const taken = new Set<LinkPort>();\n for (const source of sources) {\n const port = typeof source === \"object\" && source !== null ? ports.get(source) : undefined;\n if (!port) {\n throw new TypeError(\"link: each source must be a chart (barChart, donutChart or lineChart), a chartSwitch or an attachment (expressive or fromVegaView).\");\n }\n const parts = partsOf(port);\n if (parts.some((part) => linked.has(part) || taken.has(part))) {\n throw new TypeError(\"link: a chart, chart switch or attachment can be in one link at a time, and a chart switch's views' charts go with it. Destroy the link it's in first.\");\n }\n for (const part of parts) taken.add(part);\n members.push(port);\n }\n\n /** The sources still in the link. */\n const live = new Set<LinkPort>();\n /** The source whose own hover the link shows. */\n let origin: LinkPort | undefined;\n /** The linking values of its hovered marks. */\n let values: ReadonlySet<string | undefined> = new Set();\n\n /** A mark's linking value as a string, or undefined for none. */\n function valueOf(input: RunInput): string | undefined {\n let value: unknown;\n if (by) {\n try {\n value = by(input as RunInput<RowsOf<S>>);\n } catch (error) {\n report(error);\n return undefined;\n }\n } else {\n const { samples } = input.data;\n value = samples[samples.length - 1]?.at ?? input.mark.key;\n }\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? undefined : value.toISOString();\n return value === undefined || value === null ? undefined : String(value);\n }\n\n /** The keys of the port's targets that have a mark with one of `shown`'s values. */\n function keysIn(port: LinkPort, shown: ReadonlySet<string | undefined>): string[] {\n if (shown.size === 0) return [];\n /** Whether a target has a mark with one of the hovered marks' values. */\n const matches = (target: readonly RunInput[]): boolean => target.some((mark) => {\n const value = valueOf(mark);\n return value !== undefined && shown.has(value);\n });\n return port.targets().flatMap((target) => (matches(target.marks) ? [target.key] : []));\n }\n\n function hovered(from: LinkPort, marks: readonly RunInput[]): void {\n origin = from;\n const shown = new Set(marks.map(valueOf));\n shown.delete(undefined);\n values = shown;\n for (const port of live) {\n if (port === from) continue;\n port.hover(keysIn(port, shown), effects);\n // A listener started another hover meanwhile: that one is shown.\n if (origin !== from) return;\n }\n }\n\n function left(from: LinkPort): void {\n if (origin !== from) return;\n origin = undefined;\n values = new Set();\n for (const port of live) port.unlink();\n }\n\n for (const port of members) {\n const listening = port.listen({\n hover: (marks) => hovered(port, marks),\n leave: () => left(port),\n dismiss() {\n const from = origin;\n from?.leave();\n if (from) left(from);\n },\n shown() {\n if (origin !== undefined && origin !== port && live.has(port)) port.hover(keysIn(port, values), effects);\n },\n gone() {\n live.delete(port);\n for (const part of partsOf(port)) linked.delete(part);\n left(port);\n }\n });\n if (!listening) continue;\n live.add(port);\n for (const part of partsOf(port)) linked.add(part);\n }\n\n return {\n destroy() {\n for (const port of live) {\n port.listen(undefined);\n port.unlink();\n for (const part of partsOf(port)) linked.delete(part);\n }\n live.clear();\n origin = undefined;\n values = new Set();\n }\n };\n}\n","// A chart's motion: the page-wide one, the author's own Motion, or a mode string. A mode is a per-chart\n// author default, like setMode(): the viewer's choice and the device's reduced-motion setting still win.\n\nimport { defaultScaling, scaleDuration, type Motion, type MotionMode, type MotionView } from \"../core\";\n\nexport type ChartMotion = MotionView & Pick<Motion, \"subscribe\">;\n\nconst MODES: readonly MotionMode[] = [\"presentation\", \"analysis\", \"off\"];\n\nexport function chartMotion(option: Motion | MotionMode | undefined, page: Motion): ChartMotion {\n if (option === undefined) return page;\n if (typeof option !== \"string\") return option;\n if (!MODES.includes(option)) throw new TypeError(`Unknown motion mode \"${String(option)}\". Use one of: ${MODES.join(\", \")}.`);\n const effective = (): MotionMode => page.viewerChoice ?? (page.prefersReduced ? \"off\" : option);\n return {\n get mode() {\n return effective();\n },\n get staged() {\n return effective() === \"presentation\";\n },\n duration(base, timing = \"transition\") {\n const mode = effective();\n return mode === \"off\" ? 0 : scaleDuration(base, defaultScaling[mode][timing]);\n },\n subscribe: (listener) => page.subscribe(listener)\n };\n}\n","// The focus ring and halos drawn above the marks, masked to outside the mark: they show evenly on every\n// side of marks that touch (a donut's slices), and never cover the mark itself. expressive() draws its\n// ring and halos this way, since its overlay is above the host's marks, and so does donutChart.\n\nimport type { MarkStyle, Matrix, Outline } from \"../../core\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { cssColor } from \"./theme\";\n\n/** The focus ring's px: a gap around the mark, then the ring, as on barChart. */\nexport const RING_GAP = 2;\nexport const RING = 2;\n\n/** What the focus ring goes round: the mark's outline as it is on screen, and an effect's transform on it. */\nexport interface RingTarget {\n readonly outline: Outline;\n /** An open outline (a line) is its stroke's centre: the gap starts at the stroke's edge. */\n readonly thickness: number;\n readonly transform?: Matrix | undefined;\n}\n\nexport interface MaskedRing {\n /** Draws the ring round `target`, or hides it. */\n draw(target: RingTarget | undefined): void;\n}\n\n/** Focus-ring masks made in each document, for their ids: a page's markup doesn't depend on other pages. */\nconst ringMasks = new WeakMap<Document, number>();\n/** Halo masks, for their ids. */\nlet haloMasks = 0;\n\n/**\n * The focus ring, appended to `parent`: a 2 px ring in --ec-focus, 2 px out from the mark. It's a\n * stroke on the outline, masked to outside the mark and its gap, so it can't cover data or merge with\n * a mark in the focus colour. The gap is left clear rather than painted, since what's behind may be\n * any colour. The mask is in the ring's own user space, so the ring takes an effect's transform whole.\n */\nexport function maskedRing(parent: SVGGElement): MaskedRing {\n const doc = parent.ownerDocument;\n const number = (ringMasks.get(doc) ?? 0) + 1;\n ringMasks.set(doc, number);\n const mask = svgElement(\"mask\", { id: `ec-focus-mask-${number}`, maskUnits: \"userSpaceOnUse\", x: -1e5, y: -1e5, width: 2e5, height: 2e5 }, parent);\n svgElement(\"rect\", { x: -1e5, y: -1e5, width: 2e5, height: 2e5, fill: \"white\" }, mask);\n const hole = svgElement(\"path\", { stroke: \"black\", \"stroke-linejoin\": \"round\" }, mask);\n const ring = svgElement(\"path\", { class: \"ec-focus-ring\", visibility: \"hidden\", \"stroke-linejoin\": \"round\", mask: `url(#${mask.id})` }, parent);\n setStyles(ring, { fill: \"none\", stroke: cssColor(\"focus\") });\n return {\n draw(target) {\n if (!target) {\n setAttributes(ring, { visibility: \"hidden\" });\n return;\n }\n const { outline, thickness, transform } = target;\n // The hole isn't filled for an open outline: a fill would close the line into a polygon and hide\n // the ring along its inside.\n const stroke = outline.closed ? 0 : thickness;\n setAttributes(hole, { d: outline.d, fill: outline.closed ? \"black\" : \"none\", \"stroke-width\": stroke + 2 * RING_GAP });\n setAttributes(ring, {\n d: outline.d,\n \"stroke-width\": stroke + 2 * (RING_GAP + RING),\n transform: transform && transformAttribute(transform),\n visibility: undefined\n });\n }\n };\n}\n\n/** One part of a mark the halo goes round: its outline, and its own colour (what the halo is drawn in by default). */\nexport interface HaloPart {\n readonly d: string;\n readonly color: string | undefined;\n /** An open outline (a line) is its stroke's centre: the stroke's width. Undefined for a closed outline. */\n readonly stroke?: number | undefined;\n}\n\nexport interface MaskedHalo {\n /**\n * Strokes each part's outline in a group of its own in `container`, at `width` (half of it outside\n * the mark), masked to outside the mark, so it shows only where it would behind the mark. Around an\n * open outline, the mask cuts out the stroke, as the ring's does, and the halo is stroked at the\n * stroke's width plus its own with round caps, so as much of it shows as round a closed mark, ends\n * included, as svgMarkHandle's halo behind a line does. Moved with the mark's `transform`. No halo,\n * no container or no parts removes it.\n */\n paint(container: SVGGElement | undefined, parts: readonly HaloPart[], halo: MarkStyle[\"halo\"], transform: Matrix | undefined): void;\n remove(): void;\n}\n\nexport function maskedHalo(): MaskedHalo {\n let group: SVGGElement | undefined;\n const remove = (): void => {\n group?.remove();\n group = undefined;\n };\n return {\n paint(container, parts, halo, transform) {\n if (!halo || !container || parts.length === 0) {\n remove();\n return;\n }\n if (!group || group.parentNode !== container) {\n group?.remove();\n group = svgElement(\"g\", { class: \"ec-halo\" }, container);\n }\n group.textContent = \"\";\n const id = `ec-halo-mask-${++haloMasks}`;\n const mask = svgElement(\"mask\", { id, maskUnits: \"userSpaceOnUse\", x: -1e5, y: -1e5, width: 2e5, height: 2e5 }, group);\n svgElement(\"rect\", { x: -1e5, y: -1e5, width: 2e5, height: 2e5, fill: \"white\" }, mask);\n for (const part of parts) {\n // Not filled for an open outline: a fill would close the line into a polygon and mask the halo along its inside.\n const cut = part.stroke === undefined ? { fill: \"black\" } : { fill: \"none\", stroke: \"black\", \"stroke-width\": part.stroke, \"stroke-linejoin\": \"round\" };\n svgElement(\"path\", { d: part.d, ...cut }, mask);\n }\n setAttributes(group, { transform: transform && transformAttribute(transform) });\n for (const part of parts) {\n const open = part.stroke !== undefined;\n const path = svgElement(\n \"path\",\n { d: part.d, \"stroke-width\": halo.width + (part.stroke ?? 0), \"stroke-opacity\": halo.opacity, \"stroke-linejoin\": \"round\", \"stroke-linecap\": open ? \"round\" : undefined, mask: `url(#${id})` },\n group\n );\n setStyles(path, { fill: \"none\", stroke: halo.color === undefined ? (part.color ?? cssColor(\"mark\")) : cssColor(halo.color) });\n }\n },\n remove\n };\n}\n","// The drawing API's MarkHandle in SVG: effects restyle a mark through it (transform, opacity, emphasis,\n// halo). The runner merges every live run's style before calling it.\n\nimport type { MarkHandle, MarkStyle } from \"../../core\";\nimport { mergeFields } from \"../../core/merge\";\nimport { maskedHalo } from \"./outside\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { cssColor, type SeriesColors } from \"./theme\";\n\n/** One part of a mark: a filled bar segment or slice, or a stroked line. */\nexport interface StyledPart {\n readonly element: SVGPathElement;\n /** The part's outline, which the halo follows. */\n readonly d: string;\n readonly colors: SeriesColors;\n /** False for parts too short to see (a zero value): they get no halo. */\n readonly visible: boolean;\n /**\n * For an open outline (a line), which is stroked rather than filled: the stroke's width. Emphasis\n * then mixes the stroke's colour, and the halo is stroked behind it this much wider than its own\n * width, so as much of it shows on each side as round a closed mark.\n */\n readonly open?: { readonly width: number };\n}\n\n/** What a style applies to: the mark's body group (it moves with `transform`) and its parts. */\nexport interface StyleTarget {\n readonly body: SVGGElement;\n readonly parts: readonly StyledPart[];\n}\n\nexport interface SvgMarkHandleOptions {\n /**\n * Where halos go instead of behind the mark: a group above the marks, where each is masked to\n * outside its mark (render/outside.ts). For marks that touch, such as slices, so a halo shows evenly\n * on every side instead of under the neighbour drawn after it.\n */\n readonly halos?: () => SVGGElement | undefined;\n}\n\nexport interface SvgMarkHandle extends MarkHandle {\n readonly style: MarkStyle;\n /** Applies the current style again, after the mark was redrawn (new parts or outlines). */\n repaint(): void;\n}\n\n/**\n * - `transform` is in chart space, on the body, so labels and the hit area stay put.\n * - `opacity` is on the body; it multiplies with the built-in hover dimming.\n * - `emphasis` mixes each part's colour toward its strong colour, without the CSS hover transition\n * (effects animate it themselves): its fill, or an open part's stroke.\n * - `halo` strokes each visible part's outline behind the mark: `width` is the stroke width, so half\n * of it shows outside the mark. An open part's halo is its own width wider, with round caps, so it\n * goes round the line's ends too. With `halos`, it's drawn there instead, masked to outside the mark\n * (outside an open part's stroke).\n */\nexport function svgMarkHandle(target: () => StyleTarget | undefined, options: SvgMarkHandleOptions = {}): SvgMarkHandle {\n let style: MarkStyle = {};\n let halo: SVGGElement | undefined;\n const above = options.halos && maskedHalo();\n\n const repaint = (): void => {\n const current = target();\n if (!current) return;\n const { body, parts } = current;\n setAttributes(body, {\n transform: style.transform && transformAttribute(style.transform),\n opacity: style.opacity\n });\n const emphasis = style.emphasis;\n for (const part of parts) {\n setStyles(part.element, {\n [part.open ? \"stroke\" : \"fill\"]: emphasis === undefined ? undefined : mix(part.colors, emphasis),\n transition: emphasis === undefined ? undefined : \"none\"\n });\n }\n paintHalo(body, parts);\n };\n\n const paintHalo = (body: SVGGElement, parts: readonly StyledPart[]): void => {\n const spec = style.halo;\n if (above) {\n const visible = parts.flatMap((part) => (part.visible ? [{ d: part.d, color: part.colors.color, ...(part.open ? { stroke: part.open.width } : {}) }] : []));\n above.paint(options.halos?.(), visible, spec, style.transform);\n return;\n }\n if (!spec) {\n halo?.remove();\n halo = undefined;\n return;\n }\n if (!halo || halo.parentNode !== body) {\n halo?.remove();\n halo = svgElement(\"g\", { class: \"ec-halo\" }, body);\n body.insertBefore(halo, body.firstChild);\n }\n const visible = parts.filter((part) => part.visible);\n while (halo.childElementCount > visible.length) halo.lastElementChild?.remove();\n visible.forEach((part, index) => {\n const path = (halo!.children[index] as SVGPathElement | undefined) ?? svgElement(\"path\", { \"stroke-linejoin\": \"round\" }, halo);\n setAttributes(path, {\n d: part.d,\n \"stroke-width\": spec.width + (part.open?.width ?? 0),\n \"stroke-opacity\": spec.opacity,\n \"stroke-linecap\": part.open ? \"round\" : undefined\n });\n setStyles(path, { fill: \"none\", stroke: spec.color === undefined ? part.colors.color : cssColor(spec.color) });\n });\n };\n\n return {\n get style() {\n return style;\n },\n set(next) {\n style = mergeFields(style, next);\n repaint();\n },\n reset() {\n style = {};\n repaint();\n },\n repaint\n };\n}\n\nfunction mix(colors: SeriesColors, emphasis: number): string {\n const amount = Math.min(1, Math.max(0, emphasis));\n if (amount === 0) return colors.color;\n if (amount === 1) return colors.strong;\n return `color-mix(in srgb, ${colors.strong} ${Math.round(amount * 1000) / 10}%, ${colors.color})`;\n}\n","// The drawing API's Layer in SVG: one run's overlay group. See src/core/contracts/drawing.ts.\n\nimport { matrix, type Icon, type IconHandle, type IconShape, type Layer, type Matrix, type Paint, type PathHandle, type TextHandle, type TextStyle } from \"../../core\";\nimport { mergeFields } from \"../../core/merge\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { cssColor } from \"./theme\";\n\n/** The class of the groups that hold a run's paths and icons when they follow their mark. */\nexport const FOLLOW = \"ec-follow\";\n\nlet clipIds = 0;\n\n/**\n * Draws into `group`. Handles keep working on removed elements, so calls after a clear are harmless.\n *\n * With `follow`, the mark's transform now, paths and icons go in a `FOLLOW` group that takes it, so\n * they move (and dim) with the mark's body, while text stays put, as the mark's labels do. Text drawn\n * between them starts another group, so everything stays in the order it was drawn.\n */\nexport function svgLayer(group: SVGGElement, follow?: () => Matrix | undefined): Layer {\n const into = (): SVGGElement => {\n if (!follow) return group;\n const last = group.lastElementChild;\n if (last?.getAttribute(\"class\") === FOLLOW) return last as SVGGElement;\n const m = follow();\n return svgElement(\"g\", { class: FOLLOW, transform: m && transformAttribute(m) }, group);\n };\n return {\n icon(icon, options) {\n const size = options?.size;\n if (size !== undefined && !(size >= 0)) throw new RangeError(`layer.icon: size must be a non-negative number, got ${String(size)}.`);\n // Hidden until the first place().\n const placed = svgElement(\"g\", { class: \"ec-icon\", \"data-icon\": icon.name, visibility: \"hidden\" }, into());\n // The size rule: scale by size / icon.size about the anchor, in icon space, before place().\n const k = size === undefined || !(icon.size > 0) ? 1 : size / icon.size;\n const body = k === 1 ? placed : svgElement(\"g\", { transform: transformAttribute(matrix.scale(k, k, icon.anchor)) }, placed);\n for (const shape of icon.shapes) drawShape(shape, body);\n const handle: IconHandle = {\n place(transform) {\n setAttributes(placed, { transform: transformAttribute(transform), visibility: undefined });\n },\n remove: () => placed.remove()\n };\n return handle;\n },\n\n path(d, paint) {\n const element = svgElement(\"path\", { class: \"ec-path\", d }, into());\n let current: Paint = { ...paint };\n paintPath(element, current);\n const handle: PathHandle = {\n update(next, nextPaint) {\n element.setAttribute(\"d\", next);\n if (nextPaint) {\n current = mergeFields(current, nextPaint);\n paintPath(element, current);\n }\n },\n remove: () => element.remove()\n };\n return handle;\n },\n\n text(content, style) {\n const element = svgElement(\"text\", { class: \"ec-text\" }, group);\n element.textContent = content;\n let current: TextStyle = { ...style };\n styleText(element, current);\n const handle: TextHandle = {\n update(nextStyle, nextContent) {\n current = mergeFields(current, nextStyle);\n styleText(element, current);\n if (nextContent !== undefined) element.textContent = nextContent;\n },\n remove: () => element.remove()\n };\n return handle;\n }\n };\n}\n\n/**\n * One path per shape. Unset fill or stroke draws none; the width is in icon units, so it scales with the icon.\n * The fill rule and the opacities are SVG's own, so unset ones are left to SVG's defaults: nonzero, and 1.\n */\nfunction drawShape(shape: IconShape, parent: SVGGElement): void {\n let clip: string | undefined;\n if (shape.clip !== undefined) {\n // userSpaceOnUse (the default) puts the clip path in the shape's own space: icon space.\n clip = `ec-clip-${++clipIds}`;\n const clipPath = svgElement(\"clipPath\", { id: clip }, parent);\n svgElement(\"path\", { d: shape.clip }, clipPath);\n }\n const element = svgElement(\n \"path\",\n {\n d: shape.d,\n \"clip-path\": clip && `url(#${clip})`,\n \"stroke-width\": shape.stroke === undefined ? undefined : (shape.width ?? 1),\n \"stroke-linecap\": shape.linecap,\n \"stroke-linejoin\": shape.linejoin,\n \"fill-rule\": shape.fillRule,\n opacity: shape.opacity,\n \"fill-opacity\": shape.fillOpacity,\n \"stroke-opacity\": shape.strokeOpacity\n },\n parent\n );\n setStyles(element, {\n // SVG's default fill is black, so \"none\" is set explicitly.\n fill: shape.fill === undefined ? \"none\" : cssColor(shape.fill),\n stroke: shape.stroke === undefined ? undefined : cssColor(shape.stroke)\n });\n}\n\n/** Overlay paths are unfilled unless a fill is given. */\nfunction paintPath(element: SVGPathElement, paint: Paint): void {\n setAttributes(element, {\n \"stroke-width\": paint.stroke === undefined ? undefined : (paint.width ?? 1),\n opacity: paint.opacity,\n \"stroke-linecap\": paint.linecap,\n \"stroke-linejoin\": \"round\"\n });\n setStyles(element, {\n fill: paint.fill === undefined ? \"none\" : cssColor(paint.fill),\n stroke: paint.stroke === undefined ? undefined : cssColor(paint.stroke)\n });\n}\n\nfunction styleText(element: SVGTextElement, style: TextStyle): void {\n setAttributes(element, { x: style.at.x, y: style.at.y, \"text-anchor\": style.anchor ?? \"start\", opacity: style.opacity });\n setStyles(element, { fill: cssColor(style.color ?? \"text\") });\n}\n","// The runner's surface in SVG: one overlay group per run, above the marks, and the marks' style handles.\n// A run's paths and icons follow its mark: they take the transform an effect gives the mark's body,\n// and dim with it while another mark is hovered. Its text stays put, as the mark's labels do.\n\nimport type { MarkHandle, Matrix } from \"../../core\";\nimport type { RunnerSurface } from \"../../core/runner\";\nimport { FOLLOW, svgLayer } from \"./layer\";\nimport { setAttributes, setStyles, svgElement, transformAttribute } from \"./svg\";\nimport { markColorStyles, type SeriesColors } from \"./theme\";\n\nexport interface SvgSurfaceOptions {\n /** Where runs draw: a group above the marks, in chart coordinates. */\n readonly overlay: SVGGElement;\n /** The mark's own style handle. */\n mark(key: string): MarkHandle;\n /** The colours the \"mark\" token means in this mark's groups. */\n colors(key: string): SeriesColors | undefined;\n}\n\nexport interface SvgSurface extends RunnerSurface {\n /** Sets the \"mark\" colours again on the key's live groups, after the mark's colours changed (a new palette, a different first series). */\n recolor(key: string): void;\n /** Hides the key's groups, and any it gets later, or shows them again: a line chart's points past its reveal. */\n hide(key: string, hidden: boolean): void;\n /**\n * Gives the key's groups, and any it gets later, the hover's emphasis (`ec-hot`), or takes it away:\n * inside `.ec-hovering`, the paths and icons of the groups without it dim, as their marks do.\n */\n hot(key: string, on: boolean): void;\n}\n\nexport function svgSurface(options: SvgSurfaceOptions): SvgSurface {\n const { overlay } = options;\n const orders = new WeakMap<Element, number>();\n /** Live groups by mark key. */\n const groups = new Map<string, Set<SVGGElement>>();\n const hidden = new Set<string>();\n const hotKeys = new Set<string>();\n /** Each mark's transform, as an effect set it on its body. */\n const transforms = new Map<string, Matrix>();\n const follow = (key: string, transform: Matrix | undefined): void => {\n if (transform) transforms.set(key, transform);\n else if (!transforms.delete(key)) return;\n for (const group of groups.get(key) ?? []) {\n for (const child of Array.from(group.children)) if (child.getAttribute(\"class\") === FOLLOW) setAttributes(child, { transform: transform && transformAttribute(transform) });\n }\n };\n return {\n group(key, slot, order) {\n const group = svgElement(\"g\", { class: hotKeys.has(key) ? \"ec-run ec-hot\" : \"ec-run\", \"data-key\": key, \"data-slot\": slot, visibility: hidden.has(key) ? \"hidden\" : undefined }, overlay);\n setStyles(group, markColorStyles(options.colors(key)));\n orders.set(group, order);\n // Stacked by start order, not by when the group was asked for: a decoration may first draw late.\n const above = Array.from(overlay.children).find((child) => (orders.get(child) ?? -Infinity) > order);\n overlay.insertBefore(group, above ?? null);\n let live = groups.get(key);\n if (!live) groups.set(key, (live = new Set()));\n live.add(group);\n const owner = live;\n return {\n ...svgLayer(group, () => transforms.get(key)),\n clear() {\n group.remove();\n owner.delete(group);\n if (owner.size === 0 && groups.get(key) === owner) groups.delete(key);\n }\n };\n },\n mark(key) {\n const handle = options.mark(key);\n return {\n set(style) {\n handle.set(style);\n if (\"transform\" in style) follow(key, style.transform);\n },\n reset() {\n handle.reset();\n follow(key, undefined);\n }\n };\n },\n recolor(key) {\n const live = groups.get(key);\n if (!live) return;\n const styles = markColorStyles(options.colors(key));\n for (const group of live) setStyles(group, styles);\n },\n hide(key, hide) {\n if (hide) hidden.add(key);\n else hidden.delete(key);\n for (const group of groups.get(key) ?? []) setAttributes(group, { visibility: hide ? \"hidden\" : undefined });\n },\n hot(key, on) {\n if (on) hotKeys.add(key);\n else hotKeys.delete(key);\n for (const group of groups.get(key) ?? []) group.classList.toggle(\"ec-hot\", on);\n }\n };\n}\n","// Series names for people. A series is named after its field (\"goals\"; a value read by a function is\n// \"value\"); `seriesLabels` gives it a name to show instead, used as given wherever the chart names it.\n\nimport type { ChartOptions } from \"./types\";\n\n/** The `seriesLabels` option. */\nexport type SeriesLabels = ChartOptions<unknown>[\"seriesLabels\"];\n\n/** The series' name for people: its label, or its own name. Only the object's own keys count, so \"constructor\" is just a series. */\nexport function seriesLabel(labels: SeriesLabels, series: string): string {\n return labels !== undefined && Object.prototype.hasOwnProperty.call(labels, series) ? (labels[series] ?? series) : series;\n}\n\n/** Throws on a `seriesLabels` option that isn't an object of names. `chart` names the chart in the message. */\nexport function checkSeriesLabels(option: unknown, chart: string): void {\n if (option === undefined) return;\n if (typeof option !== \"object\" || option === null || Array.isArray(option)) throw new TypeError(`${chart}: seriesLabels must be an object of names by series, as { goals: \"Goals\" }.`);\n for (const [series, label] of Object.entries(option)) {\n if (typeof label !== \"string\" || label.trim() === \"\") throw new TypeError(`${chart}: seriesLabels.${series} must be a name, not ${typeof label === \"string\" ? \"blank\" : String(label)}.`);\n }\n}\n","// A chart's mark events: the listeners `on()` adds, and emitting to them. A listener that throws is\n// reported, and the others still hear the event.\n\nimport { report } from \"../../core/report\";\nimport type { Chart, MarkEvents } from \"../types\";\n\ntype Listeners<D> = { [K in keyof MarkEvents<D>]: Set<(event: MarkEvents<D>[K]) => void> };\n\nexport interface ChartEvents<D> {\n emit<K extends keyof MarkEvents<D>>(type: K, event: MarkEvents<D>[K]): void;\n /** One event per mark, each given its place in the batch. `read` makes each one as it's emitted. */\n emitEach<K extends keyof MarkEvents<D>, T>(type: K, marks: readonly T[], read: (mark: T) => Omit<MarkEvents<D>[K], \"batch\">): void;\n /** The chart's `on()`: throws on an event it doesn't have. */\n readonly on: Chart<D, unknown>[\"on\"];\n /** Drops every listener. */\n clear(): void;\n}\n\n/** `chart` names the chart in errors. */\nexport function chartEvents<D>(chart: string): ChartEvents<D> {\n const listeners: Listeners<D> = { enter: new Set(), update: new Set(), exit: new Set(), hover: new Set(), leave: new Set() };\n\n function emit<K extends keyof MarkEvents<D>>(type: K, event: MarkEvents<D>[K]): void {\n for (const listener of [...listeners[type]]) {\n try {\n listener(event);\n } catch (error) {\n report(error);\n }\n }\n }\n\n return {\n emit,\n emitEach(type, marks, read) {\n marks.forEach((mark, index) => emit(type, { ...read(mark), batch: { index, count: marks.length } } as MarkEvents<D>[typeof type]));\n },\n on(type, listener) {\n const set = listeners[type] as Set<typeof listener> | undefined;\n if (!set) throw new TypeError(`${chart}: unknown event \"${String(type)}\". Use one of: ${Object.keys(listeners).join(\", \")}.`);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n },\n clear() {\n for (const set of Object.values(listeners)) set.clear();\n }\n };\n}\n","// Numbers as a chart shows them: the `format` option or its default, the rounding a counting label\n// uses between two values, and a share as a percent.\n\n/** The chart's `format`, or the default: the locale's, to at most 2 decimals. */\nexport function format(options: { readonly format?: ((value: number) => string) | undefined }): (value: number) => string {\n return options.format ?? defaultFormat;\n}\n\nlet numberFormat: Intl.NumberFormat | undefined;\nfunction defaultFormat(value: number): string {\n numberFormat ??= new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });\n return numberFormat.format(value);\n}\n\n/** Decimal places a value is given to, up to 6: a counting label shows whole numbers between whole totals. */\nexport function decimals(value: number): number {\n const text = String(Number(value.toPrecision(12)));\n if (/e/i.test(text)) return 6;\n const point = text.indexOf(\".\");\n return point < 0 ? 0 : Math.min(6, text.length - point - 1);\n}\n\nexport function round(value: number, digits: number): number {\n const factor = 10 ** digits;\n const rounded = Math.round(value * factor) / factor;\n // No \"-0\" on a label counting down to zero.\n return rounded === 0 ? 0 : rounded;\n}\n\n/** A share, from 0 to 1, as a whole percent: \"28%\". */\nexport function percent(share: number): string {\n return `${round(share * 100, 0)}%`;\n}\n","// Pointer hover for a chart's marks, delegated from the root <svg>. A mouse or pen hovers; a touch tap\n// acts as hover until a tap somewhere else. While a tooltip shows, the pointer on it is on the target\n// it's for, so it can be read, selected and magnified without the hover ending (WCAG 1.4.13).\n\nexport interface HoverTarget {\n readonly key: string;\n /** The segment's series under the pointer, if it's over one. */\n readonly segment?: string;\n}\n\n/** The chart's own hovered target, and its tooltip's element while that shows. */\nexport interface HoverTooltip {\n readonly key: string;\n readonly element: HTMLElement | undefined;\n}\n\nexport interface PointerHoverOptions {\n /** The mark an event target belongs to, if any (leaving marks don't count). */\n find(target: EventTarget | null): HoverTarget | undefined;\n hover(target: HoverTarget, source: \"pointer\" | \"touch\"): void;\n leave(): void;\n /**\n * The chart's own hover, if any, and its tooltip while that shows: the pointer on the tooltip is on\n * the hovered target. Undefined with no hover, or a link's.\n */\n tooltip?(): HoverTooltip | undefined;\n}\n\nexport interface PointerHover {\n /** The hovered key, if any: the target the pointer is on, or whose tooltip it's on. */\n readonly current: string | undefined;\n /**\n * Leaves the hovered mark, for example because it's being removed. A pointer resting on its tooltip\n * hovers again only once it moves, though the browser may hit-test the mark under it at once.\n */\n clear(): void;\n destroy(): void;\n}\n\nexport function pointerHover(svg: SVGSVGElement, options: PointerHoverOptions): PointerHover {\n const doc = svg.ownerDocument;\n let current: string | undefined;\n let lastPointer = \"mouse\";\n /** The tooltip the pointer is on, and where the pointer is there, in client px. */\n let held: { readonly element: HTMLElement; x: number; y: number } | undefined;\n /** Watches the held tooltip for a change that moves it, or hides it, from under the pointer. */\n let watcher: MutationObserver | undefined;\n /**\n * Where the pointer rested on a tooltip whose hover ended there. With the tooltip gone, a browser may\n * hit-test again and send the mark under it a pointerover, though the pointer hasn't moved: until it\n * moves, that doesn't hover it, or a dismissed tooltip would come back at once.\n */\n let still: { readonly x: number; readonly y: number } | undefined;\n\n const enter = (target: HoverTarget | undefined, source: \"pointer\" | \"touch\"): void => {\n if (target?.key === current) return;\n leave();\n if (!target) return;\n current = target.key;\n options.hover(target, source);\n };\n\n const leave = (): void => {\n letGo();\n if (current === undefined) return;\n current = undefined;\n options.leave();\n };\n\n /** The tooltip's element while it shows, if it holds `node`. */\n const tooltipHolding = (node: Node | null): HoverTooltip | undefined => {\n const tip = options.tooltip?.();\n return tip?.element && node && tip.element.contains(node) ? tip : undefined;\n };\n\n /** The element at a point in client px, in the chart's document or shadow root; undefined where that can't be found. */\n const elementAt = (x: number, y: number): Element | null | undefined => {\n const root = svg.getRootNode() as Document | ShadowRoot;\n return typeof root.elementFromPoint === \"function\" ? root.elementFromPoint(x, y) : undefined;\n };\n\n /** Where the pointer went from an element it left: the event's related target or, without one, what's under it. */\n const landing = (event: PointerEvent): Element | null => (event.relatedTarget as Element | null) ?? elementAt(event.clientX, event.clientY) ?? null;\n\n /** The pointer is now over `element`: the tooltip, whose target it holds; a mark, which it hovers; or anything else, which ends the hover. */\n const arrive = (element: Element | null, x: number, y: number): void => {\n const tip = tooltipHolding(element);\n if (tip) hold(tip, x, y);\n else enter(element && svg.contains(element) ? options.find(element) : undefined, \"pointer\");\n };\n\n /** The pointer is on the tooltip, on its target: keyboard focus may have put it there. */\n const hold = (tip: HoverTooltip, x: number, y: number): void => {\n enter({ key: tip.key }, \"pointer\");\n const element = tip.element!;\n if (held?.element === element) {\n held.x = x;\n held.y = y;\n return;\n }\n letGo();\n held = { element, x, y };\n element.addEventListener(\"pointermove\", track);\n element.addEventListener(\"pointerleave\", off);\n watcher = new MutationObserver(recheck);\n watcher.observe(element, { attributes: true, childList: true, characterData: true, subtree: true });\n };\n\n const letGo = (): void => {\n if (!held) return;\n held.element.removeEventListener(\"pointermove\", track);\n held.element.removeEventListener(\"pointerleave\", off);\n watcher?.disconnect();\n watcher = undefined;\n held = undefined;\n };\n\n const track = (event: PointerEvent): void => {\n if (!held || event.pointerType === \"touch\") return;\n held.x = event.clientX;\n held.y = event.clientY;\n };\n\n /** Off the tooltip: onto a mark, which it hovers, or anywhere else, which ends the hover. */\n const off = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\") return;\n letGo();\n arrive(landing(event), event.clientX, event.clientY);\n };\n\n /**\n * The held tooltip changed. If it has moved from under the pointer, the pointer is on whatever it's\n * over now. If it shows another target now (focus moved the hover), the pointer isn't on the\n * hovered target any more, and hovers again when it next moves onto a mark.\n */\n const recheck = (): void => {\n if (!held) return;\n const { x, y } = held;\n const under = elementAt(x, y);\n if (under === undefined) return;\n const tip = options.tooltip?.();\n const onTip = tip?.element !== undefined && under !== null && tip.element.contains(under);\n if (onTip && tip.key === current) return;\n letGo();\n if (!onTip && tip?.key !== current) {\n still = { x, y };\n leave();\n return;\n }\n arrive(under, x, y);\n };\n\n /** Whether the pointer is still where a hover ended on its tooltip; once it has moved, it isn't. */\n const resting = (event: PointerEvent): boolean => {\n if (still && Math.abs(event.clientX - still.x) < 1 && Math.abs(event.clientY - still.y) < 1) return true;\n still = undefined;\n return false;\n };\n // Touch fires pointerover and pointerleave around every tap; taps are handled on click instead.\n const over = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\" || resting(event)) return;\n letGo();\n enter(options.find(event.target), \"pointer\");\n };\n // Off the <svg>, onto the tooltip the pointer stays on the hovered target; anywhere else it leaves.\n const out = (event: PointerEvent): void => {\n if (event.pointerType === \"touch\") return;\n still = undefined;\n arrive(landing(event), event.clientX, event.clientY);\n };\n const move = (event: PointerEvent): void => {\n if (event.pointerType !== \"touch\") resting(event);\n };\n const down = (event: PointerEvent): void => {\n lastPointer = event.pointerType;\n };\n // A click follows a tap but not a scroll, so scrolling past the chart doesn't hover anything.\n const click = (event: MouseEvent): void => {\n if (lastPointer === \"touch\") enter(options.find(event.target), \"touch\");\n };\n // A tap on the tooltip isn't a tap elsewhere: the hover stays. The document hears a chart in a\n // shadow root's events from its host, so the target is the first in the event's path.\n const elsewhere = (event: PointerEvent): void => {\n if (current === undefined || event.pointerType !== \"touch\") return;\n const target = (event.composedPath()[0] ?? event.target) as Node | null;\n if (!svg.contains(target) && !tooltipHolding(target)) leave();\n };\n\n svg.addEventListener(\"pointerover\", over);\n svg.addEventListener(\"pointerleave\", out);\n svg.addEventListener(\"pointermove\", move);\n svg.addEventListener(\"pointerdown\", down);\n svg.addEventListener(\"click\", click);\n doc.addEventListener(\"pointerdown\", elsewhere, true);\n\n return {\n get current() {\n return current;\n },\n clear() {\n if (held) still = { x: held.x, y: held.y };\n leave();\n },\n destroy() {\n letGo();\n current = undefined;\n svg.removeEventListener(\"pointerover\", over);\n svg.removeEventListener(\"pointerleave\", out);\n svg.removeEventListener(\"pointermove\", move);\n svg.removeEventListener(\"pointerdown\", down);\n svg.removeEventListener(\"click\", click);\n doc.removeEventListener(\"pointerdown\", elsewhere, true);\n }\n };\n}\n","// Keyboard focus for a chart's marks, delegated from the root <svg> like pointer hover. The chart is\n// one tab stop (a roving tabindex): arrow keys move between marks in visual order, Page Up and Page\n// Down by a page, Home and End jump to the ends, and Escape leaves. Focus that follows a key press\n// shows the ring and plays the hover story; focus from a click or tap does neither (the pointer's own\n// hover is playing), as with :focus-visible. The charts (through shell/hover.ts) and expressive()\n// share it.\n\nexport interface KeyboardFocusOptions {\n /** The mark an event target belongs to, if any (leaving marks don't count). */\n find(target: EventTarget | null): string | undefined;\n /** The marks that can take focus, in visual order. */\n order(): readonly string[];\n /** The element that takes a mark's focus. Leaving marks' too, unless `tabIndex` is given. */\n element(key: string): SVGElement | undefined;\n /**\n * Sets a mark's tabindex: \"0\" for the tab stop, \"-1\" for the others, and undefined once the mark\n * has left. By default it's set on `element(key)`; the adapter sets it on the host's elements itself,\n * so it can put back what they had.\n */\n tabIndex?(key: string, value: \"0\" | \"-1\" | undefined): void;\n /** A mark took focus. `visible`: it followed a key press, so it shows the ring. */\n focus(key: string, visible: boolean): void;\n /** Focus left the chart's marks. */\n blur(key: string): void;\n /** Escape on a focused mark. Returns whether it did anything. */\n escape(key: string): boolean;\n /**\n * Where a page goes from `key`: on (`by` 1, Page Down) or back (-1, Page Up), for an axis whose page\n * isn't a count of marks. A line chart's time axis gives the first x a calendar month or more away.\n * Undefined, or a key not in the order, keeps the default: a tenth of the marks, rounded up.\n */\n page?(key: string, by: 1 | -1): string | undefined;\n}\n\nexport interface KeyboardFocus {\n /** The element with focus in the chart's document or shadow root, even while the window is in the background. */\n active(): Element | null;\n /** Moves the tab stop and focus to a mark as a key press would, whatever the last input was: it shows the ring and plays the hover. */\n focus(key: string): void;\n /**\n * After the marks changed: keeps the tab stop on its key, or, when that mark left, moves it to its\n * nearest neighbour; then sets every mark's tabindex. Focus follows the tab stop if its mark left,\n * and goes to the mark's new element if the host replaced the focused one. It also listens on the\n * <svg> as it is now: a host may draw a new one, or move it into or out of a shadow root.\n */\n sync(): void;\n destroy(): void;\n}\n\nexport function keyboardFocus(svg: () => SVGSVGElement | undefined, options: KeyboardFocusOptions): KeyboardFocus {\n /** What the listeners are on. Focus is heard on the document or shadow root, not on the <svg>. */\n let on: { readonly svg: SVGSVGElement; readonly doc: Document; readonly scope: Document | ShadowRoot } | undefined;\n /** The mark with focus, as focusin and focusout tell it. */\n let current: string | undefined;\n /** The element that last took a mark's focus, and its mark. */\n let focused: { readonly key: string; readonly element: SVGElement } | undefined;\n /** A mark's element that focus left for nowhere in this task: maybe the host removing it. */\n let dropped: SVGElement | undefined;\n let tabStop: string | undefined;\n /** The order sync() last saw, to find a leaving mark's neighbours. */\n let last: readonly string[] = [];\n /** Whether the last input was a key (or there's been none), as :focus-visible decides. */\n let keyboardInput = true;\n\n const setTabIndex =\n options.tabIndex ??\n ((key: string, value: \"0\" | \"-1\" | undefined): void => {\n const element = options.element(key);\n if (value === undefined) element?.removeAttribute(\"tabindex\");\n else element?.setAttribute(\"tabindex\", value);\n });\n\n /** One mark is in the tab order; the others take focus from the arrow keys. */\n const applyTabIndex = (keys: readonly string[]): void => {\n for (const key of keys) setTabIndex(key, key === tabStop ? \"0\" : \"-1\");\n };\n\n const focusKey = (key: string): void => {\n tabStop = key;\n applyTabIndex(options.order());\n options.element(key)?.focus();\n };\n\n const leave = (): void => {\n const key = current;\n current = undefined;\n if (key !== undefined) options.blur(key);\n };\n\n // On the whole document: a Tab from outside the chart has to count, and so does a click anywhere.\n const anyKey = (event: KeyboardEvent): void => {\n if (!event.metaKey && !event.altKey && !event.ctrlKey) keyboardInput = true;\n };\n const anyPointer = (): void => {\n keyboardInput = false;\n dropped = undefined;\n };\n\n const focusIn = (event: FocusEvent): void => {\n dropped = undefined;\n const key = options.find(event.target);\n if (key === undefined) {\n // Focus moved on from an element the host removed, which brings no focusout.\n leave();\n return;\n }\n // Focus on a mark's element that screen readers can't see (a click on a stack's other segment,\n // which the adapter's markLabel hides) goes on to the element that carries the mark's name.\n const own = options.element(key);\n if (own && own !== event.target && (event.target as Element).getAttribute(\"aria-hidden\") === \"true\") {\n own.focus();\n if (on?.scope.activeElement === own) return;\n }\n focused = { key, element: event.target as SVGElement };\n if (key === current) return;\n current = key;\n tabStop = key;\n applyTabIndex(options.order());\n options.focus(key, keyboardInput);\n };\n\n const focusOut = (event: FocusEvent): void => {\n const element = focused?.element;\n if (current === undefined || !element || event.target !== element) return;\n // Moving to another mark: its focusin takes over.\n if (options.find(event.relatedTarget) !== undefined) return;\n leave();\n if (event.relatedTarget !== null) return;\n // Focus going nowhere may be the host removing the element: Chrome tells that as a blur while the\n // element is still in the page. If it's gone once this task is done, sync() brings focus back.\n dropped = element;\n queueMicrotask(() => {\n if (dropped === element && element.isConnected) dropped = undefined;\n });\n };\n\n const keyDown = (event: KeyboardEvent): void => {\n const key = options.find(event.target);\n if (key === undefined || event.altKey || event.ctrlKey || event.metaKey) return;\n const keys = options.order();\n const index = keys.indexOf(key);\n let next: string | undefined;\n switch (event.key) {\n // Down or right is next whatever the orientation: rows run top to bottom, columns left to right.\n case \"ArrowDown\":\n case \"ArrowRight\":\n next = keys[Math.min(keys.length - 1, index + 1)];\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n next = keys[Math.max(0, index - 1)];\n break;\n case \"PageDown\":\n case \"PageUp\": {\n const by = event.key === \"PageDown\" ? 1 : -1;\n const paged = options.page?.(key, by);\n next = paged !== undefined && keys.includes(paged) ? paged : keys[Math.min(keys.length - 1, Math.max(0, index + by * Math.ceil(keys.length / 10)))];\n break;\n }\n case \"Home\":\n next = keys[0];\n break;\n case \"End\":\n next = keys[keys.length - 1];\n break;\n case \"Escape\":\n if (options.escape(key)) event.preventDefault();\n return;\n default:\n return;\n }\n // Arrows and pages at either end stay put, without scrolling the page.\n event.preventDefault();\n if (next !== undefined && next !== key) focusKey(next);\n };\n\n const unlisten = (): void => {\n if (!on) return;\n on.doc.removeEventListener(\"keydown\", anyKey, true);\n on.doc.removeEventListener(\"pointerdown\", anyPointer, true);\n on.scope.removeEventListener(\"focusin\", focusIn as EventListener, true);\n on.scope.removeEventListener(\"focusout\", focusOut as EventListener, true);\n on.svg.removeEventListener(\"keydown\", keyDown);\n on = undefined;\n };\n\n /** Listens on the <svg> as it is now, if it or its document or shadow root changed. */\n const listen = (): void => {\n const next = svg();\n const node = next?.getRootNode();\n // Not on the <svg>: Chrome makes an SVG element with focus listeners of its own a tab stop.\n const scope = node && \"host\" in node ? (node as ShadowRoot) : next?.ownerDocument;\n if (next === on?.svg && scope === on?.scope) return;\n unlisten();\n if (!next || !scope) return;\n on = { svg: next, doc: next.ownerDocument, scope };\n on.doc.addEventListener(\"keydown\", anyKey, true);\n on.doc.addEventListener(\"pointerdown\", anyPointer, true);\n on.scope.addEventListener(\"focusin\", focusIn as EventListener, true);\n on.scope.addEventListener(\"focusout\", focusOut as EventListener, true);\n on.svg.addEventListener(\"keydown\", keyDown);\n };\n\n listen();\n\n return {\n active: () => on?.scope.activeElement ?? null,\n focus(key) {\n keyboardInput = true;\n // Already focused (from a click, say): no focusin comes, so it's told here.\n if (key === current && focused?.element === on?.scope.activeElement) options.focus(key, true);\n else focusKey(key);\n },\n sync() {\n listen();\n const keys = options.order();\n const live = new Set(keys);\n const gone = last.filter((key) => !live.has(key));\n if (tabStop === undefined || !live.has(tabStop)) tabStop = neighbour(last, tabStop, live) ?? keys[0];\n // The mark with focus: its element is active (even while the window is in the background, when\n // no focus events come), or the host removed its element while it had focus. Browsers tell that\n // differently: Chrome with a blur just before, which left focus nowhere; others not at all.\n const nowhere = !on?.doc.activeElement || on.doc.activeElement === on.doc.body;\n const removed = focused !== undefined && !focused.element.isConnected && (current !== undefined || (focused.element === dropped && nowhere));\n const had = focused && (focused.element === on?.scope.activeElement || removed) ? focused : undefined;\n dropped = undefined;\n if (had && !live.has(had.key)) {\n // It left: focus goes to its neighbour, or, with no marks left, out of the chart.\n if (tabStop !== undefined) focusKey(tabStop);\n else if (had.element.isConnected) had.element.blur();\n else leave();\n } else if (had && options.find(had.element) !== had.key) {\n // The host replaced its element (Vega does), even if the old one is still in the page, as in a\n // D3 exit transition: focus the new one.\n focusKey(had.key);\n }\n applyTabIndex(keys);\n for (const key of gone) setTabIndex(key, undefined);\n last = keys;\n },\n destroy() {\n current = undefined;\n focused = undefined;\n dropped = undefined;\n unlisten();\n }\n };\n}\n\n/** The nearest key to `key` in `order` that's still live: the one after it first, then the one before, and outwards. */\nfunction neighbour(order: readonly string[], key: string | undefined, live: ReadonlySet<string>): string | undefined {\n const index = key === undefined ? -1 : order.indexOf(key);\n if (index < 0) return undefined;\n for (let step = 1; step < order.length; step++) {\n for (const at of [index + step, index - step]) {\n const candidate = order[at];\n if (candidate !== undefined && live.has(candidate)) return candidate;\n }\n }\n return undefined;\n}\n","// Hover for a reference chart's marks. Pointer, touch and keyboard focus share one hover: the marks'\n// emphasis (`ec-hot`), the others' dimming (`ec-hovering` on the <svg>), the tooltip, the runner's\n// hover and leave, and the events. Focus from a key press, or from the chart's focus(key), shows the\n// focus ring and plays the hover; focus from a click or tap moves the tab stop but leaves the hover to\n// the pointer.\n//\n// What's hovered is a target: what the pointer is over and what takes focus. A target stands for one\n// mark or several, hovered together in one batch: a bar or a slice is its own mark, while a line\n// chart's x stands for every series' point there. The keyboard moves between targets.\n//\n// The chart says which targets and marks there are and draws them: it finds a live target from an\n// event target, gives a target's marks, their elements and how they are on screen, draws the ring\n// and shows the tooltip. The pointer on the tooltip stays on the hovered target (../interaction.ts).\n//\n// A link (../link.ts) hovers targets too, as \"linked\": their marks' emphasis, the dimming and their\n// hover runs, with no tooltip, ring or focus. It hears the chart's own hovers, and Escape on a linked\n// hover ends the link's, where it started.\n\nimport type { RunInput, Runner } from \"../../core/runner\";\nimport { pointerHover, type HoverTarget } from \"../interaction\";\nimport { keyboardFocus } from \"../keyboard\";\nimport { own, type LinkListener, type LinkPort } from \"../link\";\nimport type { MarkEvents } from \"../types\";\nimport type { ChartEvents } from \"./events\";\n\ntype HoverSource = MarkEvents<unknown>[\"hover\"][\"source\"];\n\nexport interface ChartHoverOptions<D> {\n readonly svg: SVGSVGElement;\n readonly runner: Pick<Runner<D>, \"hover\" | \"leave\">;\n readonly events: Pick<ChartEvents<D>, \"emit\">;\n /** Whether the other marks dim while one is hovered: the `dim` option as it is now. */\n dim(): boolean;\n /** The live target an event target belongs to, with the segment under the pointer; leaving ones don't count. */\n find(target: EventTarget | null): HoverTarget | undefined;\n /** Whether the target `key` is live: on screen and not leaving. */\n live(key: string): boolean;\n /** The live targets' keys, in visual order: the keyboard's order. */\n order(): readonly string[];\n /** Where Page Down (`by` 1) or Page Up (-1) goes from the target `key`. Default, or undefined: a tenth of the targets on or back (../keyboard.ts). */\n page?(key: string, by: 1 | -1): string | undefined;\n /**\n * The keys of the marks a live target stands for, in the batch's order: a line chart's x gives each\n * series' point there. Default: the target alone, as a bar or a slice is its own mark.\n */\n marks?(key: string): readonly string[];\n /** A target's element, live or leaving: it takes focus and, for a target that is its own mark, the hover's emphasis. */\n element(key: string): SVGElement | undefined;\n /** A mark's element, live or leaving: it takes the hover's emphasis (`ec-hot`). Default: `element`, for targets that are their own marks. */\n markElement?(key: string): SVGElement | undefined;\n /** The mark's overlay groups take the hover's emphasis too, or lose it, so the others' decorations dim with them (the surface's `hot`). */\n hot?(key: string, on: boolean): void;\n /** A mark as it is on screen, live or leaving: what hover and leave report, so mid-change they match what's under the pointer. */\n onScreen(key: string): RunInput<D> | undefined;\n /** Draws the focus ring around the live target `key` as it is on screen, or hides it. */\n ring(key: string | undefined): void;\n readonly tooltip: {\n /** Shows the tooltip for the live target `key` as it is on screen, or moves it there. */\n show(key: string): void;\n hide(): void;\n /** The tooltip's element while it shows: the pointer on it stays on the hovered target. */\n element?(): HTMLElement | undefined;\n };\n}\n\nexport interface ChartHover {\n /** The hovered target's key, when the hover is the chart's own: a link's shows no tooltip. */\n readonly key: string | undefined;\n /** The target showing the focus ring: focused from the keyboard. */\n readonly ringKey: string | undefined;\n /** The chart's hover as a link drives it, for the chart to register with its handle. */\n readonly link: LinkPort;\n /** The element with focus in the chart's document or shadow root. */\n active(): Element | null;\n /** An effect restyled a mark: the focus ring and the tooltip of the target it belongs to follow its transform. */\n restyled(key: string): void;\n /** After `dim` changed: the others dim, or stop dimming, now. */\n syncDim(): void;\n /**\n * After the marks changed: ends the hover if its targets have left. Otherwise the hover follows the\n * marks its targets stand for now: those it no longer has are left, and new ones are hovered, their\n * events placed in the whole batch, as the runner's runs are.\n */\n dropGone(): void;\n /** After the marks changed: the tab stop stays on its key, or moves to its nearest neighbour, and focus follows. */\n sync(): void;\n /** Moves focus to the live target `key` as a key press would: the ring shows and its hover plays. Does nothing for a key that isn't live. */\n focus(key: string): void;\n /**\n * Ends the hover, the pointer's or focus's, as the viewer moving away would: the emphasis, the\n * dimming, the tooltip and the hover runs end, with their leave events. Focus stays where it is,\n * with its ring, as after Escape; the pointer hovers again when it next moves onto a mark.\n */\n leave(): void;\n destroy(): void;\n}\n\ninterface Hovered {\n /** The targets' keys: one for the chart's own hover, any number for a link's. */\n readonly keys: readonly string[];\n readonly source: HoverSource;\n /** The marks hovered for them, in the batch's order. */\n readonly marks: readonly string[];\n /** Whether their hover runs play: a link with `effects: false` keeps its marks to emphasis and dimming. */\n readonly effects: boolean;\n}\n\nexport function chartHover<D>(options: ChartHoverOptions<D>): ChartHover {\n const { svg, runner, events } = options;\n const marksOf = (key: string): readonly string[] => options.marks?.(key) ?? [key];\n const markElement = (key: string): SVGElement | undefined => (options.markElement ?? options.element)(key);\n /** The mark takes the hover's emphasis, or loses it, with its overlay groups. */\n const heat = (key: string, on: boolean): void => {\n markElement(key)?.classList.toggle(\"ec-hot\", on);\n options.hot?.(key, on);\n };\n let hovered: Hovered | undefined;\n let ringKey: string | undefined;\n /** The link the chart is in, which hears its own hovers. */\n let linked: LinkListener | undefined;\n let destroyed = false;\n\n /** The marks among `keys` that are on screen, with how they are there. */\n const onScreen = (keys: readonly string[]): { readonly key: string; readonly input: RunInput<D> }[] =>\n keys.flatMap((key) => {\n const input = options.onScreen(key);\n return input ? [{ key, input }] : [];\n });\n /** The marks the targets `keys` stand for, each once. */\n const marksFor = (keys: readonly string[]): readonly string[] => (keys.length === 1 ? marksOf(keys[0]!) : [...new Set(keys.flatMap(marksOf))]);\n\n /** The marks' hover runs, in one batch, and an event for each with its place in it. */\n function hoverMarks(marks: ReturnType<typeof onScreen>, source: HoverSource, effects: boolean, segment?: string): void {\n if (marks.length === 0) return;\n if (effects) runner.hover(marks.map(({ input }) => input));\n const count = marks.length;\n marks.forEach(({ input }, index) => events.emit(\"hover\", { ...input, batch: { index, count }, source, ...(segment === undefined ? {} : { segment }) }));\n }\n\n /** The marks lose their emphasis, their hover runs end in one batch, and each gets a leave event. */\n function leaveMarks(keys: readonly string[]): void {\n // Every key, on screen or not, so a mark that comes back with the same key isn't hot.\n for (const key of keys) heat(key, false);\n const marks = onScreen(keys);\n if (marks.length === 0) return;\n runner.leave(marks.map(({ key }) => key));\n const count = marks.length;\n marks.forEach(({ input }, index) => events.emit(\"leave\", { ...input, batch: { index, count } }));\n }\n\n /**\n * Pointer, keyboard and link hover share this: the marks' emphasis, the others' dimming, the hover\n * runs and the events. The chart's own adds the tooltip and Escape, and tells its link.\n */\n function startHover(keys: readonly string[], source: HoverSource, segment?: string, effects = true): void {\n const marks = onScreen(marksFor(keys));\n const started: Hovered = { keys, source, marks: marks.map((mark) => mark.key), effects };\n hovered = started;\n for (const { key: mark } of marks) heat(mark, true);\n if (options.dim()) svg.classList.add(\"ec-hovering\");\n if (source !== \"linked\") {\n options.tooltip.show(keys[0]!);\n listenForEscape(true);\n }\n hoverMarks(marks, source, effects, segment);\n // A listener may have ended it (leave()) or started another, which told the link itself.\n if (source !== \"linked\" && hovered === started) linked?.hover(marks.map(({ input }) => input));\n }\n\n function endHover(): void {\n const ended = hovered;\n hovered = undefined;\n listenForEscape(false);\n svg.classList.remove(\"ec-hovering\");\n options.tooltip.hide();\n leaveMarks(ended?.marks ?? []);\n if (own(ended)) linked?.leave();\n }\n\n /** The document listening for Escape while something is hovered. */\n let escapeDoc: Document | undefined;\n /**\n * Escape anywhere ends the hover, the pointer's too, as leave() does: its tooltip covers other marks,\n * so it can be dismissed without moving the pointer (WCAG 1.4.13). With focus on a mark, the\n * keyboard's own Escape has ended it first.\n */\n const dismiss = (event: KeyboardEvent): void => {\n if (event.key === \"Escape\" && !event.defaultPrevented && hovered !== undefined) leave();\n };\n function listenForEscape(on: boolean): void {\n escapeDoc?.removeEventListener(\"keydown\", dismiss);\n escapeDoc = on ? svg.ownerDocument : undefined;\n escapeDoc?.addEventListener(\"keydown\", dismiss);\n }\n\n function leave(): void {\n // The pointer lets go first, so it hovers again when it next moves onto a mark.\n interaction.clear();\n if (hovered !== undefined) endHover();\n }\n\n /** Whether the mark `key` is, or belongs to, the target `target`. */\n const within = (target: string, key: string): boolean => key === target || (options.live(target) && marksOf(target).includes(key));\n\n const interaction = pointerHover(svg, {\n find: options.find,\n hover(target: HoverTarget, source) {\n // Already playing for keyboard focus: it goes on.\n if (!options.live(target.key) || (own(hovered) && hovered.keys[0] === target.key)) return;\n endHover();\n startHover([target.key], source, target.segment);\n },\n leave() {\n // Focus holds a keyboard hover until blur or Escape, and a link holds its own.\n if (hovered?.source === \"pointer\" || hovered?.source === \"touch\") endHover();\n },\n // The pointer can move onto the tooltip of the chart's own hover. A link's has none.\n tooltip: () => (own(hovered) ? { key: hovered.keys[0]!, element: options.tooltip.element?.() } : undefined)\n });\n\n const keyboard = keyboardFocus(() => svg, {\n find: (eventTarget) => options.find(eventTarget)?.key,\n order: options.order,\n page: (key, by) => options.page?.(key, by),\n element: options.element,\n focus(key, visible) {\n ringKey = visible ? key : undefined;\n options.ring(ringKey);\n if (!options.live(key)) return;\n if (!visible) {\n // Focus from a click or tap: the pointer's own hover plays.\n if (hovered?.source === \"keyboard\" && hovered.keys[0] !== key) endHover();\n return;\n }\n if (own(hovered) && hovered.keys[0] === key) {\n // Already playing for the pointer: it goes on, held by focus now.\n hovered = { ...hovered, source: \"keyboard\" };\n return;\n }\n endHover();\n startHover([key], \"keyboard\");\n },\n blur() {\n ringKey = undefined;\n options.ring(ringKey);\n if (hovered?.source !== \"keyboard\") return;\n // The pointer is still over it: the hover goes on, held by the pointer now.\n if (interaction.current === hovered.keys[0]) hovered = { ...hovered, source: \"pointer\" };\n else endHover();\n },\n escape() {\n if (!hovered) return false;\n // A link's hover ends where it started, and with it every chart's in the link.\n if (hovered.source === \"linked\" && linked) linked.dismiss();\n else endHover();\n return true;\n }\n });\n\n const link: LinkPort = {\n targets: () => options.order().map((key) => ({ key, marks: onScreen(marksOf(key)).map(({ input }) => input) })),\n hover(keys, effects) {\n if (hovered !== undefined) endHover();\n const live = keys.filter(options.live);\n if (live.length > 0) startHover(live, \"linked\", undefined, effects);\n },\n unlink() {\n if (hovered?.source === \"linked\") endHover();\n },\n leave,\n listen(listener) {\n if (destroyed) return false;\n linked = listener;\n return true;\n }\n };\n\n return {\n get key() {\n return own(hovered) ? hovered.keys[0] : undefined;\n },\n get ringKey() {\n return ringKey;\n },\n link,\n active: () => keyboard.active(),\n restyled(key) {\n if (ringKey !== undefined && within(ringKey, key)) options.ring(ringKey);\n // A link's hover has no tooltip.\n const target = own(hovered) ? hovered.keys[0]! : undefined;\n if (target !== undefined && (hovered?.marks.includes(key) || key === target) && options.live(target)) options.tooltip.show(target);\n },\n syncDim() {\n if (!options.dim()) svg.classList.remove(\"ec-hovering\");\n else if (hovered !== undefined) svg.classList.add(\"ec-hovering\");\n },\n dropGone() {\n if (hovered === undefined) return;\n const keys = hovered.keys.filter(options.live);\n if (keys.length === 0) {\n interaction.clear();\n endHover();\n return;\n }\n const { source, marks: before, effects } = hovered;\n const now = onScreen(marksFor(keys));\n hovered = { ...hovered, keys };\n if (now.length === before.length && now.every((mark, i) => mark.key === before[i])) return;\n const had = new Set(before);\n const kept = new Set(now.map((mark) => mark.key));\n const gone = onScreen(before.filter((key) => !kept.has(key)));\n hovered = { ...hovered, marks: now.map((mark) => mark.key) };\n for (const key of before) if (!kept.has(key)) heat(key, false);\n for (const { key } of now) if (!had.has(key)) heat(key, true);\n // The runner hears the targets' whole new batch, in order. Mid-change (playUpdate interrupts\n // first), it holds hovers and replays every hovered mark as one batch when the change settles, so\n // a joined mark's run gets the place its event gives; at rest, the marks that stayed start again\n // with their new places.\n runner.leave(before);\n if (effects) runner.hover(now.map(({ input }) => input));\n gone.forEach(({ input }, index) => events.emit(\"leave\", { ...input, batch: { index, count: gone.length } }));\n const count = now.length;\n now.forEach(({ key, input }, index) => {\n if (!had.has(key)) events.emit(\"hover\", { ...input, batch: { index, count }, source });\n });\n },\n sync: () => keyboard.sync(),\n focus(key) {\n if (options.live(key)) keyboard.focus(key);\n },\n leave,\n destroy() {\n destroyed = true;\n linked?.gone();\n linked = undefined;\n listenForEscape(false);\n interaction.destroy();\n keyboard.destroy();\n }\n };\n}\n","// What a chart's labels() reports: each mark's labels as drawn, by key and role, with their text,\n// where they sit in the chart's <svg>, and their <text>.\n\nimport type { TextPlacement } from \"../render/text\";\nimport type { ChartLabel } from \"../types\";\n\n/** The label `element` drawn as `placement`, in a list for flatMap: empty when it isn't shown (no placement) or has no text. */\nexport function chartLabel(key: string, role: ChartLabel[\"role\"], placement: TextPlacement | undefined, element: SVGTextElement): ChartLabel[] {\n if (!placement || placement.text === \"\") return [];\n return [{ key, role, text: placement.text, x: placement.x, y: placement.y, anchor: placement.anchor, element }];\n}\n","// Marks on their way out. A leaving mark stays, unhoverable and no longer read, until it has faded out\n// and its exit effects are done; one that comes back meanwhile keeps its element and grows back from\n// where it is.\n\n/** One departure: a fresh one each time, so a mark that comes back and leaves again starts over. */\nexport interface Leave {\n /** Its exit effects are done. */\n exited: boolean;\n /** Resolves when its element is removed, or the mark comes back. */\n readonly gone: Promise<void>;\n readonly resolve: () => void;\n}\n\n/** What a chart's mark record needs for leaving. */\nexport interface LeavingMark {\n readonly key: string;\n /** The mark's element: hidden from screen readers while it leaves, and removed once it's gone. */\n readonly group: SVGElement;\n /** Set while the mark leaves. */\n leave: Leave | undefined;\n}\n\nexport interface LeavingMarks<R extends LeavingMark> {\n get(key: string): R | undefined;\n /** In the order they started leaving. */\n values(): Iterable<R>;\n /** Starts a mark leaving, once the chart has taken it out of its live marks. */\n start(record: R): void;\n /** Brings back the mark leaving under `key`, if there is one: it keeps its element, and the runner cancels its exit. */\n recall(key: string): R | undefined;\n /** Removes the marks whose exit effects are done and which have stopped `fading`. */\n sweep(): void;\n clear(): void;\n}\n\n/** `fading(record)`: the mark is still animating its way out. */\nexport function leavingMarks<R extends LeavingMark>(fading: (record: R) => boolean): LeavingMarks<R> {\n const marks = new Map<string, R>();\n return {\n get: (key) => marks.get(key),\n values: () => marks.values(),\n start(record) {\n marks.set(record.key, record);\n record.group.classList.add(\"ec-leaving\");\n // On its way out: no longer read.\n record.group.setAttribute(\"aria-hidden\", \"true\");\n record.leave = leave();\n },\n recall(key) {\n const record = marks.get(key);\n if (!record) return undefined;\n marks.delete(key);\n record.group.classList.remove(\"ec-leaving\");\n record.group.removeAttribute(\"aria-hidden\");\n record.leave?.resolve();\n record.leave = undefined;\n return record;\n },\n sweep() {\n for (const record of [...marks.values()]) {\n const { leave } = record;\n if (!leave?.exited || fading(record)) continue;\n marks.delete(record.key);\n record.leave = undefined;\n record.group.remove();\n leave.resolve();\n }\n },\n clear: () => marks.clear()\n };\n}\n\nfunction leave(): Leave {\n let resolve!: () => void;\n const gone = new Promise<void>((r) => {\n resolve = r;\n });\n return { exited: false, gone, resolve };\n}\n","// DOM order follows visual order, so screen readers read the marks as they're seen.\n\n/**\n * Moves the marks' elements in `layer` from `previous` into `next` order, when it changed. The element\n * with focus (`active`) stays put and the others move around it, because moving a focused element blurs it.\n */\nexport function orderElements(layer: Element, previous: readonly Element[], next: readonly Element[], active: () => Element | null): void {\n if (!next.some((element, i) => previous[i] !== element)) return;\n const focused = active();\n const pivot = next.findIndex((element) => element === focused);\n const anchor = next[pivot] ?? null;\n next.forEach((element, i) => {\n if (i < pivot) layer.insertBefore(element, anchor);\n else if (i > pivot) layer.appendChild(element);\n });\n}\n","// The chart's data table: the fallback that every screen reader can read, whatever it makes of ARIA\n// in SVG. A closed <details> \"Data table\" after the chart, or, with `table: \"hidden\"`, a table that's\n// visually hidden but still read. Its rows are the chart's, in visual order, so it follows the sort;\n// its columns are the category (each row's header), any extra columns the page lists, each series,\n// and the total of a stack, in the chart's format, then any columns the page puts after the values.\n// A donut adds each row's share and a total row. A line's missing value says \"missing\". Text is only\n// ever set as text, never parsed as HTML.\n\nimport { percent } from \"./shell/format\";\nimport type { ChartOptions, TableColumn, TableOptions } from \"./types\";\n\n/** The `table` option. */\nexport type TableOption<D> = ChartOptions<D>[\"table\"];\n\n/** A row as the chart has it. */\nexport interface TableRow<D> {\n readonly key: string;\n readonly category: string;\n readonly datum: D;\n /** Its index in `data`. */\n readonly index: number;\n readonly values: readonly { readonly series: string; readonly value: number }[];\n /** The series with no value in this row, a line chart's gaps: their cells say \"missing\". */\n readonly missing?: ReadonlySet<string>;\n readonly total: number;\n}\n\nexport interface TableInput<D> {\n readonly option: TableOption<D>;\n /** The chart's label. */\n readonly caption: string;\n /** The category's field name, when a field gives it: the column's default header. */\n readonly category: string | undefined;\n /** In stack order. */\n readonly series: readonly string[];\n /** A series' column header when `table.series` has none: its label. Default: the series' own name. */\n readonly label?: (series: string) => string;\n /** In visual order. */\n readonly rows: readonly TableRow<D>[];\n readonly format: (value: number) => string;\n /**\n * Whether there's a Total column after the series, each row's values added up. Default: when\n * there's more than one series, as a stack has. A line chart's series don't add up, so it has none.\n */\n readonly total?: boolean;\n /**\n * A donut's: a Share column after the values, each row's share of the rows' total as a whole\n * percent, and a total row in <tfoot>: \"Total\", the values added up, and 100%.\n */\n readonly shares?: boolean;\n}\n\nexport interface TableCell {\n readonly text: string;\n /** Right-aligned. */\n readonly numeric: boolean;\n}\n\n/** What the table shows: headers, then each row's cells, the first of which is the row's header. */\nexport interface TableModel {\n readonly hidden: boolean;\n readonly summary: string;\n readonly caption: string;\n readonly headers: readonly TableCell[];\n readonly rows: readonly { readonly key: string; readonly cells: readonly TableCell[] }[];\n /** The total row's cells, in <tfoot>; the first is its header. */\n readonly footer?: readonly TableCell[];\n}\n\nexport interface ChartTable {\n /**\n * Shows `model` after the chart's <svg>, or removes the table when it's undefined. Rows are kept by\n * key and only what changed is written, so an open table, and a screen reader's place in it, stay.\n */\n render(model: TableModel | undefined): void;\n destroy(): void;\n}\n\n/** Throws on a `table` option that isn't true, false, \"hidden\" or a valid object. `chart` names the chart in the message. */\nexport function checkTableOption(option: unknown, chart: string): void {\n if (option === undefined || typeof option === \"boolean\" || option === \"hidden\") return;\n const fail = (what: string): never => {\n throw new TypeError(`${chart}: ${what}`);\n };\n if (typeof option !== \"object\" || option === null) fail('table must be true, false, \"hidden\" or an object of table options.');\n const { hidden, columns, category, total, share, summary, series } = option as TableOptions<unknown>;\n if (hidden !== undefined && typeof hidden !== \"boolean\") fail(\"table.hidden must be true or false.\");\n for (const [name, text] of Object.entries({ category, total, share, summary })) {\n if (text !== undefined && typeof text !== \"string\") fail(`table.${name} must be a string.`);\n }\n if (series !== undefined) {\n if (typeof series !== \"object\" || series === null || Array.isArray(series)) fail('table.series must be an object of headers by series, as { shots: \"Shots\" }.');\n for (const [name, header] of Object.entries(series)) {\n if (typeof header !== \"string\") fail(`table.series.${name} must be a string: the column's header.`);\n }\n }\n if (columns === undefined) return;\n if (!Array.isArray(columns)) fail(\"table.columns must be an array of { label, field }.\");\n columns.forEach((entry: Partial<TableColumn<unknown>> | null, i: number) => {\n const column = typeof entry === \"object\" && entry !== null ? entry : fail(`table.columns[${i}] must be an object with a label and a field.`);\n if (typeof column.label !== \"string\") fail(`table.columns[${i}].label must be a string: the column's header.`);\n if (typeof column.field !== \"string\" && typeof column.field !== \"function\") fail(`table.columns[${i}].field must be a field name or a function of the row.`);\n if (column.format !== undefined && typeof column.format !== \"function\") fail(`table.columns[${i}].format must be a function.`);\n if (column.after !== undefined && column.after !== \"category\" && column.after !== \"values\") fail(`table.columns[${i}].after must be \"category\" or \"values\".`);\n });\n}\n\n/** A missing value's cell: a word, so it's heard as missing, not as an empty cell. */\nconst MISSING = \"missing\";\n\n/** What the table shows, or undefined with `table: false`. Reads every cell, so a column that throws throws here. */\nexport function tableModel<D>(input: TableInput<D>): TableModel | undefined {\n const { option, format } = input;\n if (option === false) return undefined;\n const options: TableOptions<D> = typeof option === \"object\" ? option : {};\n const columns = options.columns ?? [];\n const first = columns.filter((column) => column.after !== \"values\");\n const last = columns.filter((column) => column.after === \"values\");\n const totals = input.total ?? input.series.length > 1;\n const number = (value: number): TableCell => ({ text: format(value), numeric: true });\n const grand = input.rows.reduce((sum, row) => sum + row.total, 0);\n const share = (value: number): TableCell[] => (input.shares ? [{ text: percent(grand > 0 ? value / grand : 0), numeric: true }] : []);\n const header = (column: TableColumn<D>): TableCell => ({ text: column.label, numeric: false });\n // Only the option's own keys count, so \"constructor\" is just a series.\n const own = (series: string): string | undefined => (options.series && Object.prototype.hasOwnProperty.call(options.series, series) ? options.series[series] : undefined);\n const blank = (): TableCell => ({ text: \"\", numeric: false });\n\n const headers: TableCell[] = [\n { text: options.category ?? input.category ?? \"Category\", numeric: false },\n ...first.map(header),\n ...input.series.map((series) => ({ text: own(series) ?? input.label?.(series) ?? series, numeric: true })),\n ...(totals ? [{ text: options.total ?? \"Total\", numeric: true }] : []),\n ...(input.shares ? [{ text: options.share ?? \"Share\", numeric: true }] : []),\n ...last.map(header)\n ];\n const rows = input.rows.map((row) => {\n const values = new Map(row.values.map((v) => [v.series, v.value]));\n return {\n key: row.key,\n cells: [\n { text: row.category, numeric: false },\n ...first.map((column) => columnCell(column, row, format)),\n ...input.series.map((series) => (row.missing?.has(series) ? { text: MISSING, numeric: true } : number(values.get(series) ?? 0))),\n ...(totals ? [number(row.total)] : []),\n ...share(row.total),\n ...last.map((column) => columnCell(column, row, format))\n ]\n };\n });\n const sum = (series: string): number => input.rows.reduce((total, row) => total + (row.values.find((v) => v.series === series)?.value ?? 0), 0);\n const footer: TableCell[] | undefined = input.shares\n ? [\n { text: options.total ?? \"Total\", numeric: false },\n ...first.map(blank),\n ...input.series.map((series) => number(sum(series))),\n ...(totals ? [number(grand)] : []),\n ...share(grand),\n ...last.map(blank)\n ]\n : undefined;\n // A column of numbers is right-aligned, header and all.\n const lastAt = headers.length - last.length;\n const pageColumns = [...first.map((_, i) => 1 + i), ...last.map((_, i) => lastAt + i)];\n for (const at of pageColumns) {\n const cells = rows.map((row) => row.cells[at]!).filter((cell) => cell.text !== \"\");\n if (cells.length > 0 && cells.every((cell) => cell.numeric)) headers[at] = { ...headers[at]!, numeric: true };\n }\n return {\n hidden: option === \"hidden\" || options.hidden === true,\n summary: options.summary ?? \"Data table\",\n caption: input.caption,\n headers,\n rows,\n ...(footer ? { footer } : {})\n };\n}\n\nfunction columnCell<D>(column: TableColumn<D>, row: TableRow<D>, format: (value: number) => string): TableCell {\n const value = typeof column.field === \"function\" ? column.field(row.datum, row.index) : (row.datum as Record<string, unknown> | null | undefined)?.[column.field];\n if (column.format) return { text: String(column.format(value)), numeric: typeof value === \"number\" };\n if (value === null || value === undefined) return { text: \"\", numeric: false };\n if (typeof value === \"number\") return { text: format(value), numeric: true };\n return { text: String(value), numeric: false };\n}\n\n/** The data table for a chart's <svg>: made the first time there's something to show, just after the <svg>. */\nexport function chartTable(svg: SVGSVGElement): ChartTable {\n const doc = svg.ownerDocument;\n /** The <details>, or the visually hidden <div>, around the table. */\n let wrapper: HTMLElement | undefined;\n let summary: HTMLElement | undefined;\n let table: HTMLTableElement | undefined;\n let caption: HTMLTableCaptionElement | undefined;\n let head: HTMLTableRowElement | undefined;\n let body: HTMLTableSectionElement | undefined;\n /** The total row's <tfoot>, while the model has one. */\n let foot: HTMLTableSectionElement | undefined;\n /** The body's rows by key. */\n const rows = new Map<string, HTMLTableRowElement>();\n /** The headers drawn, so a change of columns redraws the rows. */\n let drawn = \"\";\n\n const element = <K extends keyof HTMLElementTagNameMap>(tag: K, className?: string): HTMLElementTagNameMap[K] => {\n const made = doc.createElement(tag);\n if (className) made.className = className;\n return made;\n };\n\n function build(): HTMLTableElement {\n table = element(\"table\");\n caption = element(\"caption\", \"ec-table-caption\");\n const thead = element(\"thead\");\n head = element(\"tr\");\n thead.appendChild(head);\n body = element(\"tbody\");\n table.append(caption, thead, body);\n return table;\n }\n\n /** The wrapper for `hidden`, made or swapped in place, holding the table. */\n function place(hidden: boolean, text: string): void {\n const want = hidden ? \"DIV\" : \"DETAILS\";\n if (wrapper?.tagName !== want) {\n const next = hidden ? element(\"div\", \"ec-table ec-visually-hidden\") : element(\"details\", \"ec-table\");\n const content = table ?? build();\n if (hidden) {\n summary = undefined;\n next.appendChild(content);\n } else {\n summary = element(\"summary\");\n const scroll = element(\"div\", \"ec-table-scroll\");\n scroll.appendChild(content);\n next.append(summary, scroll);\n }\n if (wrapper?.isConnected) wrapper.replaceWith(next);\n wrapper = next;\n }\n if (!wrapper.isConnected) svg.after(wrapper);\n if (summary && summary.textContent !== text) summary.textContent = text;\n }\n\n function fill(cell: HTMLTableCellElement, { text, numeric }: TableCell): void {\n if (cell.textContent !== text) cell.textContent = text;\n cell.classList.toggle(\"ec-num\", numeric);\n }\n\n function remove(): void {\n wrapper?.remove();\n wrapper = summary = table = caption = head = body = foot = undefined;\n rows.clear();\n drawn = \"\";\n }\n\n return {\n render(model) {\n if (!model) {\n remove();\n return;\n }\n place(model.hidden, model.summary);\n if (caption!.textContent !== model.caption) caption!.textContent = model.caption;\n\n const headers = JSON.stringify(model.headers);\n if (headers !== drawn) {\n drawn = headers;\n head!.replaceChildren(\n ...model.headers.map((header) => {\n const th = element(\"th\");\n th.scope = \"col\";\n fill(th, header);\n return th;\n })\n );\n // Other columns: every row is drawn again.\n rows.clear();\n body!.replaceChildren();\n }\n\n const keep = new Set(model.rows.map((row) => row.key));\n for (const [key, tr] of rows) {\n if (keep.has(key)) continue;\n tr.remove();\n rows.delete(key);\n }\n model.rows.forEach((row, i) => {\n let tr = rows.get(row.key);\n if (!tr) {\n tr = element(\"tr\");\n tr.setAttribute(\"data-key\", row.key);\n row.cells.forEach((_, j) => {\n const cell = element(j === 0 ? \"th\" : \"td\");\n if (j === 0) (cell as HTMLTableCellElement).scope = \"row\";\n tr!.appendChild(cell);\n });\n rows.set(row.key, tr);\n }\n row.cells.forEach((cell, j) => fill(tr!.cells[j]!, cell));\n // In visual order, moving only rows that are out of place.\n if (body!.children[i] !== tr) body!.insertBefore(tr, body!.children[i] ?? null);\n });\n\n if (!model.footer) {\n foot?.remove();\n foot = undefined;\n return;\n }\n const cells = model.footer;\n let total = foot?.rows[0];\n if (!foot || !total || total.cells.length !== cells.length) {\n foot?.remove();\n foot = element(\"tfoot\");\n total = element(\"tr\");\n cells.forEach((_, j) => {\n const cell = element(j === 0 ? \"th\" : \"td\");\n if (j === 0) (cell as HTMLTableCellElement).scope = \"row\";\n total!.appendChild(cell);\n });\n foot.appendChild(total);\n table!.appendChild(foot);\n }\n cells.forEach((cell, j) => fill(total!.cells[j]!, cell));\n },\n destroy: remove\n };\n}\n","// What a reference chart needs before it draws: the environment the composition root hands it, its\n// container and width, its accessible name, and a check that data effects find the series they read.\n// And its effects when update() gives it a new `on`.\n\nimport type { Clock, EffectSlot, EffectSlots, IconSource, Motion } from \"../../core\";\nimport { EFFECT_SLOTS, resolveEffects, type PresetFactory, type Registry } from \"../../core/registry\";\nimport type { SlotEffects } from \"../../core/runner\";\nimport { checkLegendOption } from \"../legend\";\nimport { svgElement } from \"../render/svg\";\nimport { checkSeriesLabels } from \"../series\";\nimport { checkTableOption } from \"../table\";\n\n/** What the composition root hands every chart, so charts never import the registries or effects. */\nexport interface ChartEnv {\n /** Resolves preset names in `on`. */\n readonly presets: Pick<Registry<PresetFactory>, \"resolve\">;\n /** Resolves icon names for effects. */\n readonly icons: IconSource;\n /** The page-wide motion: the default, and what a mode given as a string follows. */\n readonly motion: Motion;\n /** Default: the page-wide clock. */\n readonly clock?: Clock;\n}\n\n/** Used when the container has no width yet (hidden, or no layout as in jsdom); the prototype's width. */\nconst FALLBACK_WIDTH = 640;\n\n/** The container: the element, or the one a selector matches. `chart` names the chart in errors. */\nexport function resolveTarget(target: string | Element, chart: string): Element {\n if (typeof target === \"string\") {\n const found = typeof document === \"undefined\" ? null : document.querySelector(target);\n if (!found) throw new TypeError(`${chart}: no element matches \"${target}\".`);\n return found;\n }\n if (!target || typeof (target as Element).appendChild !== \"function\") throw new TypeError(`${chart} needs a container element or a selector.`);\n return target;\n}\n\n/** The container's content width in px; a fallback when it has none (hidden, or no layout). */\nexport function containerWidth(container: Element): number {\n const style = container.ownerDocument.defaultView?.getComputedStyle(container);\n const padding = (parseFloat(style?.paddingLeft ?? \"\") || 0) + (parseFloat(style?.paddingRight ?? \"\") || 0);\n const width = container.clientWidth - padding;\n return width > 0 ? width : FALLBACK_WIDTH;\n}\n\n/** The <svg>'s accessible name (`label`) and description (`description`, in a <desc>). */\nexport function describeChart(svg: SVGSVGElement, options: { readonly label: string; readonly description?: string | undefined }): void {\n svg.setAttribute(\"aria-label\", options.label);\n let desc = svg.querySelector(\":scope > desc\");\n if (options.description) {\n desc ??= svg.insertBefore(svgElement(\"desc\", {}, svg), svg.firstChild);\n desc.textContent = options.description;\n } else {\n desc?.remove();\n }\n}\n\n/**\n * Data effects name the series they read through `needs.related`. A chart without one of them\n * throws when it's created or updated, rather than the effect finding nothing when it runs.\n */\nexport function checkNeeds<D>(effects: SlotEffects<D>, series: readonly string[], chart: string): void {\n for (const slot of EFFECT_SLOTS) {\n const effect = effects[slot];\n if (effect?.kind !== \"data\") continue;\n for (const name of effect.needs?.related ?? []) {\n if (series.includes(name)) continue;\n throw new RangeError(`${chart}: on.${slot} needs the series \"${name}\", but the chart's series are ${series.map((s) => `\"${s}\"`).join(\", \")}.`);\n }\n }\n}\n\n/**\n * The effects for a new `on` (update({ on })), resolved as a chart resolves them when it's made, so an\n * unknown preset name or slot throws before anything changes. A slot given the same preset name or\n * effect as before keeps the effect it has, so its runs go on; a preset name makes a fresh effect only\n * when it's new to the slot.\n */\nexport function nextEffects<D>(effects: SlotEffects<D>, from: EffectSlots<D> | undefined, to: EffectSlots<D> | undefined, presets: ChartEnv[\"presets\"]): SlotEffects<D> {\n const kept = (slot: string): boolean => (EFFECT_SLOTS as readonly string[]).includes(slot) && to?.[slot as EffectSlot] !== undefined && to[slot as EffectSlot] === from?.[slot as EffectSlot];\n // Everything else is resolved, unknown slots included, so they throw.\n const resolved = resolveEffects(Object.fromEntries(Object.entries(to ?? {}).filter(([slot]) => !kept(slot))) as EffectSlots<D>, presets);\n const next: { -readonly [S in EffectSlot]?: SlotEffects<D>[S] } = {};\n for (const slot of EFFECT_SLOTS) {\n const effect = kept(slot) ? effects[slot] : resolved[slot];\n if (effect) next[slot] = effect;\n }\n return next;\n}\n\n/** The options every chart takes, as checkChartOptions reads them. */\ntype CommonOptions = { readonly [K in \"label\" | \"data\" | \"width\" | \"height\" | \"format\" | \"tooltip\" | \"markLabel\" | \"markDescription\" | \"legend\" | \"seriesLabels\" | \"table\" | \"announce\"]?: unknown };\n\n/** Throws on the options every chart shares when they're the wrong kind of thing. `chart` names the chart in the message. */\nexport function checkChartOptions(options: CommonOptions, chart: string): void {\n if (typeof options !== \"object\" || options === null) throw new TypeError(`${chart} needs options.`);\n if (typeof options.label !== \"string\" || options.label.trim() === \"\") throw new TypeError(`${chart} needs a label: the chart's accessible name.`);\n if (!Array.isArray(options.data)) throw new TypeError(`${chart}: data must be an array of rows.`);\n for (const field of [\"width\", \"height\"] as const) {\n const value = options[field];\n if (value !== undefined && !(typeof value === \"number\" && Number.isFinite(value) && value > 0)) throw new RangeError(`${chart}: ${field} must be a positive number of px, got ${String(value)}.`);\n }\n const { format, tooltip, markLabel, markDescription, legend, announce } = options;\n if (format !== undefined && typeof format !== \"function\") throw new TypeError(`${chart}: format must be a function that turns a value into text.`);\n if (tooltip !== undefined && typeof tooltip !== \"boolean\" && typeof tooltip !== \"function\") throw new TypeError(`${chart}: tooltip must be true, false or a function that returns a row's text.`);\n if (markLabel !== undefined && typeof markLabel !== \"function\") throw new TypeError(`${chart}: markLabel must be a function that returns a mark's accessible name.`);\n if (markDescription !== undefined && markDescription !== false && typeof markDescription !== \"function\") {\n throw new TypeError(`${chart}: markDescription must be false or a function that returns a mark's accessible description.`);\n }\n checkLegendOption(legend, chart);\n checkSeriesLabels(options.seriesLabels, chart);\n checkTableOption(options.table, chart);\n if (announce !== undefined && typeof announce !== \"boolean\" && typeof announce !== \"function\") throw new TypeError(`${chart}: announce must be true, false or a function that returns the text to announce.`);\n}\n","// A chart's transitions: one in flight at a time, drawn every frame until its tweens settle, then landed\n// exactly on the layout. An update's change, played through the runner in the order it expects. And\n// the small tests a chart's retarget makes: whether a value still has to move, whether a mark moved.\n\nimport type { Animated, Clock, MarkGeometry } from \"../../core\";\nimport type { RunInput, Runner } from \"../../core/runner\";\nimport type { ChartEvents } from \"./events\";\nimport type { ChartHover } from \"./hover\";\nimport type { Leave, LeavingMark, LeavingMarks } from \"./leaving\";\n\nexport interface ChartTransitionsOptions {\n readonly clock: Clock;\n readonly runner: Pick<Runner, \"settle\">;\n readonly leaving: Pick<LeavingMarks<LeavingMark>, \"sweep\">;\n /** Draws what moved since the last frame. */\n draw(): void;\n /** Draws exactly the layout once a transition settles: the frames in between are computed, this is laid out. */\n land(): void;\n}\n\nexport interface ChartTransitions {\n /**\n * Draws the first frame of a transition whose tweens, `running`, have just started, then every frame\n * until they've all settled. Resolves when it settles. One still in flight is taken over: its waiters\n * wait for this one instead.\n */\n run(running: readonly Promise<unknown>[]): Promise<void>;\n /** Resolves the latest update()'s promise early: another update() supersedes it. */\n supersede(): void;\n /**\n * The promise update() returns: it resolves once `settled` has and the marks the update removed are\n * gone (their exit effects done), or as soon as another update() supersedes it.\n */\n wait(settled: Promise<void>, leaves: readonly Leave[]): Promise<void>;\n destroy(): void;\n}\n\nexport function chartTransitions(options: ChartTransitionsOptions): ChartTransitions {\n const { clock } = options;\n /** The transition in flight: resolved when it settles. */\n let transition: { readonly id: number; readonly waiters: readonly (() => void)[] } | undefined;\n let transitions = 0;\n let unfollow: (() => void) | undefined;\n /** Resolves the latest update()'s promise early, when another update() supersedes it. */\n let supersede: (() => void) | undefined;\n let destroyed = false;\n\n function settle(id: number): void {\n if (destroyed || transition?.id !== id) return;\n const { waiters } = transition;\n transition = undefined;\n unfollow?.();\n unfollow = undefined;\n options.land();\n options.runner.settle();\n options.leaving.sweep();\n for (const resolve of waiters) resolve();\n }\n\n return {\n run(running) {\n options.draw();\n const id = ++transitions;\n return new Promise<void>((resolve) => {\n transition = { id, waiters: [...(transition?.waiters ?? []), resolve] };\n if (running.length === 0) {\n settle(id);\n return;\n }\n // Subscribed after the tweens just started, so each frame draws once they've all moved.\n unfollow?.();\n unfollow = clock.onFrame(() => options.draw());\n void Promise.all(running).then(() => settle(id));\n });\n },\n supersede: () => supersede?.(),\n wait(settled, leaves) {\n return new Promise<void>((resolve) => {\n supersede = resolve;\n void settled.then(() => Promise.all(leaves.map((leave) => leave.gone))).then(() => resolve());\n });\n },\n destroy() {\n destroyed = true;\n transition = undefined;\n unfollow?.();\n supersede?.();\n }\n };\n}\n\n/** What an update changed, in the chart's own mark records. */\nexport interface ChartDiff<R> {\n readonly entering: R[];\n readonly exiting: R[];\n /** Values changed: update effects run. A move alone (a re-sort, a new scale) isn't a change. */\n readonly changed: { readonly record: R; readonly from: MarkGeometry }[];\n}\n\nexport interface PlayUpdateOptions<D, R extends LeavingMark> {\n readonly runner: Runner<D>;\n readonly events: ChartEvents<D>;\n readonly hover: Pick<ChartHover, \"dropGone\" | \"sync\">;\n readonly leaving: Pick<LeavingMarks<R>, \"sweep\">;\n /** Where a mark is heading: what enter and update report as a change starts. */\n input(record: R): RunInput<D>;\n /** The mark as it is on screen: what exit reports, so it matches what's on its way out. */\n onScreen(record: R): RunInput<D>;\n /**\n * Whether update() was given `data`. Then it's an update even if no value changed (a matchweek where\n * nobody scores), so the runner ends the update runs of the marks it leaves alone. Without `data`,\n * it's one only if a value changed or a mark came or went: `update({ on })` alone keeps them.\n */\n readonly data: boolean;\n /**\n * With a new `on`: swaps the runner's effects once `arrange` has matched the new layout to the\n * marks, before the runner hears the change, so the new effects start on the marks as the update\n * leaves them and play its exit, update and enter. Given what changed, so it can leave out the\n * marks entering, which enter() starts.\n */\n swap?(diff: ChartDiff<R>): void;\n}\n\n/**\n * Plays an update's change through the runner, in the order it expects: interrupt; `arrange` matches\n * the new layout to the marks; new effects, if any, are swapped in; a hover whose mark has left ends; then exit, update and enter, each\n * followed by its events; `announce`; and the tab stop follows its key. The runner hears update() only\n * for an update (see `data`), so `update({ on })` alone keeps what the last one explained. The runner\n * then hears change() on every frame, and settle() once the transition settles. Returns the leaves to wait for.\n */\nexport function playUpdate<D, R extends LeavingMark>(\n options: PlayUpdateOptions<D, R>,\n arrange: () => ChartDiff<R>,\n announce: (diff: ChartDiff<R>) => void\n): Leave[] {\n const { runner, events, input, onScreen } = options;\n runner.interrupt();\n const diff = arrange();\n options.swap?.(diff);\n options.hover.dropGone();\n const leaves = diff.exiting.map((record) => record.leave!);\n const exited = runner.exit(diff.exiting.map(onScreen));\n void exited.then(() => {\n for (const leave of leaves) leave.exited = true;\n options.leaving.sweep();\n });\n events.emitEach(\"exit\", diff.exiting, onScreen);\n if (options.data || diff.changed.length > 0 || diff.entering.length > 0 || diff.exiting.length > 0) {\n runner.update(diff.changed.map(({ record, from }) => ({ ...input(record), from })));\n }\n events.emitEach(\"update\", diff.changed, ({ record, from }) => ({ ...input(record), from }));\n runner.enter(diff.entering.map(input));\n events.emitEach(\"enter\", diff.entering, input);\n announce(diff);\n // Focus stayed with its key. If that mark is leaving, focus moves to its nearest neighbour, whose\n // hover the runner holds until the change settles.\n options.hover.sync();\n return leaves;\n}\n\n/** Still animating, or resting somewhere else than `to`. */\nexport function busy<T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean): boolean {\n return value.animating || !equal(value.value, to);\n}\n\nexport const same = (a: number, b: number): boolean => a === b;\n\n/** The same fields with the same values. */\nexport function sameFields<T extends object>(a: T, b: T): boolean {\n const keys = Object.keys(a) as (keyof T)[];\n return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);\n}\n\n/** Whether a mark looks different: its outline, its segments, or its labels' boxes. Its runs hear about it through change(). */\nexport function geometryChanged(from: MarkGeometry, to: MarkGeometry): boolean {\n if (from.outline.d !== to.outline.d || labelsMoved(from, to)) return true;\n const a = from.segments ?? [];\n const b = to.segments ?? [];\n return a.length !== b.length || a.some((segment, i) => segment.key !== b[i]!.key || segment.outline.d !== b[i]!.outline.d);\n}\n\n/** Whether a mark's `labelBounds` differ: text placed past them has to follow. */\nexport function labelsMoved(from: MarkGeometry, to: MarkGeometry): boolean {\n const a = from.labelBounds;\n const b = to.labelBounds;\n if (a === b) return false;\n if (!a || !b || a.length !== b.length) return true;\n return a.some((box, i) => box.x !== b[i]!.x || box.y !== b[i]!.y || box.width !== b[i]!.width || box.height !== b[i]!.height);\n}\n","// What a chart follows on the page besides its options: its container's width, web fonts arriving,\n// and the motion that times its CSS hover transitions. Each returns its stop.\n\nimport type { Clock } from \"../../core\";\nimport type { ChartMotion } from \"../motion\";\n\n/**\n * Follows the container's width with a ResizeObserver, from `width`, the one laid out at. `resize`\n * hears of a change of half a px or more, at most once a frame.\n */\nexport function watchWidth(container: Element, clock: Clock, width: number, resize: (width: number) => void): () => void {\n if (typeof ResizeObserver !== \"function\") return () => {};\n let measured = width;\n let pending = width;\n let stopFrame: (() => void) | undefined;\n const observer = new ResizeObserver((entries) => {\n const next = entries[entries.length - 1]?.contentRect.width ?? 0;\n if (!(next > 0) || Math.abs(next - pending) < 0.5) return;\n pending = next;\n // Once per frame, outside the observer callback, so the new height can't loop back into it.\n stopFrame ??= clock.onFrame(() => {\n stopFrame?.();\n stopFrame = undefined;\n if (Math.abs(pending - measured) < 0.5) return;\n measured = pending;\n resize(measured);\n });\n });\n observer.observe(container);\n return () => {\n observer.disconnect();\n stopFrame?.();\n };\n}\n\n/** Calls `loaded` each time web fonts finish loading: text measured before then was measured in a fallback font. */\nexport function watchFonts(doc: Document, loaded: () => void): () => void {\n const fonts = (doc as Document & { fonts?: EventTarget }).fonts;\n fonts?.addEventListener?.(\"loadingdone\", loaded);\n return () => fonts?.removeEventListener?.(\"loadingdone\", loaded);\n}\n\n/** CSS hover transitions read their duration, `--ec-hover-duration`, from motion, like everything else. */\nexport function watchHoverDuration(svg: SVGSVGElement, motion: ChartMotion): () => void {\n const sync = (): void => svg.style.setProperty(\"--ec-hover-duration\", `${motion.duration(100, \"feedback\")}ms`);\n sync();\n return motion.subscribe(sync);\n}\n","// The chart's tooltip: an HTML box beside the hovered or focused mark, placed from the mark's bounds\n// and centre, or at a point, such as a crosshair over the points it crosses. The box is aria-hidden, so it isn't read twice: each mark's aria-label has the values,\n// and its accessible description is `markDescription`'s text or, by default, a tooltip function's.\n// Its text is only ever set as text, never parsed as HTML, so a tooltip function can't inject markup.\n// While it shows it takes the pointer, so it can be hovered (WCAG 1.4.13): beside a mark, a clear\n// bridge spans the gap to the mark, so the pointer can cross from one to the other. One that comes up\n// under a pointer that didn't move onto it lets the pointer through until the pointer is off it.\n\nimport { matrix, type Matrix, type MarkGeometry, type MotionView } from \"../core\";\nimport { report } from \"../core/report\";\nimport { svgElement } from \"./render/svg\";\n\n/** The `tooltip` option: on (the default text), off, or a function giving a row's text. */\nexport type TooltipOption<D> = boolean | ((d: D) => string);\n\n/** Plain text (a function's, with \"\\n\" for line breaks), or a bold title over lines. */\nexport type TooltipContent = string | { readonly title: string; readonly lines: readonly string[] };\n\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\n/** What the box is placed against, in the chart box's px: the x to centre on, and the mark's top and bottom edges. */\nexport interface TooltipAnchor {\n readonly x: number;\n readonly top: number;\n readonly bottom: number;\n}\n\n/** A point the box is placed at instead of a mark, in the <svg>'s viewBox units: the x to centre on, and the top and bottom to keep clear. */\nexport interface TooltipPoint {\n readonly x: number;\n readonly top: number;\n readonly bottom: number;\n}\n\nexport interface TooltipPlacement {\n /** The box's top-left corner, in the chart box's px. */\n readonly x: number;\n readonly y: number;\n readonly side: \"above\" | \"below\";\n}\n\nexport interface Tooltip {\n /**\n * Shows the tooltip beside `mark` (in the <svg>'s viewBox units), or moves it there. `transform` is\n * an effect's transform on the mark, which the tooltip follows. Its text is worked out again only\n * when `row` or the option changes: the default `summary`, a function's result, or nothing with\n * `tooltip: false`.\n */\n show(mark: MarkGeometry, row: { readonly datum: unknown }, summary: () => TooltipContent, transform?: Matrix): void;\n /**\n * Shows the tooltip at `point` instead of beside a mark, or moves it there: centred on its x, above\n * its top or, without room there, below its bottom. A line chart's crosshair gives its x and the\n * highest and lowest points it crosses. The text is worked out as show()'s is.\n */\n showAt(point: TooltipPoint, row: { readonly datum: unknown }, summary: () => TooltipContent): void;\n /**\n * Gives the mark's `element` its accessible description for `row` (aria-describedby, to a <desc>\n * inside it): `markDescription`'s text when it's a function, nothing when it's false, and otherwise\n * a tooltip function's text, so what a custom tooltip adds beyond the values reaches screen readers.\n * The default tooltip text says nothing the mark's aria-label doesn't, so it describes nothing.\n */\n describe(element: SVGElement, row: { readonly datum: unknown }): void;\n /**\n * The tooltip while it shows, or undefined: its layer, holding the box and, beside a mark, the\n * bridge to it. Both take the pointer.\n */\n element(): HTMLElement | undefined;\n hide(): void;\n destroy(): void;\n}\n\n/** Px between the mark and the box, as in the prototype. */\nconst GAP = 12;\n/** Px the bridge reaches into the mark, so no sliver is left between them. */\nconst OVERLAP = 1;\n/** Base ms for showing and hiding: hover feedback. */\nconst FADE = 100;\n/** For description ids, unique in the page. */\nlet described = 0;\n\n/**\n * Where the box goes: centred on the mark, above it, or below it when there isn't room above. When\n * neither side has room it takes the side with more. `side` picks it instead. It's clamped to the\n * box's left and right edges (to the left edge when it's wider), but never moved over the mark it\n * describes.\n */\nexport function placeTooltip(anchor: TooltipAnchor, size: Size, box: Size, side?: TooltipPlacement[\"side\"]): TooltipPlacement {\n const above = anchor.top - GAP;\n const below = box.height - anchor.bottom - GAP;\n side ??= size.height <= above || above >= below ? \"above\" : \"below\";\n return {\n x: Math.max(0, Math.min(box.width - size.width, anchor.x - size.width / 2)),\n y: side === \"above\" ? above - size.height : anchor.bottom + GAP,\n side\n };\n}\n\n/**\n * The default text: the category, then each series' value in `format` with its label, or its name\n * when it has none (\"16 goals · 4 assists\"), then the total when there's more than one. A lone value\n * read by a function (its series is \"value\") goes unnamed unless it's labelled, as in the marks' names.\n * `total: false` leaves the total out, for series that don't add up (goals and xG at one x).\n */\nexport function summaryContent(\n category: string,\n values: readonly { readonly series: string; readonly label?: string; readonly value: number }[],\n format: (value: number) => string,\n options: { readonly total?: boolean } = {}\n): TooltipContent {\n const lone = values.length === 1 && values[0]!.series === \"value\" && (values[0]!.label ?? \"value\") === \"value\";\n const lines = [values.map((v) => (lone ? format(v.value) : `${format(v.value)} ${v.label ?? v.series}`)).join(\" · \")];\n if (values.length > 1 && options.total !== false) lines.push(`${format(values.reduce((sum, v) => sum + v.value, 0))} total`);\n return { title: category, lines };\n}\n\n/**\n * The tooltip for a chart's <svg>. The box is made the first time it shows, in a positioned layer\n * just after the <svg>, and placed in px from both elements' boxes, so it lands right whatever the\n * page's layout. Showing and hiding fade over `feedback` timing, so they're instant with motion off.\n */\nexport function chartTooltip<D>(\n svg: SVGSVGElement,\n options: {\n readonly motion: Pick<MotionView, \"duration\">;\n readonly option: () => TooltipOption<D> | undefined;\n /** The `markDescription` option: a function, false, or unset (a tooltip function's text). */\n readonly description?: () => false | ((d: D) => string) | undefined;\n }\n): Tooltip {\n let layer: HTMLDivElement | undefined;\n let box: HTMLDivElement | undefined;\n let bridge: HTMLDivElement | undefined;\n /** Each row's text, and the option it was worked out with: a function is called once per row. */\n let texts = new WeakMap<object, { readonly option: TooltipOption<D> | undefined; readonly content: TooltipContent | undefined }>();\n /** The text the box shows. */\n let rendered: string | undefined;\n /** Where a mouse or pen last was, in client px. */\n let pointer: { readonly x: number; readonly y: number } | undefined;\n /**\n * Whether it came up, or moved, under a pointer that hadn't moved onto it: a crosshair's column\n * reaches it, so it can. Then it lets the pointer through, so it doesn't catch a pointer running\n * along the chart, until the pointer is off it.\n */\n let through = false;\n /** The bridge's trapezoid in the layer's px, while there's one. */\n let shape: Trapezoid | undefined;\n\n const timing = (element: HTMLElement): void => element.style.setProperty(\"--ec-hover-duration\", `${options.motion.duration(FADE, \"feedback\")}ms`);\n\n const shown = (): boolean => box?.classList.contains(\"ec-tooltip-shown\") ?? false;\n /** Whether the pointer is over the box or the bridge. */\n const under = (): boolean => {\n if (!pointer || !box || !layer) return false;\n const { x, y } = pointer;\n const { left, right, top, bottom } = box.getBoundingClientRect();\n if (x > left && x < right && y > top && y < bottom) return true;\n if (!shape) return false;\n const origin = layer.getBoundingClientRect();\n return inside(shape, x - origin.left, y - origin.top);\n };\n const letThrough = (on: boolean): void => {\n through = on;\n layer?.classList.toggle(\"ec-tooltip-through\", on);\n };\n /** The document's pointer, heard before the chart hears it. */\n const track = (event: PointerEvent): void => {\n pointer = event.pointerType === \"touch\" ? undefined : { x: event.clientX, y: event.clientY };\n if (through && !under()) letThrough(false);\n };\n\n svg.ownerDocument.addEventListener(\"pointerover\", track, true);\n svg.ownerDocument.addEventListener(\"pointermove\", track, true);\n\n /** The box, in its layer just after the <svg>, with the bridge after it. */\n function made(): HTMLDivElement {\n if (!layer || !box || !bridge) {\n const doc = svg.ownerDocument;\n layer = doc.createElement(\"div\");\n layer.className = \"ec-tooltip-layer\";\n box = doc.createElement(\"div\");\n box.className = \"ec-tooltip\";\n box.setAttribute(\"aria-hidden\", \"true\");\n bridge = doc.createElement(\"div\");\n bridge.className = \"ec-tooltip-bridge\";\n bridge.setAttribute(\"aria-hidden\", \"true\");\n layer.append(box, bridge);\n }\n if (layer.previousSibling !== svg) svg.after(layer);\n return box;\n }\n\n function contentFor(row: { readonly datum: unknown }, summary: () => TooltipContent): TooltipContent | undefined {\n const option = options.option();\n const known = texts.get(row);\n if (known && known.option === option) return known.content;\n const content = text(option, row.datum as D, summary);\n texts.set(row, { option, content });\n return content;\n }\n\n function hide(): void {\n if (!box) return;\n timing(box);\n box.classList.remove(\"ec-tooltip-shown\");\n letThrough(false);\n }\n\n /**\n * Shows the box with `row`'s text, placed against `anchor`: it turns viewBox units into the chart\n * box's px with `toPx`, at rest or, with `moved`, as an effect has moved the mark. An anchor with a\n * left and right edge is a mark, and gets a bridge.\n */\n function place(row: { readonly datum: unknown }, summary: () => TooltipContent, anchor: (toPx: ToPx, moved: boolean) => Anchored, moved: boolean): void {\n const content = contentFor(row, summary);\n if (content === undefined) {\n hide();\n return;\n }\n const tip = made();\n // The pointer on it, having moved onto it, stays on it wherever it goes.\n const held = shown() && !through && under();\n const key = typeof content === \"string\" ? `text:${content}` : JSON.stringify(content);\n if (key !== rendered) {\n render(tip, content);\n rendered = key;\n }\n // The <svg> may be scaled to fit its container: its viewBox units become px by its width.\n const view = viewBox(svg);\n const chart = svg.getBoundingClientRect();\n const k = chart.width > 0 && view.width > 0 ? chart.width / view.width : 1;\n const toPx: ToPx = { x: (x) => (x - view.x) * k, y: (y) => (y - view.y) * k };\n const area = chart.width > 0 ? { width: chart.width, height: chart.height } : { width: view.width, height: view.height };\n const size = { width: tip.offsetWidth, height: tip.offsetHeight };\n const near = anchor(toPx, moved);\n // The side is the mark's at rest, so an effect moving it (a wiggle) can't flip the box back and forth.\n const placed = placeTooltip(near, size, area, moved ? placeTooltip(anchor(toPx, false), size, area).side : undefined);\n const origin = layer!.getBoundingClientRect();\n // From the chart box's px to the layer's.\n const dx = chart.left - origin.left;\n const dy = chart.top - origin.top;\n const left = Math.round(dx + placed.x);\n const top = Math.round(dy + placed.y);\n tip.style.left = `${left}px`;\n tip.style.top = `${top}px`;\n tip.setAttribute(\"data-side\", placed.side);\n const mark = near.left === undefined || near.right === undefined ? undefined : { left: dx + near.left, right: dx + near.right, top: dy + near.top, bottom: dy + near.bottom };\n shape = span(bridge!, { left, top, ...size }, mark, placed.side);\n timing(tip);\n tip.classList.add(\"ec-tooltip-shown\");\n letThrough(!held && under());\n }\n\n return {\n show(mark, row, summary, transform) {\n const anchor = (toPx: ToPx, moved: boolean): Anchored => {\n const m = moved ? transform : undefined;\n const { x, y, width, height } = mark.bounds;\n const corners = [{ x, y }, { x: x + width, y }, { x, y: y + height }, { x: x + width, y: y + height }].map((corner) => (m ? matrix.apply(m, corner) : corner));\n const xs = corners.map((corner) => corner.x);\n const ys = corners.map((corner) => corner.y);\n const center = m ? matrix.apply(m, mark.center) : mark.center;\n return { x: toPx.x(center.x), top: toPx.y(Math.min(...ys)), bottom: toPx.y(Math.max(...ys)), left: toPx.x(Math.min(...xs)), right: toPx.x(Math.max(...xs)) };\n };\n place(row, summary, anchor, transform !== undefined);\n },\n showAt(point, row, summary) {\n place(row, summary, (toPx) => ({ x: toPx.x(point.x), top: toPx.y(point.top), bottom: toPx.y(point.bottom) }), false);\n },\n describe(element, row) {\n const own = options.description?.();\n let content: TooltipContent | undefined;\n if (own === false) content = undefined;\n else if (typeof own === \"function\") {\n try {\n const text: unknown = own(row.datum as D);\n content = typeof text === \"string\" && text !== \"\" ? text : undefined;\n } catch (error) {\n report(error);\n content = undefined;\n }\n } else content = typeof options.option() === \"function\" ? contentFor(row, () => \"\") : undefined;\n let desc = element.querySelector<SVGDescElement>(\":scope > desc.ec-description\");\n if (typeof content !== \"string\") {\n if (!desc) return;\n if (element.getAttribute(\"aria-describedby\") === desc.id) element.removeAttribute(\"aria-describedby\");\n desc.remove();\n return;\n }\n desc ??= svgElement(\"desc\", { class: \"ec-description\", id: `ec-description-${++described}` }, element);\n if (desc.textContent !== content) desc.textContent = content;\n element.setAttribute(\"aria-describedby\", desc.id);\n },\n element: () => (shown() ? layer : undefined),\n hide,\n destroy() {\n svg.ownerDocument.removeEventListener(\"pointerover\", track, true);\n svg.ownerDocument.removeEventListener(\"pointermove\", track, true);\n layer?.remove();\n layer = undefined;\n box = undefined;\n bridge = undefined;\n shape = undefined;\n through = false;\n texts = new WeakMap();\n rendered = undefined;\n }\n };\n}\n\n/** A mark's edges in px. */\ninterface Edges {\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly bottom: number;\n}\n\n/** What the box is placed against in the chart box's px and, for a mark, its left and right edges. */\ninterface Anchored extends TooltipAnchor {\n readonly left?: number;\n readonly right?: number;\n}\n\n/** A trapezoid with level top and bottom edges: their y's, and each edge's left and right. */\ninterface Trapezoid {\n readonly top: number;\n readonly bottom: number;\n readonly upper: { readonly left: number; readonly right: number };\n readonly lower: { readonly left: number; readonly right: number };\n}\n\n/** Whether a point is inside a trapezoid, off its edges. */\nfunction inside({ top, bottom, upper, lower }: Trapezoid, x: number, y: number): boolean {\n if (y <= top || y >= bottom) return false;\n const t = (y - top) / (bottom - top);\n return x > upper.left + (lower.left - upper.left) * t && x < upper.right + (lower.right - upper.right) * t;\n}\n\n/**\n * Spans the bridge across the gap between the box and `mark`, in the layer's px: a trapezoid from the\n * box's edge to the mark's, a px into it, so the pointer can go straight from one to the other without\n * leaving the hover. It's clear, and takes only the pointer. At a point there's none: a crosshair's\n * target is its whole column, which reaches the box. Gives the trapezoid, if there's one.\n */\nfunction span(bridge: HTMLElement, box: { readonly left: number; readonly top: number; readonly width: number; readonly height: number }, mark: Edges | undefined, side: TooltipPlacement[\"side\"]): Trapezoid | undefined {\n bridge.hidden = mark === undefined;\n if (!mark) return undefined;\n const edge = { left: box.left, right: box.left + box.width };\n // The upper edge and the lower one, with their y's.\n const [upper, lower, top, bottom] =\n side === \"above\" ? [edge, mark, box.top + box.height, Math.round(mark.top + OVERLAP)] : [mark, edge, Math.round(mark.bottom - OVERLAP), box.top];\n const left = Math.round(Math.min(upper.left, lower.left));\n const width = Math.round(Math.max(upper.right, lower.right)) - left;\n const height = Math.max(0, bottom - top);\n const x = (value: number): string => `${Math.round(value) - left}px`;\n bridge.style.left = `${left}px`;\n bridge.style.top = `${top}px`;\n bridge.style.width = `${width}px`;\n bridge.style.height = `${height}px`;\n bridge.style.setProperty(\"clip-path\", `polygon(${x(upper.left)} 0px, ${x(upper.right)} 0px, ${x(lower.right)} ${height}px, ${x(lower.left)} ${height}px)`);\n const round = (edge: { readonly left: number; readonly right: number }) => ({ left: Math.round(edge.left), right: Math.round(edge.right) });\n return { top, bottom: top + height, upper: round(upper), lower: round(lower) };\n}\n\n/** None with `false`; a function's text, where an empty string or a throw shows none; otherwise the default. */\nfunction text<D>(option: TooltipOption<D> | undefined, datum: D, summary: () => TooltipContent): TooltipContent | undefined {\n if (option === false) return undefined;\n if (typeof option !== \"function\") return summary();\n try {\n const result = option(datum);\n return result === undefined || result === null || result === \"\" ? undefined : String(result);\n } catch (error) {\n report(error);\n return undefined;\n }\n}\n\nfunction render(box: HTMLDivElement, content: TooltipContent): void {\n if (typeof content === \"string\") {\n box.textContent = content;\n return;\n }\n const doc = box.ownerDocument;\n const line = (value: string, className?: string): HTMLDivElement => {\n const div = doc.createElement(\"div\");\n if (className) div.className = className;\n div.textContent = value;\n return div;\n };\n box.replaceChildren(line(content.title, \"ec-tooltip-title\"), ...content.lines.map((value) => line(value)));\n}\n\n/** Turns viewBox units into px in the chart's box. */\ninterface ToPx {\n x(x: number): number;\n y(y: number): number;\n}\n\n/** The <svg>'s viewBox, or its size from 0, 0 when it has none. */\nfunction viewBox(svg: SVGSVGElement): { readonly x: number; readonly y: number; readonly width: number; readonly height: number } {\n const parts = (svg.getAttribute(\"viewBox\") ?? \"\").split(/[\\s,]+/).map(Number);\n if (parts.length === 4 && parts.every(Number.isFinite)) return { x: parts[0]!, y: parts[1]!, width: parts[2]!, height: parts[3]! };\n return { x: 0, y: 0, width: Number(svg.getAttribute(\"width\")) || 0, height: Number(svg.getAttribute(\"height\")) || 0 };\n}\n","// barChart: the thin reference bar chart. Horizontal bars or vertical columns, plain or stacked; keyed\n// marks described with describe.bar; a measured layout; axis, grid and labels in theme colours;\n// colours by series or, with one series, by category; built-in hover dimming; pointer, touch and\n// keyboard hover with a tooltip; a legend for stacks or categories; a data table and, with `announce`, a\n// live region for screen readers. update() animates the change: staged in presentation (values, then positions), in one short stage\n// in analysis, at once when motion is off.\n//\n// The chart never names an effect: it resolves `on` through the presets it's handed and plays them\n// through the runner, which draws on the SVG surface. What doesn't depend on bars (events, hover and\n// focus, transitions and leaving marks, DOM order, size and fonts) is in shell/.\n\nimport type { AnimateOptions, Animated, TweenResult } from \"../core\";\nimport { animated, defaultClock, interpolateNumber, interpolateRecord } from \"../core\";\nimport { resolveEffects } from \"../core/registry\";\nimport { report } from \"../core/report\";\nimport { createRunner, type RunInput } from \"../core/runner\";\nimport { chartAnnouncer, changeText, type Announcer, type SortName } from \"./announce\";\nimport { barEncoding, layoutBars, placeRow, placeTick, type BarFrame, type BarLayout, type BarRow, type BarValue } from \"./bar-layout\";\nimport { toColorAssignment } from \"./colors\";\nimport { chartLegend } from \"./legend\";\nimport { linkable } from \"./link\";\nimport { chartMotion } from \"./motion\";\nimport { svgMarkHandle, type StyledPart, type SvgMarkHandle } from \"./render/mark-style\";\nimport { svgSurface } from \"./render/surface\";\nimport { setAttributes, setStyles, sizeAttributes, svgElement, transformAttribute } from \"./render/svg\";\nimport { placeText, textMeasure } from \"./render/text\";\nimport { injectStyles, markColorStyles, seriesColors } from \"./render/theme\";\nimport { seriesLabel } from \"./series\";\nimport { chartEvents } from \"./shell/events\";\nimport { decimals, format, round } from \"./shell/format\";\nimport { chartHover } from \"./shell/hover\";\nimport { chartLabel } from \"./shell/labels\";\nimport { leavingMarks, type Leave } from \"./shell/leaving\";\nimport { orderElements } from \"./shell/order\";\nimport { checkChartOptions, checkNeeds, containerWidth, describeChart, nextEffects, resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport { busy, chartTransitions, geometryChanged, playUpdate, same, sameFields, type ChartDiff } from \"./shell/transitions\";\nimport { watchFonts, watchHoverDuration, watchWidth } from \"./shell/watch\";\nimport { chartTable, tableModel, type TableModel } from \"./table\";\nimport { chartTooltip, summaryContent } from \"./tooltip\";\nimport type { BarChartOptions, Chart } from \"./types\";\n\nexport type { ChartEnv } from \"./shell/setup\";\n\nexport type BarChart<D> = Chart<D, BarChartOptions<D>>;\n\n/** Signed values by series, in data units. */\ntype Values = Readonly<Record<string, number>>;\n\ninterface MarkRecord<D> {\n readonly key: string;\n /** Where the mark is heading, or rests: its row in the latest layout (its last one while it leaves). */\n row: BarRow<D>;\n /** What's on screen now. */\n shown: BarRow<D>;\n readonly group: SVGGElement;\n readonly hit: SVGRectElement;\n readonly label: SVGTextElement;\n /** Holds the segments; effects' transform and opacity go here. */\n readonly body: SVGGElement;\n readonly value: SVGTextElement;\n readonly paths: Map<string, SVGPathElement>;\n parts: StyledPart[];\n readonly handle: SvgMarkHandle;\n /** In data units, so the bar's length follows the animated scale and always reads true against the axis. */\n readonly values: Animated<Values>;\n /** The order segments are drawn in: the layout's, with series on their way out kept where they were. */\n series: readonly string[];\n /** Position along the category axis, in bands. */\n readonly slot: Animated<number>;\n /** 0 to 1. A mark entering or leaving fades its labels; its bar grows or shrinks. */\n readonly presence: Animated<number>;\n /** The value label counts between totals, rounded to this many decimals; undefined shows the row's own text. */\n count: number | undefined;\n /** Set while the mark leaves. */\n leave: Leave | undefined;\n}\n\ninterface TickRecord {\n readonly value: number;\n readonly line: SVGLineElement;\n readonly label: SVGTextElement;\n /** Ticks the scale gains fade in, and ones it loses fade out. */\n readonly opacity: Animated<number>;\n /** In the latest layout. */\n wanted: boolean;\n}\n\n/** What an update changed. A re-sort or a new scale only moves a mark: its values didn't change. */\ntype Diff<D> = ChartDiff<MarkRecord<D>>;\n\n/** Base ms for each stage of a data change: values, then positions. Unstaged, a change takes as long as its stages together, which analysis scales down. */\nconst STAGE = 500;\n/** The focus ring's px: a gap in the surface colour around the mark, then the ring. */\nconst RING_GAP = 2;\nconst RING = 2;\n\nexport function barChart<D>(target: string | Element, options: BarChartOptions<D>, env: ChartEnv): BarChart<D> {\n const container = resolveTarget(target, \"barChart\");\n checkOptions(options);\n let current = options;\n const motion = chartMotion(options.motion, env.motion);\n let effects = resolveEffects(options.on, env.presets);\n let colors = toColorAssignment(options.colors);\n const clock = env.clock ?? defaultClock;\n const doc = container.ownerDocument;\n injectStyles(doc);\n\n // A named group of marks, each an image with its own name: see \"ARIA structure\" in docs/architecture.md.\n const svg = svgElement(\"svg\", { class: \"ec-chart ec-bar-chart\", role: \"group\" }, container);\n const grid = svgElement(\"g\", { class: \"ec-grid\", \"aria-hidden\": \"true\" }, svg);\n const axis = svgElement(\"g\", { class: \"ec-axis\", \"aria-hidden\": \"true\" }, svg);\n // Behind the marks, so it can't cover them; the gap keeps it apart from a bar in the same colour.\n const ring = svgElement(\"g\", { class: \"ec-focus\", \"aria-hidden\": \"true\", visibility: \"hidden\" }, svg);\n const ringPaths = [\n svgElement(\"path\", { class: \"ec-focus-ring\", \"stroke-width\": 2 * (RING_GAP + RING), \"stroke-linejoin\": \"round\" }, ring),\n svgElement(\"path\", { class: \"ec-focus-gap\", \"stroke-width\": 2 * RING_GAP, \"stroke-linejoin\": \"round\" }, ring)\n ];\n const marksLayer = svgElement(\"g\", { class: \"ec-marks\" }, svg);\n const overlay = svgElement(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" }, svg);\n const measure = textMeasure(svg);\n\n /** Marks on screen, in visual order. */\n let order: MarkRecord<D>[] = [];\n const records = new Map<string, MarkRecord<D>>();\n /** Marks on their way out: fading, or waiting for their exit effects. */\n const leaving = leavingMarks<MarkRecord<D>>((record) => record.values.animating || record.presence.animating);\n const byGroup = new WeakMap<Element, MarkRecord<D>>();\n const events = chartEvents<D>(\"barChart\");\n let measuredWidth = containerWidth(container);\n let destroyed = false;\n\n let laidOut: BarLayout<D>;\n let firstTable: TableModel | undefined;\n try {\n // Throws on data it can't draw, or a table column it can't read. Nothing but the <svg> is in\n // place yet (no listeners, observers or elements beside it), so that's all to undo.\n laidOut = layout(current);\n firstTable = tableFor(current, laidOut);\n } catch (error) {\n svg.remove();\n throw error;\n }\n\n const find = (key: string): MarkRecord<D> | undefined => records.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay,\n // Looked up on each call, so the handle follows the mark's record.\n mark: (key) => ({\n set: (style) => {\n find(key)?.handle.set(style);\n hover.restyled(key);\n },\n reset: () => {\n find(key)?.handle.reset();\n hover.restyled(key);\n }\n }),\n colors: (key) => find(key)?.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const tooltip = chartTooltip<D>(svg, { motion, option: () => current.tooltip, description: () => current.markDescription });\n const legend = chartLegend(svg);\n const table = chartTable(svg);\n let announcer: Announcer | undefined = current.announce ? chartAnnouncer(svg) : undefined;\n\n // ── Animated state ─────────────────────────────────────────────────────────\n // One animated value per mark property (values, slot, presence) plus the scale and the bands, so a\n // new update() mid-flight retargets each from where it is and nothing jumps.\n\n let orientation = laidOut.orientation;\n const ticks = new Map<number, TickRecord>();\n /** What changed since the last frame was drawn. */\n const dirty = new Set<MarkRecord<D>>();\n let frameMoved = false;\n let ticksFaded = false;\n const scale = animated(laidOut.frame.scale, interpolateRecord, { clock, motion, onChange: () => (frameMoved = true) });\n const bands = animated(laidOut.frame.bands, interpolateRecord, { clock, motion, onChange: () => (frameMoved = true) });\n\n const transitions = chartTransitions({ clock, runner, leaving, draw, land });\n\n // ── Drawing ────────────────────────────────────────────────────────────────\n\n function layout(opts: BarChartOptions<D>, using = effects): BarLayout<D> {\n const encoding = barEncoding(opts);\n checkNeeds(using, encoding.series.map((s) => s.series), \"barChart\");\n return layoutBars({\n data: opts.data,\n encoding,\n sort: opts.sort,\n width: opts.width ?? measuredWidth,\n height: opts.height,\n format: format(opts),\n measure,\n room: opts.room ?? 0\n });\n }\n\n /** A new mark: drawn as laid out, or, when it enters, at its slot with nothing showing yet. */\n function createRecord(row: BarRow<D>, entering: boolean): MarkRecord<D> {\n // An image: its aria-label says it all, and its text and shapes aren't read on their own.\n const group = svgElement(\"g\", { class: \"ec-mark\", \"data-key\": row.key, role: \"img\" }, marksLayer);\n const env = { clock, motion, onChange: () => dirty.add(record) };\n const values = valuesOf(row);\n const record: MarkRecord<D> = {\n key: row.key,\n row,\n shown: row,\n group,\n hit: svgElement(\"rect\", { class: \"ec-hit\" }, group),\n label: svgElement(\"text\", { class: \"ec-label\", \"aria-hidden\": \"true\" }, group),\n body: svgElement(\"g\", { class: \"ec-body\" }, group),\n value: svgElement(\"text\", { class: \"ec-value\", \"aria-hidden\": \"true\" }, group),\n paths: new Map(),\n parts: [],\n handle: svgMarkHandle(() => record),\n values: animated(entering ? zeros(values) : values, interpolateRecord, env),\n series: row.values.map((v) => v.series),\n slot: animated(row.slot, interpolateNumber, env),\n presence: animated(entering ? 0 : 1, interpolateNumber, env),\n count: undefined,\n leave: undefined\n };\n byGroup.set(group, record);\n drawMark(record, entering ? currentRow(record, currentFrame()) : row);\n return record;\n }\n\n function drawMark(record: MarkRecord<D>, row: BarRow<D>): void {\n const before = record.parts[0]?.colors.color;\n record.shown = row;\n setAttributes(record.hit, { ...row.hit });\n placeText(record.label, row.label);\n placeText(record.value, row.value);\n const presence = record.presence.value;\n const opacity = presence < 1 ? presence : undefined;\n setAttributes(record.label, { opacity });\n setAttributes(record.value, { opacity });\n const segments = row.geometry.segments ?? [];\n const keep = new Set<string>();\n // By category, the bar's own slot: the assignment never hears the series' name, so a shared one\n // keeps every slot for the categories.\n const ownColors = byCategory(current) ? seriesColors(colors.slot(record.key)) : undefined;\n record.parts = segments.map((segment) => {\n const series = segment.series ?? segment.key;\n keep.add(series);\n let element = record.paths.get(series);\n if (!element) {\n element = svgElement(\"path\", { class: \"ec-segment\", \"data-series\": series }, record.body);\n record.paths.set(series, element);\n }\n const partColors = ownColors ?? seriesColors(colors.slot(series));\n element.setAttribute(\"d\", segment.outline.d);\n setStyles(element, markColorStyles(partColors));\n return { element, d: segment.outline.d, colors: partColors, visible: segment.length >= 0.5 };\n });\n for (const [series, element] of record.paths) {\n if (keep.has(series)) continue;\n element.remove();\n record.paths.delete(series);\n }\n // Stack order, from the baseline, after the halo.\n const drawn = Array.from(record.body.children).filter((child) => child.classList.contains(\"ec-segment\"));\n if (record.parts.some((part, i) => drawn[i] !== part.element)) for (const part of record.parts) record.body.appendChild(part.element);\n record.handle.repaint();\n // A new palette or a different first series: overlays already drawn in \"mark\" follow.\n if (record.parts[0]?.colors.color !== before) surface.recolor(record.key);\n if (record.key === hover.ringKey) drawRing(record.key);\n }\n\n /** The focus ring follows the outline of the mark as it is on screen, moved with its body when an effect moves it. */\n function drawRing(key: string | undefined): void {\n const record = key === undefined ? undefined : records.get(key);\n if (!record) {\n ring.setAttribute(\"visibility\", \"hidden\");\n return;\n }\n for (const path of ringPaths) path.setAttribute(\"d\", record.shown.geometry.outline.d);\n const { transform } = record.handle.style;\n setAttributes(ring, { transform: transform && transformAttribute(transform), visibility: undefined });\n }\n\n /**\n * Draws the mark as `row`. Its runs hear about it when its geometry or its row changed, so\n * decorations follow: a label from a field the bar doesn't plot too.\n */\n function show(record: MarkRecord<D>, row: BarRow<D>): void {\n const moved = geometryChanged(record.shown.geometry, row.geometry) || record.shown.datum !== row.datum;\n drawMark(record, row);\n if (moved) runner.change(row.geometry, row.data);\n if (record.key === hover.key) showTooltip(record);\n }\n\n /** The tooltip beside the hovered mark as it is on screen, moved with its effects, with the text for where it's heading. */\n function showTooltip(record: MarkRecord<D>): void {\n const { row } = record;\n tooltip.show(record.shown.geometry, row, () => summaryContent(row.category, labelled(row.values, current), format(current)), record.handle.style.transform);\n }\n\n /** The legend for `next`: the series or, coloured by category, each bar's category in visual order. */\n function syncLegend(next: BarLayout<D>): void {\n if (byCategory(current)) {\n legend.categories(\n next.rows.map((row) => ({ key: row.key, label: row.category })),\n colors,\n current.legend\n );\n return;\n }\n legend.update(\n barEncoding(current).series.map((s) => ({ series: s.series, label: seriesLabel(current.seriesLabels, s.series) })),\n colors,\n current.legend\n );\n }\n\n /** The data table for `opts`, laid out as `next`: its rows in visual order. Throws on a column it can't read. */\n function tableFor(opts: BarChartOptions<D>, next: BarLayout<D>): TableModel | undefined {\n const encoding = barEncoding(opts);\n const field = encoding.orientation === \"horizontal\" ? opts.y : opts.x;\n return tableModel({\n option: opts.table,\n caption: opts.label,\n category: typeof field === \"string\" ? field : undefined,\n series: encoding.series.map((s) => s.series),\n label: (series) => seriesLabel(opts.seriesLabels, series),\n rows: next.rows.map((row) => ({ key: row.key, category: row.category, datum: row.datum, index: row.index, values: row.values, total: row.total })),\n format: format(opts)\n });\n }\n\n /** Says what an update changed, in the live region: the chart's summary, or the page's text from it. */\n function announceChange(previous: BarChartOptions<D>, diff: Diff<D>): void {\n const option = current.announce;\n if (!announcer || !option) return;\n const series = barEncoding(current).series.map((s) => s.series);\n const before = barEncoding(previous).series.map((s) => s.series);\n const sort = sortName(current.sort);\n const name = (record: MarkRecord<D>): string => record.row.category;\n const changed = diff.changed.map(({ record }) => record);\n const text = changeText({\n ...(current.label !== previous.label ? { label: current.label } : {}),\n // New series are said by their labels; new labels alone show the same view, so say nothing.\n ...(series.join(\"\\n\") !== before.join(\"\\n\") ? { series: series.map((s) => seriesLabel(current.seriesLabels, s)) } : {}),\n ...(sort !== sortName(previous.sort) || (sort === \"custom\" && current.sort !== previous.sort) ? { sort } : {}),\n changed: changed.map(name),\n added: diff.entering.map(name),\n removed: diff.exiting.map(name),\n count: order.length\n });\n if (typeof option !== \"function\") {\n announcer.say(text);\n return;\n }\n const key = (record: MarkRecord<D>): string => record.key;\n try {\n const said = option({ text, changed: changed.map(key), added: diff.entering.map(key), removed: diff.exiting.map(key) });\n if (said !== undefined && said !== null) announcer.say(String(said));\n } catch (error) {\n report(error);\n }\n }\n\n const currentFrame = (): BarFrame => ({ orientation, scale: scale.value, bands: bands.value });\n\n /** The mark as it is now, part way through a transition. */\n function currentRow(record: MarkRecord<D>, frame: BarFrame): BarRow<D> {\n const { row } = record;\n const now = record.values.value;\n const values = record.series.map((series) => ({ series, value: now[series] ?? 0 }));\n const total = values.reduce((sum, v) => sum + v.value, 0);\n const text = record.count === undefined ? row.value.text : format(current)(round(total, record.count));\n return placeRow(frame, { key: row.key, datum: row.datum, index: row.index, category: row.category, values, slot: record.slot.value, text, drawn: row.drawn }, measure);\n }\n\n function addTick(value: number, opacity: number): void {\n const tick: TickRecord = {\n value,\n line: svgElement(\"line\", { class: value === 0 ? \"ec-baseline\" : \"ec-gridline\" }, grid),\n label: svgElement(\"text\", { class: \"ec-tick\" }, axis),\n opacity: animated(opacity, interpolateNumber, { clock, motion, onChange: () => (ticksFaded = true) }),\n wanted: true\n };\n ticks.set(value, tick);\n // In value order, as the layout lists them.\n for (const t of [...ticks.values()].sort((a, b) => a.value - b.value)) {\n grid.appendChild(t.line);\n axis.appendChild(t.label);\n }\n }\n\n function drawTick(tick: TickRecord, frame: BarFrame): void {\n const placed = placeTick(frame, tick.value, format(current)(tick.value));\n const opacity = tick.opacity.value < 1 ? tick.opacity.value : undefined;\n setAttributes(tick.line, { ...placed.line, opacity });\n placeText(tick.label, placed.label);\n setAttributes(tick.label, { opacity });\n }\n\n /** Draws what moved since the last frame. */\n function draw(): void {\n const frame = currentFrame();\n if (frameMoved) setAttributes(svg, sizeAttributes(frame.bands));\n if (frameMoved || ticksFaded) for (const tick of ticks.values()) drawTick(tick, frame);\n for (const record of [...order, ...leaving.values()]) {\n if (frameMoved || dirty.has(record)) show(record, currentRow(record, frame));\n }\n frameMoved = false;\n ticksFaded = false;\n dirty.clear();\n }\n\n /** Draws exactly the layout once a transition settles: the frames in between are computed, this is laid out. */\n function land(): void {\n setAttributes(svg, sizeAttributes(laidOut.frame.bands));\n for (const tick of [...ticks.values()]) {\n if (tick.wanted) continue;\n tick.line.remove();\n tick.label.remove();\n ticks.delete(tick.value);\n }\n for (const placed of laidOut.ticks) {\n const tick = ticks.get(placed.value);\n if (!tick) continue;\n setAttributes(tick.line, { ...placed.line, opacity: undefined });\n placeText(tick.label, placed.label);\n tick.label.removeAttribute(\"opacity\");\n }\n for (const record of order) {\n record.series = record.row.values.map((v) => v.series);\n record.count = undefined;\n show(record, record.row);\n }\n frameMoved = false;\n ticksFaded = false;\n dirty.clear();\n }\n\n /** Matches the layout's rows to marks by key. New marks start at their slot with nothing showing; marks without a row start to leave. */\n function arrange(next: BarLayout<D>): Diff<D> {\n const keys = new Set(next.rows.map((row) => row.key));\n const diff: Diff<D> = { entering: [], exiting: [], changed: [] };\n for (const record of order) {\n if (keys.has(record.key)) continue;\n records.delete(record.key);\n leaving.start(record);\n record.count = undefined;\n diff.exiting.push(record);\n }\n const previous = order;\n order = next.rows.map((row) => {\n let record = records.get(row.key);\n if (record) {\n if (valuesChanged(record.row, row)) diff.changed.push({ record, from: record.shown.geometry });\n record.count = Math.max(decimals(record.row.total), decimals(row.total));\n } else {\n // A mark that comes back mid-exit keeps its element; the runner cancels its exit.\n record = leaving.recall(row.key) ?? createRecord(row, true);\n record.count = undefined;\n records.set(row.key, record);\n diff.entering.push(record);\n }\n record.row = row;\n record.series = mergeSeries(record.series, row.values.map((v) => v.series));\n labelMark(record);\n return record;\n });\n // DOM order follows visual order, for screen readers.\n orderElements(\n marksLayer,\n previous.map((record) => record.group),\n order.map((record) => record.group),\n hover.active\n );\n return diff;\n }\n\n /** The mark's accessible name, from where it's heading, and its description (`markDescription`, or a tooltip function's text). */\n function labelMark(record: MarkRecord<D>): void {\n record.group.setAttribute(\"aria-label\", markLabel(record.row, current));\n tooltip.describe(record.group, record.row);\n }\n\n /**\n * Sends every animated value toward `next`, and returns the animations started. Presentation stages\n * the change: values first (bars resize, leaving bars shrink, the scale and ticks retarget), then\n * positions (rows move to their slots; new bars grow in during the second half). A stage with\n * nothing to do is skipped. Analysis runs it all as one stage, which its scaling keeps short. A\n * jump (motion off, a new orientation, a resize) lands at once.\n */\n function retarget(next: BarLayout<D>, jump: boolean): Promise<TweenResult>[] {\n const { frame } = next;\n if (jump) orientation = next.orientation;\n const wanted = new Set(next.ticks.map((tick) => tick.value));\n for (const value of wanted) if (!ticks.has(value)) addTick(value, 0);\n for (const tick of ticks.values()) tick.wanted = wanted.has(tick.value);\n\n // New marks, and ones back after fading out completely, grow in at their slot.\n const arriving = new Set(order.filter((record) => record.presence.value === 0));\n const staying = order.filter((record) => !arriving.has(record));\n const gone = [...leaving.values()];\n\n const values =\n busy(scale, frame.scale, sameFields) ||\n [...ticks.values()].some((tick) => busy(tick.opacity, tick.wanted ? 1 : 0, same)) ||\n staying.some((record) => busy(record.values, valuesOf(record.row), sameFields) || busy(record.presence, 1, same)) ||\n gone.some((record) => busy(record.values, zeros(record.values.value), sameFields) || busy(record.presence, 0, same));\n const positions = arriving.size > 0 || busy(bands, frame.bands, sameFields) || staying.some((record) => busy(record.slot, record.row.slot, same));\n\n let first: AnimateOptions | undefined;\n let second: AnimateOptions | undefined;\n let grow: AnimateOptions | undefined;\n if (!jump && motion.staged) {\n const wait = values ? STAGE : 0;\n first = { duration: STAGE };\n second = { duration: STAGE, delay: wait };\n grow = { duration: STAGE / 2, delay: wait + STAGE / 2 };\n } else if (!jump) {\n first = second = grow = { duration: (values && positions ? 2 : 1) * STAGE };\n }\n\n const running: Promise<TweenResult>[] = [];\n const move = <T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean, timing: AnimateOptions | undefined): void => {\n if (!busy(value, to, equal)) return;\n if (timing) running.push(value.to(to, timing));\n else value.set(to);\n };\n move(scale, frame.scale, sameFields, first);\n move(bands, frame.bands, sameFields, second);\n for (const tick of ticks.values()) move(tick.opacity, tick.wanted ? 1 : 0, same, first);\n for (const record of staying) {\n move(record.values, valuesOf(record.row), sameFields, first);\n move(record.presence, 1, same, first);\n move(record.slot, record.row.slot, same, second);\n }\n for (const record of arriving) {\n record.slot.set(record.row.slot);\n move(record.values, valuesOf(record.row), sameFields, grow);\n move(record.presence, 1, same, grow);\n }\n for (const record of gone) {\n move(record.values, zeros(record.values.value), sameFields, first);\n move(record.presence, 0, same, first);\n }\n return running;\n }\n\n /**\n * Moves to `next`, animated or at once, drawing every frame. Resolves when the transition settles.\n * One still in flight is taken over: its waiters wait for this one instead.\n */\n function transitionTo(next: BarLayout<D>, jump: boolean): Promise<void> {\n laidOut = next;\n return transitions.run(retarget(next, jump));\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /** Where a mark is heading: what enter and update report as a change starts. */\n const input = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.row.geometry, data: record.row.data });\n /** The mark as it is on screen: what hover, leave and exit report, so mid-change they match what's under the pointer or on its way out. */\n const onScreen = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.shown.geometry, data: record.shown.data });\n\n /** The mark an event target belongs to; leaving marks don't count. */\n function liveRecordOf(eventTarget: EventTarget | null): MarkRecord<D> | undefined {\n const element = eventTarget as Element | null;\n const group = typeof element?.closest === \"function\" ? element.closest(\".ec-mark\") : null;\n const record = group ? byGroup.get(group) : undefined;\n return record && records.get(record.key) === record ? record : undefined;\n }\n\n // Pointer, touch and keyboard focus share one hover: see shell/hover.ts.\n const hover = chartHover<D>({\n svg,\n runner,\n events,\n dim: () => current.dim !== false,\n find(eventTarget) {\n const record = liveRecordOf(eventTarget);\n if (!record) return undefined;\n const segment = (eventTarget as Element).closest(\".ec-segment\")?.getAttribute(\"data-series\") ?? undefined;\n return segment === undefined ? { key: record.key } : { key: record.key, segment };\n },\n live: (key) => records.has(key),\n order: () => order.map((record) => record.key),\n element: (key) => find(key)?.group,\n hot: surface.hot,\n onScreen(key) {\n const record = find(key);\n return record && onScreen(record);\n },\n ring: drawRing,\n tooltip: {\n show(key) {\n const record = records.get(key);\n if (record) showTooltip(record);\n },\n hide: () => tooltip.hide(),\n element: () => tooltip.element()\n }\n });\n\n // ── Motion, size and fonts ─────────────────────────────────────────────────\n\n const unwatchHoverDuration = watchHoverDuration(svg, motion);\n\n /** Re-lays out without animating: a resize or fonts loading. A transition in flight lands at once. Effects follow through change(). */\n function relayout(): void {\n if (destroyed) return;\n const next = layout(current);\n // The same rows as now: only the sizes changed.\n const rows = new Map(next.rows.map((row) => [row.key, row]));\n for (const record of order) record.row = rows.get(record.key) ?? record.row;\n void transitionTo(next, true);\n }\n\n const unwatchWidth = watchWidth(container, clock, measuredWidth, (width) => {\n measuredWidth = width;\n // A fixed `width` ignores the container.\n if (current.width === undefined) relayout();\n });\n\n // Label margins are measured; measure again once web fonts arrive.\n const unwatchFonts = watchFonts(doc, () => {\n measure.clear();\n relayout();\n });\n\n // ── First render ───────────────────────────────────────────────────────────\n\n describeChart(svg, current);\n syncLegend(laidOut);\n table.render(firstTable);\n setAttributes(svg, sizeAttributes(laidOut.frame.bands));\n for (const tick of laidOut.ticks) addTick(tick.value, 1);\n for (const tick of ticks.values()) drawTick(tick, laidOut.frame);\n order = laidOut.rows.map((row) => {\n const record = createRecord(row, false);\n records.set(row.key, record);\n labelMark(record);\n return record;\n });\n hover.sync();\n runner.enter(order.map(input));\n\n return linkable(hover.link, {\n element: svg,\n\n async update(next) {\n if (destroyed) return;\n if (next.motion !== undefined && next.motion !== current.motion) throw new TypeError(\"barChart: `motion` can't be changed by update() yet.\");\n const merged: BarChartOptions<D> = { ...current, ...next };\n checkOptions(merged);\n // Throws on an effect it can't resolve, data it can't draw, or a table column it can't read,\n // before anything changes.\n const swapped = \"on\" in next ? nextEffects(effects, current.on, merged.on, env.presets) : effects;\n const nextLayout = layout(merged, swapped);\n const nextTable = tableFor(merged, nextLayout);\n if (\"colors\" in next) colors = toColorAssignment(merged.colors);\n const previous = current;\n current = merged;\n describeChart(svg, current);\n syncLegend(nextLayout);\n table.render(nextTable);\n // A region that appears with its first text is often missed: it announces from the next update.\n const announcing = announcer !== undefined;\n if (current.announce && !announcer) announcer = chartAnnouncer(svg);\n else if (!current.announce && announcer) {\n announcer.destroy();\n announcer = undefined;\n }\n hover.syncDim();\n transitions.supersede();\n const swapping = swapped !== effects;\n effects = swapped;\n\n // The runner hears exit / update / enter now, then change() on every frame, then settle(). New\n // effects start where the old ones were, on the bars staying, as this update leaves them; a held\n // hover replays with them once the change settles.\n const leaves = playUpdate(\n {\n runner,\n events,\n hover,\n leaving,\n input,\n onScreen,\n data: \"data\" in next,\n ...(swapping\n ? {\n swap: (diff: Diff<D>) => {\n const entering = new Set(diff.entering);\n runner.swap(swapped, order.filter((record) => !entering.has(record)).map(input));\n }\n }\n : {})\n },\n () => arrange(nextLayout),\n (diff) => {\n if (announcing) announceChange(previous, diff);\n }\n );\n // Coloured the other way now: every bar takes its new colour on the change's first frame.\n if (byCategory(current) !== byCategory(previous)) for (const record of [...order, ...leaving.values()]) dirty.add(record);\n const settled = transitionTo(nextLayout, motion.mode === \"off\" || nextLayout.orientation !== orientation);\n await transitions.wait(settled, leaves);\n },\n\n on: events.on,\n\n marks: () => order.map((record) => record.shown.geometry),\n\n focus(key) {\n if (!destroyed) hover.focus(key);\n },\n\n leave() {\n if (!destroyed) hover.leave();\n },\n\n labels: () =>\n order.flatMap((record) => [\n ...chartLabel(record.key, \"category\", record.shown.label, record.label),\n ...chartLabel(record.key, \"value\", record.shown.value, record.value)\n ]),\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n // Ends the transition in flight, and resolves the latest update()'s promise.\n transitions.destroy();\n hover.destroy();\n runner.destroy();\n tooltip.destroy();\n legend.destroy();\n table.destroy();\n announcer?.destroy();\n unwatchHoverDuration();\n unwatchWidth();\n unwatchFonts();\n for (const record of [...order, ...leaving.values()]) {\n for (const value of [record.values, record.slot, record.presence]) value.stop();\n record.leave?.resolve();\n }\n scale.stop();\n bands.stop();\n for (const tick of ticks.values()) tick.opacity.stop();\n events.clear();\n records.clear();\n leaving.clear();\n order = [];\n svg.remove();\n }\n });\n}\n\n/** The options every chart shares, then `room`, and `colorBy`: \"category\" needs one series, so a stack throws. */\nfunction checkOptions<D>(options: BarChartOptions<D>): void {\n checkChartOptions(options, \"barChart\");\n const { colorBy, room } = options;\n if (room !== undefined && !(typeof room === \"number\" && Number.isFinite(room) && room >= 0)) throw new RangeError(`barChart: room must be a number of px, 0 or more, got ${String(room)}.`);\n if (colorBy !== undefined && colorBy !== \"series\" && colorBy !== \"category\") throw new TypeError(`barChart: colorBy must be \"series\" or \"category\", got ${String(colorBy)}.`);\n if (colorBy === \"category\" && options.stack !== undefined) {\n throw new TypeError('barChart: colorBy: \"category\" gives each bar one colour, so it needs one series, not a stack. A stack colours its segments by series.');\n }\n}\n\n/** Each bar takes its own slot, by key, rather than each segment its series'. */\nfunction byCategory<D>(options: BarChartOptions<D>): boolean {\n return options.colorBy === \"category\";\n}\n\n/**\n * \"Okafor: 16 goals, 4 assists\", each series said by its label, or the page's wording from `markLabel`.\n * A lone value read by a function (its series is \"value\") goes unnamed unless it's labelled: \"Okafor:\n * 16\". An empty name, or a throw (reported), keeps the default, so a focusable mark is never left unnamed.\n */\nfunction markLabel<D>(row: BarRow<D>, options: BarChartOptions<D>): string {\n const formatted = format(options);\n const values = labelled(row.values, options);\n const lone = values.length === 1 && values[0]!.series === \"value\" && values[0]!.label === \"value\";\n const text = `${row.category}: ${values.map((v) => (lone ? formatted(v.value) : `${formatted(v.value)} ${v.label}`)).join(\", \")}`;\n if (!options.markLabel) return text;\n try {\n const named: unknown = options.markLabel(row.datum, { key: row.key, category: row.category, values, total: row.total, format: formatted, text });\n if (named !== undefined && named !== null && String(named).trim() !== \"\") return String(named);\n } catch (error) {\n report(error);\n }\n return text;\n}\n\n/** The row's values, each with its series' label: what the tooltip and the mark's name say. Copies, so a page can't change the layout's. */\nfunction labelled<D>(values: readonly BarValue[], options: BarChartOptions<D>): { series: string; label: string; value: number }[] {\n return values.map((v) => ({ series: v.series, label: seriesLabel(options.seriesLabels, v.series), value: v.value }));\n}\n\nfunction valuesChanged<D>(from: BarRow<D>, to: BarRow<D>): boolean {\n return from.values.length !== to.values.length || from.values.some((v, i) => v.series !== to.values[i]!.series || v.value !== to.values[i]!.value);\n}\n\nfunction valuesOf<D>(row: BarRow<D>): Values {\n return Object.fromEntries(row.values.map((v) => [v.series, v.value]));\n}\n\nfunction zeros(values: Values): Values {\n return Object.fromEntries(Object.keys(values).map((series) => [series, 0]));\n}\n\n/**\n * The layout's series order, with series on their way out kept where they were: just after the\n * series they followed, or first. So a stack that loses its base shrinks it in place.\n */\nfunction mergeSeries(shown: readonly string[], next: readonly string[]): string[] {\n const out = [...next];\n shown.forEach((series, i) => {\n if (out.includes(series)) return;\n let at = 0;\n for (let j = i - 1; j >= 0; j--) {\n const found = out.indexOf(shown[j]!);\n if (found >= 0) {\n at = found + 1;\n break;\n }\n }\n out.splice(at, 0, series);\n });\n return out;\n}\n\nfunction sortName<D>(sort: BarChartOptions<D>[\"sort\"]): SortName {\n return typeof sort === \"function\" ? \"custom\" : (sort ?? \"none\");\n}\n","// The donut chart's layout: pure, so it's tested without a DOM. Options in, slices (described with\n// describe.arc), outside labels, the centre text and the size out. Sizes follow the prototype's card 3\n// (demo/lab.html): a ring whose inner radius is 0.6 × the outer, with labels outside it.\n//\n// A layout is drawn from a few numbers: the frame (the chart's size, the ring's centre and radii) and\n// each slice's value and angles. Transitions interpolate those, and placeSlice, placeLabels and\n// placeCenter draw any state in between the same way the layout draws its own.\n\nimport type { MarkData, MarkGeometry, Rect } from \"../core\";\nimport { describeArc } from \"../core/geometry/describe/arc\";\nimport { textBox, type TextPlacement } from \"./render/text\";\nimport { percent } from \"./shell/format\";\nimport type { DonutChartOptions } from \"./types\";\n\nexport interface DonutEncoding<D> {\n /** Names each slice. */\n readonly category: (d: D, i: number) => unknown;\n /** The category unless `key` is given. */\n readonly key: (d: D, i: number) => unknown;\n /** The slices' series: the value field's name, or \"value\" when a function reads it. */\n readonly series: string;\n readonly value: (d: D, i: number) => unknown;\n}\n\n/** Where the ring is: the chart's size, the ring's centre and its radii, all in px. */\nexport interface DonutFrame {\n readonly width: number;\n readonly height: number;\n readonly cx: number;\n readonly cy: number;\n readonly inner: number;\n readonly outer: number;\n}\n\n/** What placeSlice draws a slice from: a laid-out slice, or a state in between two. */\nexport interface SliceState<D> {\n readonly key: string;\n readonly datum: D;\n /** The row's index in `data`. */\n readonly index: number;\n readonly category: string;\n readonly series: string;\n /** In data units, 0 or more. */\n readonly value: number;\n /** The value's share of the total, from 0 to 1. */\n readonly share: number;\n /** Radians, 0 at 12 o'clock and clockwise: d3.pie()'s convention, as describe.arc takes them. */\n readonly start: number;\n readonly end: number;\n}\n\nexport interface DonutSlice<D> extends SliceState<D> {\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n}\n\n/** A slice's label outside the ring: its category over its share. */\nexport interface SliceLabel {\n readonly category: TextPlacement;\n readonly share: TextPlacement;\n /** Both lines' box, for overlaps. */\n readonly box: Rect;\n}\n\n/** A line of the centre's text. The first is drawn large, at `size` px. */\nexport interface CenterLine extends TextPlacement {\n readonly size: number;\n}\n\nexport interface DonutLayout<D> {\n readonly frame: DonutFrame;\n /** The values added up. */\n readonly total: number;\n /** Clockwise from 12 o'clock: the visual order. */\n readonly slices: readonly DonutSlice<D>[];\n /** Each slice's label, in the same order; undefined where none is shown. */\n readonly labels: readonly (SliceLabel | undefined)[];\n /** The centre's text, with \"\\n\" between lines; \"\" for none. */\n readonly centerText: string;\n readonly center: readonly CenterLine[];\n}\n\nexport interface DonutLayoutInput<D> {\n readonly data: readonly D[];\n readonly encoding: DonutEncoding<D>;\n readonly sort: DonutChartOptions<D>[\"sort\"];\n readonly width: number;\n readonly height: number | undefined;\n /** The centre's text for a total (\"\\n\" between lines), or \"\" for none. */\n readonly center: (total: number) => string;\n /** Text width in px, for the labels' room. */\n readonly measure: Measure;\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\nconst TAU = 2 * Math.PI;\nconst HEIGHT = 300;\n/** The inner radius, as a share of the outer: the prototype's 70 / 116. */\nconst HOLE = 0.6;\n/** Between the chart's edge and anything drawn. */\nconst PAD = 4;\n/** Between the ring and its labels. */\nconst GAP = 10;\n/** Slices narrower than this get no label: 15°. */\nconst LABEL_ANGLE = Math.PI / 12;\nconst LABEL_SIZE = 12.5;\nconst VALUE_SIZE = 12.5;\n/** A label's lines: the category's baseline sits this far below the block's top, the share's a line lower. */\nconst ASCENT = 10;\nconst LINE = 15;\n/** A label block's height: two lines and the share's descent. */\nconst BLOCK = ASCENT + LINE + 3;\n/** Labels keep at least this far apart. */\nconst LABEL_SPACE = 2;\n/** The centre's first line, in px, unless it's shrunk to fit the hole. */\nexport const CENTER_SIZE = 26;\nconst CENTER_MIN = 14;\n/** Baselines below the centre's first line: 20 px to the second (as in the prototype), 16 px after that. */\nconst CENTER_STEP = 20;\nconst CENTER_LINE = 16;\n/** Moves a text baseline down by this share of the font size to centre the text on a line. */\nconst CENTRE = 0.36;\n\n/** Reads the options: which accessor names the slices, which sizes them. Throws on what it can't draw. */\nexport function donutEncoding<D>(options: DonutChartOptions<D>): DonutEncoding<D> {\n const { category, value, key } = options;\n if (typeof category !== \"string\" && typeof category !== \"function\") {\n throw new TypeError(\"donutChart needs a category: the field, or a function, that names each slice.\");\n }\n if (typeof value !== \"string\" && typeof value !== \"function\") {\n throw new TypeError(\"donutChart needs a value: the numeric field, or a function, that sizes each slice.\");\n }\n if (key !== undefined && typeof key !== \"string\" && typeof key !== \"function\") throw new TypeError(\"donutChart: key must be a field name or a function.\");\n const name = accessor<D, unknown>(category);\n return {\n category: name,\n key: key === undefined ? name : accessor(key),\n series: typeof value === \"string\" ? value : \"value\",\n value: accessor(value)\n };\n}\n\nexport function layoutDonut<D>(input: DonutLayoutInput<D>): DonutLayout<D> {\n const rows = sortSlices(prepareSlices(input), input.sort);\n const frame = donutFrame(input, rows);\n const total = rows.reduce((sum, row) => sum + row.value, 0);\n const starts = joinedStarts(rows.map((row) => row.value));\n const states = rows.map((row, i): SliceState<D> => {\n const share = total > 0 ? row.value / total : 0;\n // The last slice ends exactly at 12 o'clock again.\n const end = i + 1 < rows.length && total > 0 ? starts[i + 1]! : total > 0 ? 1 : 0;\n return { ...row, series: input.encoding.series, share, start: starts[i]! * TAU, end: end * TAU };\n });\n const labels = placeLabels(frame, states, input.measure);\n const centerText = input.center(total);\n return {\n frame,\n total,\n slices: states.map((state, i) => placeSlice(frame, state, labels[i], input.measure)),\n labels,\n centerText,\n center: placeCenter(frame, centerText, input.measure)\n };\n}\n\n/**\n * Where each slice starts, in turns from 12 o'clock, laid end to end in order: values in data units,\n * so every start is a true share of the total. All 0 when the total is.\n */\nexport function joinedStarts(values: readonly number[]): number[] {\n const total = values.reduce((sum, v) => sum + v, 0);\n let before = 0;\n return values.map((value) => {\n const start = total > 0 ? before / total : 0;\n before += value;\n return start;\n });\n}\n\n/**\n * Draws a slice in a frame: its arc, described with describe.arc, and its data. With its label\n * (and `measure`), the boxes of the label's two lines are its `labelBounds`; with no label, none.\n */\nexport function placeSlice<D>(frame: DonutFrame, state: SliceState<D>, label?: SliceLabel, measure?: Measure): DonutSlice<D> {\n const geometry = describeArc({\n key: state.key,\n series: state.series,\n cx: frame.cx,\n cy: frame.cy,\n inner: frame.inner,\n outer: frame.outer,\n start: state.start,\n end: state.end,\n labelBounds: label && measure ? labelBoxes(label, measure) : []\n });\n return { ...state, geometry, data: sliceData(state.datum, state.share, state.series) };\n}\n\n/**\n * The labels outside the ring, in the slices' order: each slice's category over its share, on slices\n * of 15° or more. A label sits just outside the ring at the slice's middle angle, and leans away from\n * it the way the slice points: beside the ring at 3 and 9 o'clock, above it at 12, below it at 6, and\n * smoothly in between, so a label never jumps as its slice turns. A label that would overlap the one\n * before it (or, going round, the first) or leave the chart is dropped; the legend, the tooltip, the\n * data table and the slice's name still say it.\n */\nexport function placeLabels<D>(frame: DonutFrame, slices: readonly SliceState<D>[], measure: Measure): (SliceLabel | undefined)[] {\n let previous: Rect | undefined;\n let first: number | undefined;\n const labels = slices.map((slice, i): SliceLabel | undefined => {\n if (slice.end - slice.start < LABEL_ANGLE - 1e-9) return undefined;\n const label = labelAt(frame, slice, measure);\n const { box } = label;\n if (box.x < 0 || box.y < 0 || box.x + box.width > frame.width || box.y + box.height > frame.height) return undefined;\n if (previous && overlaps(previous, box)) return undefined;\n previous = box;\n first ??= i;\n return label;\n });\n // Going round, the first label comes after the last: the later one gives way.\n for (let i = labels.length - 1; first !== undefined && i > first; i--) {\n const label = labels[i];\n if (!label) continue;\n if (!overlaps(labels[first]!.box, label.box)) break;\n labels[i] = undefined;\n }\n return labels;\n}\n\n/**\n * The centre's text, one line per \"\\n\", in the hole: the first line large (shrunk to fit the hole when\n * it's wide), the others below it. The lines are centred on the ring's centre together.\n */\nexport function placeCenter(frame: DonutFrame, text: string, measure: Measure): CenterLine[] {\n if (text === \"\") return [];\n const lines = text.split(\"\\n\");\n const room = 2 * frame.inner * 0.85;\n const width = measure(lines[0]!, \"ec-center-value\", CENTER_SIZE);\n const size = width > room && width > 0 ? Math.max(CENTER_MIN, (CENTER_SIZE * room) / width) : CENTER_SIZE;\n const offsets = lines.map((_, i) => (i === 0 ? 0 : CENTER_STEP + (i - 1) * CENTER_LINE));\n const last = offsets[offsets.length - 1]!;\n // The first line's cap height (about 0.72 em) down to the last line's baseline, centred.\n const top = frame.cy + (2 * CENTRE * size - last) / 2;\n return lines.map((line, i) => ({ x: frame.cx, y: top + offsets[i]!, anchor: \"middle\", text: line, size: i === 0 ? size : LABEL_SIZE }));\n}\n\ninterface Prepared<D> {\n readonly key: string;\n readonly category: string;\n readonly datum: D;\n readonly index: number;\n readonly value: number;\n}\n\nfunction prepareSlices<D>({ data, encoding }: DonutLayoutInput<D>): Prepared<D>[] {\n const keys = new Set<string>();\n return data.map((datum, index) => {\n const key = String(encoding.key(datum, index));\n if (keys.has(key)) throw new Error(`donutChart: two rows have the key \"${key}\". Keys must be unique; pass a key accessor if categories repeat.`);\n keys.add(key);\n const value = numberOf(encoding.value(datum, index), encoding.series, key);\n return { key, category: String(encoding.category(datum, index) ?? \"\"), datum, index, value };\n });\n}\n\nfunction sortSlices<D>(rows: Prepared<D>[], sort: DonutLayoutInput<D>[\"sort\"]): Prepared<D>[] {\n if (sort === undefined || sort === \"none\") return rows;\n // Array.prototype.sort is stable, so ties keep data order.\n if (sort === \"value\") return [...rows].sort((a, b) => b.value - a.value);\n throw new TypeError(`donutChart: sort must be \"value\" or \"none\", got ${String(sort)}.`);\n}\n\n/**\n * The ring is as large as the room left for labels allows, wherever they land: the widest label beside\n * it, and a label's height above and below it. So the ring keeps its size as values change. When that\n * leaves less than half the radius the chart could have, the ring takes half, and labels that don't\n * fit are dropped.\n */\nfunction donutFrame<D>(input: DonutLayoutInput<D>, rows: readonly Prepared<D>[]): DonutFrame {\n const { width, measure } = input;\n const height = input.height ?? HEIGHT;\n const cx = width / 2;\n const cy = height / 2;\n const share = measure(\"100%\", \"ec-value\", VALUE_SIZE);\n const widest = rows.reduce((max, row) => Math.max(max, measure(row.category, \"ec-label\", LABEL_SIZE)), share);\n const room = Math.min(cx - PAD - GAP - widest, cy - PAD - GAP - BLOCK);\n const most = Math.max(0, Math.min(cx, cy) - PAD);\n const outer = Math.max(0, room, most / 2);\n return { width, height, cx, cy, inner: outer * HOLE, outer };\n}\n\n/** A slice's label, placed at its middle angle. */\nfunction labelAt<D>(frame: DonutFrame, slice: SliceState<D>, measure: Measure): SliceLabel {\n const middle = (slice.start + slice.end) / 2;\n const sin = Math.sin(middle);\n const cos = Math.cos(middle);\n const r = frame.outer + GAP;\n const x = frame.cx + r * sin;\n const y = frame.cy - r * cos;\n const share = percent(slice.share);\n const widths = [measure(slice.category, \"ec-label\", LABEL_SIZE), measure(share, \"ec-value\", VALUE_SIZE)] as const;\n const width = Math.max(...widths);\n // Above the point at 12 o'clock, below it at 6, centred on it at 3 and 9.\n const top = y - (BLOCK * (cos + 1)) / 2;\n // Each line starts at the point at 3 o'clock, ends there at 9, and is centred on it at 12 and 6.\n const along = (w: number): number => x + (sin * w) / 2;\n return {\n category: { x: along(widths[0]), y: top + ASCENT, anchor: \"middle\", text: slice.category },\n share: { x: along(widths[1]), y: top + ASCENT + LINE, anchor: \"middle\", text: share },\n box: { x: along(width) - width / 2, y: top, width, height: BLOCK }\n };\n}\n\n/** The boxes of a label's two lines, leaving out a line with no text. */\nfunction labelBoxes(label: SliceLabel, measure: Measure): Rect[] {\n const out: Rect[] = [];\n if (label.category.text !== \"\") out.push(textBox(label.category, measure, \"ec-label\", LABEL_SIZE));\n if (label.share.text !== \"\") out.push(textBox(label.share, measure, \"ec-value\", VALUE_SIZE));\n return out;\n}\n\nfunction overlaps(a: Rect, b: Rect): boolean {\n return a.x < b.x + b.width + LABEL_SPACE && b.x < a.x + a.width + LABEL_SPACE && a.y < b.y + b.height + LABEL_SPACE && b.y < a.y + a.height + LABEL_SPACE;\n}\n\n/** Values along the walk, from 0 at the start to the slice's share at the end. Its own series is the only one related. */\nfunction sliceData<D>(datum: D, share: number, series: string): MarkData<D> {\n const data: MarkData<D> = {\n datum,\n samples: [\n { t: 0, value: 0 },\n { t: 1, value: share }\n ],\n related: (name) => (name === series ? data : undefined)\n };\n return data;\n}\n\nfunction accessor<D, T>(option: string | ((d: D, i: number) => T)): (d: D, i: number) => T {\n if (typeof option === \"function\") return option;\n return (d) => (d as Record<string, unknown>)[option] as T;\n}\n\n/** Missing values (null, undefined) count as 0; negative and non-finite ones throw. */\nfunction numberOf(value: unknown, series: string, key: string): number {\n if (value === null || value === undefined) return 0;\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) return value;\n throw new RangeError(\n `donutChart: \"${series}\" for \"${key}\" must be a finite number of 0 or more, got ${typeof value === \"string\" ? JSON.stringify(value) : String(value)}.`\n );\n}\n","// donutChart: the reference donut. Keyed slices described with describe.arc, from 12 o'clock and\n// clockwise, separated by strokes in the surface colour; labels outside the ring and the total in its\n// hole; a legend per category; built-in hover dimming; pointer, touch and keyboard hover with a\n// tooltip; a data table with each share and the total and, with `announce`, a live region for screen\n// readers. update() animates the values in data units, so every frame's angles are true shares:\n// staged in presentation (values, then slices turning to their new places), in one short stage in\n// analysis, at once when motion is off.\n//\n// The chart never names an effect: it resolves `on` through the presets it's handed and plays them\n// through the runner, which draws on the SVG surface. What doesn't depend on slices (events, hover and\n// focus, transitions and leaving marks, DOM order, size and fonts) is in shell/. The focus ring and\n// halos are drawn above the slices, masked to outside them (render/outside.ts), since slices touch.\n\nimport type { AnimateOptions, Animated, TweenResult } from \"../core\";\nimport { animated, defaultClock, interpolateNumber, interpolateRecord } from \"../core\";\nimport { resolveEffects } from \"../core/registry\";\nimport { report } from \"../core/report\";\nimport { createRunner, type RunInput } from \"../core/runner\";\nimport { chartAnnouncer, changeText, type Announcer } from \"./announce\";\nimport { toColorAssignment } from \"./colors\";\nimport { CENTER_SIZE, donutEncoding, layoutDonut, placeCenter, placeLabels, placeSlice, type CenterLine, type DonutFrame, type DonutLayout, type DonutSlice, type SliceLabel, type SliceState } from \"./donut-layout\";\nimport { chartLegend } from \"./legend\";\nimport { linkable } from \"./link\";\nimport { chartMotion } from \"./motion\";\nimport { svgMarkHandle, type StyledPart, type SvgMarkHandle } from \"./render/mark-style\";\nimport { maskedRing } from \"./render/outside\";\nimport { svgSurface } from \"./render/surface\";\nimport { setAttributes, setStyles, sizeAttributes, svgElement } from \"./render/svg\";\nimport { placeText, textMeasure } from \"./render/text\";\nimport { injectStyles, markColorStyles, seriesColors } from \"./render/theme\";\nimport { seriesLabel } from \"./series\";\nimport { chartEvents } from \"./shell/events\";\nimport { decimals, format, percent, round } from \"./shell/format\";\nimport { chartHover } from \"./shell/hover\";\nimport { chartLabel } from \"./shell/labels\";\nimport { leavingMarks, type Leave } from \"./shell/leaving\";\nimport { orderElements } from \"./shell/order\";\nimport { checkChartOptions, checkNeeds, containerWidth, describeChart, nextEffects, resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport { busy, chartTransitions, geometryChanged, playUpdate, same, sameFields, type ChartDiff } from \"./shell/transitions\";\nimport { watchFonts, watchHoverDuration, watchWidth } from \"./shell/watch\";\nimport { chartTable, tableModel, type TableModel } from \"./table\";\nimport { chartTooltip } from \"./tooltip\";\nimport type { Chart, DonutChartOptions } from \"./types\";\n\nexport type DonutChart<D> = Chart<D, DonutChartOptions<D>>;\n\ninterface SliceRecord<D> {\n readonly key: string;\n /** Where the slice is heading, or rests: its slice in the latest layout (its last one while it leaves). */\n row: DonutSlice<D>;\n /** What's on screen now. */\n shown: DonutSlice<D>;\n readonly group: SVGGElement;\n /** The pointer target, which stays put while an effect moves the slice. */\n readonly hit: SVGPathElement;\n /** Holds the slice; effects' transform and opacity go here. */\n readonly body: SVGGElement;\n readonly path: SVGPathElement;\n /** The label outside the ring: the category over the share. */\n readonly label: SVGTextElement;\n readonly share: SVGTextElement;\n /** Where the label is drawn now; undefined while it's dropped for room. */\n drawnLabel: SliceLabel | undefined;\n parts: StyledPart[];\n readonly handle: SvgMarkHandle;\n /** In data units, so every frame's angles are true shares. */\n readonly value: Animated<number>;\n /** 0 to 1: how far the slice has turned from where it was to its place in the ring. */\n readonly turn: Animated<number>;\n /** Where it turns from, in turns: its start in the order it turns from, plus this. */\n offset: number;\n /** How far it turns, in turns, at the targets: the shorter way, chosen once so it can't flip mid-turn. */\n planned: number;\n /** 0 to 1. A slice entering or leaving fades its label in or out. */\n readonly presence: Animated<number>;\n /** Set while the slice leaves. */\n leave: Leave | undefined;\n}\n\n/** What an update changed. A re-sort only turns a slice, and a new total only resizes it: its value didn't change. */\ntype Diff<D> = ChartDiff<SliceRecord<D>>;\n\n/** Base ms for each stage of a data change: values, then the turn to new places. Unstaged, a change takes as long as its stages together, which analysis scales down. */\nconst STAGE = 500;\nconst TAU = 2 * Math.PI;\n/** A walk shorter than this draws nothing, as effects treat it. */\nconst VISIBLE = 0.5;\n\nexport function donutChart<D>(target: string | Element, options: DonutChartOptions<D>, env: ChartEnv): DonutChart<D> {\n const container = resolveTarget(target, \"donutChart\");\n checkOptions(options);\n let current = options;\n const motion = chartMotion(options.motion, env.motion);\n let effects = resolveEffects(options.on, env.presets);\n let colors = toColorAssignment(options.colors);\n const clock = env.clock ?? defaultClock;\n const doc = container.ownerDocument;\n injectStyles(doc);\n\n // A named group of slices, each an image with its own name: see \"ARIA structure\" in docs/architecture.md.\n const svg = svgElement(\"svg\", { class: \"ec-chart ec-donut-chart\", role: \"group\" }, container);\n // Read through the chart's description instead.\n const center = svgElement(\"g\", { class: \"ec-center\", \"aria-hidden\": \"true\" }, svg);\n const marksLayer = svgElement(\"g\", { class: \"ec-marks\" }, svg);\n const overlay = svgElement(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" }, svg);\n // Above the slices, masked to outside the slice: slices touch, so anything behind one would hide\n // under its neighbour on one side.\n const halos = svgElement(\"g\", { class: \"ec-halos\" }, overlay);\n const focusRing = maskedRing(overlay);\n const runs = svgElement(\"g\", { class: \"ec-runs\" }, overlay);\n const measure = textMeasure(svg);\n\n /** Live slices, in the layout's order: clockwise from 12 o'clock. */\n let order: SliceRecord<D>[] = [];\n const records = new Map<string, SliceRecord<D>>();\n /** Slices on their way out: shrinking, or waiting for their exit effects. */\n const leaving = leavingMarks<SliceRecord<D>>((record) => record.value.animating || record.presence.animating);\n const byGroup = new WeakMap<Element, SliceRecord<D>>();\n const events = chartEvents<D>(\"donutChart\");\n let measuredWidth = containerWidth(container);\n let destroyed = false;\n\n let laidOut: DonutLayout<D>;\n let firstTable: TableModel | undefined;\n /** Each slice's accessible name, by key, for the latest layout. */\n let names: ReadonlyMap<string, string>;\n try {\n // Throws on data it can't draw, a table column it can't read, or a `format` that throws. Nothing\n // but the <svg> is in place yet (no listeners, observers or elements beside it), so that's all to undo.\n laidOut = layout(current);\n firstTable = tableFor(current, laidOut);\n // Last, so a markLabel that throws is reported only for a layout the chart draws.\n names = namesFor(current, laidOut);\n } catch (error) {\n svg.remove();\n throw error;\n }\n\n const find = (key: string): SliceRecord<D> | undefined => records.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay: runs,\n // Looked up on each call, so the handle follows the slice's record.\n mark: (key) => ({\n set: (style) => {\n find(key)?.handle.set(style);\n hover.restyled(key);\n },\n reset: () => {\n find(key)?.handle.reset();\n hover.restyled(key);\n }\n }),\n colors: (key) => find(key)?.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const tooltip = chartTooltip<D>(svg, { motion, option: () => current.tooltip, description: () => current.markDescription });\n const legend = chartLegend(svg);\n const table = chartTable(svg);\n let announcer: Announcer | undefined = current.announce ? chartAnnouncer(svg) : undefined;\n\n // ── Animated state ─────────────────────────────────────────────────────────\n // Each slice has its value, how far it has turned and its presence, and the chart has the frame, so\n // a new update() mid-flight retargets each from where it is and nothing jumps. Where a slice is comes\n // from them: the slices in `ring` are laid end to end from their values, and a slice still turning\n // is part way from its start in `from` (plus its offset) to its start in `ring`.\n\n /** Every slice drawn, live and leaving, in the order they're joined in: the layout's, with leaving slices kept where they were. */\n let ring: SliceRecord<D>[] = [];\n /** The order slices turn from: where they were joined before the latest change. */\n let from: SliceRecord<D>[] = [];\n /** Something moved since the last frame was drawn. Every slice's angles depend on every value, so a frame draws them all. */\n let dirty = false;\n const frame = animated(laidOut.frame, interpolateRecord, { clock, motion, onChange: () => (dirty = true) });\n /** The centre's total counts between totals, rounded to this many decimals; undefined shows the layout's text. */\n let count: number | undefined;\n /** The centre's text for the total last shown while counting. */\n let counted: { readonly total: number; readonly text: string } | undefined;\n\n const transitions = chartTransitions({ clock, runner, leaving, draw, land });\n\n // ── Drawing ────────────────────────────────────────────────────────────────\n\n function layout(opts: DonutChartOptions<D>, using = effects): DonutLayout<D> {\n const encoding = donutEncoding(opts);\n checkNeeds(using, [encoding.series], \"donutChart\");\n return layoutDonut({\n data: opts.data,\n encoding,\n sort: opts.sort,\n width: opts.width ?? measuredWidth,\n height: opts.height,\n center: (total) => centerText(opts, encoding.series, total),\n measure\n });\n }\n\n /** A new slice, drawn when it's first shown. One that enters grows from nothing. */\n function createRecord(row: DonutSlice<D>, entering: boolean): SliceRecord<D> {\n // An image: its aria-label says it all, and its text and shapes aren't read on their own.\n const group = svgElement(\"g\", { class: \"ec-mark\", \"data-key\": row.key, role: \"img\" }, marksLayer);\n const env = { clock, motion, onChange: () => (dirty = true) };\n const body = svgElement(\"g\", { class: \"ec-body\" }, group);\n const record: SliceRecord<D> = {\n key: row.key,\n row,\n shown: row,\n group,\n hit: svgElement(\"path\", { class: \"ec-hit\" }, group),\n body,\n path: svgElement(\"path\", { class: \"ec-slice\", \"data-series\": row.series }, body),\n label: svgElement(\"text\", { class: \"ec-label\", \"aria-hidden\": \"true\" }, group),\n share: svgElement(\"text\", { class: \"ec-value\", \"aria-hidden\": \"true\" }, group),\n drawnLabel: undefined,\n parts: [],\n handle: svgMarkHandle(() => record, { halos: () => halos }),\n value: animated(entering ? 0 : row.value, interpolateNumber, env),\n turn: animated(1, interpolateNumber, env),\n offset: 0,\n planned: 0,\n presence: animated(entering ? 0 : 1, interpolateNumber, env),\n leave: undefined\n };\n // The pointer target first, under the slice.\n group.insertBefore(record.hit, body);\n byGroup.set(group, record);\n return record;\n }\n\n /** Draws the slice as `slice`, with its label outside the ring or none. */\n function drawMark(record: SliceRecord<D>, slice: DonutSlice<D>, label: SliceLabel | undefined): void {\n const before = record.parts[0]?.colors.color;\n record.shown = slice;\n const { outline } = slice.geometry;\n // A slice with no angle draws nothing: not even its separator.\n const visible = slice.geometry.length >= VISIBLE;\n const hidden = visible ? undefined : \"hidden\";\n setAttributes(record.path, { d: outline.d, visibility: hidden });\n setAttributes(record.hit, { d: outline.d, visibility: hidden });\n const sliceColors = seriesColors(colors.slot(record.key));\n setStyles(record.path, markColorStyles(sliceColors));\n record.parts = [{ element: record.path, d: outline.d, colors: sliceColors, visible }];\n const presence = record.presence.value;\n const opacity = presence < 1 ? presence : undefined;\n record.drawnLabel = label;\n for (const [text, placement] of [\n [record.label, label?.category],\n [record.share, label?.share]\n ] as const) {\n if (placement) placeText(text, placement);\n setAttributes(text, { visibility: placement ? undefined : \"hidden\", opacity });\n }\n record.handle.repaint();\n // A new palette: overlays already drawn in \"mark\" follow.\n if (sliceColors.color !== before) surface.recolor(record.key);\n if (record.key === hover.ringKey) drawRing(record.key);\n }\n\n /** The focus ring follows the slice's outline as it is on screen, moved with its body when an effect moves it. */\n function drawRing(key: string | undefined): void {\n const record = key === undefined ? undefined : records.get(key);\n focusRing.draw(record && { outline: record.shown.geometry.outline, thickness: record.shown.geometry.thickness, transform: record.handle.style.transform });\n }\n\n /**\n * Draws the slice as `slice`. Its runs hear about it when its geometry or its row changed, so\n * decorations follow: a label from a field the slice doesn't plot too.\n */\n function show(record: SliceRecord<D>, slice: DonutSlice<D>, label: SliceLabel | undefined): void {\n const moved = geometryChanged(record.shown.geometry, slice.geometry) || record.shown.datum !== slice.datum;\n drawMark(record, slice, label);\n if (moved) runner.change(slice.geometry, slice.data);\n if (record.key === hover.key) showTooltip(record);\n }\n\n /** The tooltip beside the hovered slice as it is on screen, moved with its effects, with the text for where it's heading. */\n function showTooltip(record: SliceRecord<D>): void {\n const { row } = record;\n tooltip.show(record.shown.geometry, row, () => ({ title: row.category, lines: [`${valueText(row, current)} · ${percent(row.share)}`] }), record.handle.style.transform);\n }\n\n /** The text in the hole, a line per <text>: the first large. */\n function drawCenter(lines: readonly CenterLine[]): void {\n while (center.childElementCount > lines.length) center.lastElementChild!.remove();\n lines.forEach((line, i) => {\n const text = (center.children[i] as SVGTextElement | undefined) ?? svgElement(\"text\", {}, center);\n setAttributes(text, { class: i === 0 ? \"ec-center-value\" : \"ec-center-label\" });\n placeText(text, line);\n // Shrunk to fit the hole; otherwise the stylesheet's size.\n setStyles(text, { \"font-size\": i === 0 && line.size !== CENTER_SIZE ? `${line.size}px` : undefined });\n });\n }\n\n const syncLegend = (): void =>\n legend.categories(\n laidOut.slices.map((slice) => ({ key: slice.key, label: slice.category })),\n colors,\n current.legend\n );\n\n /** The data table for `opts`, laid out as `next`: its rows in the slices' order, each share, and the total. Throws on a column it can't read. */\n function tableFor(opts: DonutChartOptions<D>, next: DonutLayout<D>): TableModel | undefined {\n const { series } = donutEncoding(opts);\n return tableModel({\n option: opts.table,\n caption: opts.label,\n category: typeof opts.category === \"string\" ? opts.category : undefined,\n series: [series],\n label: (name) => seriesLabel(opts.seriesLabels, name),\n rows: next.slices.map((slice) => ({ key: slice.key, category: slice.category, datum: slice.datum, index: slice.index, values: [{ series, value: slice.value }], total: slice.value })),\n format: format(opts),\n shares: true\n });\n }\n\n /** The chart's description: its own, then the centre's text, so the total is heard on entering the chart. */\n function describeDonut(): void {\n describeChart(svg, { label: current.label, description: description(current.description, laidOut.centerText) });\n }\n\n /** Says what an update changed, in the live region: the chart's summary, or the page's text from it. */\n function announceChange(previous: DonutChartOptions<D>, diff: Diff<D>): void {\n const option = current.announce;\n if (!announcer || !option) return;\n const series = donutEncoding(current).series;\n const before = donutEncoding(previous).series;\n const sort = current.sort ?? \"none\";\n const name = (record: SliceRecord<D>): string => record.row.category;\n const changed = diff.changed.map(({ record }) => record);\n const text = changeText({\n ...(current.label !== previous.label ? { label: current.label } : {}),\n // A new series is said by its label; a new label alone shows the same view, so say nothing.\n ...(series !== before ? { series: [seriesLabel(current.seriesLabels, series)] } : {}),\n ...(sort !== (previous.sort ?? \"none\") ? { sort } : {}),\n changed: changed.map(name),\n added: diff.entering.map(name),\n removed: diff.exiting.map(name),\n count: order.length\n });\n if (typeof option !== \"function\") {\n announcer.say(text);\n return;\n }\n const key = (record: SliceRecord<D>): string => record.key;\n try {\n const said = option({ text, changed: changed.map(key), added: diff.entering.map(key), removed: diff.exiting.map(key) });\n if (said !== undefined && said !== null) announcer.say(String(said));\n } catch (error) {\n report(error);\n }\n }\n\n /** On screen: live, or leaving and not yet gone. */\n const drawn = (record: SliceRecord<D>): boolean => records.get(record.key) === record || leaving.get(record.key) === record;\n const valueOf = (record: SliceRecord<D>): number => Math.max(0, record.value.value);\n\n /** Each slice's start, in turns, laid end to end from 12 o'clock in the order given, as shares of `total`. */\n function startsIn(slices: readonly SliceRecord<D>[], total: number, value = valueOf): Map<SliceRecord<D>, number> {\n const starts = new Map<SliceRecord<D>, number>();\n let before = 0;\n for (const record of slices) {\n starts.set(record, total > 0 ? before / total : 0);\n before += value(record);\n }\n return starts;\n }\n\n /** Where every slice drawn is now, in turns: its start, and its span (its true share). */\n function angles(): Map<SliceRecord<D>, { readonly start: number; readonly span: number }> {\n ring = ring.filter(drawn);\n from = from.filter(drawn);\n const total = ring.reduce((sum, record) => sum + valueOf(record), 0);\n const to = startsIn(ring, total);\n const was = startsIn(from, total);\n const out = new Map<SliceRecord<D>, { readonly start: number; readonly span: number }>();\n for (const record of ring) {\n const start = to.get(record)!;\n const turned = record.turn.value;\n const origin = was.get(record);\n let at = start;\n if (origin !== undefined && turned < 1) {\n // The way it has to go now, kept to the side it set off on.\n const raw = origin + record.offset - start;\n at = start + (1 - turned) * (raw - Math.round(raw - record.planned));\n }\n out.set(record, { start: at, span: total > 0 ? valueOf(record) / total : 0 });\n }\n return out;\n }\n\n /** Every slice as it is now, part way through a transition, in the ring's order, with its label or none. */\n function currentSlices(f: DonutFrame): { readonly record: SliceRecord<D>; readonly slice: DonutSlice<D>; readonly label: SliceLabel | undefined }[] {\n const now = [...angles()].map(([record, { start, span }]) => {\n const { row } = record;\n const state: SliceState<D> = {\n key: row.key,\n datum: row.datum,\n index: row.index,\n category: row.category,\n series: row.series,\n value: valueOf(record),\n share: span,\n start: start * TAU,\n end: (start + span) * TAU\n };\n return { record, state };\n });\n const labels = placeLabels(\n f,\n now.map(({ state }) => state),\n measure\n );\n return now.map(({ record, state }, i) => ({ record, slice: placeSlice(f, state, labels[i], measure), label: labels[i] }));\n }\n\n /** Draws every slice as it is now, its label, and the total counting in the hole. */\n function draw(): void {\n if (!dirty) return;\n dirty = false;\n const f = frame.value;\n setAttributes(svg, sizeAttributes(f));\n const slices = currentSlices(f);\n for (const { record, slice, label } of slices) show(record, slice, label);\n const total = slices.reduce((sum, { slice }) => sum + slice.value, 0);\n drawCenter(placeCenter(f, count === undefined ? laidOut.centerText : counting(round(total, count)), measure));\n }\n\n /** The centre's text for a total on its way to the layout's, worked out once per total shown. */\n function counting(total: number): string {\n if (counted?.total !== total) counted = { total, text: centerText(current, donutEncoding(current).series, total) };\n return counted.text;\n }\n\n /** Draws exactly the layout once a transition settles: the frames in between are computed, this is laid out. */\n function land(): void {\n ring = ring.filter(drawn);\n from = ring;\n for (const record of ring) {\n record.turn.set(1);\n record.offset = 0;\n record.planned = 0;\n }\n count = undefined;\n counted = undefined;\n setAttributes(svg, sizeAttributes(laidOut.frame));\n laidOut.slices.forEach((slice, i) => show(records.get(slice.key)!, slice, laidOut.labels[i]));\n drawCenter(laidOut.center);\n dirty = false;\n }\n\n /** Matches the layout's slices to records by key. New slices start with nothing showing; slices without one start to leave. */\n function arrange(next: DonutLayout<D>): Diff<D> {\n const keys = new Set(next.slices.map((slice) => slice.key));\n const diff: Diff<D> = { entering: [], exiting: [], changed: [] };\n for (const record of order) {\n if (keys.has(record.key)) continue;\n records.delete(record.key);\n leaving.start(record);\n diff.exiting.push(record);\n }\n const previous = order;\n order = next.slices.map((slice) => {\n let record = records.get(slice.key);\n if (record) {\n // Its own value: a share that moved because others changed isn't an update.\n if (record.row.value !== slice.value || record.row.series !== slice.series) diff.changed.push({ record, from: record.shown.geometry });\n } else {\n // A slice that comes back mid-exit keeps its element; the runner cancels its exit.\n record = leaving.recall(slice.key) ?? createRecord(slice, true);\n records.set(slice.key, record);\n diff.entering.push(record);\n }\n record.row = slice;\n record.path.setAttribute(\"data-series\", slice.series);\n labelMark(record);\n return record;\n });\n // DOM order follows visual order, for screen readers.\n orderElements(\n marksLayer,\n previous.map((record) => record.group),\n order.map((record) => record.group),\n hover.active\n );\n return diff;\n }\n\n /** The slice's accessible name, from where it's heading, and its description (`markDescription`, or a tooltip function's text). */\n function labelMark(record: SliceRecord<D>): void {\n record.group.setAttribute(\"aria-label\", names.get(record.key)!);\n tooltip.describe(record.group, record.row);\n }\n\n /**\n * Sends every animated value toward `next`, and returns the animations started. Presentation stages\n * the change: values first (slices resize, staying joined in the order they're in, and leaving slices\n * shrink to nothing), then the turn (slices turn the shorter way to their places in the new order,\n * the ring resizes, and new slices grow in at their places in the second half). A stage with nothing\n * to do is skipped. Analysis runs it all as one stage, which its scaling keeps short. A jump (motion\n * off, a resize) lands at once.\n */\n function retarget(next: DonutLayout<D>, jump: boolean): Promise<TweenResult>[] {\n dirty = true;\n // Where every slice is now, before the orders change, so nothing jumps.\n const now = angles();\n // New slices, and ones back after fading out completely, grow in at their places.\n const arriving = new Set(order.filter((record) => record.presence.value === 0));\n const staying = order.filter((record) => !arriving.has(record));\n const gone = [...leaving.values()];\n\n // Still joined in `from` and not turning yet (stopped in the values stage): they go on from there.\n // Otherwise they turn from the ring they're in, each from where it is now.\n const waiting = from.length > 0 && from.every((record) => record.turn.value === 0);\n const before = ring;\n ring = mergeRing(before, order);\n if (!waiting) {\n from = before;\n const total = before.reduce((sum, record) => sum + valueOf(record), 0);\n const joined = startsIn(before, total);\n for (const record of before) record.offset = now.get(record)!.start - joined.get(record)!;\n }\n from = from.filter((record) => !arriving.has(record));\n\n // The shorter way round, at the targets: where it's heading in the ring against where it turns from.\n const target = (record: SliceRecord<D>): number => (records.get(record.key) === record ? record.row.value : 0);\n const total = ring.reduce((sum, record) => sum + target(record), 0);\n const ends = startsIn(ring, total, target);\n const starts = startsIn(from, total, target);\n let turns = false;\n for (const record of from) {\n const raw = starts.get(record)! + record.offset - ends.get(record)!;\n record.planned = raw - Math.round(raw);\n if (Math.abs(record.planned) > 1e-9) turns = true;\n }\n\n const values =\n staying.some((record) => busy(record.value, record.row.value, same) || busy(record.presence, 1, same)) ||\n gone.some((record) => busy(record.value, 0, same) || busy(record.presence, 0, same));\n const positions = turns || arriving.size > 0 || busy(frame, next.frame, sameFields);\n\n let first: AnimateOptions | undefined;\n let second: AnimateOptions | undefined;\n let grow: AnimateOptions | undefined;\n if (!jump && motion.staged) {\n const wait = values ? STAGE : 0;\n first = { duration: STAGE };\n second = { duration: STAGE, delay: wait };\n grow = { duration: STAGE / 2, delay: wait + STAGE / 2 };\n } else if (!jump) {\n first = second = grow = { duration: (values && positions ? 2 : 1) * STAGE };\n }\n\n const running: Promise<TweenResult>[] = [];\n const move = <T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean, timing: AnimateOptions | undefined): void => {\n if (!busy(value, to, equal)) return;\n if (timing) running.push(value.to(to, timing));\n else value.set(to);\n };\n move(frame, next.frame, sameFields, second);\n for (const record of staying) {\n move(record.value, record.row.value, same, first);\n move(record.presence, 1, same, first);\n }\n for (const record of arriving) {\n move(record.value, record.row.value, same, grow);\n move(record.presence, 1, same, grow);\n }\n for (const record of gone) {\n move(record.value, 0, same, first);\n move(record.presence, 0, same, first);\n }\n if (jump) {\n from = ring;\n for (const record of ring) {\n record.turn.set(1);\n record.offset = 0;\n record.planned = 0;\n }\n return running;\n }\n // Joined where they were until their turn starts.\n const turning = new Set(from);\n for (const record of ring) record.turn.set(turning.has(record) ? 0 : 1);\n if (turns) for (const record of from) move(record.turn, 1, same, second);\n return running;\n }\n\n /**\n * Moves to `next`, animated or at once, drawing every frame. Resolves when the transition settles.\n * One still in flight is taken over: its waiters wait for this one instead.\n */\n function transitionTo(next: DonutLayout<D>, jump: boolean): Promise<void> {\n laidOut = next;\n return transitions.run(retarget(next, jump));\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /** Where a slice is heading: what enter and update report as a change starts. */\n const input = (record: SliceRecord<D>): RunInput<D> => ({ mark: record.row.geometry, data: record.row.data });\n /** The slice as it is on screen: what hover, leave and exit report, so mid-change they match what's under the pointer or on its way out. */\n const onScreen = (record: SliceRecord<D>): RunInput<D> => ({ mark: record.shown.geometry, data: record.shown.data });\n\n /** The slice an event target belongs to (its label too); leaving slices don't count. */\n function liveRecordOf(eventTarget: EventTarget | null): SliceRecord<D> | undefined {\n const element = eventTarget as Element | null;\n const group = typeof element?.closest === \"function\" ? element.closest(\".ec-mark\") : null;\n const record = group ? byGroup.get(group) : undefined;\n return record && records.get(record.key) === record ? record : undefined;\n }\n\n // Pointer, touch and keyboard focus share one hover: see shell/hover.ts. A slice is its own target,\n // so a hover event has no segment.\n const hover = chartHover<D>({\n svg,\n runner,\n events,\n dim: () => current.dim !== false,\n find(eventTarget) {\n const record = liveRecordOf(eventTarget);\n return record && { key: record.key };\n },\n live: (key) => records.has(key),\n order: () => order.map((record) => record.key),\n element: (key) => find(key)?.group,\n hot: surface.hot,\n onScreen(key) {\n const record = find(key);\n return record && onScreen(record);\n },\n ring: drawRing,\n tooltip: {\n show(key) {\n const record = records.get(key);\n if (record) showTooltip(record);\n },\n hide: () => tooltip.hide(),\n element: () => tooltip.element()\n }\n });\n\n // ── Motion, size and fonts ─────────────────────────────────────────────────\n\n const unwatchHoverDuration = watchHoverDuration(svg, motion);\n\n /** Re-lays out without animating: a resize or fonts loading. A transition in flight lands at once. Effects follow through change(). */\n function relayout(): void {\n if (destroyed) return;\n const next = layout(current);\n // The same slices as now: only the sizes changed.\n const slices = new Map(next.slices.map((slice) => [slice.key, slice]));\n for (const record of order) record.row = slices.get(record.key) ?? record.row;\n void transitionTo(next, true);\n }\n\n const unwatchWidth = watchWidth(container, clock, measuredWidth, (width) => {\n measuredWidth = width;\n // A fixed `width` ignores the container.\n if (current.width === undefined) relayout();\n });\n\n // Labels' room is measured; measure again once web fonts arrive.\n const unwatchFonts = watchFonts(doc, () => {\n measure.clear();\n relayout();\n });\n\n // ── First render ───────────────────────────────────────────────────────────\n\n describeDonut();\n syncLegend();\n table.render(firstTable);\n setAttributes(svg, sizeAttributes(laidOut.frame));\n order = laidOut.slices.map((slice) => {\n const record = createRecord(slice, false);\n records.set(slice.key, record);\n labelMark(record);\n return record;\n });\n ring = from = order;\n laidOut.slices.forEach((slice, i) => drawMark(order[i]!, slice, laidOut.labels[i]));\n drawCenter(laidOut.center);\n hover.sync();\n runner.enter(order.map(input));\n\n return linkable(hover.link, {\n element: svg,\n\n async update(next) {\n if (destroyed) return;\n if (next.motion !== undefined && next.motion !== current.motion) throw new TypeError(\"donutChart: `motion` can't be changed by update() yet.\");\n const merged: DonutChartOptions<D> = { ...current, ...next };\n checkOptions(merged);\n // Throws on an effect it can't resolve, data it can't draw, a table column it can't read, or a\n // `format` that throws, before anything changes.\n const swapped = \"on\" in next ? nextEffects(effects, current.on, merged.on, env.presets) : effects;\n const nextLayout = layout(merged, swapped);\n const nextTable = tableFor(merged, nextLayout);\n const nextNames = namesFor(merged, nextLayout);\n if (\"colors\" in next) colors = toColorAssignment(merged.colors);\n const previous = current;\n const totalBefore = laidOut.total;\n current = merged;\n laidOut = nextLayout;\n names = nextNames;\n describeDonut();\n syncLegend();\n table.render(nextTable);\n // A region that appears with its first text is often missed: it announces from the next update.\n const announcing = announcer !== undefined;\n if (current.announce && !announcer) announcer = chartAnnouncer(svg);\n else if (!current.announce && announcer) {\n announcer.destroy();\n announcer = undefined;\n }\n hover.syncDim();\n transitions.supersede();\n const swapping = swapped !== effects;\n effects = swapped;\n\n // The runner hears exit / update / enter now, then change() on every frame, then settle(). New\n // effects start where the old ones were, on the slices staying, as this update leaves them; a\n // held hover replays with them once the change settles.\n const leaves = playUpdate(\n {\n runner,\n events,\n hover,\n leaving,\n input,\n onScreen,\n data: \"data\" in next,\n ...(swapping\n ? {\n swap: (diff: Diff<D>) => {\n const entering = new Set(diff.entering);\n runner.swap(swapped, order.filter((record) => !entering.has(record)).map(input));\n }\n }\n : {})\n },\n () => arrange(nextLayout),\n (diff) => {\n if (announcing) announceChange(previous, diff);\n }\n );\n count = nextLayout.total === totalBefore ? undefined : Math.max(decimals(totalBefore), decimals(nextLayout.total));\n const settled = transitionTo(nextLayout, motion.mode === \"off\");\n await transitions.wait(settled, leaves);\n },\n\n on: events.on,\n\n marks: () => order.map((record) => record.shown.geometry),\n\n focus(key) {\n if (!destroyed) hover.focus(key);\n },\n\n leave() {\n if (!destroyed) hover.leave();\n },\n\n // Outside the ring, the category over the share; the centre's text isn't a slice's.\n labels: () =>\n order.flatMap((record) => [\n ...chartLabel(record.key, \"category\", record.drawnLabel?.category, record.label),\n ...chartLabel(record.key, \"value\", record.drawnLabel?.share, record.share)\n ]),\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n // Ends the transition in flight, and resolves the latest update()'s promise.\n transitions.destroy();\n hover.destroy();\n runner.destroy();\n tooltip.destroy();\n legend.destroy();\n table.destroy();\n announcer?.destroy();\n unwatchHoverDuration();\n unwatchWidth();\n unwatchFonts();\n for (const record of [...order, ...leaving.values()]) {\n for (const value of [record.value, record.turn, record.presence]) value.stop();\n record.leave?.resolve();\n }\n frame.stop();\n events.clear();\n records.clear();\n leaving.clear();\n order = ring = from = [];\n svg.remove();\n }\n });\n}\n\nfunction checkOptions<D>(options: DonutChartOptions<D>): void {\n checkChartOptions(options, \"donutChart\");\n const { center, sort } = options;\n if (center !== undefined && center !== false && typeof center !== \"function\") throw new TypeError(\"donutChart: center must be false or a function that returns the text for the total.\");\n if (sort !== undefined && sort !== \"none\" && sort !== \"value\") throw new TypeError(`donutChart: sort must be \"value\" or \"none\", got ${String(sort)}.`);\n}\n\n/** The value in `format` with its series' label: \"112 shots\". A lone value read by a function goes unnamed unless it's labelled: \"112\". */\nfunction valueText<D>(slice: DonutSlice<D>, options: DonutChartOptions<D>): string {\n const formatted = format(options)(slice.value);\n const label = seriesLabel(options.seriesLabels, slice.series);\n return slice.series === \"value\" && label === \"value\" ? formatted : `${formatted} ${label}`;\n}\n\n/**\n * Every slice's name in `layout`, by key. Worked out before anything changes, since `format` may\n * first run here: with no table and no centre text, nothing else calls it.\n */\nfunction namesFor<D>(options: DonutChartOptions<D>, layout: DonutLayout<D>): ReadonlyMap<string, string> {\n return new Map(layout.slices.map((slice) => [slice.key, markLabel(slice, options)]));\n}\n\n/**\n * \"Saved: 112 shots, 28%\", the value said with its series' label, or the page's wording from\n * `markLabel`. An empty name, or a throw (reported), keeps the default, so a focusable slice is never\n * left unnamed.\n */\nfunction markLabel<D>(slice: DonutSlice<D>, options: DonutChartOptions<D>): string {\n const text = `${slice.category}: ${valueText(slice, options)}, ${percent(slice.share)}`;\n if (!options.markLabel) return text;\n try {\n const value = { series: slice.series, label: seriesLabel(options.seriesLabels, slice.series), value: slice.value };\n const named: unknown = options.markLabel(slice.datum, {\n key: slice.key,\n category: slice.category,\n values: [value],\n total: slice.value,\n share: slice.share,\n format: format(options),\n text\n });\n if (named !== undefined && named !== null && String(named).trim() !== \"\") return String(named);\n } catch (error) {\n report(error);\n }\n return text;\n}\n\n/**\n * The text in the hole for a total: `center`'s, or by default the total in `format` over the value's\n * series label (\"406\" over \"shots\"; the total alone for an unlabelled value read by a function). \"\"\n * for none, with `center: false`, and when the function throws (reported).\n */\nfunction centerText<D>(options: DonutChartOptions<D>, series: string, total: number): string {\n const { center } = options;\n const formatted = format(options);\n if (center === false) return \"\";\n if (center === undefined) {\n const label = seriesLabel(options.seriesLabels, series);\n return series === \"value\" && label === \"value\" ? formatted(total) : `${formatted(total)}\\n${label}`;\n }\n try {\n const text: unknown = center(total, formatted);\n return text === undefined || text === null ? \"\" : String(text);\n } catch (error) {\n report(error);\n return \"\";\n }\n}\n\n/** The chart's own description, then the centre's text on one line. */\nfunction description(own: string | undefined, center: string): string | undefined {\n const text = center.split(\"\\n\").join(\" \").trim();\n const mine = own?.trim();\n if (text === \"\") return own;\n if (!mine) return text;\n return /[.!?:;]$/.test(mine) ? `${mine} ${text}` : `${mine}. ${text}`;\n}\n\n/**\n * The ring's order: the layout's, with slices on their way out kept where they were, just after the\n * slice they followed, or first. So a leaving slice shrinks in place.\n */\nfunction mergeRing<R>(shown: readonly R[], next: readonly R[]): R[] {\n const out = [...next];\n shown.forEach((record, i) => {\n if (out.includes(record)) return;\n let at = 0;\n for (let j = i - 1; j >= 0; j--) {\n const found = out.indexOf(shown[j]!);\n if (found >= 0) {\n at = found + 1;\n break;\n }\n }\n out.splice(at, 0, record);\n });\n return out;\n}\n","// Time on the line chart's x: the steps between ticks, where ticks fall, and how a time is worded.\n// Pure, and with no dependency: boundaries are found with Date's own UTC or local getters and setters,\n// which handle daylight saving, and times are worded through Intl.DateTimeFormat in the page's locale.\n// A time is in ms, as Date.getTime() gives it.\n\nimport { niceStep } from \"./bar-layout\";\n\n/** The zone a time axis is in: UTC, or the viewer's clock. Named as Intl's option is, so IANA names can join it. */\nexport type TimeZone = \"UTC\" | \"local\";\n\nexport const TIME_ZONES: readonly TimeZone[] = [\"UTC\", \"local\"];\n\n/** How fine a time is: the coarsest boundary it falls on in its zone. Midnight on 1 January is a year. */\nexport type TimeLevel = \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\" | \"second\" | \"millisecond\";\n\ntype Unit = \"second\" | \"minute\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\";\n\n/** A step between ticks: `count` of a unit, on that unit's boundaries. */\nexport interface TimeStep {\n readonly unit: Unit;\n readonly count: number;\n}\n\n/** An x tick on a time axis: where it is, and its text. */\nexport interface TimeTick {\n readonly value: number;\n readonly text: string;\n}\n\nconst SECOND = 1000;\nconst MINUTE = 60 * SECOND;\nconst HOUR = 60 * MINUTE;\nconst DAY = 24 * HOUR;\n\n/**\n * Each unit at its longest, for choosing a step (never for placing a tick): a day of 25 hours when\n * the clocks go back, a month of 31 days, a year of 366. So a range of whole months or years gets\n * the step that fits it, whatever its leap days and clock changes.\n */\nconst LONGEST: Readonly<Record<Unit, number>> = { second: SECOND, minute: MINUTE, hour: HOUR, day: DAY + HOUR, week: 7 * DAY + HOUR, month: 31 * DAY, year: 366 * DAY };\n\n/** The steps shorter than a year, in order. Years go on in the number axis's nice steps. */\nconst STEPS: readonly TimeStep[] = [\n ...[1, 5, 15, 30].map((count) => ({ unit: \"second\" as const, count })),\n ...[1, 5, 15, 30].map((count) => ({ unit: \"minute\" as const, count })),\n ...[1, 3, 6, 12].map((count) => ({ unit: \"hour\" as const, count })),\n { unit: \"day\", count: 1 },\n { unit: \"day\", count: 2 },\n { unit: \"week\", count: 1 },\n { unit: \"month\", count: 1 },\n { unit: \"month\", count: 3 }\n];\n\n/** From the coarsest. */\nconst LEVELS: readonly TimeLevel[] = [\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\", \"millisecond\"];\n\n/** The level a step's boundaries are at, at least: a week starts on a day. */\nconst UNIT_LEVEL: Readonly<Record<Unit, TimeLevel>> = { second: \"second\", minute: \"minute\", hour: \"hour\", day: \"day\", week: \"day\", month: \"month\", year: \"year\" };\n\n/** Milliseconds, as a fraction of a second (\"1:00:00.100 PM\"). ES2021's option, so it isn't in this build's lib. */\nconst FRACTION = { fractionalSecondDigits: 3 } as Intl.DateTimeFormatOptions;\n\n/** What a time at each level says: the year on a year, the month on a month (\"Feb\"), the day on a day (\"Feb 8\"), the time within a day. */\nconst FIELDS: Readonly<Record<TimeLevel, Intl.DateTimeFormatOptions>> = {\n year: { year: \"numeric\" },\n month: { month: \"short\" },\n day: { month: \"short\", day: \"numeric\" },\n hour: { hour: \"numeric\", minute: \"2-digit\" },\n minute: { hour: \"numeric\", minute: \"2-digit\" },\n second: { hour: \"numeric\", minute: \"2-digit\", second: \"2-digit\" },\n millisecond: { hour: \"numeric\", minute: \"2-digit\", second: \"2-digit\", ...FRACTION }\n};\n\n/** The smallest step that can be `span` ms long, as the number axis rounds its step up. */\nexport function timeStep(span: number): TimeStep {\n for (const step of STEPS) if (LONGEST[step.unit] * step.count >= span) return step;\n return { unit: \"year\", count: Math.max(1, niceStep(span / LONGEST.year)) };\n}\n\n/**\n * The x ticks for times from `lo` to `hi`: both ends, and the boundaries strictly between them at a\n * step of about a quarter of the range (the smallest that can be that long, as on a number axis), each\n * on its boundary in the zone (a day at midnight, a month on its first). Each is worded for its own\n * level: \"2026\", \"Feb\", \"Feb 8\" (\"8 Feb\" in en-GB), \"3:00 PM\". The ends needn't be on a boundary, so\n * each also says the levels up to the step's and up to the coarsest the axis crosses, to be placed\n * even when the ticks between are dropped for room: \"Jan 5, 2026\" on an axis of years, or of months\n * into the next year; \"Feb 5, 3:00 PM\" on one of hours past midnight. A lone time says everything up\n * to its year.\n */\nexport function timeTicks(lo: number, hi: number, zone: TimeZone): TimeTick[] {\n const word = tickWording(zone);\n if (!(hi > lo)) return [{ value: lo, text: word(lo, \"year\") }];\n const step = timeStep((hi - lo) / 4);\n const ends = LEVELS[Math.min(LEVELS.indexOf(UNIT_LEVEL[step.unit]), LEVELS.indexOf(crossed(lo, hi, zone)))]!;\n const between = boundaries(lo, hi, step, zone).map((value) => ({ value, text: word(value, \"millisecond\") }));\n return [{ value: lo, text: word(lo, ends) }, ...between, { value: hi, text: word(hi, ends) }];\n}\n\n/** The coarsest boundary between `lo` and `hi`: the first of their fields that differs, from the year down. */\nfunction crossed(lo: number, hi: number, zone: TimeZone): TimeLevel {\n const [a, b] = [partsOf(lo, zone), partsOf(hi, zone)];\n if (a.year !== b.year) return \"year\";\n if (a.month !== b.month) return \"month\";\n if (a.date !== b.date) return \"day\";\n if (a.hours !== b.hours) return \"hour\";\n return a.minutes !== b.minutes ? \"minute\" : \"second\";\n}\n\n/** The step's boundaries strictly between `lo` and `hi`, in the zone, in order. */\nexport function boundaries(lo: number, hi: number, step: TimeStep, zone: TimeZone): number[] {\n const { unit, count } = step;\n const out: number[] = [];\n const start = partsOf(lo, zone);\n if (unit === \"second\" || unit === \"minute\" || unit === \"hour\") {\n // Whole units by the zone's clock, found by stepping through elapsed time and kept where the clock\n // shows a whole unit whose field is a multiple of `count`: an hour the clocks repeat has a tick each\n // time, and one they skip has none. Hours are stepped a quarter of an hour at a time, since clocks\n // change by whole quarter hours (Lord Howe Island's by half an hour), so a tick after the change is\n // still on the hour.\n const grain = unit === \"hour\" ? 15 * MINUTE : LONGEST[unit];\n let t = lo - start.ms - (unit === \"second\" ? 0 : start.seconds * SECOND) - (unit === \"hour\" ? (start.minutes % 15) * MINUTE : 0);\n for (; t < hi; t += grain) {\n const parts = partsOf(t, zone);\n const whole = unit !== \"hour\" || parts.minutes === 0;\n const field = unit === \"second\" ? parts.seconds : unit === \"minute\" ? parts.minutes : parts.hours;\n if (t > lo && whole && field % count === 0) out.push(t);\n }\n return out;\n }\n // Calendar units: each boundary is made from its fields, so a day is a day however long it is.\n const nth: (i: number) => number =\n unit === \"day\"\n ? (i) => midnight(zone, start.year, start.month, start.date + i)\n : unit === \"week\"\n ? // Weeks start on Monday, as ISO 8601's do.\n (i) => midnight(zone, start.year, start.month, start.date - ((start.weekday + 6) % 7) + 7 * i)\n : unit === \"month\"\n ? (i) => midnight(zone, start.year, Math.floor(start.month / count) * count + count * i, 1)\n : (i) => midnight(zone, Math.floor(start.year / count) * count + count * i, 0, 1);\n let previous = -Infinity;\n for (let i = 0; ; i++) {\n const t = nth(i);\n // A boundary always moves on; the check only guards against a zone that doesn't.\n if (t >= hi || t <= previous) break;\n previous = t;\n // Every other day counts from the 1st of each month.\n if (t > lo && (unit !== \"day\" || (partsOf(t, zone).date - 1) % count === 0)) out.push(t);\n }\n return out;\n}\n\n/**\n * `months` calendar months on from `t`, or back when it's negative, in the zone: the same day of the\n * month at the same time of day, or the month's last day when it's shorter, as Temporal's `add`\n * constrains it (31 January a month on is 28 February, or the 29th in a leap year). A time the\n * clocks skip there comes out just after the change, as Date's setters move it.\n */\nexport function monthsOn(t: number, months: number, zone: TimeZone): number {\n const { year, month, date, hours, minutes, seconds, ms } = partsOf(t, zone);\n // Day 0 of the month after is the last of the month: every zone's calendar has the same months.\n const last = new Date(0);\n last.setUTCFullYear(year, month + months + 1, 0);\n const day = Math.min(date, last.getUTCDate());\n const d = new Date(0);\n if (zone === \"UTC\") {\n d.setUTCFullYear(year, month + months, day);\n d.setUTCHours(hours, minutes, seconds, ms);\n } else {\n d.setFullYear(year, month + months, day);\n d.setHours(hours, minutes, seconds, ms);\n }\n return d.getTime();\n}\n\n/** The coarsest boundary `t` falls on, in the zone. */\nexport function timeLevel(t: number, zone: TimeZone): TimeLevel {\n const { ms, seconds, minutes, hours, date, month } = partsOf(t, zone);\n if (ms !== 0) return \"millisecond\";\n if (seconds !== 0) return \"second\";\n if (minutes !== 0) return \"minute\";\n if (hours !== 0) return \"hour\";\n if (date !== 1) return \"day\";\n return month !== 0 ? \"month\" : \"year\";\n}\n\n/**\n * How the chart says an x for people: a medium date in the page's locale (\"Jan 5, 2026\", or \"5 Jan\n * 2026\" in en-GB), with the time when any of `times` has one (\"Jan 5, 2026, 3:00 PM\"), its seconds\n * when any has those, and its milliseconds when any has those (\"Jan 5, 2026, 3:00:00.100 PM\"), so\n * every x is said differently.\n */\nexport function timeName(times: readonly number[], zone: TimeZone): (t: number) => string {\n const finest = times.reduce((max, t) => Math.max(max, LEVELS.indexOf(timeLevel(t, zone))), 0);\n const timeZone = zoneOption(zone);\n const timeStyle = finest >= LEVELS.indexOf(\"second\") ? \"medium\" : finest >= LEVELS.indexOf(\"hour\") ? \"short\" : undefined;\n // Intl's styles can't say a fraction of a second, so a time to the millisecond is said field by\n // field, as the medium styles say the rest.\n const options: Intl.DateTimeFormatOptions =\n finest === LEVELS.indexOf(\"millisecond\")\n ? { year: \"numeric\", ...FIELDS.day, ...FIELDS.millisecond, timeZone }\n : { dateStyle: \"medium\", ...(timeStyle ? { timeStyle } : {}), timeZone };\n const format = new Intl.DateTimeFormat(undefined, options);\n return (t) => format.format(t);\n}\n\n/** Words a time for its own level, with every level up to `upTo` when it's finer than that (\"millisecond\" adds none). A formatter per set of fields, made when first needed. */\nfunction tickWording(zone: TimeZone): (t: number, upTo: TimeLevel) => string {\n const formats = new Map<string, Intl.DateTimeFormat>();\n return (t, upTo) => {\n const own = LEVELS.indexOf(timeLevel(t, zone));\n const fields: Intl.DateTimeFormatOptions = {};\n for (let i = Math.min(own, LEVELS.indexOf(upTo)); i <= own; i++) Object.assign(fields, FIELDS[LEVELS[i]!]);\n const id = JSON.stringify(fields);\n let format = formats.get(id);\n if (!format) formats.set(id, (format = new Intl.DateTimeFormat(undefined, { ...fields, timeZone: zoneOption(zone) })));\n return format.format(t);\n };\n}\n\n/** Intl's timeZone for the zone: undefined is the viewer's own. */\nconst zoneOption = (zone: TimeZone): string | undefined => (zone === \"UTC\" ? \"UTC\" : undefined);\n\ninterface Parts {\n readonly year: number;\n /** 0 to 11. */\n readonly month: number;\n /** The day of the month, from 1. */\n readonly date: number;\n /** 0 is Sunday. */\n readonly weekday: number;\n readonly hours: number;\n readonly minutes: number;\n readonly seconds: number;\n readonly ms: number;\n}\n\nfunction partsOf(t: number, zone: TimeZone): Parts {\n const d = new Date(t);\n return zone === \"UTC\"\n ? { year: d.getUTCFullYear(), month: d.getUTCMonth(), date: d.getUTCDate(), weekday: d.getUTCDay(), hours: d.getUTCHours(), minutes: d.getUTCMinutes(), seconds: d.getUTCSeconds(), ms: d.getUTCMilliseconds() }\n : { year: d.getFullYear(), month: d.getMonth(), date: d.getDate(), weekday: d.getDay(), hours: d.getHours(), minutes: d.getMinutes(), seconds: d.getSeconds(), ms: d.getMilliseconds() };\n}\n\n/**\n * The start of a day in the zone: midnight, or the first time after it when the clocks skip it. The\n * month and the day may run over, as Date's setters allow (day 32 of January is 1 February). The\n * setters take any year, unlike Date.UTC, which reads 0 to 99 as 1900 to 1999.\n */\nfunction midnight(zone: TimeZone, year: number, month: number, date: number): number {\n const d = new Date(0);\n if (zone === \"UTC\") {\n d.setUTCFullYear(year, month, date);\n d.setUTCHours(0, 0, 0, 0);\n } else {\n d.setFullYear(year, month, date);\n d.setHours(0, 0, 0, 0);\n }\n return d.getTime();\n}\n","// The line chart's layout: pure, so it's tested without a DOM. Options in, the frame, ticks and size\n// out; placeLines and placePoints then draw the marks (lines described with describe.line, points\n// with describe.point) for any state of the rows and any reveal. Pixel sizes follow the prototype's\n// card 2 (demo/lab.html).\n//\n// A layout is drawn from a few numbers: the frame (the value scale, and the box: the x range and where\n// the plot sits) and each row's x and values. Transitions interpolate those numbers, and the place\n// functions draw any state in between, and any reveal, the same way the layout draws its own. On a\n// time axis an x is its Date's time in ms, and only its ticks, its wording and the samples' `at` know.\n// A missing value (null or undefined) is a gap in its line: the line runs on from the value after it.\n\nimport type { MarkData, MarkGeometry, Rect, Sample } from \"../core\";\nimport { describeLine } from \"../core/geometry/describe/line\";\nimport { describePoint } from \"../core/geometry/describe/point\";\nimport { clean, niceDomain, niceStep, type Tick } from \"./bar-layout\";\nimport { textBox, type TextPlacement } from \"./render/text\";\nimport { decimals } from \"./shell/format\";\nimport { TIME_ZONES, timeName, timeTicks, type TimeZone } from \"./time\";\nimport type { Accessor, LineChartOptions } from \"./types\";\n\nexport type { Tick } from \"./bar-layout\";\n\nexport interface LineSeries<D> {\n /** The series' name: its field. */\n readonly series: string;\n readonly value: (d: D, i: number) => unknown;\n}\n\n/** Which accessor gives the x, which the key, which the values; and how an x is said. */\nexport interface LineEncoding<D> {\n readonly x: (d: D, i: number) => unknown;\n /** Undefined: the key is the x. */\n readonly key: ((d: D, i: number) => unknown) | undefined;\n readonly series: readonly LineSeries<D>[];\n /** A time axis's zone. */\n readonly timeZone: TimeZone;\n /** Words an x for people instead of the default. */\n readonly xFormat: ((x: Date | number) => string) | undefined;\n}\n\nexport interface LineValue {\n readonly series: string;\n /** Undefined where the series has no value (null or undefined in the data): a gap in its line. */\n readonly value: number | undefined;\n}\n\nexport interface LineRow<D> {\n readonly key: string;\n readonly datum: D;\n /** The row's index in `data`. */\n readonly index: number;\n /** A number, or on a time axis its Date's time in ms. */\n readonly x: number;\n /** The x as text: the tooltip's title, the table's row header and the start of the x's name. */\n readonly label: string;\n /** In series order. */\n readonly values: readonly LineValue[];\n /** The series with no value here. */\n readonly missing: ReadonlySet<string>;\n /**\n * Each series' level here, which a change animates: its value, or for a missing one where its line\n * runs past this x (across the gap, or level with its nearest value; 0 with none), so a value that\n * comes grows out of the line.\n */\n readonly levels: Readonly<Record<string, number>>;\n}\n\n/** The value axis: data `lo` sits at the box's `bottom`, data `hi` at its `top`. */\nexport interface LineScale {\n readonly lo: number;\n readonly hi: number;\n}\n\n/**\n * The x axis and where the plot sits, in px: data `xLo` at `left`, `xHi` at `right`, the value scale\n * between `bottom` and `top`. Plus the chart's size.\n */\nexport interface LineBox {\n readonly xLo: number;\n readonly xHi: number;\n readonly left: number;\n readonly right: number;\n readonly top: number;\n readonly bottom: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** A change animates the scale in its values stage and the box in its positions stage. */\nexport interface LineFrame {\n readonly scale: LineScale;\n readonly box: LineBox;\n}\n\n/** An x tick: a label under the plot, with no gridline. */\nexport interface XTick {\n readonly value: number;\n readonly label: TextPlacement;\n}\n\nexport interface LineLayout<D> {\n readonly width: number;\n readonly height: number;\n readonly frame: LineFrame;\n /** In ascending x. */\n readonly rows: readonly LineRow<D>[];\n /** Whether x is a time axis: the data gives Dates. */\n readonly time: boolean;\n readonly series: readonly string[];\n /** Gridlines and labels for the values, from the bottom. */\n readonly yTicks: readonly Tick[];\n readonly xTicks: readonly XTick[];\n /** Per series, the decimals its values are given to: an end label counts rounded to these. */\n readonly decimals: Readonly<Record<string, number>>;\n}\n\nexport interface LineLayoutInput<D> {\n readonly data: readonly D[];\n readonly encoding: LineEncoding<D>;\n readonly width: number;\n readonly height: number | undefined;\n readonly format: (value: number) => string;\n /** Text width in px, for margins. */\n readonly measure: Measure;\n /** A line's end label for a value, measured for the right margin; undefined with `labels: false`. */\n readonly label: ((series: string, value: number) => string) | undefined;\n}\n\ntype Measure = (text: string, className: string, size: number) => number;\n\n/** How placeLines words the lines' end labels, and measures them for their boxes. */\nexport interface EndLabels {\n /** A line's end label for its value at its end; \"\" for none. */\n readonly text: (series: string, value: number) => string;\n readonly measure: Measure;\n}\n\n/** A row as it's drawn now, part way through a change: where it is, and its values by series. */\nexport interface RowState<D> {\n readonly key: string;\n readonly datum: D;\n readonly x: number;\n readonly values: Readonly<Record<string, number>>;\n /** The series with no value here: no point, and a gap in the line. Their `values` aren't drawn. */\n readonly missing?: ReadonlySet<string>;\n}\n\nexport interface PlacedLine<D> {\n readonly series: string;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n /** The line's revealed end, in px, where its end dot and label go, and its value there. */\n readonly end: { readonly x: number; readonly y: number; readonly value: number };\n /** Its end label, placed with the others' (its text \"\" for none); undefined without `labels`. */\n readonly label: TextPlacement | undefined;\n}\n\nexport interface PlacedPoint<D> {\n readonly key: string;\n readonly series: string;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n}\n\n// From the prototype: 2.25 px lines, dots of radius 4.5, 300 px high, labels 10 px past the end and\n// 16 px apart.\nexport const LINE_WIDTH = 2.25;\nexport const DOT_RADIUS = 4.5;\nconst HEIGHT = 300;\nconst TOP = 12;\n/** Space under the plot for the x labels. */\nconst AXIS = 32;\n/** Gridlines reach this far past the last x, so the end dots sit inside the grid. */\nconst GRID_PAST = 8;\nconst TICK_SIZE = 11;\nconst VALUE_SIZE = 12.5;\n/** Between a line's end and its label. */\nconst LABEL_GAP = 10;\n/** Between the centres of two end labels. */\nconst LABEL_SPACING = 16;\n/** Between two x labels. */\nconst TICK_GAP = 8;\n/** Moves a text baseline down by this share of the font size to centre the text on a line. */\nconst CENTRE = 0.36;\n\n/** Reads the options: the x, the key and the series. Throws on what it can't draw. */\nexport function lineEncoding<D>(options: LineChartOptions<D>): LineEncoding<D> {\n const { x, series, key } = options;\n if (typeof x !== \"string\" && typeof x !== \"function\") throw new TypeError(\"lineChart needs x: a field of numbers or Dates, or a function that returns each row's x.\");\n if (!Array.isArray(series) || series.length === 0) throw new TypeError(\"lineChart needs series: the numeric fields to draw as lines.\");\n const seen = new Set<string>();\n for (const field of series as readonly unknown[]) {\n if (typeof field !== \"string\" || field === \"\") throw new TypeError(`lineChart: each series must be a field name, got ${show(field)}.`);\n if (seen.has(field)) throw new TypeError(`lineChart: \"${field}\" appears twice in series.`);\n seen.add(field);\n }\n if (key !== undefined && typeof key !== \"string\" && typeof key !== \"function\") throw new TypeError(\"lineChart: key must be a field name or a function.\");\n const labels: unknown = options.labels;\n if (labels !== undefined && labels !== false && typeof labels !== \"function\") throw new TypeError(\"lineChart: labels must be false or a function that returns a line's end label.\");\n const timeZone: unknown = options.timeZone ?? \"UTC\";\n if (!TIME_ZONES.includes(timeZone as TimeZone)) throw new TypeError(`lineChart: timeZone must be \"UTC\" or \"local\", got ${show(timeZone)}.`);\n const xFormat: unknown = options.xFormat;\n if (xFormat !== undefined && typeof xFormat !== \"function\") throw new TypeError(\"lineChart: xFormat must be a function that turns an x into text.\");\n return {\n x: accessor(x),\n key: key === undefined ? undefined : accessor(key),\n series: series.map((field) => ({ series: field, value: accessor<D, unknown>(field) })),\n timeZone: timeZone as TimeZone,\n xFormat: options.xFormat\n };\n}\n\nexport function layoutLines<D>(input: LineLayoutInput<D>): LineLayout<D> {\n const { width, measure } = input;\n const height = input.height ?? HEIGHT;\n const { rows, time } = prepareRows(input);\n const series = input.encoding.series.map((s) => s.series);\n const domain = niceDomain(rows.flatMap((row) => row.values.flatMap((v) => (v.value === undefined ? [] : [v.value]))));\n const yTexts = domain.ticks.map(input.format);\n const xLo = rows[0]?.x ?? 0;\n const xHi = rows[rows.length - 1]?.x ?? 0;\n const ticked = rows.length === 0 ? [] : time ? timeTicks(xLo, xHi, input.encoding.timeZone) : xTickValues(xLo, xHi).map((value) => ({ value, text: xText(value) }));\n const xValues = ticked.map((tick) => tick.value);\n const xTexts = ticked.map((tick) => tick.text);\n const xWidths = xTexts.map((text) => measure(text, \"ec-tick\", TICK_SIZE));\n\n // The values' labels on the left; the end labels, or the last x label, on the right.\n const labelWidth = input.label ? widest(distinctLabels(rows, input.label), \"ec-value\", VALUE_SIZE, measure) : 0;\n const left = Math.max(widest(yTexts, \"ec-tick\", TICK_SIZE, measure) + 10, (xWidths[0] ?? 0) / 2 + 2);\n const right = Math.max(GRID_PAST + 2, (xWidths[xWidths.length - 1] ?? 0) / 2 + 2, labelWidth > 0 ? LABEL_GAP + labelWidth + 4 : 0);\n const frame: LineFrame = {\n scale: { lo: domain.lo, hi: domain.hi },\n box: { xLo, xHi, left, right: Math.max(left, width - right), top: TOP, bottom: Math.max(TOP, height - AXIS), width, height }\n };\n\n const decimalsBy: Record<string, number> = {};\n for (const name of series) decimalsBy[name] = 0;\n for (const row of rows) for (const v of row.values) if (v.value !== undefined) decimalsBy[v.series] = Math.max(decimalsBy[v.series]!, decimals(v.value));\n\n const xTicks = xValues.map((value, i) => placeXTick(frame, value, xTexts[i]!));\n return {\n width,\n height,\n frame,\n rows,\n time,\n series,\n yTicks: domain.ticks.map((value, i) => placeYTick(frame, value, yTexts[i]!)),\n xTicks: spaced(xTicks, xWidths),\n decimals: decimalsBy\n };\n}\n\n/** Data to px. With a single x, it sits in the middle of the plot. */\nexport function positions(frame: LineFrame): { x(value: number): number; y(value: number): number } {\n const { scale, box } = frame;\n const xSpan = box.xHi - box.xLo;\n const ySpan = scale.hi - scale.lo;\n return {\n x: (value) => (xSpan > 0 ? box.left + ((value - box.xLo) / xSpan) * (box.right - box.left) : (box.left + box.right) / 2),\n y: (value) => (ySpan > 0 ? box.bottom - ((value - scale.lo) / ySpan) * (box.bottom - box.top) : box.bottom)\n };\n}\n\n/**\n * Draws each series' line through `rows` (in ascending x) up to `through`: a vertex per row at or\n * before it, plus the point part way to the next row when `through` falls between two. With no row\n * at or before it, a line is its first point. Each line's data has the row at its revealed end, a\n * sample per vertex (`t` by distance along the walk, `at` its x: a Date on a `time` axis), and the\n * other lines as `related`. With `labels`, the end labels are placed together (placeEndLabels), and\n * each line's geometry has its own label's box as `labelBounds`: none when its text is \"\".\n *\n * A row missing a series is no vertex of its line: the line breaks there (`breaks`, so its geometry\n * has a gap from the value before to the value after, and the sample after it has `gapBefore`), and\n * a line revealed into a gap ends at its last value. Missing values before a line's first value or\n * after its last are no gap. A line with no value up to the reveal is empty: no length, no samples\n * and no label, at its level at the first x, and its datum the row at the reveal.\n */\nexport function placeLines<D>(frame: LineFrame, rows: readonly RowState<D>[], series: readonly string[], through: number, time = false, labels?: EndLabels): PlacedLine<D>[] {\n const first = rows[0];\n if (!first) return [];\n const at = positions(frame);\n let last = 0;\n while (last + 1 < rows.length && rows[last + 1]!.x <= through) last++;\n const end = rows[last]!;\n const next = rows[last + 1];\n const share = next && next.x > end.x && through > end.x ? (through - end.x) / (next.x - end.x) : undefined;\n const shown = rows.slice(0, last + 1);\n\n const datas = new Map<string, MarkData<D>>();\n const related = (own: string) => (name: string) => (name === own ? undefined : datas.get(name));\n const traced = series.map((name) => {\n const has = (row: RowState<D>): boolean => !row.missing?.has(name);\n const vertices: { at: number; value: number; datum: D; gapBefore: boolean }[] = [];\n let gap = false;\n for (const row of shown) {\n // A gap is only between values: none before the first.\n if (!has(row)) gap = vertices.length > 0;\n else {\n vertices.push({ at: row.x, value: row.values[name] ?? 0, datum: row.datum, gapBefore: gap });\n gap = false;\n }\n }\n if (share !== undefined && has(end) && has(next!)) {\n const from = end.values[name] ?? 0;\n vertices.push({ at: through, value: from + share * ((next!.values[name] ?? 0) - from), datum: end.datum, gapBefore: false });\n }\n const points = vertices.length > 0 ? vertices.map((v) => ({ x: at.x(v.at), y: at.y(v.value) })) : [{ x: at.x(first.x), y: at.y(first.values[name] ?? 0) }];\n return { name, vertices, points };\n });\n // An empty line has no label, and takes no room from the others'.\n const named = traced.filter(({ vertices }) => vertices.length > 0);\n const placed = labels\n ? placeEndLabels(\n frame,\n named.map(({ name, vertices, points }) => ({ ...points[points.length - 1]!, text: labels.text(name, vertices[vertices.length - 1]!.value) }))\n )\n : [];\n const lines = traced.map(({ name, vertices, points }): PlacedLine<D> => {\n const tip = points[points.length - 1]!;\n const label = labels ? (placed[named.findIndex((line) => line.name === name)] ?? { x: tip.x + LABEL_GAP, y: tip.y + VALUE_SIZE * CENTRE, anchor: \"start\", text: \"\" }) : undefined;\n const labelBounds = labels ? (label && label.text !== \"\" ? [textBox(label, labels.measure, \"ec-value\", VALUE_SIZE)] : []) : undefined;\n const breaks = vertices.flatMap((v, j) => (v.gapBefore ? [j] : []));\n const geometry = describeLine({ key: name, series: name, points, width: LINE_WIDTH, ...(breaks.length > 0 ? { breaks } : {}), ...(labelBounds ? { labelBounds } : {}) });\n // By distance, as the walk measures it, gaps and all; the last is exactly 1.\n let distance = 0;\n const samples: Sample[] = vertices.map((v, j) => {\n if (j > 0) distance += Math.hypot(points[j]!.x - points[j - 1]!.x, points[j]!.y - points[j - 1]!.y);\n const t = geometry.length > 0 ? (j === vertices.length - 1 ? 1 : Math.min(1, distance / geometry.length)) : 0;\n return { t, value: v.value, at: sampleAt(v.at, time), ...(v.gapBefore ? { gapBefore: true } : {}) };\n });\n const last = vertices[vertices.length - 1];\n const data: MarkData<D> = { datum: last ? last.datum : end.datum, samples, related: related(name) };\n datas.set(name, data);\n return { series: name, geometry, data, end: { ...tip, value: last ? last.value : (first.values[name] ?? 0) }, label };\n });\n return lines;\n}\n\n/**\n * The points that show at rest: each value next to a gap with no other value beside it, so it has\n * no stroke. Keyed as points are, from `rows` as they're drawn, in ascending x.\n */\nexport function loneValues<D>(rows: readonly RowState<D>[], series: readonly string[]): Set<string> {\n const lone = new Set<string>();\n // Every frame of a change asks: a chart with no gaps answers at once.\n if (!rows.some((row) => row.missing !== undefined && row.missing.size > 0)) return lone;\n const has = (row: RowState<D> | undefined, name: string): boolean => row !== undefined && !row.missing?.has(name);\n rows.forEach((row, i) => {\n for (const name of series) {\n const before = rows[i - 1];\n const after = rows[i + 1];\n if (has(row, name) && !has(before, name) && !has(after, name) && (before !== undefined || after !== undefined)) lone.add(pointKey(name, row.key));\n }\n });\n return lone;\n}\n\n/** The point mark's key: \"<series>@<row key>\". */\nexport function pointKey(series: string, row: string): string {\n return `${series}@${row}`;\n}\n\n/** Each series' point at the row, but those missing there: a dot, with the row's value as its one sample (`at` its x: a Date on a `time` axis) and the other series' points as `related`. */\nexport function placePoints<D>(frame: LineFrame, row: RowState<D>, series: readonly string[], time = false): PlacedPoint<D>[] {\n const at = positions(frame);\n const x = at.x(row.x);\n const datas = new Map<string, MarkData<D>>();\n return series.filter((name) => !row.missing?.has(name)).map((name) => {\n const value = row.values[name] ?? 0;\n const key = pointKey(name, row.key);\n const data: MarkData<D> = { datum: row.datum, samples: [{ t: 0, value, at: sampleAt(row.x, time) }], related: (other) => (other === name ? undefined : datas.get(other)) };\n datas.set(name, data);\n return { key, series: name, geometry: describePoint({ key, series: name, x, y: at.y(value), r: DOT_RADIUS }), data };\n });\n}\n\n/**\n * Each revealed x's hit column, given their px in ascending order: from halfway to the x before it to\n * halfway to the x after it, the first from the chart's left edge and the last to its right edge, so\n * the pointer hovers the nearest revealed x anywhere over the chart.\n */\nexport function placeColumns(frame: LineFrame, xs: readonly number[]): Rect[] {\n const { width, height } = frame.box;\n return xs.map((x, i) => {\n const from = i === 0 ? 0 : (xs[i - 1]! + x) / 2;\n const to = i === xs.length - 1 ? width : (x + xs[i + 1]!) / 2;\n return { x: from, y: 0, width: Math.max(0, to - from), height };\n });\n}\n\n/** The dashed line across the plot at x px, for the hovered x. */\nexport function placeCrosshair(frame: LineFrame, x: number): { readonly x1: number; readonly y1: number; readonly x2: number; readonly y2: number } {\n return { x1: x, y1: frame.box.top, x2: x, y2: frame.box.bottom };\n}\n\n/**\n * Each line's end label, in the order given: 10 px past its end, centred on its end's y but kept at\n * least 16 px from the others (the prototype's rule) and inside the chart.\n */\nexport function placeEndLabels(frame: LineFrame, ends: readonly { readonly x: number; readonly y: number; readonly text: string }[]): TextPlacement[] {\n const half = VALUE_SIZE / 2;\n const ys = spread(\n ends.map((end) => end.y),\n LABEL_SPACING,\n half,\n frame.box.height - half\n );\n return ends.map((end, i) => ({ x: end.x + LABEL_GAP, y: ys[i]! + VALUE_SIZE * CENTRE, anchor: \"start\", text: end.text }));\n}\n\n/**\n * Moves values apart so neighbours are at least `gap` apart, keeping them within [min, max] where\n * there's room. Values that would come too close form a cluster spaced `gap` apart and centred on\n * where its members would be, so two labels too close move apart equally. In the order given.\n */\nexport function spread(values: readonly number[], gap: number, min: number, max: number): number[] {\n const order = values.map((value, index) => ({ value, index })).sort((a, b) => a.value - b.value || a.index - b.index);\n const clusters: { members: { value: number; index: number }[]; start: number }[] = [];\n const place = (members: { value: number }[]): number => {\n const mean = members.reduce((sum, m) => sum + m.value, 0) / members.length;\n const span = (members.length - 1) * gap;\n return Math.max(min, Math.min(max - span, mean - span / 2));\n };\n for (const item of order) {\n clusters.push({ members: [item], start: place([item]) });\n // Merges with the cluster above while they'd overlap.\n while (clusters.length > 1) {\n const below = clusters[clusters.length - 1]!;\n const above = clusters[clusters.length - 2]!;\n if (below.start - (above.start + (above.members.length - 1) * gap) >= gap) break;\n clusters.pop();\n above.members.push(...below.members);\n above.start = place(above.members);\n }\n }\n const out = new Array<number>(values.length);\n for (const cluster of clusters) cluster.members.forEach((member, i) => (out[member.index] = cluster.start + i * gap));\n return out;\n}\n\n/** A value's gridline across the plot (and a little past the last x) and its label on the left. */\nexport function placeYTick(frame: LineFrame, value: number, text: string): Tick {\n const { box } = frame;\n const y = positions(frame).y(value);\n return { value, line: { x1: box.left, y1: y, x2: box.right + GRID_PAST, y2: y }, label: { x: box.left - 8, y: y + TICK_SIZE * CENTRE, anchor: \"end\", text } };\n}\n\n/** An x's label under the plot. */\nexport function placeXTick(frame: LineFrame, value: number, text: string): XTick {\n return { value, label: { x: positions(frame).x(value), y: frame.box.bottom + 18, anchor: \"middle\", text } };\n}\n\n/** Where x labels go: both ends of the rows' range, and round steps (1, 2 or 5 × a power of 10) between them, about four apart. */\nexport function xTickValues(lo: number, hi: number): number[] {\n if (!(hi > lo)) return [lo];\n const step = niceStep((hi - lo) / 4);\n const ticks = [lo];\n for (let i = Math.floor(lo / step) + 1; clean(i * step) < hi; i++) {\n const value = clean(i * step);\n if (value > lo) ticks.push(value);\n }\n ticks.push(hi);\n return ticks;\n}\n\n/** An x as text: as given, with no grouping (a year stays \"2024\"). */\nexport function xText(x: number): string {\n return String(x);\n}\n\n/** The ticks whose labels don't collide: both ends, and the steps between that clear their neighbours by 8 px. With no room for both ends, the first. */\nfunction spaced(ticks: readonly XTick[], widths: readonly number[]): XTick[] {\n if (ticks.length <= 1) return [...ticks];\n const edges = ticks.map((tick, i) => ({ tick, from: tick.label.x - widths[i]! / 2, to: tick.label.x + widths[i]! / 2 }));\n const last = edges[edges.length - 1]!;\n const kept = [edges[0]!];\n for (const edge of edges.slice(1, -1)) {\n if (edge.from - kept[kept.length - 1]!.to >= TICK_GAP && last.from - edge.to >= TICK_GAP) kept.push(edge);\n }\n if (last.from - kept[kept.length - 1]!.to >= TICK_GAP) kept.push(last);\n return kept.map((edge) => edge.tick);\n}\n\n/** The rows in ascending x, and whether x is a time axis: the first row's x is a Date. */\nfunction prepareRows<D>({ data, encoding }: LineLayoutInput<D>): { rows: LineRow<D>[]; time: boolean } {\n const keys = new Set<string>();\n let time = false;\n const read = data.map((datum, index) => {\n const raw = encoding.x(datum, index);\n if (index === 0) time = raw instanceof Date;\n const x = xOf(raw, index, time);\n // A date is keyed by its ISO string, which says the same instant the same way on every machine.\n const key = String(encoding.key ? encoding.key(datum, index) : time ? new Date(x).toISOString() : x);\n if (keys.has(key)) throw new Error(`lineChart: two rows have the key \"${key}\". Keys must be unique.`);\n keys.add(key);\n const values = encoding.series.map(({ series, value }) => ({ series, value: numberOf(value(datum, index), series, key) }));\n return { key, datum, index, x, values };\n });\n // Array.prototype.sort is stable, so the error below names the rows in data order.\n read.sort((a, b) => a.x - b.x);\n for (let i = 1; i < read.length; i++) {\n const [a, b] = [read[i - 1]!, read[i]!];\n if (a.x === b.x) {\n const x = time ? new Date(a.x).toISOString() : xText(a.x);\n throw new Error(`lineChart: the rows \"${a.key}\" and \"${b.key}\" have the same x, ${x}. Each x is one point on every line, so x values must be unique.`);\n }\n }\n const word = xWording(encoding, time, read.map((row) => row.x));\n const levels = levelsOf(read, encoding.series.length);\n return {\n rows: read.map((row, i) => ({ ...row, label: word(row.x), missing: new Set(row.values.flatMap((v) => (v.value === undefined ? [v.series] : []))), levels: levels[i]! })),\n time\n };\n}\n\n/**\n * Each row's level for each series, by series name: its value, or for a missing one where its line\n * runs past the row's x: across the gap, in proportion to x, or level with its nearest value before\n * its first or after its last. A series with no values is at 0.\n */\nfunction levelsOf(rows: readonly { readonly x: number; readonly values: readonly LineValue[] }[], count: number): Record<string, number>[] {\n const levels = rows.map((): Record<string, number> => ({}));\n for (let s = 0; s < count; s++) {\n let before = -1;\n let after = -1;\n rows.forEach((row, i) => {\n const { series, value } = row.values[s]!;\n if (value !== undefined) {\n levels[i]![series] = value;\n before = i;\n return;\n }\n // The next value, found once for each run of missing ones, so a long run stays linear.\n if (after <= i) {\n after = i + 1;\n while (after < rows.length && rows[after]!.values[s]!.value === undefined) after++;\n }\n const a = rows[before]?.values[s]!.value;\n const b = rows[after]?.values[s]!.value;\n levels[i]![series] =\n a !== undefined && b !== undefined ? a + ((row.x - rows[before]!.x) / (rows[after]!.x - rows[before]!.x)) * (b - a) : (a ?? b ?? 0);\n });\n }\n return levels;\n}\n\n/** A row's x as a number: a finite number, or on a time axis a valid Date's time. Every row's x is the same kind as the first's. */\nfunction xOf(x: unknown, index: number, time: boolean): number {\n if (x instanceof Date) {\n if (!time) throw new TypeError(`lineChart: x must be all numbers or all Dates, but row 0's is a number and row ${index}'s a Date.`);\n const t = x.getTime();\n if (Number.isNaN(t)) throw new TypeError(`lineChart: x must be a valid Date, got an invalid Date in row ${index}.`);\n return t;\n }\n if (time) {\n if (typeof x === \"number\") throw new TypeError(`lineChart: x must be all numbers or all Dates, but row 0's is a Date and row ${index}'s a number.`);\n throw new TypeError(`lineChart: x must be a valid Date, got ${show(x)} in row ${index}.`);\n }\n if (typeof x !== \"number\" || !Number.isFinite(x)) throw new RangeError(`lineChart: x must be a finite number, got ${show(x)} in row ${index}.`);\n return x;\n}\n\n/** How an x is said for people: `xFormat`'s words, given the x as the data has it; or a time axis's medium date; or a number as given. */\nfunction xWording<D>(encoding: LineEncoding<D>, time: boolean, xs: readonly number[]): (x: number) => string {\n const { xFormat } = encoding;\n if (xFormat) return (x) => xFormat(time ? new Date(x) : x);\n return time ? timeName(xs, encoding.timeZone) : xText;\n}\n\n/** A sample's `at` for an x: on a time axis, a Date of its own, so an effect that changes it changes nothing else. */\nfunction sampleAt(x: number, time: boolean): number | Date {\n return time ? new Date(x) : x;\n}\n\n/**\n * A value, or undefined for a missing one: null or undefined, a gap in the line. A line doesn't count\n * a missing value as 0 as a bar does, and NaN and the infinities still throw: they're usually a mistake.\n */\nfunction numberOf(value: unknown, series: string, key: string): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (value === null || value === undefined) return undefined;\n throw new RangeError(`lineChart: \"${series}\" for \"${key}\" must be a finite number, or null or undefined where it has no value, got ${show(value)}.`);\n}\n\n/**\n * The end labels worth measuring: one of each shape, its digits aside. Chart text has tabular digits,\n * so \"23 goals\" and \"48 goals\" are as wide, and a long series isn't measured row by row in the DOM.\n */\nfunction distinctLabels<D>(rows: readonly LineRow<D>[], label: (series: string, value: number) => string): string[] {\n const shapes = new Map<string, string>();\n for (const row of rows) {\n for (const { series, value } of row.values) {\n if (value === undefined) continue;\n const text = label(series, value);\n const shape = text.replace(/\\d/g, \"0\");\n if (!shapes.has(shape)) shapes.set(shape, text);\n }\n }\n return [...shapes.values()];\n}\n\nfunction widest(texts: readonly string[], className: string, size: number, measure: Measure): number {\n return texts.reduce((max, text) => Math.max(max, measure(text, className, size)), 0);\n}\n\nfunction accessor<D, T>(option: Accessor<D, T> | string): (d: D, i: number) => T {\n if (typeof option === \"function\") return option;\n return (d) => (d as Record<string, unknown>)[option] as T;\n}\n\nconst show = (value: unknown): string => (typeof value === \"string\" ? JSON.stringify(value) : String(value));\n","// lineChart: the reference line chart. A line per series through one row per x (described with\n// describe.line), with a dot at its end and a label in the right margin, and a point per row and series\n// (describe.point), shown where its x is hovered or focused; a measured layout with gridlines and ticks\n// in theme colours; a crosshair that hovers every series at the nearest x, from the pointer, touch or\n// keyboard, with a tooltip; a legend, a data table and, with `announce`, a live region for screen\n// readers. A missing value (null or undefined) is a gap in its line, with no point; the x is still a\n// stop. reveal(x) shows the data up to x, as playback drives it. update() animates the change:\n// staged in presentation (values, then positions), in one short stage in analysis, at once when\n// motion is off. x is numbers or Dates: a time axis has its own ticks and wording (time.ts), and is\n// otherwise drawn in ms like any number.\n//\n// The chart never names an effect: it resolves `on` through the presets it's handed and plays them\n// through the runner, which draws on the SVG surface. What doesn't depend on lines (events, hover and\n// focus, transitions and leaving marks, DOM order, size and fonts) is in shell/. Each x is a hover\n// target standing for every series' point there; the lines themselves are never hovered.\n\nimport type { AnimateOptions, Animated, MarkData, MarkGeometry, Sample, TweenResult } from \"../core\";\nimport { animated, defaultClock, interpolateNumber, interpolateRecord, matrix } from \"../core\";\nimport { resolveEffects } from \"../core/registry\";\nimport { report } from \"../core/report\";\nimport { createRunner, type RunInput } from \"../core/runner\";\nimport { chartAnnouncer, changeText, type Announcer } from \"./announce\";\nimport { toColorAssignment } from \"./colors\";\nimport { chartLegend } from \"./legend\";\nimport {\n DOT_RADIUS,\n LINE_WIDTH,\n layoutLines,\n lineEncoding,\n loneValues,\n placeColumns,\n placeCrosshair,\n placeLines,\n placePoints,\n placeXTick,\n placeYTick,\n pointKey,\n positions,\n type EndLabels,\n type LineFrame,\n type LineLayout,\n type LineRow,\n type LineValue,\n type PlacedLine,\n type PlacedPoint,\n type RowState\n} from \"./line-layout\";\nimport { linkable } from \"./link\";\nimport { chartMotion } from \"./motion\";\nimport { svgMarkHandle, type StyledPart, type SvgMarkHandle } from \"./render/mark-style\";\nimport { svgSurface } from \"./render/surface\";\nimport { setAttributes, setStyles, sizeAttributes, svgElement, transformAttribute } from \"./render/svg\";\nimport { placeText, textMeasure, type TextPlacement } from \"./render/text\";\nimport { injectStyles, markColorStyles, seriesColors, type SeriesColors } from \"./render/theme\";\nimport { seriesLabel } from \"./series\";\nimport { chartEvents } from \"./shell/events\";\nimport { decimals, format, round } from \"./shell/format\";\nimport { chartHover } from \"./shell/hover\";\nimport { chartLabel } from \"./shell/labels\";\nimport { leavingMarks, type Leave } from \"./shell/leaving\";\nimport { orderElements } from \"./shell/order\";\nimport { checkChartOptions, checkNeeds, containerWidth, describeChart, nextEffects, resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport { busy, chartTransitions, geometryChanged, playUpdate, same, sameFields, type ChartDiff } from \"./shell/transitions\";\nimport { watchFonts, watchHoverDuration, watchWidth } from \"./shell/watch\";\nimport { chartTable, tableModel, type TableModel } from \"./table\";\nimport { monthsOn } from \"./time\";\nimport { chartTooltip, summaryContent, type TooltipContent } from \"./tooltip\";\nimport type { LineChart, LineChartOptions } from \"./types\";\n\nexport type { LineChart } from \"./types\";\n\n/** Values by series, in data units. */\ntype Values = Readonly<Record<string, number>>;\n\n/** A mark as it's laid out or drawn: its geometry, and the data effects get with it. */\ninterface Placed<D> {\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n}\n\n/** One x: a focus stop with its hit column, and a point per series. A row isn't a mark itself. */\ninterface RowRecord<D> {\n readonly key: string;\n /** Where the row is heading, or rests: its row in the latest layout (its last one while it folds away). */\n row: LineRow<D>;\n /** In data units, so every frame reads true against the axes. */\n readonly x: Animated<number>;\n readonly values: Animated<Values>;\n /** 0 to 1: how far it has grown out of its anchor, or is left before it has folded into it. */\n readonly presence: Animated<number>;\n /** The row it grows out of or folds into: the nearest row that stays, before it or else after it. */\n anchor: RowRecord<D> | undefined;\n /** The focus stop: an image named for the x, holding the hit column. */\n readonly column: SVGGElement;\n readonly hit: SVGRectElement;\n /** Its points, live or leaving, live ones in series order first. */\n points: PointRecord<D>[];\n /** Set while it folds away. */\n leaving: boolean;\n /** Whether its column is shown: live and revealed. */\n shown: boolean;\n /** Where its x is drawn now, px: the crosshair's place when it has no point. */\n px: number;\n}\n\ninterface MarkBase<D> {\n readonly key: string;\n readonly series: string;\n readonly group: SVGGElement;\n /** Holds the stroke or the dot; effects' transform and opacity go here. */\n readonly body: SVGGElement;\n readonly path: SVGPathElement;\n parts: StyledPart[];\n readonly handle: SvgMarkHandle;\n /** Where it's heading, as laid out at the reveal: what enter and update report as a change starts. */\n target: Placed<D>;\n /** What's on screen now. */\n shown: Placed<D>;\n /** Set while it leaves. */\n leave: Leave | undefined;\n}\n\ninterface LineRecord<D> extends MarkBase<D> {\n readonly kind: \"line\";\n /** The dot at its revealed end. */\n readonly end: SVGCircleElement;\n readonly label: SVGTextElement;\n /** Where the end label is drawn now; undefined while it shows none. */\n drawnLabel: TextPlacement | undefined;\n /** 0 to 1: a series entering or leaving fades its line in or out. */\n readonly presence: Animated<number>;\n}\n\ninterface PointRecord<D> extends MarkBase<D> {\n readonly kind: \"point\";\n row: RowRecord<D>;\n /**\n * Past the reveal: hidden, overlays and all. Undefined until it's first drawn, so a new point sets\n * its overlays' visibility whatever a gone point with its key left there.\n */\n hidden: boolean | undefined;\n}\n\ntype MarkRecord<D> = LineRecord<D> | PointRecord<D>;\n\ninterface TickRecord {\n readonly value: number;\n /** A value's gridline; x ticks have none. */\n readonly line: SVGLineElement | undefined;\n readonly label: SVGTextElement;\n /** An x tick's text in its latest layout: a time's depends on the step. A value's is worded by `format` as it's drawn. */\n text: string;\n /** Ticks a scale gains fade in, and ones it loses fade out. */\n readonly opacity: Animated<number>;\n /** In the latest layout. */\n wanted: boolean;\n}\n\n/** What an update changed, by mark. */\ntype Diff<D> = ChartDiff<MarkRecord<D>>;\n\n/** What an update changed, by x: what the announcement says. */\ninterface RowChanges<D> {\n readonly changed: RowRecord<D>[];\n readonly added: RowRecord<D>[];\n readonly removed: RowRecord<D>[];\n}\n\n/** Base ms for each stage of a data change: values, then positions. Unstaged, a change takes as long as its stages together, which analysis scales down. */\nconst STAGE = 500;\n/** The focus ring's px: a gap in the surface colour around the point, then the ring. */\nconst RING_GAP = 2;\nconst RING = 2;\n/** A walk shorter than this draws nothing, as effects treat it. */\nconst VISIBLE = 0.5;\n\nexport function lineChart<D>(target: string | Element, options: LineChartOptions<D>, env: ChartEnv): LineChart<D> {\n const container = resolveTarget(target, \"lineChart\");\n checkChartOptions(options, \"lineChart\");\n let current = options;\n const motion = chartMotion(options.motion, env.motion);\n let effects = resolveEffects(options.on, env.presets);\n let colors = toColorAssignment(options.colors);\n const clock = env.clock ?? defaultClock;\n const doc = container.ownerDocument;\n injectStyles(doc);\n\n // A named group of x's, each an image with its own name; the lines and points are aria-hidden:\n // see \"ARIA structure\" in docs/architecture.md.\n const svg = svgElement(\"svg\", { class: \"ec-chart ec-line-chart\", role: \"group\" }, container);\n const grid = svgElement(\"g\", { class: \"ec-grid\", \"aria-hidden\": \"true\" }, svg);\n const axis = svgElement(\"g\", { class: \"ec-axis\", \"aria-hidden\": \"true\" }, svg);\n const crosshair = svgElement(\"line\", { class: \"ec-crosshair\", \"aria-hidden\": \"true\", visibility: \"hidden\" }, svg);\n // Behind the marks, so it can't cover them; the gap keeps it apart from a point in the same colour.\n const ring = svgElement(\"g\", { class: \"ec-focus\", \"aria-hidden\": \"true\", visibility: \"hidden\" }, svg);\n const marksLayer = svgElement(\"g\", { class: \"ec-marks\", \"aria-hidden\": \"true\" }, svg);\n const linesLayer = svgElement(\"g\", { class: \"ec-lines\" }, marksLayer);\n const pointsLayer = svgElement(\"g\", { class: \"ec-points\" }, marksLayer);\n // Above the marks: the pointer's targets and the focus stops.\n const columnsLayer = svgElement(\"g\", { class: \"ec-columns\" }, svg);\n const overlay = svgElement(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" }, svg);\n const measure = textMeasure(svg);\n\n /** Live rows, in ascending x. */\n let rowOrder: RowRecord<D>[] = [];\n const rows = new Map<string, RowRecord<D>>();\n /** Rows folding away: drawn until the change lands. */\n const leavingRows = new Map<string, RowRecord<D>>();\n const byColumn = new WeakMap<Element, RowRecord<D>>();\n /** Live lines, in series order. */\n let lineOrder: LineRecord<D>[] = [];\n const lines = new Map<string, LineRecord<D>>();\n const points = new Map<string, PointRecord<D>>();\n /** Lines and points on their way out: fading, or waiting for their exit effects. */\n const leaving = leavingMarks<MarkRecord<D>>((record) =>\n record.kind === \"line\" ? record.presence.animating : record.row.presence.animating || record.row.values.animating || record.row.x.animating\n );\n const events = chartEvents<D>(\"lineChart\");\n let measuredWidth = containerWidth(container);\n let destroyed = false;\n /** The x the page last revealed to, unclamped: Infinity shows every row, rows added later too. */\n let through = Infinity;\n /** Labels whose function threw, reported once: they're worded on every frame. */\n const labelFailures = new WeakSet<object>();\n\n let laidOut: LineLayout<D>;\n let firstTable: TableModel | undefined;\n /** Each x's accessible name, by row key, for the latest layout. */\n let names: ReadonlyMap<string, string>;\n try {\n // Throws on data it can't draw, a table column it can't read, or a `format` that throws. Nothing\n // but the <svg> is in place yet (no listeners, observers or elements beside it), so that's all to undo.\n laidOut = layout(current);\n firstTable = tableFor(current, laidOut);\n names = namesFor(current, laidOut);\n } catch (error) {\n svg.remove();\n throw error;\n }\n\n const findMark = (key: string): MarkRecord<D> | undefined => points.get(key) ?? lines.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay,\n // Looked up on each call, so the handle follows the mark's record.\n mark: (key) => ({\n set: (style) => {\n findMark(key)?.handle.set(style);\n hover.restyled(key);\n },\n reset: () => {\n findMark(key)?.handle.reset();\n hover.restyled(key);\n }\n }),\n colors: (key) => findMark(key)?.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const tooltip = chartTooltip<D>(svg, { motion, option: () => current.tooltip, description: () => current.markDescription });\n const legend = chartLegend(svg);\n const table = chartTable(svg);\n let announcer: Announcer | undefined = current.announce ? chartAnnouncer(svg) : undefined;\n\n // ── Animated state ─────────────────────────────────────────────────────────\n // Each row has its x, its values and its presence, and the chart has the scale and the box, so a\n // new update() mid-flight retargets each from where it is and nothing jumps. Where a line is comes\n // from them: through every row as it is now, up to the reveal.\n\n /** Something moved since the last frame was drawn. A line depends on every row, so a frame draws everything. */\n let dirty = false;\n const changed = (): void => {\n dirty = true;\n };\n const scale = animated(laidOut.frame.scale, interpolateRecord, { clock, motion, onChange: changed });\n const box = animated(laidOut.frame.box, interpolateRecord, { clock, motion, onChange: changed });\n const yTicks = new Map<number, TickRecord>();\n const xTicks = new Map<number, TickRecord>();\n /** Per series, the decimals an end label counts in: the values' own, or both sides' while a change plays. */\n let counting: Readonly<Record<string, number>> = laidOut.decimals;\n /** What the latest update changed, by x, for its announcement. */\n let rowChanges: RowChanges<D> = { changed: [], added: [], removed: [] };\n /** The frame last drawn, for the crosshair. */\n let drawnFrame: LineFrame = laidOut.frame;\n\n const transitions = chartTransitions({ clock, runner, leaving, draw, land });\n\n // ── Layout ─────────────────────────────────────────────────────────────────\n\n function layout(opts: LineChartOptions<D>, using = effects): LineLayout<D> {\n const encoding = lineEncoding(opts);\n const series = encoding.series.map((s) => s.series);\n checkNeeds(using, series, \"lineChart\");\n const next = layoutLines({ data: opts.data, encoding, width: opts.width ?? measuredWidth, height: opts.height, format: format(opts), measure, label: labeler(opts, true) });\n // A series named \"a@b\" and a key \"c\" make the same point key as \"a\" and \"b@c\".\n const keys = new Set(next.series);\n for (const row of next.rows) {\n for (const name of next.series) {\n const key = pointKey(name, row.key);\n if (keys.has(key)) throw new RangeError(`lineChart: two marks would have the key \"${key}\". Series and keys joined with \"@\" must be unique.`);\n keys.add(key);\n }\n }\n // focus(key) takes an x's key or a point's: a row keyed \"goals@2\" beside a row \"2\" would make the point ambiguous.\n for (const row of next.rows) {\n if (keys.has(row.key)) throw new RangeError(`lineChart: the key \"${row.key}\" would name both an x and a line or point. A row's key can't be a series, or a series and a key joined with \"@\".`);\n }\n return next;\n }\n\n /**\n * A line's end label for a value: `labels`' text, or by default the value in `format` with its\n * series' label (\"52 goals\"). Undefined with `labels: false`. A function that throws keeps the\n * default, and is reported once, unless `quiet` (the layout measuring).\n */\n function labeler(opts: LineChartOptions<D>, quiet = false): ((series: string, value: number) => string) | undefined {\n const { labels } = opts;\n if (labels === false) return undefined;\n const formatted = format(opts);\n return (series, value) => {\n const text = `${formatted(value)} ${seriesLabel(opts.seriesLabels, series)}`;\n if (typeof labels !== \"function\") return text;\n try {\n const own: unknown = labels(value, series, formatted);\n return own === undefined || own === null ? \"\" : String(own);\n } catch (error) {\n if (!quiet && !labelFailures.has(labels)) {\n labelFailures.add(labels);\n report(error);\n }\n return text;\n }\n };\n }\n\n /**\n * The end labels' wording for placeLines, each value rounded to its series' decimals in `given`:\n * `counting` while a change plays, or a layout's own at rest, which `counting` becomes when it\n * lands. So a line revealed part way between rows says the same at rest as in the frame before.\n * Undefined with `labels: false`.\n */\n function endLabels(given: Readonly<Record<string, number>>): EndLabels | undefined {\n const label = labeler(current);\n if (!label) return undefined;\n return { text: (series, value) => label(series, round(value, given[series] ?? decimals(value))), measure };\n }\n\n /** Each line and point as laid out in `next`, at the reveal, the lines with their end labels. */\n function placedFor(next: LineLayout<D>): { readonly lines: Map<string, PlacedLine<D>>; readonly points: Map<string, PlacedPoint<D>> } {\n const states = next.rows.map(restState);\n return {\n lines: new Map(placeLines(next.frame, states, next.series, drawnThrough(next), next.time, endLabels(next.decimals)).map((line) => [line.series, line])),\n points: new Map(states.flatMap((state) => placePoints(next.frame, state, next.series, next.time)).map((point) => [point.key, point]))\n };\n }\n\n /** The reveal in `next`: clamped to its rows' range. */\n function revealedIn(next: LineLayout<D>): number {\n const first = next.rows[0];\n const last = next.rows[next.rows.length - 1];\n return first && last ? Math.min(Math.max(through, first.x), last.x) : through;\n }\n\n /**\n * Where lines end: at the reveal, or with every row drawn when it's at the end of `next`'s rows,\n * so rows that fold away past the new last one stay drawn while they fold.\n */\n function drawnThrough(next: LineLayout<D>): number {\n const last = next.rows[next.rows.length - 1];\n return last && through < last.x ? revealedIn(next) : Infinity;\n }\n\n /** Live, and at or before the reveal. */\n const revealed = (record: RowRecord<D>): boolean => !record.leaving && record.row.x <= revealedIn(laidOut);\n\n // ── Records ────────────────────────────────────────────────────────────────\n\n /** A new row: at its place or, when it enters, waiting to grow out of its anchor. */\n function createRow(row: LineRow<D>, entering: boolean): RowRecord<D> {\n const column = svgElement(\"g\", { class: \"ec-column\", \"data-key\": row.key, role: \"img\" }, columnsLayer);\n const env = { clock, motion, onChange: changed };\n const record: RowRecord<D> = {\n key: row.key,\n row,\n column,\n hit: svgElement(\"rect\", { class: \"ec-hit\" }, column),\n x: animated(row.x, interpolateNumber, env),\n values: animated(row.levels, interpolateRecord, env),\n presence: animated(entering ? 0 : 1, interpolateNumber, env),\n anchor: undefined,\n points: [],\n leaving: false,\n shown: true,\n px: 0\n };\n byColumn.set(column, record);\n return record;\n }\n\n function createLine(series: string, placed: PlacedLine<D>, entering: boolean): LineRecord<D> {\n const group = svgElement(\"g\", { class: \"ec-line\", \"data-key\": series, \"data-series\": series }, linesLayer);\n const body = svgElement(\"g\", { class: \"ec-body\" }, group);\n const record: LineRecord<D> = {\n kind: \"line\",\n key: series,\n series,\n group,\n body,\n path: svgElement(\"path\", { class: \"ec-stroke\", \"stroke-width\": LINE_WIDTH }, body),\n end: svgElement(\"circle\", { class: \"ec-end\", r: DOT_RADIUS }, body),\n label: svgElement(\"text\", { class: \"ec-value ec-end-label\" }, group),\n drawnLabel: undefined,\n parts: [],\n handle: svgMarkHandle(() => record),\n target: placed,\n shown: placed,\n presence: animated(entering ? 0 : 1, interpolateNumber, { clock, motion, onChange: changed }),\n leave: undefined\n };\n return record;\n }\n\n function createPoint(row: RowRecord<D>, placed: PlacedPoint<D>): PointRecord<D> {\n const group = svgElement(\"g\", { class: \"ec-point\", \"data-key\": placed.key, \"data-series\": placed.series }, pointsLayer);\n const body = svgElement(\"g\", { class: \"ec-body\" }, group);\n const record: PointRecord<D> = {\n kind: \"point\",\n key: placed.key,\n series: placed.series,\n row,\n group,\n body,\n path: svgElement(\"path\", { class: \"ec-dot\" }, body),\n parts: [],\n handle: svgMarkHandle(() => record),\n target: placed,\n shown: placed,\n hidden: undefined,\n leave: undefined\n };\n return record;\n }\n\n /** On screen: live, or leaving and not yet gone. */\n const drawn = (record: MarkRecord<D>): boolean => findMark(record.key) === record;\n /** The row's live points, in series order. */\n const livePoints = (record: RowRecord<D>): PointRecord<D>[] => record.points.filter((point) => points.get(point.key) === point);\n const leavingLines = (): LineRecord<D>[] => [...leaving.values()].filter((record): record is LineRecord<D> => record.kind === \"line\");\n\n // ── Drawing ────────────────────────────────────────────────────────────────\n\n const currentFrame = (): LineFrame => ({ scale: scale.value, box: box.value });\n\n /**\n * Every row drawn, as it is now, in ascending x: a row growing in or folding away is part way\n * between its anchor and its own place. A row that has folded away, or leaves with nothing to fold\n * into, isn't drawn.\n */\n function currentRows(): { readonly record: RowRecord<D>; readonly state: RowState<D> }[] {\n const own = (record: RowRecord<D>): { x: number; values: Values } => ({ x: record.x.value, values: record.values.value });\n const states = new Map<RowRecord<D>, { x: number; values: Values }>();\n const visiting = new Set<RowRecord<D>>();\n const stateOf = (record: RowRecord<D>): { x: number; values: Values } => {\n const known = states.get(record);\n if (known) return known;\n const p = record.presence.value;\n let state = own(record);\n // An anchor chain can loop back (a row folding into one that grew out of it): the loop's start is drawn at its own place.\n if (record.anchor && p < 1 && !visiting.has(record)) {\n visiting.add(record);\n const from = stateOf(record.anchor);\n visiting.delete(record);\n state = { x: from.x + p * (state.x - from.x), values: interpolateRecord(from.values, state.values)(p) };\n }\n states.set(record, state);\n return state;\n };\n const drawnRows = [...rowOrder, ...[...leavingRows.values()].filter((record) => record.presence.value > 0 && record.anchor)];\n // A gap opens or closes as the change starts: the rows' missing values are where they're heading.\n return drawnRows\n .map((record) => {\n const { x, values } = stateOf(record);\n return { record, state: { key: record.key, datum: record.row.datum, x, values, missing: record.row.missing } };\n })\n .sort((a, b) => a.state.x - b.state.x);\n }\n\n /** Draws a frame of the change in flight. */\n function draw(): void {\n if (!dirty) return;\n dirty = false;\n const frame = currentFrame();\n const states = currentRows();\n paintFrame(frame);\n paintLines(frame, states.map((s) => s.state));\n for (const { record, state } of states) {\n const placed = new Map(placePoints(frame, state, record.points.map((point) => point.series), laidOut.time).map((point) => [point.key, point]));\n // A point whose value went missing stays where it was while it leaves.\n showAll(record.points.filter(drawn).flatMap((point) => (placed.has(point.key) ? [{ record: point, placed: placed.get(point.key)! }] : [])));\n }\n paintAlone(states.map((s) => s.state));\n paintColumns(frame, states);\n followHover();\n }\n\n /** Draws a new reveal: the lines and their labels end at it, and the x's past it are hidden. Nothing else moves. */\n function drawReveal(): void {\n const frame = currentFrame();\n const states = currentRows();\n paintLines(frame, states.map((s) => s.state));\n paintColumns(frame, states);\n followHover();\n }\n\n /** Draws exactly the layout once a change settles: the frames in between are computed, this is laid out. */\n function land(): void {\n for (const record of leavingRows.values()) {\n for (const value of [record.x, record.values, record.presence]) value.stop();\n record.column.remove();\n }\n leavingRows.clear();\n for (const record of rowOrder) {\n record.anchor = undefined;\n record.points = record.points.filter(drawn);\n }\n for (const [ticks, placedTicks] of [\n [yTicks, laidOut.yTicks],\n [xTicks, laidOut.xTicks]\n ] as const) {\n for (const tick of [...ticks.values()]) {\n if (tick.wanted) continue;\n tick.line?.remove();\n tick.label.remove();\n ticks.delete(tick.value);\n }\n for (const placed of placedTicks) {\n const tick = ticks.get(placed.value);\n if (!tick) continue;\n if (tick.line && \"line\" in placed) setAttributes(tick.line, { ...placed.line, opacity: undefined });\n placeText(tick.label, placed.label);\n tick.label.removeAttribute(\"opacity\");\n }\n }\n counting = laidOut.decimals;\n const { frame } = laidOut;\n setAttributes(svg, sizeAttributes(frame.box));\n drawnFrame = frame;\n // As laid out, keeping the objects enter and update reported while they're the same. Marks whose\n // data link to each other through `related` (the lines; a row's points) are kept or replaced together.\n const placed = placedFor(laidOut);\n const settle = <R extends MarkRecord<D>>(records: readonly R[], next: (record: R) => Placed<D> | undefined): void => {\n const pairs = records.flatMap((record) => {\n const to = next(record);\n return to ? [{ record, to }] : [];\n });\n const kept = pairs.every(({ record, to }) => sameGeometry(record.target.geometry, to.geometry) && sameData(record.target.data, to.data));\n if (!kept) for (const { record, to } of pairs) record.target = to;\n showAll(pairs.map(({ record }) => ({ record, placed: record.target })));\n };\n settle(lineOrder, (line) => placed.lines.get(line.series));\n paintLabels(new Map(lineOrder.flatMap((line) => (placed.lines.has(line.series) ? [[line, placed.lines.get(line.series)!] as const] : []))));\n const states = rowOrder.map((record) => ({ record, state: restState(record.row) }));\n for (const { record } of states) settle(livePoints(record), (point) => placed.points.get(point.key));\n paintAlone(states.map((s) => s.state));\n paintColumns(frame, states);\n followHover();\n dirty = false;\n }\n\n /** The <svg>'s size and the ticks, as the frame has them. */\n function paintFrame(frame: LineFrame): void {\n drawnFrame = frame;\n setAttributes(svg, sizeAttributes(frame.box));\n const formatted = format(current);\n for (const tick of yTicks.values()) {\n const placed = placeYTick(frame, tick.value, formatted(tick.value));\n const opacity = tick.opacity.value < 1 ? tick.opacity.value : undefined;\n setAttributes(tick.line!, { ...placed.line, opacity });\n placeText(tick.label, placed.label);\n setAttributes(tick.label, { opacity });\n }\n for (const tick of xTicks.values()) {\n placeText(tick.label, placeXTick(frame, tick.value, tick.text).label);\n setAttributes(tick.label, { opacity: tick.opacity.value < 1 ? tick.opacity.value : undefined });\n }\n }\n\n /** Draws the lines (live and leaving) through the rows as they are, up to the reveal, and their end labels. */\n function paintLines(frame: LineFrame, states: readonly RowState<D>[]): void {\n const drawnLines = [...lineOrder, ...leavingLines()];\n if (states.length === 0 || drawnLines.length === 0) return;\n const placed = placeLines(frame, states, drawnLines.map((line) => line.series), drawnThrough(laidOut), laidOut.time, endLabels(counting));\n showAll(drawnLines.map((line, i) => ({ record: line, placed: placed[i]! })));\n paintLabels(new Map(drawnLines.map((line, i) => [line, placed[i]!])));\n }\n\n /** Each line's end label as placeLines placed it, counting between values, kept 16 px apart; or none with `labels: false`. */\n function paintLabels(ends: ReadonlyMap<LineRecord<D>, PlacedLine<D>>): void {\n for (const [line, { label: text }] of ends) {\n if (text) placeText(line.label, text);\n line.drawnLabel = text && text.text !== \"\" ? text : undefined;\n setAttributes(line.label, { visibility: line.drawnLabel ? undefined : \"hidden\" });\n }\n }\n\n /**\n * Draws each mark as placed. Their data link to each other through `related` (the lines; a row's\n * points), so when any one's data changed, every one's runs hear about it with the new data: a\n * threshold on the goals line follows a change to xG alone.\n */\n function showAll(marks: readonly { readonly record: MarkRecord<D>; readonly placed: Placed<D> }[]): void {\n const related = marks.some(({ record, placed }) => !sameData(record.shown.data, placed.data));\n for (const { record, placed } of marks) {\n if (record.kind === \"line\") showLine(record, placed, related);\n else showPoint(record, placed, related);\n }\n }\n\n /** Draws the line as `placed`, with its end dot. Its runs hear about it when it moved or `related` data changed, so decorations follow. */\n function showLine(record: LineRecord<D>, placed: Placed<D>, related: boolean): void {\n const moved = related || geometryChanged(record.shown.geometry, placed.geometry);\n record.shown = placed;\n const { geometry } = placed;\n paint(record, seriesColors(colors.slot(record.series)), { visible: geometry.length >= VISIBLE, open: { width: geometry.thickness } });\n // A line with no value up to the reveal is empty: no end dot.\n setAttributes(record.end, { cx: geometry.end.x, cy: geometry.end.y, visibility: placed.data.samples.length === 0 ? \"hidden\" : undefined });\n const presence = record.presence.value;\n setAttributes(record.group, { opacity: presence < 1 ? presence : undefined });\n if (moved) runner.change(geometry, placed.data);\n }\n\n /** Draws the point as `placed`. Its runs hear about it when it moved or `related` data changed. */\n function showPoint(record: PointRecord<D>, placed: Placed<D>, related: boolean): void {\n const moved = related || geometryChanged(record.shown.geometry, placed.geometry);\n record.shown = placed;\n paint(record, seriesColors(colors.slot(record.series)), { visible: true });\n if (moved) runner.change(placed.geometry, placed.data);\n }\n\n /** Writes the mark's outline and colours, and applies its style again, when either changed. */\n function paint(record: MarkRecord<D>, markColors: SeriesColors, part: Pick<StyledPart, \"visible\" | \"open\">): void {\n const before = record.parts[0];\n const { d } = record.shown.geometry.outline;\n const recolored = before?.colors.color !== markColors.color;\n if (!recolored && before?.d === d && before.visible === part.visible && before.open?.width === part.open?.width) return;\n if (record.path.getAttribute(\"d\") !== d) record.path.setAttribute(\"d\", d);\n if (recolored) setStyles(record.group, markColorStyles(markColors));\n record.parts = [{ element: record.path, d, colors: markColors, ...part }];\n record.handle.repaint();\n // A new palette: overlays already drawn in \"mark\" follow.\n if (before && recolored) surface.recolor(record.key);\n }\n\n /** Whether a point showed at rest in the frame before: a chart with no gaps skips the points. */\n let anyAlone = false;\n\n /** A value with a gap on either side and no other value beside it has no stroke, so its point shows at rest. */\n function paintAlone(states: readonly RowState<D>[]): void {\n const lone = loneValues(states, laidOut.series);\n if (lone.size === 0 && !anyAlone) return;\n for (const point of points.values()) point.group.classList.toggle(\"ec-alone\", lone.has(point.key));\n anyAlone = lone.size > 0;\n }\n\n /**\n * Each revealed x's hit column, halfway to its neighbours, at the rows as they are; and the points\n * past the reveal hidden, their overlays too. A column that isn't live or revealed is hidden, so it\n * can't be hovered or focused.\n */\n function paintColumns(frame: LineFrame, states: readonly { readonly record: RowRecord<D>; readonly state: RowState<D> }[]): void {\n const { x } = positions(frame);\n const shown = states.filter(({ record }) => revealed(record));\n const columns = placeColumns(frame, shown.map(({ state }) => x(state.x)));\n shown.forEach(({ record, state }, i) => {\n setAttributes(record.hit, { ...columns[i]! });\n record.px = x(state.x);\n });\n const visible = new Set(shown.map(({ record }) => record));\n for (const record of [...rowOrder, ...leavingRows.values()]) {\n const show = visible.has(record);\n if (record.shown !== show) {\n record.shown = show;\n setAttributes(record.column, { visibility: show ? undefined : \"hidden\", \"aria-hidden\": record.leaving ? \"true\" : undefined });\n }\n const hidden = !revealed(record);\n for (const point of record.points) {\n if (point.hidden === hidden) continue;\n point.hidden = hidden;\n setAttributes(point.group, { visibility: hidden ? \"hidden\" : undefined });\n surface.hide(point.key, hidden);\n }\n }\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /**\n * The crosshair at the hovered x, and the tooltip above its highest point, as they are on screen.\n * An x with every value missing has no point: the tooltip sits at the crosshair's top.\n */\n function showHover(key: string): void {\n const record = rows.get(key);\n if (!record || !revealed(record)) return;\n const marks = livePoints(record);\n const x = marks[0]?.shown.geometry.center.x ?? record.px;\n setAttributes(crosshair, { ...placeCrosshair(drawnFrame, x), visibility: undefined });\n // Moved with each point's effects, as the focus ring is.\n const ys = marks.map((point) => {\n const { transform } = point.handle.style;\n const { center } = point.shown.geometry;\n return (transform ? matrix.apply(transform, center) : center).y;\n });\n const { row } = record;\n const at = ys.length > 0 ? { top: Math.min(...ys) - DOT_RADIUS, bottom: Math.max(...ys) + DOT_RADIUS } : { top: drawnFrame.box.top, bottom: drawnFrame.box.top };\n tooltip.showAt({ x, ...at }, row, () => summary(row, current));\n }\n\n function hideHover(): void {\n crosshair.setAttribute(\"visibility\", \"hidden\");\n tooltip.hide();\n }\n\n /** The focus at an x with every value missing, in `ring` while it shows there. */\n let ringLine: SVGLineElement | undefined;\n\n /**\n * A ring round each point at the focused x, as it is on screen, moved with its body when an effect\n * moves it. An x with every value missing has no point to ring: a line in the ring's colour shows\n * its focus where the crosshair is, and stays when Escape hides the crosshair.\n */\n function drawRing(key: string | undefined): void {\n const record = key === undefined ? undefined : rows.get(key);\n const live = record !== undefined && revealed(record);\n const marks = live ? livePoints(record) : [];\n if (live && marks.length === 0) {\n ringLine ??= svgElement(\"line\", { class: \"ec-focus-ring\", \"stroke-width\": RING }, ring);\n if (ring.childElementCount > 1 || ring.firstElementChild !== ringLine) ring.replaceChildren(ringLine);\n setAttributes(ringLine, placeCrosshair(drawnFrame, record.px));\n ring.removeAttribute(\"visibility\");\n return;\n }\n ringLine?.remove();\n while (ring.childElementCount > marks.length) ring.lastElementChild!.remove();\n marks.forEach((point, i) => {\n let group = ring.children[i] as SVGGElement | undefined;\n if (!group) {\n group = svgElement(\"g\", {}, ring);\n svgElement(\"path\", { class: \"ec-focus-ring\", \"stroke-width\": 2 * (RING_GAP + RING) }, group);\n svgElement(\"path\", { class: \"ec-focus-gap\", \"stroke-width\": 2 * RING_GAP }, group);\n }\n for (const path of Array.from(group.children)) path.setAttribute(\"d\", point.shown.geometry.outline.d);\n const { transform } = point.handle.style;\n setAttributes(group, { transform: transform && transformAttribute(transform) });\n });\n setAttributes(ring, { visibility: marks.length > 0 ? undefined : \"hidden\" });\n }\n\n /** The tooltip, crosshair and ring follow the hovered and focused x as it moves. */\n function followHover(): void {\n if (hover.key !== undefined) showHover(hover.key);\n if (hover.ringKey !== undefined) drawRing(hover.ringKey);\n }\n\n /** Where a mark is heading: what enter and update report as a change starts. */\n const input = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.target.geometry, data: record.target.data });\n /** The mark as it is on screen: what hover, leave and exit report, so mid-change they match what's under the pointer or on its way out. */\n const onScreen = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.shown.geometry, data: record.shown.data });\n\n /** The row a column belongs to; leaving and hidden rows don't count. */\n function liveRowOf(eventTarget: EventTarget | null): RowRecord<D> | undefined {\n const element = eventTarget as Element | null;\n const column = typeof element?.closest === \"function\" ? element.closest(\".ec-column\") : null;\n const record = column ? byColumn.get(column) : undefined;\n return record && rows.get(record.key) === record && revealed(record) ? record : undefined;\n }\n\n // Pointer, touch and keyboard focus share one hover: see shell/hover.ts. An x is the target, and\n // stands for each series' point there. Nothing dims: every series is read at once.\n const hover = chartHover<D>({\n svg,\n runner,\n events,\n dim: () => false,\n find(eventTarget) {\n const record = liveRowOf(eventTarget);\n return record && { key: record.key };\n },\n live(key) {\n const record = rows.get(key);\n return record !== undefined && revealed(record);\n },\n order: () => rowOrder.filter(revealed).map((record) => record.key),\n // On a time axis a page is a calendar month in its zone: the first x a month or more on, or back,\n // or the last one that way. On numbers it's the keyboard's own.\n page(key, by) {\n const from = rows.get(key);\n if (!laidOut.time || !from) return undefined;\n const stops = rowOrder.filter(revealed);\n const to = monthsOn(from.row.x, by, lineEncoding(current).timeZone);\n if (by > 0) return (stops.find((record) => record.row.x >= to) ?? stops[stops.length - 1])?.key;\n for (let i = stops.length - 1; i >= 0; i--) if (stops[i]!.row.x <= to) return stops[i]!.key;\n return stops[0]?.key;\n },\n marks: (key) => {\n const record = rows.get(key);\n return record ? livePoints(record).map((point) => point.key) : [];\n },\n element: (key) => (rows.get(key) ?? leavingRows.get(key))?.column,\n markElement: (key) => findMark(key)?.group,\n onScreen(key) {\n const record = findMark(key);\n return record && onScreen(record);\n },\n ring: drawRing,\n tooltip: { show: showHover, hide: hideHover, element: () => tooltip.element() }\n });\n\n // ── Changes ────────────────────────────────────────────────────────────────\n\n const syncLegend = (): void =>\n legend.update(\n laidOut.series.map((series) => ({ series, label: seriesLabel(current.seriesLabels, series) })),\n colors,\n current.legend\n );\n\n /** The data table for `opts`, laid out as `next`: a row per x, the x, each series and no total. Throws on a column it can't read. */\n function tableFor(opts: LineChartOptions<D>, next: LineLayout<D>): TableModel | undefined {\n return tableModel({\n option: opts.table,\n caption: opts.label,\n category: typeof opts.x === \"string\" ? opts.x : undefined,\n series: next.series,\n label: (series) => seriesLabel(opts.seriesLabels, series),\n rows: next.rows.map((row) => ({ key: row.key, category: row.label, datum: row.datum, index: row.index, values: present(row.values), missing: row.missing, total: total(row.values) })),\n format: format(opts),\n total: false\n });\n }\n\n /** The x's accessible name, from where it's heading, and its description (`markDescription`, or a tooltip function's text). */\n function labelColumn(record: RowRecord<D>): void {\n record.column.setAttribute(\"aria-label\", names.get(record.key)!);\n tooltip.describe(record.column, record.row);\n }\n\n /** Says what an update changed, in the live region: the chart's summary, or the page's text from it. */\n function announceChange(previous: LineChartOptions<D>, before: readonly string[]): void {\n const option = current.announce;\n if (!announcer || !option) return;\n const series = laidOut.series;\n const name = (record: RowRecord<D>): string => record.row.label;\n const { changed: values, added, removed } = rowChanges;\n const text = changeText({\n ...(current.label !== previous.label ? { label: current.label } : {}),\n // New series are said by their labels; new labels alone show the same view, so say nothing.\n ...(series.join(\"\\n\") !== before.join(\"\\n\") ? { series: series.map((s) => seriesLabel(current.seriesLabels, s)) } : {}),\n changed: values.map(name),\n added: added.map(name),\n removed: removed.map(name),\n count: rowOrder.length\n });\n if (typeof option !== \"function\") {\n announcer.say(text);\n return;\n }\n const key = (record: RowRecord<D>): string => record.key;\n try {\n const said = option({ text, changed: values.map(key), added: added.map(key), removed: removed.map(key) });\n if (said !== undefined && said !== null) announcer.say(String(said));\n } catch (error) {\n report(error);\n }\n }\n\n /**\n * Matches the layout's rows, series and points to records by key. New rows grow out of the nearest\n * row that stays (before them, or else after), and rows that go fold into theirs. A line gets\n * `update` when any of its values or rows changed, a point when its own value did; a new row's\n * points enter, a removed row's exit, and so do a series' line and points.\n */\n function arrange(next: LineLayout<D>): Diff<D> {\n laidOut = next;\n const placed = placedFor(next);\n const diff: Diff<D> = { entering: [], exiting: [], changed: [] };\n const keys = new Set(next.rows.map((row) => row.key));\n const series = next.rows.length > 0 ? next.series : [];\n const changes: RowChanges<D> = { changed: [], added: [], removed: [] };\n\n // What goes: lines first, then points by x.\n const before = rowOrder;\n const was = new Map(before.map((record) => [record, record.row]));\n const nextRows = new Map(next.rows.map((row) => [row.key, row]));\n const exitingLines = lineOrder.filter((line) => !series.includes(line.series));\n const exitingPoints: PointRecord<D>[] = [];\n for (const record of before) {\n const goes = !keys.has(record.key);\n const missing = nextRows.get(record.key)?.missing;\n if (goes) {\n rows.delete(record.key);\n record.leaving = true;\n leavingRows.set(record.key, record);\n changes.removed.push(record);\n }\n // A point goes with its row, its series, or its value.\n for (const point of livePoints(record)) if (goes || !series.includes(point.series) || missing?.has(point.series)) exitingPoints.push(point);\n }\n for (const line of exitingLines) lines.delete(line.series);\n for (const point of exitingPoints) points.delete(point.key);\n for (const record of [...exitingLines, ...exitingPoints]) leaving.start(record);\n diff.exiting.push(...exitingLines, ...exitingPoints);\n\n // The rows, matched by key.\n const stayed = new Set<RowRecord<D>>();\n let rowsMoved = changes.removed.length > 0;\n rowOrder = next.rows.map((row) => {\n let record = rows.get(row.key);\n if (record) {\n stayed.add(record);\n if (record.row.x !== row.x) rowsMoved = true;\n if (row.values.some((v, i) => record!.row.values[i]?.series !== v.series || record!.row.values[i]?.value !== v.value)) changes.changed.push(record);\n } else {\n // A row that comes back mid-fold keeps its record, and grows back from where it is.\n record = leavingRows.get(row.key) ?? createRow(row, true);\n leavingRows.delete(row.key);\n record.leaving = false;\n record.x.set(row.x);\n record.values.set(row.levels);\n rows.set(row.key, record);\n changes.added.push(record);\n rowsMoved = true;\n }\n record.row = row;\n return record;\n });\n rowOrder.forEach((record, i) => {\n if (!stayed.has(record)) record.anchor = nearest(rowOrder, i, stayed);\n else if (record.presence.value === 1) record.anchor = undefined;\n });\n for (const record of changes.removed) record.anchor ??= nearest(before, before.indexOf(record), stayed);\n\n // The lines: a line changed when its rows did, or any of its values.\n const previousLines = lineOrder;\n lineOrder = series.map((name) => {\n let line = lines.get(name);\n const target = placed.lines.get(name)!;\n if (line) {\n const values = [...stayed].some((record) => valueIn(was.get(record)!, name) !== valueIn(record.row, name));\n if (rowsMoved || values) diff.changed.push({ record: line, from: line.shown.geometry });\n } else {\n line = recall<LineRecord<D>>(name, \"line\") ?? createLine(name, target, true);\n lines.set(name, line);\n diff.entering.push(line);\n }\n line.target = target;\n return line;\n });\n\n // The points, by x: a point changed when its own value did. A missing value has none.\n for (const record of rowOrder) {\n const old = stayed.has(record) ? was.get(record) : undefined;\n const live = series.filter((name) => !record.row.missing.has(name)).map((name) => {\n const key = pointKey(name, record.key);\n const target = placed.points.get(key)!;\n let point = points.get(key);\n if (point) {\n if (old && valueIn(old, name) !== valueIn(record.row, name)) diff.changed.push({ record: point, from: point.shown.geometry });\n } else {\n point = recall<PointRecord<D>>(key, \"point\") ?? createPoint(record, target);\n point.row = record;\n points.set(key, point);\n diff.entering.push(point);\n }\n point.target = target;\n return point;\n });\n const kept = new Set(live);\n record.points = [...live, ...record.points.filter((point) => !kept.has(point) && drawn(point))];\n }\n\n for (const record of rowOrder) labelColumn(record);\n // DOM order follows visual order, for screen readers.\n orderElements(\n columnsLayer,\n before.filter((record) => !record.leaving).map((record) => record.column),\n rowOrder.map((record) => record.column),\n hover.active\n );\n orderElements(linesLayer, previousLines.map((line) => line.group), lineOrder.map((line) => line.group), () => null);\n rowChanges = changes;\n // New marks are drawn where they start, so hover and exit report them as they are on screen.\n dirty = true;\n draw();\n return diff;\n }\n\n /** Brings back the mark leaving under `key`, if there is one and it's the kind wanted: it keeps its element, and the runner cancels its exit. */\n function recall<R extends MarkRecord<D>>(key: string, kind: R[\"kind\"]): R | undefined {\n return leaving.get(key)?.kind === kind ? (leaving.recall(key) as R) : undefined;\n }\n\n /**\n * Sends every animated value toward `next`, and returns the animations started. Presentation stages\n * the change: values first (the rows' values and the value scale, ticks fading, series' lines fading\n * in or out), then positions (rows move along x, new rows grow out of their anchors and leaving rows\n * fold into theirs, the x range and the box follow). A stage with nothing to do is skipped. Analysis\n * runs it all as one stage, which its scaling keeps short. A jump (motion off, a resize) lands at once.\n */\n function retarget(next: LineLayout<D>, jump: boolean): Promise<TweenResult>[] {\n dirty = true;\n const { frame } = next;\n for (const [ticks, placed, lined] of [\n [yTicks, next.yTicks, true],\n [xTicks, next.xTicks, false]\n ] as const) {\n const wanted = new Set(placed.map((tick) => tick.value));\n for (const value of wanted) if (!ticks.has(value)) addTick(ticks, value, 0, lined);\n for (const tick of ticks.values()) tick.wanted = wanted.has(tick.value);\n }\n for (const tick of next.xTicks) xTicks.get(tick.value)!.text = tick.label.text;\n const goingLines = leavingLines();\n const folding = [...leavingRows.values()];\n\n const values =\n busy(scale, frame.scale, sameFields) ||\n [...yTicks.values()].some((tick) => busy(tick.opacity, tick.wanted ? 1 : 0, same)) ||\n rowOrder.some((record) => busy(record.values, record.row.levels, sameFields)) ||\n lineOrder.some((line) => busy(line.presence, 1, same)) ||\n goingLines.some((line) => busy(line.presence, 0, same));\n const positions =\n busy(box, frame.box, sameFields) ||\n [...xTicks.values()].some((tick) => busy(tick.opacity, tick.wanted ? 1 : 0, same)) ||\n rowOrder.some((record) => busy(record.x, record.row.x, same) || (record.anchor !== undefined && busy(record.presence, 1, same))) ||\n folding.some((record) => record.anchor !== undefined && busy(record.presence, 0, same));\n\n let first: AnimateOptions | undefined;\n let second: AnimateOptions | undefined;\n if (!jump && motion.staged) {\n first = { duration: STAGE };\n second = { duration: STAGE, delay: values ? STAGE : 0 };\n } else if (!jump) {\n first = second = { duration: (values && positions ? 2 : 1) * STAGE };\n }\n\n const running: Promise<TweenResult>[] = [];\n const move = <T>(value: Animated<T>, to: T, equal: (a: T, b: T) => boolean, timing: AnimateOptions | undefined): void => {\n if (!busy(value, to, equal)) return;\n if (timing) running.push(value.to(to, timing));\n else value.set(to);\n };\n move(scale, frame.scale, sameFields, first);\n move(box, frame.box, sameFields, second);\n for (const tick of yTicks.values()) move(tick.opacity, tick.wanted ? 1 : 0, same, first);\n for (const tick of xTicks.values()) move(tick.opacity, tick.wanted ? 1 : 0, same, second);\n for (const record of rowOrder) {\n move(record.values, record.row.levels, sameFields, first);\n move(record.x, record.row.x, same, second);\n // With nothing to grow out of, a row is in place at once.\n move(record.presence, 1, same, record.anchor ? second : undefined);\n }\n for (const record of folding) move(record.presence, 0, same, record.anchor ? second : undefined);\n for (const line of lineOrder) move(line.presence, 1, same, first);\n for (const line of goingLines) move(line.presence, 0, same, first);\n return running;\n }\n\n function addTick(ticks: Map<number, TickRecord>, value: number, opacity: number, lined: boolean, text = \"\"): void {\n const tick: TickRecord = {\n value,\n line: lined ? svgElement(\"line\", { class: value === 0 ? \"ec-baseline\" : \"ec-gridline\" }, grid) : undefined,\n label: svgElement(\"text\", { class: \"ec-tick\" }, axis),\n text,\n opacity: animated(opacity, interpolateNumber, { clock, motion, onChange: changed }),\n wanted: true\n };\n ticks.set(value, tick);\n // In value order, as the layout lists them.\n for (const t of [...ticks.values()].sort((a, b) => a.value - b.value)) {\n if (t.line) grid.appendChild(t.line);\n axis.appendChild(t.label);\n }\n }\n\n /**\n * Moves to `next`, animated or at once, drawing every frame. Resolves when the change settles.\n * One still in flight is taken over: its waiters wait for this one instead.\n */\n function transitionTo(next: LineLayout<D>, jump: boolean): Promise<void> {\n laidOut = next;\n counting = Object.fromEntries(next.series.map((name) => [name, Math.max(counting[name] ?? 0, next.decimals[name] ?? 0)]));\n return transitions.run(retarget(next, jump));\n }\n\n // ── Motion, size and fonts ─────────────────────────────────────────────────\n\n const unwatchHoverDuration = watchHoverDuration(svg, motion);\n\n /** Re-lays out without animating: a resize or fonts loading. A change in flight lands at once. Effects follow through change(). */\n function relayout(): void {\n if (destroyed) return;\n const next = layout(current);\n // The same rows as now: only the sizes changed.\n const byKey = new Map(next.rows.map((row) => [row.key, row]));\n for (const record of rowOrder) record.row = byKey.get(record.key) ?? record.row;\n const placed = placedFor(next);\n for (const line of lineOrder) line.target = placed.lines.get(line.series) ?? line.target;\n for (const point of points.values()) point.target = placed.points.get(point.key) ?? point.target;\n void transitionTo(next, true);\n }\n\n const unwatchWidth = watchWidth(container, clock, measuredWidth, (width) => {\n measuredWidth = width;\n // A fixed `width` ignores the container.\n if (current.width === undefined) relayout();\n });\n\n // Margins are measured; measure again once web fonts arrive.\n const unwatchFonts = watchFonts(doc, () => {\n measure.clear();\n relayout();\n });\n\n // ── First render ───────────────────────────────────────────────────────────\n\n describeChart(svg, current);\n syncLegend();\n table.render(firstTable);\n {\n const placed = placedFor(laidOut);\n for (const tick of laidOut.yTicks) addTick(yTicks, tick.value, 1, true);\n for (const tick of laidOut.xTicks) addTick(xTicks, tick.value, 1, false, tick.label.text);\n rowOrder = laidOut.rows.map((row) => {\n const record = createRow(row, false);\n rows.set(row.key, record);\n record.points = laidOut.series.filter((name) => !row.missing.has(name)).map((name) => {\n const point = createPoint(record, placed.points.get(pointKey(name, row.key))!);\n points.set(point.key, point);\n return point;\n });\n labelColumn(record);\n return record;\n });\n lineOrder = laidOut.rows.length > 0 ? laidOut.series.map((name) => createLine(name, placed.lines.get(name)!, false)) : [];\n for (const line of lineOrder) lines.set(line.series, line);\n land();\n }\n /** The live marks as they're heading, in the runner's order: the lines, then each x's points. */\n const liveMarks = (): MarkRecord<D>[] => [...lineOrder, ...rowOrder.flatMap(livePoints)];\n hover.sync();\n runner.enter(liveMarks().map(input));\n\n return linkable(hover.link, {\n element: svg,\n\n async update(next) {\n if (destroyed) return;\n if (next.motion !== undefined && next.motion !== current.motion) throw new TypeError(\"lineChart: `motion` can't be changed by update() yet.\");\n const merged: LineChartOptions<D> = { ...current, ...next };\n checkChartOptions(merged, \"lineChart\");\n // Throws on an effect it can't resolve, data it can't draw, a table column it can't read, or a\n // `format` that throws, before anything changes.\n const swapped = \"on\" in next ? nextEffects(effects, current.on, merged.on, env.presets) : effects;\n const nextLayout = layout(merged, swapped);\n const nextTable = tableFor(merged, nextLayout);\n const nextNames = namesFor(merged, nextLayout);\n if (\"colors\" in next) colors = toColorAssignment(merged.colors);\n const previous = current;\n const seriesBefore = laidOut.series;\n current = merged;\n names = nextNames;\n describeChart(svg, current);\n table.render(nextTable);\n // A region that appears with its first text is often missed: it announces from the next update.\n const announcing = announcer !== undefined;\n if (current.announce && !announcer) announcer = chartAnnouncer(svg);\n else if (!current.announce && announcer) {\n announcer.destroy();\n announcer = undefined;\n }\n transitions.supersede();\n const swapping = swapped !== effects;\n effects = swapped;\n\n // The runner hears exit / update / enter now, then change() on every frame, then settle(). New\n // effects start where the old ones were, on the marks staying, as this update leaves them; a\n // held hover replays with them once the change settles.\n const leaves = playUpdate(\n {\n runner,\n events,\n hover,\n leaving,\n input,\n onScreen,\n data: \"data\" in next,\n ...(swapping\n ? {\n swap: (diff: Diff<D>) => {\n const entering = new Set(diff.entering);\n runner.swap(swapped, liveMarks().filter((record) => !entering.has(record)).map(input));\n }\n }\n : {})\n },\n () => arrange(nextLayout),\n () => {\n if (announcing) announceChange(previous, seriesBefore);\n }\n );\n syncLegend();\n const settled = transitionTo(nextLayout, motion.mode === \"off\");\n await transitions.wait(settled, leaves);\n },\n\n reveal(x) {\n if (destroyed) return;\n // A Date is its time in ms, which is how a time axis has its x's.\n if (x instanceof Date && Number.isNaN(x.getTime())) throw new RangeError(\"lineChart: reveal(x) needs a valid Date, got an invalid Date.\");\n const at: unknown = x instanceof Date ? x.getTime() : x;\n if (typeof at !== \"number\" || Number.isNaN(at)) throw new RangeError(`lineChart: reveal(x) needs a number, got ${typeof at === \"string\" ? JSON.stringify(at) : String(at)}.`);\n const before = revealedIn(laidOut);\n through = at;\n if (revealedIn(laidOut) === before) return;\n // A view, not a data change: no events. The lines (and their decorations, through change())\n // end at x, and the x's past it are hidden.\n drawReveal();\n hover.dropGone();\n hover.sync();\n },\n\n on: events.on,\n\n marks: () => [...lineOrder.map((line) => line.shown.geometry), ...rowOrder.filter(revealed).flatMap((record) => livePoints(record).map((point) => point.shown.geometry))],\n\n focus(key) {\n if (destroyed) return;\n // An x takes focus, for its own key or one of its points'.\n const record = rows.get(key) ?? points.get(key)?.row;\n if (record) hover.focus(record.key);\n },\n\n leave() {\n if (!destroyed) hover.leave();\n },\n\n // A line's end label is its value; points have none.\n labels: () => lineOrder.flatMap((line) => chartLabel(line.key, \"value\", line.drawnLabel, line.label)),\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n // Ends the change in flight, and resolves the latest update()'s promise.\n transitions.destroy();\n hover.destroy();\n runner.destroy();\n tooltip.destroy();\n legend.destroy();\n table.destroy();\n announcer?.destroy();\n unwatchHoverDuration();\n unwatchWidth();\n unwatchFonts();\n for (const record of [...rowOrder, ...leavingRows.values()]) for (const value of [record.x, record.values, record.presence]) value.stop();\n for (const line of [...lineOrder, ...leavingLines()]) line.presence.stop();\n for (const record of leaving.values()) record.leave?.resolve();\n scale.stop();\n box.stop();\n for (const tick of [...yTicks.values(), ...xTicks.values()]) tick.opacity.stop();\n events.clear();\n rows.clear();\n leavingRows.clear();\n lines.clear();\n points.clear();\n leaving.clear();\n rowOrder = [];\n lineOrder = [];\n svg.remove();\n }\n });\n}\n\n/** A row at rest, as laid out: its values, and its levels where it has none. */\nfunction restState<D>(row: LineRow<D>): RowState<D> {\n return { key: row.key, datum: row.datum, x: row.x, values: row.levels, missing: row.missing };\n}\n\n/** The values a row has, leaving out the missing ones. */\nfunction present(values: readonly LineValue[]): { series: string; value: number }[] {\n return values.flatMap((v) => (v.value === undefined ? [] : [{ series: v.series, value: v.value }]));\n}\n\nfunction valueIn<D>(row: LineRow<D>, series: string): number | undefined {\n return row.values.find((v) => v.series === series)?.value;\n}\n\nfunction total(values: readonly LineValue[]): number {\n return values.reduce((sum, v) => sum + (v.value ?? 0), 0);\n}\n\n/** The nearest record to index `i` in `order` that's in `among`: before it first, then after it. */\nfunction nearest<R>(order: readonly R[], i: number, among: ReadonlySet<R>): R | undefined {\n for (let j = i - 1; j >= 0; j--) if (among.has(order[j]!)) return order[j];\n for (let j = i + 1; j < order.length; j++) if (among.has(order[j]!)) return order[j];\n return undefined;\n}\n\n/** The same walk and outline. */\nfunction sameGeometry(a: MarkGeometry, b: MarkGeometry): boolean {\n return a.key === b.key && !geometryChanged(a, b) && a.start.x === b.start.x && a.start.y === b.start.y && a.end.x === b.end.x && a.end.y === b.end.y;\n}\n\n/** The same row and samples. */\nfunction sameData<D>(a: MarkData<D>, b: MarkData<D>): boolean {\n if (a.datum !== b.datum || a.samples.length !== b.samples.length) return false;\n return a.samples.every((s, i) => {\n const o = b.samples[i]!;\n return s.t === o.t && s.value === o.value && sameAt(s.at, o.at) && s.gapBefore === o.gapBefore;\n });\n}\n\n/** The same x: Dates by their time, since each placing makes its own. */\nfunction sameAt(a: Sample[\"at\"], b: Sample[\"at\"]): boolean {\n return a === b || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime());\n}\n\n/** Each series' value with its label, leaving out the missing ones: what `markLabel` is given. Copies, so a page can't change the layout's. */\nfunction labelled<D>(values: readonly LineValue[], options: LineChartOptions<D>): { series: string; label: string; value: number }[] {\n return present(values).map((v) => ({ series: v.series, label: seriesLabel(options.seriesLabels, v.series), value: v.value }));\n}\n\n/** Each series at the row, as the x's name and the tooltip say it: its value with its label (\"15 goals\"), or \"xg missing\". */\nfunction said<D>(values: readonly LineValue[], options: LineChartOptions<D>): string[] {\n const formatted = format(options);\n return values.map((v) => {\n const label = seriesLabel(options.seriesLabels, v.series);\n return v.value === undefined ? `${label} missing` : `${formatted(v.value)} ${label}`;\n });\n}\n\n/** The default tooltip: the x, then each series' value or that it's missing. */\nfunction summary<D>(row: LineRow<D>, options: LineChartOptions<D>): TooltipContent {\n if (row.missing.size === 0) return summaryContent(row.label, labelled(row.values, options), format(options), { total: false });\n return { title: row.label, lines: [said(row.values, options).join(\" · \")] };\n}\n\n/**\n * Every x's name in `layout`, by key, worked out before anything changes: \"12: 15 goals, 14.2 xg\",\n * each series' value with its label, or the page's wording from `markLabel`. An empty name, or a throw\n * (reported), keeps the default, so a focus stop is never left unnamed.\n */\nfunction namesFor<D>(options: LineChartOptions<D>, layout: LineLayout<D>): ReadonlyMap<string, string> {\n const formatted = format(options);\n return new Map(\n layout.rows.map((row) => {\n const values = labelled(row.values, options);\n const text = `${row.label}: ${said(row.values, options).join(\", \")}`;\n if (!options.markLabel) return [row.key, text];\n try {\n const named: unknown = options.markLabel(row.datum, { key: row.key, category: row.label, values, total: total(row.values), format: formatted, text });\n if (named !== undefined && named !== null && String(named).trim() !== \"\") return [row.key, String(named)];\n } catch (error) {\n report(error);\n }\n return [row.key, text];\n })\n );\n}\n","// Whether a mark goes round a centre, read from its geometry alone: a slice does, a bar doesn't. The\n// adapter orders a ring of marks with it, and morph's \"drop\" turns its pairing by it.\n\nimport type { MarkGeometry, Point } from \"../contracts/geometry\";\n\n/** px: the same distance from the pivot give or take this much, and further from it than this. */\nconst ROUND = 0.5;\n\n/**\n * Whether the mark's walk goes round its pivot: its start, centre and end all the same distance from\n * the pivot, give or take 0.5 px, and more than 0.5 px away. An arc's pivot is the donut's centre; a\n * line's, a bar's and a point's is on its own walk, so lines that start at one point aren't a ring.\n */\nexport function goesRound(mark: Pick<MarkGeometry, \"start\" | \"center\" | \"end\" | \"pivot\">): boolean {\n const radius = distance(mark.start, mark.pivot);\n return radius > ROUND && Math.abs(distance(mark.center, mark.pivot) - radius) <= ROUND && Math.abs(distance(mark.end, mark.pivot) - radius) <= ROUND;\n}\n\nconst distance = (a: Point, b: Point): number => Math.hypot(b.x - a.x, b.y - a.y);\n","// Bars from rectangles someone else drew: which edge each grows from, and the segments of a stack,\n// described with describe.bar. Pure: the rectangles are already in the marks' common coordinates.\n\nimport type { Baseline, MarkGeometry, Rect } from \"../../core\";\nimport { describeBar } from \"../../core/geometry/describe/bar\";\n\n/** One `<rect>` of a mark, in the marks' common coordinates. */\nexport interface RectPart {\n readonly box: Rect;\n /** The segment's series, from the `segment` option. */\n readonly series: string | undefined;\n /** Corner radius (the rect's rx), used for the tip. */\n readonly radius: number;\n}\n\n/** Edges this close (px) count as the same line. */\nconst SAME = 0.5;\n\nconst BASELINES: readonly string[] = [\"left\", \"right\", \"top\", \"bottom\"];\n\nexport function isBaseline(value: unknown): value is Baseline {\n return typeof value === \"string\" && BASELINES.includes(value);\n}\n\n/**\n * Each mark's baseline. \"auto\" finds a line every mark has an edge on: a mark whose near edge\n * (left, or bottom for columns) is on it grows away from it, and one whose far edge is grows the\n * other way, like a negative bar. When both directions fit (one mark, or marks of one size), marks\n * spread down the page are bars and marks spread across are columns.\n */\nexport function baselines(boxes: readonly Rect[], option: Baseline | \"auto\"): Baseline[] {\n if (option !== \"auto\") return boxes.map(() => option);\n if (boxes.length === 0) return [];\n const horizontal = commonLine(boxes, (b) => b.x, (b) => b.x + b.width, \"left\", \"right\");\n const vertical = commonLine(boxes, (b) => b.y + b.height, (b) => b.y, \"bottom\", \"top\");\n if (horizontal && vertical) return rows(boxes) ? horizontal : vertical;\n const found = horizontal ?? vertical;\n if (!found) {\n throw new RangeError('expressive: baseline \"auto\" found no edge that every mark grows from. Pass baseline: \"left\", \"right\", \"top\" or \"bottom\".');\n }\n return found;\n}\n\n/**\n * The mark's geometry from its rects, ordered from the baseline. Each segment ends where its rect\n * ends; a gap the host left between segments becomes describe.bar's `gap`, which comes out of the\n * start of the later segment.\n */\nexport function describeRects(key: string, parts: readonly RectPart[], baseline: Baseline): { geometry: MarkGeometry; order: number[] } {\n const box = union(parts.map((part) => part.box));\n const span = spanFrom(box, baseline);\n const order = parts\n .map((part, index) => ({ index, ...span(part.box) }))\n .sort((a, b) => a.near - b.near || a.far - b.far || a.index - b.index);\n\n let reached = 0;\n let gap = Infinity;\n const segments = order.map(({ index, near, far }) => {\n // Only between parts you can see: a zero-length segment sits right where the one before ends.\n if (reached > 0 && far > near) gap = Math.min(gap, near - reached);\n const size = Math.max(0, far - reached);\n reached = Math.max(reached, far);\n return { series: parts[index]!.series, size };\n });\n\n const tip = parts[order[order.length - 1]!.index]!;\n const single = parts.length === 1 ? parts[0]!.series : undefined;\n const geometry = describeBar({\n key,\n ...(single === undefined ? {} : { series: single }),\n ...box,\n baseline,\n radius: tip.radius,\n gap: Number.isFinite(gap) ? Math.max(0, round(gap)) : 0,\n // Without `segment` there's one part and no series to name: describe.bar's default segment.\n ...(segments.every((s) => s.series !== undefined) ? { segments: segments.map((s) => ({ series: s.series!, size: round(s.size) })) } : {})\n });\n return { geometry, order: order.map((o) => o.index) };\n}\n\n/** Indices in visual order: bars top to bottom, columns left to right. */\nexport function visualOrder(boxes: readonly Rect[], baseline: readonly Baseline[]): number[] {\n const horizontal = baseline[0] === \"left\" || baseline[0] === \"right\";\n const along = (b: Rect): number => (horizontal ? b.y : b.x);\n const across = (b: Rect): number => (horizontal ? b.x : b.y);\n return boxes.map((_, index) => index).sort((a, b) => along(boxes[a]!) - along(boxes[b]!) || across(boxes[a]!) - across(boxes[b]!) || a - b);\n}\n\nexport function union(boxes: readonly Rect[]): Rect {\n const x = Math.min(...boxes.map((b) => b.x));\n const y = Math.min(...boxes.map((b) => b.y));\n return { x, y, width: round(Math.max(...boxes.map((b) => b.x + b.width)) - x), height: round(Math.max(...boxes.map((b) => b.y + b.height)) - y) };\n}\n\nfunction commonLine(\n boxes: readonly Rect[],\n nearEdge: (box: Rect) => number,\n farEdge: (box: Rect) => number,\n near: Baseline,\n far: Baseline\n): Baseline[] | undefined {\n const first = boxes[0];\n if (!first) return [];\n for (const line of [nearEdge(first), farEdge(first)]) {\n const found: Baseline[] = [];\n for (const box of boxes) {\n if (Math.abs(nearEdge(box) - line) < SAME) found.push(near);\n else if (Math.abs(farEdge(box) - line) < SAME) found.push(far);\n else break;\n }\n if (found.length === boxes.length) return found;\n }\n return undefined;\n}\n\n/** True when the marks look like rows (bars), false for columns. */\nfunction rows(boxes: readonly Rect[]): boolean {\n const spread = (values: number[]): number => Math.max(...values) - Math.min(...values);\n const down = spread(boxes.map((b) => b.y + b.height / 2));\n const across = spread(boxes.map((b) => b.x + b.width / 2));\n if (down !== across) return down > across;\n // One mark, or marks on top of each other: the longer side is the bar's length.\n return boxes[0]!.width >= boxes[0]!.height;\n}\n\n/** A part's start and end along the walk, in px from the mark's baseline. */\nfunction spanFrom(mark: Rect, baseline: Baseline): (box: Rect) => { near: number; far: number } {\n switch (baseline) {\n case \"left\":\n return (b) => ({ near: b.x - mark.x, far: b.x + b.width - mark.x });\n case \"right\":\n return (b) => ({ near: mark.x + mark.width - (b.x + b.width), far: mark.x + mark.width - b.x });\n case \"top\":\n return (b) => ({ near: b.y - mark.y, far: b.y + b.height - mark.y });\n case \"bottom\":\n return (b) => ({ near: mark.y + mark.height - (b.y + b.height), far: mark.y + mark.height - b.y });\n }\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n","// Every change the adapter makes to the host's elements, with what was there before, so it can all\n// be undone: attributes (tabindex, ARIA), inline style properties and classes. Touching el.style or\n// el.classList rewrites the whole attribute, so once the last of our changes is undone, an attribute\n// that reads the same as before gets its exact text back (or goes away, if it wasn't there).\n//\n// A host that reuses its elements may rewrite an attribute we also write (its own aria-label, as the\n// data changes). Its latest value is the one to put back, so an attribute that no longer reads as we\n// left it takes the host's value as its new original, and undoing our change leaves the host's alone.\n\n/** An attribute we changed. null: absent. */\ninterface SavedAttribute {\n /** What to put back: the host's value from before our first change, or the one it wrote since. */\n original: string | null;\n /** What we last left it as. */\n written: string | null;\n}\n\ninterface Saved {\n readonly attributes: Map<string, SavedAttribute>;\n /** Inline style properties we changed: their value and priority before. */\n readonly styles: Map<string, { readonly value: string; readonly priority: string }>;\n /** Classes we added (ones the element already had are left alone). */\n readonly classes: Set<string>;\n /** The style and class attributes' text from before our first change to each. */\n readonly before: { style?: { readonly text: string | null; readonly css: string }; class?: string | null };\n}\n\nexport interface HostEdits {\n /** Sets an attribute; null puts back the host's value, unless the host has written its own since. */\n attribute(element: Element, name: string, value: string | null): void;\n /** Removes an attribute; `attribute(element, name, null)` puts it back. */\n remove(element: Element, name: string): void;\n /** Sets an inline style property; undefined puts back what was there before. */\n style(element: Element, property: string, value: string | undefined): void;\n /** Whether we're overriding the property now. */\n styled(element: Element, property: string): boolean;\n /** Adds (true) or removes (false) a class we add; classes the element had stay. */\n toggleClass(element: Element, name: string, on: boolean): void;\n /** Undoes every change to the element. */\n restore(element: Element): void;\n /** Undoes every change to every element. */\n restoreAll(): void;\n /** Elements with changes. */\n elements(): Element[];\n}\n\nexport function hostEdits(): HostEdits {\n const saved = new Map<Element, Saved>();\n\n const entry = (element: Element): Saved => {\n let found = saved.get(element);\n if (!found) {\n found = { attributes: new Map(), styles: new Map(), classes: new Set(), before: {} };\n saved.set(element, found);\n }\n return found;\n };\n\n const styleOf = (element: Element): CSSStyleDeclaration | undefined => (element as SVGElement).style;\n\n const put = (element: Element, name: string, text: string | null): void => {\n if (text === null) element.removeAttribute(name);\n else if (element.getAttribute(name) !== text) element.setAttribute(name, text);\n };\n\n /** After the last of our style changes is undone: the exact text, if nothing else changed meanwhile. */\n const settleStyle = (element: Element, found: Saved): void => {\n const before = found.before.style;\n if (found.styles.size > 0 || !before) return;\n found.before.style = undefined;\n if (styleOf(element)?.cssText === before.css) put(element, \"style\", before.text);\n };\n\n const settleClass = (element: Element, found: Saved): void => {\n const before = found.before.class;\n if (found.classes.size > 0 || before === undefined) return;\n found.before.class = undefined;\n const tokens = (text: string | null | undefined): string => [...new Set((text ?? \"\").split(/\\s+/).filter(Boolean))].sort().join(\" \");\n if (tokens(element.getAttribute(\"class\")) === tokens(before)) put(element, \"class\", before);\n };\n\n /** Sets (text) or removes (null) an attribute, keeping the host's value to put back. */\n function write(element: Element, name: string, text: string | null): void {\n const now = element.getAttribute(name);\n const kept = entry(element).attributes;\n const found = kept.get(name);\n if (!found) kept.set(name, { original: now, written: text });\n else {\n // The host changed it since we last wrote it: that's its value now.\n if (now !== found.written) found.original = now;\n found.written = text;\n }\n put(element, name, text);\n }\n\n function attribute(element: Element, name: string, value: string | null): void {\n if (value !== null) {\n write(element, name, value);\n return;\n }\n const kept = saved.get(element)?.attributes;\n const found = kept?.get(name);\n if (!kept || !found) return;\n // Unless the host has written its own since, which stays.\n if (element.getAttribute(name) === found.written) put(element, name, found.original);\n kept.delete(name);\n }\n\n function style(element: Element, property: string, value: string | undefined): void {\n const declaration = styleOf(element);\n if (!declaration) return;\n const found = entry(element);\n const original = found.styles.get(property);\n if (value === undefined) {\n if (!original) return;\n if (original.value === \"\") declaration.removeProperty(property);\n else declaration.setProperty(property, original.value, original.priority);\n found.styles.delete(property);\n settleStyle(element, found);\n return;\n }\n if (!original) {\n if (found.styles.size === 0) found.before.style = { text: element.getAttribute(\"style\"), css: declaration.cssText };\n found.styles.set(property, { value: declaration.getPropertyValue(property), priority: declaration.getPropertyPriority(property) });\n }\n if (declaration.getPropertyValue(property) !== value) declaration.setProperty(property, value);\n }\n\n function toggleClass(element: Element, name: string, on: boolean): void {\n const list = element.classList;\n if (on) {\n if (list.contains(name)) return;\n const found = entry(element);\n if (found.classes.size === 0) found.before.class = element.getAttribute(\"class\");\n found.classes.add(name);\n list.add(name);\n return;\n }\n const found = saved.get(element);\n if (!found?.classes.delete(name)) return;\n list.remove(name);\n settleClass(element, found);\n }\n\n function restore(element: Element): void {\n const found = saved.get(element);\n if (!found) return;\n for (const property of [...found.styles.keys()]) style(element, property, undefined);\n for (const name of [...found.classes]) toggleClass(element, name, false);\n for (const name of [...found.attributes.keys()]) attribute(element, name, null);\n saved.delete(element);\n }\n\n return {\n attribute,\n remove: (element, name) => write(element, name, null),\n style,\n styled: (element, property) => saved.get(element)?.styles.has(property) ?? false,\n toggleClass,\n restore,\n restoreAll() {\n for (const element of [...saved.keys()]) restore(element);\n },\n elements: () => [...saved.keys()]\n };\n}\n","// Coordinates in someone else's SVG. Matrices between elements' user spaces come from the browser's\n// CTMs where there's layout, and from the transform attributes where there isn't (jsdom, a chart\n// that isn't rendered yet).\n\nimport type { Matrix, Point, Rect } from \"../../core\";\nimport { matrix } from \"../../core\";\nimport { invert, parseTransform } from \"../../core/geometry\";\n\n/** An element's screen CTM as a matrix, or undefined where there's no layout. */\nexport type ScreenMatrix = (element: Element) => Matrix | undefined;\n\n/**\n * Screen CTMs remembered per element, for one read while nothing changes: every mark of a read asks\n * for the common ancestor's and its parent's, which most marks share.\n */\nexport function screenMatrices(): ScreenMatrix {\n const known = new Map<Element, Matrix | undefined>();\n return (element) => {\n if (!known.has(element)) known.set(element, screenMatrix(element));\n return known.get(element);\n };\n}\n\n/**\n * Maps points in `inner`'s user space (after its own transform) into `outer`'s. Both are inside\n * `root`. Without CTMs, nested `<svg>` viewports and CSS transforms aren't seen.\n */\nexport function between(outer: Element, inner: Element, root: Element, screen: ScreenMatrix = screenMatrix): Matrix {\n const a = screen(outer);\n const b = a && screen(inner);\n if (a && b) return matrix.multiply(invert(a), b);\n return matrix.multiply(invert(fromRoot(outer, root)), fromRoot(inner, root));\n}\n\n/** The element's own transform attribute. */\nexport function ownTransform(element: Element): Matrix {\n return parseTransform(element.getAttribute(\"transform\") ?? \"\");\n}\n\n/**\n * Whether the transform keeps rectangles upright: scales, flips and quarter turns, with any\n * translation. Only then is the box a rect covers exactly the rect.\n */\nexport function axisAligned(m: Matrix): boolean {\n const [a, b, c, d] = m;\n const tiny = 1e-9 * Math.max(Math.abs(a), Math.abs(b), Math.abs(c), Math.abs(d));\n return (Math.abs(b) <= tiny && Math.abs(c) <= tiny) || (Math.abs(a) <= tiny && Math.abs(d) <= tiny);\n}\n\n/**\n * Whether the transform keeps circles round: an even scale, turns and flips, with any translation.\n * Its columns are the same length and at right angles, to within a ten-thousandth of their length,\n * so the rounding in a browser's CTMs doesn't make a circle an ellipse.\n */\nexport function keepsCircles(m: Matrix): boolean {\n const [a, b, c, d] = m;\n const u = a * a + b * b;\n const v = c * c + d * d;\n const tiny = 1e-4 * Math.max(u, v);\n return Math.abs(u - v) <= tiny && Math.abs(a * c + b * d) <= tiny;\n}\n\n/** How much the transform scales lengths: exactly for an even scale, and on average for an uneven one. */\nexport function scaleOf(m: Matrix): number {\n return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n}\n\n/** The box a transformed rectangle covers, rounded to 0.001 px like path data. */\nexport function boxIn(m: Matrix, rect: Rect): Rect {\n const corners: Point[] = [\n { x: rect.x, y: rect.y },\n { x: rect.x + rect.width, y: rect.y },\n { x: rect.x, y: rect.y + rect.height },\n { x: rect.x + rect.width, y: rect.y + rect.height }\n ].map((corner) => matrix.apply(m, corner));\n const xs = corners.map((p) => p.x);\n const ys = corners.map((p) => p.y);\n const x = round(Math.min(...xs));\n const y = round(Math.min(...ys));\n return { x, y, width: round(round(Math.max(...xs)) - x), height: round(round(Math.max(...ys)) - y) };\n}\n\n/** A `<rect>`'s rectangle in its own user space. A negative size draws nothing, so it counts as 0. */\nexport function rectOf(element: Element): Rect {\n const attribute = attributesOf(element);\n const read = (name: \"x\" | \"y\" | \"width\" | \"height\"): number => {\n const value = Number.parseFloat(attribute(name) ?? \"\");\n return Number.isFinite(value) ? value : 0;\n };\n return { x: read(\"x\"), y: read(\"y\"), width: Math.max(0, read(\"width\")), height: Math.max(0, read(\"height\")) };\n}\n\n/**\n * Reads an element's attributes for its geometry. A length is as the browser resolves it\n * (percentages, units), and anything else, or a length where there's no layout (jsdom), as written.\n */\nexport function attributesOf(element: Element): (name: string) => string | null {\n return (name) => {\n const animated = (element as unknown as Record<string, { baseVal?: { value?: unknown } } | undefined>)[name];\n return typeof animated?.baseVal?.value === \"number\" ? String(animated.baseVal.value) : element.getAttribute(name);\n };\n}\n\nfunction screenMatrix(element: Element): Matrix | undefined {\n const ctm = typeof (element as SVGGraphicsElement).getScreenCTM === \"function\" ? (element as SVGGraphicsElement).getScreenCTM() : null;\n return ctm ? [ctm.a, ctm.b, ctm.c, ctm.d, ctm.e, ctm.f] : undefined;\n}\n\n/** The element's transform attributes, its own included, down from `root` (whose own is left out). */\nfunction fromRoot(element: Element, root: Element): Matrix {\n let m: Matrix = [1, 0, 0, 1, 0, 0];\n for (let node: Element | null = element; node && node !== root; node = node.parentElement) m = matrix.multiply(ownTransform(node), m);\n return m;\n}\n\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n","// The drawing API's MarkHandle on elements someone else drew. Every change goes through HostEdits, so\n// a reset (or destroy) puts back exactly what the host had, and the host's own attributes are never\n// written: the transform is an inline style composed with the element's own transform attribute.\n\nimport type { MarkHandle, MarkStyle, Matrix } from \"../../core\";\nimport { matrix } from \"../../core\";\nimport { mergeFields } from \"../../core/merge\";\nimport { maskedHalo, type HaloPart } from \"../render/outside\";\nimport { cssColor, type SeriesColors } from \"../render/theme\";\nimport type { HostEdits } from \"./edits\";\nimport { ownTransform } from \"./space\";\n\n/** The host's colours for an element, and the property they're from, which emphasis and the hover colour write. */\nexport interface HostColors extends SeriesColors {\n /** \"stroke\" when the fill is none, as on a line. */\n readonly paint: \"fill\" | \"stroke\";\n}\n\n/** One element of a mark, as the style handle needs it. */\nexport interface HostPart {\n readonly element: Element;\n /** From the element's parent's user space into the marks' common ancestor's, and back. */\n readonly parent: Matrix;\n readonly parentInverse: Matrix | undefined;\n /** The host's colour for the element, which `emphasis`, the hover colour and the \"mark\" token start from. */\n readonly colors: HostColors | undefined;\n /**\n * The part's outline in the common ancestor's space, for the halo, with an open outline's stroke\n * width; undefined when it's too short to see.\n */\n readonly outline: Omit<HaloPart, \"color\"> | undefined;\n}\n\nexport interface HostMarkHandle extends MarkHandle {\n readonly style: MarkStyle;\n /** Applies the current style again, after a refresh (new elements or outlines). */\n repaint(): void;\n /** Gives the mark its strong colour while it's hovered, under `dim`, as our charts do. */\n hot(on: boolean): void;\n}\n\n/**\n * - `transform` is in the common ancestor's space. Each element gets an inline CSS transform that\n * moves it by that much, composed with its own transform attribute, with origin 0 0 in its user space.\n * - `opacity` and `emphasis` are inline styles; emphasis mixes the host's colour (its fill, or its\n * stroke on a line) toward its strong colour. A hot mark takes the strong one, unless an effect sets emphasis.\n * - `halo` strokes each visible part's outline in the overlay, masked to outside the mark, so it\n * shows only where it would behind the mark.\n */\nexport function hostMarkHandle(parts: () => readonly HostPart[], edits: HostEdits, halos: () => SVGGElement | undefined): HostMarkHandle {\n let style: MarkStyle = {};\n let hot = false;\n const halo = maskedHalo();\n\n const repaint = (): void => {\n const { transform, opacity, emphasis } = style;\n for (const part of parts()) {\n const { element, colors } = part;\n const moved = transform && part.parentInverse ? matrix.multiply(part.parentInverse, transform, part.parent, ownTransform(element)) : undefined;\n edits.style(element, \"transform\", moved && cssMatrix(moved));\n edits.style(element, \"transform-origin\", moved && \"0 0\");\n edits.style(element, \"transform-box\", moved && \"view-box\");\n edits.style(element, \"opacity\", opacity === undefined ? undefined : String(opacity));\n const shade = !colors ? undefined : emphasis !== undefined ? mix(colors, emphasis) : hot ? colors.strong : undefined;\n edits.style(element, \"fill\", colors?.paint === \"fill\" ? shade : undefined);\n edits.style(element, \"stroke\", colors?.paint === \"stroke\" ? shade : undefined);\n // The effect animates emphasis itself; a host transition on the colour would smear it.\n edits.style(element, \"transition\", emphasis === undefined || !colors ? undefined : \"none\");\n }\n paintHalo();\n };\n\n const paintHalo = (): void => {\n const visible = parts().flatMap((part) => (part.outline === undefined ? [] : [{ ...part.outline, color: part.colors?.color }]));\n halo.paint(halos(), visible, style.halo, style.transform);\n };\n\n return {\n get style() {\n return style;\n },\n set(next) {\n style = mergeFields(style, next);\n repaint();\n },\n reset() {\n style = {};\n repaint();\n },\n repaint,\n hot(on) {\n if (on === hot) return;\n hot = on;\n repaint();\n }\n };\n}\n\n/**\n * The host's colours for an element: its fill, or its stroke when the fill is none (a line). Each is\n * the computed value, as a browser draws it, even the initial one when the page's CSS sets it. jsdom\n * computes styles but no presentation attributes (every fill is black and every stroke none), so\n * there a computed value that's the property's initial one gives way to the nearest value declared\n * on the element or above it. A gradient or pattern gives no colours.\n *\n * The strong colour is our charts' kind of -strong: the colour stepped toward the text colour, in\n * OKLab so the hue stays, so a hovered mark gets darker in the light theme and lighter in the dark.\n * Our palette's -strong colours sit 20% of the way in light and 29% in dark; a host's colour goes 25%.\n */\nexport function hostColors(element: Element, root: Element): HostColors | undefined {\n const fill = paintOf(element, root, \"fill\");\n const paint = fill === NONE ? \"stroke\" : \"fill\";\n const color = paint === \"fill\" ? fill : paintOf(element, root, \"stroke\");\n if (color === undefined || color === NONE) return undefined;\n return { color, strong: `color-mix(in oklab, ${color}, ${cssColor(\"text\")} ${STRONG})`, paint };\n}\n\n/** How far a host's colour steps toward the text colour for its strong colour. */\nconst STRONG = \"25%\";\n\nconst NONE = \"none\";\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n\n/** Each root <svg>'s answer from attributesComputed(). */\nconst probed = new WeakMap<Element, boolean>();\n\n/**\n * Whether computed styles read SVG presentation attributes here, as a browser's do and jsdom's don't.\n * A probe with one is put in the root <svg>, read and taken out at once, so nothing draws it, once a\n * root. A root that isn't in a document has no computed styles to go by, so it isn't remembered.\n */\nfunction attributesComputed(root: Element): boolean {\n const known = probed.get(root);\n if (known !== undefined) return known;\n const view = root.ownerDocument.defaultView;\n if (!root.isConnected || typeof view?.getComputedStyle !== \"function\") return false;\n const probe = root.ownerDocument.createElementNS(SVG_NS, \"g\");\n // A property pages don't style, so no rule of theirs answers for the attribute.\n probe.setAttribute(\"stroke-miterlimit\", \"7\");\n root.appendChild(probe);\n const computed = view.getComputedStyle(probe).getPropertyValue(\"stroke-miterlimit\").trim() === \"7\";\n probe.remove();\n probed.set(root, computed);\n return computed;\n}\n\n/** A paint property's colour, NONE for no paint (or a transparent one), or undefined when it isn't a colour. */\nfunction paintOf(element: Element, root: Element, property: \"fill\" | \"stroke\"): string | undefined {\n const raw = element.ownerDocument.defaultView?.getComputedStyle?.(element).getPropertyValue(property);\n const computed = kind(raw);\n if (raw && attributesComputed(root)) return computed;\n let declared: string | undefined;\n for (let node: Element | null = element; node && declared === undefined; node = node === root ? null : node.parentElement) {\n const value = (node as SVGElement).style?.getPropertyValue(property) || node.getAttribute(property);\n if (value) declared = value;\n }\n const initial = property === \"fill\" ? computed?.replace(/\\s/g, \"\") === \"rgb(0,0,0)\" : computed === NONE;\n return computed !== undefined && !(initial && declared !== undefined) ? computed : kind(declared);\n}\n\n/**\n * An element's stroke width in its own user units, as drawn: the computed value, even a 1 px the\n * page's CSS sets. jsdom computes no presentation attributes, so there a computed 1, the initial\n * value, gives way to the nearest `stroke-width` attribute on the element or above it, passing over\n * one that can't be read, as SVG ignores it. An inline style, which jsdom computes, stops the search.\n * Undefined when there's none in px.\n */\nexport function strokeWidthOf(element: Element, root: Element): number | undefined {\n const raw = element.ownerDocument.defaultView?.getComputedStyle?.(element).getPropertyValue(\"stroke-width\");\n const computed = pixels(raw);\n if ((raw && attributesComputed(root)) || (computed !== undefined && computed !== 1)) return computed;\n for (let node: Element | null = element; node; node = node === root ? null : node.parentElement) {\n if ((node as SVGElement).style?.getPropertyValue(\"stroke-width\")) break;\n const width = pixels(node.getAttribute(\"stroke-width\"));\n if (width !== undefined) return width;\n }\n return computed;\n}\n\n/** A length of 0 or more, in px or with no unit; undefined for anything else (a percentage, inherit). */\nfunction pixels(value: string | null | undefined): number | undefined {\n // One way to match any digits, so a long run of them followed by junk is refused at once.\n const match = /^\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)\\s*(?:px\\s*)?$/i.exec(value ?? \"\");\n const number = match ? Number(match[1]) : NaN;\n return number >= 0 && Number.isFinite(number) ? number : undefined;\n}\n\n/** NONE for no paint or a transparent one, the colour as given, or undefined for anything else (a url(), inherit). */\nfunction kind(value: string | null | undefined): string | undefined {\n const v = value?.trim().toLowerCase();\n if (!v || v === \"inherit\" || v.startsWith(\"url(\")) return undefined;\n if (v === NONE || v === \"transparent\" || /^rgba\\((?:[^,]+,){3}\\s*0(?:\\.0*)?\\s*\\)$/.test(v)) return NONE;\n return value!.trim();\n}\n\nfunction mix(colors: SeriesColors, emphasis: number): string {\n const amount = Math.min(1, Math.max(0, emphasis));\n if (amount === 0) return colors.color;\n if (amount === 1) return colors.strong;\n return `color-mix(in srgb, ${colors.strong} ${Math.round(amount * 1000) / 10}%, ${colors.color})`;\n}\n\n/** CSS needs commas in matrix(); the SVG attribute doesn't mind them. */\nfunction cssMatrix(m: Matrix): string {\n return `matrix(${m.map((v, i) => (i < 4 ? Math.round(v * 1e6) / 1e6 : Math.round(v * 1000) / 1000)).join(\", \")})`;\n}\n","// Where an adapter's marks come from: a selector, elements, or a D3-style selection. And the two\n// elements every mark's coordinates hang off: the root <svg> and the marks' nearest common ancestor.\n\nimport type { MarkSource } from \"./types\";\n\nexport interface SourceMarks<D> {\n readonly elements: readonly Element[];\n /** A selection's data(), when it lines up with its nodes(). */\n readonly data: readonly D[] | undefined;\n}\n\nexport function readSource<D>(source: MarkSource<D>): SourceMarks<D> {\n if (typeof source === \"string\") {\n if (typeof document === \"undefined\") throw new TypeError(\"expressive: a selector needs a document.\");\n return { elements: Array.from(document.querySelectorAll(source)), data: undefined };\n }\n if (isElement(source)) return { elements: [source], data: undefined };\n if (isSelection<D>(source)) {\n const elements = Array.from(source.nodes());\n const data = Array.from(source.data());\n return { elements, data: data.length === elements.length ? data : undefined };\n }\n if (source !== null && typeof source === \"object\" && typeof (source as ArrayLike<Element>).length === \"number\") {\n return { elements: Array.from(source as ArrayLike<Element>), data: undefined };\n }\n throw new TypeError(\"expressive needs marks: a selector, an element, a list of elements or a D3 selection.\");\n}\n\n/** A selection's rows by element, when its data() lines up with its nodes(); otherwise undefined, and each element's own `__data__` is its row. */\nexport function boundRows<D>(source: MarkSource<D>): Map<Element, D> | undefined {\n if (!isSelection<D>(source)) return undefined;\n const { elements, data } = readSource(source);\n return data && new Map(elements.map((element, i) => [element, data[i]!]));\n}\n\n/** The outermost <svg> around the elements, which must all share it. */\nexport function rootOf(elements: readonly Element[]): SVGSVGElement {\n let root: SVGSVGElement | undefined;\n for (const element of elements) {\n if (!isElement(element)) throw new TypeError(`expressive: marks must be elements, got ${String(element)}.`);\n let svg = (element as SVGElement).ownerSVGElement ?? null;\n if (!svg) {\n const tag = element.localName;\n throw new TypeError(\n tag === \"svg\"\n ? \"expressive: got an <svg>, not its marks. Pass the marks, for example svg.querySelectorAll(\\\"rect\\\").\"\n : `expressive: marks must be SVG elements inside an <svg>, got <${tag}>.`\n );\n }\n while (svg.ownerSVGElement) svg = svg.ownerSVGElement;\n if (root && svg !== root) throw new TypeError(\"expressive: all marks must be in the same <svg>.\");\n root = svg;\n }\n if (!root) throw new TypeError(\"expressive: no marks.\");\n return root;\n}\n\n/** The deepest element containing every mark (a lone mark's parent). Geometry is in its coordinates. */\nexport function commonAncestor(elements: readonly Element[], root: Element): Element {\n let ancestor = elements[0]!.parentElement ?? root;\n while (ancestor !== root && !elements.every((element) => element !== ancestor && ancestor.contains(element))) {\n ancestor = ancestor.parentElement ?? root;\n }\n return ancestor;\n}\n\nfunction isElement(value: unknown): value is Element {\n return typeof value === \"object\" && value !== null && (value as Node).nodeType === 1;\n}\n\nfunction isSelection<D>(value: unknown): value is { nodes(): Element[]; data(): D[] } {\n return typeof value === \"object\" && value !== null && typeof (value as { nodes?: unknown }).nodes === \"function\" && typeof (value as { data?: unknown }).data === \"function\";\n}\n","// Following the host's own changes (`watch`, M4 decision 14). A MutationObserver notes changes to\n// the marks' geometry attributes, and to transform and style on every ancestor from the marks up to\n// the root <svg>: a host that animates a parent <g transform> changes none of the marks' own\n// attributes. What changed is handed on once a frame, on the chart's clock, however many\n// attributes the host wrote in between.\n//\n// The marks' own style isn't watched: the adapter writes it (effects' transforms, emphasis, the hover\n// colour), so it would hear itself.\n\nimport type { Clock } from \"../../core\";\n\n/** Attributes that move or reshape a mark. */\nconst GEOMETRY = [\"d\", \"x\", \"y\", \"width\", \"height\", \"cx\", \"cy\", \"r\", \"rx\", \"ry\", \"x1\", \"y1\", \"x2\", \"y2\", \"points\", \"transform\"];\n/** Attributes that move everything inside an ancestor. */\nconst ANCESTOR = [\"transform\", \"style\"];\n\n/** What changed since the last frame. */\nexport interface WatchedChanges {\n /** Mark elements whose geometry attributes changed. */\n readonly marks: ReadonlySet<Element>;\n /** Ancestors of the marks whose transform or style changed. */\n readonly ancestors: ReadonlySet<Element>;\n}\n\nexport interface HostWatch {\n /**\n * Watches these mark elements, and their ancestors up to `root`, instead of what it watched\n * before. Changes not handed on yet are dropped: the caller has just read everything.\n */\n observe(elements: readonly Element[], root: Element | undefined): void;\n /** Stops watching; nothing more is handed on. */\n destroy(): void;\n}\n\nexport function watchHost(doc: Document, clock: Clock, onChanges: (changes: WatchedChanges) => void): HostWatch {\n const Observer = doc.defaultView?.MutationObserver ?? (typeof MutationObserver === \"undefined\" ? undefined : MutationObserver);\n if (!Observer) throw new TypeError(\"expressive: watch needs MutationObserver, which this DOM doesn't have.\");\n\n let marks = new Set<Element>();\n let ancestors = new Set<Element>();\n /** The elements watched now: the marks', and their ancestors'. */\n let watchedMarks = new Set<Element>();\n let watchedAncestors = new Set<Element>();\n let cancelFrame: (() => void) | undefined;\n\n const collect = (records: readonly MutationRecord[]): void => {\n for (const { target, attributeName } of records) {\n const element = target as Element;\n if (watchedMarks.has(element)) marks.add(element);\n if (watchedAncestors.has(element) && (attributeName === \"transform\" || attributeName === \"style\")) ancestors.add(element);\n }\n };\n\n const observer = new Observer((records) => {\n collect(records);\n if ((marks.size > 0 || ancestors.size > 0) && !cancelFrame) cancelFrame = clock.onFrame(frame);\n });\n\n /**\n * Hands on what changed, and stays on the clock until a frame with no changes. A host that draws in\n * its own frame callback asks for its next frame there, and the clock, still on, asks after it at\n * the end of its own, so each of the host's frames is read in the frame it's drawn. Leaving after\n * every frame, the clock would ask again only on hearing the next changes, too late for that frame,\n * and the effects would trail the marks every other frame.\n */\n function frame(): void {\n // Changes the observer hasn't handed over yet, made earlier in this frame.\n collect(observer.takeRecords());\n if (marks.size === 0 && ancestors.size === 0) {\n cancelFrame?.();\n cancelFrame = undefined;\n return;\n }\n const changes: WatchedChanges = { marks, ancestors };\n marks = new Set();\n ancestors = new Set();\n onChanges(changes);\n }\n\n function drop(): void {\n observer.takeRecords();\n cancelFrame?.();\n cancelFrame = undefined;\n marks = new Set();\n ancestors = new Set();\n }\n\n return {\n observe(elements, root) {\n drop();\n observer.disconnect();\n watchedMarks = new Set(elements);\n watchedAncestors = new Set();\n for (const element of elements) {\n // Ancestors are shared: stop at one already seen, since everything above it is too.\n for (let node = element.parentElement; node && !watchedAncestors.has(node); node = node === root ? null : node.parentElement) {\n watchedAncestors.add(node);\n }\n }\n // An element that is a mark and also holds marks keeps the mark's list, which has transform but\n // not style: the adapter writes its style.\n for (const element of watchedAncestors) if (!watchedMarks.has(element)) observer.observe(element, { attributes: true, attributeFilter: ANCESTOR });\n for (const element of watchedMarks) observer.observe(element, { attributes: true, attributeFilter: GEOMETRY });\n },\n\n destroy() {\n drop();\n observer.disconnect();\n watchedMarks = new Set();\n watchedAncestors = new Set();\n }\n };\n}\n","// expressive(): effects on SVG marks drawn by other code (M1 step 10, for rects; M9 step 6, for\n// circles and shapes). It reads keys, rows and geometry from the host's elements, plays the effect\n// slots through the runner on an overlay at the end of the root <svg>, and listens for pointer events\n// once, on that <svg>. Keyboard focus is barChart's (../keyboard.ts), on the host's elements. Like the\n// charts it never names an effect, and destroy() leaves the host's DOM as it found it.\n//\n// Rects that share a key are a bar, each a segment of it. A <circle> is a point, and a <path>, <line>,\n// <polyline>, <polygon> or <ellipse> is read through describe.shape from its outline: each is a mark\n// of its own. A page describes anything else with the `geometry` option, which wins over all of it.\n//\n// Geometry is in the marks' nearest common ancestor's coordinates. The overlay carries that\n// ancestor's transform but sits on the root, because some hosts (Vega) remove foreign children from\n// their own groups when they redraw. See docs/ideas/adapter-spike.md.\n//\n// With `watch`, the host's own transitions are followed frame by frame (./watch.ts): the marks that\n// changed are read again and the runner hears change(), as on our charts' frames, with no events.\n//\n// A link (../link.ts) hovers marks too, as \"linked\": the dimming and emphasis with `dim`, and their\n// hover runs, with no focus ring or focus. It hears the attachment's own hovers.\n//\n// update({ on }) swaps effects through the runner, as a chart's does, and leave() ends the hover.\n\nimport type { Baseline, MarkData, MarkGeometry, Matrix, Point, Rect, Sample } from \"../../core\";\nimport { defaultClock, matrix } from \"../../core\";\nimport { invert } from \"../../core/geometry\";\nimport { describePoint } from \"../../core/geometry/describe/point\";\nimport { describeShape } from \"../../core/geometry/describe/shape\";\nimport { formatPath, shapeOutline } from \"../../core/geometry/path\";\nimport { goesRound } from \"../../core/geometry/ring\";\nimport { EFFECT_SLOTS, resolveEffects } from \"../../core/registry\";\nimport { report } from \"../../core/report\";\nimport { createRunner, type RunInput, type SlotEffects } from \"../../core/runner\";\nimport type { ChartEnv } from \"../bar\";\nimport { pointerHover, type PointerHover } from \"../interaction\";\nimport { keyboardFocus } from \"../keyboard\";\nimport { linkable, own, type LinkListener, type LinkPort } from \"../link\";\nimport { chartMotion } from \"../motion\";\nimport { maskedRing } from \"../render/outside\";\nimport { svgSurface } from \"../render/surface\";\nimport { setAttributes, setStyles, transformAttribute } from \"../render/svg\";\nimport { injectStyles } from \"../render/theme\";\nimport { nextEffects } from \"../shell/setup\";\nimport { labelsMoved } from \"../shell/transitions\";\nimport type { MarkEvents } from \"../types\";\nimport { baselines, describeRects, isBaseline, union, visualOrder, type RectPart } from \"./bars\";\nimport { hostEdits } from \"./edits\";\nimport { hostColors, hostMarkHandle, strokeWidthOf, type HostMarkHandle, type HostPart } from \"./host-style\";\nimport { boundRows, commonAncestor, readSource, rootOf } from \"./source\";\nimport { attributesOf, axisAligned, between, boxIn, keepsCircles, ownTransform, rectOf, scaleOf, screenMatrices, type ScreenMatrix } from \"./space\";\nimport type { Attachment, ExpressiveOptions, MarkSource } from \"./types\";\nimport { watchHost, type WatchedChanges } from \"./watch\";\n\ninterface Part<D> extends HostPart {\n readonly datum: D;\n readonly series: string | undefined;\n /** What `value` returned for it; undefined without `value`. */\n readonly value: unknown;\n /** A shape's stroke width in its own units, as the last full read found it, which watch keeps. */\n readonly strokeWidth?: number | undefined;\n}\n\n/** A mark as read from the host's elements. */\ninterface ReadMark<D> {\n readonly key: string;\n readonly geometry: MarkGeometry;\n readonly data: MarkData<D>;\n /** From the baseline for bars; in source order for marks described with `geometry`; one for a circle or a shape. */\n readonly parts: readonly Part<D>[];\n /** `markLabel`'s name for it; undefined leaves its ARIA as the host drew it. */\n readonly label: string | undefined;\n /** Its place in the source, by its first element: document order, for marks other than bars. */\n readonly index: number;\n /** A rect mark's baseline and the box its rects cover, which watch keeps and orders by. */\n readonly rect?: { readonly edge: Baseline; readonly box: Rect };\n /** Read from a <circle>, whose numeric `value` is its one sample. */\n readonly circle?: true;\n}\n\n/** A mark before its data. */\ntype Drawn<D> = Omit<ReadMark<D>, \"data\">;\n/** A mark before its name: watch keeps the one the last full read gave it. */\ntype Unnamed<D> = Omit<Drawn<D>, \"label\">;\n\n/** Where marks are read: the root and the marks' common ancestor, with the elements' screen CTMs and colours. */\ninterface ReadContext {\n readonly svg: SVGSVGElement;\n readonly common: Element;\n /** Screen CTMs, each read once. */\n readonly screen: ScreenMatrix;\n /** Computed on a full read; watch keeps the last ones, since it doesn't watch colours. */\n readonly colors: (element: Element) => HostPart[\"colors\"];\n /** A shape's stroke width in its own units: computed on a full read, and kept by watch, as colours are. */\n readonly strokeWidth: (element: Element) => number | undefined;\n}\n\n/** An element of a mark as read from the source, before its geometry. */\ninterface Piece<D> {\n readonly element: Element;\n readonly datum: D;\n readonly series: string | undefined;\n readonly value: unknown;\n}\n\ninterface Reading<D> {\n readonly root: SVGSVGElement | undefined;\n readonly ancestor: Element | undefined;\n /** In visual order. */\n readonly marks: readonly ReadMark<D>[];\n}\n\ninterface MarkRecord<D> {\n readonly key: string;\n mark: ReadMark<D>;\n readonly handle: HostMarkHandle;\n}\n\ninterface Owner<D> {\n readonly record: MarkRecord<D>;\n readonly part: Part<D>;\n}\n\ninterface Diff<D> {\n readonly entering: MarkRecord<D>[];\n readonly exiting: MarkRecord<D>[];\n /** Values changed: a part's `value`, or without `value` the length, or the segments. */\n readonly changed: { readonly record: MarkRecord<D>; readonly from: MarkGeometry }[];\n /** Only moved, or got a new row: the runner follows without an update. */\n readonly moved: MarkRecord<D>[];\n /** Whether a mark got a new row. With a value changed or a mark come or gone, that makes the read an update. */\n newRow: boolean;\n}\n\ntype HoverSource = MarkEvents<unknown>[\"hover\"][\"source\"];\ntype Listeners<D> = { [K in keyof MarkEvents<D>]: Set<(event: MarkEvents<D>[K]) => void> };\n\ninterface Hovered {\n /** The marks' keys: one for the attachment's own hover, any number for a link's. */\n readonly keys: readonly string[];\n readonly source: HoverSource;\n /** Whether their hover runs play: a link with `effects: false` keeps its marks to emphasis and dimming. */\n readonly effects: boolean;\n}\n\nconst SVG_NS = \"http://www.w3.org/2000/svg\";\n/** Elements that are each a mark of their own: a circle is a point, and the others are read through describe.shape. */\nconst SHAPES = new Set([\"circle\", \"ellipse\", \"line\", \"path\", \"polygon\", \"polyline\"]);\n/**\n * Host roles around named marks that unwrapNames takes off when they have no name: images, read as\n * one picture whose children screen readers may skip (`image` is ARIA 1.3's name for `img`), and\n * `graphics-object`, which takes its name from its contents, so the marks' names would be read twice.\n */\nconst WRAPPING_ROLES = new Set([\"img\", \"image\", \"graphics-symbol\", \"graphics-object\"]);\n\nexport function expressive<D>(target: MarkSource<D>, options: ExpressiveOptions<D>, env: ChartEnv): Attachment<D> {\n checkOptions(options);\n const motion = chartMotion(options.motion, env.motion);\n /** The effects, and the `on` they're from, which update({ on }) swaps. */\n let effects = resolveEffects(options.on, env.presets);\n let given = options.on;\n const clock = env.clock ?? defaultClock;\n const dim = options.dim === true;\n const edits = hostEdits();\n /** The host's colours per element, kept while an effect or the hover colour overrides them. */\n const colorCache = new WeakMap<Element, ReturnType<typeof hostColors>>();\n let source = target;\n let warnedIndex = false;\n let warnedImage = false;\n\n // ── Reading the host's marks ───────────────────────────────────────────────\n\n /** Reads every mark from `from`, changing nothing: it throws on marks it can't read. */\n function read(from: MarkSource<D>): Reading<D> {\n const { elements, data } = readSource(from);\n if (elements.length === 0) return { root: undefined, ancestor: undefined, marks: [] };\n const svg = rootOf(elements);\n const common = commonAncestor(elements, svg);\n\n const groups = new Map<string, Piece<D>[]>();\n elements.forEach((element, index) => {\n const datum = datumOf(element, index, data);\n const raw: unknown = options.key(datum, element);\n if (raw === undefined || raw === null || raw === \"\") {\n throw new TypeError(`expressive: key returned ${JSON.stringify(raw) ?? String(raw)} for a <${element.localName}>. Every mark needs a key.`);\n }\n const key = String(raw);\n const tag = element.localName;\n if (!options.geometry && tag !== \"rect\" && !SHAPES.has(tag)) {\n throw new TypeError(\n `expressive: can't read the geometry of a <${tag}> (mark \"${key}\"). <rect>, <circle>, <ellipse>, <line>, <path>, <polygon> and <polyline> are read; describe others with the geometry option.`\n );\n }\n const series = segmentOf(datum, element, key);\n let group = groups.get(key);\n if (!group) groups.set(key, (group = []));\n else if (!options.geometry && (SHAPES.has(tag) || SHAPES.has(group[0]!.element.localName))) {\n const shape = SHAPES.has(tag) ? tag : group[0]!.element.localName;\n throw new TypeError(`expressive: two elements have the key \"${key}\", and one is a <${shape}>. A circle or a shape is a mark of its own: give each its own key.`);\n } else if (series === undefined) throw new RangeError(`expressive: two elements have the key \"${key}\". Keys must be unique, or name each part with segment.`);\n else if (group.some((part) => part.series === series)) throw new RangeError(`expressive: the mark \"${key}\" has two \"${series}\" segments.`);\n group.push({ element, datum, series, value: options.value?.(datum, element) });\n });\n\n const at: ReadContext = { svg, common, screen: screenMatrices(), colors: (element) => colorsOf(element, svg), strokeWidth: (element) => strokeWidthOf(element, svg) };\n const named = (mark: Unnamed<D>): Drawn<D> => ({ ...mark, label: labelOf(mark.key, mark.parts) });\n const keys = [...groups.keys()];\n\n if (options.geometry) {\n const marks = keys.map((key, index) => named(givenMark(key, groups.get(key)!, index, at)));\n return { root: svg, ancestor: common, marks: checkNeeds(withData(ringOrder(marks, (mark) => mark.geometry)), effects) };\n }\n\n /** The bars' places in `keys`. A circle or a shape is read now; one that draws nothing isn't a mark. */\n const bars: number[] = [];\n const shapes: Unnamed<D>[] = [];\n keys.forEach((key, index) => {\n const pieces = groups.get(key)!;\n if (pieces[0]!.element.localName === \"rect\") bars.push(index);\n else {\n const mark = shapeMark(key, pieces[0]!, index, at);\n if (mark) shapes.push(mark);\n }\n });\n const rects = bars.map((index) => groups.get(keys[index]!)!.map((piece) => rectPiece(keys[index]!, piece, at)));\n const boxes = rects.map((pieces) => union(pieces.map((p) => p.rect.box)));\n const edges = baselines(boxes, options.baseline ?? \"auto\");\n const bar = (i: number): Unnamed<D> => rectMark(keys[bars[i]!]!, rects[i]!, edges[i]!, bars[i]!, at);\n // Bars alone go top to bottom, or left to right. With a circle or a shape among them, every mark\n // keeps document order, as marks described with `geometry` do, and marks round one pivot go clockwise.\n const marks =\n shapes.length === 0\n ? visualOrder(boxes, edges).map((i) => named(bar(i)))\n : ringOrder([...bars.map((_, i) => bar(i)), ...shapes].sort((a, b) => a.index - b.index), (mark) => mark.geometry).map((mark) => named(mark));\n return { root: svg, ancestor: common, marks: checkNeeds(withData(marks), effects) };\n }\n\n /** A mark described with `geometry`, from its elements in source order. */\n function givenMark(key: string, pieces: readonly Piece<D>[], index: number, at: ReadContext): Unnamed<D> {\n const first = pieces[0]!;\n const geometry = options.geometry!(first.element, first.datum, key);\n if (typeof geometry !== \"object\" || geometry === null || geometry.key !== key) {\n throw new TypeError(`expressive: geometry for \"${key}\" must be a MarkGeometry with the key \"${key}\". Build it with describe and the key passed in.`);\n }\n const parts = pieces.map((p) => part(p, outlineOf(geometry, p.series, pieces.length), at));\n return { key, geometry, parts, index };\n }\n\n /**\n * A <rect>'s box in the marks' common coordinates, through its parent's coordinates and its own\n * transform attribute. Its own CSS transform is the adapter's (an effect's), so it isn't read back.\n * Rects that aren't upright throw.\n */\n function rectPiece(key: string, piece: Piece<D>, at: ReadContext): Piece<D> & { readonly rect: RectPart } {\n const m = transformOf(piece.element, at);\n if (!axisAligned(m)) {\n throw new TypeError(`expressive: the <rect> of \"${key}\" is rotated or skewed, so it isn't an upright bar. Describe it with the geometry option.`);\n }\n return { ...piece, rect: { box: boxIn(m, rectOf(piece.element)), series: piece.series, radius: radiusOf(piece.element) } };\n }\n\n /** A bar from its rects, growing from `edge`: its parts go from the baseline. */\n function rectMark(key: string, pieces: readonly (Piece<D> & { readonly rect: RectPart })[], edge: Baseline, index: number, at: ReadContext): Unnamed<D> {\n const { geometry, order } = describeRects(key, pieces.map((p) => p.rect), edge);\n const segments = geometry.segments ?? [];\n const parts = order.map((j, n) => {\n const segment = segments[n];\n return part(pieces[j]!, segment && segment.length >= 0.5 ? { d: segment.outline.d } : undefined, at);\n });\n return { key, geometry, parts, index, rect: { edge, box: union(pieces.map((p) => p.rect.box)) } };\n }\n\n /**\n * A <circle> or another shape, a mark of its own, in the marks' common coordinates through its\n * transforms, as a rect's are. A circle is a point at its centre, with its radius, unless they\n * stretch it unevenly or skew it: then it's a shape, an ellipse. The others are read through\n * describe.shape from their outline, an open one with its stroke width as drawn, scaled with it. A\n * stroke width of 0 reads as 1 px, describe.shape's default. A part's `segment` names its series.\n * Undefined for a shape SVG wouldn't draw, such as a path with no path data.\n */\n function shapeMark(key: string, piece: Piece<D>, index: number, at: ReadContext): Unnamed<D> | undefined {\n const { element, series } = piece;\n const tag = element.localName;\n const m = transformOf(element, at);\n const attribute = attributesOf(element);\n const length = (name: string): number => {\n const value = Number.parseFloat(attribute(name) ?? \"\");\n return Number.isFinite(value) ? value : 0;\n };\n const r = tag === \"circle\" ? length(\"r\") : 0;\n let geometry: MarkGeometry;\n let strokeWidth: number | undefined;\n if (tag === \"circle\" && (keepsCircles(m) || !(r > 0))) {\n // A circle with no radius, which SVG wouldn't draw, is still a dot: a host may grow it from 0.\n const center = matrix.apply(m, { x: length(\"cx\"), y: length(\"cy\") });\n geometry = describePoint({ key, series, x: round(center.x), y: round(center.y), r: round(Math.max(0, r) * scaleOf(m)) });\n } else {\n const commands = shapeOutline(tag, attribute);\n if (commands[0]?.op !== \"M\" || commands.every((command) => command.op === \"M\")) return undefined;\n strokeWidth = tag === \"circle\" ? undefined : at.strokeWidth(element);\n const width = round((strokeWidth ?? 1) * scaleOf(m));\n // A path's own data, unrounded; the others' outlines are written out.\n const d = tag === \"path\" ? (attribute(\"d\") ?? \"\") : formatPath(commands);\n geometry = describeShape({ key, series, d, matrix: m, width: width > 0 ? width : 1 });\n }\n const parts = [{ ...part(piece, outlineOf(geometry, series, 1), at), strokeWidth }];\n return { key, geometry, parts, index, ...(tag === \"circle\" ? { circle: true as const } : {}) };\n }\n\n /** From an element's user space into the marks' common one: its parent's, then its own transform attribute. */\n function transformOf(element: Element, at: ReadContext): Matrix {\n return matrix.multiply(between(at.common, element.parentElement ?? at.svg, at.svg, at.screen), ownTransform(element));\n }\n\n function part(piece: Piece<D>, outline: Part<D>[\"outline\"], at: ReadContext): Part<D> {\n const parent = between(at.common, piece.element.parentElement ?? at.svg, at.svg, at.screen);\n return { element: piece.element, datum: piece.datum, series: piece.series, value: piece.value, parent, parentInverse: tryInvert(parent), colors: at.colors(piece.element), outline };\n }\n\n /**\n * Each mark's data, in the order given: its first part's row and its samples. `related(series)` is\n * the mark's own segment of that series, or else the first other live mark, in visual order, whose\n * series has that name, such as another of a D3 chart's line paths. It's looked up when called, so\n * it sees that mark as last read, by refresh() or by watch. Samples are read and checked here, so\n * bad ones throw before anything changes.\n */\n function withData(marks: readonly Drawn<D>[]): ReadMark<D>[] {\n return marks.map((mark): ReadMark<D> => {\n const { key, geometry, parts } = mark;\n const total = mark.rect ? totalOf(parts) : undefined;\n const value = parts[0]!.value;\n const dot = mark.circle && typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n const samplesOf = (datum: D, of: MarkGeometry, series?: string): readonly Sample[] => {\n if (options.samples) return checkSamples(options.samples(datum, of), series === undefined ? `\"${key}\"` : `\"${key}\" (${series})`);\n if (total !== undefined) return barSamples(geometry, of, total);\n // A dot's value, as a Vega symbol has it.\n return dot === undefined ? [] : [{ t: 0, value: dot }];\n };\n const own = new Map<string, MarkData<D>>();\n const related = (series: string): MarkData<D> | undefined => own.get(series) ?? relatedOf(series, key);\n for (const series of ownSeries(mark)) {\n const datum = (parts.find((p) => p.series === series) ?? parts[0]!).datum;\n own.set(series, { datum, samples: samplesOf(datum, geometry.segments?.find((s) => s.series === series) ?? geometry, series), related });\n }\n return { ...mark, data: { datum: parts[0]!.datum, samples: samplesOf(parts[0]!.datum, geometry), related } };\n });\n }\n\n /**\n * Data effects name the series they read through `needs.related`, and the marks must have them, so\n * a missing series throws instead of the effect drawing nothing. With no marks yet, there's nothing to check.\n */\n function checkNeeds<M extends Drawn<D>>(marks: M[], by: SlotEffects<D>): M[] {\n if (marks.length === 0) return marks;\n const series = new Set(marks.flatMap((mark) => [...(mark.geometry.series === undefined ? [] : [mark.geometry.series]), ...ownSeries(mark)]));\n for (const slot of EFFECT_SLOTS) {\n const effect = by[slot];\n if (effect?.kind !== \"data\") continue;\n for (const name of effect.needs?.related ?? []) {\n if (series.has(name)) continue;\n const known = series.size > 0 ? `the marks' series are ${[...series].map((s) => `\"${s}\"`).join(\", \")}` : \"the marks have no series\";\n throw new RangeError(\n `expressive: on.${slot} needs the series \"${name}\", but ${known}. Name each mark's series in its geometry (describe.line({ key, series, … })), or a stack's parts with segment.`\n );\n }\n }\n return marks;\n }\n\n function datumOf(element: Element, index: number, data: readonly D[] | undefined): D {\n if (options.datum) return options.datum(element);\n if (data) return data[index]!;\n const bound = (element as Element & { __data__?: unknown }).__data__;\n if (typeof bound === \"number\" && !warnedIndex) {\n warnedIndex = true;\n console.warn(\"expressive: element.__data__ is a number, which looks like Observable Plot's row index. Pass datum: (el) => rows[el.__data__].\");\n }\n return bound as D;\n }\n\n function segmentOf(datum: D, element: Element, key: string): string | undefined {\n if (!options.segment) return undefined;\n const series: unknown = options.segment(datum, element);\n if (series === undefined || series === null || series === \"\") throw new TypeError(`expressive: segment returned ${String(series)} for a part of \"${key}\".`);\n return String(series);\n }\n\n /** `markLabel`'s name for a mark. Empty, or a throw (reported), is undefined: the host's own ARIA stays. */\n function labelOf(key: string, parts: readonly Part<D>[]): string | undefined {\n if (!options.markLabel) return undefined;\n try {\n const text = String(options.markLabel(parts[0]!.datum, { key, parts: parts.map(({ series, datum }) => ({ series, datum })) }) ?? \"\");\n return text.trim() === \"\" ? undefined : text;\n } catch (error) {\n report(error);\n return undefined;\n }\n }\n\n function colorsOf(element: Element, svg: Element): HostPart[\"colors\"] {\n // While an effect or the hover colour sets it, the computed one is ours: keep the host's from before.\n if ((edits.styled(element, \"fill\") || edits.styled(element, \"stroke\")) && colorCache.has(element)) return colorCache.get(element);\n const colors = hostColors(element, svg);\n colorCache.set(element, colors);\n return colors;\n }\n\n // ── State and the overlay ──────────────────────────────────────────────────\n\n const first = read(source);\n const doc = first.root?.ownerDocument ?? (typeof document === \"undefined\" ? undefined : document);\n if (!doc) throw new TypeError(\"expressive needs a DOM.\");\n // The theme tokens the overlay and the focus ring draw in, and the dimming rules: shared, so it stays.\n injectStyles(doc);\n\n let root: SVGSVGElement | undefined;\n let ancestor: Element | undefined;\n /** Live marks by key, and in visual order. */\n const records = new Map<string, MarkRecord<D>>();\n let order: MarkRecord<D>[] = [];\n /** Marks whose exit effects are still running. */\n const leaving = new Map<string, MarkRecord<D>>();\n /** Every live mark's elements. Events find their mark through it. */\n let owners = new Map<Element, Owner<D>>();\n /** The host's elements around named marks whose role we took off (unwrapNames). */\n let unwrapped = new Set<Element>();\n const listeners: Listeners<D> = { enter: new Set(), update: new Set(), exit: new Set(), hover: new Set(), leave: new Set() };\n let hovered: Hovered | undefined;\n /** The mark showing the focus ring. */\n let ringKey: string | undefined;\n let interaction: PointerHover | undefined;\n /** The link the attachment is in, which hears its own hovers. */\n let linked: LinkListener | undefined;\n let destroyed = false;\n\n const make = <K extends keyof SVGElementTagNameMap>(tag: K, attributes: Record<string, string>, parent?: Element): SVGElementTagNameMap[K] => {\n const created = doc.createElementNS(SVG_NS, tag) as SVGElementTagNameMap[K];\n setAttributes(created, attributes);\n parent?.appendChild(created);\n return created;\n };\n const overlay = make(\"g\", { class: \"ec-overlay\", \"aria-hidden\": \"true\" });\n setStyles(overlay, { \"pointer-events\": \"none\" });\n const halos = make(\"g\", { class: \"ec-halos\" }, overlay);\n const runs = make(\"g\", { class: \"ec-runs\" }, overlay);\n // The overlay is above the marks, so the ring is masked to outside the mark and its gap: it can't\n // cover data or merge with a bar in the focus colour. The gap is left clear rather than painted in\n // --ec-surface as on barChart, since a host's background may be another colour.\n const ring = maskedRing(overlay);\n\n const find = (key: string): MarkRecord<D> | undefined => records.get(key) ?? leaving.get(key);\n const surface = svgSurface({\n overlay: runs,\n // Looked up on each call, so the handle follows the mark's record.\n mark: (key) => ({\n set: (style) => find(key)?.handle.set(style),\n reset: () => find(key)?.handle.reset()\n }),\n colors: (key) => find(key)?.mark.parts[0]?.colors\n });\n const runner = createRunner<D>({ effects, motion, icons: env.icons, clock, surface });\n const input = (record: MarkRecord<D>): RunInput<D> => ({ mark: record.mark.geometry, data: record.mark.data });\n\n function createRecord(mark: ReadMark<D>): MarkRecord<D> {\n const record: MarkRecord<D> = {\n key: mark.key,\n mark,\n // A leaving mark's elements may already belong to another mark (a join by index): leave those alone.\n handle: hostMarkHandle(() => record.mark.parts.filter((p) => (owners.get(p.element)?.record ?? record) === record), edits, () => halos)\n };\n return record;\n }\n\n // ── Applying a reading ─────────────────────────────────────────────────────\n\n /** Brings the attachment to `reading` and says what changed. Leaving marks stay until their exit is done. */\n function apply(reading: Reading<D>): Diff<D> {\n if (reading.root && reading.root !== root) moveTo(reading.root);\n ancestor = reading.ancestor ?? ancestor;\n const keys = new Set(reading.marks.map((mark) => mark.key));\n const diff: Diff<D> = { entering: [], exiting: [], changed: [], moved: [], newRow: false };\n const recolor: string[] = [];\n for (const record of order) {\n if (keys.has(record.key)) continue;\n records.delete(record.key);\n leaving.set(record.key, record);\n diff.exiting.push(record);\n }\n const before = owners;\n owners = new Map();\n order = reading.marks.map((mark) => {\n let record = records.get(mark.key);\n if (record) {\n const from = record.mark;\n // With `value`, a resize or a new axis maximum only moves marks, as on our charts.\n const changed = options.value ? valuesChanged(from.parts, mark.parts) : lengthsChanged(from.geometry, mark.geometry);\n const newRow = from.data.datum !== mark.data.datum;\n if (newRow) diff.newRow = true;\n if (changed) diff.changed.push({ record, from: from.geometry });\n else if (newRow || geometryChanged(from.geometry, mark.geometry) || samplesChanged(from.data.samples, mark.data.samples)) {\n diff.moved.push(record);\n }\n if (from.parts[0]?.colors?.color !== mark.parts[0]?.colors?.color) recolor.push(mark.key);\n record.mark = mark;\n } else {\n // A mark that comes back mid-exit keeps its record; the runner cancels its exit.\n record = leaving.get(mark.key);\n if (record) {\n leaving.delete(mark.key);\n record.mark = mark;\n } else {\n record = createRecord(mark);\n }\n records.set(mark.key, record);\n diff.entering.push(record);\n }\n for (const part of mark.parts) owners.set(part.element, { record, part });\n return record;\n });\n // Elements that left their mark, or moved to another one, get back what the host had.\n for (const [el, owner] of before) if (owners.get(el)?.record !== owner.record) edits.restore(el);\n for (const record of order) nameMark(record);\n unwrapNames();\n\n placeOverlay();\n applyDim();\n for (const record of order) record.handle.repaint();\n for (const key of recolor) surface.recolor(key);\n drawRing();\n return diff;\n }\n\n /**\n * With `markLabel`, a mark is read as one item: the element that takes its focus is an image named\n * by it (and shown, even if the host hid it), and its other parts are hidden. Each is written again\n * on every read, since a part can become the first (a stack gains a segment) or stop being it.\n */\n function nameMark(record: MarkRecord<D>): void {\n if (!options.markLabel) return;\n const { label, parts } = record.mark;\n parts.forEach((part, index) => {\n const named = label !== undefined && index === 0;\n edits.attribute(part.element, \"role\", named ? \"img\" : null);\n edits.attribute(part.element, \"aria-label\", named ? label : null);\n if (named) edits.remove(part.element, \"aria-hidden\");\n else edits.attribute(part.element, \"aria-hidden\", label === undefined ? null : \"true\");\n });\n }\n\n /**\n * With `markLabel`, the host's unnamed elements around a named mark's parts lose a wrapping role\n * (WRAPPING_ROLES) and its `aria-roledescription`, so the marks are read as the host's own `<g>`s\n * would leave them: once each, by name. Vega gives the group around each line `graphics-symbol`, an\n * image with no name (which fails WCAG 1.1.1), and the groups above it `graphics-object`. It writes\n * them again when it redraws, so they're taken off on every read, and an element with no named mark\n * inside any more gets its role back.\n */\n function unwrapNames(): void {\n const svg = root;\n const next = new Set<Element>();\n for (const record of options.markLabel && svg ? order : []) {\n if (record.mark.label === undefined) continue;\n for (const part of record.mark.parts) {\n for (let element: Element | null = part.element.parentElement; element && element !== svg && svg?.contains(element); element = element.parentElement) {\n if (next.has(element) || element.hasAttribute(\"aria-label\") || element.hasAttribute(\"aria-labelledby\")) continue;\n const role = element.getAttribute(\"role\")?.trim().split(/\\s+/)[0];\n if ((role !== undefined && WRAPPING_ROLES.has(role)) || (role === undefined && unwrapped.has(element))) next.add(element);\n }\n }\n }\n for (const element of unwrapped) {\n if (next.has(element)) continue;\n edits.attribute(element, \"role\", null);\n edits.attribute(element, \"aria-roledescription\", null);\n }\n for (const element of next) {\n edits.remove(element, \"role\");\n edits.remove(element, \"aria-roledescription\");\n }\n unwrapped = next;\n }\n\n /** The overlay is the root's last child, in the common ancestor's coordinates. */\n function placeOverlay(): void {\n if (!root || !ancestor) return;\n if (root.lastElementChild !== overlay) root.appendChild(overlay);\n overlay.removeAttribute(\"transform\");\n const m = between(overlay, ancestor, root);\n if (!isIdentity(m)) overlay.setAttribute(\"transform\", transformAttribute(m));\n }\n\n /** Listens on a new root <svg> (Plot draws a new one each time) and moves the overlay there. */\n function moveTo(next: SVGSVGElement): void {\n detach();\n root = next;\n root.appendChild(overlay);\n if ((options.keyboard === true || options.markLabel) && root.getAttribute(\"role\") === \"img\" && !warnedImage) {\n warnedImage = true;\n console.warn('expressive: the <svg> is role=\"img\", so screen readers read it as one picture and skip the marks inside, with their names and keyboard focus. Make it role=\"group\"; its aria-label can stay.');\n }\n interaction = pointerHover(root, {\n find(eventTarget) {\n const owner = ownerOf(eventTarget);\n if (!owner) return undefined;\n const { key } = owner.record;\n return owner.part.series === undefined ? { key } : { key, segment: owner.part.series };\n },\n hover(hoverTarget, from) {\n const record = records.get(hoverTarget.key);\n // Already playing for keyboard focus: let it go on.\n if (!record || (own(hovered) && hovered.keys[0] === hoverTarget.key)) return;\n endHover();\n startHover([record], from, hoverTarget.segment);\n },\n leave() {\n // Focus holds a keyboard hover until blur or Escape, and a link holds its own.\n if (hovered?.source === \"pointer\" || hovered?.source === \"touch\") endHover();\n }\n });\n }\n\n /** Stops listening on the current root. */\n function detach(): void {\n if (!root) return;\n endHover();\n interaction?.destroy();\n interaction = undefined;\n }\n\n function ownerOf(eventTarget: EventTarget | null): Owner<D> | undefined {\n for (let node = eventTarget as Element | null; node && node !== root; node = node.parentElement) {\n const owner = owners.get(node);\n if (owner) return owner;\n }\n return undefined;\n }\n\n // ── Hover ──────────────────────────────────────────────────────────────────\n\n /** Pointer, keyboard and link hover share this; the attachment's own tells its link. */\n function startHover(marks: readonly MarkRecord<D>[], from: HoverSource, segment?: string, effects = true): void {\n const started: Hovered = { keys: marks.map((record) => record.key), source: from, effects };\n hovered = started;\n applyDim();\n if (effects) runner.hover(marks.map(input));\n marks.forEach((record, index) => emit(\"hover\", { ...input(record), batch: { index, count: marks.length }, source: from, ...(segment === undefined ? {} : { segment }) }));\n // A listener may have ended it (a refresh() that removed the mark) or started another (focus()), which told the link itself.\n if (from !== \"linked\" && hovered === started) linked?.hover(marks.map(input));\n }\n\n function endHover(): void {\n const current = hovered;\n if (!current) return;\n hovered = undefined;\n applyDim();\n leaveMarks(current.keys);\n if (own(current)) linked?.leave();\n }\n\n /** The marks' hover runs end in one batch, and each gets a leave event. */\n function leaveMarks(keys: readonly string[]): void {\n const marks = keys.flatMap((key) => find(key) ?? []);\n runner.leave(keys);\n marks.forEach((record, index) => emit(\"leave\", { ...input(record), batch: { index, count: marks.length } }));\n }\n\n /** After a read: a hover whose marks have all left ends, and a link's goes on with those still here. */\n function dropGone(): void {\n if (hovered === undefined) return;\n const keys = hovered.keys.filter((key) => records.has(key));\n if (keys.length === hovered.keys.length) return;\n if (keys.length === 0) {\n interaction?.clear();\n endHover();\n return;\n }\n const gone = hovered.keys.filter((key) => !records.has(key));\n hovered = { ...hovered, keys };\n leaveMarks(gone);\n }\n\n /**\n * With `dim`, this attachment's other marks fade while one is hovered, and the hovered one takes its\n * strong colour (its fill, or its stroke on a line), as on our charts. The fade is classes, so host\n * CSS can override it, and only on its own marks, so attachments sharing an <svg> leave each other alone.\n * The paths and icons their runs draw fade with them, as on our charts: the overlay is `ec-hovering`,\n * and the hovered marks' groups `ec-hot`. All are CSS transitions timed by motion, like the charts'.\n */\n function applyDim(): void {\n if (!dim) return;\n const duration = `${motion.duration(100, \"feedback\")}ms`;\n overlay.classList.toggle(\"ec-hovering\", hovered !== undefined);\n setStyles(overlay, { \"--ec-hover-duration\": duration });\n for (const record of order) {\n const hot = hovered?.keys.includes(record.key) === true;\n for (const part of record.mark.parts) {\n edits.toggleClass(part.element, \"ec-attached\", true);\n edits.toggleClass(part.element, \"ec-dimmed\", hovered !== undefined && !hot);\n edits.style(part.element, \"--ec-hover-duration\", duration);\n }\n record.handle.hot(hot);\n surface.hot(record.key, hot);\n }\n for (const record of leaving.values()) {\n record.handle.hot(false);\n surface.hot(record.key, false);\n }\n }\n\n const unsubscribeMotion = dim ? motion.subscribe(applyDim) : undefined;\n\n /** The series data effects read through `related`, maybe from other marks: found again when update() swaps them. */\n const neededBy = (by: SlotEffects<D>): Set<string> =>\n new Set(\n EFFECT_SLOTS.flatMap((slot) => {\n const effect = by[slot];\n return effect?.kind === \"data\" ? (effect.needs?.related ?? []) : [];\n })\n );\n let needed = neededBy(effects);\n\n // ── Keyboard ───────────────────────────────────────────────────────────────\n\n /** The focus ring follows the mark's outline, drawn in the overlay. An open outline (a line from `geometry`) is ringed outside its stroke. */\n function drawRing(): void {\n const record = ringKey === undefined ? undefined : records.get(ringKey);\n ring.draw(record?.mark.geometry);\n }\n\n // barChart's keyboard focus, with the same hover rules: on the host's elements, written through\n // the edits so destroy() puts back what they had.\n const keyboard =\n options.keyboard === true\n ? keyboardFocus(() => root, {\n find: (eventTarget) => ownerOf(eventTarget)?.record.key,\n order: () => order.map((record) => record.key),\n element: (key) => records.get(key)?.mark.parts[0]?.element as SVGElement | undefined,\n tabIndex(key, value) {\n // A mark that left: apply() already gave its elements back what the host had.\n const record = records.get(key);\n if (!record || value === undefined) return;\n // The first element takes the mark's focus; a click can focus the others. The ring stands in for their own outline.\n record.mark.parts.forEach((part, index) => {\n edits.attribute(part.element, \"tabindex\", index === 0 ? value : \"-1\");\n edits.style(part.element, \"outline\", \"none\");\n });\n },\n focus(key, visible) {\n ringKey = visible ? key : undefined;\n drawRing();\n const record = records.get(key);\n if (!record) return;\n if (!visible) {\n // Focus from a click or tap: the pointer's own hover plays.\n if (hovered?.source === \"keyboard\" && hovered.keys[0] !== key) endHover();\n return;\n }\n if (own(hovered) && hovered.keys[0] === key) {\n // Already playing for the pointer: it goes on, held by focus now.\n hovered = { ...hovered, source: \"keyboard\" };\n return;\n }\n endHover();\n startHover([record], \"keyboard\");\n },\n blur() {\n ringKey = undefined;\n drawRing();\n if (hovered?.source !== \"keyboard\") return;\n // The pointer is still over it: the hover goes on, held by the pointer now.\n if (interaction?.current === hovered.keys[0]) hovered = { ...hovered, source: \"pointer\" };\n else endHover();\n },\n escape() {\n if (!hovered) return false;\n // A link's hover ends where it started, and with it every chart's in the link.\n if (hovered.source === \"linked\" && linked) linked.dismiss();\n else endHover();\n return true;\n }\n })\n : undefined;\n\n // ── Watching the host ──────────────────────────────────────────────────────\n\n const watching = options.watch === true ? watchHost(doc, clock, follow) : undefined;\n\n /** Watches the live marks' elements from now on, and drops changes not followed yet: the caller has just read them all. */\n function watchMarks(): void {\n watching?.observe(\n order.flatMap((record) => record.mark.parts.map((part) => part.element)),\n root\n );\n }\n\n /**\n * A frame's changes, with `watch`. The marks whose geometry attributes changed, and every mark inside\n * an ancestor that moved below the marks' common ancestor, are read again, put in visual order again\n * and followed through change(), with no events and no interrupt, as on our charts' frames. An\n * ancestor at or above the common ancestor moves the overlay: the marks' geometry is in that\n * ancestor's coordinates, so it hasn't changed.\n */\n function follow(changes: WatchedChanges): void {\n if (destroyed || !ancestor) return;\n const changed = new Set<MarkRecord<D>>();\n for (const element of changes.marks) {\n const record = owners.get(element)?.record;\n if (record) changed.add(record);\n }\n let overlayMoved = false;\n for (const element of changes.ancestors) {\n if (element.contains(ancestor)) overlayMoved = true;\n else for (const record of order) if (record.mark.parts.some((part) => element.contains(part.element))) changed.add(record);\n }\n if (overlayMoved) placeOverlay();\n if (changed.size === 0) return;\n\n // Throws (reported by the clock) on marks it can't read, before anything changes.\n const { records, marks } = reread([...changed]);\n records.forEach((record, i) => {\n const mark = marks[i]!;\n record.mark = mark;\n for (const part of mark.parts) owners.set(part.element, { record, part });\n record.handle.repaint();\n });\n order = visual(order);\n if (records.some((record) => record.key === ringKey)) drawRing();\n // As in refresh(): when a mark of a series a data effect needs moves, every other live mark follows too.\n const following = new Set(records);\n if (records.some((record) => needed.has(record.mark.geometry.series ?? \"\"))) for (const record of order) following.add(record);\n for (const record of following) runner.change(record.mark.geometry, record.mark.data);\n }\n\n /**\n * The marks that changed again, as the host draws them now: their rows, geometry and samples, in the\n * coordinates of the last full read. Their values, colours, stroke widths and names stay as that read\n * found them, and so do their elements. Bars whose baseline changed come too, though they didn't\n * move. A shape that draws nothing in this frame stays as it was, until refresh() reads it. Throws,\n * changing nothing, on marks it can't read.\n */\n function reread(changed: readonly MarkRecord<D>[]): { readonly records: MarkRecord<D>[]; readonly marks: ReadMark<D>[] } {\n const at: ReadContext = {\n svg: root!,\n common: ancestor!,\n screen: screenMatrices(),\n colors: (element) => owners.get(element)?.part.colors,\n strokeWidth: (element) => owners.get(element)?.part.strokeWidth\n };\n const rowOf = rowsNow();\n const piecesOf = ({ parts }: ReadMark<D>): Piece<D>[] => parts.map((part) => ({ element: part.element, datum: rowOf(part.element), series: part.series, value: part.value }));\n if (options.geometry) {\n const marks = changed.map(({ mark }): Drawn<D> => ({ ...givenMark(mark.key, piecesOf(mark), mark.index, at), label: mark.label }));\n return { records: [...changed], marks: withData(marks) };\n }\n const rects = new Map(changed.flatMap((record) => (record.mark.rect ? [[record, piecesOf(record.mark).map((piece) => rectPiece(record.key, piece, at))] as const] : [])));\n const edges = edgesNow(rects);\n for (const record of order) {\n if (record.mark.rect && !rects.has(record) && edges.get(record) !== record.mark.rect.edge) {\n rects.set(record, piecesOf(record.mark).map((piece) => rectPiece(record.key, piece, at)));\n }\n }\n const records = [...rects.keys()];\n const marks = records.map((record): Drawn<D> => ({ ...rectMark(record.key, rects.get(record)!, edges.get(record)!, record.mark.index, at), label: record.mark.label }));\n for (const record of changed) {\n if (record.mark.rect) continue;\n const mark = shapeMark(record.key, piecesOf(record.mark)[0]!, record.mark.index, at);\n if (!mark) continue;\n records.push(record);\n marks.push({ ...mark, label: record.mark.label });\n }\n return { records, marks: withData(marks) };\n }\n\n /**\n * Each live bar's baseline now. With \"auto\", the edge every bar shares is found again from their\n * boxes (the new ones of the bars read this frame), as a full read would, so a bar that ends a\n * transition on the other side of the line grows from it the other way. In a frame where no edge is\n * shared (a bar crossing the line), each keeps the one it had.\n */\n function edgesNow(rects: ReadonlyMap<MarkRecord<D>, readonly (Piece<D> & { readonly rect: RectPart })[]>): Map<MarkRecord<D>, Baseline> {\n const bars = order.filter((record) => record.mark.rect);\n const kept = new Map(bars.map((record) => [record, record.mark.rect!.edge]));\n if (options.baseline !== undefined && options.baseline !== \"auto\") return kept;\n const boxes = bars.map((record) => {\n const pieces = rects.get(record);\n return pieces ? union(pieces.map((p) => p.rect.box)) : record.mark.rect!.box;\n });\n try {\n const found = baselines(boxes, \"auto\");\n return new Map(bars.map((record, i) => [record, found[i]!]));\n } catch {\n return kept;\n }\n }\n\n /** Each element's row now: `datum`'s, a selection's data(), or the element's own `__data__`. */\n function rowsNow(): (element: Element) => D {\n if (options.datum) return options.datum;\n const bound = boundRows(source);\n return (element) => (bound?.has(element) ? bound.get(element)! : datumOf(element, 0, undefined));\n }\n\n /** The records in visual order, as read() orders marks: by their place in the source and, for bars alone, their boxes. */\n function visual(records: readonly MarkRecord<D>[]): MarkRecord<D>[] {\n const bySource = [...records].sort((a, b) => a.mark.index - b.mark.index);\n if (options.geometry || !bySource.every((record) => record.mark.rect)) return [...ringOrder(bySource, (record) => record.mark.geometry)];\n const boxes = bySource.map((record) => record.mark.rect!.box);\n const edges = bySource.map((record) => record.mark.rect!.edge);\n return visualOrder(boxes, edges).map((i) => bySource[i]!);\n }\n\n /** The first other live mark of that series, in visual order: another of a D3 chart's line paths. */\n function relatedOf(series: string, key: string): MarkData<D> | undefined {\n return order.find((record) => record.key !== key && record.mark.geometry.series === series)?.mark.data;\n }\n\n // ── Events ─────────────────────────────────────────────────────────────────\n\n function emit<K extends keyof MarkEvents<D>>(type: K, event: MarkEvents<D>[K]): void {\n for (const listener of [...listeners[type]]) {\n try {\n listener(event);\n } catch (error) {\n report(error);\n }\n }\n }\n\n function emitEach(type: \"enter\" | \"exit\", marks: readonly MarkRecord<D>[]): void {\n marks.forEach((record, index) => emit(type, { ...input(record), batch: { index, count: marks.length } }));\n }\n\n // ── First read ─────────────────────────────────────────────────────────────\n\n runner.enter(apply(first).entering.map(input));\n keyboard?.sync();\n watchMarks();\n\n const link: LinkPort = {\n targets: () => order.map((record) => ({ key: record.key, marks: [input(record)] })),\n hover(keys, effects) {\n endHover();\n const marks = keys.flatMap((key) => records.get(key) ?? []);\n if (marks.length > 0) startHover(marks, \"linked\", undefined, effects);\n },\n unlink() {\n if (hovered?.source === \"linked\") endHover();\n },\n leave() {\n interaction?.clear();\n endHover();\n },\n listen(listener) {\n if (destroyed) return false;\n linked = listener;\n return true;\n }\n };\n\n return linkable(link, {\n refresh(next) {\n if (destroyed) return;\n // Throws on marks it can't read, before anything changes.\n const reading = read(next ?? source);\n if (next !== undefined) source = next;\n\n // The order the runner expects: interrupt, then exit / update / enter, then change, then settle.\n runner.interrupt();\n const diff = apply(reading);\n watchMarks();\n dropGone();\n const exited = runner.exit(diff.exiting.map(input));\n emitEach(\"exit\", diff.exiting);\n // A new row, a new value, or a mark come or gone is an update: it ends the update runs of the\n // marks it leaves alone. A read that finds none (a Vega render for a hover signal) keeps them.\n if (diff.newRow || diff.changed.length > 0 || diff.entering.length > 0 || diff.exiting.length > 0) {\n runner.update(diff.changed.map(({ record, from }) => ({ ...input(record), from })));\n }\n diff.changed.forEach(({ record, from }, index) => emit(\"update\", { ...input(record), from, batch: { index, count: diff.changed.length } }));\n runner.enter(diff.entering.map(input));\n emitEach(\"enter\", diff.entering);\n // A data effect can read another mark through related(series): when a mark of a series one needs\n // changes, moves, comes or goes, every other live mark follows too, with data that sees it.\n const following = new Set([...diff.changed.map((c) => c.record), ...diff.moved]);\n if ([...following, ...diff.entering, ...diff.exiting].some((record) => needed.has(record.mark.geometry.series ?? \"\"))) {\n const entering = new Set(diff.entering);\n for (const record of order) if (!entering.has(record)) following.add(record);\n }\n for (const record of following) runner.change(record.mark.geometry, record.mark.data);\n runner.settle();\n // Focus stays with its key, on the mark's new element if the host replaced it (Vega does). If the\n // mark left, focus moves to its nearest neighbour. Every mark's tabindex is set again.\n keyboard?.sync();\n\n void exited.then(() => {\n for (const record of diff.exiting) if (leaving.get(record.key) === record) leaving.delete(record.key);\n });\n },\n\n async update(next) {\n if (destroyed) return;\n if (typeof next !== \"object\" || next === null) throw new TypeError('expressive: update() needs options, such as { on: { hover: \"lift\" } }.');\n const other = Object.keys(next).find((name) => name !== \"on\");\n if (other !== undefined) throw new TypeError(`expressive: \\`${other}\\` can't be changed by update() yet. Only \\`on\\` can.`);\n if (!(\"on\" in next)) return;\n // Throws on an effect it can't resolve, or a series a data effect needs that the marks don't\n // have, before anything changes.\n const swapped = nextEffects(effects, given, next.on, env.presets);\n checkNeeds(order.map((record) => record.mark), swapped);\n given = next.on;\n effects = swapped;\n needed = neededBy(swapped);\n // New effects start where the old ones were: decorate on every live mark, a held hover at once\n // (an attachment has no change to settle), and enter, update and exit at their end state.\n runner.swap(swapped, order.map(input));\n },\n\n on(type, listener) {\n const set = listeners[type] as Set<typeof listener> | undefined;\n if (!set) throw new TypeError(`expressive: unknown event \"${String(type)}\". Use one of: ${Object.keys(listeners).join(\", \")}.`);\n set.add(listener);\n return () => {\n set.delete(listener);\n };\n },\n\n marks: () => order.map((record) => record.mark.geometry),\n\n focus(key) {\n if (records.has(key) && !destroyed) keyboard?.focus(key);\n },\n\n leave() {\n if (!destroyed) link.leave();\n },\n\n destroy() {\n if (destroyed) return;\n destroyed = true;\n hovered = undefined;\n linked?.gone();\n linked = undefined;\n watching?.destroy();\n // The runner resets every mark it styled, through the records, so it goes first.\n runner.destroy();\n unsubscribeMotion?.();\n keyboard?.destroy();\n detach();\n overlay.remove();\n edits.restoreAll();\n for (const set of Object.values(listeners)) set.clear();\n records.clear();\n leaving.clear();\n order = [];\n owners = new Map();\n }\n });\n}\n\nfunction checkOptions<D>(options: ExpressiveOptions<D>): void {\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"expressive needs options, with at least a key: { key: (d) => d.name }.\");\n if (typeof options.key !== \"function\") throw new TypeError(\"expressive needs a key function, for example key: (d) => d.name. Marks are matched by key.\");\n for (const name of [\"datum\", \"segment\", \"value\", \"geometry\", \"markLabel\"] as const) {\n if (options[name] !== undefined && typeof options[name] !== \"function\") throw new TypeError(`expressive: ${name} must be a function.`);\n }\n if (options.baseline !== undefined && options.baseline !== \"auto\" && !isBaseline(options.baseline)) {\n throw new RangeError(`expressive: baseline must be \"left\", \"right\", \"top\", \"bottom\" or \"auto\", got ${String(options.baseline)}.`);\n }\n}\n\n/** The series a mark has of its own: its segments' and its parts'. */\nfunction ownSeries<D>(mark: Drawn<D>): string[] {\n const names = [...(mark.geometry.segments ?? []).map((s) => s.series), ...mark.parts.map((p) => p.series)];\n return [...new Set(names.filter((name): name is string => name !== undefined))];\n}\n\n/** A rect mark's total: the sum of its parts' values when every one is a finite number (from `value`), else undefined. */\nfunction totalOf<D>(parts: readonly Part<D>[]): number | undefined {\n let total = 0;\n for (const { value } of parts) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n total += value;\n }\n return total;\n}\n\n/**\n * The bar chart's samples: from 0 at the baseline to the total at the tip, values in proportion to\n * distance along the bar. A segment's run over its own span of it.\n */\nfunction barSamples(bar: MarkGeometry, of: MarkGeometry, total: number): Sample[] {\n const valueAt = (along: number): number => (bar.length > 0 ? (total * along) / bar.length : 0);\n if (of === bar) {\n return [\n { t: 0, value: 0 },\n { t: 1, value: total }\n ];\n }\n const from = distance(bar.start, of.start);\n return [\n { t: 0, value: valueAt(from) },\n { t: 1, value: valueAt(from + of.length) }\n ];\n}\n\n/** A copy of the page's samples, checked: t in [0, 1] and never decreasing, and finite values. */\nfunction checkSamples(samples: unknown, mark: string): Sample[] {\n if (!Array.isArray(samples)) throw new TypeError(`expressive: samples for ${mark} must return an array of { t, value }, got ${describeValue(samples)}.`);\n let last = 0;\n return samples.map((sample: unknown, i): Sample => {\n const { t, value, at, gapBefore } = (typeof sample === \"object\" && sample !== null ? sample : {}) as Partial<Sample>;\n if (typeof t !== \"number\" || !(t >= 0 && t <= 1)) throw new RangeError(`expressive: samples for ${mark}: samples[${i}].t must be in [0, 1], got ${describeValue(t)}.`);\n if (t < last) throw new RangeError(`expressive: samples for ${mark} must be in t order: samples[${i}].t is ${t}, after ${last}.`);\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new RangeError(`expressive: samples for ${mark}: samples[${i}].value must be a finite number, got ${describeValue(value)}.`);\n }\n if (gapBefore !== undefined && typeof gapBefore !== \"boolean\") {\n throw new RangeError(`expressive: samples for ${mark}: samples[${i}].gapBefore must be true or false, got ${describeValue(gapBefore)}.`);\n }\n last = t;\n return { t, value, ...(at === undefined ? {} : { at }), ...(gapBefore ? { gapBefore } : {}) };\n });\n}\n\nfunction describeValue(value: unknown): string {\n return typeof value === \"string\" ? JSON.stringify(value) : String(value);\n}\n\n/**\n * The visual order of marks described with `geometry`. Marks that go round one pivot (a pie's\n * slices) are ordered clockwise from 12 o'clock, by the angle of each mark's centre about the pivot,\n * as a ring is read: d3.pie() sorts slices by value but returns them in data order, so document\n * order jumps around the ring. Otherwise it's document order.\n */\nfunction ringOrder<T>(marks: readonly T[], geometryOf: (mark: T) => MarkGeometry): readonly T[] {\n const pivot = marks[0] && geometryOf(marks[0]).pivot;\n if (!pivot || !marks.every((mark) => distance(geometryOf(mark).pivot, pivot) <= 0.5 && goesRound(geometryOf(mark)))) return marks;\n const TURN = 2 * Math.PI;\n const clockwise = (mark: T): number => {\n const { center } = geometryOf(mark);\n // In [0, 2π): 0 straight up (y points down), turning towards +x.\n const angle = Math.atan2(center.x - pivot.x, pivot.y - center.y);\n const turned = angle < 0 ? angle + TURN : angle;\n return turned >= TURN ? 0 : turned;\n };\n // A stable sort: marks at one angle (dots on the pivot) keep document order.\n return marks\n .map((mark) => ({ mark, angle: clockwise(mark) }))\n .sort((a, b) => a.angle - b.angle)\n .map(({ mark }) => mark);\n}\n\nfunction distance(a: Point, b: Point): number {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\n/**\n * For a mark described with `geometry`: the part's own segment, or the whole mark for a lone part,\n * with the stroke's width when the outline is open (a line).\n */\nfunction outlineOf(geometry: MarkGeometry, series: string | undefined, parts: number): HostPart[\"outline\"] {\n const segment = series === undefined ? undefined : geometry.segments?.find((s) => s.series === series);\n const shape = segment ?? (parts === 1 ? geometry : undefined);\n if (!shape || (segment && segment.length < 0.5)) return undefined;\n return shape.outline.closed ? { d: shape.outline.d } : { d: shape.outline.d, stroke: shape.thickness };\n}\n\n/** The rect's corner radius: rx, or ry when only that is given. */\nfunction radiusOf(element: Element): number {\n const rx = Number.parseFloat(element.getAttribute(\"rx\") ?? \"\");\n const ry = Number.parseFloat(element.getAttribute(\"ry\") ?? \"\");\n const radius = Number.isFinite(rx) ? rx : ry;\n return Number.isFinite(radius) && radius > 0 ? radius : 0;\n}\n\n/** px, rounded to 0.001 as path data and a rect's box are. */\nfunction round(value: number): number {\n return Math.round(value * 1000) / 1000;\n}\n\nfunction tryInvert(m: Matrix): Matrix | undefined {\n try {\n return invert(m);\n } catch {\n return undefined;\n }\n}\n\nfunction isIdentity(m: Matrix): boolean {\n return Math.abs(m[0] - 1) < 1e-9 && Math.abs(m[1]) < 1e-9 && Math.abs(m[2]) < 1e-9 && Math.abs(m[3] - 1) < 1e-9 && Math.abs(m[4]) < 1e-6 && Math.abs(m[5]) < 1e-6;\n}\n\n/** A part's value changed, or the mark gained or lost a segment. Values compare like ===, but NaN equals NaN. */\nfunction valuesChanged<D>(from: readonly Part<D>[], to: readonly Part<D>[]): boolean {\n if (from.length !== to.length) return true;\n const before = new Map(from.map((part) => [part.series, part.value]));\n return to.some((part) => {\n const was = before.get(part.series);\n return !before.has(part.series) || !(was === part.value || Object.is(was, part.value));\n });\n}\n\n/** What the adapter can see of a change in values without `value`: a mark's length, or its segments' lengths. */\nfunction lengthsChanged(from: MarkGeometry, to: MarkGeometry): boolean {\n const a = from.segments ?? [];\n const b = to.segments ?? [];\n if (Math.abs(from.length - to.length) > 0.01 || a.length !== b.length) return true;\n return a.some((segment, i) => segment.key !== b[i]!.key || Math.abs(segment.length - b[i]!.length) > 0.01);\n}\n\n/** The page's samples changed, though the geometry and the row may not have. */\nfunction samplesChanged(from: readonly Sample[], to: readonly Sample[]): boolean {\n const sameAt = (a: Sample[\"at\"], b: Sample[\"at\"]): boolean => a === b || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime());\n return from.length !== to.length || from.some((a, i) => a.t !== to[i]!.t || a.value !== to[i]!.value || !sameAt(a.at, to[i]!.at));\n}\n\n/** Whether a mark moved: its outline, its segments, its thickness (which a line's stroke width changes alone), or its labels' boxes. */\nfunction geometryChanged(from: MarkGeometry, to: MarkGeometry): boolean {\n if (from.outline.d !== to.outline.d || from.thickness !== to.thickness || labelsMoved(from, to)) return true;\n const a = from.segments ?? [];\n const b = to.segments ?? [];\n return a.length !== b.length || a.some((segment, i) => segment.key !== b[i]!.key || segment.outline.d !== b[i]!.outline.d);\n}\n","// Vega and Vega-Lite views through expressive(): the marks Vega's SVG renderer draws, described from\n// its scenegraph rather than from the DOM. Each item Vega renders is bound to its element as\n// `__data__` (an internal the adapter spike found, so the tests pin Vega's version), the row is\n// `item.datum`, and the item's numbers give the geometry: rects become bars, arcs slices, symbols\n// points and lines lines, whose items give each vertex with its row, so samples come with them. A\n// line breaks where Vega leaves a point out, as Vega-Lite does at a missing value.\n// Duck-typed on the View: nothing here imports Vega, so it stays a dev dependency.\n\nimport type { Baseline, MarkGeometry, Matrix, Point, Rect, Sample } from \"../../core\";\nimport { defaultClock, matrix, samplesAlong } from \"../../core\";\nimport { describeArc } from \"../../core/geometry/describe/arc\";\nimport { describeLine } from \"../../core/geometry/describe/line\";\nimport { describePoint } from \"../../core/geometry/describe/point\";\nimport { report } from \"../../core/report\";\nimport { linkable, portOf } from \"../link\";\nimport type { ChartEnv } from \"../shell/setup\";\nimport { baselines, describeRects, union, visualOrder, type RectPart } from \"./bars\";\nimport { expressive } from \"./expressive\";\nimport { commonAncestor, rootOf } from \"./source\";\nimport { between, boxIn, screenMatrices } from \"./space\";\nimport type { Attachment, ExpressiveOptions } from \"./types\";\n\n/**\n * What fromVegaView() uses of a Vega View: its renderer, its scenegraph and the element it renders\n * into. The scenegraph is read as `{ root }` (what Vega returns) or as the root mark itself (what\n * vega-typings declare), so a View fits whichever the types say.\n */\nexport interface VegaViewLike {\n renderer(): string;\n scenegraph(): object;\n container(): Element | null;\n}\n\n/** A mark in Vega's scenegraph: its type, its name, and its items. */\nexport interface VegaMark {\n readonly marktype?: string;\n readonly name?: string;\n readonly items?: readonly VegaItem[];\n}\n\n/** An item of a Vega mark, as its encoders left it. A group's items hold the marks inside it. */\nexport interface VegaItem {\n readonly mark?: VegaMark;\n readonly datum?: unknown;\n readonly items?: readonly VegaMark[];\n readonly x?: number;\n readonly y?: number;\n readonly width?: number;\n readonly height?: number;\n readonly startAngle?: number;\n readonly endAngle?: number;\n readonly innerRadius?: number;\n readonly outerRadius?: number;\n readonly size?: number;\n readonly strokeWidth?: number;\n readonly cornerRadius?: number;\n /** False for a line's point Vega leaves out, which breaks the line there. */\n readonly defined?: boolean;\n /** How a line is drawn between its points: only \"linear\" (or unset) can be read. */\n readonly interpolate?: string;\n}\n\n/** A value for data effects: alone, or with where it is along x (`at`), which threshold matches series by. */\nexport type VegaSample = number | { readonly value: number; readonly at?: string | number | Date };\n\nexport interface VegaOptions<D> extends Omit<ExpressiveOptions<D>, \"datum\" | \"geometry\" | \"watch\"> {\n /** The Vega mark to read, by name. Default \"marks\", the name Vega-Lite gives a chart's data mark. */\n readonly mark?: string;\n /**\n * For data effects: the value an item's row shows, and optionally where it is along x. A line gets a\n * sample at each of its points, a bar from 0 at its baseline to its value (a stack's segments each over\n * their own range), a slice from 0 to its value, and a point its value. `samples` replaces this.\n * Unless `value` is given, it's also what each element shows (a line: every point's), so a re-render\n * that only moves marks, such as a resize, isn't an update.\n */\n readonly sample?: (row: D) => VegaSample;\n}\n\n/** fromVegaView()'s attachment: refresh() reads the View again (it refreshes itself after each render too). */\nexport interface VegaAttachment<D> extends Omit<Attachment<D>, \"refresh\"> {\n refresh(): void;\n}\n\nconst MARK_TYPES = [\"line\", \"rect\", \"arc\", \"symbol\"] as const;\ntype MarkType = (typeof MARK_TYPES)[number];\n\n/**\n * Attributes Vega writes when it draws marks somewhere new (a data change, a resize, a signal), and\n * `stroke-width`, which a line's thickness, and so its decorations and focus ring, are read from.\n */\nconst DRAWN = [\"d\", \"transform\", \"x\", \"y\", \"width\", \"height\", \"stroke-width\"];\n\n/** One read of the View: the elements to attach, in visual order, and each mark's geometry and samples. */\ninterface ViewRead {\n readonly root: SVGSVGElement | undefined;\n readonly elements: readonly Element[];\n readonly items: ReadonlyMap<Element, VegaItem>;\n readonly geometry: ReadonlyMap<string, MarkGeometry>;\n readonly samples: ReadonlyMap<MarkGeometry, readonly Sample[]>;\n /** What each element shows, from `sample`: a line's every point, so a resize isn't an update. */\n readonly values: ReadonlyMap<Element, string>;\n}\n\n/** A read being made. */\ninterface Reading {\n readonly root: SVGSVGElement;\n readonly elements: Element[];\n readonly items: Map<Element, VegaItem>;\n readonly geometry: Map<string, MarkGeometry>;\n readonly samples: Map<MarkGeometry, readonly Sample[]>;\n readonly values: Map<Element, string>;\n}\n\n/**\n * Effects on a Vega or Vega-Lite chart rendered as SVG: reads the named mark's items from the View's\n * scenegraph and attaches to the elements Vega drew for them, as expressive() would with `datum` and\n * `geometry` written for Vega. It reads the View again after every render that moves or replaces\n * those elements (a data change, a resize), so the page never calls refresh().\n */\nexport function fromVegaView<D = Record<string, unknown>>(view: VegaViewLike, options: VegaOptions<D>, env: ChartEnv): VegaAttachment<D> {\n checkView(view);\n if (typeof options !== \"object\" || options === null || typeof options.key !== \"function\") {\n throw new TypeError(\"fromVegaView needs options with a key: { key: (d) => d.series }. Marks are matched by key.\");\n }\n const name = options.mark ?? \"marks\";\n if (typeof name !== \"string\" || name === \"\") throw new TypeError(`fromVegaView: mark must be a mark's name, got ${String(name)}.`);\n if (options.sample !== undefined && typeof options.sample !== \"function\") throw new TypeError(\"fromVegaView: sample must be a function.\");\n\n let current = readView();\n const { mark: _mark, sample: _sample, ...rest } = options;\n const attachment = expressive<D>(\n current.elements,\n {\n ...rest,\n datum: (element) => itemOf(element).datum as D,\n geometry: (_element, _datum, key) => {\n const geometry = current.geometry.get(key);\n if (!geometry) throw new TypeError(`fromVegaView: no geometry for \"${key}\". Its key must be the same for every item of a mark.`);\n return geometry;\n },\n ...(options.samples || !options.sample ? {} : { samples: (_datum: D, mark: MarkGeometry) => current.samples.get(mark) ?? [] }),\n ...(options.value || !options.sample ? {} : { value: (_datum: D, element: Element) => current.values.get(element) })\n },\n env\n );\n\n // Vega's data and resize listeners run before it renders, so the elements they'd read are the old\n // ones. What Vega draws is watched instead, and read again on the next frame.\n const clock = env.clock ?? defaultClock;\n let observed: SVGSVGElement | undefined;\n let stopFrame: (() => void) | undefined;\n let destroyed = false;\n const observer = typeof MutationObserver === \"function\" ? new MutationObserver((records) => records.some(drawn) && schedule()) : undefined;\n observe(current.root);\n\n function itemOf(element: Element): VegaItem {\n const item = current.items.get(element);\n if (!item) throw new TypeError(\"fromVegaView: an element that isn't one of the View's items.\");\n return item;\n }\n\n function readView(): ViewRead {\n const marks = findMarks(sceneRoot(view), name);\n const type = markType(marks, name, view);\n const host = view.container();\n const root = (host?.localName === \"svg\" ? host : host?.querySelector(\"svg\")) as SVGSVGElement | null | undefined;\n const empty: ViewRead = { root: root ?? undefined, elements: [], items: new Map(), geometry: new Map(), samples: new Map(), values: new Map() };\n if (!type || !root) return empty;\n\n // The element Vega drew for each item: a line's one path is bound to its first item, which may be\n // one it leaves out. A line with nothing to draw has no mark.\n const wanted = new Set<unknown>(type === \"line\" ? marks.flatMap((mark) => (mark.items?.[0] && drawsLine(mark.items[0]) ? [mark.items[0]] : [])) : marks.flatMap((mark) => mark.items ?? []));\n const items = new Map<Element, VegaItem>();\n for (const element of Array.from(root.querySelectorAll(\"*\"))) {\n const bound = (element as Element & { __data__?: unknown }).__data__;\n if (wanted.has(bound)) items.set(element, bound as VegaItem);\n }\n const elements = [...items.keys()];\n if (elements.length === 0) return empty;\n\n const svg = rootOf(elements);\n const common = commonAncestor(elements, svg);\n const screen = screenMatrices();\n const toCommon = (element: Element): Matrix => between(common, element.parentElement ?? svg, svg, screen);\n const keyOf = (element: Element): string => String(options.key(items.get(element)!.datum as D, element));\n const seriesOf = (element: Element): string | undefined => (options.segment ? String(options.segment(items.get(element)!.datum as D, element)) : undefined);\n\n const read: Reading = { root: svg, items, elements, geometry: new Map(), samples: new Map(), values: new Map() };\n if (options.sample) {\n // A line's every point, with a point left out as empty, so a value that goes missing changes it.\n for (const [element, item] of items) {\n const points = type === \"line\" ? lineItems(item) : [item];\n read.values.set(element, points.map((point) => (point.defined === false ? \"\" : valueOf(point).value)).join(\",\"));\n }\n }\n if (type === \"rect\") return readBars(read, toCommon, keyOf, seriesOf);\n for (const element of elements) {\n const item = items.get(element)!;\n const key = keyOf(element);\n if (read.geometry.has(key)) continue; // a second part of a mark: expressive() says whether that's allowed\n const m = toCommon(element);\n const geometry = type === \"line\" ? lineOf(key, element, item, m) : type === \"arc\" ? sliceOf(key, item, m) : pointOf(key, item, m);\n read.geometry.set(key, geometry);\n if (options.sample) read.samples.set(geometry, type === \"line\" ? lineSamples(geometry, item, m) : oneSample(geometry, item, type));\n }\n return read;\n }\n\n /** Bars from rect items, grouped by key into stacks (named by `segment`), in visual order. */\n function readBars(read: Reading, toCommon: (element: Element) => Matrix, keyOf: (element: Element) => string, seriesOf: (element: Element) => string | undefined): ViewRead {\n const groups = new Map<string, { element: Element; part: RectPart }[]>();\n for (const element of read.elements) {\n const item = read.items.get(element)!;\n const key = keyOf(element);\n const part: RectPart = { box: boxIn(toCommon(element), boxOf(item)), series: seriesOf(element), radius: Math.max(0, item.cornerRadius ?? 0) };\n const group = groups.get(key);\n if (group) group.push({ element, part });\n else groups.set(key, [{ element, part }]);\n }\n const keys = [...groups.keys()];\n const boxes = keys.map((key) => union(groups.get(key)!.map((p) => p.part.box)));\n const edges: Baseline[] = baselines(boxes, options.baseline ?? \"auto\");\n const elements: Element[] = [];\n for (const i of visualOrder(boxes, edges)) {\n const key = keys[i]!;\n const parts = groups.get(key)!;\n const { geometry, order } = describeRects(key, parts.map((p) => p.part), edges[i]!);\n read.geometry.set(key, geometry);\n // From the baseline, so the mark's first part (its row, its focus) is the one at the baseline.\n elements.push(...order.map((j) => parts[j]!.element));\n if (options.sample) {\n const values = order.map((j) => valueOf(read.items.get(parts[j]!.element)!).value);\n const total = values.reduce((sum, v) => sum + v, 0);\n read.samples.set(geometry, [{ t: 0, value: 0 }, { t: 1, value: total }]);\n let reached = 0;\n (geometry.segments ?? []).forEach((segment, n) => {\n const from = reached;\n reached += values[n] ?? 0;\n read.samples.set(segment, [{ t: 0, value: from }, { t: 1, value: reached }]);\n });\n }\n }\n return { ...read, elements };\n }\n\n function valueOf(item: VegaItem): { value: number; at?: string | number | Date } {\n const given = options.sample!(item.datum as D);\n const sample = typeof given === \"number\" ? { value: given } : given;\n if (typeof sample !== \"object\" || sample === null || !Number.isFinite(sample.value)) {\n throw new RangeError(`fromVegaView: sample must give a finite number, or { value, at }, got ${JSON.stringify(given)}.`);\n }\n return sample.at === undefined ? { value: sample.value } : { value: sample.value, at: sample.at };\n }\n\n /** A line's samples, one per point it draws, where each point is along the walk, with `gapBefore` after each gap. */\n function lineSamples(geometry: MarkGeometry, first: VegaItem, m: Matrix): Sample[] {\n return samplesAlong(\n geometry,\n pointsOf(first).map(({ item, point }) => ({ ...matrix.apply(m, point), ...valueOf(item) }))\n );\n }\n\n function oneSample(geometry: MarkGeometry, item: VegaItem, type: MarkType): Sample[] {\n const { value, at } = valueOf(item);\n const end = at === undefined ? { t: 1, value } : { t: 1, value, at };\n return type === \"symbol\" ? [{ ...end, t: 0 }] : geometry.length > 0 ? [{ t: 0, value: 0 }, end] : [{ ...end, t: 0 }];\n }\n\n // ── Following the View ─────────────────────────────────────────────────────\n\n /** A change Vega made to its marks: not one the adapter made in its overlay, nor its own attributes. */\n function drawn(record: MutationRecord): boolean {\n const overlay = observed?.querySelector(\":scope > .ec-overlay\");\n const ours = (node: Node): boolean => node === overlay || (overlay?.contains(node) ?? false);\n if (ours(record.target)) return false;\n if (record.type === \"childList\") return [...Array.from(record.addedNodes), ...Array.from(record.removedNodes)].some((node) => !ours(node));\n return true;\n }\n\n function schedule(): void {\n if (stopFrame || destroyed) return;\n const stop = clock.onFrame(() => {\n stop();\n stopFrame = undefined;\n try {\n refresh();\n } catch (error) {\n report(error);\n }\n });\n stopFrame = stop;\n }\n\n function observe(root: SVGSVGElement | undefined): void {\n if (!observer || root === observed) return;\n observer.disconnect();\n observed = root;\n if (root) observer.observe(root, { subtree: true, childList: true, attributes: true, attributeFilter: DRAWN });\n }\n\n function refresh(): void {\n if (destroyed) return;\n const next = readView();\n const previous = current;\n current = next;\n try {\n attachment.refresh(next.elements);\n } catch (error) {\n current = previous;\n throw error;\n }\n observe(next.root);\n }\n\n // Linked through the attachment's hover.\n return linkable(portOf(attachment)!, {\n refresh,\n update: attachment.update,\n on: attachment.on,\n marks: attachment.marks,\n focus: attachment.focus,\n leave: attachment.leave,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n observer?.disconnect();\n stopFrame?.();\n stopFrame = undefined;\n attachment.destroy();\n }\n });\n}\n\nfunction checkView(view: VegaViewLike): void {\n if (typeof view !== \"object\" || view === null || typeof view.renderer !== \"function\" || typeof view.scenegraph !== \"function\" || typeof view.container !== \"function\") {\n throw new TypeError(\"fromVegaView needs a Vega View: new vega.View(runtime, { renderer: \\\"svg\\\", container }), or vega-embed's result.view.\");\n }\n const renderer = view.renderer();\n if (renderer !== \"svg\") {\n throw new TypeError(\n `fromVegaView: the View renders with \"${renderer}\", which draws no SVG elements to attach to. Use renderer: \"svg\" (vega-embed's default; a bare vega.View uses canvas).`\n );\n }\n}\n\nfunction sceneRoot(view: VegaViewLike): VegaMark {\n const graph = view.scenegraph() as { readonly root?: VegaMark } & VegaMark;\n return graph.root ?? graph;\n}\n\n/** Every mark of that name in the scenegraph: Vega-Lite draws one per series for a line with a colour field. */\nfunction findMarks(root: VegaMark, name: string): VegaMark[] {\n const found: VegaMark[] = [];\n const visit = (mark: VegaMark): void => {\n if (mark.name === name && mark.marktype !== \"group\") found.push(mark);\n if (mark.marktype !== \"group\") return;\n for (const item of mark.items ?? []) for (const inner of item.items ?? []) visit(inner);\n };\n visit(root);\n return found;\n}\n\nfunction markType(marks: readonly VegaMark[], name: string, view: VegaViewLike): MarkType | undefined {\n if (marks.length === 0) {\n const names = namesIn(sceneRoot(view));\n // Before the View first runs there are no marks yet; it's read again once Vega draws them.\n if (names.length === 0) return undefined;\n throw new RangeError(`fromVegaView: the View has no mark named \"${name}\". Its named marks: ${names.map((n) => `\"${n}\"`).join(\", \")}.`);\n }\n const type = marks[0]!.marktype;\n if (!marks.every((mark) => mark.marktype === type) || !MARK_TYPES.includes(type as MarkType)) {\n throw new TypeError(`fromVegaView: \"${name}\" is a ${String(type)} mark. Rects, arcs, symbols and lines can be read; describe others with expressive()'s geometry option.`);\n }\n return type as MarkType;\n}\n\nfunction namesIn(root: VegaMark): string[] {\n const names = new Set<string>();\n const visit = (mark: VegaMark): void => {\n if (mark.name && mark.marktype !== \"group\") names.add(mark.name);\n for (const item of mark.items ?? []) for (const inner of item.items ?? []) visit(inner);\n };\n visit(root);\n return [...names];\n}\n\n/** A line's items, from the item its path is bound to: its first. */\nconst lineItems = (first: VegaItem): readonly VegaItem[] => first.mark?.items ?? [first];\n\n/** Whether a line has a point to draw: Vega draws nothing for one whose every item is left out. */\nconst drawsLine = (first: VegaItem): boolean => lineItems(first).some((item) => item.defined !== false);\n\n/**\n * A line's points, from its mark's items. Lines are straight between their points (M4 decision 5),\n * so a curve Vega interpolates (monotone, basis, step and the rest; it reads the first item's) would\n * be described as a different path from the one drawn, and throws instead. A point Vega leaves out\n * (`defined: false`, as Vega-Lite does for a missing value) is left out here too, and the next point\n * Vega draws starts a new run after a gap (`gapBefore`). Points left out before the first or after the\n * last only shorten the line.\n */\nfunction pointsOf(first: VegaItem): { item: VegaItem; point: Point; gapBefore: boolean }[] {\n const items = lineItems(first);\n const interpolate = items[0]?.interpolate;\n if (interpolate !== undefined && interpolate !== \"linear\") {\n throw new TypeError(\n `fromVegaView: a line is drawn with interpolate \"${interpolate}\", but only straight lines can be read. Use interpolate \"linear\" (the default), or describe the curve with expressive()'s geometry option.`\n );\n }\n const points: { item: VegaItem; point: Point; gapBefore: boolean }[] = [];\n let gap = false;\n for (const item of items) {\n if (item.defined === false) {\n gap = points.length > 0;\n continue;\n }\n points.push({ item, point: { x: number(item.x), y: number(item.y) }, gapBefore: gap });\n gap = false;\n }\n return points;\n}\n\n/** A line through the points Vega draws, with a break where it leaves some out. */\nfunction lineOf(key: string, element: Element, first: VegaItem, m: Matrix): MarkGeometry {\n const width = first.strokeWidth ?? Number.parseFloat(element.getAttribute(\"stroke-width\") ?? \"1\");\n const points = pointsOf(first);\n const breaks = points.flatMap((p, i) => (p.gapBefore ? [i] : []));\n return describeLine({\n key,\n series: key,\n points: points.map(({ point }) => matrix.apply(m, point)),\n ...(breaks.length > 0 ? { breaks } : {}),\n width: (Number.isFinite(width) ? width : 1) * scaleOf(m)\n });\n}\n\n/** A slice: Vega-Lite's arcs can run anticlockwise (start > end), so the angles are put in order. */\nfunction sliceOf(key: string, item: VegaItem, m: Matrix): MarkGeometry {\n const center = matrix.apply(m, { x: number(item.x), y: number(item.y) });\n const s = scaleOf(m);\n const [start, end] = [number(item.startAngle), number(item.endAngle)].sort((a, b) => a - b) as [number, number];\n return describeArc({ key, cx: center.x, cy: center.y, inner: number(item.innerRadius) * s, outer: number(item.outerRadius) * s, start, end });\n}\n\n/** A point: Vega's symbol `size` is its area in px², 64 by default. */\nfunction pointOf(key: string, item: VegaItem, m: Matrix): MarkGeometry {\n const center = matrix.apply(m, { x: number(item.x), y: number(item.y) });\n return describePoint({ key, x: center.x, y: center.y, r: Math.sqrt(Math.max(0, item.size ?? 64) / Math.PI) * scaleOf(m) });\n}\n\n/** A rect item's box in its group's coordinates, with a negative width or height turned round. */\nfunction boxOf(item: VegaItem): Rect {\n const x = number(item.x);\n const y = number(item.y);\n const width = number(item.width);\n const height = number(item.height);\n return { x: Math.min(x, x + width), y: Math.min(y, y + height), width: Math.abs(width), height: Math.abs(height) };\n}\n\nfunction scaleOf(m: Matrix): number {\n return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n}\n\nfunction number(value: number | undefined): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n","// A chart switch: views of the same data in one place, one shown at a time, and a transition effect\n// that turns each mark of one view into its own mark in the next, as the lab's donut turns into\n// columns. It reads only what a chart's handle reports (marks and labels by key, focus by key, its\n// <svg>, its events and its hover for links), so it never names a chart type, and it plays whatever\n// transition effect it's given: the composition root (src/index.ts) fills in morph() when the page\n// leaves it out.\n//\n// A switch runs along one line, s, from 0 (the view it began in, `a`) to 1 (the view it went to,\n// `b`). The pairs morph at s; the labels move and swap their text, the unmatched marks fade, and the\n// views' other parts fade, each as a function of s, as the lab draws its centre and baseline from\n// its one `t`. So a switch back mid-way plays the same picture backwards from where it is.\n//\n// In a link (./link.ts), the switch's hover is the view on show's: its chart's own hovers go to the\n// link while it rests, and the link's hover shows in it. While a switch plays, neither view can be\n// reached, so a link's hover waits for it to land and shows in the new view.\n\nimport { defaultClock, easeInOutCubic, linear, matrix, tween, type Clock, type MarkGeometry, type Matrix, type MotionEnv, type Point, type TransitionEffect, type Tween } from \"../core\";\nimport { unease } from \"../core/easing\";\nimport { formatPath, parsePath, transformPath } from \"../core/geometry/path\";\nimport { isTransitionEffect, playTransition, type Transition, type TransitionPair, type TransitionSurface } from \"../core/transition\";\nimport { between, boxIn } from \"./adapter/space\";\nimport { chartAnnouncer, type Announcer } from \"./announce\";\nimport { toColorAssignment, type ColorAssignment } from \"./colors\";\nimport { linkable, portOf, type LinkListener, type LinkPort, type RowsOf } from \"./link\";\nimport { svgLayer } from \"./render/layer\";\nimport { setAttributes, setStyles, svgElement } from \"./render/svg\";\nimport { injectStyles, markColorStyles, seriesColors } from \"./render/theme\";\nimport { resolveTarget, type ChartEnv } from \"./shell/setup\";\nimport type { ChartLabel, MarkEvents } from \"./types\";\n\n/**\n * What a chart switch uses of each view's chart. A reference chart's handle has all of it: its\n * `<svg>` (which takes `ec-morphing` while its marks morph in the switch's overlay), its marks and\n * labels as drawn, focus by key, leave() to end its hover, and destroy(). A reference chart also\n * has on(), which the switch's on() hears, and a hover a link can drive; a view without them isn't\n * heard and isn't linked.\n */\nexport interface ChartSwitchView {\n readonly element: SVGSVGElement;\n marks(): readonly MarkGeometry[];\n labels(): readonly ChartLabel[];\n focus(key: string): void;\n leave(): void;\n destroy(): void;\n}\n\n/**\n * Draws one view's chart in `container` and returns it. `colors` is the switch's assignment: pass it\n * to the chart as its `colors`, so a key has the same colour in every view and in the overlay.\n */\nexport type ChartSwitchViewFactory = (container: HTMLElement, colors: ColorAssignment) => ChartSwitchView;\n\n/** The views by name, each a function that draws its chart. */\nexport type ChartSwitchViews = Readonly<Record<string, ChartSwitchViewFactory>>;\n\n/** A view's name. */\nexport type ChartSwitchViewName<T extends ChartSwitchViews> = keyof T & string;\n\n/** The rows of the views' charts, as a union: what the switch's events carry, and what a link's `by` reads. A view that may be left out counts when it's there. */\ntype ViewRows<T extends ChartSwitchViews> = RowsOf<ReturnType<NonNullable<T[ChartSwitchViewName<T>]>>>;\n\nexport interface ChartSwitchOptions<T extends ChartSwitchViews> {\n /** The views by name. Each is drawn once, when the switch is created, in a container of its own; they share one grid cell. */\n readonly views: T;\n /** The view shown first. */\n readonly initial: NoInfer<ChartSwitchViewName<T>>;\n /**\n * Plays each pair of marks, matched by key. Default: morph(). The switch draws the labels and the\n * fades, and starts a reverse, on morph's schedule: 950 ms base with transition timing, eased in\n * and out (easeInOutCubic), and from `start` the rest of a full run's time. A transition effect\n * can't report how far its shapes have got, so one with other timing still plays, but its shapes\n * drift from the labels and a switch back can jump.\n */\n readonly transition?: TransitionEffect;\n /** Palette slots by key, shared by every view (each view's function is given it). Default: a new assignment. */\n readonly colors?: ColorAssignment | Readonly<Record<string, number>>;\n /** A polite live region that says the new view's label (its chart's `label`) after each switch. Default false. */\n readonly announce?: boolean;\n}\n\nexport interface ChartSwitch<T extends ChartSwitchViews> {\n /** The view shown, or the one a switch is heading for. */\n readonly current: ChartSwitchViewName<T>;\n /**\n * Switches to `view`: each mark morphs into the mark with its key, by the motion mode. Resolves\n * when the switch has landed, or as soon as another show() replaces it. A show() back to the view\n * a switch is leaving reverses it from where the shapes are; one to a third view lands the switch\n * first. With motion off, the switch has landed when show() returns. Rejects for an unknown view.\n * One a `leave` listener calls as the old view's hover ends runs once the switch has begun.\n */\n show(view: ChartSwitchViewName<T>): Promise<void>;\n /** The chart a view's function returned: for update(), on() and the rest. */\n chart<K extends ChartSwitchViewName<T>>(view: K): ReturnType<T[K]>;\n /**\n * Listens for the mark events of the view on show (`current`), as its chart's on() does; returns\n * the unsubscribe. The other views' events aren't heard. A switch makes the view it's heading for\n * the one heard once the old view's hover has ended, so that hover's leave is heard too.\n */\n on<K extends keyof MarkEvents<ViewRows<T>>>(type: K, listener: (event: MarkEvents<ViewRows<T>>[K]) => void): () => void;\n /** The marks of the view on show (`current`), as its chart's marks() gives them: while a switch plays, the view it's heading for's. */\n marks(): readonly MarkGeometry[];\n /**\n * Ends the hover of the view on show (`current`), as its chart's leave() does: its own, or a\n * link's. A link's hover then shows in the switch again with the link's next hover, not when a\n * switch lands.\n */\n leave(): void;\n /** Ends any switch, destroys every view's chart and removes everything the switch added. */\n destroy(): void;\n}\n\n/** The lab's morph: 950 ms base, with transition timing, in one stage. */\nconst DURATION = 950;\n/** The old view's other parts are gone by here. */\nconst OUT_BY = 0.4;\n/** The new view's other parts start to show here; labels swap their text, and unmatched marks hand over. */\nconst HALF = 0.5;\n\ninterface View {\n readonly name: string;\n readonly container: HTMLDivElement;\n readonly chart: ChartSwitchView;\n /** Its chart's hover as a link drives it: a reference chart's. */\n readonly port: LinkPort | undefined;\n}\n\n/** Where focus was when a switch began, if it was in the view it left: on a mark (its key) or elsewhere. */\ninterface FocusMemory {\n readonly key: string | undefined;\n}\n\n/** What a switch draws in its overlay besides the pairs, at each s. */\ninterface Scene {\n draw(s: number): void;\n clear(): void;\n}\n\ninterface Switch {\n /** Where s is 0: the view the switch began in. */\n readonly a: View;\n /** Where s is 1: the view it went to. */\n readonly b: View;\n /** Heading for b. A show() back flips it. */\n forward: boolean;\n /** From a to b, in b's order; `reversed` is the same pairs from b to a, in the same order, so the overlay stacks the same way back. */\n readonly pairs: readonly TransitionPair[];\n readonly reversed: readonly TransitionPair[];\n readonly scene: Scene;\n readonly focus: FocusMemory | undefined;\n /** The run's eased progress from where it began to where it's heading, as last drawn: the shapes' progress, as morph draws them. */\n progress: number;\n transition: Transition | undefined;\n driver: Tween | undefined;\n /** Counts runs, so a run that was replaced or landed doesn't land the switch. */\n run: number;\n /** What the latest show() returned, and its resolve. */\n done: Promise<void>;\n settle: () => void;\n}\n\n/**\n * Views of the same data in `target` (an element or a selector), one shown at a time. Each view's\n * chart is drawn once, in its own container; the containers share one grid cell, so a view keeps\n * its layout while it's hidden. `show(view)` hides both views' marks and plays `transition` on each\n * pair of marks with the same key in an overlay above them, while the labels move to their places\n * in the new view and swap their text half way, marks with no partner fade, and the old view's other\n * parts (axes, centre text, legend, table) fade out as the new one's fade in.\n */\nexport function chartSwitch<T extends ChartSwitchViews>(\n target: string | Element,\n options: ChartSwitchOptions<T> & { readonly transition: TransitionEffect },\n env: Pick<ChartEnv, \"icons\" | \"motion\" | \"clock\">\n): ChartSwitch<T> {\n const host = resolveTarget(target, \"chartSwitch\");\n const names = checkOptions(options);\n const effect = options.transition;\n const colors = toColorAssignment(options.colors);\n const motion = env.motion;\n const clock = env.clock ?? defaultClock;\n const doc = host.ownerDocument;\n injectStyles(doc);\n\n const wrapper = doc.createElement(\"div\");\n wrapper.className = \"ec-switch\";\n host.appendChild(wrapper);\n const views = new Map<string, View>();\n try {\n for (const name of names) {\n const container = doc.createElement(\"div\");\n container.className = \"ec-switch-view\";\n container.setAttribute(\"data-view\", name);\n wrapper.appendChild(container);\n // Hidden before its chart is drawn, so it never shows; it still lays out at the cell's width.\n setActive(container, name === options.initial);\n const chart: unknown = options.views[name]!(container, colors);\n if (!isView(chart, container)) {\n (chart as Partial<ChartSwitchView> | null)?.destroy?.();\n throw new TypeError(`chartSwitch: views.${name} must return the chart it draws in the container it's given (with element, marks(), labels(), focus(), leave() and destroy()), such as donutChart(container, { ... }).`);\n }\n views.set(name, { name, container, chart, port: portOf(chart) });\n }\n } catch (error) {\n for (const view of views.values()) view.chart.destroy();\n wrapper.remove();\n throw error;\n }\n\n // Above the views: the pairs, the marks fading, and the labels, in px from the cell's top left.\n // `ec-chart` gives the copied labels the stylesheet's text sizes.\n const overlay = svgElement(\"svg\", { class: \"ec-chart ec-switch-overlay\", \"aria-hidden\": \"true\" }, wrapper);\n const fadesLayer = svgElement(\"g\", { class: \"ec-switch-fades\" }, overlay);\n const runsLayer = svgElement(\"g\", { class: \"ec-switch-runs\" }, overlay);\n const labelsLayer = svgElement(\"g\", { class: \"ec-switch-labels\" }, overlay);\n // Made now: screen readers miss text in a region that appears with it.\n const announcer: Announcer | undefined = options.announce ? chartAnnouncer(overlay) : undefined;\n\n /** Each pair's run draws in a group of its own, in its key's colour, stacked by the pair's place. */\n const orders = new WeakMap<Element, number>();\n const surface: TransitionSurface = {\n group(key, order) {\n const group = svgElement(\"g\", { class: \"ec-run\", \"data-key\": key }, runsLayer);\n setStyles(group, markColorStyles(seriesColors(colors.slot(key))));\n orders.set(group, order);\n const above = Array.from(runsLayer.children).find((child) => (orders.get(child) ?? -Infinity) > order);\n runsLayer.insertBefore(group, above ?? null);\n return { ...svgLayer(group), clear: () => group.remove() };\n }\n };\n\n let current: string = options.initial;\n let active: Switch | undefined;\n let destroyed = false;\n /** The link the switch is in, which hears the view on show's own hovers. */\n let linked: LinkListener | undefined;\n /** The view whose own hover the link heard last. */\n let told: View | undefined;\n /** Whether the link has a hover from another source for the switch: shown in the view on show, or once a switch lands. */\n let held = false;\n /** While a switch's old view's hover ends: the show() calls its listeners made, run once the switch has begun. */\n let opening: (() => void)[] | undefined;\n\n // Turning motion off mid-switch lands it, as every animation jumps to its end.\n const stopMotion = motion.subscribe(() => {\n if (motion.mode === \"off\" && active) land(active, true);\n });\n\n // A resize lands a switch: the charts lay out again, and the shapes it began with are stale. The\n // first observation, which comes after observe(), is the width to compare with.\n let width: number | undefined;\n const observer =\n typeof ResizeObserver === \"function\"\n ? new ResizeObserver((entries) => {\n const next = entries[entries.length - 1]?.contentRect.width ?? 0;\n if (width !== undefined && Math.abs(next - width) < 0.5) return;\n const first = width === undefined;\n width = next;\n if (!first && active) land(active, true);\n })\n : undefined;\n observer?.observe(wrapper);\n\n const view = (name: string): View => views.get(name)!;\n\n /** The element with focus in the switch's document or shadow root. */\n function focused(): Element | null {\n return (wrapper.getRootNode() as Document | ShadowRoot).activeElement ?? null;\n }\n\n /** Read before anything is hidden: a browser may move focus off an element that turns hidden. */\n function readFocus(from: View): FocusMemory | undefined {\n const element = focused();\n if (!element || !from.container.contains(element)) return undefined;\n const keyed = element.closest(\"[data-key]\");\n return { key: keyed && from.chart.element.contains(keyed) ? (keyed.getAttribute(\"data-key\") ?? undefined) : undefined };\n }\n\n /** Focus that was in the old view goes to the same key in the new one, or to its first mark, unless it has moved on outside the switch. */\n function restoreFocus(to: View, memory: FocusMemory | undefined): void {\n if (!memory) return;\n const now = focused();\n if (now && now !== doc.body && now !== doc.documentElement && !wrapper.contains(now)) return;\n const inside = (): boolean => to.chart.element.contains(focused());\n if (memory.key !== undefined) to.chart.focus(memory.key);\n if (inside()) return;\n for (const mark of to.chart.marks()) {\n to.chart.focus(mark.key);\n if (inside()) return;\n }\n }\n\n function say(to: View): void {\n announcer?.say(to.chart.element.getAttribute(\"aria-label\") ?? \"\");\n }\n\n /** The view on show can be reached again: the link's hover, if it has one for the switch, shows in it. */\n function reached(): void {\n if (held) linked?.shown();\n }\n\n function start(from: View, to: View, carried?: { readonly focus: FocusMemory | undefined }): Promise<void> {\n const memory = carried ? carried.focus : readFocus(from);\n // The old view's hover ends as the viewer's would, a link's too, while it's still the view on\n // show, so the switch's on() and its link hear it end. A show() its listeners call waits until\n // the switch has begun, and a destroy() stops it. Focus stays where it is, already read, until\n // the view turns inert, which takes it off in a browser.\n const waiting: (() => void)[] = [];\n opening = waiting;\n try {\n from.chart.leave();\n } finally {\n opening = undefined;\n }\n const done = destroyed ? Promise.resolve() : begin(from, to, memory);\n for (const run of waiting) run();\n return done;\n }\n\n /** Switches from `from` to `to`, its hover ended. */\n function begin(from: View, to: View, memory: FocusMemory | undefined): Promise<void> {\n current = to.name;\n if (motion.mode === \"off\") {\n for (const each of views.values()) setActive(each.container, each === to);\n restoreFocus(to, memory);\n say(to);\n reached();\n return Promise.resolve();\n }\n // Both views' marks and labels hide, and neither can be reached until the switch lands; the\n // new view shows, its other parts faded out.\n for (const each of [from, to]) {\n each.container.classList.remove(\"ec-switch-inactive\");\n each.container.classList.add(\"ec-switching\");\n each.container.setAttribute(\"inert\", \"\");\n each.chart.element.classList.add(\"ec-morphing\");\n }\n const { pairs, scene } = prepare(from, to);\n const { done, settle } = deferred();\n const session: Switch = {\n a: from,\n b: to,\n forward: true,\n pairs,\n reversed: pairs.map(({ from: a, to: b }) => ({ from: b, to: a })),\n scene,\n focus: memory,\n progress: 0,\n transition: undefined,\n driver: undefined,\n run: 0,\n done,\n settle\n };\n active = session;\n play(session, 0);\n return session.done;\n }\n\n /** Plays the pairs toward where the switch is heading, from `begin` in the shapes' progress, and the scene with them. */\n function play(session: Switch, begin: number): void {\n const run = ++session.run;\n if (begin >= 1) {\n land(session, true);\n return;\n }\n const at = (progress: number): void => {\n session.progress = progress;\n session.scene.draw(session.forward ? progress : 1 - progress);\n };\n // The pairs' runs and the switch's own tween start at one time, on the same clock and with\n // morph's timing, so `progress` is the progress morph draws the shapes at, frame by frame, and a\n // reverse begins exactly where they are. An effect can't say how far it has got, so this schedule\n // is the switch's: an effect that keeps to it stays in step.\n const started = startClock(clock);\n session.transition = playTransition(session.forward ? session.pairs : session.reversed, { effect, surface, start: begin, motion, clock: started.clock, icons: env.icons });\n session.driver = drive(begin, at, { clock: started.clock, motion });\n started.release();\n void Promise.all([session.driver.finished, session.transition.finished]).then(([result]) => {\n if (active === session && session.run === run && result === \"done\") land(session, true);\n });\n }\n\n /** A show() back mid-way: the pairs play back from where the shapes are, and so does everything drawn with them. */\n function reverse(session: Switch): Promise<void> {\n session.driver?.cancel();\n session.transition?.clear();\n session.forward = !session.forward;\n current = (session.forward ? session.b : session.a).name;\n session.settle();\n ({ done: session.done, settle: session.settle } = deferred());\n play(session, 1 - session.progress);\n return session.done;\n }\n\n /**\n * Ends the switch where it's heading: the overlay empties, that view's marks show and it becomes\n * the active view, every other view inactive. `settle`: focus follows its key and the new view is\n * announced; a switch landed for one to a third view hands its focus on instead.\n */\n function land(session: Switch, settle: boolean): void {\n if (active !== session) return;\n active = undefined;\n session.run++;\n session.driver?.cancel();\n session.transition?.clear();\n session.scene.clear();\n const to = session.forward ? session.b : session.a;\n for (const each of [session.a, session.b]) {\n each.chart.element.classList.remove(\"ec-morphing\");\n each.container.classList.remove(\"ec-switching\");\n each.container.style.removeProperty(\"opacity\");\n }\n for (const each of views.values()) setActive(each.container, each === to);\n if (settle) {\n restoreFocus(to, session.focus);\n say(to);\n reached();\n }\n session.settle();\n }\n\n /** Both views' marks and labels in overlay px, the pairs matched by key, and what's drawn with them. */\n function prepare(a: View, b: View): { pairs: TransitionPair[]; scene: Scene } {\n const toA = between(overlay, a.chart.element, wrapper);\n const toB = between(overlay, b.chart.element, wrapper);\n const from = a.chart.marks().map((mark) => mapMark(mark, toA));\n const to = b.chart.marks().map((mark) => mapMark(mark, toB));\n const fromByKey = new Map(from.map((mark) => [mark.key, mark]));\n const toKeys = new Set(to.map((mark) => mark.key));\n const pairs = to.flatMap((mark) => {\n const partner = fromByKey.get(mark.key);\n return partner ? [{ from: partner, to: mark }] : [];\n });\n\n const drawings: ((s: number) => void)[] = [];\n // Marks with no partner fade where they stand: out over the first half, in over the second.\n for (const mark of from) if (!toKeys.has(mark.key)) drawings.push(fadeMark(mark, fadeOut));\n for (const mark of to) if (!fromByKey.has(mark.key)) drawings.push(fadeMark(mark, fadeIn));\n\n // Labels match by key and role. A pair moves from one place to the other and swaps its text half\n // way; a label with no partner fades, as a mark does.\n const id = (label: ChartLabel): string => `${label.role}\\n${label.key}`;\n const labelsA = a.chart.labels();\n const labelsB = b.chart.labels();\n const byId = new Map(labelsA.map((label) => [id(label), label]));\n const matched = new Set<string>();\n for (const label of labelsB) {\n const partner = byId.get(id(label));\n if (!partner) continue;\n matched.add(id(label));\n drawings.push(moveLabel(copyLabel(partner, toA), copyLabel(label, toB)));\n }\n for (const label of labelsA) if (!matched.has(id(label))) drawings.push(fadeLabel(copyLabel(label, toA), fadeOut));\n for (const label of labelsB) if (!byId.has(id(label))) drawings.push(fadeLabel(copyLabel(label, toB), fadeIn));\n\n // The views' other parts: the old one's gone by 40% of the way, the new one's in from half way.\n drawings.push((s) => {\n setOpacity(a.container, 1 - clamp(s / OUT_BY));\n setOpacity(b.container, clamp((s - HALF) / (1 - HALF)));\n });\n\n return {\n pairs,\n scene: {\n draw: (s) => {\n for (const draw of drawings) draw(s);\n },\n clear: () => {\n fadesLayer.replaceChildren();\n runsLayer.replaceChildren();\n labelsLayer.replaceChildren();\n }\n }\n };\n }\n\n /** A mark with no partner, drawn as its outline in its key's colour. */\n function fadeMark(mark: MarkGeometry, opacity: (s: number) => number): (s: number) => void {\n const group = svgElement(\"g\", { class: \"ec-switch-fade\", \"data-key\": mark.key }, fadesLayer);\n setStyles(group, markColorStyles(seriesColors(colors.slot(mark.key))));\n svgLayer(group).path(mark.outline.d, mark.outline.closed ? { fill: \"mark\" } : { stroke: \"mark\", width: mark.thickness });\n return (s) => setAttributes(group, { opacity: opacity(s) });\n }\n\n /** A copy of the label's <text> in the overlay, with its classes, and where it sits there. */\n function copyLabel(label: ChartLabel, m: Matrix): { readonly text: SVGTextElement; readonly at: Point } {\n const text = label.element.cloneNode(true) as SVGTextElement;\n for (const name of [\"id\", \"opacity\", \"visibility\", \"aria-hidden\"]) text.removeAttribute(name);\n text.textContent = label.text;\n const at = matrix.apply(m, label);\n setAttributes(text, { x: at.x, y: at.y, \"text-anchor\": label.anchor });\n labelsLayer.appendChild(text);\n return { text, at };\n }\n\n const api: ChartSwitch<T> = {\n get current() {\n return current as ChartSwitchViewName<T>;\n },\n show(name) {\n if (!views.has(name)) return Promise.reject(new TypeError(`chartSwitch: there's no view ${JSON.stringify(name)}. The views are ${names.map((n) => JSON.stringify(n)).join(\", \")}.`));\n if (destroyed) return Promise.resolve();\n const waiting = opening;\n if (waiting) return new Promise<void>((resolve) => waiting.push(() => resolve(api.show(name))));\n const session = active;\n if (!session) return name === current ? Promise.resolve() : start(view(current), view(name));\n const heading = session.forward ? session.b : session.a;\n const leaving = session.forward ? session.a : session.b;\n if (name === heading.name) return session.done;\n if (name === leaving.name) return reverse(session);\n // A third view: this switch lands first, and its focus goes on with the next.\n land(session, false);\n return start(heading, view(name), { focus: session.focus });\n },\n chart(name) {\n const found = views.get(name);\n if (!found) throw new TypeError(`chartSwitch: there's no view ${JSON.stringify(name)}. The views are ${names.map((n) => JSON.stringify(n)).join(\", \")}.`);\n return found.chart as ReturnType<T[typeof name]>;\n },\n on(type, listener) {\n const stops = Array.from(views.values(), (each) => {\n const on = (each.chart as { readonly on?: unknown }).on;\n if (typeof on !== \"function\") return undefined;\n return (on as ViewOn).call(each.chart, type, (event) => {\n if (each.name === current) (listener as (event: unknown) => void)(event);\n });\n });\n return () => {\n for (const stop of stops) stop?.();\n };\n },\n marks: () => view(current).chart.marks(),\n leave() {\n held = false;\n if (!destroyed) view(current).chart.leave();\n },\n destroy() {\n if (destroyed) return;\n destroyed = true;\n const session = active;\n if (session) {\n active = undefined;\n session.run++;\n session.driver?.cancel();\n session.transition?.clear();\n session.scene.clear();\n session.settle();\n }\n stopMotion();\n observer?.disconnect();\n announcer?.destroy();\n // The link hears the switch go before its views' charts go, which it no longer hears.\n const link = linked;\n linked = undefined;\n link?.gone();\n for (const each of views.values()) each.chart.destroy();\n wrapper.remove();\n }\n };\n\n /** Whether the view is on show and can be reached: no switch is playing. */\n const resting = (each: View): boolean => active === undefined && each.name === current;\n\n /** What a view's chart tells the switch's link: the view on show's own hovers, while it rests. */\n function relay(each: View): LinkListener {\n const leave = (): void => {\n if (told !== each) return;\n told = undefined;\n linked?.leave();\n };\n return {\n hover(marks) {\n if (!resting(each)) return;\n told = each;\n linked?.hover(marks);\n },\n leave,\n dismiss() {\n if (resting(each)) linked?.dismiss();\n },\n // Only the switch says it can be reached again.\n shown() {},\n // A view's chart destroyed on its own takes its hover with it.\n gone: leave\n };\n }\n\n // The switch's hover as a link drives it: the view on show's, while it rests. Mid-switch it has no\n // targets, and a link's hover is held until it lands.\n const port: LinkPort = {\n targets: () => (active === undefined ? (view(current).port?.targets() ?? []) : []),\n hover(keys, effects) {\n held = true;\n if (active === undefined) view(current).port?.hover(keys, effects);\n },\n unlink() {\n held = false;\n for (const each of views.values()) each.port?.unlink();\n },\n leave: () => api.leave(),\n listen(listener) {\n if (destroyed) return false;\n linked = listener;\n told = undefined;\n held = false;\n for (const each of views.values()) each.port?.listen(listener && relay(each));\n return true;\n },\n parts: Array.from(views.values()).flatMap((each) => (each.port ? [each.port] : []))\n };\n return linkable(port, api);\n}\n\n/** A view's chart's on(), as a reference chart has it. */\ntype ViewOn = (type: string, listener: (event: unknown) => void) => () => void;\n\n/**\n * A tween with morph's timing, from `begin` in the shapes' eased progress: 950 ms base with\n * transition timing, of which it takes the rest from where easeInOutCubic reaches `begin`, as morph\n * does. `at` gets the eased progress, `begin` itself first.\n */\nfunction drive(begin: number, at: (progress: number) => void, env: MotionEnv): Tween {\n const begun = unease(begin);\n let running: Tween | undefined;\n running = tween(\n {\n duration: DURATION,\n timing: \"transition\",\n ease: linear,\n update: (k) => {\n const u = Math.min(1, begun + k);\n at(k === 0 ? begin : easeInOutCubic(u));\n if (u >= 1 && k < 1) running?.finish();\n }\n },\n env\n );\n return running;\n}\n\n/**\n * The clock, with its time held at one reading until release(): what everything started before then\n * takes as its start. A live clock (performance.now()) moves while the pairs' runs sample their\n * outlines and draw their first frame, so a tween made after them would start a little later\n * (a fraction of a millisecond in Chromium) and lag the shapes. After release() it reads the clock, so a tween an\n * effect starts later starts when it does.\n */\nfunction startClock(clock: Clock): { readonly clock: Clock; release(): void } {\n let held: number | undefined = clock.now();\n return {\n clock: { now: () => held ?? clock.now(), onFrame: (callback) => clock.onFrame(callback) },\n release() {\n held = undefined;\n }\n };\n}\n\n/** The inactive view can't be seen, reached or read, but keeps its layout, so its geometry is ready for a switch. */\nfunction setActive(container: HTMLElement, active: boolean): void {\n container.classList.toggle(\"ec-switch-inactive\", !active);\n container.toggleAttribute(\"inert\", !active);\n if (active) container.removeAttribute(\"aria-hidden\");\n else container.setAttribute(\"aria-hidden\", \"true\");\n}\n\nfunction setOpacity(container: HTMLElement, opacity: number): void {\n container.style.setProperty(\"opacity\", String(Math.round(opacity * 1000) / 1000));\n}\n\n/** A matched label at s: both copies at the same place along the way, the old text before half way and the new from there. */\nfunction moveLabel(a: { readonly text: SVGTextElement; readonly at: Point }, b: { readonly text: SVGTextElement; readonly at: Point }): (s: number) => void {\n return (s) => {\n const x = mix(a.at.x, b.at.x, s);\n const y = mix(a.at.y, b.at.y, s);\n const second = s >= HALF;\n setAttributes(a.text, { x, y, visibility: second ? \"hidden\" : undefined });\n setAttributes(b.text, { x, y, visibility: second ? undefined : \"hidden\" });\n };\n}\n\nfunction fadeLabel(label: { readonly text: SVGTextElement }, opacity: (s: number) => number): (s: number) => void {\n return (s) => setAttributes(label.text, { opacity: opacity(s) });\n}\n\nconst fadeOut = (s: number): number => 1 - clamp(s / HALF);\nconst fadeIn = (s: number): number => clamp((s - HALF) / (1 - HALF));\nconst clamp = (value: number): number => Math.min(1, Math.max(0, value));\n/** Weighted on both sides, as morph mixes, so a switch back puts a label where the switch forward had it. */\nconst mix = (x: number, y: number, s: number): number => x * (1 - s) + y * s;\n\nconst isIdentity = (m: Matrix): boolean => m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1 && m[4] === 0 && m[5] === 0;\n\n/**\n * The mark in another coordinate space: a view's <svg> units to the overlay's px. A switch maps by\n * where each <svg> sits and how it's scaled, so the transform keeps angles; its outline's path data\n * is moved through it, arcs and all.\n */\nfunction mapMark(mark: MarkGeometry, m: Matrix): MarkGeometry {\n if (isIdentity(m)) return mark;\n const point = (p: Point): Point => matrix.apply(m, p);\n const path = (d: string): string => formatPath(transformPath(parsePath(d), m));\n const scale = Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]));\n const { outline } = mark;\n return {\n key: mark.key,\n ...(mark.series === undefined ? {} : { series: mark.series }),\n start: point(mark.start),\n end: point(mark.end),\n length: mark.length * scale,\n path: (t) => point(mark.path(t)),\n angle: (t) => {\n const angle = mark.angle(t);\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n return Math.atan2(m[1] * cos + m[3] * sin, m[0] * cos + m[2] * sin);\n },\n slice: (t0, t1) => path(mark.slice(t0, t1)),\n thickness: mark.thickness * scale,\n outline: { d: path(outline.d), closed: outline.closed, sample: (n) => outline.sample(n).map(point) },\n bounds: boxIn(m, mark.bounds),\n center: point(mark.center),\n pivot: point(mark.pivot),\n ...(mark.segments === undefined ? {} : { segments: mark.segments.map((segment) => mapMark(segment, m)) })\n };\n}\n\nfunction deferred(): { done: Promise<void>; settle: () => void } {\n let settle!: () => void;\n const done = new Promise<void>((resolve) => {\n settle = resolve;\n });\n return { done, settle };\n}\n\nfunction isView(value: unknown, container: Element): value is ChartSwitchView {\n if (typeof value !== \"object\" || value === null) return false;\n const view = value as Partial<Record<keyof ChartSwitchView, unknown>>;\n const element = view.element as Node | undefined;\n return (\n ([\"marks\", \"labels\", \"focus\", \"leave\", \"destroy\"] as const).every((method) => typeof view[method] === \"function\") &&\n element?.nodeType === 1 &&\n container.contains(element)\n );\n}\n\n/** Throws on options that aren't a switch's; returns the views' names. */\nfunction checkOptions(options: ChartSwitchOptions<ChartSwitchViews>): string[] {\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"chartSwitch needs options.\");\n const { views, initial, transition, announce } = options;\n if (typeof views !== \"object\" || views === null) throw new TypeError(\"chartSwitch needs views: by name, a function that draws each view's chart in the container it's given.\");\n const names = Object.keys(views);\n if (names.length === 0) throw new TypeError(\"chartSwitch needs at least one view.\");\n for (const name of names) {\n if (typeof views[name] !== \"function\") throw new TypeError(`chartSwitch: views.${name} must be a function that draws the view's chart in the container it's given.`);\n }\n if (typeof initial !== \"string\" || !names.includes(initial)) {\n throw new TypeError(`chartSwitch: initial must be one of the views (${names.map((n) => JSON.stringify(n)).join(\", \")}), got ${typeof initial === \"string\" ? JSON.stringify(initial) : String(initial)}.`);\n }\n if (!isTransitionEffect(transition)) throw new TypeError(\"chartSwitch: transition must be a transition effect, such as morph().\");\n if (announce !== undefined && typeof announce !== \"boolean\") throw new TypeError(\"chartSwitch: announce must be true or false.\");\n return names;\n}\n","// motionSwitch: the viewer's own motion control, the prototype's Presentation / Analysis / Off\n// segmented buttons. The viewer operates it, so it calls motion.chooseMode(), the one call that\n// overrides the device's reduced-motion setting. It imports only core (and the shared stylesheet).\n\nimport type { Motion, MotionMode } from \"../../core\";\nimport { injectStyles } from \"../render/theme\";\n\nexport interface MotionSwitchOptions {\n /** The group's visible label, which is also its accessible name. Default \"Motion\". */\n readonly label?: string;\n /** Button text by mode. Default \"Presentation\", \"Analysis\", \"Off\". */\n readonly labels?: Partial<Readonly<Record<MotionMode, string>>>;\n /**\n * The note beside the buttons, by effective mode, and `reduced` for while the device asks for\n * reduced motion and the viewer hasn't picked a mode.\n */\n readonly hints?: Partial<Readonly<Record<MotionMode | \"reduced\", string>>>;\n /**\n * A localStorage key. Opt-in: the viewer's choice is saved under it, and restored when the switch\n * is made, so it carries across pages and visits. Storage that's blocked or full is ignored.\n */\n readonly persist?: string;\n}\n\nexport interface MotionSwitch {\n /** The switch's root, a `role=\"group\"` element appended to the target. */\n readonly element: HTMLElement;\n /** Removes the switch and stops following the motion. The viewer's choice stays. */\n destroy(): void;\n}\n\nconst MODES: readonly MotionMode[] = [\"presentation\", \"analysis\", \"off\"];\n\nconst LABELS: Readonly<Record<MotionMode, string>> = {\n presentation: \"Presentation\",\n analysis: \"Analysis\",\n off: \"Off\"\n};\n\nconst HINTS: Readonly<Record<MotionMode | \"reduced\", string>> = {\n presentation: \"Staged, unhurried motion. Best for walking someone through a change.\",\n analysis: \"Quick, unstaged motion. Best for exploring.\",\n off: \"No motion: charts jump straight to their end state.\",\n reduced: \"Your device asks for reduced motion, so motion is off. Picking a mode here overrides it.\"\n};\n\nlet switches = 0;\n\n/**\n * Builds the motion switch in `target` (an element or a selector): a group of real buttons with\n * `aria-pressed`, one per mode, and a note on what the mode does. The pressed button is the effective\n * mode, so while the device asks for reduced motion and the viewer hasn't picked, Off is pressed and\n * the note says why. It follows `motion.subscribe`, so it stays right whoever changes the mode.\n */\nexport function motionSwitch(target: string | Element, motion: Motion, options: MotionSwitchOptions = {}): MotionSwitch {\n const parent = resolveTarget(target);\n checkMotion(motion);\n checkOptions(options);\n const labels = { ...LABELS, ...options.labels };\n const hints = { ...HINTS, ...options.hints };\n const { persist } = options;\n const doc = parent.ownerDocument;\n injectStyles(doc);\n\n const id = `ec-motion-${++switches}`;\n const root = doc.createElement(\"div\");\n root.className = \"ec-motion-switch\";\n root.setAttribute(\"role\", \"group\");\n root.setAttribute(\"aria-labelledby\", `${id}-label`);\n root.setAttribute(\"aria-describedby\", `${id}-hint`);\n\n const label = root.appendChild(doc.createElement(\"span\"));\n label.className = \"ec-motion-label\";\n label.id = `${id}-label`;\n label.textContent = options.label ?? \"Motion\";\n\n const modes = root.appendChild(doc.createElement(\"span\"));\n modes.className = \"ec-motion-modes\";\n const buttons = MODES.map((mode) => {\n const button = modes.appendChild(doc.createElement(\"button\"));\n button.type = \"button\";\n button.dataset.mode = mode;\n button.textContent = labels[mode];\n button.addEventListener(\"click\", () => motion.chooseMode(mode));\n return button;\n });\n\n // Polite: the note changes when the viewer picks a mode, or when the device setting changes.\n const hint = root.appendChild(doc.createElement(\"span\"));\n hint.className = \"ec-motion-hint\";\n hint.id = `${id}-hint`;\n hint.setAttribute(\"aria-live\", \"polite\");\n\n const render = (): void => {\n const mode = motion.mode;\n for (const button of buttons) button.setAttribute(\"aria-pressed\", String(button.dataset.mode === mode));\n hint.textContent = motion.prefersReduced && motion.viewerChoice === undefined ? hints.reduced : hints[mode];\n };\n\n if (persist !== undefined) {\n const saved = storage(doc, (store) => store.getItem(persist));\n if (MODES.includes(saved as MotionMode)) motion.chooseMode(saved as MotionMode);\n }\n // Drawn before it's in the page, so the live region doesn't announce the first note.\n render();\n parent.appendChild(root);\n\n const unsubscribe = motion.subscribe(() => {\n render();\n if (persist === undefined) return;\n const choice = motion.viewerChoice;\n storage(doc, (store) => (choice === undefined ? store.removeItem(persist) : store.setItem(persist, choice)));\n });\n\n let destroyed = false;\n return {\n element: root,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n unsubscribe();\n root.remove();\n }\n };\n}\n\n/** Runs `use` on the document's localStorage; anything that throws (blocked, full, sandboxed) is ignored. */\nfunction storage<T>(doc: Document, use: (store: Storage) => T): T | undefined {\n try {\n const store = doc.defaultView?.localStorage;\n return store ? use(store) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction resolveTarget(target: string | Element): Element {\n if (typeof target === \"string\") {\n const found = typeof document === \"undefined\" ? null : document.querySelector(target);\n if (!found) throw new TypeError(`motionSwitch: no element matches \"${target}\".`);\n return found;\n }\n if (typeof target !== \"object\" || target === null || typeof (target as Element).appendChild !== \"function\") {\n throw new TypeError(\"motionSwitch needs an element or a selector to build the switch in.\");\n }\n return target;\n}\n\nfunction checkMotion(motion: Motion): void {\n if (typeof motion !== \"object\" || motion === null || typeof motion.chooseMode !== \"function\" || typeof motion.subscribe !== \"function\") {\n throw new TypeError(\"motionSwitch needs a Motion, such as the page-wide `motion` or one from createMotion().\");\n }\n}\n\nfunction checkOptions(options: MotionSwitchOptions): void {\n const { label, labels, hints, persist } = options;\n if (label !== undefined && typeof label !== \"string\") throw new TypeError(`motionSwitch: label must be a string, got ${typeof label}.`);\n for (const [name, texts] of [[\"labels\", labels], [\"hints\", hints]] as const) {\n if (texts === undefined) continue;\n for (const [key, text] of Object.entries(texts)) {\n if (typeof text !== \"string\") throw new TypeError(`motionSwitch: ${name}.${key} must be a string, got ${typeof text}.`);\n }\n }\n if (persist !== undefined && (typeof persist !== \"string\" || persist === \"\")) {\n throw new TypeError(`motionSwitch: persist must be a localStorage key, got ${JSON.stringify(persist) ?? String(persist)}.`);\n }\n}\n","// playButton: Play and Pause for a playback() (WCAG 2.2.2: anything that plays for more than 5 s can be\n// paused). One real button whose text, and so its name, says what a click does. It has no aria-pressed:\n// a toggle button keeps one name, and this one's name changes. It imports only core (and the shared\n// stylesheet).\n\nimport type { Playback } from \"../../core\";\nimport { injectStyles } from \"../render/theme\";\n\nexport interface PlayButtonOptions {\n /** The button's text, which is its accessible name, by what a click does. Default \"Play\" and \"Pause\". */\n readonly labels?: Partial<Readonly<Record<\"play\" | \"pause\", string>>>;\n}\n\nexport interface PlayButton {\n /** The `<button type=\"button\">` appended to the target. */\n readonly element: HTMLButtonElement;\n /** Removes the button and stops following the playback, which carries on as it is. */\n destroy(): void;\n}\n\nconst LABELS: Readonly<Record<\"play\" | \"pause\", string>> = { play: \"Play\", pause: \"Pause\" };\n\n/**\n * Builds a Play/Pause button in `target` (an element or a selector) for `playback`. A click plays or\n * pauses; the text says Pause while it plays and goes back to Play when it pauses, seeks or ends. It\n * follows `playback.subscribe`, so it stays right whoever drives the playback, and it's the same\n * element throughout, so focus stays on it.\n */\nexport function playButton(target: string | Element, playback: Playback, options: PlayButtonOptions = {}): PlayButton {\n const parent = resolveTarget(target);\n checkPlayback(playback);\n checkOptions(options);\n const labels = { ...LABELS, ...options.labels };\n const doc = parent.ownerDocument;\n injectStyles(doc);\n\n const button = doc.createElement(\"button\");\n button.type = \"button\";\n button.className = \"ec-play\";\n button.addEventListener(\"click\", () => (playback.playing ? playback.pause() : playback.play()));\n\n const render = (): void => {\n const text = playback.playing ? labels.pause : labels.play;\n // Only when it changes, so assistive technology doesn't hear the same name again.\n if (button.textContent !== text) button.textContent = text;\n };\n render();\n parent.appendChild(button);\n const unsubscribe = playback.subscribe(render);\n\n let destroyed = false;\n return {\n element: button,\n destroy() {\n if (destroyed) return;\n destroyed = true;\n unsubscribe();\n button.remove();\n }\n };\n}\n\nfunction resolveTarget(target: string | Element): Element {\n if (typeof target === \"string\") {\n const found = typeof document === \"undefined\" ? null : document.querySelector(target);\n if (!found) throw new TypeError(`playButton: no element matches \"${target}\".`);\n return found;\n }\n if (typeof target !== \"object\" || target === null || typeof (target as Element).appendChild !== \"function\") {\n throw new TypeError(\"playButton needs an element or a selector to build the button in.\");\n }\n return target;\n}\n\nfunction checkPlayback(playback: Playback): void {\n if (\n typeof playback !== \"object\" ||\n playback === null ||\n typeof playback.play !== \"function\" ||\n typeof playback.pause !== \"function\" ||\n typeof playback.subscribe !== \"function\"\n ) {\n throw new TypeError(\"playButton needs a Playback, from playback().\");\n }\n}\n\nfunction checkOptions(options: PlayButtonOptions): void {\n const { labels } = options;\n if (labels === undefined) return;\n for (const [key, text] of Object.entries(labels)) {\n // Only spaces would collapse to a blank button with no accessible name.\n if (typeof text !== \"string\" || text.trim() === \"\") {\n throw new TypeError(`playButton: labels.${key} must be a string with some text, got ${JSON.stringify(text) ?? String(text)}.`);\n }\n }\n}\n","// Gaits: how an icon moves while travel carries it along a walk. A gait is a small function from how\n// far the icon has gone to its pose. Gaits never name icons, and icons only name a gait.\n\nimport { easeInOutCubic, type Easing } from \"../core\";\n\n/** Where the icon is on its trip. Distances are in the icon's own units (px at its natural size), so a gait looks the same at any size. */\nexport interface GaitState {\n /** How far the icon has gone. */\n readonly distance: number;\n /** The whole trip; 0 when the icon doesn't move. */\n readonly length: number;\n /** distance ÷ length, 0 to 1 (1 for a trip of length 0). */\n readonly progress: number;\n /** The icon's rolling radius. */\n readonly radius: number;\n}\n\n/** How the icon is held, relative to its place on the walk. */\nexport interface GaitPose {\n /** Raised this far towards the icon's up side, in icon units. */\n readonly lift: number;\n /** Rolling rotation about the icon's pivot, in radians; positive rolls forward (clockwise when facing +x). */\n readonly spin: number;\n /** Rocking rotation about the icon's pivot, in radians; positive raises the front. */\n readonly tilt: number;\n}\n\nexport interface Gait {\n (state: GaitState): GaitPose;\n /** The trip's easing. Default easeOutCubic. */\n readonly ease?: Easing;\n /** Multiplies the trip's duration. Default 1. */\n readonly pace?: number;\n}\n\nexport interface StepOptions {\n /** Distance per step, in icon units. Default 42. */\n readonly stride?: number;\n /** Height of each step, in icon units. Default 3.2. */\n readonly lift?: number;\n /** Most the front is raised during a step, in degrees. Default 9. */\n readonly tilt?: number;\n}\n\nconst STILL: GaitPose = Object.freeze({ lift: 0, spin: 0, tilt: 0 });\n\n/** Rolls without slipping: the spin is the distance over the radius. */\nfunction roll(): Gait {\n return (state) => ({ lift: 0, spin: state.distance / state.radius, tilt: 0 });\n}\n\n/**\n * Steps along, the prototype's cleat: a whole number of steps (at least one), each lifting and\n * tilting the front up and setting it down again, a little less as the trip goes on. A step takes 15%\n * longer than a roll over the same distance and eases in and out.\n */\nfunction step(options: StepOptions = {}): Gait {\n const stride = options.stride ?? 42;\n const lift = options.lift ?? 3.2;\n const tilt = options.tilt ?? 9;\n if (!(stride > 0) || !Number.isFinite(stride)) throw new RangeError(`gaits.step: stride must be more than 0, got ${stride}.`);\n if (!(lift >= 0) || !Number.isFinite(lift)) throw new RangeError(`gaits.step: lift can't be negative, got ${lift}.`);\n if (!Number.isFinite(tilt)) throw new RangeError(`gaits.step: tilt must be a finite number of degrees, got ${tilt}.`);\n const peak = (tilt * Math.PI) / 180;\n const gait = (state: GaitState): GaitPose => {\n const steps = Math.max(1, Math.round(state.length / stride));\n // Exactly 0 at the start and end of every step, so the boot rests flat when it arrives.\n const phase = Math.abs(Math.sin(Math.PI * ((state.progress * steps) % 1)));\n return { lift: phase * lift, spin: 0, tilt: phase * peak * (1 - 0.3 * state.progress) };\n };\n return Object.assign(gait, { ease: easeInOutCubic, pace: 1.15 });\n}\n\n/** Slides along without turning. */\nfunction slide(): Gait {\n return () => STILL;\n}\n\nexport const gaits: { roll: typeof roll; step: typeof step; slide: typeof slide } = { roll, step, slide };\n\n/** The gaits icons and options name. */\nexport type GaitName = keyof typeof gaits;\n","// travel: carries an icon along a mark's walk (the ball rolling out a bar, the boot stepping along\n// the assists). It reads only the walk, the thickness and the segments, so it runs on any mark.\n\nimport { easeOutCubic, matrix, offset } from \"../core\";\nimport type { EffectContext, GeometryEffect, Icon, IconHandle, MarkGeometry, Matrix, Point } from \"../core\";\nimport { normalizeAngle } from \"../core/geometry\";\nimport { gaits, type Gait, type GaitName } from \"./gaits\";\n\nexport interface TravelOptions {\n /**\n * A segment's series (\"goals\"); the whole walk if omitted. A mark with no segments counts as its\n * own one segment. A missing segment, or one shorter than 0.5 px, makes travel a no-op.\n */\n readonly along?: string;\n /** How the icon moves. Default: the icon's own gait, else \"slide\". */\n readonly gait?: Gait | GaitName;\n /** Length along the walk in px, or \"fit\": scaled so the icon is 85% of the mark's thickness across. Default: the icon's own size. */\n readonly size?: number | \"fit\";\n /** \"follow\" turns with the walk, \"level\" never turns, \"auto\" (default) follows but mirrors an upright icon instead of turning it upside down. */\n readonly orient?: \"auto\" | \"follow\" | \"level\";\n /** \"center\" (default) puts the icon's anchor on the walk; \"on\" sits the icon on top of it (a ball riding a line). */\n readonly ride?: \"center\" | \"on\";\n}\n\n/** Base duration: max(260 ms, distance ÷ 360 px/s) times the gait's pace, at most 4 s, with effect timing. */\nconst SPEED = 360;\nconst SHORTEST = 260;\n/**\n * The longest trip, base ms, after the gait's pace: past 1,440 px at pace 1 the icon goes faster,\n * not longer. With stagger's longest spread (500 ms) in front, it still ends within 5 s (WCAG 2.2.2).\n */\nconst LONGEST = 4000;\n/** A walk shorter than this draws nothing. */\nconst MIN_WALK = 0.5;\n/** \"fit\" makes the icon this much of the mark's thickness. */\nconst FIT = 0.85;\n/** The heading is smoothed over at least this many px either side, so corners don't snap. */\nconst MIN_SMOOTHING = 2;\nconst IDENTITY: Matrix = [1, 0, 0, 1, 0, 0];\nconst ORIENTS: readonly string[] = [\"auto\", \"follow\", \"level\"];\nconst RIDES: readonly string[] = [\"center\", \"on\"];\n\n/** One trip of an icon along one walk. */\ninterface Trip {\n readonly icon: Icon;\n /** Drawn length along the walk, px. */\n readonly size: number;\n /** How far the anchor moves, px, across no gap; 0 when every part of the walk is shorter than the icon. */\n readonly span: number;\n /** Base ms, before the motion mode scales it. */\n readonly duration: number;\n readonly gait: Gait;\n /** Where the icon is at eased progress p: the place() transform for its natural size. */\n transform(progress: number): Matrix;\n}\n\n/**\n * Moves an icon along the walk, or along one segment, inset by the icon's footprint so it stays\n * inside the mark. Its end state is the icon resting at the end. An icon given by name is looked up\n * in `ctx.icons` when it runs, and an unknown name throws there.\n *\n * Across a gap in the walk it jumps: it's inset from each part's ends as from the walk's, and goes\n * from one part to the next at once, so it's never drawn over a gap. The trip's time counts only the\n * parts it's drawn on, and a part shorter than the icon is skipped, unless it's the last: the icon\n * rests there, at the last value.\n */\nexport function travel(icon: Icon | string, options: TravelOptions = {}): GeometryEffect {\n checkOptions(icon, options);\n\n /** Plans the trip on the mark's current geometry; undefined when there's nothing to travel along. */\n function plan(mark: MarkGeometry, ctx: EffectContext): Trip | undefined {\n const resolved = typeof icon === \"string\" ? ctx.icons.get(icon) : icon;\n if (!resolved) throw new RangeError(`travel: unknown icon \"${String(icon)}\". Register it with registerIcon(icon), or pass the icon itself.`);\n const walk = pick(mark, options.along);\n if (!walk || !(drawn(walk) >= MIN_WALK)) return undefined;\n const scale =\n options.size === undefined ? 1 : options.size === \"fit\" ? (FIT * walk.thickness) / resolved.box.height : options.size / resolved.size;\n if (!(scale > 0)) return undefined;\n return trip(walk, resolved, scale, options);\n }\n\n /** Draws the trip at a progress, and follows the geometry when it moves (a resize, a transition). */\n function rider(mark: MarkGeometry, ctx: EffectContext): { readonly trip: Trip | undefined; show(progress: number): void } {\n let current = plan(mark, ctx);\n let handle: IconHandle | undefined;\n let drawn: { icon: Icon; size: number } | undefined;\n let progress = 0;\n const draw = (): void => {\n if (!current) {\n handle?.remove();\n handle = drawn = undefined;\n return;\n }\n if (!handle || drawn?.icon !== current.icon || drawn.size !== current.size) {\n handle?.remove();\n handle = ctx.layer.icon(current.icon, { size: current.size });\n drawn = { icon: current.icon, size: current.size };\n }\n handle.place(current.transform(progress));\n };\n ctx.onChange((next) => {\n current = plan(next, ctx);\n draw();\n });\n return {\n get trip() {\n return current;\n },\n show(p) {\n progress = p;\n draw();\n }\n };\n }\n\n return {\n kind: \"geometry\",\n async run(mark, ctx) {\n if (ctx.signal.aborted) return;\n const ride = rider(mark, ctx);\n const planned = ride.trip;\n // Nothing to travel along, or no room to move: draw the end state at once.\n if (!planned || planned.span <= 0) {\n ride.show(1);\n return;\n }\n await ctx.tween({\n duration: planned.duration,\n timing: \"effect\",\n ease: planned.gait.ease ?? easeOutCubic,\n update: (p) => ride.show(p)\n }).finished;\n },\n end(mark, ctx) {\n rider(mark, ctx).show(1);\n },\n clear() {}\n };\n}\n\n/** A part of the walk between gaps, in px along it, with how far the icon's anchor moves along it. */\ninterface Leg {\n readonly from: number;\n readonly to: number;\n readonly span: number;\n /** The span of the legs before it. */\n readonly before: number;\n}\n\nfunction trip(walk: MarkGeometry, icon: Icon, scale: number, options: TravelOptions): Trip {\n const gait = typeof options.gait === \"function\" ? options.gait : gaits[options.gait ?? icon.gait ?? \"slide\"]();\n const length = walk.length;\n const behind = icon.footprint[0] * scale;\n const ahead = icon.footprint[1] * scale;\n // A part shorter than the icon: the icon rests at its start (which may hang past its end) and doesn't move along it.\n let span = 0;\n const legs: Leg[] = parts(walk).map(([from, to]) => {\n const leg = { from, to, span: Math.max(0, to - from - behind - ahead), before: span };\n span += leg.span;\n return leg;\n });\n const smoothing = Math.max(MIN_SMOOTHING, (behind + ahead) / 2);\n const radius = icon.radius ?? icon.box.height / 2;\n const { anchor } = icon;\n // The drawing layer scales the icon about its anchor before place(), so the pivot moves with it.\n const pivot = { x: anchor.x + scale * (icon.pivot.x - anchor.x), y: anchor.y + scale * (icon.pivot.y - anchor.y) };\n // Riding on the walk: half the stroke, plus the anchor's height above the icon's bottom.\n const ride = options.ride === \"on\" ? walk.thickness / 2 + (icon.box.y + icon.box.height - anchor.y) * scale : 0;\n const orient = options.orient ?? \"auto\";\n\n return {\n icon,\n size: icon.size * scale,\n span,\n duration: Math.min(LONGEST, Math.max(SHORTEST, (span / SPEED) * 1000) * (gait.pace ?? 1)),\n gait,\n transform(progress) {\n const travelled = progress * span;\n // The last leg the icon has reached: a leg it can't move along is passed at once, unless it's the last.\n let index = legs.length - 1;\n while (index > 0 && legs[index]!.before > travelled) index--;\n const leg = legs[index]!;\n const distance = leg.from + behind + Math.min(leg.span, travelled - leg.before);\n const pose = gait({ distance: travelled / scale, length: span / scale, progress, radius });\n const at = pointAt(walk, distance);\n const direction = heading(walk, Math.min(distance, length), smoothing, leg);\n // Mirroring keeps an upright icon's top up when the walk heads left.\n const mirror = orient === \"auto\" && icon.upright === true && Math.cos(direction) < -1e-9;\n const turn = orient === \"level\" ? 0 : mirror ? normalizeAngle(direction - Math.PI) : direction;\n return matrix.multiply(\n matrix.translate(at.x, at.y),\n matrix.rotate(turn),\n mirror ? matrix.scale(-1, 1) : IDENTITY,\n matrix.translate(-anchor.x, -anchor.y - pose.lift * scale - ride),\n matrix.rotate(pose.spin - pose.tilt, pivot)\n );\n }\n };\n}\n\n/** The walk to travel along: the named segment, or the mark itself. */\nfunction pick(mark: MarkGeometry, along: string | undefined): MarkGeometry | undefined {\n if (along === undefined) return mark;\n if (mark.segments) return mark.segments.find((segment) => segment.series === along);\n return mark.series === along ? mark : undefined;\n}\n\n/** The walk's parts between its gaps, as [from, to] px along it, in order. A walk with no gaps is one part. */\nfunction parts(walk: MarkGeometry): [number, number][] {\n const { length } = walk;\n const found: [number, number][] = [];\n let at = 0;\n for (const [from, to] of walk.gaps ?? []) {\n // Taken as the contract has them, in order and apart; any that aren't are read as far as they go.\n if (!(to > from) || !(to > at)) continue;\n if (from > at) found.push([at * length, Math.min(1, from) * length]);\n at = Math.min(1, to);\n }\n found.push([at * length, length]);\n return found;\n}\n\n/** How much of the walk is drawn: its length less its gaps. */\nfunction drawn(walk: MarkGeometry): number {\n return parts(walk).reduce((sum, [from, to]) => sum + (to - from), 0);\n}\n\n/** The point `distance` px along the walk; past the end, it carries on in the end's direction. */\nfunction pointAt(walk: MarkGeometry, distance: number): Point {\n const { length } = walk;\n return distance <= length ? walk.path(distance / length) : offset(walk.end, walk.angle(1), distance - length);\n}\n\n/**\n * The direction of travel at `distance`, smoothed over a window either side: the chord between the\n * window's ends. On straight legs and circular arcs the chord is exactly the tangent; across a\n * polyline corner it turns gradually. The window shrinks near the ends of the leg so it stays on it,\n * never across a gap.\n */\nfunction heading(walk: MarkGeometry, distance: number, window: number, leg: Leg): number {\n const { length } = walk;\n const reach = Math.min(window, distance - leg.from, leg.to - distance);\n if (reach > 1e-6) {\n const a = walk.path((distance - reach) / length);\n const b = walk.path((distance + reach) / length);\n if (Math.hypot(b.x - a.x, b.y - a.y) > 1e-9) return Math.atan2(b.y - a.y, b.x - a.x);\n }\n return walk.angle(distance / length);\n}\n\nfunction checkOptions(icon: Icon | string, options: TravelOptions): void {\n const named = typeof icon === \"string\" && icon !== \"\";\n if (!named && (typeof icon !== \"object\" || icon === null || typeof icon.name !== \"string\")) {\n throw new TypeError(`travel needs an icon or an icon's name, got ${icon === null ? \"null\" : typeof icon}.`);\n }\n const { along, gait, size, orient, ride } = options;\n if (along !== undefined && typeof along !== \"string\") throw new RangeError(`travel: along must be a series name, got ${String(along)}.`);\n if (gait !== undefined && typeof gait !== \"function\" && !Object.prototype.hasOwnProperty.call(gaits, gait)) {\n throw new RangeError(`travel: gait must be a gait or one of roll, step, slide, got ${String(gait)}.`);\n }\n if (size !== undefined && size !== \"fit\" && !(typeof size === \"number\" && size > 0 && Number.isFinite(size))) {\n throw new RangeError(`travel: size must be more than 0 px, or \"fit\", got ${String(size)}.`);\n }\n if (orient !== undefined && !ORIENTS.includes(orient)) throw new RangeError(`travel: orient must be auto, follow or level, got ${String(orient)}.`);\n if (ride !== undefined && !RIDES.includes(ride)) throw new RangeError(`travel: ride must be center or on, got ${String(ride)}.`);\n}\n","// flash: one halo blink along the mark's outline, for \"this changed\" (`on: { update: \"flash\" }`). It\n// reads nothing of the geometry: the halo is a mark style, which the renderer strokes along the outline\n// as it is on screen, so it follows the mark through the transition it runs alongside.\n\nimport { linear } from \"../core\";\nimport type { Color, EffectContext, GeometryEffect } from \"../core\";\n\nexport interface FlashOptions {\n /** The halo's widest stroke, px; half of it shows outside the mark. Default 8, as in the prototype. */\n readonly width?: number;\n /** Default 0.35. */\n readonly opacity?: number;\n /** A theme token or any CSS colour. Default: the mark's own colour. */\n readonly color?: Color;\n}\n\n/** Base duration, with effect timing. */\nconst DURATION = 900;\n/** The prototype's keyframes: the stroke is widest a quarter of the way through. */\nconst PEAK = 0.25;\nconst WIDTH = 8;\nconst OPACITY = 0.35;\n\n/**\n * One blink of a halo along the mark's outline: the stroke grows from 0 to `width` and back over a\n * 900 ms base, as the prototype's CSS flash does.\n *\n * Its end state is nothing, on purpose. A flash is emphasis, not information: the change it points\n * at (the bar's new length, its new value label) stays on the chart, so with motion off or reduced\n * the viewer still sees everything the flash would have drawn attention to.\n */\nexport function flash(options: FlashOptions = {}): GeometryEffect {\n checkOptions(options);\n const width = options.width ?? WIDTH;\n const opacity = options.opacity ?? OPACITY;\n const { color } = options;\n\n const show = (ctx: EffectContext, progress: number): void => {\n const stroke = width * blink(progress);\n ctx.mark.set({ halo: stroke > 0 ? { width: stroke, opacity, ...(color === undefined ? {} : { color }) } : undefined });\n };\n\n return {\n kind: \"geometry\",\n async run(_mark, ctx) {\n if (ctx.signal.aborted) return;\n // Linear here: the keyframes ease each half themselves.\n await ctx.tween({ duration: DURATION, timing: \"effect\", ease: linear, update: (p) => show(ctx, p) }).finished;\n },\n end() {},\n clear() {}\n };\n}\n\n/** The halo's width at linear progress t, 0–1: up to 1 by PEAK, back to 0 at the end, each half eased out. */\nfunction blink(t: number): number {\n if (!(t > 0) || t >= 1) return 0;\n return t < PEAK ? easeOut(t / PEAK) : 1 - easeOut((t - PEAK) / (1 - PEAK));\n}\n\n/** CSS's `ease-out`, cubic-bezier(0, 0, 0.58, 1), which the prototype's keyframes use. */\nfunction easeOut(x: number): number {\n if (!(x > 0)) return 0;\n if (x >= 1) return 1;\n // x(s) = 1.74·s²(1 − s) + s³ rises with s, so bisection finds the curve's parameter.\n let lo = 0;\n let hi = 1;\n for (let i = 0; i < 24; i++) {\n const s = (lo + hi) / 2;\n if (1.74 * s * s * (1 - s) + s * s * s < x) lo = s;\n else hi = s;\n }\n const s = (lo + hi) / 2;\n return 3 * s * s - 2 * s * s * s;\n}\n\nfunction checkOptions(options: FlashOptions): void {\n const { width, opacity, color } = options;\n if (width !== undefined && !(typeof width === \"number\" && width > 0 && Number.isFinite(width))) {\n throw new RangeError(`flash: width must be more than 0 px, got ${String(width)}.`);\n }\n if (opacity !== undefined && !(typeof opacity === \"number\" && opacity > 0 && opacity <= 1)) {\n throw new RangeError(`flash: opacity must be more than 0 and at most 1, got ${String(opacity)}.`);\n }\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`flash: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n}\n","// wiggle: a short damped rotation of the mark about its pivot, for hover (`on: { hover: \"wiggle\" }`).\n// It reads only the pivot and the outline, so a bar rocks on its baseline and a donut slice about the\n// donut's centre, and the angle is capped so no part of the mark moves more than a few px.\n\nimport { linear, matrix } from \"../core\";\nimport type { EffectContext, GeometryEffect, MarkGeometry } from \"../core\";\n\nexport interface WiggleOptions {\n /** How far the point of the mark farthest from its pivot may move, px: more than 0, at most 3. Default 3. */\n readonly swing?: number;\n}\n\n/** Base duration, with effect timing. */\nconst DURATION = 450;\n/** Each half-swing's share of the cap, alternating sides: three, each smaller than the last. */\nconst SWINGS = [1, -0.5, 0.25];\nconst SWING = 3;\n/** A mark whose outline is all within this of its pivot doesn't move. */\nconst MIN_REACH = 0.5;\n/** Outline points measured to find the reach. */\nconst SAMPLES = 64;\n/** Never more than 15°, so a tiny mark nods instead of spinning, however little it moves. */\nconst MAX_ANGLE = Math.PI / 12;\n\n/**\n * Rocks the mark about `mark.pivot` in three decaying half-swings over a 450 ms base. The angle is\n * capped so the outline point farthest from the pivot moves at most `swing` px: effects never\n * distort data, and a few px of movement reads as emphasis, not as a change of value.\n *\n * Its end state is no transform: the mark rests where the chart drew it.\n */\nexport function wiggle(options: WiggleOptions = {}): GeometryEffect {\n checkOptions(options);\n const swing = options.swing ?? SWING;\n\n return {\n kind: \"geometry\",\n async run(mark, ctx) {\n if (ctx.signal.aborted) return;\n // Follow the geometry, so a wiggle running alongside a transition rocks about the pivot as it is now.\n let current = mark;\n let cap = limit(mark, swing);\n let progress = 0;\n const show = (): void => {\n const angle = cap * rock(progress);\n ctx.mark.set({ transform: angle === 0 ? undefined : matrix.rotate(angle, current.pivot) });\n };\n ctx.onChange((next) => {\n current = next;\n cap = limit(next, swing);\n show();\n });\n // Linear here: each half-swing eases itself.\n await ctx.tween({\n duration: DURATION,\n timing: \"effect\",\n ease: linear,\n update: (p) => {\n progress = p;\n show();\n }\n }).finished;\n },\n end() {},\n clear() {}\n };\n}\n\n/**\n * The largest angle, in radians, that moves no outline point more than `swing` px. A point at\n * distance r from the pivot, turned by θ, moves along a chord of 2r·sin(θ/2).\n */\nfunction limit(mark: MarkGeometry, swing: number): number {\n const { pivot } = mark;\n let reach = 0;\n for (const point of mark.outline.sample(SAMPLES)) reach = Math.max(reach, Math.hypot(point.x - pivot.x, point.y - pivot.y));\n if (!(reach >= MIN_REACH)) return 0;\n return Math.min(MAX_ANGLE, 2 * Math.asin(Math.min(1, swing / (2 * reach))));\n}\n\n/** The share of the cap at linear progress t, 0–1: each half-swing a sine arch, 0 at both ends. */\nfunction rock(t: number): number {\n if (!(t > 0) || t >= 1) return 0;\n const position = t * SWINGS.length;\n const index = Math.floor(position);\n return SWINGS[index]! * Math.sin(Math.PI * (position - index));\n}\n\nfunction checkOptions(options: WiggleOptions): void {\n const { swing } = options;\n if (swing !== undefined && !(typeof swing === \"number\" && swing > 0 && swing <= SWING)) {\n throw new RangeError(`wiggle: swing must be more than 0 and at most ${SWING} px, got ${String(swing)}.`);\n }\n}\n","// pulse: a halo that grows out from the mark's outline and fades, a few times over, for \"look here\"\n// (`on: { enter: \"pulse\" }`). Like flash it reads nothing of the geometry: the renderer strokes the\n// halo along the outline as it is on screen.\n\nimport { easeOutCubic, linear } from \"../core\";\nimport type { Color, EffectContext, GeometryEffect } from \"../core\";\n\nexport interface PulseOptions {\n /** How many pulses, a whole number from 1 to 6. Fewer play if they wouldn't finish within 5 s. Default 2. */\n readonly times?: number;\n /** The halo's widest stroke, px; half of it shows outside the mark. Default 12. */\n readonly width?: number;\n /** A theme token or any CSS colour. Default: the mark's own colour. */\n readonly color?: Color;\n}\n\n/** Base duration of each pulse, with effect timing. */\nconst DURATION = 600;\nconst TIMES = 2;\nconst MAX_TIMES = 6;\nconst WIDTH = 12;\n/** The halo's opacity as it starts; it fades to 0 as it widens. */\nconst OPACITY = 0.4;\n/** Every pulse ends before this, in ms after scaling: anything longer needs a pause control (WCAG 2.2.2). */\nconst LIMIT = 5000;\n\n/**\n * Halos that widen from 0 to `width` while fading from 40% to nothing, 600 ms base each, `times`\n * over. Each pulse is its own tween, so Analysis shortens every pulse rather than dropping any; a\n * page whose scaling stretches pulses past 5 s in all gets fewer of them instead.\n *\n * It never changes the mark's size, so a value never looks bigger than it is. Its end state is\n * nothing: a pulse draws attention, and what it points at stays on the chart.\n */\nexport function pulse(options: PulseOptions = {}): GeometryEffect {\n checkOptions(options);\n const times = options.times ?? TIMES;\n const width = options.width ?? WIDTH;\n const { color } = options;\n\n // The ring rushes out and slows, while it fades steadily.\n const show = (ctx: EffectContext, t: number): void => {\n const visible = t > 0 && t < 1;\n ctx.mark.set({\n halo: visible ? { width: width * easeOutCubic(t), opacity: OPACITY * (1 - t), ...(color === undefined ? {} : { color }) } : undefined\n });\n };\n\n return {\n kind: \"geometry\",\n async run(_mark, ctx) {\n let total = 0;\n for (let i = 0; i < times; i++) {\n if (ctx.signal.aborted) return;\n // Each pulse's length as the motion scales it now; drop the ones that would end at 5 s or later.\n const length = ctx.motion.duration(DURATION, \"effect\");\n if (total + length >= LIMIT) return;\n total += length;\n // Linear here: show() eases the width itself.\n await ctx.tween({ duration: DURATION, timing: \"effect\", ease: linear, update: (t) => show(ctx, t) }).finished;\n }\n },\n end() {},\n clear() {}\n };\n}\n\nfunction checkOptions(options: PulseOptions): void {\n const { times, width, color } = options;\n if (times !== undefined && !(Number.isInteger(times) && times >= 1 && times <= MAX_TIMES)) {\n throw new RangeError(`pulse: times must be a whole number from 1 to ${MAX_TIMES}, got ${String(times)}.`);\n }\n if (width !== undefined && !(typeof width === \"number\" && width > 0 && Number.isFinite(width))) {\n throw new RangeError(`pulse: width must be more than 0 px, got ${String(width)}.`);\n }\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`pulse: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n}\n","// trace: a highlighter stroke that draws itself along the mark's walk and stays (the effects guide's\n// sketch, grown). It reads only the walk, so it runs on any mark, and it leaves the mark itself\n// untouched, so it's safe in any slot.\n\nimport { easeInOutCubic } from \"../core\";\nimport type { Color, EffectContext, GeometryEffect, MarkGeometry, Paint, PathHandle } from \"../core\";\n\nexport interface TraceOptions {\n /** A theme token or any CSS colour. Default \"mark\", the mark's own colour (a stack's first segment's). */\n readonly color?: Color;\n /** The stroke's width, px. Default 3. */\n readonly width?: number;\n /** From 0 to 1. Default 0.5. */\n readonly opacity?: number;\n /** Base ms to draw the stroke, before the motion mode scales it, with effect timing. Default 500. */\n readonly duration?: number;\n}\n\nconst DURATION = 500;\nconst WIDTH = 3;\nconst OPACITY = 0.5;\n/** A walk shorter than this draws nothing. */\nconst MIN_WALK = 0.5;\n\n/**\n * Draws an overlay stroke along the mark's walk, from its start to its end, eased in and out over\n * `duration`, with round caps. On a stack it runs the whole walk, across every segment. A walk under\n * 0.5 px (a point) draws nothing, and a run on one finishes at once.\n *\n * The stroke stays, and follows `onChange`, so it keeps to the mark through a transition or a\n * resize. Its end state is the whole stroke, so reduced motion shows what a full run ends with.\n */\nexport function trace(options: TraceOptions = {}): GeometryEffect {\n checkOptions(options);\n const duration = options.duration ?? DURATION;\n const paint: Paint = { stroke: options.color ?? \"mark\", width: options.width ?? WIDTH, opacity: options.opacity ?? OPACITY, linecap: \"round\" };\n\n /** Draws the stroke up to progress p along the walk, and keeps it on the mark when the mark moves. */\n const stroke = (mark: MarkGeometry, ctx: EffectContext): ((p: number) => void) => {\n let current = mark;\n let progress = 0;\n let path: PathHandle | undefined;\n const draw = (): void => {\n if (!(current.length >= MIN_WALK)) {\n path?.remove();\n path = undefined;\n return;\n }\n // At progress 0 this is a lone moveto, which SVG doesn't stroke, even with round caps.\n const d = current.slice(0, progress);\n if (path) path.update(d);\n else path = ctx.layer.path(d, paint);\n };\n ctx.onChange((next) => {\n current = next;\n draw();\n });\n // Drawn now, so a run stacks the stroke where end() does among the other parts of a combination.\n draw();\n return (p) => {\n progress = p;\n draw();\n };\n };\n\n return {\n kind: \"geometry\",\n async run(mark, ctx) {\n if (ctx.signal.aborted) return;\n const show = stroke(mark, ctx);\n // No walk to draw along: the end state at once, so the stroke is whole if the mark grows one.\n if (!(mark.length >= MIN_WALK)) {\n show(1);\n return;\n }\n await ctx.tween({ duration, timing: \"effect\", ease: easeInOutCubic, update: show }).finished;\n },\n end(mark, ctx) {\n stroke(mark, ctx)(1);\n },\n clear() {}\n };\n}\n\nfunction checkOptions(options: TraceOptions): void {\n const { color, width, opacity, duration } = options;\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`trace: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n if (width !== undefined && !(typeof width === \"number\" && width >= 0 && Number.isFinite(width))) {\n throw new RangeError(`trace: width must be 0 px or more, got ${String(width)}.`);\n }\n if (opacity !== undefined && !(typeof opacity === \"number\" && opacity >= 0 && opacity <= 1)) {\n throw new RangeError(`trace: opacity must be from 0 to 1, got ${String(opacity)}.`);\n }\n if (duration !== undefined && !(typeof duration === \"number\" && duration >= 0 && Number.isFinite(duration))) {\n throw new RangeError(`trace: duration must be 0 ms or more, got ${String(duration)}.`);\n }\n}\n","// A caption: text past the end of a mark's walk, or past its own labels (`labelBounds`), rising into\n// place. delta and label draw through it, so they place and rise the same way. Internal:\n// it reads only the geometry, and draws only through the context's layer.\n\nimport { offset } from \"../core\";\nimport type { Color, EffectContext, MarkData, MarkGeometry, Point, Rect, TextHandle } from \"../core\";\n\n/** Past the end of the walk, with no label in the way. */\nconst PAST_END = 10;\n/** Past the farthest of the mark's labels in the way; a label is in the way when the line it's placed along passes within this of it, since the text has height. */\nconst PAST_LABEL = 6;\n/** How far it rises into place, across the way it's placed. */\nconst RISE = 8;\n/** The overlay's text size (the theme's `.ec-text`), for where the baseline goes. */\nconst TEXT = 12.5;\n/** Shares of the text size from the anchor point down to the baseline: text read sideways is centred on the walk's line, as the charts' labels are; text read downwards hangs from it. */\nconst CENTRE = 0.36;\nconst HANG = 0.8;\n\nexport type CaptionAnchor = \"start\" | \"middle\" | \"end\";\n\nexport interface CaptionPlace {\n /** The text's anchor point, on its baseline. */\n readonly at: Point;\n readonly anchor: CaptionAnchor;\n /** The way it was placed, in radians: the walk's heading, or the mark's up side. */\n readonly toward: number;\n}\n\n/**\n * Where a caption goes on `mark`.\n *\n * - **Along the heading,** from the end of the walk: 10 px past the end, or 6 px past the farthest of\n * its `labelBounds` the heading meets, whichever is further. The heading meets a box when it passes\n * within 6 px of it: the text has height, and a heading that just misses a label would put the\n * text on it.\n * - **Up from its centre,** when the heading meets none of its labels but its up side does: 6 px past\n * the farthest of them. A slice's heading runs along the ring, and its up side goes out through its\n * label outside it.\n *\n * It's anchored by the way it was placed: at its start reading rightwards, its end leftwards, and its\n * middle within 45° of vertical, so a column's sits centred above its value. Its baseline is a little\n * below the point: read sideways, the text is centred on the line it was placed along, as the\n * charts' labels are; read upwards, it stands on it; read downwards, it hangs from it.\n */\nexport function captionPlace(mark: MarkGeometry): CaptionPlace {\n const boxes = mark.labelBounds ?? [];\n const heading = mark.angle(1);\n const along = farthest(mark.end, heading, boxes);\n if (along === undefined && boxes.length > 0) {\n const up = mark.angle(0.5) - Math.PI / 2;\n const out = farthest(mark.center, up, boxes);\n if (out !== undefined) return placed(mark.center, up, out);\n }\n return placed(mark.end, heading, Math.max(PAST_END, along ?? -Infinity));\n}\n\n/** The caption `distance` px from `from` towards `toward`, anchored and dropped to its baseline by that direction. */\nfunction placed(from: Point, toward: number, distance: number): CaptionPlace {\n const cos = Math.cos(toward);\n const sin = Math.sin(toward);\n const point = offset(from, toward, distance);\n const drop = TEXT * (sin < 0 ? CENTRE * (1 + sin) : CENTRE + (HANG - CENTRE) * sin);\n const anchor: CaptionAnchor = Math.abs(cos) <= Math.SQRT1_2 + 1e-9 ? \"middle\" : cos > 0 ? \"start\" : \"end\";\n return { at: { x: point.x, y: point.y + drop }, anchor, toward };\n}\n\n/**\n * How far from `from` towards `toward` the ray leaves the farthest of `boxes` it meets, each grown by\n * 6 px on every side, so it's 6 px past the box itself; or undefined when it meets none.\n */\nfunction farthest(from: Point, toward: number, boxes: readonly Rect[]): number | undefined {\n const cos = Math.cos(toward);\n const sin = Math.sin(toward);\n let exit: number | undefined;\n for (const { x, y, width, height } of boxes) {\n const grown = { x: x - PAST_LABEL, y: y - PAST_LABEL, width: width + 2 * PAST_LABEL, height: height + 2 * PAST_LABEL };\n const leaving = leaves(from, cos, sin, grown);\n if (leaving !== undefined) exit = Math.max(exit ?? leaving, leaving);\n }\n return exit;\n}\n\n/** How far along the ray from `from` (direction cos, sin) it leaves `box`, or undefined when it never meets it. */\nfunction leaves(from: Point, cos: number, sin: number, box: Rect): number | undefined {\n let near = 0;\n let far = Infinity;\n for (const [origin, step, lo, hi] of [\n [from.x, cos, box.x, box.x + box.width],\n [from.y, sin, box.y, box.y + box.height]\n ] as const) {\n if (Math.abs(step) < 1e-12) {\n if (origin < lo || origin > hi) return undefined;\n continue;\n }\n const a = (lo - origin) / step;\n const b = (hi - origin) / step;\n near = Math.max(near, Math.min(a, b));\n far = Math.min(far, Math.max(a, b));\n }\n return far >= near ? far : undefined;\n}\n\n/**\n * Draws a caption on the mark now, at rise 0, and returns how to draw it at rise p: from 0 (8 px\n * across the way it was placed, on that way's down side, unseen) to 1 (in place, at full strength). It keeps to the mark\n * through `onChange`, its text worded again by `words` from the moved mark and its latest data. No\n * text (undefined or \"\") draws nothing.\n */\nexport function caption<D>(\n mark: MarkGeometry,\n data: MarkData<D>,\n ctx: EffectContext,\n color: Color,\n words: (mark: MarkGeometry, data: MarkData<D>) => string | undefined\n): (p: number) => void {\n let current = mark;\n let content = words(mark, data) ?? \"\";\n let latest = data;\n let progress = 0;\n let handle: TextHandle | undefined;\n const draw = (): void => {\n if (content === \"\") {\n handle?.remove();\n handle = undefined;\n return;\n }\n const { at, anchor, toward } = captionPlace(current);\n // Rising across the way it was placed, towards that way's up side, so it never crosses the labels it's placed past.\n const style = { at: offset(at, toward - Math.PI / 2, -RISE * (1 - progress)), anchor, color, opacity: progress };\n if (handle) handle.update(style, content);\n else handle = ctx.layer.text(content, style);\n };\n ctx.onChange((next, nextData) => {\n current = next;\n // The runner tells a run its own mark's data, so it has the run's rows.\n latest = (nextData as MarkData<D> | undefined) ?? latest;\n content = words(current, latest) ?? \"\";\n draw();\n });\n draw();\n return (p) => {\n progress = p;\n draw();\n };\n}\n","// delta: the change since the last update (\"+2\"), past the end of the mark and clear of its own labels,\n// for the update slot (`on: { update: delta() }`). A data effect: it compares the mark's value with its\n// value before the update, and draws the change as text that rises into place and stays.\n\nimport type { Color, DataEffect, MarkData } from \"../core\";\nimport { caption } from \"./caption\";\n\nexport interface DeltaOptions<D = unknown> {\n /** The mark's value. Default: its last sample's, so a bar's total, a line's value at its revealed end, a slice's share. */\n readonly value?: (data: MarkData<D>) => number;\n /** Words the change. Default: the page's locale, with its sign and at most two decimals (\"+2\", \"-0.3\"). */\n readonly format?: (change: number) => string;\n /** A theme token or any CSS colour. Default \"text\", never the series' colour. */\n readonly color?: Color;\n}\n\n/** Base duration of the rise, with effect timing. */\nconst DURATION = 400;\n/** A change this small, relative to the values, is float noise (0.1 + 0.2 against 0.3), not a change. */\nconst TIE = 1e-9;\n\nconst lastSample = (data: MarkData<unknown>): number => {\n const { samples } = data;\n return samples[samples.length - 1]?.value ?? Number.NaN;\n};\n\nlet wording: Intl.NumberFormat | undefined;\nconst signed = (change: number): string => {\n wording ??= new Intl.NumberFormat(undefined, { signDisplay: \"always\", maximumFractionDigits: 2 });\n return wording.format(change);\n};\n\n/**\n * The change since the last update, `value(data) − value(data.previous)`, as text past the end of the\n * mark: 10 px past the end of its walk, or 6 px past the farthest of its own labels its heading meets.\n * It rises 8 px into place and fades in over 400 ms base, then stays until the next update clears it,\n * following the mark as it moves. Its end state is the text in place, so reduced motion shows the\n * change. With no `previous`, or no change, it draws nothing.\n *\n * The text is in the overlay, which screen readers don't read: a page that relies on it says the same\n * in its table or its announcement.\n */\nexport function delta<D = unknown>(options: DeltaOptions<D> = {}): DataEffect<D> {\n checkOptions(options);\n const value = options.value ?? lastSample;\n const format = options.format ?? signed;\n const color = options.color ?? \"text\";\n\n /** The change in words, or undefined for none. */\n const words = (data: MarkData<D>): string | undefined => {\n if (!data.previous) return undefined;\n const now = value(data);\n const before = value(data.previous);\n const change = now - before;\n if (!Number.isFinite(change) || Math.abs(change) <= TIE * Math.max(Math.abs(now), Math.abs(before))) return undefined;\n return format(change);\n };\n\n return {\n kind: \"data\",\n run: async (mark, data, ctx) => {\n if (ctx.signal.aborted) return;\n // Worked out once: the change is this update's, wherever the mark moves after.\n const text = words(data);\n if (text === undefined || text === \"\") return;\n const show = caption(mark, data, ctx, color, () => text);\n await ctx.tween({ duration: DURATION, timing: \"effect\", update: show }).finished;\n },\n end: (mark, data, ctx) => {\n const text = words(data);\n if (text !== undefined && text !== \"\") caption(mark, data, ctx, color, () => text)(1);\n },\n clear() {}\n };\n}\n\nfunction checkOptions<D>(options: DeltaOptions<D>): void {\n const { value, format, color } = options;\n if (value !== undefined && typeof value !== \"function\") throw new TypeError(`delta: value must be a function that reads the mark's value from its data, got ${typeof value}.`);\n if (format !== undefined && typeof format !== \"function\") throw new TypeError(`delta: format must be a function that words the change, got ${typeof format}.`);\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`delta: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n }\n}\n","// label: text worked out from the mark's own data, past the end of the mark and clear of its own\n// labels, usually for the decorate slot: a slope's change from first to last, a step's signed value, a\n// field such as `vsLastMonth`. A data effect: it reads the mark's data, and words it again on every change.\n\nimport type { Color, DataEffect, MarkData, MarkGeometry } from \"../core\";\nimport { caption } from \"./caption\";\n\nexport interface LabelOptions {\n /** A theme token or any CSS colour. Default \"text\", never the series' colour. */\n readonly color?: Color;\n}\n\n/** Base duration of the rise, with effect timing, as delta's. */\nconst DURATION = 400;\n\n/**\n * Text from `text(data, mark)` past the end of the mark: 10 px past the end of its walk, or 6 px\n * past the farthest of its own labels its heading meets. `text` returns the words, or undefined or\n * \"\" for none. It's typed by the rows it reads, so a label written for one kind of row is a type\n * error on a chart of another.\n *\n * It rises 8 px into place and fades in over 400 ms base, as delta does, then follows every change,\n * its text worked out again from the new data. Its end state is the text in place. The text is in\n * the overlay, which screen readers don't read: a page that relies on it says the same in its table\n * or its announcement.\n */\nexport function label<D = unknown>(text: (data: MarkData<D>, mark: MarkGeometry) => string | undefined, options: LabelOptions = {}): DataEffect<D> {\n if (typeof text !== \"function\") throw new TypeError(`label needs a function that returns the text from the mark's data, got ${typeof text}.`);\n const { color = \"text\" } = options;\n if (typeof color !== \"string\" || color === \"\") throw new RangeError(`label: color must be a theme token or a CSS colour, got ${JSON.stringify(color) ?? String(color)}.`);\n const words = (mark: MarkGeometry, data: MarkData<D>): string | undefined => {\n const said: unknown = text(data, mark);\n return said === undefined || said === null ? undefined : String(said);\n };\n\n return {\n kind: \"data\",\n run: async (mark, data, ctx) => {\n if (ctx.signal.aborted) return;\n const show = caption(mark, data, ctx, color, words);\n await ctx.tween({ duration: DURATION, timing: \"effect\", update: show }).finished;\n },\n end: (mark, data, ctx) => caption(mark, data, ctx, color, words)(1),\n clear() {}\n };\n}\n","// threshold: colours the parts of a mark's walk where its values are below a reference (or above it),\n// as the lab's goals line turns red wherever it's under xG. A data effect: it reads the mark's samples\n// and, for a series, the related series' samples, and draws along the walk, so it runs on any mark\n// that has samples. It's an encoding, not motion: it draws at once and redraws on every change.\n\nimport type { Color, DataEffect, EffectContext, MarkData, MarkGeometry, Paint, PathHandle, Sample } from \"../core\";\n\nexport interface ThresholdOptions {\n /**\n * The reference: a constant, or the name of a related series (\"xg\"), which goes in `needs.related`\n * so a chart without that series throws when it's created.\n */\n readonly compareTo: number | string;\n /** Colour where the mark's values are \"below\" the reference (default) or \"above\" it. Equal values aren't coloured. */\n readonly when?: \"below\" | \"above\";\n /** A theme token or any CSS colour. Default \"negative\". */\n readonly color?: Color;\n}\n\n/** A walk shorter than this draws nothing. */\nconst MIN_WALK = 0.5;\n/** Values this close, relative to their size, count as equal, so float noise in a sum colours nothing. */\nconst TIE = 1e-9;\nconst WHENS: readonly string[] = [\"below\", \"above\"];\n\n/**\n * Colours the parts of the walk where the mark's values are below `compareTo` (or above it, with\n * `when: \"above\"`): one overlay path per run, `mark.slice(t0, t1)` stroked in `color` at the mark's\n * thickness with butt caps, so a coloured part ends exactly at its crossing.\n *\n * - **A constant** is compared with every sample as it is.\n * - **A series** is compared by `at` when every sample of both has a number or a Date there, the\n * reference interpolated between its samples and nothing coloured outside its range. Otherwise by `t`.\n * - **Crossings** are interpolated linearly in `t` between samples (and between the reference's\n * samples, where it bends), so they're exact where the walk is straight between samples: our lines,\n * and a host polyline sampled at its vertices. Along a curve they're approximate; denser samples\n * narrow the error.\n * - **Gaps.** Nothing is interpolated across a sample with `gapBefore`, the mark's or the reference's:\n * where either has no value, nothing is coloured. `slice()` leaves the mark's own gaps out too.\n *\n * It draws at once, with no animation, and redraws on every `onChange`, so it follows a line as it's\n * revealed. Its end state is the same picture, so the colour shows with motion off.\n */\nexport function threshold(options: ThresholdOptions): DataEffect {\n checkOptions(options);\n const { compareTo } = options;\n const when = options.when ?? \"below\";\n const color = options.color ?? \"negative\";\n\n /** Draws the runs on the mark, and again whenever it or its data change. */\n const follow = (mark: MarkGeometry, data: MarkData, ctx: EffectContext): void => {\n const paths: PathHandle[] = [];\n let latest = data;\n const draw = (current: MarkGeometry): void => {\n const parts = current.length >= MIN_WALK ? runs(latest.samples, reference(compareTo, latest), when) : [];\n const paint: Paint = { stroke: color, width: current.thickness, linecap: \"butt\" };\n parts.forEach(([t0, t1], i) => {\n const d = current.slice(t0, t1);\n const path = paths[i];\n if (path) path.update(d, paint);\n else paths.push(ctx.layer.path(d, paint));\n });\n for (const path of paths.splice(parts.length)) path.remove();\n };\n ctx.onChange((next, nextData) => {\n latest = nextData ?? latest;\n draw(next);\n });\n draw(mark);\n };\n\n return {\n kind: \"data\",\n ...(typeof compareTo === \"string\" ? { needs: Object.freeze({ related: Object.freeze([compareTo]) }) } : {}),\n run: async (mark, data, ctx) => {\n if (!ctx.signal.aborted) follow(mark, data, ctx);\n },\n end: (mark, data, ctx) => follow(mark, data, ctx),\n clear() {}\n };\n}\n\n/** What the mark's values are compared with, along some axis `u`: the samples' `at`, or their `t`. */\ninterface Reference {\n /** Where a mark's sample sits on the reference's axis. */\n place(sample: Sample): number;\n /** The reference at u, or undefined outside its range and inside its gaps (their ends have values). */\n valueAt(u: number): number | undefined;\n /** Where the reference bends, in u: its samples' places. */\n readonly bends: readonly number[];\n}\n\n/** The reference for the mark's data, or undefined when the related series is missing. */\nfunction reference(compareTo: number | string, data: MarkData): Reference | undefined {\n if (typeof compareTo === \"number\") return { place: (sample) => sample.t, valueAt: () => compareTo, bends: [] };\n const related = data.related(compareTo);\n if (!related) return undefined;\n const byAt = data.samples.every((sample) => numeric(sample.at) !== undefined) && related.samples.every((sample) => numeric(sample.at) !== undefined);\n const place = byAt ? (sample: Sample) => numeric(sample.at)! : (sample: Sample) => sample.t;\n const points = related.samples\n .map((sample) => ({ u: place(sample), value: sample.value }))\n .filter((point) => Number.isFinite(point.u))\n .sort((a, b) => a.u - b.u);\n const gaps = gapsOf(related.samples, place);\n return { place, valueAt: (u) => (inside(gaps, u) ? undefined : interpolate(points, u)), bends: points.map((point) => point.u) };\n}\n\n/** Where the samples have no value, in u: from the sample before each `gapBefore` to it, merged and in order. */\nfunction gapsOf(samples: readonly Sample[], place: (sample: Sample) => number): [number, number][] {\n const gaps: [number, number][] = [];\n samples.forEach((sample, i) => {\n const before = samples[i - 1];\n if (sample.gapBefore !== true || !before) return;\n const u = place(before);\n const v = place(sample);\n if (Number.isFinite(u) && Number.isFinite(v) && u !== v) gaps.push([Math.min(u, v), Math.max(u, v)]);\n });\n gaps.sort((a, b) => a[0] - b[0]);\n const merged: [number, number][] = [];\n for (const gap of gaps) {\n const last = merged[merged.length - 1];\n if (last && gap[0] < last[1]) last[1] = Math.max(last[1], gap[1]);\n else merged.push(gap);\n }\n return merged;\n}\n\n/** Whether u is strictly inside one of the gaps (merged and in order). */\nfunction inside(gaps: readonly (readonly [number, number])[], u: number): boolean {\n // The gap after the last one that starts before u.\n let lo = 0;\n let hi = gaps.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (gaps[mid]![0] < u) lo = mid + 1;\n else hi = mid;\n }\n const gap = gaps[lo - 1];\n return gap !== undefined && u < gap[1];\n}\n\n/** A sample's `at` as a number: a finite number, or a valid Date's time. Labels have none. */\nfunction numeric(at: Sample[\"at\"]): number | undefined {\n const value = typeof at === \"number\" ? at : at instanceof Date ? at.getTime() : undefined;\n return value !== undefined && Number.isFinite(value) ? value : undefined;\n}\n\n/** The value at u, linear between the points around it (sorted by u); undefined outside them. */\nfunction interpolate(points: readonly { readonly u: number; readonly value: number }[], u: number): number | undefined {\n const first = points[0];\n const last = points[points.length - 1];\n if (!first || !last || u < first.u || u > last.u) return undefined;\n // The first point at u or past it.\n let lo = 0;\n let hi = points.length - 1;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (points[mid]!.u < u) lo = mid + 1;\n else hi = mid;\n }\n const b = points[lo]!;\n if (lo === 0 || b.u === u) return b.value;\n const a = points[lo - 1]!;\n return a.value + ((u - a.u) / (b.u - a.u)) * (b.value - a.value);\n}\n\n/** A place along the walk, with how far past the reference the mark is there: more than 0 is coloured. */\ninterface Station {\n readonly t: number;\n /** Where it is on the reference's axis. */\n readonly u: number;\n /** Undefined where there's no reference or no finite value. */\n readonly past: number | undefined;\n /** False after a gap in the mark's values: nothing is coloured between it and the station before. */\n readonly joined: boolean;\n}\n\n/**\n * The parts of the walk, as [t0, t1] in order, where the mark's values are past the reference on the\n * `when` side. Between neighbouring stations (the samples, plus the places where the reference bends\n * between them) both are linear in t, so each crossing is where that difference reaches 0. Stations\n * either side of a gap, the mark's or the reference's, aren't joined.\n */\nfunction runs(samples: readonly Sample[], ref: Reference | undefined, when: \"below\" | \"above\"): [number, number][] {\n if (!ref) return [];\n const sign = when === \"below\" ? 1 : -1;\n const station = (t: number, u: number, value: number, joined = true): Station => {\n const level = ref.valueAt(u);\n if (level === undefined || !Number.isFinite(level) || !Number.isFinite(value) || !Number.isFinite(t)) return { t, u, past: undefined, joined };\n const past = sign * (level - value);\n return { t, u, past: Math.abs(past) <= TIE * Math.max(Math.abs(level), Math.abs(value)) ? 0 : past, joined };\n };\n\n const stations: Station[] = [];\n samples.forEach((sample, i) => {\n const u = ref.place(sample);\n stations.push(station(sample.t, u, sample.value, sample.gapBefore !== true));\n const next = samples[i + 1];\n // No bends across a gap in the mark's values: there's nothing there to compare.\n if (!next || next.gapBefore === true) return;\n // Where the reference bends between this sample and the next, in the order the walk meets them.\n const v = ref.place(next);\n if (u === v || !Number.isFinite(u) || !Number.isFinite(v)) return;\n const shares: number[] = [];\n const { bends } = ref;\n for (let j = firstAbove(bends, Math.min(u, v)); j < bends.length && bends[j]! < Math.max(u, v); j++) shares.push((bends[j]! - u) / (v - u));\n if (v < u) shares.reverse();\n for (const share of shares) {\n stations.push(station(sample.t + share * (next.t - sample.t), u + share * (v - u), sample.value + share * (next.value - sample.value)));\n }\n });\n\n const parts: [number, number][] = [];\n const add = (t0: number, t1: number): void => {\n const from = clamp(t0);\n const to = clamp(t1);\n if (!(to > from)) return;\n const last = parts[parts.length - 1];\n if (last && last[1] >= from) last[1] = Math.max(last[1], to);\n else parts.push([from, to]);\n };\n for (let i = 1; i < stations.length; i++) {\n const a = stations[i - 1]!;\n const b = stations[i]!;\n if (a.past === undefined || b.past === undefined || !b.joined || !(b.t > a.t)) continue;\n // Between two stations the reference doesn't bend, so it's in a gap there if it is halfway.\n if (a.u !== b.u && ref.valueAt((a.u + b.u) / 2) === undefined) continue;\n if (a.past > 0 && b.past > 0) add(a.t, b.t);\n else if (a.past > 0) add(a.t, a.t + (b.t - a.t) * (a.past / (a.past - b.past)));\n else if (b.past > 0) add(a.t + (b.t - a.t) * (a.past / (a.past - b.past)), b.t);\n }\n return parts;\n}\n\nconst clamp = (t: number): number => Math.min(1, Math.max(0, t));\n\n/** The index of the first value more than x, in ascending values. */\nfunction firstAbove(values: readonly number[], x: number): number {\n let lo = 0;\n let hi = values.length;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (values[mid]! <= x) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n}\n\nfunction checkOptions(options: ThresholdOptions): void {\n const { compareTo, when, color } = (options ?? {}) as Partial<ThresholdOptions>;\n if (!(typeof compareTo === \"string\" ? compareTo !== \"\" : typeof compareTo === \"number\" && Number.isFinite(compareTo))) {\n throw new RangeError(`threshold: compareTo must be a finite number or a series name, got ${show(compareTo)}.`);\n }\n if (when !== undefined && !WHENS.includes(when)) throw new RangeError(`threshold: when must be \"below\" or \"above\", got ${show(when)}.`);\n if (color !== undefined && (typeof color !== \"string\" || color === \"\")) {\n throw new RangeError(`threshold: color must be a theme token or a CSS colour, got ${show(color)}.`);\n }\n}\n\nconst show = (value: unknown): string => (typeof value === \"string\" ? JSON.stringify(value) : String(value));\n","// morph: the transition effect that turns one mark's shape into another's, as the lab's donut turns\n// into columns. Both outlines are sampled at the same number of points and each point moves in a\n// straight line to its partner. It reads only the two geometries, so it morphs any mark into any\n// other: bars, slices and points (closed outlines) and lines (open ones).\n\nimport { easeInOutCubic, linear } from \"../core\";\nimport type { Layer, MarkGeometry, Paint, PathHandle, Point, TransitionEffect, Tween } from \"../core\";\nimport { unease } from \"../core/easing\";\nimport { formatNumber } from \"../core/geometry\";\nimport { goesRound } from \"../core/geometry/ring\";\n\n/** How two closed outlines' sides are matched. */\nexport type MorphAlign = \"unroll\" | \"drop\";\n\nexport interface MorphOptions {\n /** Points sampled on each outline, a whole multiple of 4 (a quarter on each side of a closed one). Default 160, the lab's 40 a side. */\n readonly points?: number;\n /**\n * How two closed outlines' sides are matched:\n * - \"unroll\" matches each side with the same side. A slice's walk becomes a column's, so the slice\n * stands up: its outer arc becomes the column's left side, and the angle it spans its height.\n * - \"drop\" turns the matching by one side, as the lab does: a slice's outer arc becomes a column's\n * top, so it settles onto the baseline.\n *\n * Default \"unroll\", picked over \"drop\" by comparing the two in the morph demo (demo/morph.html).\n */\n readonly align?: MorphAlign;\n}\n\n/** The lab's morph: 950 ms base, with transition timing. */\nconst DURATION = 950;\nconst POINTS = 160;\nconst ALIGNS: readonly string[] = [\"unroll\", \"drop\"];\n\n/** Draws the morph at eased progress p, from 0 (`from`) to 1 (`to`), creating or updating its paths. */\ntype Draw = (p: number) => void;\n\n/**\n * Morphs `from` into `to` over 950 ms base (`transition` timing: at most 200 ms in Analysis, a jump\n * in Off), eased in and out.\n *\n * - **Two closed outlines** (bars, slices, points): both are sampled at `points`, and each point\n * moves in a straight line to its partner, drawn as one filled path in the mark's colour. With\n * `align: \"drop\"` the pairing is turned by a quarter, from a mark that goes round its pivot (a\n * slice) to one that doesn't (a bar), whichever is `from`: so a switch back retraces the same\n * pairing instead of twisting. Between two marks of the same kind, \"drop\" pairs as \"unroll\" does.\n * - **Two open outlines** (lines): both strokes are sampled along their length, and the stroke's\n * width moves from one thickness to the other.\n * - **A closed and an open outline** crossfade: the first fades out as the second fades in.\n *\n * A run from `ctx.start` begins with the shapes there, in their eased progress, and takes the rest\n * of the time a full run would. The end state is the target's own outline.\n */\nexport function morph(options: MorphOptions = {}): TransitionEffect {\n checkOptions(options);\n const points = options?.points ?? POINTS;\n const align = options?.align ?? \"unroll\";\n\n return {\n kind: \"transition\",\n async run(from, to, ctx) {\n if (ctx.signal.aborted) return;\n const draw = drawing(from, to, ctx.layer, points, align);\n const start = startOf(ctx.start);\n if (start >= 1) {\n draw(1);\n return;\n }\n // When a full run's shapes are at `start`: the run plays from there, so it takes the rest of\n // the full run's time, whatever the motion mode scales that to.\n const begun = unease(start);\n let running: Tween | undefined;\n running = ctx.tween({\n duration: DURATION,\n timing: \"transition\",\n ease: linear,\n update: (k) => {\n const u = Math.min(1, begun + k);\n draw(k === 0 ? start : easeInOutCubic(u));\n if (u >= 1 && k < 1) running?.finish();\n }\n });\n await running.finished;\n },\n end(from, to, ctx) {\n drawing(from, to, ctx.layer, points, align)(1);\n },\n clear() {}\n };\n}\n\nfunction drawing(from: MarkGeometry, to: MarkGeometry, layer: Layer, points: number, align: MorphAlign): Draw {\n const closed = from.outline.closed;\n if (closed !== to.outline.closed) return crossfade(from, to, layer);\n const a = from.outline.sample(points);\n const b = to.outline.sample(points);\n if (!closed) return stroke(from, to, layer, a, b);\n const [shiftA, shiftB] = align === \"drop\" ? turn(from, to, points) : [0, 0];\n let path: PathHandle | undefined;\n return (p) => {\n const d = p <= 0 ? from.outline.d : p >= 1 ? to.outline.d : between(a, b, shiftA, shiftB, p, true);\n if (path) path.update(d);\n else path = layer.path(d, { fill: \"mark\" });\n };\n}\n\n/** One stroke whose points and width move between the two lines'. */\nfunction stroke(from: MarkGeometry, to: MarkGeometry, layer: Layer, a: readonly Point[], b: readonly Point[]): Draw {\n let path: PathHandle | undefined;\n return (p) => {\n const d = p <= 0 ? from.outline.d : p >= 1 ? to.outline.d : between(a, b, 0, 0, p, false);\n const width = p <= 0 ? from.thickness : p >= 1 ? to.thickness : mix(from.thickness, to.thickness, p);\n if (path) path.update(d, { width });\n else path = layer.path(d, { stroke: \"mark\", width });\n };\n}\n\n/** The two outlines as they are, the closed one below the open one, whichever is leaving: so a switch back draws the same picture. */\nfunction crossfade(from: MarkGeometry, to: MarkGeometry, layer: Layer): Draw {\n const paint = (mark: MarkGeometry, opacity?: number): Paint => ({\n ...(mark.outline.closed ? { fill: \"mark\" } : { stroke: \"mark\", width: mark.thickness }),\n ...(opacity === undefined ? {} : { opacity })\n });\n let leaving: PathHandle | undefined;\n let coming: PathHandle | undefined;\n return (p) => {\n if (p >= 1) {\n leaving?.remove();\n leaving = undefined;\n if (coming) coming.update(to.outline.d, { opacity: undefined });\n else coming = layer.path(to.outline.d, paint(to));\n return;\n }\n if (coming) {\n leaving?.update(from.outline.d, { opacity: 1 - p });\n coming.update(to.outline.d, { opacity: p });\n } else if (from.outline.closed) {\n leaving = layer.path(from.outline.d, paint(from, 1 - p));\n coming = layer.path(to.outline.d, paint(to, p));\n } else {\n coming = layer.path(to.outline.d, paint(to, p));\n leaving = layer.path(from.outline.d, paint(from, 1 - p));\n }\n };\n}\n\n/**\n * Path data for the shape at p: point i is a[i + shiftA] moved toward b[i + shiftB] (indices wrap).\n * The shifts start the path at the same pair whichever mark is `from`, so a run back from 1 - p\n * draws exactly what the run forward drew at p.\n */\nfunction between(a: readonly Point[], b: readonly Point[], shiftA: number, shiftB: number, p: number, closed: boolean): string {\n const n = a.length;\n let d = \"\";\n for (let i = 0; i < n; i++) {\n const from = a[(i + shiftA) % n]!;\n const to = b[(i + shiftB) % n]!;\n d += `${i === 0 ? \"M\" : \"L\"}${formatNumber(mix(from.x, to.x, p))},${formatNumber(mix(from.y, to.y, p))}`;\n }\n return closed ? `${d}Z` : d;\n}\n\n/**\n * x moved toward y by p, weighted on both sides so that mix(y, x, 1 - p) is the same number: a run\n * back rounds every coordinate as the run forward did, even on a half (36.5625 at 0.001).\n */\nconst mix = (x: number, y: number, p: number): number => x * (1 - p) + y * p;\n\n/**\n * \"drop\"'s quarter turn, as [shift into from's samples, shift into to's]: the round mark's point i\n * pairs with the other's point i + n/4, so its first side (a slice's outer arc) meets the other's\n * end side (a column's top). Fixed by the marks' geometry, never by which one is `from`: whether a\n * walk goes round its pivot (a slice's does, a bar's doesn't), the test the adapter orders a ring by.\n */\nfunction turn(from: MarkGeometry, to: MarkGeometry, points: number): [number, number] {\n const quarter = points / 4;\n const roundFrom = goesRound(from);\n if (roundFrom === goesRound(to)) return [0, 0];\n return roundFrom ? [0, quarter] : [quarter, 0];\n}\n\n/** `ctx.start` clamped to 0–1; anything else is 0, so a context without one plays it all. */\nfunction startOf(start: unknown): number {\n return typeof start === \"number\" && start > 0 ? Math.min(1, start) : 0;\n}\n\nfunction checkOptions(options: MorphOptions): void {\n const { points, align } = (options ?? {}) as MorphOptions;\n if (points !== undefined && !(Number.isInteger(points) && points >= 4 && points % 4 === 0)) {\n throw new RangeError(`morph: points must be a whole multiple of 4, got ${String(points)}.`);\n }\n if (align !== undefined && !ALIGNS.includes(align)) throw new RangeError(`morph: align must be \"unroll\" or \"drop\", got ${typeof align === \"string\" ? JSON.stringify(align) : String(align)}.`);\n}\n","// Combinators: small effects put together. Every part shares the run's context (its layer, mark\n// handle and signal), and a combination is a data effect when any part is one.\n\nimport type { AnyMarkEffect, Combined, DataEffect, EffectContext, GeometryEffect, MarkData, MarkGeometry } from \"../core\";\nimport { describeValue, isMarkEffect } from \"../core/registry\";\n\n/**\n * Runs the parts one after another, each on the geometry and data as they are when it starts, since\n * the mark may move while an earlier part runs (a transition, a line being revealed). An abort stops\n * the chain, and `end()` draws every part's end state in order. A part with nothing to do (a travel\n * along a missing segment) finishes at once, so one sequence tells the whole story whatever the chart\n * shows.\n */\nexport function sequence<E extends readonly AnyMarkEffect[]>(...effects: E): Combined<E> {\n const parts = check(\"sequence\", effects);\n return combine<E>(parts, async (start, ctx) => {\n for (const part of parts) {\n if (ctx.signal.aborted) return;\n await start(part);\n }\n });\n}\n\n/** Runs the parts together and finishes when they all have. `end()` draws every part's end state, in order. */\nexport function parallel<E extends readonly AnyMarkEffect[]>(...effects: E): Combined<E> {\n const parts = check(\"parallel\", effects);\n return combine<E>(parts, async (start) => {\n await Promise.all(parts.map(start));\n });\n}\n\n/**\n * What `only` and `stagger` return: a new effect of the same kind, needing the same rows. Only the\n * effect interface is kept, not any other members the effect has.\n */\ntype Filtered<E extends AnyMarkEffect> = E extends DataEffect<infer D> ? DataEffect<D> : GeometryEffect;\n\n/** Runs the effect only on matching marks: a key, a series name, or a predicate. Elsewhere it does nothing. */\nexport function only<E extends AnyMarkEffect>(filter: string | ((mark: MarkGeometry) => boolean), effect: E): Filtered<E> {\n if (typeof filter !== \"string\" && typeof filter !== \"function\") throw new TypeError(`only needs a key, a series name or a predicate, got ${describeValue(filter)}.`);\n const [part] = check(\"only\", [effect]);\n const matches = typeof filter === \"string\" ? (mark: MarkGeometry) => mark.key === filter || mark.series === filter : filter;\n if (part!.kind === \"data\") {\n const inner = part as DataEffect<unknown>;\n const filtered: DataEffect<unknown> = {\n kind: \"data\",\n ...(inner.needs ? { needs: inner.needs } : {}),\n run: (mark, data, ctx) => (matches(mark) ? inner.run(mark, data, ctx) : Promise.resolve()),\n end: (mark, data, ctx) => {\n if (matches(mark)) inner.end(mark, data, ctx);\n },\n clear: (ctx) => inner.clear(ctx)\n };\n return filtered as Filtered<E>;\n }\n const inner = part as GeometryEffect;\n const filtered: GeometryEffect = {\n kind: \"geometry\",\n run: (mark, ctx) => (matches(mark) ? inner.run(mark, ctx) : Promise.resolve()),\n end(mark, ctx) {\n if (matches(mark)) inner.end(mark, ctx);\n },\n clear: (ctx) => inner.clear(ctx)\n };\n return filtered as Filtered<E>;\n}\n\nexport interface StaggerOptions {\n /** Base ms between one mark's start and the next's, 0 or more. Default 50. */\n readonly delay?: number;\n}\n\n/** Default base delay between marks, ms. */\nconst STAGGER_DELAY = 50;\n/** The last mark of a batch starts at most this long (base ms) after the first. */\nconst STAGGER_SPREAD = 500;\n\n/**\n * Starts each mark of a batch a little after the one before: mark i waits `i × delay` (base ms,\n * with \"stagger\" timing, so none at all in analysis or off), then runs the effect. The whole spread\n * is capped at 500 ms base, so a big batch's delay shrinks. A batch of one (a hover) never waits.\n *\n * Never a default: research finds little benefit in staggering, and it can hurt. It keeps the\n * effect's kind and `needs`, and `end()` draws the effect's end state at once.\n */\nexport function stagger<E extends AnyMarkEffect>(effect: E, options: StaggerOptions = {}): Filtered<E> {\n const [part] = check(\"stagger\", [effect]);\n const delay = options.delay ?? STAGGER_DELAY;\n if (!(typeof delay === \"number\" && delay >= 0 && Number.isFinite(delay))) {\n throw new RangeError(`stagger: delay must be 0 ms or more, got ${String(delay)}.`);\n }\n\n /**\n * Waits this mark's turn. The geometry and data may move meanwhile (marks growing in on enter), so\n * it resolves with the latest of each; undefined if the run was aborted while it waited.\n */\n const wait = async <M>(mark: MarkGeometry, data: M, ctx: EffectContext): Promise<Latest<M> | undefined> => {\n if (ctx.signal.aborted) return undefined;\n const { index, count } = ctx.batch;\n const step = count > 1 ? Math.min(delay, STAGGER_SPREAD / (count - 1)) : 0;\n const base = index > 0 ? index * step : 0;\n if (!(base > 0)) return { mark, data };\n const now = follow(mark, data, ctx);\n await ctx.tween({ duration: base, timing: \"stagger\", update: () => {} }).finished;\n return ctx.signal.aborted ? undefined : now();\n };\n\n if (part!.kind === \"data\") {\n const inner = part as DataEffect<unknown>;\n const staggered: DataEffect<unknown> = {\n kind: \"data\",\n ...(inner.needs ? { needs: inner.needs } : {}),\n run: async (mark, data, ctx) => {\n const turn = await wait(mark, data, ctx);\n if (turn) await inner.run(turn.mark, turn.data, ctx);\n },\n end: (mark, data, ctx) => inner.end(mark, data, ctx),\n clear: (ctx) => inner.clear(ctx)\n };\n return staggered as Filtered<E>;\n }\n const inner = part as GeometryEffect;\n const staggered: GeometryEffect = {\n kind: \"geometry\",\n async run(mark, ctx) {\n const turn = await wait(mark, undefined, ctx);\n if (turn) await inner.run(turn.mark, ctx);\n },\n end: (mark, ctx) => inner.end(mark, ctx),\n clear: (ctx) => inner.clear(ctx)\n };\n return staggered as Filtered<E>;\n}\n\n/** A mark's geometry and data as they are now. */\ninterface Latest<M> {\n readonly mark: MarkGeometry;\n readonly data: M;\n}\n\n/** The geometry and data as they are now: those given, until onChange brings newer ones. */\nfunction follow<M>(mark: MarkGeometry, data: M, ctx: EffectContext): () => Latest<M> {\n let latest: Latest<M> = { mark, data };\n ctx.onChange((next, nextData) => {\n latest = { mark: next, data: (nextData as M | undefined) ?? latest.data };\n });\n return () => latest;\n}\n\ntype Start = (part: AnyMarkEffect) => Promise<void>;\n\n/** Builds the combination's effect object, of the kind its parts make it. */\nfunction combine<E extends readonly AnyMarkEffect[]>(parts: readonly AnyMarkEffect[], play: (start: Start, ctx: EffectContext) => Promise<void>): Combined<E> {\n // Each part starts on the latest geometry and data, so a sequence's later parts don't start where the mark was.\n const starter = (mark: MarkGeometry, data: MarkData<unknown> | undefined, ctx: EffectContext): Start => {\n const now = follow(mark, data, ctx);\n return (part) => {\n const { mark: latest, data: values } = now();\n return part.kind === \"data\" ? part.run(latest, values!, ctx) : part.run(latest, ctx);\n };\n };\n const end = (mark: MarkGeometry, data: MarkData<unknown> | undefined, ctx: EffectContext): void => {\n for (const part of parts) {\n if (part.kind === \"data\") part.end(mark, data!, ctx);\n else part.end(mark, ctx);\n }\n };\n // Every part gets to clean up, even if one throws; the first error is passed on.\n const clear = (ctx: EffectContext): void => {\n let failure: { error: unknown } | undefined;\n for (const part of parts) {\n try {\n part.clear(ctx);\n } catch (error) {\n failure ??= { error };\n }\n }\n if (failure) throw failure.error;\n };\n\n if (parts.some((part) => part.kind === \"data\")) {\n const related = [...new Set(parts.flatMap((part) => (part.kind === \"data\" ? (part.needs?.related ?? []) : [])))];\n const effect: DataEffect<unknown> = {\n kind: \"data\",\n ...(related.length > 0 ? { needs: { related } } : {}),\n run: (mark, data, ctx) => play(starter(mark, data, ctx), ctx),\n end: (mark, data, ctx) => end(mark, data, ctx),\n clear\n };\n return effect as unknown as Combined<E>;\n }\n const effect: GeometryEffect = {\n kind: \"geometry\",\n run: (mark, ctx) => play(starter(mark, undefined, ctx), ctx),\n end: (mark, ctx) => end(mark, undefined, ctx),\n clear\n };\n return effect as unknown as Combined<E>;\n}\n\nfunction check(name: string, effects: readonly unknown[]): readonly AnyMarkEffect[] {\n effects.forEach((effect, index) => {\n if (!isMarkEffect(effect)) throw new TypeError(`${name}: part ${index + 1} needs to be a mark effect (kind \"geometry\" or \"data\"), got ${describeValue(effect)}.`);\n });\n return [...(effects as readonly AnyMarkEffect[])];\n}\n","// defineEffect and defineDataEffect: how effects written outside the library are made. They fill in\n// the kind and a no-op clear(), check that the effect can run and has an end state, and freeze it,\n// since one effect object runs on many marks at once (effects are stateless).\n\nimport type { DataEffect, EffectContext, GeometryEffect, MarkData, MarkGeometry } from \"../core\";\n\n/** What defineEffect takes: a geometry effect without its `kind`, `clear()` optional. */\nexport interface GeometryEffectSpec {\n /** Animates the mark; resolves when done or cancelled (ctx.signal aborted). */\n run(mark: MarkGeometry, ctx: EffectContext): Promise<void>;\n /** Draws the state a full run ends in, at once. Reduced motion shows only this. */\n end(mark: MarkGeometry, ctx: EffectContext): void;\n /** Cleanup beyond the runner's own (it empties the layer and resets the mark anyway). */\n clear?(ctx: EffectContext): void;\n}\n\n/**\n * What defineDataEffect takes: a data effect without its `kind`, `clear()` optional. As on\n * DataEffect, the functions are properties rather than methods, so the row type is checked strictly:\n * methods would let a spec that reads fields `D` doesn't have through.\n */\nexport interface DataEffectSpec<D> {\n /** Series the effect reads through data.related(), checked when a chart is created. */\n readonly needs?: { readonly related?: readonly string[] };\n readonly run: (mark: MarkGeometry, data: MarkData<D>, ctx: EffectContext) => Promise<void>;\n readonly end: (mark: MarkGeometry, data: MarkData<D>, ctx: EffectContext) => void;\n readonly clear?: (ctx: EffectContext) => void;\n}\n\nconst nothing = (): void => {};\n\n/**\n * A geometry effect from its `run` and `end`: `kind` is filled in and `clear` defaults to doing\n * nothing. Only `run`, `end` and `clear` are kept, and the effect is frozen. A spec without `run` or\n * `end` functions throws a TypeError: every effect needs an end state, since reduced motion shows\n * only that.\n */\nexport function defineEffect(spec: GeometryEffectSpec): GeometryEffect {\n check(\"defineEffect\", spec);\n const effect: GeometryEffect = { kind: \"geometry\", run: spec.run, end: spec.end, clear: spec.clear ?? nothing };\n return Object.freeze(effect);\n}\n\n/**\n * A data effect from its `run` and `end`, which also get the mark's data (`MarkData<D>`): its row,\n * values along the walk, related series and the values before an update. `needs.related` lists the\n * series it reads through `data.related()`, so a chart without them throws when it's created.\n * Otherwise as defineEffect.\n */\nexport function defineDataEffect<D = unknown>(spec: DataEffectSpec<D>): DataEffect<D> {\n check(\"defineDataEffect\", spec);\n const needs = checkNeeds(spec.needs);\n const effect: DataEffect<D> = { kind: \"data\", ...(needs ? { needs } : {}), run: spec.run, end: spec.end, clear: spec.clear ?? nothing };\n return Object.freeze(effect);\n}\n\nfunction check(name: string, spec: unknown): void {\n if (typeof spec !== \"object\" || spec === null) throw new TypeError(`${name} needs a spec object { run, end }, got ${spec === null ? \"null\" : typeof spec}.`);\n const { run, end, clear } = spec as Record<string, unknown>;\n if (typeof run !== \"function\") throw new TypeError(`${name}: run must be a function that animates the mark, got ${typeof run}.`);\n if (typeof end !== \"function\") {\n throw new TypeError(`${name}: end must be a function that draws the final state, got ${typeof end}. Every effect needs one: reduced motion shows only end states.`);\n }\n if (clear !== undefined && typeof clear !== \"function\") throw new TypeError(`${name}: clear must be a function if it's given, got ${typeof clear}.`);\n}\n\n/** A copy of `needs`, frozen, or undefined when it names no series. */\nfunction checkNeeds(needs: unknown): DataEffect[\"needs\"] {\n if (needs === undefined) return undefined;\n const related = typeof needs === \"object\" && needs !== null ? (needs as { related?: unknown }).related : undefined;\n const valid = typeof needs === \"object\" && needs !== null && (related === undefined || (Array.isArray(related) && related.every((s) => typeof s === \"string\" && s !== \"\")));\n if (!valid) throw new TypeError(`defineDataEffect: needs must be { related: [series names] }, got ${JSON.stringify(needs) ?? String(needs)}.`);\n return related === undefined ? undefined : Object.freeze({ related: Object.freeze([...(related as string[])]) });\n}\n","// iconFromSvg: turns SVG markup into an icon's shapes, keeping only plain drawing. It reads the\n// markup as text (no DOM, no parser that could load anything), so it's safe for untrusted input.\n\nimport type { Icon, IconShape, Matrix, Point, Rect } from \"../core\";\nimport { matrix } from \"../core\";\nimport { parseTransform } from \"../core/geometry\";\nimport { formatPath, shapeOutline, transformPath } from \"../core/geometry/path\";\nimport { defineIcon, type IconSpec } from \"./define\";\n\n/**\n * What iconFromSvg takes besides the markup. `anchor`, `pivot`, `footprint` and `radius` are in the\n * SVG's own units (its viewBox). `size` is the natural length in px: the whole icon is scaled so its\n * box is that wide. Default: the viewBox's width, unscaled.\n */\nexport type SvgIconSpec = Omit<IconSpec, \"shapes\" | \"box\">;\n\n/** Elements whose children are drawn. Every other element that isn't a shape is dropped with its children. */\nconst CONTAINERS = new Set([\"svg\", \"g\", \"a\"]);\nconst SHAPES = new Set([\"path\", \"circle\", \"rect\", \"ellipse\", \"line\", \"polyline\", \"polygon\"]);\n// No part of a tag can contain \"<\" (XML doesn't allow it in attribute values), so a scan never runs\n// past the next tag and unclosed tags can't make matching slow.\nconst TAG = /<![^<>]*>|<(\\/?)([A-Za-z][\\w:.-]*)((?:\\s+[^\\s=/<>]+(?:\\s*=\\s*(?:\"[^\"<]*\"|'[^'<]*'|[^\\s\"'<>]+))?)*)\\s*(\\/?)>/g;\nconst ATTRIBUTE = /([^\\s=/<>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'<>]+)))?/g;\n/** Plain colours and theme tokens. url() paint servers and anything with quotes or brackets are not kept. */\nconst COLOR = /^(?:#[0-9a-fA-F]{3,8}|[a-zA-Z][a-zA-Z0-9-]*|(?:rgba?|hsla?)\\([\\d\\s.,%+\\-/]*\\))$/;\n\ninterface Inherited {\n readonly fill: string;\n readonly stroke: string;\n readonly width: number;\n readonly linecap: IconShape[\"linecap\"];\n readonly linejoin: IconShape[\"linejoin\"];\n readonly fillRule: NonNullable<IconShape[\"fillRule\"]>;\n /** The shape's own opacity times its groups'. */\n readonly opacity: number;\n /** The nearest one set, the shape's own or a group's, as SVG inherits them. */\n readonly fillOpacity: number;\n readonly strokeOpacity: number;\n readonly transform: Matrix;\n}\n\n/**\n * Converts `path`, `circle`, `rect`, `ellipse`, `line`, `polyline` and `polygon` elements into shapes,\n * with their fill, stroke, stroke width, line caps and joins, fill rule, opacity, fill opacity and stroke\n * opacity (as attributes or in `style`, inherited from `<g>`, a group's opacity multiplied into its\n * shapes') and transforms applied. `currentColor` becomes the theme's `text` colour, so an icon from an\n * icon set follows the chart's theme. Everything else is dropped: scripts, event handlers, `<use>`, text,\n * images, what's inside `<defs>`, `<clipPath>` and the like, shapes with an opacity of 0, and fills and\n * strokes with one of 0. Gradients, patterns and CSS classes aren't kept; a shape painted with a gradient\n * or pattern falls back to its inherited colour.\n */\nexport function iconFromSvg(markup: string, spec: SvgIconSpec): Icon {\n if (typeof markup !== \"string\") throw new TypeError(\"iconFromSvg needs SVG markup as a string.\");\n const label = typeof spec?.name === \"string\" ? `\"${spec.name}\"` : \"an icon\";\n const fail = (problem: string): never => {\n throw new RangeError(`iconFromSvg: ${label} ${problem}.`);\n };\n\n let box: Rect | undefined;\n let scale = 1;\n const shapes: IconShape[] = [];\n // One entry per open element; undefined while inside something dropped.\n const stack: { readonly tag: string; readonly state: Inherited | undefined }[] = [];\n let root: Inherited | undefined;\n\n for (const match of withoutComments(markup).matchAll(TAG)) {\n const [, closing, rawTag, rawAttributes = \"\", selfClosing] = match;\n if (rawTag === undefined) continue; // a doctype\n const tag = rawTag.toLowerCase();\n if (closing) {\n const index = findLast(stack, tag);\n if (index >= 0) stack.length = index;\n continue;\n }\n const attributes = readAttributes(rawAttributes);\n const first = !box && tag === \"svg\";\n if (first) {\n box = viewBox(attributes) ?? fail(\"needs a viewBox, or a width and height in px, on its <svg>\");\n if (spec.size !== undefined) {\n if (typeof spec.size !== \"number\" || !(spec.size > 0) || !Number.isFinite(spec.size)) fail(`size must be more than 0, got ${String(spec.size)}`);\n scale = spec.size / box.width;\n }\n root = { fill: \"#000000\", stroke: \"none\", width: 1, linecap: undefined, linejoin: undefined, fillRule: \"nonzero\", opacity: 1, fillOpacity: 1, strokeOpacity: 1, transform: matrix.scale(scale) };\n }\n // Only what's inside the first <svg> is drawn.\n const parent = stack.length > 0 ? stack[stack.length - 1]!.state : first ? root : undefined;\n const state = parent && !hidden(attributes) ? inherit(parent, attributes) : undefined;\n if (state && SHAPES.has(tag)) {\n const shape = toShape(tag, attributes, state);\n if (shape) shapes.push(shape);\n }\n if (!selfClosing) stack.push({ tag, state: CONTAINERS.has(tag) ? state : undefined });\n }\n\n if (!box) fail(\"needs an <svg> element\");\n if (shapes.length === 0) fail(\"has nothing to draw: no path, circle, rect, ellipse, line, polyline or polygon with a fill or stroke\");\n const sized: Rect = { x: box!.x * scale, y: box!.y * scale, width: box!.width * scale, height: box!.height * scale };\n const at = (point: Point): Point => (point && typeof point === \"object\" ? { x: point.x * scale, y: point.y * scale } : point);\n return defineIcon({\n ...spec,\n shapes,\n box: sized,\n anchor: at(spec.anchor),\n ...(spec.pivot ? { pivot: at(spec.pivot) } : {}),\n ...(Array.isArray(spec.footprint) ? { footprint: [spec.footprint[0] * scale, spec.footprint[1] * scale] as const } : {}),\n ...(typeof spec.radius === \"number\" ? { radius: spec.radius * scale } : {})\n });\n}\n\n/** Removes comments, CDATA sections and processing instructions in one pass; an unclosed one runs to the end. */\nfunction withoutComments(markup: string): string {\n const pairs: readonly (readonly [open: string, close: string])[] = [[\"<!--\", \"-->\"], [\"<![CDATA[\", \"]]>\"], [\"<?\", \"?>\"]];\n // Where each kind next opens; found again only once the reading has passed it, so this stays linear.\n const opens = pairs.map(([open]) => markup.indexOf(open));\n let out = \"\";\n let i = 0;\n for (;;) {\n let kind = -1;\n opens.forEach((at, k) => {\n if (at >= 0 && (kind < 0 || at < opens[kind]!)) kind = k;\n });\n if (kind < 0) return out + markup.slice(i);\n const at = opens[kind]!;\n const close = pairs[kind]![1];\n out += markup.slice(i, at);\n const end = markup.indexOf(close, at + pairs[kind]![0].length);\n if (end < 0) return out;\n i = end + close.length;\n opens.forEach((open, k) => {\n if (open >= 0 && open < i) opens[k] = markup.indexOf(pairs[k]![0], i);\n });\n }\n}\n\nfunction readAttributes(source: string): Map<string, string> {\n const attributes = new Map<string, string>();\n for (const [, name, double, single, bare] of source.matchAll(ATTRIBUTE)) {\n if (name !== undefined) attributes.set(name, double ?? single ?? bare ?? \"\");\n }\n // Declarations in `style` win over attributes, as in CSS.\n for (const declaration of (attributes.get(\"style\") ?? \"\").split(\";\")) {\n const colon = declaration.indexOf(\":\");\n if (colon > 0) attributes.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).replace(/!important/i, \"\").trim());\n }\n return attributes;\n}\n\nfunction viewBox(attributes: Map<string, string>): Rect | undefined {\n const values = (attributes.get(\"viewBox\") ?? \"\").trim().split(/[\\s,]+/).map(Number);\n if (values.length === 4 && values.every(Number.isFinite) && values[2]! > 0 && values[3]! > 0) {\n return { x: values[0]!, y: values[1]!, width: values[2]!, height: values[3]! };\n }\n const width = pixels(attributes.get(\"width\"));\n const height = pixels(attributes.get(\"height\"));\n return width !== undefined && height !== undefined ? { x: 0, y: 0, width, height } : undefined;\n}\n\n/** The number is read as alpha() reads it, in a form with one way to match, so a long run of digits can't make it slow. */\nfunction pixels(value: string | undefined): number | undefined {\n const match = /^\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)\\s*(?:px\\s*)?$/i.exec(value ?? \"\");\n const number = match ? Number(match[1]) : NaN;\n return number > 0 && Number.isFinite(number) ? number : undefined;\n}\n\n/** An opacity as a number or a percentage, one past 0 or 1 counting as 0 or 1, as in CSS. Undefined when it can't be read. */\nfunction alpha(value: string | undefined): number | undefined {\n const match = /^\\s*([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?)(%?)\\s*$/i.exec(value ?? \"\");\n return match ? Math.min(1, Math.max(0, Number(match[1]) / (match[2] ? 100 : 1))) : undefined;\n}\n\nfunction hidden(attributes: Map<string, string>): boolean {\n return attributes.get(\"display\")?.trim() === \"none\" || attributes.get(\"visibility\")?.trim() === \"hidden\";\n}\n\nfunction inherit(parent: Inherited, attributes: Map<string, string>): Inherited {\n const paint = (name: string, current: string): string => {\n const value = attributes.get(name)?.trim();\n if (value === undefined || !COLOR.test(value)) return current;\n // Keywords are any case. currentColor would follow the page's `color`; the text token follows the chart's theme.\n const keyword = value.toLowerCase();\n return keyword === \"inherit\" ? current : keyword === \"currentcolor\" ? \"text\" : keyword === \"none\" ? keyword : value;\n };\n const width = Number.parseFloat(attributes.get(\"stroke-width\") ?? \"\");\n const linecap = attributes.get(\"stroke-linecap\")?.trim();\n const linejoin = attributes.get(\"stroke-linejoin\")?.trim();\n const fillRule = attributes.get(\"fill-rule\")?.trim().toLowerCase();\n const transform = attributes.get(\"transform\");\n return {\n fill: paint(\"fill\", parent.fill),\n stroke: paint(\"stroke\", parent.stroke),\n width: width >= 0 ? width : parent.width,\n linecap: linecap === \"butt\" || linecap === \"round\" ? linecap : parent.linecap,\n linejoin: linejoin === \"miter\" || linejoin === \"round\" ? linejoin : parent.linejoin,\n fillRule: fillRule === \"nonzero\" || fillRule === \"evenodd\" ? fillRule : parent.fillRule,\n // Opacity isn't inherited in SVG: a group is drawn and then faded. Multiplying is the same unless its shapes overlap.\n // One that can't be read counts as 1.\n opacity: parent.opacity * (alpha(attributes.get(\"opacity\")) ?? 1),\n // These are inherited, so a shape's own replaces its group's, and one that can't be read leaves the group's.\n fillOpacity: alpha(attributes.get(\"fill-opacity\")) ?? parent.fillOpacity,\n strokeOpacity: alpha(attributes.get(\"stroke-opacity\")) ?? parent.strokeOpacity,\n transform: transform ? matrix.multiply(parent.transform, parseTransform(transform)) : parent.transform\n };\n}\n\nfunction toShape(tag: string, attributes: Map<string, string>, state: Inherited): IconShape | undefined {\n // A fill or stroke faded to 0 draws nothing, so it's dropped as \"none\" is.\n const fillOpacity = round(state.fillOpacity);\n const strokeOpacity = round(state.strokeOpacity);\n const fill = state.fill === \"none\" || !(fillOpacity > 0) ? undefined : state.fill;\n const stroke = state.stroke === \"none\" || !(state.width > 0) || !(strokeOpacity > 0) ? undefined : state.stroke;\n const opacity = round(state.opacity);\n if ((fill === undefined && stroke === undefined) || !(opacity > 0)) return undefined;\n const commands = shapeOutline(tag, (name) => attributes.get(name));\n if (!commands.some((command) => command.op !== \"M\")) return undefined;\n const m = state.transform;\n return {\n d: formatPath(transformPath(commands, m)),\n ...(fill !== undefined\n ? { fill, ...(state.fillRule === \"evenodd\" ? { fillRule: state.fillRule } : {}), ...(fillOpacity < 1 ? { fillOpacity } : {}) }\n : {}),\n ...(stroke !== undefined\n ? {\n stroke,\n // A stroke scales with the transform; for an uneven scale this is the average.\n width: round(state.width * Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2]))),\n ...(state.linecap ? { linecap: state.linecap } : {}),\n ...(state.linejoin ? { linejoin: state.linejoin } : {}),\n ...(strokeOpacity < 1 ? { strokeOpacity } : {})\n }\n : {}),\n ...(opacity < 1 ? { opacity } : {})\n };\n}\n\nfunction findLast(stack: readonly { readonly tag: string }[], tag: string): number {\n for (let i = stack.length - 1; i >= 0; i--) if (stack[i]!.tag === tag) return i;\n return -1;\n}\n\nconst round = (value: number): number => Math.round(value * 1000) / 1000;\n","// The neutral icons that ship with the core. They're drawn in theme colours, so they read in light\n// and dark themes and on any series colour. Domain icons live in optional packs (./sport).\n\nimport type { Icon } from \"../core\";\nimport { defineIcon } from \"./define\";\n\n/** A plain marker, outlined so it shows on any bar. */\nconst dot = /* @__PURE__ */ defineIcon({\n name: \"dot\",\n shapes: [{ d: \"M4,0A4,4 0 0 1 -4,0A4,4 0 0 1 4,0Z\", fill: \"surface\", stroke: \"text\", width: 1.5 }],\n box: { x: -5, y: -5, width: 10, height: 10 },\n anchor: { x: 0, y: 0 }\n});\n\n/** Points the way it travels, with a halo in the surface colour. */\nconst arrow = /* @__PURE__ */ defineIcon({\n name: \"arrow\",\n shapes: [{ d: \"M-7,-1.5L1,-1.5L1,-5L7,0L1,5L1,1.5L-7,1.5Z\", fill: \"text\", stroke: \"surface\", width: 1.5, linejoin: \"round\" }],\n box: { x: -8, y: -6, width: 16, height: 12 },\n anchor: { x: 0, y: 0 }\n});\n\n/** A light-weight pointer: a stroked \">\" over a wider halo. */\nconst chevron = /* @__PURE__ */ defineIcon({\n name: \"chevron\",\n shapes: [\n { d: \"M-2.5,-5L2.5,0L-2.5,5\", stroke: \"surface\", width: 4.5, linecap: \"round\", linejoin: \"round\" },\n { d: \"M-2.5,-5L2.5,0L-2.5,5\", stroke: \"text\", width: 2, linecap: \"round\", linejoin: \"round\" }\n ],\n box: { x: -5, y: -7.5, width: 10, height: 15 },\n anchor: { x: 0, y: 0 }\n});\n\n/** The built-in icons, registered by name in every chart: `travel(\"arrow\")` or `travel(icons.arrow)`. */\nexport const icons: { readonly dot: Icon; readonly arrow: Icon; readonly chevron: Icon } = /* @__PURE__ */ Object.freeze({ dot, arrow, chevron });\n","// The page-wide registries. The composition root (src/index.ts) hands them to every chart and\n// adapter, which resolve preset and icon names through them. The neutral core icons are registered\n// here; the sport pack is opt-in, with registerIcons(sport). The built-in presets are exactly flash,\n// wiggle and pulse: none combines effects, draws an icon or staggers.\n\nimport type { Icon, MarkEffect } from \"./core\";\nimport { createRegistry, type PresetFactory, type Registry } from \"./core/registry\";\nimport { flash, pulse, wiggle } from \"./effects\";\nimport { icons } from \"./icons\";\n\nexport const presetRegistry: Registry<PresetFactory> = /* @__PURE__ */ createRegistry<PresetFactory>({\n kind: \"preset\",\n entries: { flash: () => flash(), wiggle: () => wiggle(), pulse: () => pulse() },\n hint: \"Register custom presets with registerPreset(name, factory).\"\n});\n\nexport const iconRegistry: Registry<Icon> = /* @__PURE__ */ createRegistry<Icon>({\n kind: \"icon\",\n entries: icons,\n hint: \"Register icons with registerIcon(icon) or registerIcons(icons).\"\n});\n\n/** Makes `name` usable in any chart's `on` slots, e.g. `on: { hover: \"nudge\" }`. A later registration replaces an earlier one. */\nexport function registerPreset(name: string, factory: () => MarkEffect): void {\n if (typeof factory !== \"function\") throw new TypeError(`registerPreset(\"${name}\") needs a function that returns an effect.`);\n presetRegistry.register(name, factory);\n}\n\n/** Makes an icon usable by name, e.g. `travel(\"cleat\")`. A later icon with the same name replaces an earlier one. */\nexport function registerIcon(icon: Icon): void {\n if (typeof icon !== \"object\" || icon === null || typeof icon.name !== \"string\") {\n throw new TypeError(\"registerIcon needs an icon with a name.\");\n }\n iconRegistry.register(icon.name, icon);\n}\n\nexport function registerIcons(icons: readonly Icon[]): void {\n for (const icon of icons) registerIcon(icon);\n}\n","// Page-wide settings. For now they say how the stylesheet reaches the page. The stylesheet is one\n// <style> per document, injected by whatever is created first (a chart, an adapter, a control), so\n// these can't be chart options: a nonce passed to one chart would only count if that chart came\n// first, and one chart's injectStyles: false couldn't stop the next one injecting. A CSP nonce is per\n// page response anyway, so it's set once.\n\nimport { styleOptions, type StyleOptions } from \"./charts\";\n\n/**\n * Sets how charts, adapters and controls get their stylesheet, page-wide. Call it before creating\n * any: the stylesheet is injected once, by the first one. Options left out keep their current value.\n *\n * - `nonce`: set on the injected `<style>`, for a Content-Security-Policy with a `style-src` nonce.\n * - `injectStyles: false`: inject nothing; the page loads `expressive-charts/style.css` itself, which\n * has the same rules. For a CSP that allows no inline styles at all.\n */\nexport function configure(options: StyleOptions): void {\n if (typeof options !== \"object\" || options === null) throw new TypeError(\"configure needs an options object.\");\n if (\"nonce\" in options) {\n if (options.nonce !== undefined && (typeof options.nonce !== \"string\" || options.nonce === \"\")) {\n throw new TypeError(\"configure: nonce must be a non-empty string.\");\n }\n styleOptions.nonce = options.nonce;\n }\n if (\"injectStyles\" in options) {\n if (options.injectStyles !== undefined && typeof options.injectStyles !== \"boolean\") {\n throw new TypeError(\"configure: injectStyles must be true or false.\");\n }\n styleOptions.injectStyles = options.injectStyles;\n }\n}\n","// Public entry point and composition root: the only file that brings charts and effects together.\n// Exports are added here as each layer is built. See docs/architecture.md for the design.\n\nimport { motion as pageMotion, type Motion, type TransitionEffect } from \"./core\";\nimport {\n barChart as drawBarChart,\n chartSwitch as buildChartSwitch,\n donutChart as drawDonutChart,\n expressive as attach,\n fromVegaView as attachVega,\n lineChart as drawLineChart,\n type Attachment,\n type BarChart,\n type BarChartOptions,\n type ChartEnv,\n type ChartSwitch,\n type ChartSwitchOptions,\n type ChartSwitchViews,\n type DonutChart,\n type DonutChartOptions,\n type ExpressiveOptions,\n type LineChart,\n type LineChartOptions,\n type MarkSource,\n type VegaAttachment,\n type VegaOptions,\n type VegaViewLike\n} from \"./charts\";\nimport { motionSwitch as buildMotionSwitch, type MotionSwitch, type MotionSwitchOptions } from \"./charts/controls\";\nimport { morph } from \"./effects\";\nimport { iconRegistry, presetRegistry } from \"./registries\";\n\nexport const VERSION = \"0.4.0\";\n\nexport * from \"./core\";\nexport * from \"./effects\";\nexport * from \"./icons\";\nexport { registerIcon, registerIcons, registerPreset } from \"./registries\";\nexport { configure } from \"./settings\";\nexport { colorAssignment, link } from \"./charts\";\nexport type {\n Accessor,\n Attachment,\n BarChart,\n BarChartOptions,\n Chart,\n ChartChange,\n ChartLabel,\n ChartOptions,\n ChartSwitch,\n ChartSwitchOptions,\n ChartSwitchView,\n ChartSwitchViewFactory,\n ChartSwitchViewName,\n ChartSwitchViews,\n ColorAssignment,\n DonutChart,\n DonutChartOptions,\n ExpressiveOptions,\n HostMark,\n KeyOfType,\n LegendEntry,\n LegendOptions,\n LineChart,\n Link,\n LinkOptions,\n LinkSource,\n LineChartOptions,\n MarkEvent,\n MarkEvents,\n MarkSource,\n MarkSummary,\n NumericKey,\n SliceSummary,\n StyleOptions,\n TableColumn,\n TableOptions,\n VegaAttachment,\n VegaItem,\n VegaMark,\n VegaOptions,\n VegaSample,\n VegaViewLike\n} from \"./charts\";\nexport { playButton } from \"./charts/controls\";\nexport type { MotionSwitch, MotionSwitchOptions, PlayButton, PlayButtonOptions } from \"./charts/controls\";\n\n/** Charts resolve preset and icon names through the page-wide registries and follow the page-wide motion. */\nconst env: ChartEnv = { presets: presetRegistry, icons: iconRegistry, motion: pageMotion };\n\n/**\n * A bar chart in `target` (an element or a selector). The axis whose values aren't numbers is the\n * category; `stack` stacks numeric fields; `on` attaches effects by slot.\n */\nexport function barChart<D>(target: string | Element, options: BarChartOptions<D>): BarChart<D> {\n return drawBarChart(target, options, env);\n}\n\n/**\n * A donut chart in `target` (an element or a selector). `category` names each slice and `value` sizes\n * it; slices go clockwise from 12 o'clock, in data order or largest first with `sort: \"value\"`; `on`\n * attaches effects by slot.\n */\nexport function donutChart<D>(target: string | Element, options: DonutChartOptions<D>): DonutChart<D> {\n return drawDonutChart(target, options, env);\n}\n\n/**\n * A line chart in `target` (an element or a selector): one row per `x`, a number or a Date, a line\n * per field in `series`, with a point per row and series that shows where its x is hovered or\n * focused. `reveal(x)` shows the data up to x, as `playback()` drives it; `on` attaches effects by slot.\n */\nexport function lineChart<D>(target: string | Element, options: LineChartOptions<D>): LineChart<D> {\n return drawLineChart(target, options, env);\n}\n\n/**\n * Views of the same data in `target` (an element or a selector), one shown at a time: `show(view)`\n * turns each mark into the mark with its key in the other view with `transition`, morph() by default,\n * while the labels move and swap their text. Each view's function draws its chart in the container\n * it's given; pass it the `colors` it's given too, so a key keeps its colour from view to view.\n */\nexport function chartSwitch<T extends ChartSwitchViews>(target: string | Element, options: ChartSwitchOptions<T>): ChartSwitch<T> {\n // Charts never import effects: the default transition is filled in here.\n const filled = typeof options === \"object\" && options !== null && options.transition === undefined ? { ...options, transition: morph() } : options;\n return buildChartSwitch(target, filled as ChartSwitchOptions<T> & { readonly transition: TransitionEffect }, env);\n}\n\n/**\n * Adds effects to SVG marks drawn by other code: a selector, elements, or a D3 selection (whose data\n * types the callbacks). `key` is required; `on` attaches effects by slot, as on the charts. Call\n * `refresh()` after the host re-renders.\n */\nexport function expressive<D = unknown>(target: MarkSource<D>, options: ExpressiveOptions<D>): Attachment<D> {\n return attach(target, options, env);\n}\n\n/**\n * Adds effects to a Vega or Vega-Lite chart rendered as SVG (vega-embed's default): the View's mark\n * named `mark` (\"marks\", Vega-Lite's data mark, by default), read from its scenegraph. Rects are bars,\n * arcs slices, symbols points and lines lines; `sample` gives data effects their values. It follows\n * the View's own renders, so there's no refresh() to call. `key` is required, as for expressive().\n */\nexport function fromVegaView<D = Record<string, unknown>>(view: VegaViewLike, options: VegaOptions<D>): VegaAttachment<D> {\n return attachVega(view, options, env);\n}\n\n/**\n * The viewer's motion control in `target` (an element or a selector): Presentation, Analysis and Off\n * as buttons with `aria-pressed`, and a note on what the mode does. A click is the viewer's own\n * choice (`motion.chooseMode()`), so it overrides the device's reduced-motion setting. Default: the\n * page-wide `motion`. `persist: \"key\"` saves the choice in localStorage.\n */\nexport function motionSwitch(target: string | Element, motion: Motion = pageMotion, options?: MotionSwitchOptions): MotionSwitch {\n return buildMotionSwitch(target, motion, options);\n}\n"],"mappings":";;;;AASA,MAAa,qBAA2C,GAAG,OAAO,MAAM,KAAK,IAAI,KAAK,IAAI;AAE1F,MAAa,oBAAyC,GAAG,OAAO,OAAO;CACrE,GAAG,EAAE,KAAK,IAAI,KAAK,EAAE,IAAI;CACzB,GAAG,EAAE,KAAK,IAAI,KAAK,EAAE,IAAI;AAC3B;AAMA,SAAgB,kBACd,GACA,GACkC;CAClC,MAAM,OAAO,CAAC,mBAAG,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,GAAG,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;CAChE,QAAQ,MAAM;EACZ,IAAI,MAAM,GAAG,OAAO,EAAE,GAAG,EAAE;EAC3B,MAAM,MAAM,CAAC;EACb,KAAK,MAAM,OAAO,MAAM,IAAI,QAAQ,EAAE,QAAQ,MAAM,IAAI,MAAM,EAAE,QAAQ,KAAK;EAC7E,OAAO;CACT;AACF;AAiCA,SAAgB,SAAY,SAAY,aAA8B,UAA8B,CAAC,GAAgB;CACnH,MAAM,EAAE,UAAU,GAAG,QAAQ;CAC7B,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI;CAEJ,IAAI,SAAS;CAEb,MAAM,UAAU,SAAkB;EAChC,QAAQ;EACR,WAAW,IAAI;CACjB;CAEA,MAAM,aAAmB;EACvB,MAAM,UAAU;EAChB,UAAU,KAAA;EACV,SAAS;EACT,SAAS,OAAO;CAClB;CAEA,OAAO;EACL,IAAI,QAAQ;GACV,OAAO;EACT;EACA,IAAI,SAAS;GAEX,OAAO,SAAS,UAAU,cAAc,QAAQ;EAClD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