@ex-grid/chart 0.0.0-stage → 0.2.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +39 -2
- package/dist/index.d.ts +2358 -0
- package/dist/index.js +10048 -0
- package/dist/index.js.map +7 -0
- package/ex-chart.min.css +4 -0
- package/ex-chart.min.css.map +1 -0
- package/package.json +32 -4
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/values.ts", "../src/invariant-text.ts", "../src/must.ts", "../src/day-numbers.ts", "../src/edges.ts", "../src/numbers.ts", "../src/ticks.ts", "../src/point-scales.ts", "../src/price-ranges.ts", "../src/definition.ts", "../src/appearance.ts", "../src/metrics.ts", "../src/series-drawing.ts", "../src/thinning.ts", "../src/scene.ts", "../src/reading.ts", "../src/csv.ts", "../src/summary.ts", "../src/surface.ts", "../src/surface-mesh.ts", "../src/chart-data.ts", "../src/spec.ts", "../src/chart-source.ts", "../src/spec-answer.ts", "../src/fitting.ts", "../src/interpolation.ts", "../src/dom/chart-element.ts", "../src/dom/chart-chrome.ts", "../src/dom/svg-markup.ts", "../src/dom/chart-drawing.ts", "../src/dom/shipped-stylesheet.ts", "../src/dom/chart-files.ts", "../src/dom/chart-words.ts", "../src/dom/range-text.ts", "../src/dom/create-chart.ts", "../src/dom/surface-element.ts", "../src/dom/surface-drawing.ts", "../src/dom/create-surface.ts", "../src/bridge/selection-reader.ts", "../src/bridge/grid-chart-bridge.ts", "../src/bridge/grid-chart.ts"],
|
|
4
|
+
"sourcesContent": ["import { FormatCode } from '@ex-grid/core';\nimport { roundTrip } from './invariant-text';\nimport type { AxisValues, ChartAxis, ChartSeries, ChartValue, SeriesKind } from './model';\nimport { dateOf, isoDate, wholeDay } from './day-numbers';\nimport { elementAt, unreachable } from './must';\n\n/** A chart that cannot be drawn as it was asked for, said by name (spine rule 1). */\nexport class ChartRefusedError extends Error {\n /** A refusal saying why. */\n constructor(message: string) {\n super(message);\n this.name = 'ChartRefusedError';\n }\n}\n\n/** A value as a number, for geometry only (ADR-0251). */\nexport function toNumber(value: ChartValue): number {\n return typeof value === 'bigint' ? Number(value) : value;\n}\n\n/** A value written invariantly, with every digit it was handed in with. */\nexport function invariantText(value: ChartValue): string {\n return typeof value === 'bigint' ? value.toString() : roundTrip(value);\n}\n\n/** A series' value written through its format or its format code (ADR-0420), or invariantly. */\nexport function writeValue(series: ChartSeries, value: ChartValue): string {\n if (series.format !== undefined) {\n return series.format(value);\n }\n return series.formatCode === undefined ? invariantText(value) : codeOf(series.formatCode).format(value, 'invariant');\n}\n\n/**\n * An axis' or a series' Excel format code, read by the family's reader both cores write a code with (ADR-0420,\n * ADR-0342): the reader, or why it cannot be read, a phrase completing \"the format code \u2026\".\n */\nexport function readCode(code: string): FormatCode | string {\n const reading = FormatCode.tryParse(code);\n return 'format' in reading ? reading.format : reading.reason;\n}\n\n// Each code read once, as C# reads it once as the definition is made: a writer is asked at every tick and pointer move.\nconst readings = new Map<string, FormatCode | string>();\n\n// A code the definition checked: one it could not read never reaches a writer.\nfunction codeOf(code: string): FormatCode {\n let reading = readings.get(code);\n if (reading === undefined) {\n reading = readCode(code);\n readings.set(code, reading);\n }\n if (typeof reading === 'string') {\n throw new Error(`Internal: the format code \"${code}\" was written with, which the definition refuses: it ${reading}.`);\n }\n return reading;\n}\n\n/** Whether the axis' format or format code writes its positions, in place of its own writing. */\nexport function axisWrites(axis: ChartAxis): boolean {\n return axis.format !== undefined || axis.formatCode !== undefined;\n}\n\nconst ticksPerDay = 864_000_000_000;\n\n// A position through a code: a Dates axis' day number as the date and time it is, as .NET ticks; a Numbers axis'\n// as the number. A fraction of a day's ticks is rounded half away from zero, as C# rounds them.\nfunction writeCodePosition(code: FormatCode, values: AxisValues, position: number): string {\n if (values !== 'dates') {\n return code.format(position, 'invariant');\n }\n const day = Math.floor(position);\n const ticks = BigInt(day) * BigInt(ticksPerDay) + BigInt(Math.round((position - day) * ticksPerDay));\n return code.format(ticks, 'invariant');\n}\n\n/** A Row Key, a node's name or a surface's value written as C# writes an object into a sentence. */\nexport function writeObject(value: unknown): string {\n if (typeof value === 'number') {\n return roundTrip(value);\n }\n if (typeof value === 'string') {\n return value;\n }\n // C# writes a bool as `True` or `False`.\n if (typeof value === 'boolean') {\n return value ? 'True' : 'False';\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n // C# interpolates a null as nothing.\n if (value === null || value === undefined) {\n return '';\n }\n // Any other key is written as data, which names it where C#'s `ToString()` of an object would name only its type.\n return JSON.stringify(value);\n}\n\n/** A position written as the axis writes it (ADR-0250). */\nexport function writePosition(axis: ChartAxis, position: number): string {\n if (axis.format !== undefined) {\n return axis.format(position);\n }\n if (axis.formatCode !== undefined) {\n return writeCodePosition(codeOf(axis.formatCode), axis.values, position);\n }\n switch (axis.values) {\n case 'dates':\n return isoDate(dateOf(wholeDay(position)));\n case 'labels':\n return position >= 0 && position < axis.labels.length && position === Math.floor(position)\n ? elementAt(axis.labels, position)\n : roundTrip(position);\n case 'numbers': {\n const named = axis.named.find(n => n[0] === position);\n return named === undefined ? roundTrip(position) : named[1];\n }\n default:\n return unreachable(axis.values);\n }\n}\n\n/** The length in years of the interval between two positions, which an Amount per period is divided by. */\nexport function yearsBetween(axis: ChartAxis, from: number, to: number): number {\n switch (axis.values) {\n case 'dates':\n return (to - from) / axis.daysPerYear;\n case 'numbers':\n return to - from;\n case 'labels':\n throw new Error('A category axis has no length.');\n default:\n return unreachable(axis.values);\n }\n}\n\n/** A Series Kind as the C# engine names it in a sentence. */\nexport function kindName(kind: SeriesKind): string {\n switch (kind) {\n case 'level':\n return 'Level';\n case 'rateOverInterval':\n return 'RateOverInterval';\n case 'amountPerPeriod':\n return 'AmountPerPeriod';\n case 'observation':\n return 'Observation';\n case 'priceRange':\n return 'PriceRange';\n default:\n return unreachable(kind);\n }\n}\n", "// Numbers written as the C# engine writes them with the invariant culture, so a label, a Note or a\n// refusal reads alike in both cores (ADR-0370, section 2). Each function names the .NET format it stands\n// for; JavaScript's own `String(n)` and `toFixed` round and switch to exponents elsewhere.\n\n/** A decimal digit string and the place of its point: `digits` \u00D7 10^(`point` \u2212 digits.length). */\ninterface Digits {\n readonly negative: boolean;\n readonly digits: string;\n readonly point: number;\n}\n\n// The digits of a finite number as `toExponential` or `toPrecision` writes them in exponent form.\nfunction digitsOf(value: number, written: string): Digits {\n const match = /^-?(\\d)(?:\\.(\\d+))?e([+-]\\d+)$/.exec(written);\n if (match === null) {\n throw new Error(`Internal: ${written} is not a number in exponent form.`);\n }\n const [, first, rest, exponent] = match;\n if (first === undefined || exponent === undefined) {\n throw new Error(`Internal: ${written} has no leading digit or no exponent.`);\n }\n return {\n negative: value < 0 || Object.is(value, -0),\n // A number of one significant digit has no fraction digits.\n digits: rest === undefined ? first : first + rest,\n point: Number(exponent) + 1,\n };\n}\n\nfunction finite(value: number, format: string): void {\n if (!Number.isFinite(value)) {\n throw new RangeError(`${String(value)} is not a finite number, which the format ${format} writes.`);\n }\n}\n\n/**\n * C#'s `ToString(\"R\")`, and a double written into a string as C# writes it: the shortest digits that\n * read back as the same number, in exponent form (`1E-05`, `1.2345678901234568E+17`) where the point\n * stands more than seventeen places left or three places right of the digits. A number that is no\n * number is written by the invariant culture's names, `NaN`, `Infinity` and `-Infinity`, as a position\n * the definition refuses is named in its sentence.\n */\nexport function roundTrip(value: number): string {\n if (Number.isNaN(value)) {\n return 'NaN';\n }\n if (!Number.isFinite(value)) {\n return value > 0 ? 'Infinity' : '-Infinity';\n }\n if (value === 0) {\n return Object.is(value, -0) ? '-0' : '0';\n }\n const d = digitsOf(value, Math.abs(value).toExponential());\n const sign = d.negative ? '-' : '';\n if (d.point > 17 || d.point < -3) {\n const exponent = d.point - 1;\n const mantissa = d.digits.length > 1 ? `${d.digits.slice(0, 1)}.${d.digits.slice(1)}` : d.digits;\n return `${sign}${mantissa}E${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`;\n }\n return sign + placed(d.digits, d.point);\n}\n\n// Digits written with their point, zeros added on either side as the point needs.\nfunction placed(digits: string, point: number): string {\n if (point <= 0) {\n return `0.${'0'.repeat(-point)}${digits}`;\n }\n if (point >= digits.length) {\n return digits + '0'.repeat(point - digits.length);\n }\n return `${digits.slice(0, point)}.${digits.slice(point)}`;\n}\n\n/**\n * C#'s custom format `0.###\u2026` with `places` hashes (`0.####`, `0.##`): the number taken to fifteen\n * significant digits, as .NET takes a double for a custom format, then rounded to `places` decimals with\n * a half going away from zero, its trailing zeros dropped. A negative number that rounds to nothing is\n * written `-0`, as .NET writes it.\n */\nexport function upToPlaces(value: number, places: number): string {\n finite(value, `0.${'#'.repeat(places)}`);\n const negative = value < 0 || Object.is(value, -0);\n if (value === 0) {\n return negative ? '-0' : '0';\n }\n const r = rounded(fifteenDigits(value), places);\n const digits = r.digits.replace(/0+$/, '');\n const text = digits === '' ? '0' : placed(digits, r.point);\n return (negative ? '-' : '') + text;\n}\n\n/**\n * C#'s custom format `0.00`: the number taken to fifteen significant digits, rounded to two decimals with\n * a half going away from zero, both decimals kept. A negative number that rounds to nothing is written\n * `-0.00`, as .NET writes it.\n */\nexport function twoPlaces(value: number): string {\n finite(value, '0.00');\n return twoPlacesMoved(value, 0);\n}\n\n/**\n * C#'s custom format `0.00%`: the number as a percentage \u2014 its point moved two places, as .NET moves it,\n * never multiplied \u2014 taken to fifteen significant digits, rounded to two decimals with a half going away\n * from zero, both decimals kept. A negative number that rounds to nothing is written `-0.00%`, as .NET\n * writes it.\n */\nexport function percentTwoPlaces(value: number): string {\n finite(value, '0.00%');\n return `${twoPlacesMoved(value, 2)}%`;\n}\n\n// The number to fifteen digits, its point moved `shift` places right, written with two decimals.\nfunction twoPlacesMoved(value: number, shift: number): string {\n const negative = value < 0 || Object.is(value, -0);\n let text = '0.00';\n if (value !== 0) {\n const d = fifteenDigits(value);\n const r = rounded({ ...d, point: d.point + shift }, 2);\n if (r.digits !== '') {\n const whole = r.point <= 0 ? '0' : r.digits.slice(0, r.point).padEnd(r.point, '0');\n const fraction = r.point <= 0 ? '0'.repeat(-r.point) + r.digits : r.digits.slice(r.point);\n text = `${whole}.${fraction.padEnd(2, '0')}`;\n }\n }\n return `${negative ? '-' : ''}${text}`;\n}\n\n// The digits kept up to `places` decimals; the next one rounds the kept ones half away from zero.\nfunction rounded(d: Digits, places: number): { readonly digits: string; readonly point: number } {\n const keep = d.point + places;\n let digits = d.digits;\n let point = d.point;\n if (keep < digits.length) {\n const up = keep >= 0 && Number(digits.charAt(keep)) >= 5;\n digits = keep > 0 ? digits.slice(0, keep) : '';\n if (up) {\n const carried = carry(digits);\n if (carried.length > digits.length) {\n point += 1;\n }\n digits = carried;\n }\n }\n return { digits, point };\n}\n\n// The number to fifteen significant digits as .NET takes it for a custom format: a tie goes to the even\n// digit, where `toExponential(14)` would send it up. A hundred digits hold the expansion as far as a tie\n// can be told.\nfunction fifteenDigits(value: number): Digits {\n // oxlint-disable-next-line oxc/number-arg-out-of-range -- ES2018 raised the limit to 100 digits, which an exact tie needs\n const exact = digitsOf(value, Math.abs(value).toExponential(99));\n const kept = exact.digits.slice(0, 15);\n const next = Number(exact.digits.charAt(15));\n const tie = next === 5 && /^0*$/.test(exact.digits.slice(16));\n const up = next > 5 || (next === 5 && !tie) || (tie && Number(kept.charAt(14)) % 2 === 1);\n if (!up) {\n return { ...exact, digits: kept };\n }\n const carried = carry(kept);\n return carried.length > kept.length\n ? { ...exact, digits: carried.slice(0, 15), point: exact.point + 1 }\n : { ...exact, digits: carried };\n}\n\n// One added to the last digit, carried left.\nfunction carry(digits: string): string {\n const out = digits.split('');\n for (let i = out.length - 1; i >= 0; i--) {\n if (out[i] === '9') {\n out[i] = '0';\n continue;\n }\n out[i] = String(Number(out[i]) + 1);\n return out.join('');\n }\n return `1${out.join('')}`;\n}\n\n/**\n * C#'s `ToString(\"G3\")`: three significant digits, trailing zeros dropped, in exponent form (`1.23E-05`)\n * where the point stands more than three places right or left of the first digit.\n */\nexport function threeSignificant(value: number): string {\n finite(value, 'G3');\n if (value === 0) {\n return Object.is(value, -0) ? '-0' : '0';\n }\n const d = digitsOf(value, Math.abs(value).toExponential(2));\n const sign = d.negative ? '-' : '';\n const digits = d.digits.replace(/0+$/, '');\n if (d.point > 3 || d.point < -3) {\n const exponent = d.point - 1;\n const mantissa = digits.length > 1 ? `${digits.slice(0, 1)}.${digits.slice(1)}` : digits;\n return `${sign}${mantissa}E${exponent < 0 ? '-' : '+'}${String(Math.abs(exponent)).padStart(2, '0')}`;\n }\n return sign + placed(digits, d.point);\n}\n\n/** C#'s `ToString(\"N0\")` of a whole number: its digits in groups of three, split by commas. */\nexport function grouped(count: number): string {\n if (!Number.isSafeInteger(count)) {\n throw new RangeError(`${String(count)} is not a whole number, which N0 is written for here.`);\n }\n const digits = String(Math.abs(count));\n const groups: string[] = [];\n for (let end = digits.length; end > 0; end -= 3) {\n groups.unshift(digits.slice(Math.max(0, end - 3), end));\n }\n return (count < 0 ? '-' : '') + groups.join(',');\n}\n\n/** A number written as a surface writes a tick it has no format for (C#'s `SurfaceMesh.Plain`): `G3` near zero, `0.####` elsewhere. */\nexport function tickText(value: number): string {\n return value !== 0 && Math.abs(value) < 1e-4 ? threeSignificant(value) : upToPlaces(value, 4);\n}\n", "// What the core knows is there. `noUncheckedIndexedAccess` makes every read of a list or a map say what\n// happens on a miss; where the answer is \"a miss is a defect in the core\", these helpers say it by\n// throwing, where a `!` would read on with `undefined` (CONVENTIONS.md, \"No quiet fallback\").\n\n/** The element at `index`, which the caller knows is there. A miss throws: it is a defect, never an answer. */\nexport function elementAt<T extends object | string | number | boolean | bigint | symbol | null>(list: readonly T[], index: number): T {\n const value = list[index];\n if (value === undefined) {\n throw new Error(`Internal: index ${index} is outside a list of ${list.length}.`);\n }\n return value;\n}\n\n/** The item at `index` of a list whose items may be any type, a Consumer's rows among them, where\n * `undefined` could be an item: the index, not the value, is checked. A miss throws, as `elementAt`'s does. */\nexport function itemAt<T>(list: readonly T[], index: number): T {\n if (!Number.isInteger(index) || index < 0 || index >= list.length) {\n throw new Error(`Internal: index ${index} is outside a list of ${list.length}.`);\n }\n return list[index] as T; // oxlint-disable-line typescript/no-unsafe-type-assertion -- the index was checked against the length above\n}\n\n/** The value, which the caller knows is there. `undefined` throws, naming what was missing. */\nexport function defined<T>(value: T | undefined, what: string): T {\n if (value === undefined) {\n throw new Error(`Internal: ${what} is missing.`);\n }\n return value;\n}\n\n/**\n * The end of a switch that has taken every member of a union. The type checker proves nothing reaches it;\n * a value from outside the union, which only an untyped caller can pass, throws here rather than falling\n * out of the switch as `undefined`.\n */\nexport function unreachable(value: never): never {\n throw new Error(`Internal: ${String(value)} is not a value this switch takes.`);\n}\n", "// A date on a Dates axis is its day number, as C#'s `DateOnly.DayNumber` counts it: days since\n// 0001-01-01 in the proleptic Gregorian calendar (ADR-0251). The arithmetic here is the calendar's own,\n// so the two cores put a month's first day on the same position.\nimport { elementAt } from './must';\n\n/** A calendar date: its year, its month from 1 and its day from 1. */\nexport interface CivilDate {\n readonly year: number;\n readonly month: number;\n readonly day: number;\n}\n\n// Day 0 of the count is 1970-01-01's distance from 0001-01-01.\nconst epoch = 719_162;\n\n/** The day number of a date. */\nexport function dayNumber(year: number, month: number, day: number): number {\n // Howard Hinnant's days_from_civil, counted from 1970-01-01.\n const y = month <= 2 ? year - 1 : year;\n const era = Math.floor(y / 400);\n const yoe = y - era * 400;\n const mp = (month + 9) % 12;\n const doy = Math.floor((153 * mp + 2) / 5) + day - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n return era * 146_097 + doe - 719_468 + epoch;\n}\n\n/** The date of a whole day number. */\nexport function dateOf(dayNumberValue: number): CivilDate {\n if (!Number.isSafeInteger(dayNumberValue) || dayNumberValue < 0 || dayNumberValue > 3_652_058) {\n throw new RangeError(`${String(dayNumberValue)} is not a day number between 0001-01-01 and 9999-12-31.`);\n }\n // Howard Hinnant's civil_from_days.\n const z = dayNumberValue - epoch + 719_468;\n const era = Math.floor(z / 146_097);\n const doe = z - era * 146_097;\n const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36_524) - Math.floor(doe / 146_096)) / 365);\n const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));\n const mp = Math.floor((5 * doy + 2) / 153);\n const day = doy - Math.floor((153 * mp + 2) / 5) + 1;\n const month = mp < 10 ? mp + 3 : mp - 9;\n return { year: yoe + era * 400 + (month <= 2 ? 1 : 0), month, day };\n}\n\n/** A position as C#'s `(int)` cast takes it to a day: its whole part, towards zero. */\nexport function wholeDay(position: number): number {\n return Math.trunc(position);\n}\n\nfunction daysInMonth(year: number, month: number): number {\n return dayNumber(month === 12 ? year + 1 : year, month === 12 ? 1 : month + 1, 1) - dayNumber(year, month, 1);\n}\n\n/** C#'s `DateOnly.AddMonths`: the same day `months` later, or the month's last where it has fewer days. */\nexport function addMonths(date: CivilDate, months: number): CivilDate {\n const index = date.year * 12 + (date.month - 1) + months;\n const year = Math.floor(index / 12);\n const month = index - year * 12 + 1;\n return { year, month, day: Math.min(date.day, daysInMonth(year, month)) };\n}\n\n/** The day of the week as C#'s `DayOfWeek` numbers it: Sunday 0 to Saturday 6. 0001-01-01 was a Monday. */\nexport function dayOfWeek(dayNumberValue: number): number {\n return (dayNumberValue + 1) % 7;\n}\n\nconst monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] as const;\n\nconst two = (n: number): string => String(n).padStart(2, '0');\nconst four = (n: number): string => String(n).padStart(4, '0');\n\n/** `yyyy-MM-dd`. */\nexport function isoDate(date: CivilDate): string {\n return `${four(date.year)}-${two(date.month)}-${two(date.day)}`;\n}\n\n/** `yyyy-MM`. */\nexport function yearMonth(date: CivilDate): string {\n return `${four(date.year)}-${two(date.month)}`;\n}\n\n/** `yyyy`. */\nexport function yearOnly(date: CivilDate): string {\n return four(date.year);\n}\n\n/** `MMM yyyy`, the month abbreviated as the invariant culture abbreviates it. */\nexport function monthYear(date: CivilDate): string {\n return `${elementAt(monthNames, date.month - 1)} ${four(date.year)}`;\n}\n", "// An Observation's edges between its nodes (ADR-0321): drawn as lines between their positions, cut at\n// the plot's edges.\nimport type { Box } from './metrics';\nimport type { ChartSeries } from './model';\nimport { kindName, toNumber, writeObject } from './values';\n\n/** An edge in CSS pixels, cut at the plot's edges. */\nexport interface DrawnEdge {\n /** Where it starts across. */\n readonly x1: number;\n /** Where it starts down. */\n readonly y1: number;\n /** Where it ends across. */\n readonly x2: number;\n /** Where it ends down. */\n readonly y2: number;\n /** Which of its series' edges it is. */\n readonly index: number;\n}\n\n/** What the definition refuses of a series' edges, or `undefined`. */\nexport function edgeRefusal(s: ChartSeries): string | undefined {\n if (s.edges.length === 0) {\n return undefined;\n }\n if (s.kind !== 'observation') {\n return `'${s.name}' has edges, which join an observation's nodes; a ${kindName(s.kind)} joins its points itself.`;\n }\n const keys = new Set<unknown>();\n for (let i = 0; i < s.points.length; i++) {\n const p = s.points[i];\n if (p === undefined) {\n break;\n }\n if (p.row === undefined || p.row === null) {\n return `'${s.name}' has edges, but its point at row ${String(i + 1)} has no key for an edge to name.`;\n }\n if (keys.has(p.row)) {\n return `'${s.name}' has two nodes keyed ${writeObject(p.row)}; an edge could not say which it joins.`;\n }\n keys.add(p.row);\n if (p.y === null || !Number.isFinite(p.x)) {\n return `'${s.name}': node ${writeObject(p.row)} has no position, so no edge can reach it.`;\n }\n }\n for (const e of s.edges) {\n for (const end of [e.from, e.to]) {\n if (!keys.has(end)) {\n return `'${s.name}' has an edge from ${writeObject(e.from)} to ${writeObject(e.to)}, but no node is keyed ${writeObject(end)}.`;\n }\n }\n }\n return undefined;\n}\n\n/** The series' edges in pixels, each cut to the plot; an edge wholly outside it is left out. */\nexport function edgePixels(s: ChartSeries, mapX: (x: number) => number, mapY: (y: number) => number, plot: Box): DrawnEdge[] {\n if (s.edges.length === 0) {\n return [];\n }\n const at = new Map<unknown, readonly [number, number]>();\n for (const p of s.points) {\n if (p.y !== null) {\n at.set(p.row, [mapX(p.x), mapY(toNumber(p.y))]);\n }\n }\n const drawn: DrawnEdge[] = [];\n s.edges.forEach((edge, index) => {\n const a = at.get(edge.from);\n const b = at.get(edge.to);\n if (a === undefined || b === undefined) {\n throw new Error('Internal: an edge names a node the definition did not hold.');\n }\n const cut = clip(a[0], a[1], b[0], b[1], plot, index);\n if (cut !== undefined) {\n drawn.push(cut);\n }\n });\n return drawn;\n}\n\n// Liang\u2013Barsky: the part of the segment inside the box, or undefined.\nfunction clip(x1: number, y1: number, x2: number, y2: number, box: Box, index: number): DrawnEdge | undefined {\n let t0 = 0;\n let t1 = 1;\n const dx = x2 - x1;\n const dy = y2 - y1;\n for (const [p, q] of [[-dx, x1 - box.x], [dx, box.x + box.width - x1], [-dy, y1 - box.y], [dy, box.y + box.height - y1]] as const) {\n if (p === 0) {\n if (q < 0) {\n return undefined;\n }\n continue;\n }\n const r = q / p;\n if (p < 0) {\n t0 = Math.max(t0, r);\n } else {\n t1 = Math.min(t1, r);\n }\n if (t0 > t1) {\n return undefined;\n }\n }\n return Object.freeze({ x1: x1 + t0 * dx, y1: y1 + t0 * dy, x2: x1 + t1 * dx, y2: y1 + t1 * dy, index });\n}\n", "// The arithmetic the C# engine does in .NET's way, where JavaScript's would land elsewhere.\n\n/** The nearest whole number, a tie going to the even one: C#'s `Math.Round`. */\nexport function roundHalfToEven(value: number): number {\n const floor = Math.floor(value);\n if (value - floor !== 0.5) {\n return Math.round(value);\n }\n return floor % 2 === 0 ? floor : floor + 1;\n}\n\n/**\n * C#'s `Math.Round(value, digits)`: scaled by a power of ten, rounded to even, scaled back; a number of\n * sixteen digits or more is returned as it is, as .NET returns it.\n */\nexport function roundToDigits(value: number, digits: number): number {\n if (!Number.isInteger(digits) || digits < 0 || digits > 15) {\n throw new RangeError(`${String(digits)} digits is not between 0 and 15.`);\n }\n if (!(Math.abs(value) < 1e16)) {\n return value;\n }\n const power = 10 ** digits;\n return roundHalfToEven(value * power) / power;\n}\n\nconst scratch = new DataView(new ArrayBuffer(8));\n\n/** C#'s `Math.BitDecrement`: the largest number below `value`. */\nexport function bitDecrement(value: number): number {\n if (Number.isNaN(value) || value === -Infinity) {\n return value;\n }\n if (value === 0) {\n return -Number.MIN_VALUE;\n }\n scratch.setFloat64(0, value);\n const bits = scratch.getBigInt64(0);\n scratch.setBigInt64(0, value > 0 ? bits - 1n : bits + 1n);\n return scratch.getFloat64(0);\n}\n\n/** The least of `values`, read in one pass so a long series never meets the argument limit of `Math.min`; refused when there are none. */\nexport function least(values: Iterable<number>): number {\n let result = Infinity;\n let any = false;\n for (const v of values) {\n result = Math.min(result, v);\n any = true;\n }\n if (!any) {\n throw new RangeError('There is no least of no values.');\n }\n return result;\n}\n\n/**\n * The first of `items` whose value `before` puts ahead of every other's, as C#'s MinBy and MaxBy take it, so\n * a tie keeps the earlier item; refused when there are none.\n */\nexport function firstBy<T extends object | number | bigint>(items: readonly T[], value: (item: T) => number, before: (a: number, b: number) => boolean): T {\n const [head, ...rest] = items;\n if (head === undefined) {\n throw new RangeError('There is no first of no items.');\n }\n let best = head;\n for (const item of rest) {\n if (before(value(item), value(best))) {\n best = item;\n }\n }\n return best;\n}\n\n/** The greatest of `values`, as `least` reads them; refused when there are none. */\nexport function greatest(values: Iterable<number>): number {\n let result = -Infinity;\n let any = false;\n for (const v of values) {\n result = Math.max(result, v);\n any = true;\n }\n if (!any) {\n throw new RangeError('There is no greatest of no values.');\n }\n return result;\n}\n", "// Ticks and labels for both axes (ticket 04). Text is never measured: widths come from the estimate the\n// caller hands in (ADR-0021).\nimport { addMonths, dateOf, dayNumber, isoDate, monthYear, wholeDay, yearMonth, yearOnly, type CivilDate } from './day-numbers';\nimport { upToPlaces } from './invariant-text';\nimport type { ChartAxis } from './model';\nimport { elementAt, unreachable } from './must';\nimport { roundHalfToEven, roundToDigits } from './numbers';\nimport { axisWrites, writePosition } from './values';\n\n/** Where a horizontal axis puts its ticks. */\nexport type TickPlacement =\n /** The default for the axis: calendar boundaries for dates, round numbers for numbers, every category. */\n | 'auto'\n /** At calendar boundaries \u2014 years, quarters, months or days, the finest that fits. */\n | 'calendar'\n /** At every position some series has a point at. */\n | 'everyPoint'\n /** At the market's tenors counted from the first date: 1M, 3M, 6M, 1Y, 2Y, 3Y, 5Y, 7Y, 10Y \u2026 */\n | 'tenors'\n /** At the positions the axis names. */\n | 'named';\n\n/** How a date tick is labelled: the finest format the ticks need, 2026, 2026-10, 2026-10-19, Oct 2026, or a tenor. */\nexport type DateLabel = 'auto' | 'year' | 'yearMonth' | 'date' | 'monthYear' | 'tenor';\n\n/** How the horizontal axis is ticked and labelled: three independent choices. */\nexport interface AxisStyle {\n /** Where the ticks go; `auto` by default. */\n readonly placement?: TickPlacement;\n /** How a date tick is labelled; `auto` by default. */\n readonly label?: DateLabel;\n /** The labels' angle: 0 (the default), 45 or 90 degrees, read upwards. */\n readonly angle?: number;\n}\n\n/** A tick: where it stands on the axis, and its label, or `null` where it was left out so as not to touch its neighbour. */\nexport interface AxisTick {\n /** The position, in the axis' units. */\n readonly position: number;\n /** The label, or `null`. */\n readonly label: string | null;\n}\n\n/** The ticks of an axis, laid out: every tick is drawn; a label that would touch its neighbour is left out. */\nexport interface AxisTicks {\n /** The ticks, in order. */\n readonly ticks: readonly AxisTick[];\n /** How far the labels reach from the axis, in pixels. */\n readonly depth: number;\n /** How many ticks kept their label. */\n readonly labelled: number;\n}\n\n/** Round-number ticks: the range they cover and their step. */\nexport interface NiceTicks {\n /** The first tick. */\n readonly min: number;\n /** The last. */\n readonly max: number;\n /** The step between them. */\n readonly step: number;\n}\n\nconst tenorMonths = [1, 3, 6, 12, 24, 36, 60, 84, 120, 180, 240, 300, 360, 480, 600] as const;\n\n/** A tenor in years written as the market writes it: 6M, 18M, 1Y, 2.5Y. */\nexport function tenor(years: number): string {\n const months = years * 12;\n if (Math.abs(months - roundHalfToEven(months)) < 1e-6) {\n const m = roundHalfToEven(months);\n return m % 12 === 0 ? `${String(Math.trunc(m / 12))}Y` : `${String(m)}M`;\n }\n const weeks = years * 52;\n if (years < 1 / 12 && Math.abs(weeks - roundHalfToEven(weeks)) < 1e-6) {\n return `${String(roundHalfToEven(weeks))}W`;\n }\n return `${upToPlaces(years, 2)}Y`;\n}\n\n/** The whole decades that hold `min` to `max`, both above zero: the bounds of a logarithmic axis (ADR-0290). */\nexport function decades(min: number, max: number): readonly [min: number, max: number] {\n if (!(min > 0) || !(max > 0)) {\n return [1, 10];\n }\n const lo = 10 ** Math.floor(Math.log10(min) + 1e-9);\n const hi = 10 ** Math.ceil(Math.log10(max) - 1e-9);\n return hi > lo ? [lo, hi] : [lo, lo * 10];\n}\n\n/**\n * A logarithmic axis' ticks between `min` and `max`, both above zero (ADR-0290): every 1, 2 and 5 times a\n * power of ten across up to three decades, every power of ten across more, every whole multiple within one.\n */\nexport function logSteps(min: number, max: number): readonly number[] {\n if (!(min > 0) || !(max > min)) {\n return min > 0 ? [min] : [];\n }\n const span = Math.log10(max / min);\n const multiples = span < 1 ? [1, 2, 3, 4, 5, 6, 7, 8, 9] : span <= 3 ? [1, 2, 5] : [1];\n const ticks: number[] = [];\n for (let e = Math.floor(Math.log10(min)) - 1; e <= Math.ceil(Math.log10(max)); e++) {\n for (const m of multiples) {\n const t = roundToDigits(m * 10 ** e, 12 - Math.min(12, Math.max(0, e)));\n if (t >= min * (1 - 1e-9) && t <= max * (1 + 1e-9)) {\n ticks.push(t);\n }\n }\n }\n return ticks;\n}\n\n/** Round-number ticks covering `min` to `max`, about `target` of them, at a step of 1, 2, 2.5 or 5 times a power of ten. */\nexport function nice(min: number, max: number, target = 5): NiceTicks {\n let lo = min;\n let hi = max;\n if (lo === hi) {\n const pad = lo === 0 ? 1 : Math.abs(lo) / 10;\n lo -= pad;\n hi += pad;\n }\n const raw = (hi - lo) / Math.max(target, 1);\n const mag = 10 ** Math.floor(Math.log10(raw));\n const step = [1, 2, 2.5, 5, 10].map(f => f * mag).find(s => s >= raw * (1 - 1e-9));\n if (step === undefined) {\n throw new Error(`Internal: no round step covers ${String(raw)}.`);\n }\n return { min: Math.floor(lo / step + 1e-9) * step, max: Math.ceil(hi / step - 1e-9) * step, step };\n}\n\n/** The positions of round-number ticks from `min` to `max` at `step`. */\nexport function steps(min: number, max: number, step: number): readonly number[] {\n const n = Math.trunc(roundHalfToEven((max - min) / step));\n if (n + 1 < 0) {\n throw new RangeError(`${String(n + 1)} ticks is not a count.`);\n }\n return Array.from({ length: n + 1 }, (_, i) => roundToDigits(min + i * step, 12));\n}\n\n/**\n * The horizontal axis' ticks over `from` to `to`, placed on the plot by `map`, in pixels, with labels left\n * out where they would touch. `points` are the positions series have points at; `textWidth` estimates a\n * label's width and `lineHeight` is a label's height, in pixels.\n */\nexport function horizontalTicks(axis: ChartAxis, style: AxisStyle, from: number, to: number, points: Iterable<number>,\n map: (position: number) => number, textWidth: (text: string) => number, lineHeight: number, gap = 4): AxisTicks {\n const { placement: declared = 'auto', angle = 0 } = style;\n const placement: TickPlacement = declared === 'auto'\n ? axis.values === 'dates' ? 'calendar' : axis.values === 'labels' ? 'everyPoint' : axis.named.length > 0 ? 'named' : 'calendar'\n : declared;\n const label = style.label === undefined ? 'auto' : style.label;\n const ticks: (readonly [number, string])[] = [];\n if (axis.effectiveScale === 'logarithmic' && from > 0) {\n for (const x of logSteps(from, to)) {\n ticks.push([x, axisWrites(axis) ? writePosition(axis, x) : upToPlaces(x, 4)]);\n }\n } else if (axis.values === 'labels') {\n axis.labels.forEach((text, i) => ticks.push([i, text]));\n } else if (placement === 'named') {\n for (const [position, text] of axis.named) {\n if (position >= from && position <= to) {\n ticks.push([position, text]);\n }\n }\n } else if (placement === 'everyPoint') {\n const xs = [...new Set([...points].filter(x => x >= from && x <= to))].toSorted((a, b) => a - b);\n for (const x of xs) {\n ticks.push([x, labelOf(axis, label, x, from, 'day')]);\n }\n } else if (placement === 'tenors') {\n for (const m of tenorMonths) {\n const x = axis.values === 'dates' ? dayOfDate(addMonths(dateOf(wholeDay(from)), m)) : from + m / 12;\n if (x <= to) {\n ticks.push([x, axis.values === 'dates' && label !== 'tenor' && label !== 'auto' ? labelOf(axis, label, x, from, 'day') : tenor(m / 12)]);\n }\n }\n } else if (axis.values === 'dates') {\n const unit = calendarUnit(from, to, map, textWidth, gap, axis.formatCode !== undefined && label === 'auto' ? axis : undefined);\n for (const x of calendarTicks(from, to, unit)) {\n ticks.push([x, labelOf(axis, label, x, from, unit.kind)]);\n }\n } else {\n const n = nice(from, to, 6);\n for (const x of steps(n.min, n.max, n.step)) {\n if (x >= from - 1e-9 && x <= to + 1e-9) {\n ticks.push([x, axis.formatCode === undefined ? upToPlaces(x, 4) : writePosition(axis, x)]);\n }\n }\n }\n return fitLabels(ticks, angle, map, textWidth, lineHeight, gap);\n}\n\n/** Keeps each label whose footprint along the axis clears the last kept one's; every tick stays. */\nexport function fitLabels(ticks: readonly (readonly [position: number, label: string])[], angle: number, map: (position: number) => number,\n textWidth: (text: string) => number, lineHeight: number, gap: number): AxisTicks {\n const rad = angle * Math.PI / 180;\n const result: AxisTick[] = [];\n let lastEnd = -Infinity;\n let depth = 0;\n let labelled = 0;\n for (const [x, text] of ticks) {\n const w = textWidth(text);\n // Along the axis a label at an angle takes its height's share, not its width's; read upwards, it\n // is anchored at its tick, so its footprint starts there.\n const along = w * Math.cos(rad) + lineHeight * Math.sin(rad);\n const px = map(x);\n const start = angle === 0 ? px - along / 2 : px - lineHeight * Math.sin(rad) / 2;\n if (start >= lastEnd + gap) {\n result.push(Object.freeze({ position: x, label: text }));\n labelled++;\n lastEnd = start + along;\n depth = Math.max(depth, w * Math.sin(rad) + lineHeight * Math.cos(rad));\n } else {\n result.push(Object.freeze({ position: x, label: null }));\n }\n }\n return Object.freeze({ ticks: Object.freeze(result), depth, labelled });\n}\n\nexport type Unit = 'day' | 'month' | 'quarter' | 'year';\n\ninterface CalendarStep {\n readonly kind: Unit;\n readonly every: number;\n}\n\nconst calendarSteps: readonly CalendarStep[] = [\n { kind: 'day', every: 1 }, { kind: 'day', every: 7 }, { kind: 'month', every: 1 }, { kind: 'quarter', every: 1 }, { kind: 'month', every: 6 },\n { kind: 'year', every: 1 }, { kind: 'year', every: 2 }, { kind: 'year', every: 5 }, { kind: 'year', every: 10 }, { kind: 'year', every: 25 },\n { kind: 'year', every: 50 },\n];\n\nconst unitOrder: readonly Unit[] = ['day', 'month', 'quarter', 'year'];\n\n// A day whose names are the longest a code writes: a Wednesday in September.\nconst widestDay = dayNumber(2026, 9, 30);\n\n/**\n * The finest calendar step a date code tells apart, found by writing days a day, a month and a year apart with\n * it; `undefined` for a code that writes none of them apart, such as one of the time alone (ADR-0420).\n */\nexport function codeResolution(write: (position: number) => string): Unit | undefined {\n const text = write(dayNumber(2001, 2, 3));\n if (write(dayNumber(2001, 2, 4)) !== text) {\n return 'day';\n }\n if (write(dayNumber(2001, 3, 3)) !== text) {\n return 'month';\n }\n return write(dayNumber(2002, 2, 3)) === text ? undefined : 'year';\n}\n\n// The finest step whose labels, at their usual width, fit side by side across the plot. Where the axis' code\n// writes the ticks, no step finer than the code tells apart, so no two ticks read alike, and its labels are as\n// wide as the code writes a long date (ADR-0420).\nfunction calendarUnit(from: number, to: number, map: (position: number) => number, textWidth: (text: string) => number, gap: number,\n coded: ChartAxis | undefined): CalendarStep {\n const plot = Math.abs(map(to) - map(from));\n const finest = coded === undefined ? 'day' : codeResolution(x => writePosition(coded, x));\n if (finest === undefined) {\n throw new Error('Internal: a code that tells no dates apart was not refused.');\n }\n const codedWidth = coded === undefined ? 0 : textWidth(writePosition(coded, widestDay));\n for (const s of calendarSteps) {\n if (unitOrder.indexOf(s.kind) < unitOrder.indexOf(finest)) {\n continue;\n }\n const count = Math.max(1, calendarTicks(from, to, s).length);\n const label = coded === undefined ? textWidth(s.kind === 'year' ? '2026' : s.kind === 'day' ? '2026-10-19' : '2026-10') : codedWidth;\n if (plot / count >= label + gap) {\n return s;\n }\n }\n return elementAt(calendarSteps, calendarSteps.length - 1);\n}\n\nconst dayOfDate = (d: CivilDate): number => dayNumber(d.year, d.month, d.day);\n\nfunction calendarTicks(from: number, to: number, step: CalendarStep): number[] {\n const start = wholeDay(Math.ceil(from));\n const end = wholeDay(Math.floor(to));\n const first = dateOf(start);\n let d: CivilDate = step.kind === 'day' ? first : { year: first.year, month: 1, day: 1 };\n const result: number[] = [];\n for (let day = dayOfDate(d); day <= end; day = dayOfDate(d)) {\n let on: boolean;\n switch (step.kind) {\n case 'day':\n on = true;\n break;\n case 'month':\n on = d.day === 1 && (d.month - 1) % step.every === 0;\n break;\n case 'quarter':\n on = d.day === 1 && (d.month - 1) % 3 === 0;\n break;\n case 'year':\n on = d.day === 1 && d.month === 1 && d.year % step.every === 0;\n break;\n default:\n return unreachable(step.kind);\n }\n if (on && day >= start) {\n result.push(day);\n }\n d = step.kind === 'day' ? dateOf(day + step.every) : step.kind === 'year' ? addMonths(d, 12) : addMonths(d, 1);\n }\n return result;\n}\n\nfunction labelOf(axis: ChartAxis, style: DateLabel, x: number, first: number, unit: Unit): string {\n if (axis.values === 'numbers') {\n const named = axis.named.find(n => n[0] === x);\n if (named !== undefined) {\n return named[1];\n }\n return axis.formatCode === undefined ? upToPlaces(x, 4) : writePosition(axis, x);\n }\n // A code writes a date tick, unless the axis' style names how date ticks are labelled (ADR-0420); a Format,\n // written for the values a column holds, leaves the ticks to the axis' own labels.\n if (axis.formatCode !== undefined && style === 'auto') {\n return writePosition(axis, x);\n }\n const d = dateOf(wholeDay(x));\n const label = style === 'auto' ? unit === 'year' ? 'year' : unit === 'day' ? 'date' : 'yearMonth' : style;\n switch (label) {\n case 'year':\n return yearOnly(d);\n case 'yearMonth':\n return yearMonth(d);\n case 'monthYear':\n return monthYear(d);\n case 'tenor': {\n const a = dateOf(wholeDay(first));\n return tenor(((d.year - a.year) * 12 + d.month - a.month) / 12);\n }\n case 'date':\n return isoDate(d);\n default:\n return unreachable(label);\n }\n}\n", "// An Observation's colour and size read from a column (ADR-0320), and the keys beside the plot they are\n// read on.\nimport { upToPlaces } from './invariant-text';\nimport type { ChartSeries, ChartValue, PointColour } from './model';\nimport { invariantText, toNumber } from './values';\nimport { nice, steps } from './ticks';\nimport type { Box, ChartMetricsResolved } from './metrics';\nimport { greatest, least } from './numbers';\n\n/** A tick of a key: its value, its height in CSS pixels, and its label. */\nexport interface KeyTick {\n /** The value. */\n readonly value: number;\n /** Its height in CSS pixels. */\n readonly y: number;\n /** Its label. */\n readonly label: string;\n}\n\n/** The colour bar a series' colour is read on (ADR-0320). */\nexport interface ColourKey {\n /** The series it belongs to. */\n readonly seriesId: string;\n /** What the colours are. */\n readonly title: string;\n /** The value at the foot of the lowest band. */\n readonly from: number;\n /** The value at the head of the highest band. */\n readonly to: number;\n /** Its ticks, the centre always among them when it diverges. */\n readonly ticks: readonly KeyTick[];\n /** Whether the bands diverge from a centre, which the middle band holds. */\n readonly diverging: boolean;\n /** The bar's box in CSS pixels; its title stands above it. */\n readonly box: Box;\n /** How many bands it is drawn in, low to high. */\n readonly bands: number;\n}\n\n/** A size key's entry: a value, its label, and the radius a marker of that value is drawn at. */\nexport interface SizeEntry {\n /** The value. */\n readonly value: number;\n /** Its label. */\n readonly label: string;\n /** The radius in CSS pixels. */\n readonly radius: number;\n}\n\n/** The size key a series' size is read on (ADR-0320). */\nexport interface SizeKey {\n /** The series it belongs to. */\n readonly seriesId: string;\n /** What the sizes are. */\n readonly title: string;\n /** Its entries, smallest first. */\n readonly entries: readonly SizeEntry[];\n /** Its box in CSS pixels, under its title. */\n readonly box: Box;\n}\n\n/** How many bands a colour is drawn in; the stylesheet's heat and diverge tokens, as the surface's (ADR-0310). */\nexport const bandCount = 9;\n\nconst barWidth = 12;\n\n/** The largest marker's radius, against a line's height. */\nexport const maxRadius = (lineHeight: number): number => lineHeight * 0.6;\n\n/** The gap between the plot and the keys: a marker at the plot's edge reaches past it by its radius. */\nexport const keyGap = (m: ChartMetricsResolved): number => m.padding + maxRadius(m.lineHeight);\n\nconst keyed = (s: ChartSeries): boolean => s.colourBy !== undefined || s.sizeBy !== undefined;\n\n/** A number on a key, as an axis writes its ticks. */\nexport const keyNumber = (v: number): string => upToPlaces(v, 4);\n\n/** The lowest and highest of a scale's values, or `undefined` when it has none. */\nexport function valueRange(values: readonly (ChartValue | null)[]): readonly [lo: number, hi: number] | undefined {\n const present = values.flatMap(v => (v === null ? [] : [toNumber(v)]));\n return present.length === 0 ? undefined : [least(present), greatest(present)];\n}\n\n/** The width of the column the keys take at the plot's right, or 0 when no visible series has one. */\nexport function keyColumnWidth(visible: readonly ChartSeries[], m: ChartMetricsResolved): number {\n const withKeys = visible.filter(keyed);\n if (withKeys.length === 0) {\n return 0;\n }\n const ends = withKeys.flatMap(s => {\n const colour = s.colourBy === undefined ? [0, 0] : colourRun(s.colourBy);\n const size = s.sizeBy === undefined ? undefined : valueRange(s.sizeBy.values);\n return [colour[0], colour[1], 0, size === undefined ? 0 : size[1]];\n });\n const label = greatest(ends.map(v => m.textWidth(keyNumber(v))));\n const titles = greatest(withKeys.flatMap(s => [s.colourBy?.title, s.sizeBy?.title]).flatMap(t => (t === undefined ? [] : [m.textWidth(t)])));\n return keyGap(m) + Math.max(titles, Math.max(barWidth, 2 * maxRadius(m.lineHeight)) + m.padding / 2 + label) + m.padding;\n}\n\n/** The run a colour's bands cover: the values' own, or alike on both sides of its centre (ADR-0310). */\nexport function colourRun(c: PointColour): readonly [from: number, to: number] {\n const range = valueRange(c.values);\n const [lo, hi] = range === undefined ? [c.centre === undefined ? 0 : c.centre, c.centre === undefined ? 0 : c.centre] : range;\n if (c.centre !== undefined) {\n const mid = c.centre;\n let reach = Math.max(Math.abs(hi - mid), Math.abs(lo - mid));\n if (reach === 0) {\n reach = mid === 0 ? 1 : Math.abs(mid) / 10;\n }\n return [mid - reach, mid + reach];\n }\n return hi > lo ? [lo, hi] : [lo - (lo === 0 ? 1 : Math.abs(lo) / 10), hi + (hi === 0 ? 1 : Math.abs(hi) / 10)];\n}\n\n/** A value's band: by its place in the run, or by its distance from the centre, the middle band neutral. */\nexport function colourBand(c: PointColour, run: readonly [number, number], value: number): number {\n const [from, to] = run;\n if (c.centre !== undefined) {\n const t = (value - c.centre) / ((to - from) / 2);\n const depth = Math.min(Math.trunc(bandCount / 2), Math.trunc(Math.floor(Math.abs(t) * bandCount / 2 + 0.5)));\n return Math.trunc(bandCount / 2) + Math.sign(t) * depth;\n }\n return Math.min(Math.max(Math.trunc(Math.floor((value - from) / (to - from) * bandCount)), 0), bandCount - 1);\n}\n\n/** A value's radius as a share of the largest: its area in proportion to the value. */\nexport const sizeShare = (max: number, value: number): number => (max > 0 ? Math.sqrt(value / max) : 1);\n\n/** The keys of the visible series, stacked down the column at `x`. */\nexport function pointKeys(visible: readonly ChartSeries[], x: number, top: number, height: number, m: ChartMetricsResolved):\n readonly [colours: ColourKey[], sizes: SizeKey[]] {\n const colours: ColourKey[] = [];\n const sizes: SizeKey[] = [];\n const lh = m.lineHeight;\n let y = top;\n for (const s of visible.filter(keyed)) {\n if (s.colourBy !== undefined) {\n const c = s.colourBy;\n const [from, to] = colourRun(c);\n const barTop = y + lh;\n const barHeight = Math.max(4 * lh, Math.min(10 * lh, height - (barTop - top) - lh));\n const box: Box = Object.freeze({ x, y: barTop, width: barWidth, height: barHeight });\n const n = nice(from, to, 4);\n const values = steps(n.min, n.max, n.step).filter(v => v >= from - 1e-9 * (to - from) && v <= to + 1e-9 * (to - from));\n if (c.centre !== undefined && !values.includes(c.centre)) {\n values.push(c.centre);\n }\n const ticks = values.toSorted((a, b) => a - b)\n .map(v => Object.freeze({ value: v, y: box.y + box.height * (to - v) / (to - from), label: keyNumber(v) }));\n colours.push(Object.freeze({\n seriesId: s.id, title: c.title, from, to, ticks: Object.freeze(ticks), diverging: c.centre !== undefined, box, bands: bandCount,\n }));\n y = barTop + barHeight + lh;\n }\n if (s.sizeBy !== undefined) {\n // Always drawn (ADR-0320): with no value above zero, every marker is drawn whole, and the key says so.\n const z = s.sizeBy;\n const rMax = maxRadius(lh);\n const range = valueRange(z.values);\n const hi = range === undefined ? 0 : range[1];\n const values: number[] = [];\n if (hi > 0) {\n const n = nice(0, hi, 3);\n values.push(...steps(n.step, n.max, n.step).filter(v => v <= hi).slice(-3));\n }\n if (values.length === 0) {\n values.push(hi);\n }\n const entries = values.map(v => Object.freeze({ value: v, label: keyNumber(v), radius: Math.max(0.75, rMax * sizeShare(hi, v)) }));\n const boxHeight = entries.reduce((sum, e) => sum + Math.max(2 * e.radius, lh) + lh / 4, 0);\n sizes.push(Object.freeze({\n seriesId: s.id, title: z.title, entries: Object.freeze(entries), box: Object.freeze({ x, y: y + lh, width: 2 * rMax, height: boxHeight }),\n }));\n y += lh + boxHeight + lh;\n }\n }\n return [colours, sizes];\n}\n\n/** What the Notes say of points a scale has no value for. */\nexport function pointScaleNotes(s: ChartSeries): string[] {\n const notes: string[] = [];\n for (const scale of [s.colourBy, s.sizeBy]) {\n if (scale === undefined) {\n continue;\n }\n const missing = s.points.filter((p, i) => p.y !== null && scale.values[i] === null).length;\n if (missing > 0) {\n notes.push(`${s.name}: ${String(missing)} ${missing === 1 ? 'point has' : 'points have'} no ${scale.title}, drawn as ${missing === 1 ? 'an outline' : 'outlines'}.`);\n }\n }\n return notes;\n}\n\n/** What the definition refuses of a series' scales, or `undefined`. */\nexport function pointScaleRefusal(s: ChartSeries): string | undefined {\n if (!keyed(s)) {\n return undefined;\n }\n if (s.kind !== 'observation') {\n return `'${s.name}' takes a colour or a size from a column, which belongs to marks drawn one a row: an observation.`;\n }\n if (s.colourBy !== undefined) {\n const c = s.colourBy;\n if (c.values.length !== s.points.length) {\n return `'${s.name}' has ${String(s.points.length)} points and ${String(c.values.length)} values of ${c.title}: its colour takes one a point.`;\n }\n if (c.centre !== undefined && !Number.isFinite(c.centre)) {\n return `'${s.name}': the value its colours diverge from is a finite number.`;\n }\n }\n if (s.sizeBy !== undefined) {\n const z = s.sizeBy;\n if (z.values.length !== s.points.length) {\n return `'${s.name}' has ${String(s.points.length)} points and ${String(z.values.length)} values of ${z.title}: its size takes one a point.`;\n }\n for (let i = 0; i < z.values.length; i++) {\n const v = z.values[i];\n if (v !== undefined && v !== null && toNumber(v) < 0) {\n const point = s.points[i];\n const at = point?.name === undefined ? `row ${String(i + 1)}` : point.name;\n return `'${s.name}' at ${at}: ${z.title} is ${invariantText(v)}, a negative size, which no marker can be drawn at.`;\n }\n }\n }\n return undefined;\n}\n", "// A Price Range's candles (ADR-0300, ADR-0302): its rows, and those rows merged into the market's own\n// periods where the plot cannot hold one a row.\nimport { dateOf, dayNumber, dayOfWeek, wholeDay } from './day-numbers';\nimport type { CandlePeriod, ChartAxis, ChartSeries, PriceBar } from './model';\nimport { elementAt, unreachable } from './must';\nimport { percentTwoPlaces } from './invariant-text';\nimport { greatest, least } from './numbers';\nimport { toNumber, writePosition, writeValue } from './values';\n\n/** A candle as drawn, in the data's units: one row, or a merged candle standing for several (ADR-0302). */\nexport interface DrawnCandle {\n /** The first position it stands for. */\n readonly from: number;\n /** The last. */\n readonly to: number;\n /** Where it is centred. */\n readonly x: number;\n /** Its open, or `null` for a High-Low-Close bar. */\n readonly open: number | null;\n /** Its high. */\n readonly high: number;\n /** Its low. */\n readonly low: number;\n /** Its close. */\n readonly close: number;\n /** Its volume, or `null`. */\n readonly volume: number | null;\n /** How many rows it stands for. */\n readonly rows: number;\n /** Its close above its own open, drawn hollow (ADR-0300). */\n readonly rising: boolean;\n /** Its close equal to its own open, drawn as one horizontal line. */\n readonly unchanged: boolean;\n}\n\n/** The start of the period a position falls in: the row itself, or the period's first day. */\nexport function periodStart(x: number, period: CandlePeriod): number {\n if (period === 'row') {\n return x;\n }\n const day = wholeDay(Math.floor(x));\n const d = dateOf(day);\n switch (period) {\n case 'week':\n return day - ((dayOfWeek(day) + 6) % 7);\n case 'month':\n return dayNumber(d.year, d.month, 1);\n case 'quarter':\n return dayNumber(d.year, Math.floor((d.month - 1) / 3) * 3 + 1, 1);\n case 'year':\n return dayNumber(d.year, 1, 1);\n default:\n return unreachable(period);\n }\n}\n\n/** A period's name, as the title and the Notes say it. */\nexport function periodName(period: CandlePeriod): string {\n switch (period) {\n case 'week':\n return 'Weekly';\n case 'month':\n return 'Monthly';\n case 'quarter':\n return 'Quarterly';\n case 'year':\n return 'Yearly';\n case 'row':\n return 'Rows';\n default:\n return unreachable(period);\n }\n}\n\n/** The market's periods, finest first. */\nexport const candlePeriods: readonly CandlePeriod[] = Object.freeze(['row', 'week', 'month', 'quarter', 'year']);\n\n/** Whether a row makes a candle: all four values present, or three where the series has no open at all. */\nexport function wholeBar(bar: PriceBar, withOpen: boolean): boolean {\n return bar.high !== null && bar.low !== null && bar.close !== null && (!withOpen || bar.open !== null);\n}\n\n/** Whether any row has an open: a series with none is drawn as High-Low-Close bars. */\nexport function hasOpen(bars: readonly PriceBar[]): boolean {\n return bars.some(b => b.open !== null);\n}\n\n/** The candles of the rows between `from` and `to`, one a row or merged into `period`. */\nexport function candlesOf(series: ChartSeries, from: number, to: number, period: CandlePeriod): DrawnCandle[] {\n const open = hasOpen(series.bars);\n const groups = new Map<number, PriceBar[]>();\n for (const b of series.bars) {\n if (b.x >= from && b.x <= to && wholeBar(b, open)) {\n const key = periodStart(b.x, period);\n const group = groups.get(key);\n if (group === undefined) {\n groups.set(key, [b]);\n } else {\n group.push(b);\n }\n }\n }\n const candles: DrawnCandle[] = [];\n for (const bars of groups.values()) {\n const first = elementAt(bars, 0);\n const last = elementAt(bars, bars.length - 1);\n const volumes = bars.flatMap(b => (b.volume === undefined || b.volume === null ? [] : [toNumber(b.volume)]));\n const openValue = open && first.open !== null ? toNumber(first.open) : null;\n const close = toNumber(must(last.close));\n candles.push(Object.freeze({\n from: first.x,\n to: last.x,\n x: period === 'row' ? first.x : (first.x + last.x) / 2,\n open: openValue,\n high: greatest(bars.map(b => toNumber(must(b.high)))),\n low: least(bars.map(b => toNumber(must(b.low)))),\n close,\n volume: volumes.length > 0 ? volumes.reduce((a, b) => a + b, 0) : null,\n rows: bars.length,\n rising: openValue !== null && close > openValue,\n unchanged: openValue !== null && close === openValue,\n }));\n }\n return candles;\n}\n\n/** A candle's change from the previous close as a percentage, in brackets after its amount; nothing where the previous close is zero. */\nexport function percentChange(change: number, previous: number): string {\n return previous === 0 ? '' : ` (${change >= 0 ? '+' : ''}${percentTwoPlaces(change / previous)})`;\n}\n\nfunction must<T>(value: T | null): T {\n if (value === null) {\n throw new Error('Internal: a whole row is missing a value.');\n }\n return value;\n}\n\n/** The refusal of a row whose values disagree (ADR-0300), named by its row and its values, or `undefined`. */\nexport function disagreement(series: ChartSeries, axis: ChartAxis, bar: PriceBar): string | undefined {\n if (bar.high === null || bar.low === null || bar.close === null) {\n return undefined;\n }\n const h = toNumber(bar.high);\n const l = toNumber(bar.low);\n const c = toNumber(bar.close);\n const row = `'${series.name}', the row of ${writePosition(axis, bar.x)}`;\n const w = (v: number | bigint): string => writeValue(series, v);\n if (bar.open !== null) {\n const o = toNumber(bar.open);\n if (h < o) {\n return `${row}: high ${w(bar.high)} is below open ${w(bar.open)}.`;\n }\n if (l > o) {\n return `${row}: low ${w(bar.low)} is above open ${w(bar.open)}.`;\n }\n }\n if (h < c) {\n return `${row}: high ${w(bar.high)} is below close ${w(bar.close)}.`;\n }\n if (l > c) {\n return `${row}: low ${w(bar.low)} is above close ${w(bar.close)}.`;\n }\n if (h < l) {\n return `${row}: high ${w(bar.high)} is below low ${w(bar.low)}.`;\n }\n return undefined;\n}\n", "// What a chart is of, in the data's own terms (ADR-0251). A definition that cannot be drawn honestly is\n// refused when it is made, with the sentence that says why (spine rule 1).\nimport { edgeRefusal } from './edges';\nimport { roundTrip } from './invariant-text';\nimport type {\n AppearanceKeys, ChartAxis, ChartAxisOptions, ChartPoint, ChartSeries, ChartSeriesOptions, ChartValue, SeriesInterval,\n} from './model';\nimport { elementAt } from './must';\nimport { pointScaleRefusal } from './point-scales';\nimport { disagreement, hasOpen, wholeBar } from './price-ranges';\nimport { codeResolution } from './ticks';\nimport { ChartRefusedError, readCode, toNumber, writePosition, writeValue } from './values';\n\nconst kinds = new Set(['level', 'rateOverInterval', 'amountPerPeriod', 'observation', 'priceRange']);\n\n/** The horizontal axis with its defaults applied. */\nexport function chartAxis(options: ChartAxisOptions): ChartAxis {\n const { values, title = '', labels = [], named = [], daysPerYear = 365.25, packed = false } = options;\n const effectiveScale = options.scale === undefined ? (values === 'labels' ? 'categories' : 'proportional') : options.scale;\n return Object.freeze({\n values, title,\n ...(options.scale === undefined ? {} : { scale: options.scale }),\n labels: Object.freeze([...labels]),\n named: Object.freeze(named.map(n => Object.freeze([n[0], n[1]] as const))),\n daysPerYear, packed,\n ...(options.format === undefined ? {} : { format: options.format }),\n ...(options.formatCode === undefined ? {} : { formatCode: options.formatCode }),\n effectiveScale,\n });\n}\n\n// A value as the C# engine's `ChartValue.Of` takes it: finite, or a whole number held exactly. What it is\n// is named only when it is refused, so a long series is not written out point by point to check it.\nfunction checkedValue(value: unknown, what: () => string): ChartValue | null {\n if (value === null || typeof value === 'bigint') {\n return value;\n }\n if (typeof value !== 'number') {\n throw new TypeError(`${what()} is ${typeof value}; a chart value is a number or a bigint, and a missing value is null.`);\n }\n if (!Number.isFinite(value)) {\n throw new RangeError(`${what()} is ${String(value)}. A chart value is finite; a missing value is a gap, handed in as null.`);\n }\n return value;\n}\n\n/** One series with its defaults applied, its values checked. */\nexport function chartSeries(options: ChartSeriesOptions): ChartSeries {\n const {\n step = 'preceding', axis = 'left', panel = '', interpolated = false, segments = [], details = [], edges = [], thinned = [],\n } = options;\n const where = `'${options.name}'`;\n const bars = options.bars === undefined ? [] : options.bars.map(b => Object.freeze({\n x: b.x,\n open: checkedValue(b.open, () => `${where}'s open`),\n high: checkedValue(b.high, () => `${where}'s high`),\n low: checkedValue(b.low, () => `${where}'s low`),\n close: checkedValue(b.close, () => `${where}'s close`),\n volume: b.volume === undefined ? null : checkedValue(b.volume, () => `${where}'s volume`),\n }));\n const open = hasOpen(bars);\n const given = options.points === undefined ? [] : options.points;\n // A Price Range's points are its bars' closes, as C#'s Bars sets them. A series handed back as options, as\n // C#'s `with` copies one, carries `bars: []` beside its own points, which stand.\n const points: readonly ChartPoint[] = options.bars === undefined || options.bars.length === 0\n ? given.map(p => Object.freeze({ ...p, y: checkedValue(p.y, () => `${where}'s value at ${roundTrip(p.x)}`) }))\n : bars.map(b => Object.freeze({ x: b.x, y: wholeBar(b, open) ? b.close : null }));\n const keys = options.keys;\n const effectiveKeys: AppearanceKeys = Object.freeze(keys === undefined ? { colour: options.id } : { ...keys });\n const kind = options.kind;\n const reachesZero = kind === 'amountPerPeriod'\n || (kind === 'observation' || kind === 'priceRange' ? options.fromZero === true : options.fromZero !== false);\n const scaled = (values: readonly (ChartValue | null)[], title: string): readonly (ChartValue | null)[] =>\n Object.freeze(values.map(v => checkedValue(v, () => `${where}'s ${title}`)));\n // The Consumer's function answers at the boundary as a point does: a value it cannot be is refused where\n // it is asked, never drawn as NaN (CONVENTIONS.md, \"Check at the boundary\").\n const sampler = options.sampler;\n const checkedSampler = sampler === undefined ? undefined : Object.freeze({\n from: sampler.from,\n to: sampler.to,\n valueAt: (x: number) => checkedValue(sampler.valueAt(x), () => `${where}'s value at ${roundTrip(x)}`),\n });\n return Object.freeze({\n id: options.id,\n name: options.name,\n kind,\n step,\n axis,\n panel,\n ...(keys === undefined ? {} : { keys: effectiveKeys }),\n ...(options.fromZero === undefined ? {} : { fromZero: options.fromZero }),\n interpolated,\n // What the definition checked is copied and frozen, so a Consumer's later change to what it handed\n // in cannot reach past the checks (CONVENTIONS.md, \"Immutable base plus a thin diff\").\n segments: Object.freeze(segments.map(g => Object.freeze({ ...g }))),\n points: Object.freeze(points),\n ...(options.colourBy === undefined ? {} : { colourBy: Object.freeze({ ...options.colourBy, values: scaled(options.colourBy.values, options.colourBy.title) }) }),\n ...(options.sizeBy === undefined ? {} : { sizeBy: Object.freeze({ ...options.sizeBy, values: scaled(options.sizeBy.values, options.sizeBy.title) }) }),\n details: Object.freeze(details.map(d => Object.freeze({ ...d, values: Object.freeze([...d.values]) }))),\n edges: Object.freeze(edges.map(e => Object.freeze({ ...e }))),\n bars: Object.freeze(bars),\n ...(options.mergeTo === undefined ? {} : { mergeTo: options.mergeTo }),\n ...(options.interval === undefined ? {} : { interval: checkedInterval(options.interval, where) }),\n ...(options.xInterval === undefined ? {} : { xInterval: checkedInterval(options.xInterval, where) }),\n thinned: Object.freeze(thinned.map(t => Object.freeze({ ...t }))),\n ...(checkedSampler === undefined ? {} : { sampler: checkedSampler }),\n ...(options.format === undefined ? {} : { format: options.format }),\n ...(options.formatCode === undefined ? {} : { formatCode: options.formatCode }),\n effectiveKeys,\n reachesZero,\n });\n}\n\nfunction checkedInterval(interval: SeriesInterval, where: string): SeriesInterval {\n return Object.freeze({\n ...interval,\n bounds: Object.freeze(interval.bounds.map(b => Object.freeze({\n x: b.x,\n lower: checkedValue(b.lower, () => `${where}'s lower bound`),\n upper: checkedValue(b.upper, () => `${where}'s upper bound`),\n }))),\n });\n}\n\n/** What a chart is of: its horizontal axis, its series, and the Consumer's Notes (ADR-0251, ADR-0257). */\nexport interface ChartDefinitionOptions {\n /** The horizontal axis. */\n readonly axis: ChartAxisOptions;\n /** The series, in the order the legend lists them. */\n readonly series: readonly ChartSeriesOptions[];\n /** The Consumer's Notes: plain lines shown under the chart (ADR-0257). */\n readonly notes?: readonly string[];\n}\n\n/**\n * What a chart is of, in the data's own terms (ADR-0251): its horizontal axis, its series and the\n * Consumer's Notes. A definition that cannot be drawn honestly is refused when it is made, with a\n * `ChartRefusedError` whose sentence says why.\n */\nexport class ChartDefinition {\n readonly #axis: ChartAxis;\n readonly #series: readonly ChartSeries[];\n readonly #notes: readonly string[];\n\n /** A chart of the given series on the given axis; refused when it cannot be drawn as asked. */\n constructor(options: ChartDefinitionOptions) {\n const { notes = [] } = options;\n this.#axis = chartAxis(options.axis);\n this.#series = Object.freeze(options.series.map(chartSeries));\n this.#notes = Object.freeze([...notes]);\n validate(this.#axis, this.#series);\n validatePacked(this.#axis, this.#series);\n }\n\n /** The horizontal axis. */\n get axis(): ChartAxis {\n return this.#axis;\n }\n\n /** The series, in the order the legend lists them. */\n get series(): readonly ChartSeries[] {\n return this.#series;\n }\n\n /** The Consumer's Notes. */\n get notes(): readonly string[] {\n return this.#notes;\n }\n}\n\n/** The packed axis's slots: each row of a Price Range with a value (ADR-0301). */\nexport function packedSessions(series: readonly ChartSeries[]): number[] {\n const sessions = new Set<number>();\n for (const s of series) {\n if (s.kind === 'priceRange') {\n const open = hasOpen(s.bars);\n for (const b of s.bars) {\n if (wholeBar(b, open)) {\n sessions.add(b.x);\n }\n }\n }\n }\n return [...sessions];\n}\n\nfunction validatePacked(axis: ChartAxis, series: readonly ChartSeries[]): void {\n if (!axis.packed) {\n return;\n }\n if (axis.values !== 'dates') {\n throw new ChartRefusedError('Only a Dates axis packs its sessions.');\n }\n const candles = new Set(packedSessions(series));\n if (candles.size === 0) {\n throw new ChartRefusedError('A packed axis takes its sessions from a Price Range, and the chart has none.');\n }\n for (const s of series.filter(o => o.kind !== 'priceRange')) {\n if (s.sampler !== undefined) {\n throw new ChartRefusedError(`'${s.name}' is a function, which has no values between the packed sessions.`);\n }\n const off = s.points.find(p => !candles.has(p.x));\n if (off !== undefined) {\n throw new ChartRefusedError(`'${s.name}' has a point at ${writePosition(axis, off.x)}, where no candle stands: a packed axis has nowhere true to put it.`);\n }\n }\n}\n\nfunction edgeWithoutInterval(s: ChartSeries): ChartPoint | undefined {\n if (s.points.length === 0) {\n return undefined;\n }\n const edge = s.step === 'preceding' ? elementAt(s.points, 0) : elementAt(s.points, s.points.length - 1);\n return edge.y === null ? undefined : edge;\n}\n\n// Refuses an axis' code it cannot write with, naming it (ADR-0420), as C#'s `ChartCodes.CheckAxis`.\nfunction checkAxisCode(axis: ChartAxis): void {\n const code = axis.formatCode;\n if (code === undefined) {\n return;\n }\n const reading = readCode(code);\n if (typeof reading === 'string') {\n throw new ChartRefusedError(`The axis' format code \"${code}\" ${reading}.`);\n }\n if (axis.format !== undefined) {\n throw new ChartRefusedError(`The axis has both a Format and the format code \"${code}\": it would write one position two ways.`);\n }\n if (axis.values === 'labels') {\n throw new ChartRefusedError(`The axis places labels, which it writes as they are: the format code \"${code}\" has nothing to write.`);\n }\n if (axis.values === 'dates' && !reading.isDate) {\n throw new ChartRefusedError(`The axis' format code \"${code}\" writes numbers, and the axis places dates.`);\n }\n if (axis.values === 'dates' && codeResolution(x => writePosition(axis, x)) === undefined) {\n throw new ChartRefusedError(`The axis' format code \"${code}\" writes no day, month or year, and the axis places dates.`);\n }\n if (axis.values === 'numbers' && reading.isDate) {\n throw new ChartRefusedError(`The axis' format code \"${code}\" writes dates, and the axis places numbers.`);\n }\n}\n\n// Refuses a series' code it cannot write with, naming the series (ADR-0420), as C#'s `ChartCodes.CheckSeries`.\nfunction checkSeriesCode(s: ChartSeries): void {\n const code = s.formatCode;\n if (code === undefined) {\n return;\n }\n const reading = readCode(code);\n if (typeof reading === 'string') {\n throw new ChartRefusedError(`'${s.name}''s format code \"${code}\" ${reading}.`);\n }\n if (s.format !== undefined) {\n throw new ChartRefusedError(`'${s.name}' has both a Format and the format code \"${code}\": it would write one value two ways.`);\n }\n if (reading.isDate) {\n throw new ChartRefusedError(`'${s.name}''s format code \"${code}\" writes dates, and its values are numbers.`);\n }\n}\n\nfunction validate(axis: ChartAxis, series: readonly ChartSeries[]): void {\n const ids = new Set<string>();\n const logarithmic = axis.effectiveScale === 'logarithmic';\n if (logarithmic && axis.values !== 'numbers') {\n throw new ChartRefusedError('Only a number axis can be logarithmic.');\n }\n checkAxisCode(axis);\n for (const s of series) {\n if (ids.has(s.id)) {\n throw new ChartRefusedError(`Two series are named '${s.id}'; each series needs an identity of its own.`);\n }\n checkSeriesCode(s);\n ids.add(s.id);\n if (!kinds.has(s.kind)) {\n throw new ChartRefusedError(`'${s.name}' declares no Series Kind: say whether it is a Level, a Rate over an interval or an Amount per period.`);\n }\n if (s.kind === 'amountPerPeriod' && s.fromZero === false) {\n throw new ChartRefusedError(`'${s.name}' is an Amount per period, which is always drawn from zero.`);\n }\n if (s.kind === 'amountPerPeriod' && axis.values === 'labels') {\n throw new ChartRefusedError(`'${s.name}' is an Amount per period, but categories have no length to draw it per year over.`);\n }\n if (s.sampler !== undefined && s.points.length > 0) {\n throw new ChartRefusedError(`'${s.name}' is handed in both as points and as a function; give one.`);\n }\n if (s.sampler !== undefined && axis.effectiveScale === 'categories') {\n throw new ChartRefusedError(`'${s.name}' is a function, which has no values between categories to sample.`);\n }\n if (s.sampler !== undefined && s.kind !== 'level') {\n throw new ChartRefusedError(`'${s.name}' is a function, which is drawn as a Level; a step is handed in as its points.`);\n }\n const edge = s.kind === 'amountPerPeriod' ? edgeWithoutInterval(s) : undefined;\n if (edge !== undefined) {\n throw new ChartRefusedError(`'${s.name}' has an amount at ${roundTrip(edge.x)} with no interval to draw it per year over: an Amount per period's ${s.step === 'preceding' ? 'first' : 'last'} point only bounds the interval next to it, and holds no amount.`);\n }\n if (s.sampler !== undefined && !(s.sampler.from < s.sampler.to)) {\n throw new ChartRefusedError(`'${s.name}' is sampled over an empty range.`);\n }\n if (s.kind === 'observation' && axis.effectiveScale === 'categories') {\n throw new ChartRefusedError(`'${s.name}' is an Observation, which needs a value axis across: numbers or dates, not categories.`);\n }\n if (s.kind === 'observation' && s.sampler !== undefined) {\n throw new ChartRefusedError(`'${s.name}' is an Observation, which is handed in as its points, not as a function.`);\n }\n const unplaced = logarithmic ? s.points.find(p => !(p.x > 0)) : undefined;\n if (unplaced !== undefined) {\n throw new ChartRefusedError(`'${s.name}' has a point at ${roundTrip(unplaced.x)}, which a logarithmic axis cannot place: every position must be above zero.`);\n }\n if (logarithmic && s.sampler !== undefined && !(s.sampler.from > 0)) {\n throw new ChartRefusedError(`'${s.name}' is sampled from ${roundTrip(s.sampler.from)}, which a logarithmic axis cannot place: every position must be above zero.`);\n }\n // An Observation's points are neither ordered nor unique in x (ADR-0290).\n for (let i = 1; i < s.points.length && s.kind !== 'observation'; i++) {\n if (!(elementAt(s.points, i - 1).x < elementAt(s.points, i).x)) {\n throw new ChartRefusedError(`'${s.name}' has its points out of order at position ${roundTrip(elementAt(s.points, i).x)}; a line joins only neighbours, so the order must be the data's.`);\n }\n }\n if (s.kind === 'priceRange') {\n if (axis.values !== 'dates') {\n throw new ChartRefusedError(`'${s.name}' is a Price Range, which stands on a Dates axis: its candles merge into weeks and months.`);\n }\n if (s.sampler !== undefined || s.points.length !== s.bars.length) {\n throw new ChartRefusedError(`'${s.name}' is a Price Range, handed in as its rows (open, high, low, close), not as points.`);\n }\n for (const b of s.bars) {\n const refusal = disagreement(s, axis, b);\n if (refusal !== undefined) {\n throw new ChartRefusedError(refusal);\n }\n }\n } else if (s.bars.length > 0) {\n throw new ChartRefusedError(`'${s.name}' has rows of open, high, low and close, but is not a Price Range.`);\n }\n const scaleRefusal = pointScaleRefusal(s);\n if (scaleRefusal !== undefined) {\n throw new ChartRefusedError(scaleRefusal);\n }\n for (const detail of s.details) {\n if (s.kind !== 'observation') {\n throw new ChartRefusedError(`'${s.name}' says ${detail.title} in its tooltip, which belongs to marks drawn one a row: an observation.`);\n }\n if (detail.values.length !== s.points.length) {\n throw new ChartRefusedError(`'${s.name}' has ${String(s.points.length)} points and ${String(detail.values.length)} values of ${detail.title}: its tooltip says one a point.`);\n }\n }\n const edgeProblem = edgeRefusal(s);\n if (edgeProblem !== undefined) {\n throw new ChartRefusedError(edgeProblem);\n }\n if (s.mergeTo !== undefined && s.kind !== 'priceRange') {\n throw new ChartRefusedError(`'${s.name}' fixes a candle period, but is not a Price Range.`);\n }\n if (s.interval !== undefined) {\n if ((s.kind !== 'level' && s.kind !== 'observation') || s.sampler !== undefined) {\n throw new ChartRefusedError(`'${s.name}' has an Interval, which belongs to a Level's or an Observation's points.`);\n }\n validateInterval(axis, s, s.interval, '');\n }\n if (s.xInterval !== undefined) {\n if (s.kind !== 'observation') {\n throw new ChartRefusedError(`'${s.name}' has a horizontal Interval, which belongs to an Observation's points.`);\n }\n validateInterval(axis, s, s.xInterval, 'horizontal ');\n }\n for (const g of s.segments) {\n if (!(g.from < g.to)) {\n throw new ChartRefusedError(`'${s.name}' has an empty segment, '${g.method}'.`);\n }\n }\n }\n}\n\n// A Level's bounds are found by position; an Observation's are one a row, in the points' order\n// (ADR-0303, ADR-0304).\nfunction validateInterval(axis: ChartAxis, s: ChartSeries, iv: SeriesInterval, which: string): void {\n if (iv.meaning.trim() === '') {\n throw new ChartRefusedError(`'${s.name}' has a ${which}Interval that does not say what it means: name it (\"95% CI\", \"\u00B11\u03C3\", \"Bid\u2013Ask\").`);\n }\n const write = (v: ChartValue): string => (which.length > 0 ? writePosition(axis, toNumber(v)) : writeValue(s, v));\n if (s.kind === 'observation') {\n if (iv.style === 'band') {\n throw new ChartRefusedError(`'${s.name}' draws its ${which}Interval as a band, which joins neighbours: an Observation's points have none, so it takes whiskers.`);\n }\n if (iv.bounds.length !== s.points.length) {\n throw new ChartRefusedError(`'${s.name}' has ${String(s.points.length)} points and ${String(iv.bounds.length)} ${which}bounds: an Observation's bounds are one a row, in its points' order.`);\n }\n for (let i = 0; i < s.points.length; i++) {\n const b = elementAt(iv.bounds, i);\n const p = elementAt(s.points, i);\n const at = p.name === undefined ? `row ${String(i + 1)}` : p.name;\n if (b.x !== p.x && !(Number.isNaN(b.x) && Number.isNaN(p.x))) {\n throw new ChartRefusedError(`'${s.name}' at ${at}: the ${which}bound stands at ${writePosition(axis, b.x)}, but its point at ${writePosition(axis, p.x)}.`);\n }\n if (b.lower !== null && b.upper !== null && toNumber(b.lower) > toNumber(b.upper)) {\n throw new ChartRefusedError(`'${s.name}' at ${at}: the lower bound ${write(b.lower)} of its ${iv.meaning} is above the upper ${write(b.upper)}.`);\n }\n }\n return;\n }\n const xs = new Set(s.points.map(p => p.x));\n const seen = new Set<number>();\n for (const b of iv.bounds) {\n if (!xs.has(b.x)) {\n throw new ChartRefusedError(`'${s.name}' has an interval at ${writePosition(axis, b.x)}, where it has no point.`);\n }\n if (seen.has(b.x)) {\n throw new ChartRefusedError(`'${s.name}' has two intervals at ${writePosition(axis, b.x)}.`);\n }\n seen.add(b.x);\n if (b.lower !== null && b.upper !== null && toNumber(b.lower) > toNumber(b.upper)) {\n throw new ChartRefusedError(`'${s.name}' at ${writePosition(axis, b.x)}: the lower bound ${writeValue(s, b.lower)} of its ${iv.meaning} is above the upper ${writeValue(s, b.upper)}.`);\n }\n }\n}\n\n", "// Each series' look from its Appearance Keys (ADR-0256).\nimport type { ChartDefinition } from './definition';\nimport type { MarkerShape, SeriesLook } from './model';\nimport { elementAt } from './must';\n\n/** The line-style slots the stylesheet defines: solid, dashed, dotted, dash-dot. */\nexport const lineStyles = 4;\n\n/** The marker shapes there are. */\nexport const markers = 4;\n\n/** The colour slots the stylesheet defines unless a theme declares more. */\nexport const defaultColourSlots = 10;\n\nconst shapes: readonly MarkerShape[] = ['circle', 'square', 'diamond', 'triangle'];\n\n/** Each series' look, and whether colours repeat. */\nexport interface Looks {\n /** Each series' look by its identity. */\n readonly looks: ReadonlyMap<string, SeriesLook>;\n /** Whether more colour keys than slots made colours repeat. */\n readonly coloursRepeat: boolean;\n}\n\n/** A look of these slots. */\nexport function seriesLook(colour: number, lineStyle: number, marker: number): SeriesLook {\n return Object.freeze({ colour, lineStyle, marker, shape: elementAt(shapes, marker % markers) });\n}\n\n// A key's slot: the one it took when first named, or the next.\nfunction slot(table: Map<string, number>, key: string): number {\n const found = table.get(key);\n if (found !== undefined) {\n return found;\n }\n table.set(key, table.size);\n return table.size - 1;\n}\n\n/**\n * Each series' look by its identity, and whether more colour keys than `colourSlots` made colours repeat.\n * A key takes the next slot the first time any series of the definition names it, hidden series included,\n * so the same key keeps the same look when another series is hidden, filtered or added after it. A series\n * that sets no line-style key is solid; one that sets no marker key takes a circle.\n */\nexport function appearanceOf(definition: ChartDefinition, colourSlots = defaultColourSlots): Looks {\n if (!Number.isInteger(colourSlots) || colourSlots < 1) {\n throw new RangeError(`${String(colourSlots)} colour slots is not a count of one at least.`);\n }\n const colours = new Map<string, number>();\n const lines = new Map<string, number>();\n const marks = new Map<string, number>();\n const looks = new Map<string, SeriesLook>();\n for (const s of definition.series) {\n const k = s.effectiveKeys;\n looks.set(s.id, seriesLook(\n slot(colours, k.colour) % colourSlots,\n k.lineStyle === undefined ? 0 : slot(lines, k.lineStyle) % lineStyles,\n k.marker === undefined ? 0 : slot(marks, k.marker) % markers));\n }\n return Object.freeze({ looks, coloursRepeat: colours.size > colourSlots });\n}\n", "// The geometry a chart is laid out with, in CSS pixels (ADR-0027/0028), and what the viewer narrowed it to.\nimport type { AxisScale } from './model';\nimport { defaultColourSlots } from './appearance';\n\n/** A rectangle in CSS pixels. */\nexport interface Box {\n /** Its left. */\n readonly x: number;\n /** Its top. */\n readonly y: number;\n /** Its width. */\n readonly width: number;\n /** Its height. */\n readonly height: number;\n}\n\n/** The geometry a chart is laid out with, in CSS pixels, resolved by the caller and never paired with a stylesheet literal. */\nexport interface ChartMetrics {\n /** The chart's width. */\n readonly width: number;\n /** The chart's height. */\n readonly height: number;\n /** Device pixels per CSS pixel, which Thinning and sampling count in (ADR-0090); 1 by default. */\n readonly devicePixelRatio?: number;\n /** A label's height; 14 by default. */\n readonly lineHeight?: number;\n /** The space around the plots; 8 by default. */\n readonly padding?: number;\n /** The space between panels; 16 by default. */\n readonly panelGap?: number;\n /** A label's estimated width; text is never measured (ADR-0021). By default 0.6 of the line height a character. */\n readonly textWidth?: (text: string) => number;\n /** How many colour slots the stylesheet defines: ten, unless a theme declares more (ADR-0256). */\n readonly colourSlots?: number;\n}\n\n/** The metrics with their defaults applied. */\nexport interface ChartMetricsResolved {\n readonly width: number;\n readonly height: number;\n readonly devicePixelRatio: number;\n readonly lineHeight: number;\n readonly padding: number;\n readonly panelGap: number;\n readonly textWidth: (text: string) => number;\n readonly colourSlots: number;\n}\n\n/** The metrics with their defaults applied, as C#'s `ChartMetrics` holds them. */\nexport function resolveMetrics(metrics: ChartMetrics): ChartMetricsResolved {\n const { width, height, devicePixelRatio = 1, lineHeight = 14, padding = 8, panelGap = 16, colourSlots = defaultColourSlots } = metrics;\n const textWidth = metrics.textWidth === undefined ? (text: string): number => text.length * lineHeight * 0.6 : metrics.textWidth;\n return { width, height, devicePixelRatio, lineHeight, padding, panelGap, textWidth, colourSlots };\n}\n\n/** What the viewer narrowed a chart to \u2014 its Chart Filters \u2014 which narrow the drawing, never the definition. */\nexport interface ChartView {\n /** The identities of the series hidden. */\n readonly hidden?: ReadonlySet<string> | readonly string[];\n /** The first position shown; absent for the data's first. */\n readonly from?: number;\n /** The last position shown; absent for the data's last. */\n readonly to?: number;\n /** The scale the viewer switched the axis to; absent for the declared one (ADR-0251). */\n readonly scale?: AxisScale;\n /** The lowest value the left axis shows; absent for the data's (ADR-0290). */\n readonly yFrom?: number;\n /** The highest; absent for the data's. */\n readonly yTo?: number;\n /** The vertical axes' scale: `logarithmic`, or absent or `proportional` (ADR-0290). */\n readonly yScale?: AxisScale;\n}\n", "// What one series draws, in the axes' units, before any pixel (ADR-0253): a Level's points joined only to\n// their neighbours, a step's levels with filled and open ends, a gap where a value is missing.\nimport type { ChartAxis, ChartPoint, ChartSeries, IntervalBound, Segment, SeriesInterval, SeriesSampler } from './model';\nimport { elementAt, unreachable } from './must';\nimport { bitDecrement } from './numbers';\nimport { colourBand, colourRun, sizeShare, valueRange } from './point-scales';\nimport { candlesOf, type DrawnCandle } from './price-ranges';\nimport { toNumber, yearsBetween } from './values';\n\n/** A point of a drawn line, in the axes' own units: the horizontal position and the height. */\nexport interface DrawnPoint {\n /** The horizontal position. */\n readonly x: number;\n /** The height, in the vertical axis' units. */\n readonly y: number;\n}\n\n/** A lower and an upper bound. */\nexport type Bounds = readonly [lower: number, upper: number];\n\n/** A marker: where it stands, and whether it is filled \u2014 the function takes the value there \u2014 or an outline (ADR-0253). */\nexport interface DrawnMarker {\n /** The horizontal position. */\n readonly x: number;\n /** The height. */\n readonly y: number;\n /** Filled where the function takes the value; an outline where it does not. */\n readonly filled: boolean;\n /** The index of the series' point the marker stands for, or -1 when it stands for none. */\n readonly point: number;\n /** How many of the series' points it stands for: more than one where markers on one device pixel were merged (ADR-0290). */\n readonly count: number;\n /** An Observation's vertical interval at the marker; where marks merged, the union of theirs (ADR-0304). */\n readonly yBounds?: Bounds;\n /** An Observation's horizontal interval at the marker (ADR-0304). */\n readonly xBounds?: Bounds;\n /** Its colour band from the series' colour scale; absent for the series' own colour (ADR-0320). */\n readonly band?: number;\n /** Its radius from the series' size scale: a share of the largest in a drawing, CSS pixels in a scene (ADR-0320). */\n readonly radius?: number;\n}\n\n/** A whisker as drawn: a point's interval. */\nexport interface DrawnWhisker {\n /** The point's position. */\n readonly x: number;\n /** Its lower bound. */\n readonly lower: number;\n /** Its upper bound. */\n readonly upper: number;\n}\n\n/** What one series draws, in the axes' units: its lines, each joining only neighbours, and its markers. */\nexport interface SeriesDrawing {\n /** Each an unbroken line; a gap, a step's level or a Segment's boundary starts another. */\n readonly lines: readonly (readonly DrawnPoint[])[];\n /** The markers, filled or an outline. */\n readonly markers: readonly DrawnMarker[];\n /** A Price Range's candles (ADR-0300, ADR-0302). */\n readonly candles: readonly DrawnCandle[];\n /** A Level's Interval drawn as whiskers (ADR-0303). */\n readonly whiskers: readonly DrawnWhisker[];\n /** A Level's Interval drawn as a band: each run of neighbours that all have one (ADR-0303). */\n readonly bands: readonly (readonly DrawnWhisker[])[];\n}\n\n/** A drawing of these lines and markers, and nothing else. */\nexport function seriesDrawing(lines: readonly (readonly DrawnPoint[])[], markers: readonly DrawnMarker[],\n more: Partial<Pick<SeriesDrawing, 'candles' | 'whiskers' | 'bands'>> = {}): SeriesDrawing {\n const { candles = [], whiskers = [], bands = [] } = more;\n return Object.freeze({\n lines: Object.freeze(lines), markers: Object.freeze(markers),\n candles: Object.freeze(candles), whiskers: Object.freeze(whiskers), bands: Object.freeze(bands),\n });\n}\n\n/** A marker, its point and count those of a marker that stands for none. */\nexport function marker(x: number, y: number, filled: boolean, more: Partial<Omit<DrawnMarker, 'x' | 'y' | 'filled'>> = {}): DrawnMarker {\n return Object.freeze({ x, y, filled, point: -1, count: 1, ...more });\n}\n\nconst point = (x: number, y: number): DrawnPoint => Object.freeze({ x, y });\n\n/** Where a sampled series is drawn, and the quotes it is asked at. */\nexport interface DrawingRange {\n /** The first position drawn; \u2212\u221E by default. */\n readonly from?: number;\n /** The last; +\u221E by default. */\n readonly to?: number;\n /** About how many positions a sampled series is asked at; 0 by default. */\n readonly pixels?: number;\n /** Positions a sampled series is always asked at: the quotes it is drawn through (ADR-0257). */\n readonly quotes?: Iterable<number>;\n}\n\n/**\n * What a series draws. A sampled series is asked at about `pixels` positions over the part of its range\n * inside `from` to `to`, and always at each Segment's boundary and at each of `quotes` (ADR-0257).\n */\nexport function drawSeries(series: ChartSeries, axis: ChartAxis, range: DrawingRange = {}): SeriesDrawing {\n const { from = -Infinity, to = Infinity, pixels = 0, quotes = [] } = range;\n switch (series.kind) {\n case 'level':\n return series.sampler === undefined\n ? withInterval(level(series.points, series.segments, true), series)\n : level(sample(series.sampler, series.segments, from, to, pixels, quotes, axis.effectiveScale === 'logarithmic'), series.segments, false);\n case 'priceRange':\n return seriesDrawing([], [], { candles: candlesOf(series, from, to, 'row') });\n case 'rateOverInterval':\n return steps(series, axis);\n case 'amountPerPeriod':\n return steps(series, axis);\n case 'observation':\n return observations(series);\n default:\n return unreachable(series.kind);\n }\n}\n\n// A point's interval where both its bounds are given; a band joins only neighbours that each have one, and\n// breaks at a point that has none (ADR-0303).\nfunction withInterval(drawing: SeriesDrawing, series: ChartSeries): SeriesDrawing {\n const iv = series.interval;\n if (iv === undefined) {\n return drawing;\n }\n const bounds = new Map<number, DrawnWhisker>();\n for (const b of iv.bounds) {\n if (b.lower !== null && b.upper !== null) {\n if (bounds.has(b.x)) {\n throw new Error('Internal: two bounds at one position passed the definition.');\n }\n bounds.set(b.x, Object.freeze({ x: b.x, lower: toNumber(b.lower), upper: toNumber(b.upper) }));\n }\n }\n if (iv.style !== 'band') {\n return seriesDrawing(drawing.lines, drawing.markers, {\n whiskers: series.points.flatMap(p => {\n const w = bounds.get(p.x);\n return w === undefined ? [] : [w];\n }),\n });\n }\n const bands: (readonly DrawnWhisker[])[] = [];\n let run: DrawnWhisker[] = [];\n for (const p of series.points) {\n const w = bounds.get(p.x);\n if (w !== undefined) {\n run.push(w);\n continue;\n }\n if (run.length > 0) {\n bands.push(Object.freeze(run));\n }\n run = [];\n }\n if (run.length > 0) {\n bands.push(Object.freeze(run));\n }\n return seriesDrawing(drawing.lines, drawing.markers, { bands });\n}\n\n/** The height a step at point `i` is drawn at: its value, or for an amount its value per year. */\nexport function stepHeight(series: ChartSeries, axis: ChartAxis, i: number): number {\n const v = toNumber(valueAt(series.points, i));\n if (series.kind !== 'amountPerPeriod') {\n return v;\n }\n const [a, b] = stepInterval(series, i);\n return v / yearsBetween(axis, a, b);\n}\n\n/** The interval a step's point `i` stands for. */\nexport function stepInterval(series: ChartSeries, i: number): readonly [from: number, to: number] {\n return series.step === 'preceding'\n ? [elementAt(series.points, i - 1).x, elementAt(series.points, i).x]\n : [elementAt(series.points, i).x, elementAt(series.points, i + 1).x];\n}\n\nfunction valueAt(points: readonly ChartPoint[], i: number): number | bigint {\n const y = elementAt(points, i).y;\n if (y === null) {\n throw new Error('Internal: a step was asked its height where it has no value.');\n }\n return y;\n}\n\nfunction level(points: readonly ChartPoint[], segments: readonly Segment[], withMarkers: boolean): SeriesDrawing {\n const lines: (readonly DrawnPoint[])[] = [];\n const markers: DrawnMarker[] = [];\n let line: DrawnPoint[] = [];\n const end = (): void => {\n if (line.length > 1) {\n lines.push(Object.freeze(line));\n }\n line = [];\n };\n for (const p of points) {\n if (p.y === null) {\n end();\n continue;\n }\n const d = point(p.x, toNumber(p.y));\n const last = line.at(-1);\n if (last !== undefined && segments.some(g => crosses(g, last.x, p.x))) {\n end();\n }\n const atBoundary = segments.some(g => g.from === p.x || g.to === p.x);\n // Sampled, the curve was asked just short of the boundary from its left: the left line ends there\n // and the right one starts at the boundary itself, never joined.\n const before = line.at(-1);\n if (atBoundary && before !== undefined && before.x === bitDecrement(p.x)) {\n end();\n }\n line.push(d);\n if (withMarkers) {\n markers.push(marker(d.x, d.y, true));\n }\n // Handed in as points, a point on the boundary ends the left line and starts the right.\n if (atBoundary && line.length > 1) {\n end();\n line.push(d);\n }\n }\n end();\n return seriesDrawing(lines, markers);\n}\n\n// A boundary strictly between two neighbours: the line is not joined across it, where the Consumer's\n// method changes and a forward may jump (ADR-0257).\nconst crosses = (g: Segment, a: number, b: number): boolean => (a < g.from && g.from < b) || (a < g.to && g.to < b);\n\nfunction steps(series: ChartSeries, axis: ChartAxis): SeriesDrawing {\n const p = series.points;\n const lines: (readonly DrawnPoint[])[] = [];\n const markers: DrawnMarker[] = [];\n const preceding = series.step === 'preceding';\n for (let i = 0; i < p.length; i++) {\n const y = elementAt(p, i).y;\n if (y === null) {\n continue;\n }\n const hasInterval = preceding ? i > 0 : i < p.length - 1;\n if (!hasInterval) {\n // A rate at the edge holds at its own instant only; an amount there is refused when the\n // definition is made.\n markers.push(marker(elementAt(p, i).x, toNumber(y), true));\n continue;\n }\n const h = stepHeight(series, axis, i);\n const [a, b] = stepInterval(series, i);\n lines.push(Object.freeze([point(a, h), point(b, h)]));\n const [own, other] = preceding ? [b, a] : [a, b];\n markers.push(marker(own, h, true));\n const neighbour = preceding ? i - 1 : i + 1;\n const continuous = elementAt(p, neighbour).y !== null && neighbourHeight(series, axis, neighbour, preceding) === h;\n if (!continuous) {\n markers.push(marker(other, h, false));\n }\n }\n return seriesDrawing(lines, markers);\n}\n\n// The height the neighbour's own level takes at the shared end; at an edge with no interval the value\n// itself, which an amount never has there.\nfunction neighbourHeight(series: ChartSeries, axis: ChartAxis, i: number, preceding: boolean): number {\n const hasInterval = preceding ? i > 0 : i < series.points.length - 1;\n return hasInterval ? stepHeight(series, axis, i) : toNumber(valueAt(series.points, i));\n}\n\n// An Observation's points, each a marker of its own and none joined (ADR-0290); a point missing its value\n// is no marker. Its interval's bounds are one a row (ADR-0304).\nfunction observations(series: ChartSeries): SeriesDrawing {\n const markers: DrawnMarker[] = [];\n const colourBy = series.colourBy;\n const sizeBy = series.sizeBy;\n // Each scale's run is read once, not once a point.\n const run = colourBy === undefined ? undefined : colourRun(colourBy);\n const sizeRange = sizeBy === undefined ? undefined : valueRange(sizeBy.values);\n const largest = sizeRange === undefined ? 0 : sizeRange[1];\n series.points.forEach((p, i) => {\n if (p.y === null || !Number.isFinite(p.x)) {\n return;\n }\n // A point a scale has no value for is an outline, and the Notes say so (ADR-0320).\n const colour = colourBy === undefined ? undefined : colourBy.values[i];\n const size = sizeBy === undefined ? undefined : sizeBy.values[i];\n const unscaled = (colourBy !== undefined && (colour === undefined || colour === null)) || (sizeBy !== undefined && (size === undefined || size === null));\n const yBounds = boundsAt(series.interval, i);\n const xBounds = boundsAt(series.xInterval, i);\n markers.push(marker(p.x, toNumber(p.y), !unscaled, {\n point: i,\n ...(yBounds === undefined ? {} : { yBounds }),\n ...(xBounds === undefined ? {} : { xBounds }),\n ...(colourBy === undefined || run === undefined || colour === undefined || colour === null ? {} : { band: colourBand(colourBy, run, toNumber(colour)) }),\n ...(size === undefined || size === null ? {} : { radius: sizeShare(largest, toNumber(size)) }),\n }));\n });\n return seriesDrawing([], markers);\n}\n\n/** An Observation's bounds at row `i`, where both are given. */\nexport function boundsAt(interval: SeriesInterval | undefined, i: number): Bounds | undefined {\n if (interval === undefined) {\n return undefined;\n }\n const b: IntervalBound = elementAt(interval.bounds, i);\n return b.lower === null || b.upper === null ? undefined : Object.freeze([toNumber(b.lower), toNumber(b.upper)] as const);\n}\n\n/** The positions a sampled series is asked at, and its answers. */\nexport function sample(f: SeriesSampler, segments: readonly Segment[], from: number, to: number, pixels: number, quotes: Iterable<number>, logarithmic = false): ChartPoint[] {\n const lo = Math.max(f.from, from);\n const hi = Math.min(f.to, to);\n if (!(lo <= hi)) {\n return [];\n }\n const xs = new Set<number>([lo, hi]);\n const n = Math.max(pixels, 2);\n // On a logarithmic axis the samples are even in the axis' own scale (ADR-0290).\n for (let k = 1; k < n; k++) {\n xs.add(logarithmic && lo > 0 ? lo * (hi / lo) ** (k / n) : lo + (hi - lo) * k / n);\n }\n for (const g of segments) {\n for (const b of [g.from, g.to]) {\n if (lo <= b && b <= hi) {\n xs.add(b);\n }\n }\n }\n for (const q of quotes) {\n if (lo <= q && q <= hi) {\n xs.add(q);\n }\n }\n const points: ChartPoint[] = [];\n for (const x of [...xs].toSorted((a, b) => a - b)) {\n // Just short of a boundary the curve is asked from its left, so a jump there is drawn as the\n // Consumer's method has it on each side.\n if (segments.some(g => (g.from === x || g.to === x) && x > lo)) {\n const left = bitDecrement(x);\n points.push(Object.freeze({ x: left, y: f.valueAt(left) }));\n }\n points.push(Object.freeze({ x, y: f.valueAt(x) }));\n }\n return points;\n}\n\n/** The Segment that covers `x`: the one it lies in, or the one it ends, since a Segment's end is its own (ADR-0257). */\nexport function segmentAt(s: ChartSeries, x: number): Segment | undefined {\n const inside = s.segments.find(k => k.from <= x && x < k.to);\n return inside !== undefined ? inside : s.segments.findLast(k => k.to === x);\n}\n", "// Thinning (ADR-0254): past the plot's device pixels, each pixel column keeps a line's first, last,\n// lowest and highest point, so the drawn shape is the full series' at that width, every peak and trough\n// kept. It runs on the drawing, never on the data: the files keep every point.\nimport type { PixelSummary } from './model';\nimport { elementAt } from './must';\nimport { greatest, least } from './numbers';\nimport { seriesDrawing, type DrawnPoint, type SeriesDrawing } from './series-drawing';\n\n/** A series' drawing after Thinning, and what each thinned pixel holds. */\nexport interface ThinnedDrawing {\n /** What is drawn. */\n readonly drawing: SeriesDrawing;\n /** One entry per pixel that held more than one point; empty when nothing was thinned. */\n readonly thinned: readonly PixelSummary[];\n}\n\nconst summary = (from: number, to: number, min: number, max: number, count: number): PixelSummary =>\n Object.freeze({ from, to, min, max, count });\n\n/**\n * Thins `drawing` for a plot where `toPixel` gives a position's device pixel column. A drawing with no more\n * points than pixels is returned as it is.\n */\nexport function thin(drawing: SeriesDrawing, toPixel: (position: number) => number, pixels: number): ThinnedDrawing {\n const points = drawing.lines.reduce((sum, l) => sum + l.length, 0);\n if (points <= pixels) {\n return Object.freeze({ drawing, thinned: Object.freeze([]) });\n }\n const summaries: PixelSummary[] = [];\n const isSteps = drawing.lines.length > 0 && drawing.lines.every(l => l.length === 2 && elementAt(l, 0).y === elementAt(l, 1).y);\n const lines = isSteps ? stepLevels(drawing.lines, toPixel, summaries) : drawing.lines.map(l => line(l, toPixel, summaries));\n // Past one point a pixel, a marker stands for no one point: markers go, the shape stays.\n return Object.freeze({\n drawing: seriesDrawing(lines, []),\n thinned: Object.freeze(summaries),\n });\n}\n\n/**\n * What each pixel holds when the points were thinned before they came (ADR-0344): a pixel the drawing thinned\n * again counts every row the source's pixels inside it held, and a source pixel the drawing left alone says\n * what it held. A source pixel whose kept points fall in two of the drawing's pixels joins them into one.\n */\nexport function thinnedThrough(source: readonly PixelSummary[], drawn: readonly PixelSummary[], kept: readonly number[]): readonly PixelSummary[] {\n if (source.length === 0) {\n return drawn;\n }\n // Every summary, in order across; overlapping ones are one region, swept once.\n const all = [...source.map(p => ({ pixel: p, source: true })), ...drawn.map(p => ({ pixel: p, source: false }))]\n .toSorted((a, b) => (a.pixel.from === b.pixel.from ? a.pixel.to - b.pixel.to : a.pixel.from - b.pixel.from));\n const points = kept.toSorted((a, b) => a - b);\n const result: PixelSummary[] = [];\n let next = 0;\n let i = 0;\n while (i < all.length) {\n const head = elementAt(all, i).pixel;\n const from = head.from;\n let { to, min, max } = head;\n const sources: PixelSummary[] = [];\n for (; i < all.length && elementAt(all, i).pixel.from <= to; i++) {\n const entry = elementAt(all, i);\n const p = entry.pixel;\n to = Math.max(to, p.to);\n min = Math.min(min, p.min);\n max = Math.max(max, p.max);\n if (entry.source) {\n sources.push(p);\n }\n }\n // A source pixel stands for its rows; a point kept outside every one stands for itself.\n let count = sources.reduce((sum, p) => sum + p.count, 0);\n let s = 0;\n for (; next < points.length && elementAt(points, next) <= to; next++) {\n const x = elementAt(points, next);\n if (x < from) {\n continue;\n }\n while (s < sources.length && elementAt(sources, s).to < x) {\n s++;\n }\n if (s === sources.length || x < elementAt(sources, s).from) {\n count++;\n }\n }\n result.push(summary(from, to, min, max, Math.min(count, 2_147_483_647)));\n }\n return Object.freeze(result);\n}\n\nfunction line(points: readonly DrawnPoint[], toPixel: (position: number) => number, summaries: PixelSummary[]): readonly DrawnPoint[] {\n const kept: DrawnPoint[] = [];\n let i = 0;\n while (i < points.length) {\n const column = Math.floor(toPixel(elementAt(points, i).x));\n let j = i;\n while (j + 1 < points.length && Math.floor(toPixel(elementAt(points, j + 1).x)) === column) {\n j++;\n }\n if (j === i) {\n kept.push(elementAt(points, i));\n i++;\n continue;\n }\n let lo = i;\n let hi = i;\n for (let k = i; k <= j; k++) {\n if (elementAt(points, k).y < elementAt(points, lo).y) {\n lo = k;\n }\n if (elementAt(points, k).y > elementAt(points, hi).y) {\n hi = k;\n }\n }\n for (const k of [...new Set([i, lo, hi, j])].toSorted((a, b) => a - b)) {\n kept.push(elementAt(points, k));\n }\n summaries.push(summary(elementAt(points, i).x, elementAt(points, j).x, elementAt(points, lo).y, elementAt(points, hi).y, j - i + 1));\n i = j + 1;\n }\n return Object.freeze(kept);\n}\n\n// A step thinned by its levels: each pixel column draws its lowest and its highest level across the column,\n// so no end is drawn at a level the function does not take there.\nfunction stepLevels(levels: readonly (readonly DrawnPoint[])[], toPixel: (position: number) => number, summaries: PixelSummary[]): (readonly DrawnPoint[])[] {\n const groups = new Map<number, (readonly DrawnPoint[])[]>();\n for (const l of levels) {\n const key = Math.floor(toPixel((elementAt(l, 0).x + elementAt(l, 1).x) / 2));\n const group = groups.get(key);\n if (group === undefined) {\n groups.set(key, [l]);\n } else {\n group.push(l);\n }\n }\n const result: (readonly DrawnPoint[])[] = [];\n for (const g of groups.values()) {\n if (g.length === 1) {\n result.push(elementAt(g, 0));\n continue;\n }\n const a = least(g.map(l => elementAt(l, 0).x));\n const b = greatest(g.map(l => elementAt(l, 1).x));\n const min = least(g.map(l => elementAt(l, 0).y));\n const max = greatest(g.map(l => elementAt(l, 0).y));\n result.push(Object.freeze([point(a, min), point(b, min)]));\n if (max !== min) {\n result.push(Object.freeze([point(a, max), point(b, max)]));\n }\n summaries.push(summary(a, b, min, max, g.length));\n }\n return result;\n}\n\nconst point = (x: number, y: number): DrawnPoint => Object.freeze({ x, y });\n", "// A chart laid out in CSS pixels as immutable pieces (ADR-0252): panels stacked down the chart, the\n// horizontal axis under the last, and the Notes. The port of the C# engine's `ChartScene.Build`, held to it\n// by the shared cases under tests/cases/chart/ (ADR-0370).\nimport { appearanceOf } from './appearance';\nimport type { ChartDefinition } from './definition';\nimport { packedSessions } from './definition';\nimport { edgePixels, type DrawnEdge } from './edges';\nimport { grouped, upToPlaces } from './invariant-text';\nimport { resolveMetrics, type Box, type ChartMetrics, type ChartMetricsResolved, type ChartView } from './metrics';\nimport type {\n AppearanceKeys, AxisScale, AxisSide, CandlePeriod, ChartAxis, ChartSeries, PixelSummary, SeriesInterval, SeriesKind, SeriesLook,\n} from './model';\nimport { defined, elementAt, unreachable } from './must';\nimport { greatest, least, roundToDigits } from './numbers';\nimport { keyColumnWidth, keyGap, maxRadius, pointKeys, pointScaleNotes, type ColourKey, type SizeKey } from './point-scales';\nimport { candlePeriods, candlesOf, periodName, type DrawnCandle } from './price-ranges';\nimport { drawSeries, seriesDrawing, type Bounds, type DrawnMarker, type DrawnPoint, type DrawnWhisker, type SeriesDrawing } from './series-drawing';\nimport { thin, thinnedThrough } from './thinning';\nimport { decades, horizontalTicks, logSteps, nice, tenor, type AxisStyle } from './ticks';\nimport { axisWrites, toNumber, writePosition, writeValue } from './values';\n\n/** Where a panel's legend sits (ADR-0271). */\nexport type LegendPosition =\n /** Above each panel's plot. */\n | 'top'\n /** Below it; under the horizontal axis for the last panel. */\n | 'bottom'\n /** Left of the plots. */\n | 'left'\n /** Right of the plots. */\n | 'right'\n /** No legend. */\n | 'none';\n\n/** How a legend's entries align along its side (ADR-0271). */\nexport type LegendAlign = 'start' | 'centre' | 'end';\n\n/** The Consumer's placement of the legend: a side and an alignment, never a pixel offset (ADR-0271). */\nexport interface LegendPlacement {\n /** The side; `top` by default. */\n readonly position?: LegendPosition;\n /** The alignment; `start` by default. */\n readonly align?: LegendAlign;\n}\n\n/** One legend entry, laid out. */\nexport interface LegendEntry {\n /** The key a click hides it by: the series' identity, which for quotes and their Interpolated curve is the quotes' and hides both (ADR-0257). */\n readonly id: string;\n /** Its name. */\n readonly name: string;\n /** Its look, which hiding does not change. */\n readonly look: SeriesLook;\n /** Whether it is hidden, which fades the entry. */\n readonly hidden: boolean;\n /** Where the entry sits, swatch first. */\n readonly box: Box;\n}\n\n/** A tick of a vertical axis: its value, its height in pixels, and its label. */\nexport type VerticalTick = readonly [value: number, y: number, label: string];\n\n/** A vertical axis, laid out. */\nexport interface VerticalAxis {\n /** Which side it stands on. */\n readonly side: AxisSide;\n /** The value at the plot's foot. */\n readonly min: number;\n /** The value at its top. */\n readonly max: number;\n /** Its ticks. */\n readonly ticks: readonly VerticalTick[];\n /** Whether it does not reach zero, which a break mark at its foot says (ADR-0253). */\n readonly broken: boolean;\n /** Whether it is logarithmic, its `min` and `max` then both above zero (ADR-0290). */\n readonly logarithmic: boolean;\n}\n\n/** A Price Range's candle in pixels (ADR-0300). */\nexport interface PlacedCandle {\n /** Its centre across. */\n readonly x: number;\n /** Half its body's width. */\n readonly halfWidth: number;\n /** Its open's height, or `null` for a High-Low-Close bar. */\n readonly openY: number | null;\n /** Its high's height. */\n readonly highY: number;\n /** Its low's height. */\n readonly lowY: number;\n /** Its close's height. */\n readonly closeY: number;\n /** Its close above its own open, drawn hollow. */\n readonly rising: boolean;\n /** Its close equal to its own open. */\n readonly unchanged: boolean;\n /** How many rows it stands for. */\n readonly rows: number;\n /** The first position it stands for. */\n readonly from: number;\n /** The last. */\n readonly to: number;\n}\n\n/** A volume bar in pixels (ADR-0300). */\nexport interface PlacedVolume {\n /** Its centre across. */\n readonly x: number;\n /** Half its width. */\n readonly halfWidth: number;\n /** Its top's height. */\n readonly topY: number;\n /** Its base's height: zero's. */\n readonly baseY: number;\n /** Whether its candle rose. */\n readonly rising: boolean;\n /** Whether its candle was unchanged. */\n readonly unchanged: boolean;\n /** How many rows it stands for. */\n readonly rows: number;\n /** The first position it stands for. */\n readonly from: number;\n /** The last. */\n readonly to: number;\n}\n\n/** A marker of an Observation series as the pointer finds it (ADR-0290). */\nexport interface ChartMark {\n /** The series' identity. */\n readonly seriesId: string;\n /** The panel it stands in. */\n readonly panel: number;\n /** Its centre across, in pixels. */\n readonly x: number;\n /** Its centre down, in pixels. */\n readonly y: number;\n /** The index of the series' point it stands for, the first where it stands for more than one. */\n readonly point: number;\n /** How many of the series' points it stands for. */\n readonly count: number;\n}\n\n/** An edge as the pointer finds it (ADR-0321). */\nexport interface ChartEdgeMark {\n /** The series' identity. */\n readonly seriesId: string;\n /** The panel it is drawn in. */\n readonly panel: number;\n /** The edge as drawn, cut to the plot; its `index` names which of the series' edges it is. */\n readonly edge: DrawnEdge;\n}\n\n/** One series as the scene draws it: everything its component needs (ADR-0252). */\nexport interface SeriesPiece {\n /** The series' identity. */\n readonly id: string;\n /** Its name. */\n readonly name: string;\n /** The keys its look is chosen by (ADR-0256). */\n readonly keys: AppearanceKeys;\n /** The look they chose. */\n readonly look: SeriesLook;\n /** Its Series Kind. */\n readonly kind: SeriesKind;\n /** Whether it is the Consumer's interpolation (ADR-0257). */\n readonly interpolated: boolean;\n /** Its lines in pixels, each unbroken. */\n readonly lines: readonly (readonly DrawnPoint[])[];\n /** Its markers in pixels. */\n readonly markers: readonly DrawnMarker[];\n /** Its extrapolated ranges in pixels, drawn distinctly. */\n readonly extrapolated: readonly (readonly [from: number, to: number])[];\n /** What each thinned pixel holds (ADR-0254). */\n readonly thinned: readonly PixelSummary[];\n /** A Price Range's candles in pixels (ADR-0300). */\n readonly candles: readonly PlacedCandle[];\n /** The period its candles stand for: a row each, or the market period they were merged into (ADR-0302). */\n readonly period: CandlePeriod;\n /** A volume panel's bars in pixels (ADR-0300). */\n readonly volumes: readonly PlacedVolume[];\n /** Its Interval's whiskers in pixels (ADR-0303). */\n readonly whiskers: readonly DrawnWhisker[];\n /** Its Interval's bands in pixels, each a run of neighbours. */\n readonly bands: readonly (readonly DrawnWhisker[])[];\n /** What its Interval means, or `null` when it has none. */\n readonly intervalMeaning: string | null;\n /** Whether its markers' colour bands diverge from a centre (ADR-0320, ADR-0310). */\n readonly colourDiverging: boolean;\n /** Its edges in pixels, cut to the plot, drawn under its nodes (ADR-0321). */\n readonly edges: readonly DrawnEdge[];\n}\n\n/** A panel: its plot's box, its vertical axes and its series. */\nexport interface PanelScene {\n /** The panel's name. */\n readonly name: string;\n /** The plot's box. */\n readonly plot: Box;\n /** The left axis, or `null` when no series reads on it. */\n readonly left: VerticalAxis | null;\n /** The right axis, or `null`. */\n readonly right: VerticalAxis | null;\n /** The height of zero in pixels, where the plot holds it, or `null`. */\n readonly zeroY: number | null;\n /** The visible series, in the definition's order. */\n readonly series: readonly SeriesPiece[];\n /** Its legend: every series of the panel, hidden ones included (ADR-0271). */\n readonly legend: readonly LegendEntry[];\n /** The Price Range whose volume this panel draws, or `null` for a panel of the Consumer's (ADR-0300). */\n readonly volumeOf: string | null;\n}\n\n/** A tick of the horizontal axis: its position, its pixel, and its label or `null`. */\nexport type HorizontalTick = readonly [position: number, x: number, label: string | null];\n\n/** A position the pointer can be over, and its pixel. */\nexport type PointerPosition = readonly [position: number, x: number];\n\n/** A chart laid out in CSS pixels as immutable pieces (ADR-0252). */\nexport interface ChartScene {\n /** The panels, top to bottom. */\n readonly panels: readonly PanelScene[];\n /** The horizontal axis' ticks, each with its pixel position. */\n readonly xTicks: readonly HorizontalTick[];\n /** The first position shown. */\n readonly xFrom: number;\n /** The last. */\n readonly xTo: number;\n /** The lines said under the chart: the Consumer's Notes, each Segment's method, and what the scene itself must say. */\n readonly notes: readonly string[];\n /** The positions the pointer can be over, each with its pixel position, left to right (ADR-0255). */\n readonly positions: readonly PointerPosition[];\n /** Whether a visible series is an Observation: the pointer then finds the nearest mark (ADR-0290). */\n readonly scatter: boolean;\n /** The Observation series' marks, in drawing order (ADR-0290). */\n readonly marks: readonly ChartMark[];\n /** The edges drawn, which the pointer finds the nearest of where no mark is within reach (ADR-0321). */\n readonly edgeMarks: readonly ChartEdgeMark[];\n /** Whether the axis across is logarithmic as drawn (ADR-0290). */\n readonly logarithmicX: boolean;\n /** The colour bars of the visible series that take their colour from a column (ADR-0320). */\n readonly colourKeys: readonly ColourKey[];\n /** The size keys of the visible series that take their size from a column (ADR-0320). */\n readonly sizeKeys: readonly SizeKey[];\n /** The horizontal axis' title as drawn, with what the scene must add to it (ADR-0301, ADR-0302). */\n readonly xTitle: string;\n}\n\n/** What a scene is laid out with, beside the definition and the metrics. */\nexport interface SceneOptions {\n /** What the viewer narrowed the chart to; everything by default. */\n readonly view?: ChartView;\n /** How the horizontal axis is ticked and labelled. */\n readonly style?: AxisStyle;\n /** The panels whose left and right axes the Consumer declared independent (ADR-0251). */\n readonly independentScales?: ReadonlySet<string> | readonly string[];\n /** Where each panel's legend sits (ADR-0271); top, at the start, by default. */\n readonly legend?: LegendPlacement;\n}\n\n/** The height in pixels at which `value` stands on `plot`. */\nexport function yOf(axis: VerticalAxis, value: number, plot: Box): number {\n const share = axis.max === axis.min ? 0.5\n : axis.logarithmic ? Math.log(value / axis.min) / Math.log(axis.max / axis.min) : (value - axis.min) / (axis.max - axis.min);\n return plot.y + plot.height - share * plot.height;\n}\n\n/** The value that stands at height `y` on `plot`. */\nexport function valueAt(axis: VerticalAxis, y: number, plot: Box): number {\n const share = plot.height === 0 ? 0.5 : (plot.y + plot.height - y) / plot.height;\n return axis.logarithmic ? axis.min * (axis.max / axis.min) ** share : axis.min + share * (axis.max - axis.min);\n}\n\n/** The position across that stands at `x` pixels, on a proportional or logarithmic axis. */\nexport function positionAt(scene: ChartScene, x: number): number {\n const first = scene.panels[0];\n if (first === undefined) {\n return scene.xFrom;\n }\n const plot = first.plot;\n const share = plot.width === 0 ? 0.5 : (x - plot.x) / plot.width;\n return scene.logarithmicX ? scene.xFrom * (scene.xTo / scene.xFrom) ** share : scene.xFrom + share * (scene.xTo - scene.xFrom);\n}\n\n// A volume panel's height against a price panel's.\nconst volumeShare = 0.35;\n\n// A candle's body against the width it stands for.\nconst bodyShare = 0.7;\n\ntype Map1 = (position: number) => number;\n\n/** The axis as the viewer switched it, the visible series, the range shown, and the plot's span in pixels and device pixels. */\nexport interface Frame {\n readonly axis: ChartAxis;\n readonly visible: readonly ChartSeries[];\n readonly from: number;\n readonly to: number;\n readonly plotLeft: number;\n readonly plotWidth: number;\n readonly devicePixels: number;\n}\n\ninterface PanelSpec {\n readonly name: string;\n readonly volumeOf: ChartSeries | null;\n}\n\ninterface Merge {\n readonly candles: readonly DrawnCandle[];\n readonly period: CandlePeriod;\n}\n\ninterface AxisRange {\n readonly lo: number;\n readonly hi: number;\n readonly step: number;\n readonly zero: boolean;\n}\n\n/**\n * Lays `definition` out at `metrics`, narrowed by the options' view. `independentScales` lists the panels\n * whose left and right axes the Consumer declared independent (ADR-0251); `legend` says where each panel's\n * legend sits (ADR-0271).\n */\nexport function buildScene(definition: ChartDefinition, metrics: ChartMetrics, options: SceneOptions = {}): ChartScene {\n const { view = {}, style = {}, independentScales = [], legend = {} } = options;\n const { position: legendPosition = 'top', align: legendAlign = 'start' } = legend;\n const { hidden: hiddenKeys = [] } = view;\n const hidden = new Set<string>(hiddenKeys);\n const independentPanels = new Set<string>(independentScales);\n const m = resolveMetrics(metrics);\n const { looks, coloursRepeat } = appearanceOf(definition, m.colourSlots);\n const { axis, visible, from, to, plotLeft, plotWidth, devicePixels } = frame(definition, m, view, hidden, legendPosition);\n const legendKeys = legendKeysOf(definition.series);\n const categories = axis.effectiveScale === 'categories';\n const logX = axis.effectiveScale === 'logarithmic';\n const scatter = visible.some(s => s.kind === 'observation');\n const lh = m.lineHeight;\n const pad = m.padding;\n const notes: string[] = [...definition.notes];\n const lookOf = (s: ChartSeries): SeriesLook => defined(looks.get(s.id), `the look of '${s.id}'`);\n const keyOf = (s: ChartSeries): string => defined(legendKeys.get(s.id), `the legend key of '${s.id}'`);\n\n // What no longer matches is said, not ignored (ADR-0272).\n for (const key of [...hidden].filter(k => definition.series.every(s => s.id !== k)).toSorted(ordinal)) {\n notes.push(`\"${key}\" is hidden, but no series has that key.`);\n }\n // A scale asked for and not drawn is said by name (ADR-0290).\n const bounded = visible.find(s => lowBound(s.xInterval) !== undefined);\n if (view.scale === 'logarithmic' && !logX && axis.values === 'numbers' && bounded !== undefined && !visible.some(reachesZeroAcross)) {\n const low = defined(lowBound(bounded.xInterval), 'the low bound');\n const meaning = defined(bounded.xInterval, 'the horizontal interval').meaning;\n notes.push(`The axis across stays proportional: '${bounded.name}' has a bound of ${upToPlaces(low[1], 4)} in its ${meaning} at ${writePosition(axis, low[0])}, which a logarithmic axis cannot place.`);\n } else if (view.scale === 'logarithmic' && !logX) {\n notes.push(notLogarithmic(visible.find(s => reachesZeroAcross(s) || lowBound(s.xInterval) !== undefined), 'across', axis.values !== 'numbers'));\n }\n let logY = view.yScale === 'logarithmic';\n if (logY) {\n const refusal = logarithmicRefusal(visible, axis, from, to, devicePixels);\n if (refusal !== undefined) {\n notes.push(refusal);\n logY = false;\n }\n }\n\n // The horizontal map: proportional, or categories evenly spaced, centred in their slots.\n const slots = categorySlots(axis, from, to);\n const map: Map1 = categories\n ? x => {\n const i = slots.get(x);\n return i === undefined ? NaN : plotLeft + (i + 0.5) * plotWidth / Math.max(1, slots.size);\n }\n : logX ? x => plotLeft + (to === from ? 0.5 : Math.log(x / from) / Math.log(to / from)) * plotWidth\n : x => plotLeft + (to === from ? 0.5 : (x - from) / (to - from)) * plotWidth;\n\n const positions = positionsOf(visible, from, to, plotWidth, map, categories ? [...slots.keys()] : undefined);\n if (visible.length > 0 && positions.length === 0) {\n notes.push(`No series has a point between ${writePosition(axis, from)} and ${writePosition(axis, to)}.`);\n }\n\n const points = new Set(visible.flatMap(s => s.points.map(p => p.x)));\n // On packed sessions a date tick (a month's start) stands at the first session on or after it (ADR-0301).\n const sessions = categories && axis.values === 'dates' ? [...slots.keys()].toSorted(byNumber) : undefined;\n const tickMap: Map1 = sessions === undefined ? map : x => {\n const i = lowerBound(sessions, x);\n return i < sessions.length ? map(elementAt(sessions, i)) : NaN;\n };\n const xTicks = horizontalTicks(axis, style, from, to, points, tickMap, m.textWidth, lh);\n const ticksBand = xTicks.depth + lh / 2;\n\n // Every series' panel, hidden ones included, so a panel whose series are all hidden keeps its legend\n // and can show them again.\n const panelNames = [...new Set(definition.series.map(s => s.panel))];\n // A visible Price Range with a volume column gets a panel of its own below its panel (ADR-0300).\n const specs: PanelSpec[] = [];\n for (const name of panelNames) {\n specs.push({ name, volumeOf: null });\n for (const s of visible.filter(v => v.panel === name && v.kind === 'priceRange' && v.bars.some(b => b.volume !== undefined && b.volume !== null))) {\n specs.push({ name: `${s.name} volume`, volumeOf: s });\n }\n }\n const swatch = lh * 1.5;\n const entryWidth = (s: ChartSeries): number => swatch + pad / 2 + m.textWidth(legendName(s)) + pad;\n const rows = specs.map(spec => (spec.volumeOf === null && (legendPosition === 'top' || legendPosition === 'bottom')\n ? legendRows(legendSeries(definition.series, legendKeys, spec.name), entryWidth, plotWidth)\n : []));\n const band = (i: number): number => {\n const count = elementAt(rows, i).length;\n return count === 0 ? 0 : count * lh + pad / 2;\n };\n const weight = (spec: PanelSpec): number => (spec.volumeOf === null ? 1 : volumeShare);\n\n const bands = specs.reduce((sum, _, i) => sum + band(i), 0);\n const unit = specs.length === 0 ? 0\n : Math.max(1, (m.height - 2 * pad - ticksBand - bands - m.panelGap * (specs.length - 1)) / specs.reduce((sum, spec) => sum + weight(spec), 0));\n\n // Candles merged into the market's own periods where the plot is too narrow for each (ADR-0302).\n const merged = new Map<string, Merge>();\n for (const s of visible.filter(v => v.kind === 'priceRange')) {\n const { candles, period, unfit } = mergeCandles(s, from, to, devicePixels);\n merged.set(s.id, { candles, period });\n if (unfit !== undefined) {\n notes.push(unfit);\n } else if (period !== 'row') {\n notes.push(`${s.name}: ${periodName(period).toLowerCase()} candles, merged from rows${s.mergeTo === undefined ? ' to fit' : ''}.`);\n }\n }\n const mergedOf = (s: ChartSeries): Merge => defined(merged.get(s.id), `the candles of '${s.id}'`);\n // An interval's meaning, in the legend and here (ADR-0303).\n for (const s of visible) {\n if (s.interval !== undefined) {\n notes.push(`${s.name}: the ${s.xInterval === undefined ? '' : 'vertical '}interval is ${s.interval.meaning}.`);\n }\n }\n for (const s of visible) {\n if (s.xInterval !== undefined) {\n notes.push(`${s.name}: the horizontal interval is ${s.xInterval.meaning}.`);\n }\n }\n const rowWidth = rowWidthOf(visible, map, from, to, plotWidth);\n if (axis.packed) {\n notes.push('Dates are packed: the days nobody traded are left out, so the spacing is sessions, not calendar time.');\n }\n\n const visibleIds = new Set(visible.map(s => s.id));\n const panels: PanelScene[] = [];\n const marks: ChartMark[] = [];\n const edgeMarks: ChartEdgeMark[] = [];\n let y = pad;\n for (let pi = 0; pi < specs.length; pi++) {\n const spec = elementAt(specs, pi);\n const { name, volumeOf } = spec;\n const panelHeight = weight(spec) * unit;\n const last = pi === specs.length - 1;\n let plotY: number;\n let legendY: number;\n if (legendPosition === 'top') {\n legendY = y;\n plotY = y + band(pi);\n y = plotY + panelHeight;\n } else {\n plotY = y;\n legendY = plotY + panelHeight + (last ? ticksBand : pad / 2);\n y = plotY + panelHeight + band(pi);\n }\n y += m.panelGap;\n\n const plot: Box = Object.freeze({ x: plotLeft, y: plotY, width: plotWidth, height: panelHeight });\n if (volumeOf !== null) {\n panels.push(volumePanel(name, volumeOf, lookOf(volumeOf), mergedOf(volumeOf).candles, map, rowWidth, plot));\n continue;\n }\n const members = visible.filter(s => s.panel === name);\n const drawings = new Map(members.map(s => [s.id, s.kind === 'priceRange'\n ? seriesDrawing([], [], { candles: mergedOf(s).candles })\n : drawSeries(s, axis, { from, to, pixels: devicePixels, quotes: quotesOf(s, visible) })] as const));\n const drawingOf = (s: ChartSeries): SeriesDrawing => defined(drawings.get(s.id), `the drawing of '${s.id}'`);\n const { left, right, independent } = verticalAxes(members, drawingOf, from, to, plot, independentPanels.has(name), logY, view.yFrom, view.yTo);\n if (independent) {\n notes.push(panelNames.length > 1 && name.length > 0\n ? `${name}: the left and right axes put zero at different heights.`\n : 'The left and right axes put zero at different heights.');\n }\n const pieces = members.map(s => piece(s, lookOf(s), marked(s, visible), drawingOf(s),\n axisFor(s, left, right), map, plot, from, to, m.devicePixelRatio, devicePixels, rowWidth,\n maxRadius(lh), s.kind === 'priceRange' ? mergedOf(s).period : 'row'));\n if (scatter) {\n for (const p of pieces.filter(q => q.kind === 'observation')) {\n for (const mk of p.markers) {\n marks.push(Object.freeze({ seriesId: p.id, panel: pi, x: mk.x, y: mk.y, point: mk.point, count: mk.count }));\n }\n }\n }\n for (const p of pieces) {\n for (const e of p.edges) {\n edgeMarks.push(Object.freeze({ seriesId: p.id, panel: pi, edge: e }));\n }\n }\n const zero = left !== null && left.min <= 0 && left.max >= 0 ? yOf(left, 0, plot)\n : right !== null && right.min <= 0 && right.max >= 0 ? yOf(right, 0, plot) : null;\n const entries = legendOf(legendSeries(definition.series, legendKeys, name), elementAt(rows, pi), legendPosition, legendAlign, m, plot, legendY, lookOf,\n s => definition.series.filter(o => keyOf(o) === keyOf(s)).every(o => !visibleIds.has(o.id)),\n keyOf, entryWidth);\n panels.push(Object.freeze({ name, plot, left, right, zeroY: zero, series: Object.freeze(pieces), legend: entries, volumeOf: null }));\n }\n\n for (const s of visible) {\n for (const g of s.segments) {\n notes.push(`${s.name}: ${xLabel(axis, g.from)}\u2013${xLabel(axis, g.to)} ${g.method}${g.extrapolated === true ? ' (extrapolated)' : ''}`);\n }\n }\n for (const s of visible) {\n notes.push(...pointScaleNotes(s));\n }\n const plots = panels.filter(p => p.volumeOf === null);\n const firstPlot = plots[0];\n const lastPlot = plots[plots.length - 1];\n const [colourKeys, sizeKeys] = firstPlot === undefined || lastPlot === undefined ? [[], []] : pointKeys(visible,\n plotLeft + plotWidth + (visible.some(s => s.axis === 'right') ? yAxisWidth(m) : 0) + keyGap(m),\n firstPlot.plot.y, lastPlot.plot.y + lastPlot.plot.height - firstPlot.plot.y, m);\n if (coloursRepeat) {\n notes.push('Colours repeat: there are more series than colours. The legend and the tooltip name each series.');\n }\n\n return Object.freeze({\n panels: Object.freeze(panels),\n xTicks: Object.freeze(xTicks.ticks\n .map(t => Object.freeze([t.position, tickMap(t.position), t.label] as const))\n .filter(t => Number.isFinite(t[1]))),\n xFrom: from,\n xTo: to,\n notes: Object.freeze(notes),\n positions: Object.freeze(positions),\n scatter,\n marks: Object.freeze(marks),\n edgeMarks: Object.freeze(edgeMarks),\n logarithmicX: logX,\n colourKeys: Object.freeze(colourKeys),\n sizeKeys: Object.freeze(sizeKeys),\n xTitle: titleOf(axis, [...merged].map(([id, mg]) => [mg.period, defined(visible.find(s => s.id === id), id).mergeTo !== undefined] as const)),\n });\n}\n\n/**\n * The identities of the series the legend entry keyed `key` stands for (ADR-0257): the quotes and their\n * Interpolated curves for a pair's entry, otherwise the series itself. Showing the entry again shows each\n * of them, however one came to be hidden.\n */\nexport function legendMembers(definition: ChartDefinition, key: string): readonly string[] {\n const keys = legendKeysOf(definition.series);\n return Object.freeze(definition.series.filter(s => keys.get(s.id) === key).map(s => s.id));\n}\n\nconst ordinal = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\n// Doubles in .NET's order, which puts NaN first.\nfunction byNumber(a: number, b: number): number {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n if (a === b) {\n return 0;\n }\n return Number.isNaN(a) ? (Number.isNaN(b) ? 0 : -1) : 1;\n}\n\n// The first index whose value is at or after `x`, in a list in order.\nfunction lowerBound(list: readonly number[], x: number): number {\n let lo = 0;\n let hi = list.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (elementAt(list, mid) < x) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n return lo;\n}\n\n// A series a logarithmic axis across cannot place: a position at or below zero.\nfunction reachesZeroAcross(s: ChartSeries): boolean {\n return s.points.some(p => !(p.x > 0)) || (s.sampler !== undefined && s.sampler.from <= 0);\n}\n\nfunction notLogarithmic(s: ChartSeries | undefined, which: string, notNumbers: boolean): string {\n if (notNumbers) {\n return `The axis ${which} stays proportional: only numbers can be placed on a logarithmic axis.`;\n }\n // The C# engine names no series where none of the visible ones has such a value (a hidden one does),\n // and the shared cases hold the two engines to one sentence.\n const name = s === undefined ? '' : s.name;\n return `The axis ${which} stays proportional: '${name}' has a value at or below zero, which a logarithmic axis cannot place.`;\n}\n\n// A vertical log axis is refused, by name, by a series with a value at or below zero, or one that always\n// reaches zero (ADR-0290). A value is never dropped to make the axis fit.\nfunction logarithmicRefusal(visible: readonly ChartSeries[], axis: ChartAxis, from: number, to: number, devicePixels: number): string | undefined {\n for (const s of visible) {\n if (s.kind === 'amountPerPeriod') {\n return `The vertical axis stays proportional: '${s.name}' is an Amount per period, which is drawn from zero.`;\n }\n // A function is judged by the samples it would be drawn from, such as a fitted line that crosses\n // zero inside its range.\n if (s.sampler !== undefined) {\n const sample = drawSeries(s, axis, { from, to, pixels: devicePixels, quotes: quotesOf(s, visible) }).lines.flat().find(p => !(p.y > 0));\n if (sample !== undefined) {\n return `The vertical axis stays proportional: '${s.name}' reaches ${upToPlaces(sample.y, 4)} at ${writePosition(axis, sample.x)}, which a logarithmic axis cannot place.`;\n }\n } else {\n const point = s.points.find(p => p.y !== null && !(toNumber(p.y) > 0));\n if (point !== undefined && point.y !== null) {\n return `The vertical axis stays proportional: '${s.name}' has ${writeValue(s, point.y)} at ${writePosition(axis, point.x)}, which a logarithmic axis cannot place.`;\n }\n }\n const low = lowBound(s.interval);\n if (low !== undefined) {\n const meaning = defined(s.interval, 'the interval').meaning;\n return `The vertical axis stays proportional: '${s.name}' has a bound of ${upToPlaces(low[1], 4)} in its ${meaning} at ${writePosition(axis, low[0])}, which a logarithmic axis cannot place.`;\n }\n }\n return undefined;\n}\n\n/**\n * What both the scene and the files read (C#'s `ChartScene.Frame`): the frame of `definition` at `metrics`\n * narrowed by `view`, its plot as wide as with a legend above or below it, which is how the files take it.\n */\nexport function frameOf(definition: ChartDefinition, metrics: ChartMetrics, view: ChartView): Frame {\n const { hidden = [] } = view;\n // Only a legend at the left or the right narrows the plot; C#'s files pass none, which is the top's width.\n return frame(definition, resolveMetrics(metrics), view, new Set<string>(hidden), 'top');\n}\n\n// The axis as the viewer switched it, the visible series, the range shown, and the plot's span in pixels\n// and in device pixels.\nfunction frame(definition: ChartDefinition, m: ChartMetricsResolved, view: ChartView, hidden: ReadonlySet<string>, legend: LegendPosition): Frame {\n const axis = axisOf(definition, view);\n const keys = legendKeysOf(definition.series);\n const visible = definition.series.filter(s => !hidden.has(s.id) && !hidden.has(defined(keys.get(s.id), s.id)));\n const [from, to] = domain(axis, visible, view);\n const pad = m.padding;\n const column = (legend === 'left' || legend === 'right') && definition.series.length > 0\n ? greatest(definition.series.map(s => m.lineHeight * 1.5 + pad / 2 + m.textWidth(legendName(s)) + pad))\n : 0;\n const plotLeft = pad + (legend === 'left' ? column : 0) + yAxisWidth(m);\n const plotRight = m.width - pad - (legend === 'right' ? column : 0)\n - (visible.some(s => s.axis === 'right') ? yAxisWidth(m) : 0)\n - keyColumnWidth(visible, m);\n const plotWidth = Math.max(1, plotRight - plotLeft);\n return { axis, visible, from, to, plotLeft, plotWidth, devicePixels: Math.ceil(plotWidth * m.devicePixelRatio) };\n}\n\n// The axis with another scale, or another list of named positions.\nfunction rescaled(axis: ChartAxis, scale: AxisScale, named: ChartAxis['named'] = axis.named): ChartAxis {\n return Object.freeze({ ...axis, scale, effectiveScale: scale, named });\n}\n\n// The axis as the viewer switched it (ADR-0251). A Number or Date axis drawn as categories with no named\n// positions takes each position a series has, written as the axis writes it.\nfunction axisOf(d: ChartDefinition, view: ChartView): ChartAxis {\n let axis = d.axis;\n // A packed axis is the candles' positions as categories (ADR-0301).\n if (axis.packed && view.scale !== 'proportional') {\n return rescaled(axis, 'categories', Object.freeze(packedSessions(d.series).toSorted(byNumber)\n .map(x => Object.freeze([x, writePosition(d.axis, x)] as const))));\n }\n if (axis.packed) {\n axis = Object.freeze({ ...axis, packed: false });\n }\n const scale = view.scale;\n if (scale === undefined || scale === axis.effectiveScale || axis.values === 'labels') {\n return axis;\n }\n if (scale === 'categories' && d.series.some(s => s.sampler !== undefined || s.kind === 'observation')) {\n return axis;\n }\n if (scale === 'logarithmic' && (axis.values !== 'numbers'\n || d.series.some(s => reachesZeroAcross(s) || lowBound(s.xInterval) !== undefined))) {\n return axis;\n }\n if (scale === 'categories' && axis.named.length === 0) {\n const named = axis;\n return rescaled(axis, scale, Object.freeze([...new Set(d.series.flatMap(s => s.points.map(p => p.x)))].toSorted(byNumber)\n .map(x => Object.freeze([x, xLabel(named, x)] as const))));\n }\n return rescaled(axis, scale);\n}\n\n// The positions the pointer can be over: each point a visible series has in range, every slot of a\n// category axis, and for a sampled series one position per CSS pixel, which is as finely as the pointer\n// can tell them apart.\nfunction positionsOf(visible: readonly ChartSeries[], from: number, to: number, plotWidth: number, map: Map1, categories: readonly number[] | undefined): PointerPosition[] {\n const xs = categories === undefined\n ? new Set(visible.flatMap(s => s.points.map(p => p.x)).filter(x => x >= from && x <= to))\n : new Set(categories);\n if (categories === undefined) {\n for (const s of visible) {\n const f = s.sampler;\n if (f === undefined) {\n continue;\n }\n const n = Math.max(1, Math.ceil(plotWidth));\n for (let c = 0; c <= n; c++) {\n const x = to === from ? from : from + (to - from) * c / n;\n if (x >= f.from && x <= f.to) {\n xs.add(x);\n }\n }\n }\n }\n return [...xs].map(x => Object.freeze([x, map(x)] as const)).toSorted((a, b) => (byNumber(a[1], b[1]) === 0 ? byNumber(a[0], b[0]) : byNumber(a[1], b[1])));\n}\n\n// Top and bottom legends wrap their entries into rows the plot's width.\nfunction legendRows(series: readonly ChartSeries[], width: (s: ChartSeries) => number, plotWidth: number): ChartSeries[][] {\n const rows: ChartSeries[][] = [];\n let used = 0;\n for (const s of series) {\n const w = width(s);\n const current = rows[rows.length - 1];\n if (current === undefined || (used + w > plotWidth && current.length > 0)) {\n rows.push([s]);\n used = w;\n continue;\n }\n current.push(s);\n used += w;\n }\n return rows;\n}\n\nfunction legendOf(series: readonly ChartSeries[], rows: readonly (readonly ChartSeries[])[], position: LegendPosition, align: LegendAlign, m: ChartMetricsResolved,\n plot: Box, legendY: number, lookOf: (s: ChartSeries) => SeriesLook, hidden: (s: ChartSeries) => boolean, key: (s: ChartSeries) => string,\n width: (s: ChartSeries) => number): readonly LegendEntry[] {\n const lh = m.lineHeight;\n const pad = m.padding;\n const entries: LegendEntry[] = [];\n const entry = (s: ChartSeries, x: number, y: number): LegendEntry => Object.freeze({\n id: key(s), name: legendName(s), look: lookOf(s), hidden: hidden(s), box: Object.freeze({ x, y, width: width(s), height: lh }),\n });\n const offset = (space: number, used: number): number => {\n switch (align) {\n case 'centre':\n return (space - used) / 2;\n case 'end':\n return space - used;\n case 'start':\n return 0;\n default:\n return unreachable(align);\n }\n };\n switch (position) {\n case 'top':\n case 'bottom':\n rows.forEach((row, r) => {\n let x = plot.x + Math.max(0, offset(plot.width, row.reduce((sum, s) => sum + width(s), 0)));\n for (const s of row) {\n entries.push(entry(s, x, legendY + r * lh));\n x += width(s);\n }\n });\n break;\n case 'left':\n case 'right': {\n const column = series.length === 0 ? 0 : greatest(series.map(width));\n const x0 = position === 'left' ? pad : m.width - pad - column;\n let y = plot.y + Math.max(0, offset(plot.height, series.length * lh));\n for (const s of series) {\n entries.push(entry(s, x0, y));\n y += lh;\n }\n break;\n }\n case 'none':\n break;\n default:\n return unreachable(position);\n }\n return Object.freeze(entries);\n}\n\nconst yAxisWidth = (m: ChartMetricsResolved): number => m.textWidth('-0,000.00') + m.padding;\n\n// The categories in range, each with its slot: evenly spaced, in order.\nfunction categorySlots(axis: ChartAxis, from: number, to: number): Map<number, number> {\n const positions = axis.values === 'labels' ? axis.labels.map((_, i) => i) : axis.named.map(n => n[0]);\n const slots = new Map<number, number>();\n for (const x of positions.filter(p => p >= from && p <= to).toSorted(byNumber)) {\n if (slots.has(x)) {\n throw new Error(`Internal: the position ${String(x)} is named twice.`);\n }\n slots.set(x, slots.size);\n }\n return slots;\n}\n\nfunction domain(axis: ChartAxis, visible: readonly ChartSeries[], view: ChartView): readonly [from: number, to: number] {\n if (axis.effectiveScale === 'categories') {\n // Positions stay in their own units; only the map spaces them evenly.\n const [first, last] = axis.values === 'labels' ? [0, Math.max(0, axis.labels.length - 1)]\n : axis.named.length === 0 ? [0, 0] : [least(axis.named.map(n => n[0])), greatest(axis.named.map(n => n[0]))];\n return [view.from ?? first, view.to ?? last];\n }\n const xs = visible.flatMap(s => [\n ...s.points.map(p => p.x),\n ...(s.sampler === undefined ? [] : [s.sampler.from, s.sampler.to]),\n ...boundValues(s.xInterval),\n ]);\n const log = axis.effectiveScale === 'logarithmic';\n let lo = xs.length > 0 ? least(xs) : log ? 1 : 0;\n let hi = xs.length > 0 ? greatest(xs) : log ? 10 : 1;\n // A scatter's marks are not drawn on the plot's edge: its bounds are rounded out, to whole decades on\n // a logarithmic axis (ADR-0290).\n if (visible.some(s => s.kind === 'observation') && axis.values === 'numbers') {\n const n = nice(lo, hi, 6);\n [lo, hi] = log ? decades(lo, hi) : [n.min, n.max];\n }\n return [view.from ?? lo, view.to ?? hi];\n}\n\n// The key each series' legend entry hides it by, by its identity (ADR-0257): the quotes and the\n// Interpolated curves of one panel sharing a colour key are one entry, keyed by the quotes' identity, so no\n// key can name another series; any other series is its own. Two quote series of one colour key are not\n// guessed between: each keeps its entry, as its curves do (spine rule 1).\nfunction legendKeysOf(all: readonly ChartSeries[]): Map<string, string> {\n const keys = new Map(all.map(s => [s.id, s.id] as const));\n const groups = new Map<string, ChartSeries[]>();\n for (const s of all) {\n // The panel and the colour key, joined by a character neither can hold unseen.\n const group = JSON.stringify([s.panel, s.effectiveKeys.colour]);\n const members = groups.get(group);\n if (members === undefined) {\n groups.set(group, [s]);\n } else {\n members.push(s);\n }\n }\n for (const shared of groups.values()) {\n const quotes = shared.filter(s => !s.interpolated);\n const only = quotes[0];\n if (shared.some(s => s.interpolated) && quotes.length === 1 && only !== undefined) {\n for (const s of shared) {\n keys.set(s.id, only.id);\n }\n }\n }\n return keys;\n}\n\n// The series a panel's legend has an entry for: one per legend key, the quotes standing for a pair.\nfunction legendSeries(all: readonly ChartSeries[], keys: ReadonlyMap<string, string>, panel: string): ChartSeries[] {\n const order: string[] = [];\n for (const s of all) {\n const key = defined(keys.get(s.id), s.id);\n if (s.panel === panel && !order.includes(key)) {\n order.push(key);\n }\n }\n return order.map(key => defined(all.find(s => s.panel === panel && s.id === key), `the series '${key}'`));\n}\n\n/** The quotes an Interpolated series is paired with: the positions of the series that share its colour key. */\nexport function quotesOf(s: ChartSeries, visible: readonly ChartSeries[]): number[] {\n return s.sampler === undefined ? []\n : visible.filter(o => o.id !== s.id && !o.interpolated && o.effectiveKeys.colour === s.effectiveKeys.colour).flatMap(o => o.points.map(p => p.x));\n}\n\nfunction verticalAxes(members: readonly ChartSeries[], drawingOf: (s: ChartSeries) => SeriesDrawing, from: number, to: number, plot: Box,\n declaredIndependent: boolean, logarithmic: boolean, yFrom: number | undefined, yTo: number | undefined):\n { left: VerticalAxis | null; right: VerticalAxis | null; independent: boolean } {\n const inRange = (x: number): boolean => x >= from && x <= to;\n const range = (side: AxisSide): AxisRange | undefined => {\n const ss = members.filter(s => s.axis === side);\n if (ss.length === 0) {\n return undefined;\n }\n const ys = ss.flatMap(s => {\n const d = drawingOf(s);\n return [\n ...d.lines.flat().filter(p => inRange(p.x)).map(p => p.y),\n ...d.markers.filter(mk => inRange(mk.x)).flatMap(mk => (mk.yBounds === undefined ? [mk.y] : [mk.y, mk.yBounds[0], mk.yBounds[1]])),\n ...d.candles.flatMap(c => [c.low, c.high]),\n ...[...d.whiskers, ...d.bands.flat()].filter(w => inRange(w.x)).flatMap(w => [w.lower, w.upper]),\n ];\n });\n let lo = ys.length > 0 ? least(ys) : logarithmic ? 1 : 0;\n let hi = ys.length > 0 ? greatest(ys) : logarithmic ? 10 : 1;\n // The left axis narrowed by a rectangle shows what was asked, unrounded (ADR-0290).\n const narrowed = side === 'left' && (yFrom !== undefined || yTo !== undefined);\n if (narrowed) {\n lo = yFrom ?? lo;\n hi = yTo ?? hi;\n }\n if (logarithmic) {\n const [dlo, dhi] = narrowed && lo > 0 && hi > lo ? [lo, hi] : decades(lo, hi);\n return { lo: dlo, hi: dhi, step: 0, zero: false };\n }\n if (narrowed && hi > lo) {\n return { lo, hi, step: nice(lo, hi).step, zero: lo <= 0 && hi >= 0 };\n }\n if (ss.some(s => s.reachesZero)) {\n lo = Math.min(lo, 0);\n hi = Math.max(hi, 0);\n }\n const n = nice(lo, hi);\n return { lo: n.min, hi: n.max, step: n.step, zero: n.min <= 0 && n.max >= 0 };\n };\n let l = range('left');\n let r = range('right');\n // A logarithmic axis has no zero to align (ADR-0290).\n if (logarithmic) {\n return {\n left: l === undefined ? null : logAxis('left', l.lo, l.hi, plot),\n right: r === undefined ? null : logAxis('right', r.lo, r.hi, plot),\n independent: false,\n };\n }\n let independent = false;\n if (l !== undefined && r !== undefined) {\n if (declaredIndependent || !l.zero || !r.zero) {\n independent = true;\n } else {\n // Zero at the same height on both sides (ADR-0251): each axis is stretched until its share\n // below zero is the larger of the two.\n const share = Math.max(below(l.lo, l.hi), below(r.lo, r.hi));\n l = stretch(l, share);\n r = stretch(r, share);\n }\n }\n return {\n left: l === undefined ? null : linearAxis('left', l, plot),\n right: r === undefined ? null : linearAxis('right', r, plot),\n independent,\n };\n}\n\n// The axis a series reads on, which `verticalAxes` laid out because the series is there.\nfunction axisFor(s: ChartSeries, left: VerticalAxis | null, right: VerticalAxis | null): VerticalAxis {\n const axis = s.axis === 'right' ? right : left;\n if (axis === null) {\n throw new Error(`Internal: '${s.id}' reads on the ${s.axis} axis, which was not laid out.`);\n }\n return axis;\n}\n\nconst below = (lo: number, hi: number): number => (hi === lo ? 0 : -lo / (hi - lo));\n\nfunction stretch(a: AxisRange, share: number): AxisRange {\n if (share >= 1) {\n return { lo: Math.min(a.lo, -a.step), hi: 0, step: a.step, zero: true };\n }\n if (below(a.lo, a.hi) < share) {\n return { lo: -share * a.hi / (1 - share), hi: a.hi, step: a.step, zero: true };\n }\n if (below(a.lo, a.hi) > share) {\n return { lo: a.lo, hi: -a.lo * (1 - share) / share, step: a.step, zero: true };\n }\n return a;\n}\n\nfunction linearAxis(side: AxisSide, a: AxisRange, plot: Box): VerticalAxis {\n const bare: VerticalAxis = { side, min: a.lo, max: a.hi, ticks: [], broken: !a.zero, logarithmic: false };\n const first = Math.ceil(a.lo / a.step - 1e-9) * a.step;\n const ticks: VerticalTick[] = [];\n for (let t = first; t <= a.hi + a.step * 1e-9; t += a.step) {\n // Never \"-0\".\n const value = roundToDigits(t, 12) + 0;\n ticks.push(Object.freeze([value, yOf(bare, value, plot), upToPlaces(value, 4)] as const));\n }\n return Object.freeze({ ...bare, ticks: Object.freeze(ticks) });\n}\n\nfunction logAxis(side: AxisSide, lo: number, hi: number, plot: Box): VerticalAxis {\n const bare: VerticalAxis = { side, min: lo, max: hi, ticks: [], broken: false, logarithmic: true };\n const ticks = logSteps(lo, hi).map(t => Object.freeze([t, yOf(bare, t, plot), upToPlaces(t, 4)] as const));\n return Object.freeze({ ...bare, ticks: Object.freeze(ticks) });\n}\n\n// A level's points are marked when its marker key asks for it, or when they are the quotes an\n// Interpolated series is drawn through, which the markers tell apart from the curve (ADR-0257). A step's\n// ends are always marked: filled and open say which end takes the value (ADR-0253).\nfunction marked(s: ChartSeries, visible: readonly ChartSeries[]): boolean {\n return s.kind !== 'level' || s.keys?.marker !== undefined || s.interpolated\n || visible.some(o => o.id !== s.id && o.interpolated && o.effectiveKeys.colour === s.effectiveKeys.colour);\n}\n\ninterface PieceParts {\n readonly lines?: readonly (readonly DrawnPoint[])[];\n readonly markers?: readonly DrawnMarker[];\n readonly extrapolated?: readonly (readonly [number, number])[];\n readonly thinned?: readonly PixelSummary[];\n readonly candles?: readonly PlacedCandle[];\n readonly period?: CandlePeriod;\n readonly volumes?: readonly PlacedVolume[];\n readonly whiskers?: readonly DrawnWhisker[];\n readonly bands?: readonly (readonly DrawnWhisker[])[];\n readonly intervalMeaning?: string | null;\n readonly colourDiverging?: boolean;\n readonly edges?: readonly DrawnEdge[];\n}\n\nfunction pieceOf(s: ChartSeries, look: SeriesLook, name: string, interpolated: boolean, parts: PieceParts): SeriesPiece {\n const {\n lines = [], markers = [], extrapolated = [], thinned = [], candles = [], period = 'row', volumes = [], whiskers = [], bands = [],\n intervalMeaning = null, colourDiverging = false, edges = [],\n } = parts;\n return Object.freeze({\n id: s.id, name, keys: s.effectiveKeys, look, kind: s.kind, interpolated,\n lines: Object.freeze(lines), markers: Object.freeze(markers), extrapolated: Object.freeze(extrapolated), thinned: Object.freeze(thinned),\n candles: Object.freeze(candles), period, volumes: Object.freeze(volumes), whiskers: Object.freeze(whiskers), bands: Object.freeze(bands),\n intervalMeaning, colourDiverging, edges: Object.freeze(edges),\n });\n}\n\nfunction piece(s: ChartSeries, look: SeriesLook, isMarked: boolean, drawing: SeriesDrawing, axis: VerticalAxis, map: Map1, plot: Box, from: number, to: number,\n dpr: number, devicePixels: number, rowWidth: number, radius: number, period: CandlePeriod): SeriesPiece {\n const y = (v: number): number => yOf(axis, v, plot);\n if (s.kind === 'priceRange') {\n return pieceOf(s, look, s.name, s.interpolated, {\n period,\n candles: drawing.candles.map(c => {\n const [x, half] = extent(c, map, rowWidth);\n return Object.freeze({\n x, halfWidth: half, openY: c.open === null ? null : y(c.open), highY: y(c.high), lowY: y(c.low), closeY: y(c.close),\n rising: c.rising, unchanged: c.unchanged, rows: c.rows, from: c.from, to: c.to,\n });\n }),\n });\n }\n\n const inX = (x: number): boolean => x >= from && x <= to;\n // What the axis does not show is not drawn: a mark outside it is left out, and a line is cut at its\n // edge (a rectangle narrows the left axis, ADR-0290).\n const reach = Math.abs(axis.max - axis.min) * 1e-9;\n const shown = (v: number): boolean => v >= axis.min - reach && v <= axis.max + reach;\n const inRange = seriesDrawing(\n drawing.lines.map(l => l.filter(p => inX(p.x))).filter(l => l.length > 1).flatMap(l => clipLine(l, axis.min, axis.max, axis.logarithmic)),\n drawing.markers.filter(mk => inX(mk.x) && shown(mk.y)));\n if (s.kind === 'observation') {\n const clampY = (v: number): number => y(Math.min(Math.max(v, axis.min), axis.max));\n const clampX = (v: number): number => map(Math.min(Math.max(v, from), to));\n return pieceOf(s, look, s.name, s.interpolated, {\n markers: mergedMarks(inRange.markers.map(mk => Object.freeze({\n ...mk,\n x: map(mk.x),\n y: y(mk.y),\n // A whisker stops at the plot's edge when the range is narrowed past it (ADR-0304).\n ...(mk.yBounds === undefined ? {} : { yBounds: ordered(clampY(mk.yBounds[0]), clampY(mk.yBounds[1])) }),\n ...(mk.xBounds === undefined ? {} : { xBounds: ordered(clampX(mk.xBounds[0]), clampX(mk.xBounds[1])) }),\n ...(mk.radius === undefined ? {} : { radius: Math.max(0.75, mk.radius * radius) }),\n })), dpr),\n colourDiverging: s.colourBy?.centre !== undefined,\n edges: edgePixels(s, map, y, plot),\n });\n }\n const toPixel = (x: number): number => (map(x) - plot.x) * dpr;\n const thinned = thin(inRange, toPixel, devicePixels);\n const [whiskers, bands] = intervals(\n drawing.whiskers.filter(w => inX(w.x)),\n drawing.bands.map(b => b.filter(w => inX(w.x))).filter(b => b.length > 0),\n toPixel, devicePixels);\n const px = (p: DrawnPoint): DrawnPoint => Object.freeze({ x: map(p.x), y: y(p.y) });\n const wpx = (w: DrawnWhisker): DrawnWhisker => Object.freeze({ x: map(w.x), lower: y(w.lower), upper: y(w.upper) });\n return pieceOf(s, look, s.name, s.interpolated, {\n lines: thinned.drawing.lines.map(l => Object.freeze(l.map(px))),\n markers: (isMarked ? thinned.drawing.markers : []).map(mk => Object.freeze({ ...mk, x: map(mk.x), y: y(mk.y) })),\n extrapolated: s.segments.filter(g => g.extrapolated === true).map(g => Object.freeze([map(Math.max(g.from, from)), map(Math.min(g.to, to))] as const)),\n thinned: thinnedThrough(s.thinned.filter(t => t.to >= from && t.from <= to), thinned.thinned, inRange.lines.flatMap(l => l.map(p => p.x))),\n whiskers: whiskers.map(wpx),\n bands: bands.map(b => Object.freeze(b.map(wpx))),\n intervalMeaning: s.interval === undefined ? null : s.interval.meaning,\n });\n}\n\n// Past one point a device pixel, whiskers become the band, thinned to the lowest lower and the highest upper\n// per pixel column, so no interval is dropped where markers are (ADR-0303).\nfunction intervals(inWhiskers: readonly DrawnWhisker[], inBands: readonly (readonly DrawnWhisker[])[], toPixel: Map1, devicePixels: number):\n readonly [whiskers: readonly DrawnWhisker[], bands: readonly (readonly DrawnWhisker[])[]] {\n let whiskers = inWhiskers;\n let bands = inBands;\n if (whiskers.length > devicePixels) {\n bands = [whiskers];\n whiskers = [];\n }\n if (bands.reduce((sum, b) => sum + b.length, 0) <= devicePixels) {\n return [whiskers, bands];\n }\n return [whiskers, bands.map(b => {\n const columns = new Map<number, DrawnWhisker[]>();\n for (const w of b) {\n const column = Math.floor(toPixel(w.x));\n const group = columns.get(column);\n if (group === undefined) {\n columns.set(column, [w]);\n } else {\n group.push(w);\n }\n }\n return [...columns.values()].map(g => Object.freeze({\n x: (elementAt(g, 0).x + elementAt(g, g.length - 1).x) / 2,\n lower: least(g.map(w => w.lower)),\n upper: greatest(g.map(w => w.upper)),\n }));\n })];\n}\n\n// A candle centred on what it stands for, 70% as wide: one row's width, or a merged candle's rows from first\n// to last (ADR-0302).\nfunction extent(c: DrawnCandle, map: Map1, rowWidth: number): readonly [x: number, half: number] {\n const a = map(c.from) - rowWidth / 2;\n const b = map(c.to) + rowWidth / 2;\n return [(a + b) / 2, Math.max(0.5, bodyShare / 2 * (b - a))];\n}\n\n// The width of one row in pixels: the narrowest gap between neighbouring candles.\nfunction rowWidthOf(visible: readonly ChartSeries[], map: Map1, from: number, to: number, plotWidth: number): number {\n const xs = [...new Set(visible.filter(s => s.kind === 'priceRange').flatMap(s => s.bars.map(b => b.x)).filter(x => x >= from && x <= to))].toSorted(byNumber);\n if (xs.length < 2) {\n return plotWidth / 10;\n }\n let gap = Infinity;\n for (let i = 1; i < xs.length; i++) {\n gap = Math.min(gap, map(elementAt(xs, i)) - map(elementAt(xs, i - 1)));\n }\n return Number.isFinite(gap) && gap > 0 ? gap : plotWidth / xs.length;\n}\n\n// The first of the market's periods whose candles fit three device pixels each, or the Consumer's fixed\n// one, which says so when it does not fit (ADR-0302).\nfunction mergeCandles(s: ChartSeries, from: number, to: number, devicePixels: number): { candles: readonly DrawnCandle[]; period: CandlePeriod; unfit: string | undefined } {\n const fits = (count: number): boolean => count <= 1 || count * 3 <= devicePixels;\n if (s.mergeTo !== undefined) {\n const fixed = s.mergeTo;\n const candles = candlesOf(s, from, to, fixed);\n return fits(candles.length) ? { candles, period: fixed, unfit: undefined }\n : {\n candles: [], period: fixed,\n unfit: `${s.name}: ${grouped(candles.length)} ${fixed === 'row' ? 'rows' : `${periodName(fixed).toLowerCase()} candles`} do not fit; narrow the range.`,\n };\n }\n let count = 0;\n for (const period of candlePeriods) {\n const candles = candlesOf(s, from, to, period);\n if (fits(candles.length)) {\n return { candles, period, unfit: undefined };\n }\n count = candles.length;\n }\n // Not even years fit: nothing is drawn in slivers, and the chart says so (ADR-0302).\n return { candles: [], period: 'year', unfit: `${s.name}: ${grouped(count)} yearly candles do not fit; narrow the range or widen the chart.` };\n}\n\nfunction volumePanel(name: string, s: ChartSeries, look: SeriesLook, candles: readonly DrawnCandle[], map: Map1, rowWidth: number, plot: Box): PanelScene {\n // A candle with no volume raises no bar, so it does not raise the axis either.\n const max = candles.length === 0 ? 1 : candles.reduce((most, c) => (c.volume === null ? most : Math.max(most, c.volume)), 0);\n const n = nice(0, max === 0 ? 1 : max);\n const axis = linearAxis('left', { lo: n.min, hi: n.max, step: n.step, zero: true }, plot);\n const volumes = candles.flatMap(c => {\n if (c.volume === null) {\n return [];\n }\n const [x, half] = extent(c, map, rowWidth);\n return [Object.freeze({\n x, halfWidth: half, topY: yOf(axis, c.volume, plot), baseY: yOf(axis, 0, plot), rising: c.rising, unchanged: c.unchanged, rows: c.rows, from: c.from, to: c.to,\n })];\n });\n const p = pieceOf(s, look, name, false, { volumes });\n return Object.freeze({\n name, plot, left: axis, right: null, zeroY: yOf(axis, 0, plot), series: Object.freeze([p]), legend: Object.freeze([]), volumeOf: s.id,\n });\n}\n\nfunction titleOf(axis: ChartAxis, periods: readonly (readonly [period: CandlePeriod, fixed: boolean])[]): string {\n let title = axis.title.length > 0 ? axis.title : axis.packed ? 'Trading days' : periods.some(p => p[0] !== 'row') ? 'Date' : '';\n if (axis.packed) {\n title += ' (closed days packed)';\n }\n const distinct = [...new Map(periods.filter(p => p[0] !== 'row').map(p => [`${p[0]}|${String(p[1])}`, p] as const)).values()];\n const only = distinct[0];\n if (distinct.length === 1 && only !== undefined) {\n title += ` \u00B7 ${periodName(only[0])} (merged from rows${only[1] ? '' : ' to fit'})`;\n }\n return title;\n}\n\n// A series' name in its legend, with its interval's meaning (ADR-0303).\nfunction legendName(s: ChartSeries): string {\n const y = s.interval?.meaning;\n const x = s.xInterval?.meaning;\n if (y === undefined) {\n return x === undefined ? s.name : `${s.name} (x: ${x})`;\n }\n if (x === undefined || x === y) {\n return `${s.name} (${y})`;\n }\n return `${s.name} (y: ${y}; x: ${x})`;\n}\n\n// The bounds a series hands in, with values (ADR-0303, ADR-0304).\nfunction boundValues(interval: SeriesInterval | undefined): number[] {\n return interval === undefined ? [] : interval.bounds.flatMap(b => [b.lower, b.upper].flatMap(v => (v === null ? [] : [toNumber(v)])));\n}\n\n// A bound a logarithmic axis cannot place: one at or below zero (ADR-0304).\nfunction lowBound(interval: SeriesInterval | undefined): readonly [x: number, bound: number] | undefined {\n if (interval === undefined) {\n return undefined;\n }\n for (const b of interval.bounds) {\n for (const v of [b.lower, b.upper]) {\n if (v !== null && !(toNumber(v) > 0)) {\n return [b.x, toNumber(v)];\n }\n }\n }\n return undefined;\n}\n\nconst ordered = (a: number, b: number): Bounds => Object.freeze([Math.min(a, b), Math.max(a, b)] as const);\n\n// Merged marks carry the union of their intervals, so none is dropped (ADR-0304).\nfunction union(a: Bounds | undefined, b: Bounds | undefined): Bounds | undefined {\n if (a === undefined) {\n return b;\n }\n return b === undefined ? a : Object.freeze([Math.min(a[0], b[0]), Math.max(a[1], b[1])] as const);\n}\n\n// Past the pixels, an Observation's marks centred on one device pixel are one mark, which says how many it\n// stands for (ADR-0290). The first point drawn there names it.\nfunction mergedMarks(marks: readonly DrawnMarker[], dpr: number): DrawnMarker[] {\n const at = new Map<string, number>();\n const kept: DrawnMarker[] = [];\n for (const mk of marks) {\n // Marks merge only where they look alike, so no colour or size is lost to a merge (ADR-0320).\n const cell = JSON.stringify([Math.floor(mk.x * dpr), Math.floor(mk.y * dpr), mk.band === undefined ? null : mk.band, mk.radius === undefined ? null : mk.radius, mk.filled]);\n const i = at.get(cell);\n if (i === undefined) {\n at.set(cell, kept.length);\n kept.push(mk);\n continue;\n }\n const k = elementAt(kept, i);\n const yBounds = union(k.yBounds, mk.yBounds);\n const xBounds = union(k.xBounds, mk.xBounds);\n kept[i] = Object.freeze({\n ...k,\n count: k.count + mk.count,\n ...(yBounds === undefined ? {} : { yBounds }),\n ...(xBounds === undefined ? {} : { xBounds }),\n });\n }\n return kept;\n}\n\n// A line cut where it leaves [lo, hi], each piece ending on the edge it crosses. On a logarithmic axis the\n// segment is straight in the logarithm, so the crossing is found there.\nfunction clipLine(line: readonly DrawnPoint[], lo: number, hi: number, logarithmic: boolean): (readonly DrawnPoint[])[] {\n const inside = (p: DrawnPoint): boolean => p.y >= lo && p.y <= hi;\n if (line.every(inside)) {\n return [line];\n }\n const t = (v: number): number => (logarithmic ? Math.log(v) : v);\n const cross = (a: DrawnPoint, b: DrawnPoint, edge: number): DrawnPoint =>\n Object.freeze({ x: a.x + (b.x - a.x) * (t(edge) - t(a.y)) / (t(b.y) - t(a.y)), y: edge });\n const pieces: (readonly DrawnPoint[])[] = [];\n let current: DrawnPoint[] = [];\n line.forEach((p, i) => {\n const pIn = inside(p);\n const q = line[i - 1];\n if (q !== undefined) {\n const qIn = inside(q);\n if (qIn && !pIn) {\n current.push(cross(q, p, p.y > hi ? hi : lo));\n } else if (!qIn && pIn) {\n current.push(cross(q, p, q.y > hi ? hi : lo));\n } else if ((q.y < lo && p.y > hi) || (q.y > hi && p.y < lo)) {\n current.push(cross(q, p, q.y > hi ? hi : lo));\n current.push(cross(q, p, q.y > hi ? lo : hi));\n }\n }\n if (pIn) {\n current.push(p);\n } else if (current.length > 0) {\n if (current.length > 1) {\n pieces.push(Object.freeze(current));\n }\n current = [];\n }\n });\n if (current.length > 1) {\n pieces.push(Object.freeze(current));\n }\n return pieces;\n}\n\nfunction xLabel(axis: ChartAxis, x: number): string {\n return !axisWrites(axis) && axis.values === 'numbers' && axis.named.every(n => n[0] !== x) ? tenor(x) : writePosition(axis, x);\n}\n", "// What the tooltip says (ADR-0270): every visible series of the pointer's panel read at the position under\n// the pointer, each by its own Series Kind, an Observation's mark (ADR-0290) and an edge (ADR-0321). A value\n// is only ever one the Consumer handed in or its sampler answered; nothing is read between two points. The\n// port of the C# engine's `ChartReadings`, held to it by the shared cases under tests/cases/chart/.\nimport type { ChartDefinition } from './definition';\nimport { resolveMetrics, type ChartMetrics } from './metrics';\nimport type { ChartAxis, ChartPoint, ChartSeries, ChartValue, SeriesInterval, SeriesLook, StepSide } from './model';\nimport { defined, elementAt } from './must';\nimport { firstBy } from './numbers';\nimport { candlesOf, hasOpen, percentChange, periodStart, wholeBar } from './price-ranges';\nimport { yOf, type ChartScene, type PanelScene, type SeriesPiece } from './scene';\nimport { segmentAt } from './series-drawing';\nimport { invariantText, toNumber, writeObject, writePosition, writeValue, yearsBetween } from './values';\n\n/** One series' line in the tooltip (ADR-0270). */\nexport interface ReadingLine {\n /** The series' identity. */\n readonly id: string;\n /** Its name. */\n readonly name: string;\n /** Its look, for the swatch. */\n readonly look: SeriesLook;\n /** Its value at the position, written through the series' format; `null` when it has none there. */\n readonly value: string | null;\n /** What the value is: a step's interval, a thinned pixel's count, interpolated or extrapolated, or why there is no value. */\n readonly note: string | null;\n /** The value's height in pixels, which the nearest lines are chosen by; `null` when it has none there. */\n readonly y: number | null;\n}\n\n/** What the tooltip says at one position in one panel, over a mark or over an edge (ADR-0270). */\nexport interface ChartReading {\n /** The position, written as the axis writes it, or what the mark or the edge is named by. */\n readonly position: string;\n /** The lines shown, top to bottom: the nearest to the pointer's height, as many as fit the plot. */\n readonly lines: readonly ReadingLine[];\n /** How many series are not listed, which the tooltip says as \"and M more series\"; never a silent cut. */\n readonly more: number;\n}\n\n/**\n * What the tooltip says at `position` in panel `panel` of `scene`, built from `definition` at `metrics`.\n * Past what fits the plot's height, the series nearest `pointerY` are listed and the rest counted. The\n * view is the scene's own: what it hides and the range it shows are already laid out in it.\n */\nexport function readingAt(definition: ChartDefinition, scene: ChartScene, metrics: ChartMetrics, position: number, panel: number,\n pointerY: number): ChartReading {\n const p = scene.panels[panel];\n if (p === undefined) {\n throw new RangeError(`The scene has no panel ${String(panel)}; it has ${String(scene.panels.length)}.`);\n }\n const axis = definition.axis;\n const byId = new Map(definition.series.map(s => [s.id, s] as const));\n const lines = p.series.map(piece => {\n const s = defined(byId.get(piece.id), `the series '${piece.id}'`);\n return s.kind === 'priceRange' ? candle(s, piece, p, scene, axis, position) : line(s, piece, p, axis, position);\n });\n\n // A header line, the lines, and the \"more\" line, all inside the plot's height.\n const room = Math.max(1, Math.floor(p.plot.height / resolveMetrics(metrics).lineHeight) - 2);\n const shown = lines.length <= room ? lines\n : lines.map((l, i) => ({ l, i, d: l.y === null ? Infinity : Math.abs(l.y - pointerY) }))\n .toSorted((a, b) => (a.d === b.d ? a.i - b.i : a.d < b.d ? -1 : 1)).slice(0, room).map(t => t.l);\n const ordered = shown.map(l => ({ l, i: lines.indexOf(l) }))\n .toSorted((a, b) => {\n const byHeight = heightOrder(a.l.y, b.l.y);\n return byHeight === 0 ? a.i - b.i : byHeight;\n }).map(t => t.l);\n return reading(writePosition(axis, position), ordered, lines.length - shown.length);\n}\n\n/**\n * What the tooltip says over an Observation's mark (ADR-0290): the point's name, or its position across,\n * then the series with the point's x and y, and how many points the mark stands for when markers on one\n * device pixel were merged \u2014 never one of them as if it were the only one.\n */\nexport function readingOfMark(definition: ChartDefinition, scene: ChartScene, mark: number): ChartReading {\n const m = scene.marks[mark];\n if (m === undefined) {\n throw new RangeError(`The scene has no mark ${String(mark)}; it has ${String(scene.marks.length)}.`);\n }\n const s = seriesOf(definition, m.seriesId);\n const look = lookOf(scene, m.panel, s.id);\n const p = elementAt(s.points, m.point);\n const axis = definition.axis;\n const value = `${writePosition(axis, p.x)}, ${p.y === null ? '' : writeValue(s, p.y)}`;\n let note = join(join(observedBounds(s.interval, m.point, v => writeValue(s, v), s.xInterval === undefined ? '' : 'y '),\n observedBounds(s.xInterval, m.point, v => writePosition(axis, toNumber(v)), 'x ')),\n m.count > 1 ? `${String(m.count)} points here: ${p.name === undefined ? 'this one' : p.name} and ${String(m.count - 1)} more` : null);\n // A colour or a size read from a column is said with its value (ADR-0320).\n if (s.colourBy !== undefined) {\n note = join(note, `${s.colourBy.title} ${said(elementAt(s.colourBy.values, m.point))}`);\n }\n if (s.sizeBy !== undefined) {\n note = join(note, `${s.sizeBy.title} ${said(elementAt(s.sizeBy.values, m.point))}`);\n }\n // The columns the Consumer named for the tooltip, and no other (ADR-0321).\n for (const d of s.details) {\n const v = elementAt(d.values, m.point);\n note = join(note, `${d.title} ${v === null ? 'has no value' : v}`);\n }\n // A node with no label is named by its key (ADR-0321).\n const named = p.name !== undefined ? p.name : s.edges.length > 0 ? writeObject(p.row) : writePosition(axis, p.x);\n return reading(named, [readingLine(s.id, s.name, look, value, note, m.y)], 0);\n}\n\n/**\n * What the tooltip says over an edge (ADR-0321): its two keys. An edge has no value of its own, and nothing\n * about it is read from its nodes.\n */\nexport function readingOfEdge(definition: ChartDefinition, scene: ChartScene, edge: number): ChartReading {\n const m = scene.edgeMarks[edge];\n if (m === undefined) {\n throw new RangeError(`The scene has no edge ${String(edge)}; it has ${String(scene.edgeMarks.length)}.`);\n }\n const s = seriesOf(definition, m.seriesId);\n const look = lookOf(scene, m.panel, s.id);\n const e = elementAt(s.edges, m.edge.index);\n const from = writeObject(e.from);\n const to = writeObject(e.to);\n return reading(`${from} \u2192 ${to}`, [readingLine(s.id, s.name, look, `edge from ${from} to ${to}`, null, (m.edge.y1 + m.edge.y2) / 2)], 0);\n}\n\nfunction reading(position: string, lines: readonly ReadingLine[], more: number): ChartReading {\n return Object.freeze({ position, lines: Object.freeze([...lines]), more });\n}\n\nfunction readingLine(id: string, name: string, look: SeriesLook, value: string | null, note: string | null, y: number | null): ReadingLine {\n return Object.freeze({ id, name, look, value, note, y });\n}\n\nfunction seriesOf(definition: ChartDefinition, id: string): ChartSeries {\n const s = definition.series.find(x => x.id === id);\n if (s === undefined) {\n throw new Error(`The scene names a series '${id}' the definition does not have.`);\n }\n return s;\n}\n\nfunction lookOf(scene: ChartScene, panel: number, id: string): SeriesLook {\n const piece = scene.panels[panel]?.series.find(p => p.id === id);\n if (piece === undefined) {\n throw new Error(`The scene's panel ${String(panel)} does not draw the series '${id}'.`);\n }\n return piece.look;\n}\n\n// A height a line has before one it has not, as C# orders a missing height last.\nfunction heightOrder(a: number | null, b: number | null): number {\n if (a === null || b === null) {\n return a === null ? (b === null ? 0 : 1) : -1;\n }\n return a - b;\n}\n\n// A value read from a column, or that it has none.\nfunction said(v: ChartValue | null): string {\n return v === null ? 'has no value' : invariantText(v);\n}\n\nfunction line(s: ChartSeries, piece: SeriesPiece, panel: PanelScene, axis: ChartAxis, x: number): ReadingLine {\n const vertical = s.axis === 'right' ? panel.right : panel.left;\n const y = (height: number): number | null => (vertical === null ? null : yOf(vertical, height, panel.plot));\n const make = (value: string | null, note: string | null, at: number | null): ReadingLine => readingLine(s.id, s.name, piece.look, value, note, at);\n\n // A thinned pixel names its range, never one point as if it were the only one (ADR-0254).\n const thinned = piece.thinned.find(t => t.from <= x && x <= t.to);\n if (thinned !== undefined && s.sampler === undefined) {\n const held = s.points.flatMap(q => (q.x >= thinned.from && q.x <= thinned.to && q.y !== null ? [q.y] : []));\n if (held.length > 1) {\n const lo = firstBy(held, toNumber, (a, b) => a < b);\n const hi = firstBy(held, toNumber, (a, b) => a > b);\n const at = s.kind === 'amountPerPeriod' ? null : y((toNumber(lo) + toNumber(hi)) / 2);\n return make(`${writeValue(s, lo)} \u2013 ${writeValue(s, hi)}`,\n `${String(held.length)} points, ${writePosition(axis, thinned.from)} \u2013 ${writePosition(axis, thinned.to)}`, at);\n }\n }\n\n const f = s.sampler;\n if (f !== undefined) {\n if (x < f.from || x > f.to) {\n return make(null, 'outside its range', null);\n }\n const v = f.valueAt(x);\n return v === null ? make(null, 'missing', null) : make(writeValue(s, v), method(s, x), y(toNumber(v)));\n }\n\n const points = s.points;\n if (s.kind === 'level') {\n const point = points.find(q => q.x === x);\n if (point === undefined) {\n return make(null, 'no point here', null);\n }\n return point.y === null ? make(null, 'missing', null) : make(writeValue(s, point.y), join(method(s, x), bounds(s, x)), y(toNumber(point.y)));\n }\n\n // A step names its interval (ADR-0253): the point whose value holds at x, and the interval it holds over.\n const found = intervalAt(points, x, s.step);\n if (found === undefined) {\n return make(null, 'no interval here', null);\n }\n const [index, from, to] = found;\n const held = elementAt(points, index).y;\n if (held === null) {\n return make(null, 'missing', null);\n }\n const interval = from === to ? `at ${writePosition(axis, from)}` : `${writePosition(axis, from)} \u2013 ${writePosition(axis, to)}`;\n const m = method(s, x);\n const note = m === null ? interval : `${interval}, ${m}`;\n const drawn = s.kind === 'amountPerPeriod' && from !== to ? toNumber(held) / yearsBetween(axis, from, to) : toNumber(held);\n return make(writeValue(s, held), note, y(drawn));\n}\n\n\n// A candle's four values, its change from the previous candle's close and its volume; a merged candle names\n// its period and how many rows it holds (ADR-0300, ADR-0302). In a volume panel, the volume alone.\nfunction candle(s: ChartSeries, piece: SeriesPiece, panel: PanelScene, scene: ChartScene, axis: ChartAxis, x: number): ReadingLine {\n const vertical = panel.left;\n const plot = panel.plot;\n // Through the axis' own scale, as the candle is drawn, so a logarithmic axis reads where it paints.\n const y = (height: number): number | null => (vertical === null ? null : yOf(vertical, height, plot));\n const make = (value: string | null, note: string | null, at: number | null): ReadingLine => readingLine(s.id, piece.name, piece.look, value, note, at);\n const period = piece.period;\n // The candles as drawn, over the range shown, so the tooltip reads what the plot draws.\n const candles = candlesOf(s, scene.xFrom, scene.xTo, period);\n const c = candles.find(k => (period === 'row' ? k.from === x : periodStart(k.from, period) === periodStart(x, period)));\n if (c === undefined) {\n return s.bars.some(b => b.x === x) ? make(null, '(no value)', null) : make(null, 'no candle here', null);\n }\n const w = (v: number): string => writeValue(s, v);\n const volume = c.volume === null ? null : `Vol ${w(c.volume)}`;\n const span = c.rows > 1 || period !== 'row' ? `${writePosition(axis, c.from)} \u2013 ${writePosition(axis, c.to)}, ${String(c.rows)} rows` : null;\n if (panel.volumeOf !== null) {\n return make(volume === null ? '(no value)' : volume, span, c.volume === null ? null : y(c.volume));\n }\n const values = c.open === null ? `H ${w(c.high)} L ${w(c.low)} C ${w(c.close)}` : `O ${w(c.open)} H ${w(c.high)} L ${w(c.low)} C ${w(c.close)}`;\n // The change from the last close before this candle, shown or not.\n const withOpen = hasOpen(s.bars);\n const before = s.bars.filter(b => b.x < c.from && wholeBar(b, withOpen));\n const last = before[before.length - 1];\n const change = last === undefined || last.close === null ? 'Chg \u2014' : changeFrom(c.close, toNumber(last.close), w);\n return make(values, join(join(span, c.unchanged ? 'unchanged' : null), join(change, volume)), y(c.close));\n}\n\nfunction changeFrom(close: number, previous: number, w: (v: number) => string): string {\n const delta = close - previous;\n return `Chg ${delta >= 0 ? '+' : ''}${w(delta)}${percentChange(delta, previous)}`;\n}\n\nfunction bounds(s: ChartSeries, x: number): string | null {\n const iv = s.interval;\n if (iv === undefined) {\n return null;\n }\n const found = iv.bounds.filter(b => b.x === x);\n const [b] = found;\n return found.length === 1 && b !== undefined && b.lower !== null && b.upper !== null\n ? `[${writeValue(s, b.lower)}, ${writeValue(s, b.upper)}] ${iv.meaning}`\n : '(no interval)';\n}\n\n// An Observation's bounds at its row, with their meaning (ADR-0304).\nfunction observedBounds(iv: SeriesInterval | undefined, point: number, write: (v: ChartValue) => string, which: string): string | null {\n if (iv === undefined) {\n return null;\n }\n const b = elementAt(iv.bounds, point);\n return b.lower !== null && b.upper !== null ? `${which}[${write(b.lower)}, ${write(b.upper)}] ${iv.meaning}` : `${which}(no interval)`;\n}\n\nfunction join(a: string | null, b: string | null): string | null {\n return a === null ? b : b === null ? a : `${a}, ${b}`;\n}\n\n// Preceding: a point's value holds over (previous, point]; Following: over [point, next). At an edge with no\n// interval, the point's own value at its own position.\nfunction intervalAt(points: readonly ChartPoint[], x: number, side: StepSide): readonly [index: number, from: number, to: number] | undefined {\n for (let i = 0; i < points.length; i++) {\n const here = elementAt(points, i).x;\n if (side === 'preceding' && i > 0 && elementAt(points, i - 1).x < x && x <= here) {\n return [i, elementAt(points, i - 1).x, here];\n }\n if (side === 'following' && i < points.length - 1 && here <= x && x < elementAt(points, i + 1).x) {\n return [i, here, elementAt(points, i + 1).x];\n }\n }\n const first = points[0];\n const last = points[points.length - 1];\n if (first !== undefined && side === 'preceding' && first.x === x) {\n return [0, x, x];\n }\n if (last !== undefined && side === 'following' && last.x === x) {\n return [points.length - 1, x, x];\n }\n return undefined;\n}\n\n// An interpolated value says so (ADR-0257), with its Segment's method where one covers it.\nfunction method(s: ChartSeries, x: number): string | null {\n const g = segmentAt(s, x);\n if (g !== undefined) {\n return g.extrapolated === true ? `${g.method}, extrapolated` : s.interpolated ? `interpolated, ${g.method}` : g.method;\n }\n return s.interpolated ? 'interpolated' : null;\n}\n", "// What a chart shows, as CSV (ticket 07): the series and range left after the Chart Filters, every point\n// before Thinning (ADR-0254), each value with the digits it was handed in with. Invariant, unformatted, a\n// byte-order mark first so Excel reads it as UTF-8; a missing value is an empty field, never a zero. The\n// port of the C# engine's `ChartCsv`, held to it by the shared cases under tests/cases/chart/.\nimport { dateOf, isoDate, wholeDay } from './day-numbers';\nimport type { ChartDefinition } from './definition';\nimport { roundTrip } from './invariant-text';\nimport type { ChartMetrics, ChartView } from './metrics';\nimport type { ChartAxis, ChartPoint, ChartSeries, ChartValue, PriceBar, SeriesInterval } from './model';\nimport { defined, elementAt, unreachable } from './must';\nimport { hasOpen } from './price-ranges';\nimport { frameOf, quotesOf } from './scene';\nimport { sample, segmentAt } from './series-drawing';\nimport { invariantText, writeObject } from './values';\n\n/** A table of what the chart shows: a header and rows of invariant text. */\nexport interface ChartTable {\n /** The column headers: the axis' title, then a column per series. */\n readonly header: readonly string[];\n /** A row per position. */\n readonly rows: readonly (readonly string[])[];\n}\n\nconst bom = '\uFEFF';\n\n/**\n * A row per point, after a byte-order mark: Series, the axis' title, Value, Kind (quoted, interpolated,\n * extrapolated; a Price Range's columns are \"price range\", an Interval's bounds \"interval\") and Method (the\n * Segment's). Its empty Value is only ever a missing one.\n */\nexport function chartCsvLong(definition: ChartDefinition, metrics: ChartMetrics, view: ChartView = {}): string {\n const axis = definition.axis;\n const named = definition.series.some(s => s.kind === 'observation');\n let csv = bom + row(named ? ['Series', 'Point', axisTitle(axis), 'Value', 'Kind', 'Method'] : ['Series', axisTitle(axis), 'Value', 'Kind', 'Method']);\n for (const [s, points] of shown(definition, metrics, view)) {\n // An Observation's bounds follow each of its points, one a row (ADR-0304).\n if (s.kind === 'observation') {\n for (const [p, i] of observed(s, points)) {\n csv += row([s.name, nameOf(p), position(axis, p.x), text(p.y), 'observed', '']);\n for (const [iv, which] of [[s.interval, s.xInterval === undefined ? '' : 'y '], [s.xInterval, 'x ']] as const) {\n if (iv !== undefined) {\n const b = elementAt(iv.bounds, i);\n csv += row([`${s.name} ${which}lower (${iv.meaning})`, nameOf(p), position(axis, p.x), text(b.lower), 'interval', '']);\n csv += row([`${s.name} ${which}upper (${iv.meaning})`, nameOf(p), position(axis, p.x), text(b.upper), 'interval', '']);\n }\n }\n }\n continue;\n }\n const more = extra(s, points);\n if (more.length > 0) {\n // A Price Range's every row, and an Interval's bounds named by their meaning (ADR-0300, ADR-0303).\n const kind = s.kind === 'priceRange' ? 'price range' : 'interval';\n if (s.kind !== 'priceRange') {\n for (const p of points) {\n const [pk, pm] = kindOf(s, p.x);\n csv += row([s.name, position(axis, p.x), text(p.y), pk, pm]);\n }\n }\n for (const [header, values] of more) {\n for (const [x, v] of [...values].toSorted((a, b) => a[0] - b[0])) {\n csv += row([header, position(axis, x), v, kind, '']);\n }\n }\n continue;\n }\n for (const p of points) {\n const [kind, method] = kindOf(s, p.x);\n const tail = [position(axis, p.x), text(p.y), kind, method];\n csv += row(named ? [s.name, nameOf(p), ...tail] : [s.name, ...tail]);\n }\n }\n return csv;\n}\n\n/**\n * A row per position, a column per series, after a byte-order mark \u2014 an Interpolated series' column says\n * so, and a series with extrapolated points has a column of its own for them. An empty cell cannot tell a\n * missing value from a position the series has no point at; the long form can.\n */\nexport function chartCsvWide(definition: ChartDefinition, metrics: ChartMetrics, view: ChartView = {}): string {\n const table = chartTable(definition, metrics, view);\n return bom + row(table.header) + table.rows.map(row).join('');\n}\n\n/** The wide form's header and rows, unquoted: what \"View as table\" shows (ADR-0275), the same content as {@link chartCsvWide}. */\nexport function chartTable(definition: ChartDefinition, metrics: ChartMetrics, view: ChartView = {}): ChartTable {\n const axis = definition.axis;\n const all = shown(definition, metrics, view);\n // A scatter's points share positions across, so its table is a row per point, never a column per series\n // keyed by position, which would keep one point of each position (ADR-0290).\n if (definition.series.some(s => s.kind === 'observation')) {\n return observations(definition, all);\n }\n const columns: Column[] = [];\n for (const [s, points] of all) {\n if (s.kind === 'priceRange') {\n columns.push(...extra(s, points));\n continue;\n }\n const main = new Map<number, string>();\n const extrapolated = new Map<number, string>();\n for (const p of points) {\n (kindOf(s, p.x)[0] === 'extrapolated' ? extrapolated : main).set(p.x, text(p.y));\n }\n columns.push([s.interpolated ? `${s.name} (interpolated)` : s.name, main]);\n if (extrapolated.size > 0) {\n columns.push([`${s.name} (extrapolated)`, extrapolated]);\n }\n columns.push(...extra(s, points));\n }\n const xs = [...new Set(columns.flatMap(([, values]) => [...values.keys()]))].toSorted((a, b) => a - b);\n // A position a column has no value at is an empty cell (ticket 07), which only the long form tells from a missing value.\n // oxlint-disable-next-line ex-grid/no-stand-in-default -- ticket 07: the wide form leaves a position a series has no point at empty\n const rows = xs.map(x => [position(axis, x), ...columns.map(([, values]) => values.get(x) ?? '')]);\n return frozenTable([axisTitle(axis), ...columns.map(([header]) => header)], rows);\n}\n\n/** The horizontal axis' title in the files and the summary: its own, or what its positions are. */\nexport function axisTitle(axis: ChartAxis): string {\n return axis.title.length > 0 ? axis.title : axis.values === 'dates' ? 'Date' : 'X';\n}\n\ntype Column = readonly [header: string, values: ReadonlyMap<number, string>];\n\ntype Shown = readonly [series: ChartSeries, points: readonly ChartPoint[]];\n\nfunction frozenTable(header: readonly string[], rows: readonly (readonly string[])[]): ChartTable {\n return Object.freeze({ header: Object.freeze([...header]), rows: Object.freeze(rows.map(r => Object.freeze([...r]))) });\n}\n\n// The visible series and the points each shows: those in range, or a sampled series' samples.\nfunction shown(d: ChartDefinition, metrics: ChartMetrics, view: ChartView): Shown[] {\n const { axis, visible, from, to, devicePixels } = frameOf(d, metrics, view);\n return visible.map(s => [s, s.sampler === undefined\n ? s.points.filter(p => p.x >= from && p.x <= to)\n : sample(s.sampler, s.segments, from, to, devicePixels, quotesOf(s, visible), axis.effectiveScale === 'logarithmic')]);\n}\n\n// A scatter's table, a row per point, with a lower and an upper column for each quantity that has an\n// interval: named by its meaning when every series means the same, else with the meaning in a column of its\n// own (ADR-0304).\nfunction observations(d: ChartDefinition, all: readonly Shown[]): ChartTable {\n const title = axisTitle(d.axis);\n const header = ['Series', 'Point', title, 'Value'];\n const observing = all.filter(([s]) => s.kind === 'observation').map(([s]) => s);\n const quantities: { readonly of: (s: ChartSeries) => SeriesInterval | undefined; readonly plain: boolean }[] = [];\n for (const [of, name] of [[(s: ChartSeries) => s.interval, 'Value'], [(s: ChartSeries) => s.xInterval, title]] as const) {\n const meanings = distinct(observing.flatMap(s => {\n const iv = of(s);\n return iv === undefined ? [] : [iv.meaning];\n }));\n const [meaning] = meanings;\n if (meaning === undefined) {\n continue;\n }\n const plain = meanings.length > 1 || observing.some(s => of(s) === undefined);\n header.push(...(plain ? [`${name} lower`, `${name} upper`, `${name} interval`] : [`${name} lower (${meaning})`, `${name} upper (${meaning})`]));\n quantities.push({ of, plain });\n }\n // A colour or a size read from a column is a column of the file: files carry every value (ADR-0320).\n const scales = distinct(observing.flatMap(s => [s.colourBy?.title, s.sizeBy?.title].filter(t => t !== undefined)));\n header.push(...scales);\n // So is a column the tooltip says (ADR-0321).\n const details = distinct(observing.flatMap(s => s.details.map(x => x.title)).filter(t => !scales.includes(t)));\n header.push(...details);\n const rows: string[][] = [];\n for (const [s, points] of all) {\n for (const [p, i] of observed(s, points)) {\n const r = [s.name, nameOf(p), position(d.axis, p.x), text(p.y)];\n for (const { of, plain } of quantities) {\n const iv = s.kind === 'observation' ? of(s) : undefined;\n const b = iv === undefined ? undefined : elementAt(iv.bounds, i);\n r.push(b === undefined ? '' : text(b.lower), b === undefined ? '' : text(b.upper));\n if (plain) {\n r.push(iv === undefined ? '' : iv.meaning);\n }\n }\n for (const t of scales) {\n const values = s.colourBy?.title === t ? s.colourBy.values : s.sizeBy?.title === t ? s.sizeBy.values : undefined;\n r.push(values === undefined ? '' : text(elementAt(values, i)));\n }\n for (const t of details) {\n const detail = s.details.find(x => x.title === t);\n const v = detail === undefined ? null : elementAt(detail.values, i);\n r.push(v === null ? '' : v);\n }\n rows.push(r);\n }\n }\n // A node series lists its edges after its nodes (ADR-0321).\n for (const [s] of all.filter(([series]) => series.edges.length > 0)) {\n for (const e of s.edges) {\n const r = [s.name, `edge ${writeObject(e.from)} \u2192 ${writeObject(e.to)}`];\n while (r.length < header.length) {\n r.push('');\n }\n rows.push(r);\n }\n }\n return frozenTable(header, rows);\n}\n\n// The points shown with their rows: an Observation's every point in range, a sampled series' samples (row -1).\nfunction observed(s: ChartSeries, points: readonly ChartPoint[]): (readonly [point: ChartPoint, row: number])[] {\n if (s.kind !== 'observation' || s.sampler !== undefined) {\n return points.map(p => [p, -1] as const);\n }\n const kept = new Set(points);\n return s.points.flatMap((p, i) => (kept.has(p) ? [[p, i] as const] : []));\n}\n\n// The columns a series carries beyond its points: a Price Range's open, high, low, close and volume, and an\n// Interval's lower and upper bounds, each named by its meaning.\nfunction extra(s: ChartSeries, points: readonly ChartPoint[]): Column[] {\n const xs = new Set(points.map(p => p.x));\n const columns = (cols: readonly (readonly [name: string, value: (x: number) => string])[]): Column[] =>\n cols.map(([name, value]) => [`${s.name} ${name}`, new Map([...xs].map(x => [x, value(x)] as const))]);\n if (s.kind === 'priceRange') {\n const bars = new Map(s.bars.filter(b => xs.has(b.x)).map(b => [b.x, b] as const));\n const bar = (x: number): PriceBar => defined(bars.get(x), `the row of ${roundTrip(x)}`);\n const cols: (readonly [string, (x: number) => string])[] = [];\n if (hasOpen(s.bars)) {\n cols.push(['open', x => text(bar(x).open)]);\n }\n cols.push(['high', x => text(bar(x).high)], ['low', x => text(bar(x).low)], ['close', x => text(bar(x).close)]);\n if (s.bars.some(b => b.volume !== undefined && b.volume !== null)) {\n cols.push(['volume', x => text(bar(x).volume)]);\n }\n return columns(cols);\n }\n const iv = s.interval;\n if (iv !== undefined) {\n const bounds = new Map(iv.bounds.filter(b => xs.has(b.x)).map(b => [b.x, b] as const));\n return columns([\n [`lower (${iv.meaning})`, x => {\n const b = bounds.get(x);\n return b === undefined ? '' : text(b.lower);\n }],\n [`upper (${iv.meaning})`, x => {\n const b = bounds.get(x);\n return b === undefined ? '' : text(b.upper);\n }],\n ]);\n }\n return [];\n}\n\nfunction kindOf(s: ChartSeries, x: number): readonly [kind: string, method: string] {\n if (s.kind === 'observation') {\n return ['observed', ''];\n }\n const g = segmentAt(s, x);\n if (g !== undefined && g.extrapolated === true) {\n return ['extrapolated', g.method];\n }\n return [s.interpolated ? 'interpolated' : 'quoted', g === undefined ? '' : g.method];\n}\n\n// A value as the files write it: invariantly with every digit, a missing one as an empty field (ticket 07).\nfunction text(v: ChartValue | null | undefined): string {\n return v === null || v === undefined ? '' : invariantText(v);\n}\n\n// A point's name, a point with none an empty field.\nfunction nameOf(p: ChartPoint): string {\n return p.name === undefined ? '' : p.name;\n}\n\n// A position as the files write it: a date as yyyy-MM-dd, a category by its label, a number with every digit.\nfunction position(axis: ChartAxis, x: number): string {\n switch (axis.values) {\n case 'dates':\n return isoDate(dateOf(wholeDay(x)));\n case 'labels': {\n const label = axis.labels[wholeDay(x)];\n if (label === undefined) {\n throw new RangeError(`${roundTrip(x)} is not one of the axis' ${String(axis.labels.length)} labels.`);\n }\n return label;\n }\n case 'numbers':\n return roundTrip(x);\n default:\n return unreachable(axis.values);\n }\n}\n\nfunction row(fields: readonly string[]): string {\n return `${fields.map(field).join(',')}\\r\\n`;\n}\n\nfunction field(f: string): string {\n return /[,\"\\r\\n]/.test(f) ? `\"${f.replaceAll('\"', '\"\"')}\"` : f;\n}\n\nfunction distinct(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n", "// The chart said in words, for a screen reader (ADR-0275): generated from the definition, so a chart nobody\n// described still says what it is. The port of the C# engine's `ChartSummary`, held to it by the shared\n// cases under tests/cases/chart/.\nimport { axisTitle } from './csv';\nimport type { ChartDefinition } from './definition';\nimport { upToPlaces } from './invariant-text';\nimport type { ChartAxis, ChartPoint, ChartSeries, ChartValue } from './model';\nimport { defined } from './must';\nimport { firstBy, greatest, least } from './numbers';\nimport { valueRange } from './point-scales';\nimport type { ChartScene } from './scene';\nimport { toNumber, writePosition, writeValue } from './values';\n\n/**\n * The chart's name, the horizontal axis with its range, each panel's vertical axes with theirs, and each\n * visible series with its maximum, written through its format, then the Consumer's description. The view\n * is the scene's own: what it hides and the range it shows are already laid out in it.\n */\nexport function chartSummary(definition: ChartDefinition, scene: ChartScene, title?: string, description?: string): string {\n const axis = definition.axis;\n const parts: string[] = [];\n if (title !== undefined && title.trim() !== '') {\n parts.push(`${title.trim().replace(/\\.+$/, '')}.`);\n }\n parts.push(`${axisTitle(axis)}, ${writePosition(axis, scene.xFrom)} to ${writePosition(axis, scene.xTo)}.`);\n const byId = new Map(definition.series.map(s => [s.id, s] as const));\n for (const panel of scene.panels) {\n const named = scene.panels.length > 1 && panel.name.length > 0 ? `${panel.name}: ` : '';\n for (const v of [panel.left, panel.right]) {\n if (v !== null) {\n parts.push(`${named}${v.side === 'left' ? 'Left' : 'Right'} axis, ${number(v.min)} to ${number(v.max)}.`);\n }\n }\n for (const piece of panel.series) {\n const s = defined(byId.get(piece.id), `the series '${piece.id}'`);\n parts.push(panel.volumeOf === null ? series(s, axis, scene) : volume(s, axis, scene));\n }\n }\n if (description !== undefined && description.trim() !== '') {\n parts.push(description.trim());\n }\n return parts.join(' ');\n}\n\nfunction series(s: ChartSeries, axis: ChartAxis, scene: ChartScene): string {\n if (s.kind === 'observation') {\n const seen = valued(s.points.filter(p => p.x >= scene.xFrom && p.x <= scene.xTo));\n if (seen.length === 0) {\n return `${s.name}: no point in range.`;\n }\n const low = firstBy(seen, p => toNumber(p.y), (a, b) => a < b);\n const high = firstBy(seen, p => toNumber(p.y), (a, b) => a > b);\n const xs = seen.map(p => p.x);\n const across = `${writePosition(axis, least(xs))} to ${writePosition(axis, greatest(xs))} across, ${writeValue(s, low.y)} to ${writeValue(s, high.y)} up.`;\n let said = s.edges.length > 0\n ? `${s.name}: ${String(s.points.length)} nodes and ${String(s.edges.length)} edges, ${across}`\n : `${s.name}: ${String(seen.length)} points, ${across}`;\n const colour = s.colourBy === undefined ? undefined : valueRange(s.colourBy.values);\n if (s.colourBy !== undefined && colour !== undefined) {\n said += ` ${s.name}: colour is ${s.colourBy.title}, ${number(colour[0])} to ${number(colour[1])}.`;\n }\n const size = s.sizeBy === undefined ? undefined : valueRange(s.sizeBy.values);\n if (s.sizeBy !== undefined && size !== undefined) {\n said += ` ${s.name}: size is ${s.sizeBy.title}, ${number(size[0])} to ${number(size[1])}.`;\n }\n return said;\n }\n const f = s.sampler;\n const points: readonly ChartPoint[] = f === undefined\n ? s.points.filter(p => p.x >= scene.xFrom && p.x <= scene.xTo)\n : scene.positions.filter(([position]) => position >= f.from && position <= f.to).map(([position]) => ({ x: position, y: f.valueAt(position) }));\n const seen = valued(points);\n if (seen.length === 0) {\n return `${s.name}: no value in range.`;\n }\n const max = firstBy(seen, p => toNumber(p.y), (a, b) => a > b);\n return `${s.name}: maximum ${writeValue(s, max.y)} at ${writePosition(axis, max.x)}.`;\n}\n\n// A volume panel says the volume, never its series' prices again (ADR-0300).\nfunction volume(s: ChartSeries, axis: ChartAxis, scene: ChartScene): string {\n const seen = s.bars.flatMap(b => (b.volume !== undefined && b.volume !== null && b.x >= scene.xFrom && b.x <= scene.xTo ? [{ x: b.x, y: b.volume }] : []));\n if (seen.length === 0) {\n return `${s.name} volume: no value in range.`;\n }\n const max = firstBy(seen, p => toNumber(p.y), (a, b) => a > b);\n return `${s.name} volume: maximum ${writeValue(s, max.y)} at ${writePosition(axis, max.x)}.`;\n}\n\ninterface Valued {\n readonly x: number;\n readonly y: ChartValue;\n}\n\nfunction valued(points: readonly { readonly x: number; readonly y: ChartValue | null }[]): Valued[] {\n return points.flatMap(p => (p.y === null ? [] : [{ x: p.x, y: p.y }]));\n}\n\n// The first point whose value `before` puts ahead of every other's, as C#'s MinBy and MaxBy take it.\n\nconst number = (v: number): string => upToPlaces(v, 4);\n", "// A 3D surface in the data's terms (ADR-0274): a grid of values over two axes, a Consumer's sampled\n// function, or a Consumer's own triangle mesh (ADR-0311), checked when it is made, and its slices as 2D\n// charts. The port of the C# engine's `SurfaceDefinition`, held to it by the shared cases under\n// tests/cases/chart/ (ADR-0370).\nimport { ChartDefinition } from './definition';\nimport { roundTrip, tickText } from './invariant-text';\nimport type { AxisScale, ChartAxisOptions, ChartPoint, ChartSeriesOptions, ChartValue } from './model';\nimport { elementAt } from './must';\nimport { greatest, least } from './numbers';\nimport type { FormatCode } from '@ex-grid/core';\nimport { ChartRefusedError, invariantText, readCode, toNumber } from './values';\n\n/** A value of a surface's axis: a strike, a delta or a tenor, as the column holds it. */\nexport type SurfaceValue = string | number;\n\n/** One axis of a surface as a Consumer declares it (ADR-0274, ADR-0312). */\nexport interface SurfaceAxisOptions {\n /** The axis' title. */\n readonly title: string;\n /** The values, one per grid line, in order. */\n readonly values: readonly SurfaceValue[];\n /** Writes a value as the column it came from writes it; absent writes it invariantly. */\n readonly format?: (value: SurfaceValue) => string;\n /** How the axis places its values; `categories`, evenly spaced, by default (ADR-0312). */\n readonly scale?: AxisScale;\n /**\n * An Excel number format code in the invariant spelling, such as `0.0%`, read by the family's `FormatCode`\n * (ADR-0420): it writes the axis' values and its ticks between them, in place of a format. It writes numbers,\n * so the axis' values are numbers.\n */\n readonly formatCode?: string;\n}\n\n/**\n * One axis of a 3D surface (ADR-0274): its title and its values in order, each written through its\n * format. A grid's lines are evenly spaced, one per value, unless its scale places them by value (ADR-0312).\n */\nexport class SurfaceAxis {\n readonly #title: string;\n readonly #values: readonly SurfaceValue[];\n readonly #format: ((value: SurfaceValue) => string) | undefined;\n readonly #scale: AxisScale;\n readonly #formatCode: string | undefined;\n readonly #code: FormatCode | undefined;\n\n /** An axis of the given values, in the order the grid holds them; a code it cannot write them with is refused. */\n constructor(options: SurfaceAxisOptions) {\n const { scale = 'categories' } = options;\n this.#title = options.title;\n this.#values = Object.freeze([...options.values]);\n this.#format = options.format;\n this.#scale = scale;\n this.#formatCode = options.formatCode;\n this.#code = options.formatCode === undefined ? undefined : checkAxisCode(this, options.formatCode);\n }\n\n /** The axis' title. */\n get title(): string {\n return this.#title;\n }\n\n /** The values, one per grid line, in order. */\n get values(): readonly SurfaceValue[] {\n return this.#values;\n }\n\n /** The Consumer's writer of a value, if any. */\n get format(): ((value: SurfaceValue) => string) | undefined {\n return this.#format;\n }\n\n /** How the axis places its values (ADR-0312). */\n get scale(): AxisScale {\n return this.#scale;\n }\n\n /** The Excel format code its values and ticks are written by (ADR-0420), if any. */\n get formatCode(): string | undefined {\n return this.#formatCode;\n }\n\n /** Writes the value at `index` through the format or the code. */\n write(index: number): string {\n return this.writeValue(elementAt(this.#values, index));\n }\n\n /** Writes `value` through the format or the code, or invariantly. */\n writeValue(value: SurfaceValue): string {\n if (this.#format !== undefined) {\n return this.#format(value);\n }\n if (typeof value === 'string') {\n return value;\n }\n return this.#code === undefined ? roundTrip(value) : this.#code.format(value, 'invariant');\n }\n\n /**\n * Writes a position that need not be one of the values, such as a tick: through the code, through the\n * format when the values are numbers, invariantly otherwise.\n */\n writeTick(position: number): string {\n if (this.#code !== undefined) {\n return this.#code.format(position, 'invariant');\n }\n const [first] = this.#values;\n if (this.#format !== undefined && typeof first === 'number') {\n return this.#format(position);\n }\n return tickText(position);\n }\n\n /** The index of `value` among the values, or -1. */\n indexOf(value: SurfaceValue): number {\n return this.#values.indexOf(value);\n }\n\n /**\n * The value at `index` as a number; a value that is not one is a defect of the caller, which checked it.\n *\n * @internal\n */\n number(index: number): number {\n const value = elementAt(this.#values, index);\n if (typeof value !== 'number') {\n throw new Error(`Internal: ${value} is not a number.`);\n }\n return value;\n }\n}\n\n/** Which of a surface's two axes a slice holds fixed: `x` runs along y, `y` along x. */\nexport type SurfaceSliceAxis = 'x' | 'y';\n\n/** A slice of a surface, named in the data's terms (ADR-0272, ADR-0274): the axis held fixed and its value there. */\nexport interface SurfaceSlice {\n /** The axis held fixed. */\n readonly axis: SurfaceSliceAxis;\n /** Its value, as the axis holds it. */\n readonly value: SurfaceValue;\n}\n\n/** How a surface is seen, in its own terms (ADR-0272): angles in degrees, the zoom, and the centre's offset as fractions. Never pixels. */\nexport interface SurfaceView {\n /** The turn about the vertical, in degrees. */\n readonly yaw: number;\n /** The tilt from level, in degrees, -90 to 90. */\n readonly pitch: number;\n /** The zoom, 1 fitting the surface to its box. */\n readonly zoom: number;\n /** The centre's horizontal offset, as a fraction of the width. */\n readonly panX: number;\n /** The centre's vertical offset, as a fraction of the height. */\n readonly panY: number;\n}\n\n/** The view a surface is first drawn at. */\nexport const defaultSurfaceView: SurfaceView = Object.freeze({ yaw: -35, pitch: 28, zoom: 1, panX: 0, panY: 0 });\n\n/** A node of a Consumer's triangle mesh (ADR-0311): its place in the plane and its value, or `null`, a hole. */\nexport interface SurfaceNode {\n /** Its x position. */\n readonly x: number;\n /** Its y position. */\n readonly y: number;\n /** Its value, or `null`: no triangle at it is drawn. */\n readonly z: ChartValue | null;\n}\n\n/** A triangle of a Consumer's mesh (ADR-0311): the indices of its three nodes. */\nexport interface SurfaceTriangle {\n /** The first corner's index. */\n readonly a: number;\n /** The second corner's index. */\n readonly b: number;\n /** The third corner's index. */\n readonly c: number;\n}\n\n/** How the values are scaled, coloured and written, which every form of surface may say (ADR-0310, ADR-0312, ADR-0420). */\nexport interface SurfaceScaleOptions {\n /**\n * An Excel number format code in the invariant spelling, such as `0.00%`, read by the family's `FormatCode`\n * (ADR-0420): it writes the values the surface holds and the ones a slice reads between them, in place of a\n * `zFormat`.\n */\n readonly zFormatCode?: string;\n /** The vertical scale: `proportional`, the default, or `logarithmic`; never `categories`. */\n readonly zScale?: AxisScale;\n /** The value the colours diverge from, such as 0 for a P&L (ADR-0310); absent colours low to high. */\n readonly centre?: number;\n}\n\n/** A surface of a grid (ADR-0274): `z` holds one row per y value, each with one value per x value. */\nexport interface SurfaceGridOptions extends SurfaceScaleOptions {\n /** The x axis: the table's columns. */\n readonly x: SurfaceAxisOptions;\n /** The y axis: the table's rows. */\n readonly y: SurfaceAxisOptions;\n /** The values, one row per y value, `null` at a hole. */\n readonly z: readonly (readonly (ChartValue | null)[])[];\n /** What the values are; empty by default. */\n readonly zTitle?: string;\n /** Writes a value as its cell writes it. */\n readonly zFormat?: (value: ChartValue) => string;\n /** The method the interpolated values were made with, as the tooltip and the Notes say it (ADR-0257). */\n readonly method?: string;\n /** Which values are interpolated, in the table's shape; absent with a method marks every value. */\n readonly interpolated?: readonly (readonly boolean[])[];\n /** The Consumer's Notes, shown under the surface (ADR-0257). */\n readonly notes?: readonly string[];\n}\n\n/** A point of a surface handed in as points, at an x value and a y value. */\nexport interface SurfacePoint {\n /** Its x value. */\n readonly x: SurfaceValue;\n /** Its y value. */\n readonly y: SurfaceValue;\n /** Its value. */\n readonly z: ChartValue;\n}\n\n/** A surface from points on a grid (ADR-0274). */\nexport interface SurfacePointsOptions extends SurfaceScaleOptions {\n /** The points. */\n readonly points: readonly SurfacePoint[];\n /** The x axis' title. */\n readonly xTitle: string;\n /** The y axis' title. */\n readonly yTitle: string;\n /** What the values are. */\n readonly zTitle?: string;\n /** Writes an x value. */\n readonly xFormat?: (value: SurfaceValue) => string;\n /** Writes a y value. */\n readonly yFormat?: (value: SurfaceValue) => string;\n /** The x axis' Excel format code, in place of `xFormat` (ADR-0420). */\n readonly xFormatCode?: string;\n /** The y axis' Excel format code, in place of `yFormat`. */\n readonly yFormatCode?: string;\n /** Writes a value. */\n readonly zFormat?: (value: ChartValue) => string;\n}\n\n/** A surface on the Consumer's own triangle mesh (ADR-0311). */\nexport interface SurfaceTrianglesOptions extends SurfaceScaleOptions {\n /** The nodes. */\n readonly nodes: readonly SurfaceNode[];\n /** The triangles. */\n readonly triangles: readonly SurfaceTriangle[];\n /** The x axis' title. */\n readonly xTitle: string;\n /** The y axis' title. */\n readonly yTitle: string;\n /** What the values are. */\n readonly zTitle?: string;\n /** Writes an x position. */\n readonly xFormat?: (value: SurfaceValue) => string;\n /** Writes a y position. */\n readonly yFormat?: (value: SurfaceValue) => string;\n /** The x axis' Excel format code, in place of `xFormat` (ADR-0420). */\n readonly xFormatCode?: string;\n /** The y axis' Excel format code, in place of `yFormat`. */\n readonly yFormatCode?: string;\n /** Writes a value. */\n readonly zFormat?: (value: ChartValue) => string;\n /** How x positions are placed: `proportional`, the default, or `logarithmic`. */\n readonly xScale?: AxisScale;\n /** How y positions are placed. */\n readonly yScale?: AxisScale;\n /** The Consumer's Notes. */\n readonly notes?: readonly string[];\n}\n\n/** A surface handed in as the Consumer's function z(x, y), which names its method (ADR-0257). */\nexport interface SurfaceSampledOptions extends SurfaceScaleOptions {\n /** The method the function interpolates with, as the tooltip and the Notes say it. */\n readonly method: string;\n /** The first x sampled. */\n readonly xFrom: number;\n /** The last. */\n readonly xTo: number;\n /** The first y sampled. */\n readonly yFrom: number;\n /** The last. */\n readonly yTo: number;\n /** The Consumer's surface: the value at (x, y), or `null` where it has none, outside its points. */\n readonly z: (x: number, y: number) => ChartValue | null;\n /** The x axis' title. */\n readonly xTitle: string;\n /** The y axis' title. */\n readonly yTitle: string;\n /** What the values are. */\n readonly zTitle?: string;\n /** How many values an axis is sampled at; 25 by default. */\n readonly samples?: number;\n /** Writes an x value. */\n readonly xFormat?: (value: SurfaceValue) => string;\n /** Writes a y value. */\n readonly yFormat?: (value: SurfaceValue) => string;\n /** The x axis' Excel format code, in place of `xFormat` (ADR-0420). */\n readonly xFormatCode?: string;\n /** The y axis' Excel format code, in place of `yFormat`. */\n readonly yFormatCode?: string;\n /** Writes a value. */\n readonly zFormat?: (value: ChartValue) => string;\n /** How x values are sampled and placed; `categories` by default. */\n readonly xScale?: AxisScale;\n /** How y values are sampled and placed. */\n readonly yScale?: AxisScale;\n}\n\n/** One point of a cut through a mesh: its position along the other axis and its value there. */\ninterface CutPoint {\n readonly along: number;\n readonly z: ChartValue;\n}\n\n/** The method a slice through a Consumer's triangles reads between its nodes with (ADR-0311). */\nexport const trianglesMethod = 'linear on the Consumer\\'s triangles (P1)';\n\nconst scatteredReason = 'scattered points form no grid, and a surface through them is an interpolation, which ExChart does not choose. Interpolate them, with a method of ExChart.Engine.Interpolation or your own, and hand the surface in as a function that names its method, or hand in your own triangles (ADR-0257, ADR-0274, ADR-0311).';\n\nconst nameOr = (title: string, fallback: string): string => (title.trim() === '' ? fallback : title);\n\ninterface SurfaceParts {\n readonly x: SurfaceAxis;\n readonly y: SurfaceAxis;\n readonly z: readonly (readonly (ChartValue | null)[])[];\n readonly zTitle: string;\n readonly zFormat: ((value: ChartValue) => string) | undefined;\n readonly zFormatCode: string | undefined;\n readonly zCode: FormatCode | undefined;\n readonly method: string | undefined;\n readonly interpolated: readonly (readonly boolean[])[] | undefined;\n readonly notes: readonly string[];\n readonly nodes: readonly SurfaceNode[] | undefined;\n readonly triangles: readonly SurfaceTriangle[] | undefined;\n readonly zScale: AxisScale;\n readonly centre: number | undefined;\n}\n\n/**\n * A 3D surface in the data's terms (ADR-0274): x values \u00D7 y values \u00D7 a table of z, one row per y value\n * and one column per x value. A missing value is a hole, drawn as one: never 0 and never filled from its\n * neighbours. Scattered points are refused by name (`fromPoints`). Interpolation is the Consumer's\n * (ADR-0257): a surface may be handed in as a function, which ExChart samples (`sampled`), or as a grid\n * whose interpolated values are marked. A Consumer's own triangle mesh is drawn as its triangles\n * (`fromTriangles`, ADR-0311).\n */\nexport class SurfaceDefinition {\n readonly #parts: SurfaceParts;\n\n private constructor(parts: SurfaceParts) {\n this.#parts = parts;\n }\n\n /** A surface of the given grid; refused with a `ChartRefusedError` when it cannot be drawn as asked. */\n static grid(options: SurfaceGridOptions): SurfaceDefinition {\n const { zTitle = '', notes = [] } = options;\n const method = options.method === undefined || options.method.trim() === '' ? undefined : options.method;\n const x = new SurfaceAxis(options.x);\n const y = new SurfaceAxis(options.y);\n const z = Object.freeze(options.z.map(row => Object.freeze([...row])));\n const interpolated = options.interpolated === undefined ? undefined : Object.freeze(options.interpolated.map(row => Object.freeze([...row])));\n validateGrid(x, y, z, method, interpolated);\n return new SurfaceDefinition(Object.freeze({\n x, y, z, zTitle, zFormat: options.zFormat, ...zCoded(options, zTitle), method, interpolated, notes: Object.freeze([...notes]),\n nodes: undefined, triangles: undefined, ...scaled(options),\n }));\n }\n\n /**\n * A surface from points, each at an x value and a y value. The points must lie on a grid: every x value\n * they name must hold a value at two y values at least, and every y value at two x values, or the point\n * stands alone and could join a surface only by interpolation (ADR-0257, ADR-0274). Where the grid has no\n * point, it has a hole.\n */\n static fromPoints(options: SurfacePointsOptions): SurfaceDefinition {\n const { points, xTitle, yTitle, zTitle = '' } = options;\n const xs = ordered(points.map(p => p.x));\n const ys = ordered(points.map(p => p.y));\n const xAxis = new SurfaceAxis({ title: xTitle, values: xs, ...writers(options.xFormat, options.xFormatCode) });\n const yAxis = new SurfaceAxis({ title: yTitle, values: ys, ...writers(options.yFormat, options.yFormatCode) });\n const count = (key: (p: SurfacePoint) => SurfaceValue): Map<SurfaceValue, number> => {\n const counts = new Map<SurfaceValue, number>();\n for (const p of points) {\n const k = key(p);\n const seen = counts.get(k);\n counts.set(k, seen === undefined ? 1 : seen + 1);\n }\n return counts;\n };\n const xCounts = count(p => p.x);\n const yCounts = count(p => p.y);\n for (const x of xs) {\n if (elementOf(xCounts, x) < 2) {\n throw new ChartRefusedError(`${nameOr(xTitle, 'x')} ${xAxis.writeValue(x)} has a value at only one ${nameOr(yTitle, 'y')}: ${scatteredReason}`);\n }\n }\n for (const y of ys) {\n if (elementOf(yCounts, y) < 2) {\n throw new ChartRefusedError(`${nameOr(yTitle, 'y')} ${yAxis.writeValue(y)} has a value at only one ${nameOr(xTitle, 'x')}: ${scatteredReason}`);\n }\n }\n const xIndex = new Map(xs.map((v, i) => [v, i]));\n const yIndex = new Map(ys.map((v, j) => [v, j]));\n const z: (ChartValue | null)[][] = ys.map(() => xs.map(() => null));\n for (const p of points) {\n const row = elementAt(z, elementOf(yIndex, p.y));\n const i = elementOf(xIndex, p.x);\n if (elementAt(row, i) !== null) {\n throw new ChartRefusedError(`Two points lie at ${nameOr(xTitle, 'x')} ${xAxis.writeValue(p.x)} and ${nameOr(yTitle, 'y')} ${yAxis.writeValue(p.y)}; a grid point holds one value.`);\n }\n row[i] = p.z;\n }\n return SurfaceDefinition.grid({\n x: axisOptions(xAxis), y: axisOptions(yAxis), z, zTitle,\n ...(options.zFormat === undefined ? {} : { zFormat: options.zFormat }),\n ...scaleOptions(options),\n });\n }\n\n /**\n * A surface drawn on the Consumer's own triangle mesh (ADR-0311), each triangle flat through its three\n * corners, never resampled onto a grid. A slice cuts the triangles exactly, reading between nodes\n * linearly on them (`trianglesMethod`), which it says.\n */\n static fromTriangles(options: SurfaceTrianglesOptions): SurfaceDefinition {\n const { nodes, triangles, xTitle, yTitle, zTitle = '', xScale = 'proportional', yScale = 'proportional', notes = [] } = options;\n if (xScale === 'categories' || yScale === 'categories') {\n throw new ChartRefusedError('A mesh\\'s nodes are placed by their position: its axes are proportional or logarithmic, never categories (ADR-0311).');\n }\n for (const n of nodes) {\n if (!Number.isFinite(n.x) || !Number.isFinite(n.y)) {\n throw new ChartRefusedError(`A node lies at (${roundTrip(n.x)}, ${roundTrip(n.y)}), which is no place in the plane.`);\n }\n }\n const x = new SurfaceAxis({\n title: xTitle, values: ordered(nodes.map(n => n.x)), scale: xScale, ...writers(options.xFormat, options.xFormatCode),\n });\n const y = new SurfaceAxis({\n title: yTitle, values: ordered(nodes.map(n => n.y)), scale: yScale, ...writers(options.yFormat, options.yFormatCode),\n });\n const frozenNodes = Object.freeze(nodes.map(n => Object.freeze({ x: n.x, y: n.y, z: n.z })));\n const frozenTriangles = Object.freeze(triangles.map(t => Object.freeze({ a: t.a, b: t.b, c: t.c })));\n validateMesh(x, y, frozenNodes, frozenTriangles);\n return new SurfaceDefinition(Object.freeze({\n x, y, z: Object.freeze([]), zTitle, zFormat: options.zFormat, ...zCoded(options, zTitle), method: undefined, interpolated: undefined,\n notes: Object.freeze([...notes]),\n nodes: frozenNodes, triangles: frozenTriangles, ...scaled(options),\n }));\n }\n\n /**\n * A surface handed in as a function z(x, y), the Consumer's interpolation, which names its method\n * (ADR-0257). ExChart samples it on a grid of `samples` values an axis across the rectangle \u2014 evenly in\n * the axis' own scale, so geometrically on a logarithmic one (ADR-0312) \u2014 and draws a hole where it\n * returns `null`. Every value is marked interpolated.\n */\n static sampled(options: SurfaceSampledOptions): SurfaceDefinition {\n const { method, xFrom, xTo, yFrom, yTo, xTitle, yTitle, zTitle = '', samples = 25, xScale = 'categories', yScale = 'categories' } = options;\n if (method.trim() === '') {\n throw new ChartRefusedError('A surface handed in as a function names its method, so the chart can say how its values were made (ADR-0257).');\n }\n if (!(xFrom < xTo) || !(yFrom < yTo)) {\n throw new ChartRefusedError('A surface handed in as a function is sampled over a rectangle that is not empty.');\n }\n if (!Number.isInteger(samples) || samples < 2) {\n throw new RangeError(`${String(samples)} samples: a surface is sampled at two values an axis at least.`);\n }\n if ((xScale === 'logarithmic' && !(xFrom > 0)) || (yScale === 'logarithmic' && !(yFrom > 0))) {\n throw new ChartRefusedError('A surface sampled on a logarithmic axis is sampled from above zero, which is where a logarithmic axis begins.');\n }\n const at = (from: number, to: number, scale: AxisScale, k: number): number => (k === samples - 1 ? to\n : scale === 'logarithmic' ? from * Math.pow(to / from, k / (samples - 1))\n : from + (to - from) * k / (samples - 1));\n const xs = Array.from({ length: samples }, (_, k) => at(xFrom, xTo, xScale, k));\n const ys = Array.from({ length: samples }, (_, k) => at(yFrom, yTo, yScale, k));\n const z = ys.map(v => xs.map(u => options.z(u, v)));\n return SurfaceDefinition.grid({\n x: { title: xTitle, values: xs, ...writers(options.xFormat, options.xFormatCode, writeNumber), scale: xScale },\n y: { title: yTitle, values: ys, ...writers(options.yFormat, options.yFormatCode, writeNumber), scale: yScale },\n z, zTitle, method,\n ...(options.zFormat === undefined ? {} : { zFormat: options.zFormat }),\n ...scaleOptions(options),\n });\n }\n\n /** The x axis: the table's columns, or a mesh's x positions in order. */\n get x(): SurfaceAxis {\n return this.#parts.x;\n }\n\n /** The y axis: the table's rows, or a mesh's y positions in order. */\n get y(): SurfaceAxis {\n return this.#parts.y;\n }\n\n /** A grid's values, one row per y value, `null` at a hole; empty for a mesh. */\n get z(): readonly (readonly (ChartValue | null)[])[] {\n return this.#parts.z;\n }\n\n /** What the values are, such as \"Volatility\". */\n get zTitle(): string {\n return this.#parts.zTitle;\n }\n\n /** The Consumer's writer of a value, if any. */\n get zFormat(): ((value: ChartValue) => string) | undefined {\n return this.#parts.zFormat;\n }\n\n /** The Excel format code the values are written by (ADR-0420), if any. */\n get zFormatCode(): string | undefined {\n return this.#parts.zFormatCode;\n }\n\n /** The method the interpolated values were made with, if the surface claims one. */\n get method(): string | undefined {\n return this.#parts.method;\n }\n\n /** Which values are interpolated, in the table's shape; absent with a method marks every value. */\n get interpolated(): readonly (readonly boolean[])[] | undefined {\n return this.#parts.interpolated;\n }\n\n /** The Consumer's Notes (ADR-0257). */\n get notes(): readonly string[] {\n return this.#parts.notes;\n }\n\n /** A mesh's nodes; absent for a grid (ADR-0311). */\n get nodes(): readonly SurfaceNode[] | undefined {\n return this.#parts.nodes;\n }\n\n /** A mesh's triangles; absent for a grid (ADR-0311). */\n get triangles(): readonly SurfaceTriangle[] | undefined {\n return this.#parts.triangles;\n }\n\n /** Whether the surface is a Consumer's triangle mesh rather than a grid (ADR-0311). */\n get isMesh(): boolean {\n return this.#parts.triangles !== undefined;\n }\n\n /** The vertical scale asked for (ADR-0312). */\n get zScale(): AxisScale {\n return this.#parts.zScale;\n }\n\n /** The value the colours diverge from, if any (ADR-0310). */\n get centre(): number | undefined {\n return this.#parts.centre;\n }\n\n /** The vertical scale as drawn: the one asked for, unless a value or the centre cannot lie on it. */\n get effectiveZScale(): AxisScale {\n return this.#zScaleNote() === undefined ? this.#parts.zScale : 'proportional';\n }\n\n /** The lines shown under the surface: the Consumer's Notes, the method (ADR-0257), and why a logarithmic scale stays proportional (ADR-0312). */\n get allNotes(): readonly string[] {\n const lines = [...this.#parts.notes];\n if (this.#parts.method !== undefined) {\n lines.push(`Interpolated by the Consumer: ${this.#parts.method}.`);\n }\n const note = this.#zScaleNote();\n if (note !== undefined) {\n lines.push(note);\n }\n return Object.freeze(lines);\n }\n\n /** How many points the surface holds: a grid's points, row by row, or a mesh's nodes. */\n get nodeCount(): number {\n const nodes = this.#parts.nodes;\n return nodes === undefined ? this.#parts.x.values.length * this.#parts.y.values.length : nodes.length;\n }\n\n /** Whether a grid's value at x index `x` and y index `y` is interpolated; a mesh has no grid indices, and is refused. */\n isInterpolated(x: number, y: number): boolean {\n this.#gridOnly();\n const marks = this.#parts.interpolated;\n return this.#parts.method !== undefined && (marks === undefined || elementAt(elementAt(marks, y), x));\n }\n\n /** A grid's value at x index `x` and y index `y`, or `null` at a hole; a mesh has no grid indices, and is refused. */\n at(x: number, y: number): ChartValue | null {\n this.#gridOnly();\n return elementAt(elementAt(this.#parts.z, y), x);\n }\n\n /** The point at `index`, counted as `nodeCount` counts: its x and y as the axes hold them, and its value, or `null`. */\n node(index: number): readonly [x: SurfaceValue, y: SurfaceValue, z: ChartValue | null] {\n const nodes = this.#parts.nodes;\n if (nodes !== undefined) {\n const n = elementAt(nodes, index);\n return [n.x, n.y, n.z];\n }\n const count = this.#parts.x.values.length;\n const i = index % count;\n const j = Math.trunc(index / count);\n return [elementAt(this.#parts.x.values, i), elementAt(this.#parts.y.values, j), elementAt(elementAt(this.#parts.z, j), i)];\n }\n\n /** Whether the point at `index` is interpolated; a mesh's nodes are its values. */\n isInterpolatedNode(index: number): boolean {\n const count = this.#parts.x.values.length;\n return this.#parts.nodes === undefined && this.isInterpolated(index % count, Math.trunc(index / count));\n }\n\n /**\n * A tick on the vertical axis or the colour bar, and the centre the colours diverge from: through the code, as\n * the values are, or plainly; a format, written for the values a column holds, leaves them plain (ADR-0420).\n *\n * @internal\n */\n writeZTick(value: number): string {\n const code = this.#parts.zCode;\n return code === undefined ? tickText(value) : code.format(value, 'invariant');\n }\n\n /** Writes a value through the format or the code, or invariantly. */\n writeZ(value: ChartValue): string {\n const { zFormat: format, zCode: code } = this.#parts;\n return format !== undefined ? format(value) : code === undefined ? invariantText(value) : code.format(value, 'invariant');\n }\n\n /**\n * The values the surface holds, holes left out.\n *\n * @internal\n */\n present(): ChartValue[] {\n const nodes = this.#parts.nodes;\n const all = nodes === undefined ? this.#parts.z.flat() : nodes.map(n => n.z);\n return all.filter(v => v !== null);\n }\n\n /**\n * The slice as a 2D chart (ADR-0274): the values along the other axis, read exactly \u2014 as categories on\n * an evenly spaced axis, as numbers on the axis' own scale otherwise (ADR-0312). A hole is a gap. A\n * mesh's slice cuts its triangles and reads between nodes linearly on them, which it says (ADR-0311).\n * `undefined` when the slice's value is not on this surface.\n */\n sliceChart(slice: SurfaceSlice): ChartDefinition | undefined {\n const onX = slice.axis === 'x';\n const fixedAxis = onX ? this.x : this.y;\n const along = onX ? this.y : this.x;\n const zName = nameOr(this.zTitle, 'Value');\n const format = this.zFormat;\n const formatCode = this.zFormatCode;\n if (this.isMesh) {\n const runs = this.cut(slice);\n if (runs === undefined || runs.length === 0) {\n return undefined;\n }\n const cut: ChartPoint[] = [];\n for (const run of runs) {\n // A gap between runs is a point without a value, where no triangle is.\n const last = cut.at(-1);\n if (last !== undefined) {\n cut.push({ x: (last.x + elementAt(run, 0).along) / 2, y: null });\n }\n cut.push(...run.map(p => ({ x: p.along, y: p.z })));\n }\n const series: ChartSeriesOptions = {\n id: 'slice', name: `${zName} at ${fixedAxis.writeValue(slice.value)}`, kind: 'level', points: cut, fromZero: false, interpolated: true,\n segments: [{ from: elementAt(cut, 0).x, to: elementAt(cut, cut.length - 1).x, method: trianglesMethod, extrapolated: false }],\n ...(format === undefined ? {} : { format }),\n ...(formatCode === undefined ? {} : { formatCode }),\n };\n return new ChartDefinition({ axis: numberAxis(along), series: [series] });\n }\n\n const at = fixedAxis.indexOf(slice.value);\n if (at < 0) {\n return undefined;\n }\n const byValue = along.scale !== 'categories';\n const count = along.values.length;\n const points = Array.from({ length: count }, (_, k) => ({ x: byValue ? along.number(k) : k, y: onX ? this.at(at, k) : this.at(k, at) }));\n const interpolated = Array.from({ length: count }, (_, k) => (onX ? this.isInterpolated(at, k) : this.isInterpolated(k, at))).some(v => v);\n const method = this.method;\n const series: ChartSeriesOptions = {\n id: 'slice', name: `${zName} at ${fixedAxis.write(at)}`, kind: 'level', points, fromZero: false,\n ...(format === undefined ? {} : { format }),\n ...(formatCode === undefined ? {} : { formatCode }),\n ...(interpolated && method !== undefined ? {\n interpolated: true,\n segments: [{ from: byValue ? along.number(0) : 0, to: byValue ? along.number(count - 1) : count - 1, method, extrapolated: false }],\n } : {}),\n };\n const axis: ChartAxisOptions = byValue ? numberAxis(along)\n : { values: 'labels', title: along.title, labels: Array.from({ length: count }, (_, k) => along.write(k)) };\n return new ChartDefinition({ axis, series: [series] });\n }\n\n /**\n * A mesh cut at the slice's value (ADR-0311): the runs of positions along the other axis and the values\n * there, linear on each triangle, broken where no triangle is. `undefined` when the value is not a number\n * within the mesh's positions.\n *\n * @internal\n */\n cut(slice: SurfaceSlice): readonly (readonly { readonly along: number; readonly z: ChartValue }[])[] | undefined {\n const nodes = this.#parts.nodes;\n const triangles = this.#parts.triangles;\n if (nodes === undefined || triangles === undefined || typeof slice.value !== 'number') {\n return undefined;\n }\n const c = slice.value;\n const onX = slice.axis === 'x';\n const fixedOf = (n: SurfaceNode): number => (onX ? n.x : n.y);\n const alongOf = (n: SurfaceNode): number => (onX ? n.y : n.x);\n const fixedAxis = onX ? this.x : this.y;\n if (c < fixedAxis.number(0) || c > fixedAxis.number(fixedAxis.values.length - 1)) {\n return undefined;\n }\n const alongAxis = onX ? this.y : this.x;\n const span = Math.max(alongAxis.number(alongAxis.values.length - 1) - alongAxis.number(0), Number.MIN_VALUE);\n const segments: (readonly [from: CutPoint, to: CutPoint])[] = [];\n for (const t of triangles) {\n const corners = [elementAt(nodes, t.a), elementAt(nodes, t.b), elementAt(nodes, t.c)];\n if (corners.some(n => n.z === null)) {\n continue;\n }\n const hits: CutPoint[] = [];\n for (let e = 0; e < 3; e++) {\n const p = elementAt(corners, e);\n const q = elementAt(corners, (e + 1) % 3);\n const pz = p.z;\n const qz = q.z;\n if (pz === null || qz === null) {\n throw new Error('Internal: a corner without a value was passed over above.');\n }\n const dp = fixedOf(p) - c;\n const dq = fixedOf(q) - c;\n if (dp === 0) {\n hits.push({ along: alongOf(p), z: pz });\n }\n if (dp * dq < 0) {\n const w = dp / (dp - dq);\n hits.push({ along: alongOf(p) + w * (alongOf(q) - alongOf(p)), z: toNumber(pz) + w * (toNumber(qz) - toNumber(pz)) });\n }\n }\n if (hits.length < 2) {\n continue;\n }\n const lo = hits.reduce((m, h) => (h.along < m.along ? h : m));\n const hi = hits.reduce((m, h) => (h.along > m.along ? h : m));\n if (hi.along > lo.along) {\n segments.push([lo, hi]);\n }\n }\n\n // Neighbouring triangles meet on an edge, so their segments meet end to start; one that starts past the\n // run's end begins another run, the gap between them a hole.\n const runs: CutPoint[][] = [];\n const tolerance = 1e-9 * span;\n for (const [from, to] of segments.toSorted(bySegment)) {\n const run = runs.at(-1);\n const end = run?.at(-1);\n if (run !== undefined && end !== undefined && from.along <= end.along + tolerance) {\n if (to.along > end.along + tolerance) {\n run.push(to);\n }\n continue;\n }\n runs.push([from, to]);\n }\n return runs;\n }\n\n #gridOnly(): void {\n if (this.isMesh) {\n throw new Error('A mesh has no grid to index: read its points through node, counted as nodeCount counts them (ADR-0311).');\n }\n }\n\n // Why a logarithmic vertical scale stays proportional, or `undefined` when it does not.\n #zScaleNote(): string | undefined {\n if (this.#parts.zScale !== 'logarithmic') {\n return undefined;\n }\n const low = this.present().reduce((m, v) => (toNumber(v) < toNumber(m) ? v : m));\n if (!(toNumber(low) > 0)) {\n return `The vertical scale stays proportional: ${nameOr(this.zTitle, 'the values')} reach ${this.writeZ(low)}, which a logarithmic scale cannot place.`;\n }\n const centre = this.#parts.centre;\n if (centre !== undefined && !(centre > 0)) {\n return `The vertical scale stays proportional: the colours diverge from ${this.writeZTick(centre)}, which a logarithmic scale cannot place.`;\n }\n return undefined;\n }\n}\n\n// A sampled axis' value written as a tick is, where the Consumer gives no format.\nfunction writeNumber(value: SurfaceValue): string {\n return typeof value === 'number' ? tickText(value) : value;\n}\n\n// Segments in order of their start, then of their end.\nfunction bySegment(s: readonly [CutPoint, CutPoint], u: readonly [CutPoint, CutPoint]): number {\n const start = s[0].along - u[0].along;\n return start !== 0 ? start : s[1].along - u[1].along;\n}\n\n// The scale and centre a surface is asked for, checked (ADR-0310, ADR-0312).\nfunction scaled(options: SurfaceScaleOptions): Pick<SurfaceParts, 'zScale' | 'centre'> {\n const { zScale = 'proportional', centre } = options;\n if (zScale === 'categories') {\n throw new ChartRefusedError('A surface\\'s values are placed proportionally or logarithmically, never as categories.');\n }\n if (centre !== undefined && !Number.isFinite(centre)) {\n throw new ChartRefusedError('The value the colours diverge from is a finite number.');\n }\n return { zScale, centre };\n}\n\nfunction scaleOptions(options: SurfaceScaleOptions): SurfaceScaleOptions {\n return {\n ...(options.zFormatCode === undefined ? {} : { zFormatCode: options.zFormatCode }),\n ...(options.zScale === undefined ? {} : { zScale: options.zScale }),\n ...(options.centre === undefined ? {} : { centre: options.centre }),\n };\n}\n\nfunction axisOptions(axis: SurfaceAxis): SurfaceAxisOptions {\n const { format, formatCode } = axis;\n return {\n title: axis.title, values: axis.values, scale: axis.scale, ...(format === undefined ? {} : { format }),\n ...(formatCode === undefined ? {} : { formatCode }),\n };\n}\n\n// An axis' writers a factory was handed: its format, or its code, or the factory's own writing where it has one.\nfunction writers(format: ((value: SurfaceValue) => string) | undefined, formatCode: string | undefined,\n own?: (value: SurfaceValue) => string): Pick<SurfaceAxisOptions, 'format' | 'formatCode'> {\n if (format !== undefined) {\n return { format, ...(formatCode === undefined ? {} : { formatCode }) };\n }\n if (formatCode !== undefined) {\n return { formatCode };\n }\n return own === undefined ? {} : { format: own };\n}\n\n// An axis' value named in a refusal, as C#'s `ChartCodes` names it.\nfunction describe(value: SurfaceValue): string {\n return typeof value === 'string' ? `the text \"${value}\"` : `the number ${roundTrip(value)}`;\n}\n\n// A surface axis' code read, or refused by name where it cannot write the axis' values (ADR-0420), as C#'s\n// `ChartCodes.CheckSurfaceAxis`.\nfunction checkAxisCode(axis: SurfaceAxis, code: string): FormatCode {\n const name = axis.title.length > 0 ? `the surface axis '${axis.title}'` : 'a surface axis';\n const reading = readCode(code);\n if (typeof reading === 'string') {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} ${reading}.`);\n }\n if (axis.format !== undefined) {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} stands beside its Format: it would write one value two ways.`);\n }\n // A surface axis here holds numbers and texts: a date code has no date to write.\n const other = axis.values.find(v => reading.isDate || typeof v !== 'number');\n if (other !== undefined) {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} writes ${reading.isDate ? 'dates' : 'numbers'}, and the axis holds ${describe(other)}.`);\n }\n // A grid line, a slice and a tooltip are named by the text: two values written alike could not be told apart.\n const written = new Map<string, number>();\n for (const value of axis.values.filter(v => typeof v === 'number')) {\n const text = reading.format(value, 'invariant');\n const before = written.get(text);\n if (before !== undefined) {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} writes ${describe(before)} and ${describe(value)} alike, as \"${text}\".`);\n }\n written.set(text, value);\n }\n return reading;\n}\n\n// A surface's code for its values read, or refused by name (ADR-0420), as C#'s `ChartCodes.CheckZ`.\nfunction zCoded(options: SurfaceScaleOptions & { readonly zFormat?: (value: ChartValue) => string }, zTitle: string): Pick<SurfaceParts, 'zFormatCode' | 'zCode'> {\n const code = options.zFormatCode;\n if (code === undefined) {\n return { zFormatCode: undefined, zCode: undefined };\n }\n const name = zTitle.length > 0 ? `the surface's '${zTitle}'` : 'the surface\\'s values';\n const reading = readCode(code);\n if (typeof reading === 'string') {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} ${reading}.`);\n }\n if (options.zFormat !== undefined) {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} stands beside its ZFormat: it would write one value two ways.`);\n }\n if (reading.isDate) {\n throw new ChartRefusedError(`The format code \"${code}\" of ${name} writes dates, and its values are numbers.`);\n }\n return { zFormatCode: code, zCode: reading };\n}\n\nfunction numberAxis(along: SurfaceAxis): ChartAxisOptions {\n return { values: 'numbers', title: along.title, scale: along.scale, format: position => along.writeTick(position) };\n}\n\n// The distinct values in order: numbers by value, texts by their code units. A list of both cannot be ordered.\nfunction ordered(values: readonly SurfaceValue[]): SurfaceValue[] {\n const unique = [...new Set(values)];\n if (unique.every(v => typeof v === 'number')) {\n return unique.toSorted((a, b) => a - b);\n }\n if (unique.every(v => typeof v === 'string')) {\n return unique.toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n }\n throw new TypeError('An axis\\' values are all numbers or all texts; one of each cannot be put in order.');\n}\n\nfunction validateGrid(x: SurfaceAxis, y: SurfaceAxis, z: readonly (readonly (ChartValue | null)[])[], method: string | undefined,\n interpolated: readonly (readonly boolean[])[] | undefined): void {\n const nx = x.values.length;\n const ny = y.values.length;\n if (nx < 2 || ny < 2) {\n throw new ChartRefusedError(`A surface needs two ${nameOr(x.title, 'x')} values and two ${nameOr(y.title, 'y')} values at least; this one has ${String(nx)} and ${String(ny)}.`);\n }\n if (z.length !== ny) {\n throw new ChartRefusedError(`The surface's table has ${String(z.length)} rows for ${String(ny)} ${nameOr(y.title, 'y')} values; it needs one row per value.`);\n }\n z.forEach((row, j) => {\n if (row.length !== nx) {\n throw new ChartRefusedError(`The surface's row at ${nameOr(y.title, 'y')} ${y.write(j)} has ${String(row.length)} values for ${String(nx)} ${nameOr(x.title, 'x')} values; a hole is handed in as null, never left out.`);\n }\n });\n distinct(x, 'x');\n distinct(y, 'y');\n placed(x, 'x');\n placed(y, 'y');\n if (z.every(row => row.every(v => v === null))) {\n throw new ChartRefusedError('The surface holds no value.');\n }\n if (interpolated !== undefined) {\n if (method === undefined) {\n throw new ChartRefusedError('The surface marks values interpolated but names no method; the chart says how its values were made (ADR-0257).');\n }\n if (interpolated.length !== ny || interpolated.some(r => r.length !== nx)) {\n throw new ChartRefusedError('The surface\\'s marks of interpolated values need the table\\'s shape: one row per y value, one mark per x value.');\n }\n }\n}\n\nfunction validateMesh(x: SurfaceAxis, y: SurfaceAxis, nodes: readonly SurfaceNode[], triangles: readonly SurfaceTriangle[]): void {\n if (triangles.length === 0) {\n throw new ChartRefusedError('A mesh needs a triangle (ADR-0311).');\n }\n // A place is keyed as C# compares a pair of doubles: 0 and -0 alike.\n const places = new Map<string, number>();\n nodes.forEach((n, k) => {\n const key = `${String(n.x)},${String(n.y)}`;\n const first = places.get(key);\n if (first !== undefined) {\n throw new ChartRefusedError(`Nodes ${String(first)} and ${String(k)} both lie at ${nameOr(x.title, 'x')} ${x.writeTick(n.x)}, ${nameOr(y.title, 'y')} ${y.writeTick(n.y)}; a place in the plane holds one value.`);\n }\n places.set(key, k);\n });\n const xs = nodes.map(n => n.x);\n const ys = nodes.map(n => n.y);\n // Folded, not spread: a Consumer's mesh may hold more nodes than a call takes arguments.\n const span = Math.max(greatest(xs) - least(xs), greatest(ys) - least(ys));\n triangles.forEach((t, i) => {\n const { a, b, c } = t;\n const holds = (k: number): boolean => Number.isInteger(k) && k >= 0 && k < nodes.length;\n if (!holds(a) || !holds(b) || !holds(c)) {\n throw new ChartRefusedError(`Triangle ${String(i)} names a node the mesh does not hold; it has ${String(nodes.length)} nodes.`);\n }\n const p = elementAt(nodes, a);\n const q = elementAt(nodes, b);\n const r = elementAt(nodes, c);\n const area = (q.x - p.x) * (r.y - p.y) - (r.x - p.x) * (q.y - p.y);\n if (!(Math.abs(area) > 1e-12 * span * span)) {\n throw new ChartRefusedError(`Triangle ${String(i)} has no area: its corners ${String(a)}, ${String(b)} and ${String(c)} lie on one line, so it holds no plane to draw.`);\n }\n });\n placed(x, 'x');\n placed(y, 'y');\n if (nodes.every(n => n.z === null)) {\n throw new ChartRefusedError('The surface holds no value.');\n }\n}\n\n// An axis that places its values by value holds numbers, rising, above zero when logarithmic (ADR-0312).\nfunction placed(axis: SurfaceAxis, fallback: string): void {\n if (axis.scale === 'categories') {\n return;\n }\n const kind = axis.scale === 'logarithmic' ? 'logarithmic' : 'proportional';\n let previous: number | undefined;\n axis.values.forEach((v, i) => {\n if (typeof v !== 'number') {\n throw new ChartRefusedError(`${nameOr(axis.title, fallback)} ${axis.write(i)} is not a number, which a ${kind} axis cannot place; leave the axis evenly spaced (ADR-0312).`);\n }\n if (axis.scale === 'logarithmic' && !(v > 0)) {\n throw new ChartRefusedError(`${nameOr(axis.title, fallback)} ${axis.write(i)} is at or below zero, which a logarithmic axis cannot place: every position must be above zero.`);\n }\n if (previous !== undefined && !(v > previous)) {\n throw new ChartRefusedError(`${nameOr(axis.title, fallback)} ${axis.write(i)} comes after ${axis.write(i - 1)}; a ${kind} axis' values rise along it.`);\n }\n previous = v;\n });\n}\n\n// A Set compares as C#'s Equals does: NaN alike with NaN, 0 with -0.\nfunction distinct(axis: SurfaceAxis, fallback: string): void {\n const seen = new Set<SurfaceValue>();\n axis.values.forEach((v, i) => {\n if (seen.has(v)) {\n throw new ChartRefusedError(`${nameOr(axis.title, fallback)} ${axis.write(i)} appears twice; each grid line needs a value of its own.`);\n }\n seen.add(v);\n });\n}\n\n// The entry a map holds for a key it was built from.\nfunction elementOf<K, V>(map: ReadonlyMap<K, V>, key: K): V {\n const value = map.get(key);\n if (value === undefined) {\n throw new Error(`Internal: ${String(key)} is not among the keys the map was built from.`);\n }\n return value;\n}\n", "// What a surface's 3D entry is handed to draw (ADR-0255): the points placed on the floor and the vertical\n// scale, the faces with their colour bands, the floor's lines and the vertical scale's ticks, and the colour\n// bar. The core decides all of it \u2014 where each value lies on each scale (ADR-0312) and how each face is\n// coloured (ADR-0310) \u2014 and the entry only projects, orders and draws it. The port of the C# engine's\n// `SurfaceMesh`, held to it by the shared cases under tests/cases/chart/ (ADR-0370).\nimport { elementAt } from './must';\nimport { firstBy, greatest, least, roundToDigits } from './numbers';\nimport type { SurfaceAxis, SurfaceDefinition, SurfaceSlice, SurfaceValue } from './surface';\nimport { decades, logSteps, nice, steps } from './ticks';\nimport { toNumber } from './values';\n\n/** A labelled position on one of a surface's scales: its value there, and its label or `null` where labels would crowd. */\nexport interface SurfaceTick {\n /** A fraction of the floor for x and y; a value on the vertical scale for z and the colour bar. */\n readonly value: number;\n /** The label, or `null` for a line drawn unlabelled. */\n readonly label: string | null;\n}\n\n/** A point of a surface as the 3D entry places it. */\nexport interface SurfaceMeshNode {\n /** Its place across the floor, 0 to 1. */\n readonly x: number;\n /** Its place along the floor, 0 to 1. */\n readonly y: number;\n /** Its value on the vertical scale (its logarithm on a logarithmic one), or `null` at a hole. */\n readonly z: number | null;\n /** Whether its value is interpolated, so the entry draws it no dot (ADR-0257). */\n readonly interpolated: boolean;\n}\n\n/** A face the 3D entry draws: its corners, as indices of the nodes, and its colour band. */\nexport interface SurfaceFace {\n /** Four corners for a grid's cell, three for a mesh's triangle. */\n readonly corners: readonly number[];\n /** Its colour band, 0 to `surfaceBandCount` - 1. */\n readonly band: number;\n}\n\n/** The colour bar beside a surface (ADR-0310). */\nexport interface SurfaceColourBar {\n /** The value at the foot of the lowest band, on the vertical scale. */\n readonly from: number;\n /** The value at the head of the highest band. */\n readonly to: number;\n /** The labelled values along it. */\n readonly ticks: readonly SurfaceTick[];\n /** Whether the bands diverge from a centre, which the middle band holds. */\n readonly diverging: boolean;\n /** How many bands it is drawn in: `surfaceBandCount`, handed to the entry so it holds no copy. */\n readonly bands: number;\n}\n\n/** A point of a slice's line on the surface, placed as a mesh node is. */\nexport interface SurfaceMeshPoint {\n /** Its place across the floor, 0 to 1. */\n readonly x: number;\n /** Its place along the floor, 0 to 1. */\n readonly y: number;\n /** Its value on the vertical scale. */\n readonly z: number;\n}\n\n/** What the 3D entry is handed to draw a surface (ADR-0255). */\nexport interface SurfaceMesh {\n /** The x axis' title. */\n readonly xTitle: string;\n /** The y axis' title. */\n readonly yTitle: string;\n /** The values' title. */\n readonly zTitle: string;\n /** The points, counted as the definition's `nodeCount` counts them. */\n readonly nodes: readonly SurfaceMeshNode[];\n /** The faces to draw; a face with a hole at a corner is no face. */\n readonly faces: readonly SurfaceFace[];\n /** A grid's lines along x, one per y value, as node indices; empty for a mesh. */\n readonly rows: readonly (readonly number[])[];\n /** A grid's lines along y, one per x value, as node indices; empty for a mesh. */\n readonly columns: readonly (readonly number[])[];\n /** The floor's lines across x. */\n readonly xLines: readonly SurfaceTick[];\n /** The floor's lines along y. */\n readonly yLines: readonly SurfaceTick[];\n /** The bottom of the vertical scale. */\n readonly zMin: number;\n /** The top of the vertical scale. */\n readonly zMax: number;\n /** The vertical scale's ticks. */\n readonly zTicks: readonly SurfaceTick[];\n /** The colour bar. */\n readonly bar: SurfaceColourBar;\n /** How many points are holes. */\n readonly holes: number;\n}\n\n/**\n * How many colour bands a face is coloured from, low to high; each is a Visual Token, `--ex-chart-heat-0`\n * on, or `--ex-chart-diverge-0` on when the colours diverge (ADR-0310).\n */\nexport const surfaceBandCount = 9;\n\nconst half = Math.trunc(surfaceBandCount / 2);\n\nconst tick = (value: number, label: string | null): SurfaceTick => Object.freeze({ value, label });\n\nconst point = (x: number, y: number, z: number): SurfaceMeshPoint => Object.freeze({ x, y, z });\n\n/** The mesh of `definition`. */\nexport function surfaceMesh(definition: SurfaceDefinition): SurfaceMesh {\n const frame = new Frame(definition);\n const nodes: SurfaceMeshNode[] = Array.from({ length: definition.nodeCount }, (_, k) => {\n const [x, y, z] = definition.node(k);\n return Object.freeze({ x: frame.atX(k, x), y: frame.atY(k, y), z: z === null ? null : frame.scale(toNumber(z)), interpolated: definition.isInterpolatedNode(k) });\n });\n const present = nodes.flatMap(n => (n.z === null ? [] : [n.z]));\n const lo = least(present);\n const hi = greatest(present);\n\n let zMin: number;\n let zMax: number;\n let zTicks: readonly number[];\n if (frame.logarithmic) {\n const [dMin, dMax] = decades(10 ** lo, 10 ** hi);\n zMin = Math.log10(dMin);\n zMax = Math.log10(dMax);\n zTicks = logSteps(dMin, dMax).map(Math.log10);\n } else {\n const n = nice(lo, hi);\n zMin = n.min;\n zMax = n.max;\n zTicks = steps(n.min, n.max, n.step);\n }\n\n // A face is coloured by the mean of its corners on the vertical scale (ADR-0310): through the values'\n // own range, or by its distance from the centre, alike on both sides of it.\n const centre = definition.centre === undefined ? undefined : frame.scale(definition.centre);\n let reach = centre === undefined ? 0 : Math.max(Math.abs(hi - centre), Math.abs(lo - centre));\n if (centre !== undefined && reach === 0) {\n reach = frame.logarithmic || centre === 0 ? 1 : Math.abs(centre) / 10;\n }\n const band = (value: number): number => {\n if (centre !== undefined) {\n const t = (value - centre) / reach;\n const depth = Math.min(half, Math.floor(Math.abs(t) * surfaceBandCount / 2 + 0.5));\n return half + Math.sign(t) * depth;\n }\n const u = hi > lo ? (value - lo) / (hi - lo) : 0.5;\n return Math.min(Math.max(Math.floor(u * surfaceBandCount), 0), surfaceBandCount - 1);\n };\n\n const nx = definition.isMesh ? 0 : definition.x.values.length;\n const ny = definition.isMesh ? 0 : definition.y.values.length;\n const triangles = definition.triangles;\n const cornerSets = triangles === undefined ? cells(nx, ny) : triangles.map(t => [t.a, t.b, t.c]);\n const faces: SurfaceFace[] = [];\n for (const corners of cornerSets) {\n const zs = corners.flatMap(k => {\n const z = elementAt(nodes, k).z;\n return z === null ? [] : [z];\n });\n if (zs.length < corners.length) {\n continue;\n }\n const sum = zs.reduce((total, z) => total + z, 0);\n faces.push(Object.freeze({ corners: Object.freeze(corners), band: band(sum / corners.length) }));\n }\n\n const away = (v: number): number => (frame.logarithmic || v === 0 ? 1 : Math.abs(v) / 10);\n const [barFrom, barTo] = centre !== undefined ? [centre - reach, centre + reach]\n : hi > lo ? [lo, hi] : [lo - away(lo), hi + away(hi)];\n const bar: SurfaceColourBar = Object.freeze({\n from: barFrom, to: barTo, ticks: frame.barTicks(barFrom, barTo, centre), diverging: centre !== undefined, bands: surfaceBandCount,\n });\n\n const rows = Array.from({ length: ny }, (_, j) => Object.freeze(Array.from({ length: nx }, (__, i) => j * nx + i)));\n const columns = Array.from({ length: nx }, (_, i) => Object.freeze(Array.from({ length: ny }, (__, j) => j * nx + i)));\n\n return Object.freeze({\n xTitle: definition.x.title, yTitle: definition.y.title, zTitle: definition.zTitle,\n nodes: Object.freeze(nodes), faces: Object.freeze(faces), rows: Object.freeze(rows), columns: Object.freeze(columns),\n xLines: frame.floorLines(definition.x), yLines: frame.floorLines(definition.y), zMin, zMax,\n zTicks: Object.freeze(zTicks.map(v => tick(v, frame.label(v)))), bar, holes: nodes.filter(n => n.z === null).length,\n });\n}\n\nfunction cells(nx: number, ny: number): number[][] {\n const result: number[][] = [];\n for (let j = 0; j < ny - 1; j++) {\n for (let i = 0; i < nx - 1; i++) {\n result.push([j * nx + i, j * nx + i + 1, (j + 1) * nx + i + 1, (j + 1) * nx + i]);\n }\n }\n return result;\n}\n\n/**\n * The slice's line on the surface, placed as the mesh's points are, in runs broken at a hole: along a\n * grid's line, or across a mesh's triangles where the slice cuts them (ADR-0311). Empty when the slice is\n * not on this surface.\n */\nexport function surfaceSlicePath(definition: SurfaceDefinition, slice: SurfaceSlice): readonly (readonly SurfaceMeshPoint[])[] {\n const frame = new Frame(definition);\n const onX = slice.axis === 'x';\n const runs: (readonly SurfaceMeshPoint[])[] = [];\n if (definition.isMesh) {\n const cut = definition.cut(slice);\n if (cut === undefined || typeof slice.value !== 'number') {\n return runs;\n }\n const fixedAt = onX ? frame.placeX(slice.value) : frame.placeY(slice.value);\n for (const run of cut) {\n runs.push(Object.freeze(run.map(p => (onX\n ? point(fixedAt, frame.placeY(p.along), frame.scale(toNumber(p.z)))\n : point(frame.placeX(p.along), fixedAt, frame.scale(toNumber(p.z)))))));\n }\n return Object.freeze(runs);\n }\n\n const fixedAxis = onX ? definition.x : definition.y;\n const index = fixedAxis.indexOf(slice.value);\n if (index < 0) {\n return runs;\n }\n const nx = definition.x.values.length;\n const count = onX ? definition.y.values.length : nx;\n let current: SurfaceMeshPoint[] = [];\n for (let k = 0; k < count; k++) {\n const node = onX ? k * nx + index : index * nx + k;\n const [x, y, z] = definition.node(node);\n if (z === null) {\n if (current.length > 0) {\n runs.push(Object.freeze(current));\n }\n current = [];\n continue;\n }\n current.push(point(frame.atX(node, x), frame.atY(node, y), frame.scale(toNumber(z))));\n }\n if (current.length > 0) {\n runs.push(Object.freeze(current));\n }\n return Object.freeze(runs);\n}\n\n// The least distance, as a fraction of the floor, between two labels on an axis placed by value.\nconst labelRoom = 1 / 12;\n\n/**\n * The surface said in words, for a screen reader (ADR-0275's shape): what it is of, its grid or its mesh,\n * the range of its values, its holes, and how it is coloured and scaled; then the Consumer's description.\n */\nexport function surfaceSummary(definition: SurfaceDefinition, title?: string, description?: string): string {\n const present = definition.present();\n const lo = firstBy(present, toNumber, (a, b) => a < b);\n const hi = firstBy(present, toNumber, (a, b) => a > b);\n const holes = definition.nodeCount - present.length;\n const { x, y, nodes, triangles } = definition;\n const z = blank(definition.zTitle) ? 'Values' : definition.zTitle;\n const head = blank(title) ? '3D surface' : `${title}, a 3D surface`;\n const shape = nodes !== undefined && triangles !== undefined\n ? `a mesh of ${String(nodes.length)} nodes and ${String(triangles.length)} triangles`\n : `${String(x.values.length)} by ${String(y.values.length)} points`;\n const hole = definition.isMesh\n ? `${holes === 1 ? 'node' : 'nodes'} without a value`\n : `${holes === 1 ? 'hole' : 'holes'} where the data has no value`;\n const centre = definition.centre;\n const method = definition.method;\n const text = `${head} of ${z} over ${axisLabel(x, 'x')} from ${x.write(0)} to ${x.write(x.values.length - 1)} and ${axisLabel(y, 'y')} from ${y.write(0)} to ${y.write(y.values.length - 1)}`\n + `; ${shape}, from ${definition.writeZ(lo)} to ${definition.writeZ(hi)}`\n + (holes === 0 ? '.' : `, with ${String(holes)} ${hole}.`)\n + (centre === undefined ? '' : ` Coloured by distance from ${definition.writeZTick(centre)}, below and above.`)\n + (definition.effectiveZScale === 'logarithmic' ? ' The vertical scale is logarithmic.' : '')\n + (method === undefined ? '' : ` Interpolated by the Consumer: ${method}.`);\n return blank(description) ? text : `${text} ${description}`;\n}\n\nfunction blank(text: string | undefined): boolean {\n return text === undefined || text.trim() === '';\n}\n\nfunction axisLabel(axis: SurfaceAxis, fallback: string): string {\n return axis.title.trim() === '' ? fallback : axis.title;\n}\n\n// Where each value lies on each of the surface's scales (ADR-0312).\nclass Frame {\n readonly #definition: SurfaceDefinition;\n readonly logarithmic: boolean;\n\n constructor(definition: SurfaceDefinition) {\n this.#definition = definition;\n this.logarithmic = definition.effectiveZScale === 'logarithmic';\n }\n\n scale(value: number): number {\n return this.logarithmic ? Math.log10(value) : value;\n }\n\n atX(node: number, value: SurfaceValue): number {\n const d = this.#definition;\n const count = d.x.values.length;\n return d.x.scale === 'categories' && !d.isMesh ? even(node % count, count) : this.placeX(numberOf(value));\n }\n\n atY(node: number, value: SurfaceValue): number {\n const d = this.#definition;\n return d.y.scale === 'categories' && !d.isMesh\n ? even(Math.trunc(node / d.x.values.length), d.y.values.length)\n : this.placeY(numberOf(value));\n }\n\n placeX(value: number): number {\n return place(this.#definition.x, value);\n }\n\n placeY(value: number): number {\n return place(this.#definition.y, value);\n }\n\n // A grid has a line at each of its values: evenly spaced, labelled where twelve fit; placed by value,\n // labelled where a label does not crowd the last one. A mesh has no lines of its own, so its floor's are\n // at round numbers, as a 2D number axis' are (ADR-0312).\n floorLines(axis: SurfaceAxis): readonly SurfaceTick[] {\n const n = axis.values.length;\n const mesh = this.#definition.isMesh;\n if (!mesh && axis.scale === 'categories') {\n const step = Math.ceil(n / 12);\n return Object.freeze(Array.from({ length: n }, (_, i) => tick(even(i, n), i % step === 0 ? axis.write(i) : null)));\n }\n if (!mesh) {\n const lines: SurfaceTick[] = [];\n let last = -Infinity;\n for (let i = 0; i < n; i++) {\n const at = place(axis, axis.number(i));\n const room = at - last >= labelRoom;\n lines.push(tick(at, room ? axis.write(i) : null));\n if (room) {\n last = at;\n }\n }\n return Object.freeze(lines);\n }\n const min = axis.number(0);\n const max = axis.number(n - 1);\n if (!(max > min)) {\n return Object.freeze([tick(0.5, axis.writeTick(min))]);\n }\n const ticks = axis.scale === 'logarithmic' ? logSteps(min, max) : niceWithin(min, max);\n return Object.freeze(ticks.map(t => tick(place(axis, t), axis.writeTick(t))));\n }\n\n barTicks(from: number, to: number, centre: number | undefined): readonly SurfaceTick[] {\n let ticks = this.logarithmic ? logSteps(10 ** from, 10 ** to).map(Math.log10) : [...niceWithin(from, to)];\n // The centre is always labelled, clearing the round numbers that would crowd its label; a bar whose\n // span holds fewer than two round numbers is labelled at its ends, so it always reads back.\n if (centre !== undefined) {\n ticks = [...ticks.filter(t => !(Math.abs(t - centre) < (to - from) / 20)), centre];\n }\n if (ticks.length < 2) {\n ticks = [...ticks.filter(t => Math.abs(t - from) >= (to - from) / 20 && Math.abs(t - to) >= (to - from) / 20), from, to];\n }\n return Object.freeze(ticks.toSorted((a, b) => a - b).map(t => tick(t, this.label(t))));\n }\n\n label(scaled: number): string {\n return this.#definition.writeZTick(this.logarithmic ? roundToDigits(10 ** scaled, 12) : scaled);\n }\n}\n\nfunction even(index: number, count: number): number {\n return index / (count - 1);\n}\n\nfunction place(axis: SurfaceAxis, value: number): number {\n const min = axis.number(0);\n const max = axis.number(axis.values.length - 1);\n if (!(max > min)) {\n return 0.5;\n }\n return axis.scale === 'logarithmic' ? Math.log(value / min) / Math.log(max / min) : (value - min) / (max - min);\n}\n\n// A position the definition placed by value, which it checked is a number.\nfunction numberOf(value: SurfaceValue): number {\n if (typeof value !== 'number') {\n throw new Error(`Internal: ${value} is placed by value, and is not a number.`);\n }\n return value;\n}\n\n// Round-number ticks between min and max, never past them.\nfunction niceWithin(min: number, max: number): readonly number[] {\n const n = nice(min, max);\n const slack = 1e-9 * Math.max(Math.abs(min), Math.abs(max));\n return steps(n.min, n.max, n.step).filter(t => t >= min - slack && t <= max + slack);\n}\n", "// A table a Chart Spec reads by column name (ADR-0320, ADR-0322): the chart's own seam, as C#'s `IChartData`\n// is the Engine's, so a host adapts its data to it, such as a Board's bound Snapshot.\n\n/**\n * A table a chart reads by column name (ADR-0320, ADR-0322), as C#'s `IChartData` is read. A value is\n * `null` where it is missing, and otherwise one of: a `number` (C#'s `double`), a `bigint` (a whole number,\n * held exactly as C#'s `int` and `long` are), a Snapshot's decimal `{ mantissa, scale }` (C#'s `decimal`),\n * a `string`, a `boolean`, a `Temporal.PlainDate` (C#'s `DateOnly`) or a `Temporal.PlainDateTime` (C#'s\n * `DateTime`). A date is recognised by its own tag and read through its own members, never through the\n * global `Temporal`, as `@ex-grid/data` reads one.\n */\nexport interface ChartData {\n /** The columns' names, in the table's order. */\n readonly columns: readonly string[];\n /** How many rows it has. */\n readonly rowCount: number;\n /** The value in `column` at `row`, as the table holds it; `null` where it is missing. */\n value(column: string, row: number): unknown;\n}\n\n/**\n * A table of columns held in memory, each `[name, values]`, all of one length: the reference implementation\n * of {@link ChartData}, as C#'s `ChartData.Of` is. Two columns of one name, or columns of different lengths,\n * are refused with a `TypeError`; reading a column it does not have, or a row past its last, with a\n * `RangeError`.\n */\nexport function chartDataOf(columns: readonly (readonly [name: string, values: readonly unknown[]])[]): ChartData {\n const byName = new Map<string, readonly unknown[]>();\n const [first] = columns;\n const rows = first === undefined ? 0 : first[1].length;\n for (const [name, values] of columns) {\n if (byName.has(name)) {\n throw new TypeError(`Two columns are named '${name}'.`);\n }\n if (values.length !== rows) {\n throw new TypeError(`Column '${name}' has ${String(values.length)} rows and '${first === undefined ? '' : first[0]}' has ${String(rows)}; a table's columns are one length.`);\n }\n byName.set(name, Object.freeze([...values]));\n }\n const names = Object.freeze(columns.map(c => c[0]));\n return Object.freeze({\n columns: names,\n rowCount: rows,\n value(column: string, row: number): unknown {\n const values = byName.get(column);\n if (values === undefined) {\n throw new RangeError(`The table has no column '${column}'; its columns are ${names.join(', ')}.`);\n }\n if (!Number.isInteger(row) || row < 0 || row >= values.length) {\n throw new RangeError(`Row ${String(row)} is outside a table of ${String(values.length)} rows.`);\n }\n return values[row];\n },\n });\n}\n", "// The Chart Spec (ADR-0320): a chart said in JSON, as an AI writes it and as a Board holds it as one of its\n// views (ADR-0340). It names Data Handles and their columns and never holds a number; each series says its\n// Series Kind; what cannot be drawn is refused with the path and the reason. The port of the C# engine's\n// `ChartSpec.Read`, held to it by the shared cases under tests/cases/chart/ (ADR-0370, sections 2 and 3):\n// the same refusals, at the same paths, in the same words, checked in the same order.\nimport {\n JsonNumber, JsonTextError, decimalText, isJsonArray, isJsonObject, jsonMember, jsonMemberNames, jsonRawText, readJsonText, ticksOfTemporal,\n type JsonObject, type JsonValue, type SnapshotDecimal,\n} from '@ex-grid/data';\nimport type { ChartData } from './chart-data';\nimport type { ChartSource, ChartSourceAnswer } from './chart-source';\nimport { dateOf, isoDate } from './day-numbers';\nimport { ChartDefinition } from './definition';\nimport { roundTrip } from './invariant-text';\nimport type {\n AxisScale, AxisSide, AxisValues, ChartAxisOptions, ChartEdge, ChartPoint, ChartSeriesOptions, ChartValue, IntervalBound, IntervalStyle,\n PointColour, PointDetail, PriceBar, SeriesInterval, SeriesKind, StepSide,\n} from './model';\nimport { elementAt } from './must';\nimport { SurfaceDefinition, type SurfaceNode, type SurfaceTriangle, type SurfaceValue } from './surface';\nimport { ChartRefusedError, toNumber } from './values';\n\n/**\n * A Chart Spec that cannot be drawn (ADR-0320): its message names the path in the spec and the reason, in\n * one sentence a host returns to the AI that wrote it, so the AI can correct the spec. The counterpart of\n * C#'s `ChartSpecRefusedException`.\n */\nexport class ChartSpecRefusedError extends Error {\n /** Where in the spec it was refused, such as `series[1].kind`; empty for the spec as a whole. */\n readonly path: string;\n\n /** A refusal at `path`, said by `message`. */\n constructor(path: string, message: string) {\n super(message);\n this.name = 'ChartSpecRefusedError';\n this.path = path;\n }\n}\n\n/** A Chart Spec read: its title, and the Chart Definition or the 3D surface it describes. */\nexport type ChartSpecReadingOptions =\n | {\n /** The chart's title, or empty when the spec gives none. */\n readonly title: string;\n /** The chart, its points read from the tables the spec names. */\n readonly definition: ChartDefinition;\n }\n | {\n /** The surface's title, or empty when the spec gives none. */\n readonly title: string;\n /** The surface, its points read from the tables the spec names (ADR-0274). */\n readonly surface: SurfaceDefinition;\n };\n\n/** A Chart Spec read: its title, and the Chart Definition or the 3D surface it describes. */\nexport class ChartSpecReading {\n readonly #title: string;\n readonly #definition: ChartDefinition | undefined;\n readonly #surface: SurfaceDefinition | undefined;\n\n /** A spec of series, or of a 3D surface, read. */\n constructor(options: ChartSpecReadingOptions) {\n this.#title = options.title;\n if ('surface' in options) {\n this.#definition = undefined;\n this.#surface = options.surface;\n } else {\n this.#definition = options.definition;\n this.#surface = undefined;\n }\n }\n\n /** The chart's title, or empty when the spec gives none. */\n get title(): string {\n return this.#title;\n }\n\n /**\n * The chart of series, its points read from the tables the spec names. A spec of a 3D surface, which\n * {@link ChartSpecReading.surface} holds, throws an `Error`: a chart of series read from it would be no\n * chart at all (spine rule 1).\n */\n get definition(): ChartDefinition {\n if (this.#definition === undefined) {\n throw new Error('This Chart Spec is of a 3D surface: draw its Surface with ExSurface; it has no chart of series.');\n }\n return this.#definition;\n }\n\n /** The 3D surface a spec of one describes (ADR-0274); `undefined` for a spec of series. */\n get surface(): SurfaceDefinition | undefined {\n return this.#surface;\n }\n}\n\n/** The version of the Chart Spec this reader reads. */\nexport const chartSpecVersion = 1;\n\nconst rootKeys = ['version', 'title', 'axis', 'series', 'surface', 'notes'];\nconst surfaceKeys = ['data', 'x', 'y', 'z', 'xTitle', 'yTitle', 'zTitle', 'xScale', 'yScale', 'zScale', 'centre', 'method', 'interpolated', 'key', 'triangles'];\nconst triangleKeys = ['data', 'a', 'b', 'c'];\nconst axisKeys = ['values', 'title', 'scale', 'packed'];\nconst seriesKeys = [\n 'id', 'name', 'kind', 'data', 'x', 'y', 'open', 'high', 'low', 'close', 'volume', 'label', 'panel', 'axis', 'fromZero', 'step', 'colour', 'size',\n 'key', 'edges', 'tooltip', 'interval', 'xInterval',\n];\nconst edgeKeys = ['data', 'from', 'to'];\nconst colourKeys = ['column', 'scale', 'centre', 'title'];\nconst sizeKeys = ['column', 'title'];\nconst intervalKeys = ['lower', 'upper', 'meaning', 'style'];\nconst priceColumns = ['open', 'high', 'low', 'close', 'volume'] as const;\n\n// The choices a key takes, in the order a refusal lists them.\nconst kinds: ReadonlyMap<string, SeriesKind> = new Map([\n ['level', 'level'], ['rateOverInterval', 'rateOverInterval'], ['amountPerPeriod', 'amountPerPeriod'], ['observation', 'observation'],\n ['priceRange', 'priceRange'],\n]);\nconst axisValueChoices: ReadonlyMap<string, AxisValues> = new Map([['dates', 'dates'], ['numbers', 'numbers'], ['labels', 'labels']]);\nconst axisScaleChoices: ReadonlyMap<string, AxisScale> = new Map([['proportional', 'proportional'], ['categories', 'categories'], ['logarithmic', 'logarithmic']]);\nconst surfaceScaleChoices: ReadonlyMap<string, AxisScale> = new Map([['categories', 'categories'], ['proportional', 'proportional'], ['logarithmic', 'logarithmic']]);\nconst zScaleChoices: ReadonlyMap<string, AxisScale> = new Map([['proportional', 'proportional'], ['logarithmic', 'logarithmic']]);\nconst sideChoices: ReadonlyMap<string, AxisSide> = new Map([['left', 'left'], ['right', 'right']]);\nconst stepChoices: ReadonlyMap<string, StepSide> = new Map([['preceding', 'preceding'], ['following', 'following']]);\nconst colourScaleChoices: ReadonlyMap<string, boolean> = new Map([['sequential', false], ['diverging', true]]);\nconst intervalStyleChoices: ReadonlyMap<string, IntervalStyle> = new Map([['whiskers', 'whiskers'], ['band', 'band']]);\n\n/**\n * Reads `text`, a Chart Spec, into a Chart Definition or a 3D surface, taking each Data Handle's table from\n * `tables`, which answers `undefined` for a handle it does not know: the counterpart of C#'s\n * `ChartSpec.Read`. A spec that cannot be drawn throws a {@link ChartSpecRefusedError}, whose message says\n * where and why.\n */\nexport function readChartSpec(text: string, tables: (handle: string) => ChartData | undefined): ChartSpecReading {\n let root: JsonValue;\n try {\n root = readJsonText(text);\n } catch (error) {\n if (error instanceof JsonTextError) {\n throw new ChartSpecRefusedError('', `The Chart Spec is not JSON: ${error.message}`);\n }\n throw error;\n }\n return new Reader(tables).read(root);\n}\n\n/** A Chart Spec read through Chart Sources (ADR-0344): its reading, and the version each Data Handle was read at. */\nexport interface ChartSourceReading {\n /** The title and the definition. */\n readonly reading: ChartSpecReading;\n /** The version each Data Handle's answers named. */\n readonly versions: ReadonlyMap<string, bigint>;\n}\n\n/**\n * Reads `text`, a Chart Spec, through Chart Sources (ADR-0344): each series asks its Data Handle's source for its own\n * column, from `from` to `to` at `pixels` columns, all at once, and is read from the points the source kept, carrying\n * what each thinned pixel held. What a thinned point cannot stand for \u2014 a surface, a labels axis, a series that is not\n * a line from `x` and `y` \u2014 is refused by path before any source is asked, and so is a reading whose answers for one\n * Data Handle name different versions of its data: one chart is never drawn from two moments (spine rule 6). The\n * counterpart of C#'s `ChartSpec.ReadAsync`.\n */\nexport async function readChartSpecThrough(text: string, sources: (handle: string) => ChartSource | undefined, pixels: number,\n options: { readonly from?: number | null; readonly to?: number | null; readonly signal?: AbortSignal } = {}): Promise<ChartSourceReading> {\n if (!Number.isInteger(pixels) || pixels < 1) throw new RangeError(`A chart is read through its sources at one pixel or more, not ${String(pixels)}.`);\n const { from = null, to = null, signal = new AbortController().signal } = options;\n for (const end of [from, to]) {\n if (end !== null && !Number.isFinite(end)) throw new RangeError(`A chart is read through its sources over a range of finite positions, not ${String(end)}.`);\n }\n let root: JsonValue;\n try {\n root = readJsonText(text);\n } catch (error) {\n if (error instanceof JsonTextError) {\n throw new ChartSpecRefusedError('', `The Chart Spec is not JSON: ${error.message}`);\n }\n throw error;\n }\n const { values, series } = askedOf(root);\n // Every source is found before any is asked, so a Data Handle no source answers for leaves no question in flight.\n const found = series.map((asked, i) => {\n const source = sources(asked.data);\n if (source === undefined) {\n throw new ChartSpecRefusedError(`series[${String(i)}].data`, `series[${String(i)}].data \"${asked.data}\" is not known: name a Data Handle a capability returned.`);\n }\n return source;\n });\n // The questions are called off together: when the caller stops waiting, and when one fails, since the reading\n // then fails whole and no other answer is drawn.\n const asking = new AbortController();\n const stop = () => { asking.abort(signal.reason); };\n signal.addEventListener('abort', stop, { once: true });\n let answers: ChartSourceAnswer[];\n try {\n answers = await Promise.all(found.map(async (source, i) => {\n const asked = series[i];\n if (asked === undefined) throw new Error(`Internal: series ${String(i)} is not asked.`);\n return source.thin({ ...asked, values, from, to, pixels }, asking.signal);\n }));\n } catch (error) {\n asking.abort(error);\n throw error;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n const versions = new Map<string, bigint>();\n series.forEach((asked, i) => {\n const answer = answers[i];\n if (answer === undefined) throw new Error(`Internal: series ${String(i)} has no answer.`);\n const seen = versions.get(asked.data);\n if (seen !== undefined && seen !== answer.version) {\n throw new ChartSpecRefusedError(`series[${String(i)}].data`, `series[${String(i)}].data \"${asked.data}\" answered version ${String(answer.version)}, `\n + `and an earlier series of it version ${String(seen)}: one chart is never drawn from two moments of its data.`);\n }\n versions.set(asked.data, answer.version);\n });\n const reading = new Reader(() => undefined, series.length === 0 ? undefined : answers).read(root);\n return Object.freeze({ reading, versions });\n}\n\n// The keys a series read from a Chart Source may carry: its line, read from x and y (ADR-0344).\nconst sourcedSeriesKeys = ['id', 'name', 'kind', 'data', 'x', 'y', 'panel', 'axis', 'fromZero', 'step'];\n// The kinds a thinned line stands for.\nconst sourcedKinds = ['level', 'rateOverInterval', 'amountPerPeriod'];\n\n// What a spec asks of its sources, checked before any is asked (ADR-0344): C#'s `ChartSource.Asked`. Anything else\n// wrong with the spec is the reader's to refuse, once the answers are in.\nfunction askedOf(root: JsonValue): { readonly values: AxisValues; readonly series: readonly { readonly data: string; readonly x: string; readonly y: string }[] } {\n if (isJsonObject(root) && jsonMember(root, 'surface') !== undefined) {\n throw refuse('surface', 'surface needs every point of its grid or its mesh, which a Chart Source does not thin; a chart read from one draws series.');\n }\n const axis = isJsonObject(root) ? jsonMember(root, 'axis') : undefined;\n const series = isJsonObject(root) ? jsonMember(root, 'series') : undefined;\n if (!isJsonObject(axis) || !isJsonArray(series)) return { values: 'numbers', series: [] };\n const valuesMember = jsonMember(axis, 'values');\n const values = typeof valuesMember === 'string' ? valuesMember : undefined;\n if (values === 'labels') {\n throw refuse('axis.values', 'axis.values \"labels\" needs every category, which only the whole column knows; a chart read from a Chart Source places dates or numbers.');\n }\n const asked = series.map((s, i) => {\n const path = `series[${String(i)}]`;\n if (!isJsonObject(s)) throw refuse(path, `${path} is not an object: each series names its id, name, kind, data, x and y.`);\n for (const name of jsonMemberNames(s)) {\n if (!sourcedSeriesKeys.includes(name) && seriesKeys.includes(name)) {\n throw refuse(`${path}.${name}`, `${path}.${name} is one value a point, and a point read from a Chart Source stands for every row of its pixel; a series read from one draws its line from x and y.`);\n }\n }\n const kindMember = jsonMember(s, 'kind');\n const kind = typeof kindMember === 'string' ? kindMember : undefined;\n // A kind no Chart Spec knows is the reader's to refuse; one it knows and a thinned line cannot stand for, here.\n if (kind !== undefined && !sourcedKinds.includes(kind) && kinds.has(kind)) {\n throw refuse(`${path}.kind`, kind === 'observation'\n ? `${path}.kind \"observation\" draws each row as a point of its own, which a Chart Source does not thin; a series read from one is a level, a rateOverInterval or an amountPerPeriod.`\n : `${path}.kind \"${kind}\" does not draw a line a Chart Source can thin; a series read from one is a level, a rateOverInterval or an amountPerPeriod.`);\n }\n const column = (key: string): string => {\n const member = jsonMember(s, key);\n if (typeof member !== 'string') {\n throw refuse(`${path}.${key}`, `${path}.${key} names a column, and is needed: a series read from a Chart Source is asked for its \"data\", its \"x\" and its \"y\".`);\n }\n return member;\n };\n return Object.freeze({ data: column('data'), x: column('x'), y: column('y') });\n });\n return { values: values === 'dates' ? 'dates' : 'numbers', series: asked };\n}\n\n// What a grid axis places: numbers, dates as their day numbers, or labels.\ntype PlacedKind = 'numbers' | 'dates' | 'labels';\n\ninterface GridValues {\n // The axis' values: numbers and dates in order, labels as the data first shows them.\n readonly values: readonly (number | string)[];\n // Each row's value among them.\n readonly of: readonly (number | string)[];\n readonly kind: PlacedKind | undefined;\n}\n\nclass Reader {\n readonly #tables: (handle: string) => ChartData | undefined;\n // A reader through Chart Sources is handed each series' answer, in the series' order (readChartSpecThrough).\n readonly #answers: readonly ChartSourceAnswer[] | undefined;\n #answered = 0;\n // A label axis' categories, in the order the data first shows them (ADR-0251).\n readonly #labels: string[] = [];\n readonly #labelIndex = new Map<string, number>();\n\n constructor(tables: (handle: string) => ChartData | undefined, answers?: readonly ChartSourceAnswer[]) {\n this.#tables = tables;\n this.#answers = answers;\n }\n\n read(root: JsonValue): ChartSpecReading {\n if (!isJsonObject(root)) {\n throw refuse('', 'The Chart Spec is a JSON object.');\n }\n known(root, '', rootKeys);\n const version = jsonMember(root, 'version');\n if (version === undefined) {\n throw refuse('version', `version is missing: a Chart Spec says which version it is written in; this reader reads version ${String(chartSpecVersion)}.`);\n }\n if (!(version instanceof JsonNumber) || version.int32 !== chartSpecVersion) {\n throw refuse('version', `version ${jsonRawText(version)} is not known: this reader reads version ${String(chartSpecVersion)}, and never reads a spec as the nearest version.`);\n }\n const title = optionalString(root, 'title', '');\n const surfaceElement = jsonMember(root, 'surface');\n if (surfaceElement !== undefined) {\n for (const other of ['axis', 'series']) {\n if (jsonMember(root, other) !== undefined) {\n throw refuse(other, `${other} belongs to a chart of series; a spec draws a surface or series, and its surface names its own x, y and z.`);\n }\n }\n // The notes are read before the surface, as C# reads its arguments.\n const notes = notesOf(root);\n return new ChartSpecReading({ title: title === undefined ? '' : title, surface: this.#surface(surfaceElement, 'surface', notes) });\n }\n const axisElement = objectMember(root, 'axis', '');\n known(axisElement, 'axis', axisKeys);\n const values = choice(axisElement, 'values', 'axis', axisValueChoices, 'what the positions across are');\n const scale = jsonMember(axisElement, 'scale') === undefined\n ? undefined\n : choice(axisElement, 'scale', 'axis', axisScaleChoices, 'how the positions are placed');\n const seriesArray = jsonMember(root, 'series');\n if (!isJsonArray(seriesArray) || seriesArray.length === 0) {\n throw refuse('series', 'series is missing: a Chart Spec lists at least one series.');\n }\n const series = seriesArray.map((s, i) => this.#series(s, `series[${String(i)}]`, values));\n const notes = notesOf(root);\n const axisTitle = optionalString(axisElement, 'title', 'axis');\n const packed = optionalBool(axisElement, 'packed', 'axis');\n const axis: ChartAxisOptions = {\n values,\n title: axisTitle === undefined ? '' : axisTitle,\n ...(scale === undefined ? {} : { scale }),\n labels: [...this.#labels],\n packed: packed === undefined ? false : packed,\n };\n // Each series is checked on its own first, so a refusal names the series it belongs to.\n for (let n = 0; n < series.length; n++) {\n const own = elementAt(series, n);\n const duplicate = series.findIndex(s => s.id === own.id);\n if (duplicate < n) {\n throw refuse(`series[${String(n)}].id`, `series[${String(n)}].id \"${own.id}\" is series[${String(duplicate)}]'s too: each series needs an identity of its own.`);\n }\n defined(`series[${String(n)}]`, () => new ChartDefinition({ axis, series: [own] }));\n }\n return new ChartSpecReading({\n title: title === undefined ? '' : title,\n definition: defined('', () => new ChartDefinition({ axis, series, notes })),\n });\n }\n\n // A 3D surface (ADR-0274): a grid its rows lie on, or the Consumer's triangles over keyed nodes (ADR-0311);\n // its colours' centre (ADR-0310) and its scales (ADR-0312). Nothing is interpolated: rows that form no grid\n // are refused, as SurfaceDefinition.fromPoints refuses them.\n #surface(s: JsonValue, path: string, notes: readonly string[]): SurfaceDefinition {\n if (!isJsonObject(s)) {\n throw refuse(path, `${path} is a JSON object.`);\n }\n known(s, path, surfaceKeys);\n const handle = requiredString(s, 'data', path, 'the Data Handle of the table of its points');\n const table = this.#table(handle, `${path}.data`);\n const x = requiredColumn(s, 'x', path, handle, table);\n const y = requiredColumn(s, 'y', path, handle, table);\n const z = requiredColumn(s, 'z', path, handle, table);\n const xTitle = optionalString(s, 'xTitle', path) ?? x;\n const yTitle = optionalString(s, 'yTitle', path) ?? y;\n const zTitle = optionalString(s, 'zTitle', path) ?? z;\n const scaleOf = (key: string): AxisScale | undefined =>\n (jsonMember(s, key) === undefined ? undefined : choice(s, key, path, surfaceScaleChoices, 'how its values are placed'));\n const xScale = scaleOf('xScale');\n const yScale = scaleOf('yScale');\n const zScale = jsonMember(s, 'zScale') === undefined\n ? 'proportional'\n : choice(s, 'zScale', path, zScaleChoices, 'how the values are placed up');\n let centre: number | undefined;\n const centreElement = jsonMember(s, 'centre');\n if (centreElement !== undefined) {\n if (!(centreElement instanceof JsonNumber) || !Number.isFinite(centreElement.double)) {\n throw refuse(`${path}.centre`, `${path}.centre is a finite number.`);\n }\n centre = centreElement.double;\n }\n const method = optionalString(s, 'method', path);\n const rows = table.rowCount;\n const zs: (ChartValue | null)[] = [];\n for (let r = 0; r < rows; r++) {\n zs.push(valueOf(cell(table, z, r, handle), `${path}.z`, handle, r));\n }\n const scaled = { zScale, ...(centre === undefined ? {} : { centre }) };\n\n let surface: SurfaceDefinition;\n const trianglesElement = jsonMember(s, 'triangles');\n if (trianglesElement !== undefined) {\n const at = `${path}.triangles`;\n for (const gridOnly of ['interpolated', 'method']) {\n if (jsonMember(s, gridOnly) !== undefined) {\n throw refuse(`${path}.${gridOnly}`, `${path}.${gridOnly} belongs to a grid; a mesh's nodes are its values, and between them it is read linearly on its triangles, which it says.`);\n }\n }\n const key = optionalColumn(s, 'key', path, handle, table);\n if (key === undefined) {\n throw missing(path, 'key', 'a triangle names its nodes by key, so the nodes say which column holds theirs');\n }\n const nodes: SurfaceNode[] = [];\n const index = new Map<string, number>();\n for (let r = 0; r < rows; r++) {\n const name = keyOf(cell(table, key, r, handle), `${path}.key`, handle, r);\n const seen = index.get(name);\n if (seen !== undefined) {\n throw refuse(`${path}.key`, `${path}.key: rows ${String(seen + 1)} and ${String(r + 1)} of \"${handle}\" are both keyed ${name}; a triangle could not say which it names.`);\n }\n index.set(name, r);\n nodes.push({\n x: meshPosition(cell(table, x, r, handle), `${path}.x`, handle, r),\n y: meshPosition(cell(table, y, r, handle), `${path}.y`, handle, r),\n z: elementAt(zs, r),\n });\n }\n if (!isJsonObject(trianglesElement)) {\n throw refuse(at, `${at} is a JSON object.`);\n }\n known(trianglesElement, at, triangleKeys);\n const triangleHandle = requiredString(trianglesElement, 'data', at, 'the Data Handle of the triangles\\' table');\n const triangleTable = this.#table(triangleHandle, `${at}.data`);\n const corners = (['a', 'b', 'c'] as const).map(c => ({ key: c, column: requiredColumn(trianglesElement, c, at, triangleHandle, triangleTable) }));\n const triangles: SurfaceTriangle[] = [];\n for (let r = 0; r < triangleTable.rowCount; r++) {\n const [a, b, c] = corners.map(corner => {\n const name = keyOf(cell(triangleTable, corner.column, r, triangleHandle), `${at}.${corner.key}`, triangleHandle, r);\n const i = index.get(name);\n if (i === undefined) {\n throw refuse(`${at}.${corner.key}`, `${at}.${corner.key}: row ${String(r + 1)} of \"${triangleHandle}\" names node ${name}, but no node is keyed ${name}.`);\n }\n return i;\n });\n if (a === undefined || b === undefined || c === undefined) {\n throw new Error('Internal: a triangle has three corners.');\n }\n triangles.push({ a, b, c });\n }\n for (const [scaleKey, scale] of [['xScale', xScale], ['yScale', yScale]] as const) {\n if (scale === 'categories') {\n throw refuse(`${path}.${scaleKey}`, `${path}.${scaleKey} \"categories\": a mesh's nodes are placed by their position, proportionally or logarithmically.`);\n }\n }\n surface = defined(path, () => SurfaceDefinition.fromTriangles({\n nodes, triangles, xTitle, yTitle, zTitle,\n xScale: xScale === undefined ? 'proportional' : xScale,\n yScale: yScale === undefined ? 'proportional' : yScale,\n notes, ...scaled,\n }));\n } else {\n if (jsonMember(s, 'key') !== undefined) {\n throw refuse(`${path}.key`, `${path}.key belongs to a mesh, whose triangles name its nodes; a grid's points stand at their x and y.`);\n }\n const xs = gridValues(table, x, `${path}.x`, `${path}.xScale`, handle, xScale);\n const ys = gridValues(table, y, `${path}.y`, `${path}.yScale`, handle, yScale);\n const xIndex = new Map(xs.values.map((v, i) => [v, i]));\n const yIndex = new Map(ys.values.map((v, i) => [v, i]));\n const grid = ys.values.map(() => xs.values.map((): ChartValue | null => null));\n const marked = ys.values.map(() => xs.values.map(() => false));\n const taken = ys.values.map(() => xs.values.map(() => false));\n const interpolated = optionalColumn(s, 'interpolated', path, handle, table);\n if (interpolated !== undefined && method === undefined) {\n throw missing(path, 'method', 'a surface that marks values interpolated names the method they were made with, which the chart says (ADR-0257)');\n }\n for (let r = 0; r < rows; r++) {\n const xOf = elementAt(xs.of, r);\n const yOf = elementAt(ys.of, r);\n const i = indexIn(xIndex, xOf);\n const j = indexIn(yIndex, yOf);\n if (elementAt(elementAt(taken, j), i)) {\n throw refuse(`${path}.x`, `${path}: two rows of \"${handle}\" lie at ${xTitle} ${writePlaced(xOf, xs.kind)} and ${yTitle} ${writePlaced(yOf, ys.kind)}, the second row ${String(r + 1)}; a grid point holds one value.`);\n }\n elementAt(taken, j)[i] = true;\n elementAt(grid, j)[i] = elementAt(zs, r);\n if (interpolated !== undefined) {\n const mark = cell(table, interpolated, r, handle);\n if (mark !== null && typeof mark !== 'boolean') {\n throw refuse(`${path}.interpolated`, `${path}.interpolated: row ${String(r + 1)} of \"${handle}\" holds \"${cellText(mark)}\", which is not true or false.`);\n }\n elementAt(marked, j)[i] = mark === true;\n }\n }\n // A row that alone holds its x, or its y, joins a surface only by interpolation, which is not the chart's.\n for (const [axis, index, title, other, key] of [[xs, xIndex, xTitle, yTitle, 'x'], [ys, yIndex, yTitle, xTitle, 'y']] as const) {\n const held = axis.values.map(() => 0);\n for (const o of axis.of) {\n const at = indexIn(index, o);\n held[at] = elementAt(held, at) + 1;\n }\n for (const v of axis.values) {\n if (elementAt(held, indexIn(index, v)) < 2) {\n throw refuse(`${path}.${key}`, `${path}.${key}: ${title} ${writePlaced(v, axis.kind)} has a value at only one ${other}. Rows that form no grid join a surface only by interpolation, which the chart does not choose: have the capability interpolate them onto a grid and name its method, or hand its own triangles.`);\n }\n }\n }\n surface = defined(path, () => SurfaceDefinition.grid({\n x: { title: xTitle, values: xs.values, scale: xScale === undefined ? 'categories' : xScale, ...formatOf(xs.kind) },\n y: { title: yTitle, values: ys.values, scale: yScale === undefined ? 'categories' : yScale, ...formatOf(ys.kind) },\n z: grid, zTitle,\n ...(method === undefined ? {} : { method }),\n ...(interpolated === undefined ? {} : { interpolated: marked }),\n notes, ...scaled,\n }));\n }\n return surface;\n }\n\n #series(s: JsonValue, path: string, values: AxisValues): ChartSeriesOptions {\n if (!isJsonObject(s)) {\n throw refuse(path, `${path} is a JSON object.`);\n }\n known(s, path, seriesKeys);\n const id = requiredString(s, 'id', path, 'a series\\' identity, unique in the chart');\n const name = requiredString(s, 'name', path, 'its name in the legend and the tooltip');\n const kindNames = [...kinds.keys()].join(', ');\n const kindText = requiredString(s, 'kind', path, `every series says what its numbers are: ${kindNames}; there is no default`);\n const kind = kinds.get(kindText);\n if (kind === undefined) {\n throw refuse(`${path}.kind`, `${path}.kind \"${kindText}\" is not a Series Kind: it is one of ${kindNames}.`);\n }\n const handle = requiredString(s, 'data', path, 'the Data Handle of the table its values are read from');\n const answer = this.#answers?.[this.#answered++];\n const table = answer === undefined ? this.#table(handle, `${path}.data`) : answer.points;\n const x = requiredColumn(s, 'x', path, handle, table);\n const rows = table.rowCount;\n const positions: number[] = [];\n for (let r = 0; r < rows; r++) {\n positions.push(this.#position(cell(table, x, r, handle), values, `${path}.x`, handle, r));\n }\n const label = optionalColumn(s, 'label', path, handle, table);\n const key = optionalColumn(s, 'key', path, handle, table);\n let points: readonly ChartPoint[] | undefined;\n let bars: readonly PriceBar[] | undefined;\n if (kind === 'priceRange') {\n if (jsonMember(s, 'y') !== undefined) {\n throw refuse(`${path}.y`, `${path}.y belongs to a series of one value a row; a priceRange reads open, high, low and close.`);\n }\n const columns = new Map(priceColumns.map(c => [c, c === 'open' || c === 'volume'\n ? optionalColumn(s, c, path, handle, table)\n : requiredColumn(s, c, path, handle, table)]));\n const read: PriceBar[] = [];\n for (let r = 0; r < rows; r++) {\n const at = (c: (typeof priceColumns)[number]): ChartValue | null => {\n const column = columns.get(c);\n return column === undefined ? null : valueOf(cell(table, column, r, handle), `${path}.${c}`, handle, r);\n };\n const open = at('open');\n const high = at('high');\n const low = at('low');\n const close = at('close');\n read.push({ x: elementAt(positions, r), open, high, low, close, volume: at('volume') });\n }\n bars = read;\n } else {\n for (const c of priceColumns) {\n if (jsonMember(s, c) !== undefined) {\n throw refuse(`${path}.${c}`, `${path}.${c} belongs to a priceRange; a ${kindText} reads one value a row, from y.`);\n }\n }\n const y = requiredColumn(s, 'y', path, handle, table);\n const read: ChartPoint[] = [];\n for (let r = 0; r < rows; r++) {\n const value = valueOf(cell(table, y, r, handle), `${path}.y`, handle, r);\n read.push({\n x: elementAt(positions, r), y: value,\n ...(label === undefined ? {} : { name: cellText(cell(table, label, r, handle)) }),\n ...(key === undefined ? {} : { row: keyOf(cell(table, key, r, handle), `${path}.key`, handle, r) }),\n });\n }\n points = read;\n }\n let edges: readonly ChartEdge[] | undefined;\n const edgesElement = jsonMember(s, 'edges');\n if (edgesElement !== undefined) {\n const at = `${path}.edges`;\n if (kind !== 'observation') {\n throw refuse(at, `${at} belongs to an observation, whose points are the nodes.`);\n }\n if (key === undefined) {\n throw refuse(`${path}.key`, `${path}.key is missing: an edge names its nodes by key, so the nodes say which column holds theirs.`);\n }\n if (!isJsonObject(edgesElement)) {\n throw refuse(at, `${at} is a JSON object.`);\n }\n known(edgesElement, at, edgeKeys);\n const edgeHandle = requiredString(edgesElement, 'data', at, 'the Data Handle of the edges\\' table');\n const edgeTable = this.#table(edgeHandle, `${at}.data`);\n const from = requiredColumn(edgesElement, 'from', at, edgeHandle, edgeTable);\n const to = requiredColumn(edgesElement, 'to', at, edgeHandle, edgeTable);\n const read: ChartEdge[] = [];\n for (let r = 0; r < edgeTable.rowCount; r++) {\n const start = keyOf(cell(edgeTable, from, r, edgeHandle), `${at}.from`, edgeHandle, r);\n read.push({ from: start, to: keyOf(cell(edgeTable, to, r, edgeHandle), `${at}.to`, edgeHandle, r) });\n }\n edges = read;\n }\n let interval: SeriesInterval | undefined;\n const intervalElement = jsonMember(s, 'interval');\n if (intervalElement !== undefined) {\n if (kind !== 'level' && kind !== 'observation') {\n throw refuse(`${path}.interval`, `${path}.interval belongs to a level or an observation, whose points the bounds stand at.`);\n }\n interval = readInterval(intervalElement, `${path}.interval`, handle, table, positions, (v, at, r) => valueOf(v, at, handle, r));\n }\n let xInterval: SeriesInterval | undefined;\n const xIntervalElement = jsonMember(s, 'xInterval');\n if (xIntervalElement !== undefined) {\n const at = `${path}.xInterval`;\n if (kind !== 'observation') {\n throw refuse(at, `${at} belongs to an observation, whose points each stand at a position of their own.`);\n }\n if (values === 'labels') {\n throw refuse(at, `${at}: a labels axis has no units for a bound to stand in.`);\n }\n xInterval = readInterval(xIntervalElement, at, handle, table, positions,\n (v, p, r) => (v === null ? null : this.#position(v, values, p, handle, r)));\n }\n const tooltipElement = jsonMember(s, 'tooltip');\n const details = tooltipElement === undefined ? undefined : detailsOf(tooltipElement, `${path}.tooltip`, kind, handle, table);\n const colourElement = jsonMember(s, 'colour');\n const colourBy = colourElement === undefined ? undefined : colourOf(colourElement, `${path}.colour`, handle, table);\n let sizeBy: { readonly title: string; readonly values: readonly (ChartValue | null)[] } | undefined;\n const sizeElement = jsonMember(s, 'size');\n if (sizeElement !== undefined) {\n const at = `${path}.size`;\n if (!isJsonObject(sizeElement)) {\n throw refuse(at, `${at} is a JSON object.`);\n }\n known(sizeElement, at, sizeKeys);\n const column = requiredColumn(sizeElement, 'column', at, handle, table);\n const sizeTitle = optionalString(sizeElement, 'title', at) ?? column;\n sizeBy = { title: sizeTitle, values: columnValues(table, column, `${at}.column`, handle) };\n }\n const panel = optionalString(s, 'panel', path);\n const axis = jsonMember(s, 'axis') === undefined ? 'left' : choice(s, 'axis', path, sideChoices, 'the vertical axis it reads on');\n const fromZero = optionalBool(s, 'fromZero', path);\n const step = jsonMember(s, 'step') === undefined ? 'preceding' : choice(s, 'step', path, stepChoices, 'which interval a step\\'s point stands for');\n return {\n id, name, kind,\n ...(points === undefined ? {} : { points }),\n ...(bars === undefined ? {} : { bars }),\n ...(edges === undefined ? {} : { edges }),\n ...(interval === undefined ? {} : { interval }),\n ...(xInterval === undefined ? {} : { xInterval }),\n ...(details === undefined ? {} : { details }),\n ...(colourBy === undefined ? {} : { colourBy }),\n ...(sizeBy === undefined ? {} : { sizeBy }),\n panel: panel === undefined ? '' : panel,\n axis,\n ...(fromZero === undefined ? {} : { fromZero }),\n step,\n ...(answer === undefined ? {} : { thinned: answer.thinned }),\n };\n }\n\n #table(handle: string, path: string): ChartData {\n const table = this.#tables(handle);\n if (table === undefined) {\n throw refuse(path, `${path} \"${handle}\" is not known: name a Data Handle a capability returned.`);\n }\n return table;\n }\n\n #position(value: unknown, values: AxisValues, path: string, handle: string, row: number): number {\n const date = values === 'dates' ? temporalDate(value) : undefined;\n if (date !== undefined) {\n if (date.ticks % ticksPerDay !== 0n) {\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" holds ${cellText(value)}, a time of day; a dates axis places days.`);\n }\n return Number(date.ticks / ticksPerDay);\n }\n const n = values === 'numbers' ? valueOf(value, path, handle, row) : null;\n if (n !== null) {\n return toNumber(n);\n }\n if (values === 'labels' && typeof value === 'string') {\n let at = this.#labelIndex.get(value);\n if (at === undefined) {\n at = this.#labels.length;\n this.#labels.push(value);\n this.#labelIndex.set(value, at);\n }\n return at;\n }\n if (value === null) {\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" has no position; a point needs one across.`);\n }\n const expected = values === 'dates' ? 'a date' : values === 'numbers' ? 'a number' : 'a label';\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" holds \"${cellText(value)}\", but the axis is ${values} and needs ${expected}.`);\n }\n}\n\nfunction notesOf(root: JsonObject): string[] {\n const notes: string[] = [];\n const notesElement = jsonMember(root, 'notes');\n if (notesElement !== undefined) {\n if (!isJsonArray(notesElement)) {\n throw refuse('notes', 'notes is a list of lines.');\n }\n notesElement.forEach((line, n) => {\n if (typeof line !== 'string') {\n throw refuse(`notes[${String(n)}]`, `notes[${String(n)}] is a line of text.`);\n }\n notes.push(line);\n });\n }\n return notes;\n}\n\n// A grid axis' values, each row's value among them: numbers and dates in order, labels as the data first\n// shows them; one kind a column.\nfunction gridValues(table: ChartData, column: string, path: string, scalePath: string, handle: string, scale: AxisScale | undefined): GridValues {\n const of: (number | string)[] = [];\n let kind: PlacedKind | undefined;\n for (let r = 0; r < table.rowCount; r++) {\n const value = cell(table, column, r, handle);\n let placed: number | string;\n let placedKind: PlacedKind;\n const date = temporalDate(value);\n if (value === null) {\n throw refuse(path, `${path}: row ${String(r + 1)} of \"${handle}\" has no position; a point needs one.`);\n } else if (date !== undefined) {\n if (date.ticks % ticksPerDay !== 0n) {\n throw refuse(path, `${path}: row ${String(r + 1)} of \"${handle}\" holds ${cellText(value)}, a time of day; a surface places days.`);\n }\n placed = Number(date.ticks / ticksPerDay);\n placedKind = 'dates';\n } else if (typeof value === 'string') {\n placed = value;\n placedKind = 'labels';\n } else {\n const n = valueOf(value, path, handle, r);\n if (n === null) {\n throw new Error('Internal: a value that is not null read as missing.');\n }\n placed = toNumber(n);\n placedKind = 'numbers';\n }\n kind ??= placedKind;\n if (placedKind !== kind) {\n throw refuse(path, `${path}: row ${String(r + 1)} of \"${handle}\" holds \"${cellText(value)}\", but the rows before it hold ${kind}; an axis places one kind of value.`);\n }\n of.push(placed);\n }\n if ((scale === 'proportional' || scale === 'logarithmic') && kind !== undefined && kind !== 'numbers') {\n throw refuse(scalePath, `${scalePath}: only numbers are placed by value; ${path}'s ${kind} are placed evenly, as categories.`);\n }\n const distinct = [...new Set(of)];\n return {\n values: kind === 'labels' ? distinct : distinct.toSorted((a, b) => (a < b ? -1 : a > b ? 1 : 0)),\n of,\n kind,\n };\n}\n\n// A date axis writes its days as dates; the other kinds as they are.\nfunction formatOf(kind: PlacedKind | undefined): { readonly format?: (value: SurfaceValue) => string } {\n return kind === 'dates' ? { format: value => (typeof value === 'number' ? isoDate(dateOf(value)) : value) } : {};\n}\n\nfunction writePlaced(value: number | string, kind: PlacedKind | undefined): string {\n if (typeof value === 'string') {\n return value;\n }\n return kind === 'dates' ? isoDate(dateOf(value)) : roundTrip(value);\n}\n\nfunction indexIn(index: ReadonlyMap<number | string, number>, value: number | string): number {\n const at = index.get(value);\n if (at === undefined) {\n throw new Error(`Internal: ${String(value)} is not among the axis' values.`);\n }\n return at;\n}\n\nfunction meshPosition(value: unknown, path: string, handle: string, row: number): number {\n const v = valueOf(value, path, handle, row);\n if (v === null) {\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" has no position; a node needs one in the plane.`);\n }\n return toNumber(v);\n}\n\nfunction colourOf(c: JsonValue, path: string, handle: string, table: ChartData): PointColour {\n if (!isJsonObject(c)) {\n throw refuse(path, `${path} is a JSON object.`);\n }\n known(c, path, colourKeys);\n const column = requiredColumn(c, 'column', path, handle, table);\n const diverging = choice(c, 'scale', path, colourScaleChoices, 'how the colours run');\n let centre: number | undefined;\n const centreElement = jsonMember(c, 'centre');\n if (centreElement !== undefined) {\n if (!diverging) {\n throw refuse(`${path}.centre`, `${path}.centre belongs to a diverging scale; a sequential one runs from the lowest value to the highest.`);\n }\n if (!(centreElement instanceof JsonNumber) || !Number.isFinite(centreElement.double)) {\n throw refuse(`${path}.centre`, `${path}.centre is a finite number.`);\n }\n centre = centreElement.double;\n } else if (diverging) {\n throw refuse(`${path}.centre`, `${path}.centre is missing: a diverging scale says the value that means nothing, such as 0 for a P&L or 1 for a ratio.`);\n }\n const title = optionalString(c, 'title', path) ?? column;\n return { title, values: columnValues(table, column, `${path}.column`, handle), ...(centre === undefined ? {} : { centre }) };\n}\n\n// A series' interval: a lower and an upper bound a row, at the row's position (ADR-0303, ADR-0304).\nfunction readInterval(iv: JsonValue, path: string, handle: string, table: ChartData, positions: readonly number[],\n bound: (value: unknown, path: string, row: number) => ChartValue | null): SeriesInterval {\n if (!isJsonObject(iv)) {\n throw refuse(path, `${path} is a JSON object.`);\n }\n known(iv, path, intervalKeys);\n const lower = requiredColumn(iv, 'lower', path, handle, table);\n const upper = requiredColumn(iv, 'upper', path, handle, table);\n const meaning = optionalString(iv, 'meaning', path);\n if (meaning === undefined || meaning.trim() === '') {\n throw missing(path, 'meaning', 'what the bounds are, such as 95% CI, \u00B11\u03C3 or Bid\u2013Ask; an interval that does not say is not drawn');\n }\n const style = jsonMember(iv, 'style') === undefined ? 'whiskers' : choice(iv, 'style', path, intervalStyleChoices, 'how the bounds are drawn');\n const bounds: IntervalBound[] = [];\n for (let r = 0; r < table.rowCount; r++) {\n const low = bound(cell(table, lower, r, handle), `${path}.lower`, r);\n bounds.push({ x: elementAt(positions, r), lower: low, upper: bound(cell(table, upper, r, handle), `${path}.upper`, r) });\n }\n return { meaning, bounds, style };\n}\n\n// The columns an observation's tooltip says, each one value a row written as the table holds it (ADR-0321).\nfunction detailsOf(t: JsonValue, path: string, kind: SeriesKind, handle: string, table: ChartData): PointDetail[] {\n if (kind !== 'observation') {\n throw refuse(path, `${path} belongs to an observation, whose tooltip names one point; a line's tooltip reads every series at a position.`);\n }\n if (!isJsonArray(t)) {\n throw refuse(path, `${path} is a list of the columns its tooltip says.`);\n }\n const details: PointDetail[] = [];\n t.forEach((c, n) => {\n const at = `${path}[${String(n)}]`;\n if (typeof c !== 'string') {\n throw refuse(at, `${at} names a column, as text.`);\n }\n if (!table.columns.includes(c)) {\n throw refuse(at, `${at}: \"${handle}\" has no column \"${c}\"; its columns are ${table.columns.join(', ')}.`);\n }\n if (details.some(d => d.title === c)) {\n throw refuse(at, `${at} names \"${c}\" twice.`);\n }\n const values: (string | null)[] = [];\n for (let r = 0; r < table.rowCount; r++) {\n const v = cell(table, c, r, handle);\n values.push(v === null ? null : cellText(v));\n }\n details.push({ title: c, values });\n });\n return details;\n}\n\n// A key is compared as its text, so a key read as a number in one table meets the same key in another.\nfunction keyOf(value: unknown, path: string, handle: string, row: number): string {\n if (value === null) {\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" has no key.`);\n }\n return cellText(value);\n}\n\nfunction columnValues(table: ChartData, column: string, path: string, handle: string): (ChartValue | null)[] {\n const values: (ChartValue | null)[] = [];\n for (let r = 0; r < table.rowCount; r++) {\n values.push(valueOf(cell(table, column, r, handle), path, handle, r));\n }\n return values;\n}\n\n// A table's value, checked at the boundary: a table that answers `undefined` has broken its contract, where a\n// missing value is `null`.\nfunction cell(table: ChartData, column: string, row: number, handle: string): unknown {\n const value = table.value(column, row);\n if (value === undefined) {\n throw new TypeError(`\"${handle}\" answered undefined for row ${String(row + 1)} of its column \"${column}\"; a missing value is null.`);\n }\n return value;\n}\n\n// A value as a chart holds it (ADR-0251): a double as a number, a whole number exactly as a bigint, a decimal\n// as the number that writes the same digits, or a bigint where it has none after the point.\nfunction valueOf(value: unknown, path: string, handle: string, row: number): ChartValue | null {\n if (value === null) {\n return null;\n }\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" is ${cellText(value)}, which is no number; a missing value is null, drawn as a gap.`);\n }\n return value;\n }\n if (typeof value === 'bigint') {\n return value;\n }\n const decimal = asDecimal(value);\n if (decimal !== undefined) {\n const held = decimalValue(decimal);\n if (held === undefined) {\n // A chart value has no decimal of its own; one a number cannot write digit for digit is refused,\n // never rounded into a figure the cell does not show (spine rule 1).\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" holds ${decimalText(decimal)}, which a chart value cannot hold digit for digit; a decimal is drawn with every digit it holds, or not at all.`);\n }\n return held;\n }\n throw refuse(path, `${path}: row ${String(row + 1)} of \"${handle}\" holds \"${cellText(value)}\", which is not a number.`);\n}\n\n// A Snapshot's decimal, `{ mantissa, scale }`, recognised by its shape as @ex-grid/data recognises one.\nexport function asDecimal(value: unknown): SnapshotDecimal | undefined {\n if (typeof value !== 'object' || value === null) {\n return undefined;\n }\n const mantissa: unknown = Reflect.get(value, 'mantissa');\n const scale: unknown = Reflect.get(value, 'scale');\n return typeof mantissa === 'bigint' && typeof scale === 'number' && Number.isInteger(scale) && scale >= 0 && scale <= 28\n ? { mantissa, scale }\n : undefined;\n}\n\n// The decimal as a chart value: a whole one as a bigint; one with places as the number whose shortest digits\n// are the decimal's own, or `undefined` where no number writes them.\nfunction decimalValue(decimal: SnapshotDecimal): ChartValue | undefined {\n let mantissa = decimal.mantissa;\n let scale = decimal.scale;\n while (scale > 0 && mantissa % 10n === 0n) {\n mantissa /= 10n;\n scale -= 1;\n }\n if (scale === 0) {\n return mantissa;\n }\n const n = Number(decimalText({ mantissa, scale }));\n const written = Math.abs(n).toExponential();\n const match = /^(\\d)(?:\\.(\\d+))?e([+-]\\d+)$/.exec(written);\n if (match === null) {\n throw new Error(`Internal: ${written} is not a number in exponent form.`);\n }\n const [, first = '', rest = '', exponent = ''] = match;\n const digits = BigInt(first + rest);\n const places = rest.length - Number(exponent);\n const signed = mantissa < 0n ? -digits : digits;\n return places === scale && signed === mantissa ? n : undefined;\n}\n\n// A value written into a sentence as C#'s `Convert.ToString(value, CultureInfo.InvariantCulture)` writes it.\nexport function cellText(value: unknown): string {\n if (value === null || value === undefined) {\n return '';\n }\n if (typeof value === 'string') {\n return value;\n }\n if (typeof value === 'number') {\n return roundTrip(value);\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n // C# writes a bool as `True` or `False`.\n if (typeof value === 'boolean') {\n return value ? 'True' : 'False';\n }\n const decimal = asDecimal(value);\n if (decimal !== undefined) {\n return decimalText(decimal);\n }\n const date = temporalDate(value);\n if (date !== undefined) {\n const day = dateOf(Number(date.ticks / ticksPerDay));\n const written = `${two(day.month)}/${two(day.day)}/${String(day.year).padStart(4, '0')}`;\n if (!date.withTime) {\n return written;\n }\n const seconds = Number((date.ticks % ticksPerDay) / 10_000_000n);\n return `${written} ${two(Math.floor(seconds / 3600))}:${two(Math.floor(seconds / 60) % 60)}:${two(seconds % 60)}`;\n }\n // Any other value is named by its kind, as C# names an object it cannot write by its type.\n return Object.prototype.toString.call(value);\n}\n\nfunction two(n: number): string {\n return String(n).padStart(2, '0');\n}\n\nconst ticksPerDay = 864_000_000_000n;\n\n// A Temporal `PlainDate` (C#'s DateOnly) or `PlainDateTime` (DateTime), as its ticks since 0001-01-01.\nexport function temporalDate(value: unknown): { readonly ticks: bigint; readonly withTime: boolean } | undefined {\n if (typeof value !== 'object' || value === null) {\n return undefined;\n }\n const ticks = ticksOfTemporal(value);\n return ticks === undefined ? undefined : { ticks, withTime: Object.prototype.toString.call(value) === '[object Temporal.PlainDateTime]' };\n}\n\nfunction requiredColumn(s: JsonObject, key: string, path: string, handle: string, table: ChartData): string {\n const name = optionalColumn(s, key, path, handle, table);\n if (name === undefined) {\n throw missing(path, key, 'the column it is read from');\n }\n return name;\n}\n\nfunction optionalColumn(s: JsonObject, key: string, path: string, handle: string, table: ChartData): string | undefined {\n const name = optionalString(s, key, path);\n if (name === undefined) {\n return undefined;\n }\n if (!table.columns.includes(name)) {\n throw refuse(`${path}.${key}`, `${path}.${key}: \"${handle}\" has no column \"${name}\"; its columns are ${table.columns.join(', ')}.`);\n }\n return name;\n}\n\nfunction defined<T>(path: string, define: () => T): T {\n try {\n return define();\n } catch (error) {\n if (error instanceof ChartRefusedError) {\n throw refuse(path, path === '' ? error.message : `${path}: ${error.message}`);\n }\n throw error;\n }\n}\n\nfunction known(o: JsonObject, path: string, keys: readonly string[]): void {\n for (const name of jsonMemberNames(o)) {\n if (!keys.includes(name)) {\n const at = path === '' ? name : `${path}.${name}`;\n const value = jsonMember(o, name);\n const numbers = value instanceof JsonNumber || isJsonArray(value) ? ' a spec holds no numbers, only the columns they are read from;' : '';\n throw refuse(at, `${at} is not part of a Chart Spec:${numbers} ${path === '' ? 'a spec' : path} takes ${keys.join(', ')}.`);\n }\n }\n}\n\nfunction objectMember(o: JsonObject, key: string, path: string): JsonObject {\n const at = path === '' ? key : `${path}.${key}`;\n const e = jsonMember(o, key);\n if (e === undefined) {\n throw refuse(at, `${at} is missing.`);\n }\n if (!isJsonObject(e)) {\n throw refuse(at, `${at} is a JSON object.`);\n }\n return e;\n}\n\n// A text member, `undefined` where it is absent or null.\nfunction optionalString(o: JsonObject, key: string, path: string): string | undefined {\n const e = jsonMember(o, key);\n if (e === undefined || e === null) {\n return undefined;\n }\n if (typeof e === 'string') {\n return e;\n }\n const at = path === '' ? key : `${path}.${key}`;\n throw refuse(at, `${at} is text, not ${kindOf(e)}.`);\n}\n\nfunction requiredString(o: JsonObject, key: string, path: string, what: string): string {\n const text = optionalString(o, key, path);\n if (text === undefined) {\n throw missing(path, key, what);\n }\n return text;\n}\n\n// A JSON value's kind as System.Text.Json's `JsonValueKind` names it, in lower case.\nfunction kindOf(e: JsonValue): string {\n if (e === null) {\n return 'null';\n }\n if (typeof e === 'boolean') {\n return e ? 'true' : 'false';\n }\n if (typeof e === 'string') {\n return 'string';\n }\n if (e instanceof JsonNumber) {\n return 'number';\n }\n return isJsonArray(e) ? 'array' : 'object';\n}\n\nfunction optionalBool(o: JsonObject, key: string, path: string): boolean | undefined {\n const e = jsonMember(o, key);\n if (e === undefined || e === null) {\n return undefined;\n }\n if (typeof e !== 'boolean') {\n throw refuse(`${path}.${key}`, `${path}.${key} is true or false.`);\n }\n return e;\n}\n\nfunction choice<T>(o: JsonObject, key: string, path: string, choices: ReadonlyMap<string, T>, what: string): T {\n const at = `${path}.${key}`;\n const names = [...choices.keys()].join(', ');\n const text = optionalString(o, key, path);\n if (text === undefined) {\n throw refuse(at, `${at} is missing: it says ${what}, one of ${names}.`);\n }\n const chosen = choices.get(text);\n if (chosen === undefined) {\n throw refuse(at, `${at} \"${text}\" is not known: it is one of ${names}.`);\n }\n return chosen;\n}\n\nfunction missing(path: string, key: string, what: string): ChartSpecRefusedError {\n return refuse(`${path}.${key}`, `${path}.${key} is missing: ${what}.`);\n}\n\nfunction refuse(path: string, message: string): ChartSpecRefusedError {\n return new ChartSpecRefusedError(path, message);\n}\n", "// The Chart Source (ADR-0322, ADR-0344): where a chart reads a series' points, thinned where the data lives. A host\n// whose data is on a server thins it there and sends only the points kept; `chartSourceOver` thins a table held in\n// the page. `thinChartData` is the reference implementation, the specification a server's source answers as, and\n// the port of C#'s `ChartSource.Thin`, held to it by the shared cases under tests/cases/chart/ (ADR-0370, section 2).\nimport { decimalText } from '@ex-grid/data';\nimport { chartDataOf, type ChartData } from './chart-data';\nimport type { AxisValues, PixelSummary } from './model';\nimport { asDecimal, cellText, ChartSpecRefusedError, temporalDate } from './spec';\n\n/**\n * What a chart asks a {@link ChartSource} (ADR-0322, ADR-0344): one column of values, read across another, from\n * `from` to `to`, at `pixels` columns. The counterpart of C#'s `ChartSourceQuery`.\n */\nexport interface ChartSourceQuery {\n /** The Data Handle the series reads. */\n readonly data: string;\n /** The column across. */\n readonly x: string;\n /** The column of values. */\n readonly y: string;\n /** What the axis places: dates, as their day numbers, or numbers. A labels axis is never asked of a source. */\n readonly values: AxisValues;\n /** The first position asked for, in the axis' own values; `null` for the data's first. */\n readonly from: number | null;\n /** The last, or `null` for the data's last. */\n readonly to: number | null;\n /** How many columns the range is cut into, each keeping its first, last, lowest and highest point. */\n readonly pixels: number;\n}\n\n/**\n * A {@link ChartSource}'s answer (ADR-0344): the rows kept, in order across, as a table with the query's `x` and\n * `y` columns, what each thinned pixel held, and the version of the data it was read from. The counterpart of C#'s\n * `ChartSourceAnswer`.\n */\nexport interface ChartSourceAnswer {\n /** The version of the data the answer was read from, as a Snapshot names its own; an answer for an older one is never\n * drawn over a newer one. */\n readonly version: bigint;\n /** The rows kept, in order across. */\n readonly points: ChartData;\n /** What each pixel that held more than one row held, in the data's positions; empty when nothing was thinned. */\n readonly thinned: readonly PixelSummary[];\n}\n\n/**\n * Where a chart reads a series' points (ADR-0322): thinned where the data lives. The counterpart of C#'s\n * `IChartSource`.\n */\nexport interface ChartSource {\n /** Answers `query` with the points the chart draws; `signal` is aborted when the chart no longer waits for it. */\n thin(query: ChartSourceQuery, signal: AbortSignal): Promise<ChartSourceAnswer>;\n}\n\n/** A Chart Source over a table held in the page, thinning it as it is asked, its answers naming `version`; a refusal is\n * its promise's. */\nexport function chartSourceOver(data: ChartData, version = 0n): ChartSource {\n return Object.freeze({\n thin: async (query: ChartSourceQuery) => thinChartData(data, query, version),\n });\n}\n\ninterface Row {\n readonly x: number;\n readonly y: number | null;\n readonly row: number;\n}\n\n/**\n * Thins `data` as `query` asks (ADR-0344): the range cut into `pixels` equal columns, each keeping its first, last,\n * lowest and highest row (ADR-0254), never a row picked by LTTB; a row with no value kept where it is, so a gap stays a\n * gap. Rows are answered in order across, a row's place in the data breaking a tie. A table without the query's\n * columns, or a query of no pixels, of a range that is not finite or of a labels axis, is refused with a `TypeError`; a\n * position that is not the axis' kind, or a value that is no number, with a {@link ChartSpecRefusedError}.\n */\nexport function thinChartData(data: ChartData, query: ChartSourceQuery, version = 0n): ChartSourceAnswer {\n if (!Number.isInteger(query.pixels) || query.pixels < 1) throw new TypeError('A Chart Source is asked for one pixel or more.');\n if ((query.from !== null && !Number.isFinite(query.from)) || (query.to !== null && !Number.isFinite(query.to))) {\n throw new TypeError('A Chart Source is asked for a range of finite positions.');\n }\n if (query.values === 'labels') throw new TypeError('A labels axis needs every category, which a Chart Source does not thin.');\n for (const column of [query.x, query.y]) {\n if (!data.columns.includes(column)) {\n throw new TypeError(`\"${query.data}\" has no column \"${column}\"; its columns are ${data.columns.join(', ')}.`);\n }\n }\n const rows: Row[] = [];\n for (let r = 0; r < data.rowCount; r++) {\n const x = positionOf(data.value(query.x, r), query.values, query.data, r);\n if ((query.from !== null && x < query.from) || (query.to !== null && x > query.to)) continue;\n rows.push({ x, y: numberOf(data.value(query.y, r), query.data, r), row: r });\n }\n const ordered = rows.toSorted((a, b) => (a.x === b.x ? a.row - b.row : a.x - b.x));\n const xs: unknown[] = [];\n const ys: unknown[] = [];\n const thinned: PixelSummary[] = [];\n const keep = (at: number) => {\n const { row } = atRun(ordered, at);\n xs.push(data.value(query.x, row));\n ys.push(data.value(query.y, row));\n };\n // The rows from `first` to `last`, each with a value: kept whole when one, else the first, the lowest, the highest\n // and the last, in order.\n const keepRun = (first: number, last: number) => {\n if (first === last) {\n keep(first);\n return;\n }\n let lo = first;\n let hi = first;\n let low = heightOf(atRun(ordered, first));\n let high = low;\n for (let k = first + 1; k <= last; k++) {\n const y = heightOf(atRun(ordered, k));\n if (y < low) [lo, low] = [k, y];\n if (y > high) [hi, high] = [k, y];\n }\n const kept = [...new Set([first, lo, hi, last])].toSorted((a, b) => a - b);\n for (const k of kept) keep(k);\n // Said only where rows were left out: a pixel whose rows were all kept is drawn as they are.\n if (kept.length < last - first + 1) {\n thinned.push(Object.freeze({ from: atRun(ordered, first).x, to: atRun(ordered, last).x, min: low, max: high, count: last - first + 1 }));\n }\n };\n const [firstRow] = ordered;\n const lastRow = ordered.at(-1);\n if (firstRow !== undefined && lastRow !== undefined) {\n const low = query.from ?? firstRow.x;\n const width = (query.to ?? lastRow.x) - low;\n const columnOf = (x: number) => (width <= 0 ? 0 : Math.min(Math.max(Math.floor((x - low) / width * query.pixels), 0), query.pixels - 1));\n let i = 0;\n while (i < ordered.length) {\n const column = columnOf(atRun(ordered, i).x);\n let j = i;\n while (j + 1 < ordered.length && columnOf(atRun(ordered, j + 1).x) === column) j++;\n // Runs of rows with a value, each thinned on its own: a row with none is a gap, kept where it is.\n let start = i;\n for (let k = i; k <= j + 1; k++) {\n if (k <= j && atRun(ordered, k).y !== null) continue;\n if (k > start) keepRun(start, k - 1);\n if (k <= j) keep(k);\n start = k + 1;\n }\n i = j + 1;\n }\n }\n return Object.freeze({ version, points: chartDataOf([[query.x, xs], [query.y, ys]]), thinned: Object.freeze(thinned) });\n}\n\nfunction atRun(rows: readonly Row[], at: number): Row {\n const row = rows[at];\n if (row === undefined) throw new Error(`Internal: no row at ${String(at)} of the run.`);\n return row;\n}\n\nfunction heightOf(row: Row): number {\n if (row.y === null) throw new Error('Internal: a row with no value is thinned.');\n return row.y;\n}\n\nconst ticksPerDay = 864_000_000_000n;\n\n// A position as a Chart Spec reads one: a date's day number, or a number.\nfunction positionOf(value: unknown, values: AxisValues, data: string, row: number): number {\n const date = values === 'dates' ? temporalDate(value) : undefined;\n if (date !== undefined && date.ticks % ticksPerDay === 0n) return Number(date.ticks / ticksPerDay);\n if (values === 'numbers') {\n const n = numberOf(value, data, row);\n if (n !== null) return n;\n }\n const expected = values === 'dates' ? 'a date' : 'a number';\n throw new ChartSpecRefusedError('', `Row ${String(row + 1)} of \"${data}\" holds \"${cellText(value)}\" across, and the axis needs ${expected}.`);\n}\n\n// A value as a height, as C#'s `ChartSource` casts one to a double: a double, a whole number, a Snapshot's decimal as\n// the double nearest it; null for none.\nfunction numberOf(value: unknown, data: string, row: number): number | null {\n if (value === null) return null;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'bigint') return Number(value);\n const decimal = asDecimal(value);\n if (decimal !== undefined) return Number(decimalText(decimal));\n throw new ChartSpecRefusedError('', `Row ${String(row + 1)} of \"${data}\" holds \"${cellText(value)}\", which is not a number.`);\n}\n", "// What the tool an AI calls with a Chart Spec answers it (ADR-0320): the refusal, or the chart said in words\n// (ADR-0275) with how many pixels were thinned and how many points are missing. The port of the C# engine's\n// `ChartSpec.Answer`, held to it by the shared cases under tests/cases/chart/ (ADR-0370, section 3).\nimport type { ChartData } from './chart-data';\nimport type { ChartMetrics } from './metrics';\nimport { buildScene, type ChartScene } from './scene';\nimport { ChartSpecRefusedError, readChartSpec, type ChartSpecReading } from './spec';\nimport { chartSummary } from './summary';\nimport { surfaceSummary } from './surface-mesh';\nimport { ChartRefusedError } from './values';\n\n/** What the tool answers the AI: the counterpart of C#'s `ChartSpecAnswer`. */\nexport type ChartSpecAnswer =\n | {\n /** The chart can be drawn. */\n readonly accepted: true;\n /** The chart said in words, to check against what was meant. */\n readonly text: string;\n /** The spec read. */\n readonly reading: ChartSpecReading;\n }\n | {\n /** The chart cannot be drawn. */\n readonly accepted: false;\n /** The refusal, which names the path and the reason, for the AI to act on. */\n readonly text: string;\n /** No reading: nothing was drawn. */\n readonly reading: undefined;\n };\n\n/**\n * Reads `text`, a Chart Spec, against `tables` and answers as the tool answers the AI: the refusal, or the\n * chart said in words with how many pixels were thinned and how many points are missing, at `metrics`\n * (800 by 400 CSS pixels by default). A surface is said as a screen reader hears it, with why a scale it\n * asked for is not drawn. Anything thrown but a refusal of the spec or of the chart is thrown on.\n */\nexport function answerChartSpec(\n text: string, tables: (handle: string) => ChartData | undefined, metrics: ChartMetrics = { width: 800, height: 400 },\n): ChartSpecAnswer {\n let reading: ChartSpecReading;\n try {\n reading = readChartSpec(text, tables);\n } catch (error) { // oxlint-disable-line ex-grid/no-catch -- ADR-0320: a refused spec is the tool's answer, said to the AI; anything else is rethrown\n if (error instanceof ChartSpecRefusedError) {\n return { accepted: false, text: error.message, reading: undefined };\n }\n throw error;\n }\n const surface = reading.surface;\n if (surface !== undefined) {\n const said = except(surface.allNotes, surface.notes).filter(n => !n.startsWith('Interpolated by'));\n return { accepted: true, text: [surfaceSummary(surface, reading.title), ...said].join(' '), reading };\n }\n const definition = reading.definition;\n let scene: ChartScene;\n try {\n scene = buildScene(definition, metrics);\n } catch (error) { // oxlint-disable-line ex-grid/no-catch -- ADR-0320: a chart its definition refuses is the tool's answer, as C#'s; anything else is rethrown\n if (error instanceof ChartRefusedError) {\n return { accepted: false, text: error.message, reading: undefined };\n }\n throw error;\n }\n const parts = [chartSummary(definition, scene, reading.title)];\n const thinned = scene.panels.reduce((sum, p) => sum + p.series.reduce((n, s) => n + s.thinned.length, 0), 0);\n parts.push(thinned === 0 ? 'No pixel holds more than one point.'\n : `${String(thinned)} ${thinned === 1 ? 'pixel holds more than one point, and says its range' : 'pixels each hold more than one point, and say their range'}.`);\n const missing = definition.series.reduce((sum, s) => sum + s.points.filter(p => p.y === null).length, 0);\n parts.push(missing === 0 ? 'No point is missing.'\n : `${String(missing)} ${missing === 1 ? 'point is' : 'points are'} missing, drawn as ${missing === 1 ? 'a gap' : 'gaps'}.`);\n parts.push(...except(scene.notes, definition.notes));\n return { accepted: true, text: parts.join(' '), reading };\n}\n\n// The distinct lines of `lines` that `said` does not hold, in their order, as C#'s `Except` gives them.\nfunction except(lines: readonly string[], said: readonly string[]): string[] {\n const seen = new Set(said);\n const kept: string[] = [];\n for (const line of lines) {\n if (!seen.has(line)) {\n seen.add(line);\n kept.push(line);\n }\n }\n return kept;\n}\n", "// Fit helpers a Consumer may call (ADR-0291), as ExChart.Engine's `Fit` does. The chart never calls them: a\n// Consumer calls one, explicitly, and hands the result in as a series, so no fit sits on the drawing's path.\n// Each result names its method, its coefficients and the space it was fitted in, and its series carries that\n// as a Segment, so the Notes say it. None extrapolates: the series has values only between the smallest and\n// the largest x it was fitted on. The arithmetic is the C# engine's, step for step, so both engines answer\n// the same coefficients (tests/cases/chart/fitting.json).\nimport { roundTrip, twoPlaces, upToPlaces } from './invariant-text';\nimport type { ChartSeriesOptions } from './model';\nimport { elementAt } from './must';\nimport { greatest, least } from './numbers';\n\n/** The space a fit is made in (ADR-0291): y against x, ln y against x (an exponential), or ln y against ln x (a power law). */\nexport type FitSpace = 'linear' | 'logY' | 'logLog';\n\nconst spaces: ReadonlySet<string> = new Set(['linear', 'logY', 'logLog']);\n\n/** What a fitted curve is made of: the C# record's members. */\nexport interface FittedCurveOptions {\n /** The method's name, such as `OLS` or `Theil\u2013Sen`. */\n readonly method: string;\n /** The polynomial's coefficients from the constant up: for a line, the intercept then the slope. */\n readonly coefficients: readonly number[];\n /** The share of the variance it explains, in the space it was fitted in; never below zero for least squares, and below\n * zero for Theil\u2013Sen where it does worse than the mean. */\n readonly rSquared: number;\n /** How many points it was fitted on. */\n readonly count: number;\n /** The smallest x it was fitted on. */\n readonly from: number;\n /** The largest. */\n readonly to: number;\n /** The space it was fitted in; `linear` where absent. */\n readonly space?: FitSpace;\n}\n\n/**\n * A curve fitted by one of the fits (`fitLeastSquares`, `fitTheilSen`, `fitPolynomial`): its method, its\n * coefficients in the space it was fitted in, R\u00B2 there, how many points it was fitted on, and the range of x\n * they span (ADR-0291).\n */\nexport class FittedCurve {\n readonly #method: string;\n readonly #coefficients: readonly number[];\n readonly #rSquared: number;\n readonly #count: number;\n readonly #from: number;\n readonly #to: number;\n readonly #space: FitSpace;\n\n /** A curve of the given coefficients; refused when it has none, since a polynomial has a constant at least. */\n constructor(options: FittedCurveOptions) {\n const { space = 'linear' } = options;\n if (options.coefficients.length === 0) {\n throw new RangeError('A fitted curve has one coefficient at least, its constant.');\n }\n if (!spaces.has(space)) {\n throw new TypeError(`\"${space}\" is not a FitSpace; it is linear, logY or logLog.`);\n }\n this.#method = options.method;\n this.#coefficients = Object.freeze([...options.coefficients]);\n this.#rSquared = options.rSquared;\n this.#count = options.count;\n this.#from = options.from;\n this.#to = options.to;\n this.#space = space;\n }\n\n /** The method's name, such as `OLS` or `Theil\u2013Sen`. */\n get method(): string {\n return this.#method;\n }\n\n /** The polynomial's coefficients from the constant up: for a line, the intercept then the slope. */\n get coefficients(): readonly number[] {\n return this.#coefficients;\n }\n\n /** The share of the variance it explains, in the space it was fitted in; never below zero for least squares, and below\n * zero for Theil\u2013Sen where it does worse than the mean. */\n get rSquared(): number {\n return this.#rSquared;\n }\n\n /** How many points it was fitted on. */\n get count(): number {\n return this.#count;\n }\n\n /** The smallest x it was fitted on. */\n get from(): number {\n return this.#from;\n }\n\n /** The largest x it was fitted on. */\n get to(): number {\n return this.#to;\n }\n\n /** The space it was fitted in. */\n get space(): FitSpace {\n return this.#space;\n }\n\n /** The intercept: the constant coefficient. */\n get intercept(): number {\n return elementAt(this.#coefficients, 0);\n }\n\n /** The slope: the first-degree coefficient, or zero for a constant. */\n get slope(): number {\n return this.#coefficients.length > 1 ? elementAt(this.#coefficients, 1) : 0;\n }\n\n /** The polynomial's degree. */\n get degree(): number {\n return this.#coefficients.length - 1;\n }\n\n /**\n * Its Note: one line naming the method and the space, the equation for a line or the degree for a higher\n * polynomial, R\u00B2 and n (ADR-0291), such as `OLS: y = 41.2x + 88.5, R\u00B2 = 0.63, n = 212`.\n */\n get note(): string {\n const [y, x] = this.#space === 'logY' ? ['ln y', 'x'] : this.#space === 'logLog' ? ['ln y', 'ln x'] : ['y', 'x'];\n const on = this.#space === 'linear' ? '' : ` on ${y} vs ${x}`;\n const degree = this.degree;\n const intercept = this.intercept;\n const shape = degree === 0\n ? `${y} = ${coefficientText(intercept)}`\n : degree === 1\n ? `${y} = ${coefficientText(this.slope)}${x} ${intercept < 0 ? '\u2212' : '+'} ${coefficientText(Math.abs(intercept))}`\n : `degree ${String(degree)}`;\n return `${this.#method}${on}: ${shape}, R\u00B2 = ${twoPlaces(this.#rSquared)}, n = ${String(this.#count)}`;\n }\n\n /** The fitted value at `x`, back in y, or `null` outside the range it was fitted over or where it is not a finite number. */\n valueAt(x: number): number | null {\n if (!(x >= this.#from && x <= this.#to)) {\n return null;\n }\n const t = this.#space === 'logLog' ? Math.log(x) : x;\n let v = 0;\n for (let k = this.#coefficients.length - 1; k >= 0; k--) {\n v = v * t + elementAt(this.#coefficients, k);\n }\n if (this.#space !== 'linear') {\n v = Math.exp(v);\n }\n return Number.isFinite(v) ? v : null;\n }\n\n /**\n * The curve as a Level series over the range it was fitted on, sampled by the chart as it draws, read away\n * from zero, with one Segment named by its Note, so the Notes say it (ADR-0291).\n */\n series(id: string, name: string): ChartSeriesOptions {\n const from = this.#from;\n const to = this.#to;\n return Object.freeze({\n id, name, kind: 'level', fromZero: false,\n segments: Object.freeze([Object.freeze({ from, to, method: this.note, extrapolated: false })]),\n sampler: Object.freeze({ from, to, valueAt: (x: number) => this.valueAt(x) }),\n });\n }\n}\n\n// A coefficient in a Note, as C# writes it with \"0.###\".\nfunction coefficientText(v: number): string {\n return upToPlaces(v, 3);\n}\n\n/** The most points `fitTheilSen` takes: it weighs every pair, which past this is too many to run. */\nexport const theilSenLimit = 3_000;\n\n/**\n * Ordinary least squares (ADR-0291): the line that minimises the squared vertical distances, in `space`. A\n * point whose x or y is not a finite number, or whose logarithm the space cannot take, is refused.\n */\nexport function fitLeastSquares(xs: readonly number[], ys: readonly number[], space: FitSpace = 'linear'): FittedCurve {\n return fitted(xs, ys, 1, space, 'OLS');\n}\n\n/** Least squares of a polynomial of `degree` (ADR-0291), solved by Householder QR; degree 1 is `fitLeastSquares`. */\nexport function fitPolynomial(xs: readonly number[], ys: readonly number[], degree: number, space: FitSpace = 'linear'): FittedCurve {\n return fitted(xs, ys, degree, space, degree === 1 ? 'OLS' : 'Least squares');\n}\n\n/**\n * Theil\u2013Sen (ADR-0291): the median of the slopes between every pair of points with different x, and the\n * median of y\u1D62 \u2212 slope\u00B7x\u1D62 as the intercept. A single point far off does not drag it. More than\n * `theilSenLimit` points are refused.\n */\nexport function fitTheilSen(xs: readonly number[], ys: readonly number[], space: FitSpace = 'linear'): FittedCurve {\n const { x, y } = prepared(xs, ys, space, 2);\n if (x.length > theilSenLimit) {\n throw new TypeError(`Theil\u2013Sen weighs every pair of points; ${String(x.length)} points are more than the ${String(theilSenLimit)} it takes.`);\n }\n const slopes: number[] = [];\n for (let i = 0; i < x.length; i++) {\n const xi = elementAt(x, i);\n const yi = elementAt(y, i);\n for (let j = i + 1; j < x.length; j++) {\n const xj = elementAt(x, j);\n if (xi !== xj) {\n const run = xj - xi;\n const between = (elementAt(y, j) - yi) / run;\n // A slope past what a double holds would sort to an end and pass as a median or not by chance, and\n // a run past it reads as a slope of zero, so either is refused by the pair rather than weighed\n // (spine rule 1).\n if (!Number.isFinite(run)) {\n throw new TypeError(`Points ${String(i)} and ${String(j)} lie too far apart in x for the run between them to be a finite number.`);\n }\n if (!Number.isFinite(between)) {\n throw new TypeError(`Points ${String(i)} and ${String(j)} rise too steeply for the slope between them to be a finite number.`);\n }\n slopes.push(between);\n }\n }\n }\n if (slopes.length === 0) {\n throw new TypeError('Every point has the same x: no slope can be fitted.');\n }\n const slope = median(slopes);\n const intercept = median(x.map((xi, i) => elementAt(y, i) - slope * xi));\n return curve('Theil\u2013Sen', [intercept, slope], x, y, xs, space);\n}\n\nfunction fitted(xs: readonly number[], ys: readonly number[], degree: number, space: FitSpace, method: string): FittedCurve {\n if (!Number.isInteger(degree) || degree < 0) {\n throw new RangeError(`A polynomial's degree is a whole number not below zero, not ${roundTrip(degree)}.`);\n }\n const { x, y } = prepared(xs, ys, space, degree + 1);\n if (new Set(x).size <= degree) {\n throw new TypeError(`A polynomial of degree ${String(degree)} needs ${String(degree + 1)} different x at least.`);\n }\n // Centred and scaled x keeps the columns of the design matrix comparable, so degree 9 on [0, 1] is solved\n // as accurately as degree 1; the coefficients are mapped back afterwards.\n const lo = least(x);\n const hi = greatest(x);\n const mid = (lo + hi) / 2;\n const half = Math.max((hi - lo) / 2, Number.MIN_VALUE);\n // A span past what a double holds makes every centred x zero, which would read as points that do not determine\n // the polynomial.\n if (!Number.isFinite(mid) || !Number.isFinite(half)) {\n throw new TypeError('The points lie too far apart in x for a polynomial: their span is not a finite number.');\n }\n const n = degree + 1;\n const a: number[] = [];\n for (const xi of x) {\n const t = (xi - mid) / half;\n let p = 1;\n for (let k = 0; k <= degree; k++, p *= t) {\n a.push(p);\n }\n }\n const scaled = solveLeastSquares(a, x.length, n, y);\n const c = unscale(scaled, mid, half);\n kept(scaled, c, x, y, mid, half, degree, space);\n return curve(method, c, x, y, xs, space, true);\n}\n\n// Coefficients in powers of x far from zero cancel one another, and past a degree they no longer say the curve\n// that was fitted in centred x: the fitted values at the points are compared, and a curve that has lost them is\n// refused, never handed back as plausible coefficients (spine rule 1). A millionth of the values' spread is a loss\n// a reader could see; a few dozen units in the last place of the largest value is rounding the values themselves\n// carry, so a line through large values close together still fits.\nfunction kept(scaled: readonly number[], c: readonly number[], x: readonly number[], y: readonly number[], mid: number, half: number, degree: number, space: FitSpace): void {\n const tolerance = Math.max(1e-6 * (greatest(y) - least(y)), 64 * Number.EPSILON * greatest(y.map(v => Math.abs(v))));\n if (!Number.isFinite(tolerance)) {\n throw overflow();\n }\n for (const xi of x) {\n let inT = 0;\n let inX = 0;\n const t = (xi - mid) / half;\n for (let k = c.length - 1; k >= 0; k--) {\n inT = inT * t + elementAt(scaled, k);\n inX = inX * xi + elementAt(c, k);\n }\n if (!Number.isFinite(inT)) {\n throw overflow();\n }\n // Powers of x past what a double holds, where the centred curve is finite, are the same loss.\n if (!Number.isFinite(inX) || !(Math.abs(inT - inX) <= tolerance)) {\n throw new TypeError(space === 'logLog'\n // On ln x, dividing x by a constant is what moves the centre to zero.\n ? `A polynomial of degree ${String(degree)} on ln x near ${roundTrip(mid)} cannot be written in powers of ln x without losing its fit; fit it on x \u00F7 ${roundTrip(Math.exp(mid))} instead.`\n : `A polynomial of degree ${String(degree)} on x near ${roundTrip(mid)} cannot be written in powers of x without losing its fit; fit it on x \u2212 ${roundTrip(mid)} instead.`);\n }\n }\n}\n\n// R\u00B2 over the points in the space the fit was made in, the curve's range over the points as handed in.\nfunction curve(method: string, c: readonly number[], x: readonly number[], y: readonly number[], xs: readonly number[], space: FitSpace, leastSquares = false): FittedCurve {\n // A mean as .NET's Average takes it: summed in order, then divided.\n let sum = 0;\n for (const v of y) {\n sum += v;\n }\n const mean = sum / y.length;\n let res = 0;\n let tot = 0;\n for (let i = 0; i < x.length; i++) {\n const xi = elementAt(x, i);\n const yi = elementAt(y, i);\n let f = 0;\n for (let k = c.length - 1; k >= 0; k--) {\n f = f * xi + elementAt(c, k);\n }\n res += (yi - f) * (yi - f);\n tot += (yi - mean) * (yi - mean);\n }\n // Sums past what a double holds would read as an R\u00B2 of 1 or, clamped, of 0.\n if (c.some(v => !Number.isFinite(v)) || !Number.isFinite(res) || !Number.isFinite(tot)) {\n throw overflow();\n }\n const explained = tot === 0 ? (res === 0 ? 1 : 0) : 1 - res / tot;\n // Least squares with a constant does no worse than the mean, so its R\u00B2 is never below zero: a value a hair below\n // is rounding, which would read `R\u00B2 = -0.00`, and one further below is a solve that failed, which is refused\n // rather than shown as 0.00 (Theil\u2013Sen's may truly be below).\n if (leastSquares && explained < -1e-9) {\n throw new TypeError('The least-squares solve failed at these values: the fit does worse than their mean.');\n }\n const rSquared = leastSquares ? Math.max(explained, 0) : explained;\n return new FittedCurve({ method, coefficients: c, rSquared, count: x.length, from: least(xs), to: greatest(xs), space });\n}\n\nfunction overflow(): TypeError {\n return new TypeError('The fit overflows at these values: its coefficients or its R\u00B2 are not finite numbers.');\n}\n\n// The points in the space the fit is made in: ln y, and ln x for a power law. A value a logarithm cannot take\n// is refused by name, never dropped (ADR-0290); so is a point that is not a finite number.\nfunction prepared(xs: readonly number[], ys: readonly number[], space: FitSpace, fewest: number): { x: number[]; y: number[] } {\n if (!Array.isArray(xs) || !Array.isArray(ys)) {\n throw new TypeError('A fit takes its xs and its ys as lists of numbers.');\n }\n if (!spaces.has(space)) {\n throw new TypeError(`\"${space}\" is not a FitSpace; it is linear, logY or logLog.`);\n }\n if (xs.length !== ys.length) {\n throw new TypeError('Each x needs one y.');\n }\n if (xs.length < fewest) {\n throw new TypeError(`The method needs ${String(fewest)} points at least.`);\n }\n const x: number[] = [];\n const y: number[] = [];\n for (let i = 0; i < xs.length; i++) {\n // Read as what an untyped caller may have handed in, and checked.\n const xi: unknown = xs[i];\n const yi: unknown = ys[i];\n if (typeof xi !== 'number' || typeof yi !== 'number' || !Number.isFinite(xi) || !Number.isFinite(yi)) {\n throw new TypeError(`Point ${String(i)} is not a finite number.`);\n }\n if (space !== 'linear' && !(yi > 0)) {\n throw new TypeError(`Point ${String(i)} has y = ${roundTrip(yi)}, whose logarithm a fit on ln y cannot take.`);\n }\n if (space === 'logLog' && !(xi > 0)) {\n throw new TypeError(`Point ${String(i)} has x = ${roundTrip(xi)}, whose logarithm a fit on ln x cannot take.`);\n }\n x.push(space === 'logLog' ? Math.log(xi) : xi);\n y.push(space === 'linear' ? yi : Math.log(yi));\n }\n return { x, y };\n}\n\n// min \u2016Ac \u2212 b\u2016 by Householder QR, then back substitution; `a` is m rows of n, row by row.\nfunction solveLeastSquares(a: readonly number[], m: number, n: number, b: readonly number[]): number[] {\n const r = [...a];\n const q = [...b];\n const at = (i: number, j: number): number => elementAt(r, i * n + j);\n for (let k = 0; k < n; k++) {\n let norm = 0;\n for (let i = k; i < m; i++) {\n norm += at(i, k) * at(i, k);\n }\n norm = Math.sqrt(norm);\n if (norm === 0) {\n throw new TypeError('The points do not determine the polynomial.');\n }\n const alpha = at(k, k) > 0 ? -norm : norm;\n const v = Array.from({ length: m }, () => 0);\n v[k] = at(k, k) - alpha;\n for (let i = k + 1; i < m; i++) {\n v[i] = at(i, k);\n }\n let vv = 0;\n for (let i = k; i < m; i++) {\n vv += elementAt(v, i) * elementAt(v, i);\n }\n if (vv === 0) {\n continue;\n }\n for (let j = k; j < n; j++) {\n let d = 0;\n for (let i = k; i < m; i++) {\n d += elementAt(v, i) * at(i, j);\n }\n d = 2 * d / vv;\n for (let i = k; i < m; i++) {\n r[i * n + j] = at(i, j) - d * elementAt(v, i);\n }\n }\n let e = 0;\n for (let i = k; i < m; i++) {\n e += elementAt(v, i) * elementAt(q, i);\n }\n e = 2 * e / vv;\n for (let i = k; i < m; i++) {\n q[i] = elementAt(q, i) - e * elementAt(v, i);\n }\n }\n const c = Array.from({ length: n }, () => 0);\n for (let k = n - 1; k >= 0; k--) {\n let s = elementAt(q, k);\n for (let j = k + 1; j < n; j++) {\n s -= at(k, j) * elementAt(c, j);\n }\n c[k] = s / at(k, k);\n }\n return c;\n}\n\n// Coefficients in t = (x \u2212 mid) / half mapped back to coefficients in x: \u03A3 s\u2096 ((x \u2212 mid)/half)^k, expanded by\n// the binomial theorem.\nfunction unscale(scaled: readonly number[], mid: number, half: number): number[] {\n const n = scaled.length;\n const c = Array.from({ length: n }, () => 0);\n for (let k = 0; k < n; k++) {\n const coeff = elementAt(scaled, k) / half ** k;\n let binom = 1;\n for (let j = 0; j <= k; j++) {\n c[j] = elementAt(c, j) + coeff * binom * (-mid) ** (k - j);\n binom = binom * (k - j) / (j + 1);\n }\n }\n return c;\n}\n\nfunction median(values: readonly number[]): number {\n const sorted = values.toSorted((a, b) => a - b);\n const n = sorted.length;\n const middle = Math.floor(n / 2);\n return n % 2 === 1 ? elementAt(sorted, middle) : (elementAt(sorted, middle - 1) + elementAt(sorted, middle)) / 2;\n}\n", "// Interpolation helpers a Consumer may call (ADR-0257), as ExChart.Engine's `Interpolate` does. The chart never\n// calls them: a Consumer calls one, explicitly, and hands the result in as a function, so no interpolation sits\n// on the drawing's path. Each result carries its method's name, which the chart shows as it is, so an\n// interpolated curve or surface is never drawn silently as data. Only general methods live here; a\n// finance-specific choice stays the Consumer's. None extrapolates: outside the points it was made from, a\n// result has no value, and the chart draws a gap or a hole there (ADR-0274). The arithmetic is the C#\n// engine's, step for step (tests/cases/chart/interpolation.json).\nimport type { ChartSeriesOptions } from './model';\nimport { elementAt } from './must';\nimport { least, greatest } from './numbers';\nimport { SurfaceDefinition, type SurfaceSampledOptions, type SurfaceTriangle } from './surface';\n\n/** What a curve interpolated by one of the methods is made of: the C# record's members. */\nexport interface Interpolant1DOptions {\n /** The method's name, shown as it is, such as `natural cubic spline`. */\n readonly method: string;\n /** The first position it has a value at. */\n readonly from: number;\n /** The last position it has a value at. */\n readonly to: number;\n /** Its value at a position, `null` outside `from`\u2013`to`. */\n readonly evaluate: (x: number) => number | null;\n}\n\n/**\n * A curve interpolated by one of the methods (`interpolateLinear`, `interpolateNaturalCubicSpline`): its\n * method's name, the range it has values over, and its value at a position, `null` outside that range\n * (ADR-0257).\n */\nexport class Interpolant1D {\n readonly #method: string;\n readonly #from: number;\n readonly #to: number;\n readonly #evaluate: (x: number) => number | null;\n\n /** A curve of the given method and function. */\n constructor(options: Interpolant1DOptions) {\n this.#method = options.method;\n this.#from = options.from;\n this.#to = options.to;\n this.#evaluate = options.evaluate;\n }\n\n /** The method's name, shown as it is, such as `natural cubic spline`. */\n get method(): string {\n return this.#method;\n }\n\n /** The first position it has a value at. */\n get from(): number {\n return this.#from;\n }\n\n /** The last position it has a value at. */\n get to(): number {\n return this.#to;\n }\n\n /** Its value at a position, `null` outside `from`\u2013`to`, as the function it was made with answers. */\n get evaluate(): (x: number) => number | null {\n return this.#evaluate;\n }\n\n /** The value at `x`, or `null` outside the range it was made over or where it is not a finite number. */\n valueAt(x: number): number | null {\n const v = this.#evaluate(x);\n return v !== null && Number.isFinite(v) ? v : null;\n }\n\n /**\n * The curve as a series declared Interpolated, sampled by the chart as it draws, with one Segment named by\n * the method, so the tooltip and the Notes say it (ADR-0257).\n */\n series(id: string, name: string): ChartSeriesOptions {\n const from = this.#from;\n const to = this.#to;\n return Object.freeze({\n id, name, kind: 'level', interpolated: true,\n segments: Object.freeze([Object.freeze({ from, to, method: this.#method, extrapolated: false })]),\n sampler: Object.freeze({ from, to, valueAt: (x: number) => this.valueAt(x) }),\n });\n }\n}\n\n/** What a surface interpolated by one of the methods is made of: the C# record's members. */\nexport interface Interpolant2DOptions {\n /** The method's name, shown as it is, such as `bilinear`. */\n readonly method: string;\n /** The rectangle's left edge. */\n readonly xFrom: number;\n /** Its right edge. */\n readonly xTo: number;\n /** Its near edge. */\n readonly yFrom: number;\n /** Its far edge. */\n readonly yTo: number;\n /** Its value at a point, or `null` where it has none. */\n readonly evaluate: (x: number, y: number) => number | null;\n}\n\n/**\n * What a surface from an interpolant is sampled with besides: everything `SurfaceDefinition.sampled` takes but\n * the method, the rectangle and the function, which the interpolant gives.\n */\nexport type InterpolatedSurfaceOptions = Omit<SurfaceSampledOptions, 'method' | 'xFrom' | 'xTo' | 'yFrom' | 'yTo' | 'z'>;\n\n/**\n * A surface interpolated by one of the methods (`interpolateBilinear`, `interpolateTriangles`): its method's\n * name, the rectangle it is evaluated over, and its value at a point, `null` where it has none \u2014 outside the\n * points it was made from, or where a value it would need is missing (ADR-0257, ADR-0274).\n */\nexport class Interpolant2D {\n readonly #method: string;\n readonly #xFrom: number;\n readonly #xTo: number;\n readonly #yFrom: number;\n readonly #yTo: number;\n readonly #evaluate: (x: number, y: number) => number | null;\n\n /** A surface of the given method and function. */\n constructor(options: Interpolant2DOptions) {\n this.#method = options.method;\n this.#xFrom = options.xFrom;\n this.#xTo = options.xTo;\n this.#yFrom = options.yFrom;\n this.#yTo = options.yTo;\n this.#evaluate = options.evaluate;\n }\n\n /** The method's name, shown as it is, such as `bilinear`. */\n get method(): string {\n return this.#method;\n }\n\n /** The rectangle's left edge. */\n get xFrom(): number {\n return this.#xFrom;\n }\n\n /** Its right edge. */\n get xTo(): number {\n return this.#xTo;\n }\n\n /** Its near edge. */\n get yFrom(): number {\n return this.#yFrom;\n }\n\n /** Its far edge. */\n get yTo(): number {\n return this.#yTo;\n }\n\n /** Its value at a point, or `null`, as the function it was made with answers. */\n get evaluate(): (x: number, y: number) => number | null {\n return this.#evaluate;\n }\n\n /** The value at (`x`, `y`), or `null` where it has none or where it is not a finite number. */\n valueAt(x: number, y: number): number | null {\n const v = this.#evaluate(x, y);\n return v !== null && Number.isFinite(v) ? v : null;\n }\n\n /**\n * The surface sampled across its rectangle under its method's name, as `SurfaceDefinition.sampled` samples a\n * function (ADR-0257): every value marked interpolated, a hole where it has none.\n */\n surface(options: InterpolatedSurfaceOptions): SurfaceDefinition {\n return SurfaceDefinition.sampled({\n ...options,\n method: this.#method, xFrom: this.#xFrom, xTo: this.#xTo, yFrom: this.#yFrom, yTo: this.#yTo,\n z: (x, y) => this.valueAt(x, y),\n });\n }\n}\n\n/** A point of a Consumer's mesh: its position and its value. */\nexport interface MeshPoint {\n /** Its x position. */\n readonly x: number;\n /** Its y position. */\n readonly y: number;\n /** Its value. */\n readonly z: number;\n}\n\n/** Straight lines between neighbouring points (ADR-0257); `xs` strictly increasing. */\nexport function interpolateLinear(xs: readonly number[], ys: readonly number[]): Interpolant1D {\n check(xs, ys.length, 2);\n finite(ys);\n const x = [...xs];\n const y = [...ys];\n const first = elementAt(x, 0);\n const last = elementAt(x, x.length - 1);\n return new Interpolant1D({\n method: 'linear', from: first, to: last,\n evaluate: t => {\n if (!(t >= first && t <= last)) {\n return null;\n }\n const k = interval(x, t);\n const xk = elementAt(x, k);\n const yk = elementAt(y, k);\n const f = (t - xk) / (elementAt(x, k + 1) - xk);\n return yk + f * (elementAt(y, k + 1) - yk);\n },\n });\n}\n\n/** A natural cubic spline through the points (ADR-0257): zero second derivative at both ends; `xs` strictly increasing. */\nexport function interpolateNaturalCubicSpline(xs: readonly number[], ys: readonly number[]): Interpolant1D {\n check(xs, ys.length, 3);\n finite(ys);\n const x = [...xs];\n const y = [...ys];\n const m = secondDerivatives(x, y);\n const first = elementAt(x, 0);\n const last = elementAt(x, x.length - 1);\n return new Interpolant1D({\n method: 'natural cubic spline', from: first, to: last,\n evaluate: t => {\n if (!(t >= first && t <= last)) {\n return null;\n }\n const k = interval(x, t);\n const xk = elementAt(x, k);\n const xk1 = elementAt(x, k + 1);\n const h = xk1 - xk;\n const a = (xk1 - t) / h;\n const b = (t - xk) / h;\n return a * elementAt(y, k) + b * elementAt(y, k + 1) + ((a * a * a - a) * elementAt(m, k) + (b * b * b - b) * elementAt(m, k + 1)) * h * h / 6;\n },\n });\n}\n\n/**\n * Bilinear interpolation on a grid (ADR-0257): `z` holds one row per y value and one value per x value, both\n * axes strictly increasing. A cell with a missing corner, `null`, has no value inside (ADR-0274).\n */\nexport function interpolateBilinear(xs: readonly number[], ys: readonly number[], z: readonly (readonly (number | null)[])[]): Interpolant2D {\n check(xs, xs.length, 2, 'X position');\n check(ys, ys.length, 2, 'Y position');\n if (z.length !== ys.length || z.some(r => r.length !== xs.length)) {\n throw new TypeError('The table needs one row per y value, each with one value per x value.');\n }\n for (let j = 0; j < z.length; j++) {\n const row = elementAt(z, j);\n for (let i = 0; i < row.length; i++) {\n // Read as what an untyped caller may have handed in: a hole in the list is no number either.\n const value: unknown = row[i];\n if (value !== null && (typeof value !== 'number' || !Number.isFinite(value))) {\n throw new TypeError(`The table's value in row ${String(j)}, column ${String(i)} is not a finite number; a missing value is null.`);\n }\n }\n }\n const x = [...xs];\n const y = [...ys];\n const table = z.map(r => [...r]);\n const xFrom = elementAt(x, 0);\n const xTo = elementAt(x, x.length - 1);\n const yFrom = elementAt(y, 0);\n const yTo = elementAt(y, y.length - 1);\n return new Interpolant2D({\n method: 'bilinear', xFrom, xTo, yFrom, yTo,\n evaluate: (u, v) => {\n if (!(u >= xFrom && u <= xTo && v >= yFrom && v <= yTo)) {\n return null;\n }\n const i = interval(x, u);\n const j = interval(y, v);\n const near = elementAt(table, j);\n const far = elementAt(table, j + 1);\n const z00 = elementAt(near, i);\n const z10 = elementAt(near, i + 1);\n const z01 = elementAt(far, i);\n const z11 = elementAt(far, i + 1);\n if (z00 === null || z10 === null || z01 === null || z11 === null) {\n return null;\n }\n const xi = elementAt(x, i);\n const yj = elementAt(y, j);\n const fx = (u - xi) / (elementAt(x, i + 1) - xi);\n const fy = (v - yj) / (elementAt(y, j + 1) - yj);\n return (1 - fy) * ((1 - fx) * z00 + fx * z10) + fy * ((1 - fx) * z01 + fx * z11);\n },\n });\n}\n\n/**\n * Linear interpolation on a triangle mesh (P1, ADR-0257): within each triangle the plane through its three\n * corners. `triangles` index into `points`; outside every triangle there is no value. The mesh is the\n * Consumer's, from its own solver or triangulation.\n */\nexport function interpolateTriangles(points: readonly MeshPoint[], triangles: readonly SurfaceTriangle[]): Interpolant2D {\n if (triangles.length === 0) {\n throw new TypeError('A mesh needs a triangle.');\n }\n for (const { a, b, c } of triangles) {\n if ([a, b, c].some(k => !Number.isInteger(k) || k < 0 || k >= points.length)) {\n throw new TypeError('A triangle names a point the mesh does not hold.');\n }\n }\n for (let k = 0; k < points.length; k++) {\n const q: MeshPoint | undefined = points[k];\n if (q === undefined || !Number.isFinite(q.x) || !Number.isFinite(q.y) || !Number.isFinite(q.z)) {\n throw new TypeError(`Point ${String(k)} is not a finite number.`);\n }\n }\n const p = points.map(q => Object.freeze({ x: q.x, y: q.y, z: q.z }));\n const t = triangles.map(q => Object.freeze({ a: q.a, b: q.b, c: q.c }));\n return new Interpolant2D({\n method: 'linear on triangles (P1)',\n xFrom: least(p.map(q => q.x)), xTo: greatest(p.map(q => q.x)), yFrom: least(p.map(q => q.y)), yTo: greatest(p.map(q => q.y)),\n evaluate: (u, v) => {\n for (const { a, b, c } of t) {\n const pa = elementAt(p, a);\n const pb = elementAt(p, b);\n const pc = elementAt(p, c);\n const det = (pb.y - pc.y) * (pa.x - pc.x) + (pc.x - pb.x) * (pa.y - pc.y);\n if (det === 0) {\n continue;\n }\n const l1 = ((pb.y - pc.y) * (u - pc.x) + (pc.x - pb.x) * (v - pc.y)) / det;\n const l2 = ((pc.y - pa.y) * (u - pc.x) + (pa.x - pc.x) * (v - pc.y)) / det;\n const l3 = 1 - l1 - l2;\n if (l1 >= edge && l2 >= edge && l3 >= edge) {\n return l1 * pa.z + l2 * pb.z + l3 * pc.z;\n }\n }\n return null;\n },\n });\n}\n\n// How far outside a triangle a point may lie, in its barycentric coordinates, and still be read on it, so a\n// point on an edge shared by two triangles is never a hole.\nconst edge = -1e-12;\n\nfunction check(xs: readonly number[], count: number, fewest: number, position = 'Position'): void {\n if (xs.length !== count) {\n throw new TypeError('Each position needs one value.');\n }\n if (xs.length < fewest) {\n throw new TypeError(`The method needs ${String(fewest)} points at least.`);\n }\n for (let k = 0; k < xs.length; k++) {\n if (!Number.isFinite(xs[k])) {\n throw new TypeError(`${position} ${String(k)} is not a finite number.`);\n }\n }\n for (let k = 1; k < xs.length; k++) {\n if (!(elementAt(xs, k - 1) < elementAt(xs, k))) {\n throw new TypeError('The positions must be strictly increasing.');\n }\n }\n}\n\n// A value that is no number would spread to every interval a spline or a line reads it in, so it is refused by\n// its place rather than drawn (spine rule 1).\nfunction finite(ys: readonly number[]): void {\n for (let k = 0; k < ys.length; k++) {\n if (!Number.isFinite(ys[k])) {\n throw new TypeError(`Value ${String(k)} is not a finite number.`);\n }\n }\n}\n\n// The interval [x[k], x[k+1]] that holds t, which lies within x[0]..x[^1]: the last x at or below t, as C#'s\n// Array.BinarySearch finds it in strictly increasing positions, kept off the last position.\nfunction interval(x: readonly number[], t: number): number {\n let lo = 0;\n let hi = x.length - 1;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (elementAt(x, mid) <= t) {\n lo = mid;\n } else {\n hi = mid - 1;\n }\n }\n return Math.min(Math.max(lo, 0), x.length - 2);\n}\n\nfunction secondDerivatives(x: readonly number[], y: readonly number[]): number[] {\n const n = x.length;\n const m = Array.from({ length: n }, () => 0);\n const c = Array.from({ length: n }, () => 0);\n const d = Array.from({ length: n }, () => 0);\n for (let k = 1; k < n - 1; k++) {\n const h0 = elementAt(x, k) - elementAt(x, k - 1);\n const h1 = elementAt(x, k + 1) - elementAt(x, k);\n const rhs = 6 * ((elementAt(y, k + 1) - elementAt(y, k)) / h1 - (elementAt(y, k) - elementAt(y, k - 1)) / h0);\n const diag = 2 * (h0 + h1) - h0 * elementAt(c, k - 1);\n c[k] = h1 / diag;\n d[k] = (rhs - h0 * elementAt(d, k - 1)) / diag;\n }\n for (let k = n - 2; k >= 1; k--) {\n m[k] = elementAt(d, k) - elementAt(c, k) * elementAt(m, k + 1);\n }\n return m;\n}\n", "// A chart in the DOM (ADR-0370 section 1): ExChart's Script Core builds and updates the elements inside\n// the instance root itself, to the DOM contract the Razor component writes, so ex-chart.css and layer 3\n// read both alike. The drawing is SVG written in parts (ADR-0252): a part whose markup did not change is\n// not touched, so a move of the pointer rewrites the tooltip and the guide and nothing else.\n//\n// It holds no view state of the Consumer's (ADR-0272): what the user changes \u2014 a series hidden from the\n// legend, the range narrowed by a drag or under Chart Filters, the axis switched \u2014 is raised as an event\n// and taken back as an option, in the data's terms, so it applies to new data as it is. An option that\n// changed replaces what the user last did; one that did not leaves it.\n//\n// The pointer is heard here, where the Razor component needed a script entry to hear it without a round\n// trip per move (ADR-0255): only a move onto another position or mark is read, and nothing is measured \u2014\n// a position's pixel is the scene's, and the pointer's is the event's offset on the hit layer it is over,\n// whose own offsets the layer carries. A press taken against one drawing is refused when it is released\n// against another (spine rule 6).\nimport { densityText, type DensityText, type GridDensity } from '@ex-grid/core';\nimport { ChartDefinition } from '../definition';\nimport type { ChartMetrics, ChartView } from '../metrics';\nimport type { AxisScale } from '../model';\nimport { defined, elementAt } from '../must';\nimport { roundHalfToEven, roundToDigits } from '../numbers';\nimport { chartCsvWide, chartTable, type ChartTable } from '../csv';\nimport { readingAt, readingOfEdge, readingOfMark, type ChartReading } from '../reading';\nimport { buildScene, legendMembers, positionAt, valueAt, type ChartScene, type LegendPlacement } from '../scene';\nimport { chartSummary } from '../summary';\nimport type { AxisStyle } from '../ticks';\nimport { ChartSlot, checkedChartChrome, type ChartChrome, type ChartCommand, type ChartFiltersSlotContext, type ChartMenuSlotContext, type ChartToolbarSlotContext } from './chart-chrome';\nimport { bandMarkup, drawingParts, guideMarkup, tooltipMarkup, type DrawingPart, type GuideDot } from './chart-drawing';\nimport { fileName, mediaType, paintPng, save, screenTheme, svgFile, type ChartFileFormat } from './chart-files';\nimport { chartWord, chartWordIds, type ChartLabel } from './chart-words';\nimport { readEnd, writeEnd } from './range-text';\nimport { stylesheetName, stylesheetStamp } from './shipped-stylesheet';\nimport { n } from './svg-markup';\n\n/**\n * The range of the horizontal axis the user narrowed the chart to (ADR-0273), in the axis' own values \u2014 a\n * date's day number, a number, a category's index \u2014 never in pixels (ADR-0272). An end left out is the\n * data's own.\n */\nexport interface ChartRange {\n /** The first position shown; absent for the data's first. */\n readonly from?: number;\n /** The last position shown; absent for the data's last. */\n readonly to?: number;\n /** The lowest value the left axis shows, which a rectangle dragged across a scatter narrows (ADR-0290); absent for the data's. */\n readonly yFrom?: number;\n /** The highest; absent for the data's. */\n readonly yTo?: number;\n}\n\n/** A series the user hid or showed from the legend (ADR-0271, ADR-0272). */\nexport interface SeriesVisibility {\n /** The legend entry's key: the series' identity, which for quotes and their Interpolated curve is the quotes' and hides both (ADR-0257). */\n readonly key: string;\n /** Whether it is now hidden. */\n readonly hidden: boolean;\n}\n\n/** A click on a point of a chart (ADR-0258): the series nearest the pointer, at the position clicked. */\nexport interface ChartPointClick {\n /** The series' identity, as the Chart Definition gives it. */\n readonly seriesId: string;\n /** The position clicked, in the axis' own values. */\n readonly position: number;\n /** The Row Key of an Observation's point clicked, as its point gives it (ADR-0290); absent otherwise. */\n readonly row?: unknown;\n}\n\n/** What a chart is drawn from, and what it tells. */\nexport interface ChartOptions {\n /** The chart, in the data's terms. */\n readonly definition: ChartDefinition;\n /** The drawing's width in CSS pixels; geometry is an option, never only a stylesheet value (ADR-0027). 800 unless given. */\n readonly width?: number;\n /** The drawing's height in CSS pixels; 400 unless given. */\n readonly height?: number;\n /** The density whose font size and glyph widths lay out the labels, as a grid's (ADR-0016, ADR-0028); `standard` unless given. */\n readonly density?: GridDensity;\n /** The chart's name, which its accessible summary and its table's caption begin with (ADR-0275). */\n readonly title?: string;\n /** A description the Consumer adds after the generated summary. */\n readonly description?: string;\n /** Where the legend sits: top (the default), bottom, left or right, aligned, or none (ADR-0271). */\n readonly legend?: LegendPlacement;\n /** How the horizontal axis places and writes its ticks. */\n readonly axisStyle?: AxisStyle;\n /** The panels whose left and right axes the Consumer declared independent (ADR-0251). */\n readonly independentScales?: ReadonlySet<string> | readonly string[];\n /** How many colour slots the stylesheet defines: ten, unless a theme declares more (ADR-0256). */\n readonly colourSlots?: number;\n /** The keys of the series hidden, taken back from `onSeriesVisibilityChanged`. */\n readonly hiddenSeries?: ReadonlySet<string> | readonly string[];\n /** Hears the user hide or show a series from the legend. */\n readonly onSeriesVisibilityChanged?: (change: SeriesVisibility) => void;\n /** The range shown, taken back from `onRangeChanged`; absent or `null` for the whole range. */\n readonly range?: ChartRange | null;\n /** Hears the user narrow the range, or return it to the whole (`null`). */\n readonly onRangeChanged?: (range: ChartRange | null) => void;\n /** The scale the horizontal axis is switched to, taken back from `onScaleChanged`; absent for the declared one. */\n readonly scale?: AxisScale;\n /** Hears the user switch the horizontal axis under Chart Filters. */\n readonly onScaleChanged?: (scale: AxisScale) => void;\n /** The vertical axes' scale: `logarithmic`, or absent for proportional (ADR-0290). A value at or below zero keeps them proportional, with a Note naming it. */\n readonly yScale?: AxisScale;\n /** Hears a click on a point: pressed and released at one position, on the series nearest the pointer that has a value there (ADR-0258). */\n readonly onPointClick?: (click: ChartPointClick) => void;\n /** The name a saved file takes, without its extension; the title's when absent, else `chart` (ADR-0282). */\n readonly fileName?: string;\n /** The words of the built-in markup by id (ADR-0370 section 10): the Consumer's, `japaneseChartWords`, or the English. */\n readonly label?: ChartLabel;\n /** The parts a Wrapper's Chrome draws in place of the built-in markup: the toolbar and the context menu's\n * contents (ADR-0281, ADR-0390). */\n readonly chrome?: ChartChrome;\n}\n\n// The lattice, in CSS pixels, a drag across a scatter is followed on (ADR-0290).\nconst dragCell = 4;\n\n// A summary's id, unique on the page even beside another copy of this package: random, as the Razor\n// component's is a GUID.\nfunction uniqueId(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(8));\n return `ex-chart-${Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')}`;\n}\n\nconst svgNs = 'http://www.w3.org/2000/svg';\n\ninterface Taken {\n readonly hidden: ReadonlySet<string>;\n readonly range: ChartRange | null;\n readonly scale: AxisScale | undefined;\n}\n\ninterface Press {\n readonly version: number;\n readonly index: number;\n}\n\ninterface ScatterPress {\n readonly version: number;\n readonly index: number;\n readonly x: number;\n readonly y: number;\n readonly panel: number;\n}\n\ninterface Pointer {\n readonly x: number;\n readonly y: number;\n readonly panel: number;\n}\n\ninterface Built {\n readonly metrics: ChartMetrics;\n readonly lineHeight: number;\n readonly fontSize: number;\n readonly view: ChartView;\n readonly scene: ChartScene;\n readonly summary: string;\n}\n\ninterface Command {\n readonly id: string;\n readonly label: string;\n readonly enabled: boolean;\n readonly run: () => void;\n readonly expanded?: boolean;\n readonly title?: string;\n}\n\nconst sameRange = (a: ChartRange | null, b: ChartRange | null): boolean =>\n a === b || (a !== null && b !== null && a.from === b.from && a.to === b.to && a.yFrom === b.yFrom && a.yTo === b.yTo);\n\nconst sameSet = (a: ReadonlySet<string>, b: ReadonlySet<string>): boolean => a.size === b.size && [...a].every(k => b.has(k));\n\n/** Two plain values alike: numbers, strings, arrays, sets and objects of them, compared by what they hold. */\nfunction plain(value: unknown): value is object {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction alike(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n if (a instanceof Set && b instanceof Set) {\n return a.size === b.size && [...a].every(k => b.has(k));\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => alike(v, b[i]));\n }\n // Only plain objects compare by their entries: an instance, such as a Chart Definition, holds its state where\n // entries do not reach, so it is the same only when it is the same instance.\n if (plain(a) && plain(b)) {\n const ea: [string, unknown][] = Object.entries(a);\n const eb = new Map<string, unknown>(Object.entries(b));\n return ea.length === eb.size && ea.every(([k, v]) => eb.has(k) && alike(v, eb.get(k)));\n }\n return false;\n}\n\nconst setOf = (keys: ReadonlySet<string> | readonly string[] | undefined): ReadonlySet<string> => new Set(keys);\n\n/** The chart behind {@link createChart}'s handle. */\nexport class ChartElement {\n readonly #root: HTMLElement;\n readonly #summaryId: string;\n #options: ChartOptions;\n #destroyed = false;\n\n // What the user changed, as last taken from an option or a gesture, and the options it was taken from.\n #hidden: ReadonlySet<string> = new Set();\n #range: ChartRange | null = null;\n #scale: AxisScale | undefined;\n #taken: Taken | undefined;\n\n // The scene and what it was built from.\n #text: DensityText | undefined;\n #textDensity: GridDensity | undefined;\n #built: Built;\n #table: ChartTable | null = null;\n #builtFrom: readonly unknown[] = [];\n\n // The drawing's version (ADR-0272): a press taken against another is refused when it is released.\n #version = 0;\n\n // The pointer: where it rests over a hit layer, the position or mark it is over, and what is read there.\n #over: Pointer | null = null;\n #pointerIndex: number | null = null;\n #pointerPanel = 0;\n #readingY = 0;\n #reading: ChartReading | null = null;\n #dots: readonly GuideDot[] = [];\n #press: Press | null = null;\n #pressAt: ScatterPress | null = null;\n #dragAt: { readonly x: number; readonly y: number } | null = null;\n #lastCell = '';\n\n #filtersOpen = false;\n #tableOpen = false;\n #fromText: string | null = null;\n #toText: string | null = null;\n #filterError: string | null = null;\n #menu: { readonly x: number; readonly y: number } | null = null;\n #menuShape: string | null = null;\n\n // The elements the chart keeps between paints.\n readonly #toolbar: HTMLDivElement;\n readonly #stage: HTMLDivElement;\n readonly #svg: SVGSVGElement;\n readonly #title: SVGTitleElement;\n #filters: HTMLDivElement | null = null;\n readonly #notice: HTMLDivElement;\n // The root's own properties the chart sets, so destroy() takes back only those.\n static readonly #rootProperties = ['width', 'font-size', '--ex-chart-line-height'] as const;\n // The SVG parts of the scene last drawn, kept while the scene and the angle are the same.\n #drawn: { readonly built: Built; readonly angle: number; readonly parts: readonly DrawingPart[] } | null = null;\n #menuParts: readonly HTMLElement[] = [];\n // The Chrome's parts, while a slot is given for them (ADR-0390).\n #toolbarSlot: ChartSlot<ChartToolbarSlotContext> | null = null;\n #menuSlot: ChartSlot<ChartMenuSlotContext> | null = null;\n #notes: HTMLUListElement | null = null;\n #tableBlock: HTMLElement | null = null;\n #tableShown: ChartTable | 'notice' | null = null;\n #parts: readonly (DrawingPart & { readonly nodes: readonly ChildNode[] })[] = [];\n #hits: readonly HTMLDivElement[] = [];\n #hitPlots = '';\n #tooltip: Element | null = null;\n #tooltipMarkup = '';\n #notesShown: readonly string[] = [];\n readonly #unlisten: readonly (() => void)[];\n\n constructor(root: HTMLElement, options: ChartOptions) {\n this.#root = root;\n this.#summaryId = uniqueId();\n this.#options = ChartElement.#checked(options);\n\n root.replaceChildren();\n root.classList.add('ex-chart');\n const notice = document.createElement('div');\n notice.setAttribute('data-ex-notice', 'stylesheet');\n notice.setAttribute('data-ex-stylesheet', stylesheetName);\n notice.setAttribute('data-ex-stamp', stylesheetStamp);\n notice.style.display = 'none';\n root.append(notice);\n this.#notice = notice;\n this.#toolbar = document.createElement('div');\n this.#toolbar.className = 'ex-chart-toolbar';\n this.#toolbar.setAttribute('role', 'toolbar');\n root.append(this.#toolbar);\n this.#stage = document.createElement('div');\n this.#stage.className = 'ex-chart-stage';\n this.#svg = document.createElementNS(svgNs, 'svg');\n this.#svg.setAttribute('class', 'ex-chart-svg');\n this.#svg.setAttribute('role', 'img');\n this.#svg.setAttribute('aria-labelledby', this.#summaryId);\n this.#title = document.createElementNS(svgNs, 'title');\n this.#title.id = this.#summaryId;\n this.#svg.append(this.#title);\n this.#stage.append(this.#svg);\n root.append(this.#stage);\n\n const unlisten: (() => void)[] = [];\n const listen = <K extends keyof HTMLElementEventMap>(type: K, handle: (event: HTMLElementEventMap[K]) => void): void => {\n root.addEventListener(type, handle);\n unlisten.push(() => { root.removeEventListener(type, handle); });\n };\n listen('pointermove', e => { this.#onMove(e); });\n listen('pointerdown', e => { this.#onDown(e); });\n listen('pointerup', e => { this.#onUp(e); });\n listen('pointercancel', () => { this.#onCancel(); });\n listen('pointerleave', () => { this.#onLeave(); });\n listen('click', e => { this.#onClick(e); });\n listen('dblclick', e => { this.#onDoubleClick(e); });\n listen('keydown', e => { this.#onKey(e); });\n listen('contextmenu', e => { this.#onContextMenu(e); });\n listen('input', e => { this.#onInput(e); });\n listen('change', e => { this.#onChange(e); });\n this.#unlisten = unlisten;\n this.#take(this.#options);\n this.#builtFrom = this.#inputs();\n this.#built = this.#layout();\n this.#version = 1;\n // A chart its Chrome cannot draw is not made: what it attached is taken back, and the error thrown on.\n try {\n this.#paint();\n } catch (error) {\n this.destroy();\n throw error;\n }\n }\n\n /** Takes the options again, whole: what did not change costs nothing. */\n update(options: ChartOptions): void {\n this.#alive();\n this.#options = ChartElement.#checked(options);\n this.#take(this.#options);\n this.#rebuild();\n this.#paint();\n }\n\n /**\n * Returns the range the user narrowed to the whole without raising `onRangeChanged`: a Framework Adapter's\n * refusal of a narrowing its host learned was taken against data replaced before it ended (ADR-0272, spine rule 6).\n */\n dropRange(): void {\n this.#alive();\n if (this.#range !== null) {\n this.#showRange(null);\n }\n }\n\n /** Stops the chart: it hears nothing more and empties its element. */\n destroy(): void {\n if (this.#destroyed) {\n return;\n }\n this.#destroyed = true;\n for (const stop of this.#unlisten) {\n stop();\n }\n // The Chrome's contents go before the elements they stand in.\n this.#toolbarSlot?.hide();\n this.#menuSlot?.hide();\n this.#root.replaceChildren();\n this.#root.classList.remove('ex-chart');\n for (const property of ChartElement.#rootProperties) {\n this.#root.style.removeProperty(property);\n }\n }\n\n /**\n * Saves the chart as a file, as the user sees it: CSV of the visible series in the range shown, the SVG of\n * the drawing, or that SVG painted to PNG at the screen's Device Pixel (ADR-0282). One call is one save.\n * False for a CSV of a chart its Chart Source thinned, which would hold only the points drawn (ADR-0344),\n * and once the chart is destroyed.\n */\n async download(format: ChartFileFormat): Promise<boolean> {\n // Taken now: the file is the drawing on screen at the click, whatever is drawn meanwhile.\n const { definition } = this.#options;\n const scene = this.#scene;\n const metrics = this.#metrics;\n const view = this.#view;\n if (this.#destroyed || (format === 'csv' && this.#thinnedAtSource)) {\n return false;\n }\n const name = fileName(this.#options.fileName, this.#options.title, format);\n if (format === 'csv') {\n save(name, mediaType(format), chartCsvWide(definition, metrics, view));\n return true;\n }\n const svg = svgFile({\n scene, width: this.#width, height: this.#height, fontSize: this.#fontSize, lineHeight: this.#lineHeight,\n angle: this.#angle, summary: this.#summary, theme: screenTheme(this.#root),\n });\n if (format === 'svg') {\n save(name, mediaType(format), svg);\n return true;\n }\n save(name, mediaType(format), await paintPng(svg, this.#width, this.#height));\n return true;\n }\n\n // ---- Options ----\n\n static #checked(options: ChartOptions): ChartOptions {\n // An untyped caller's options are checked here, at the boundary (CONVENTIONS.md).\n const { definition, width, height, onSeriesVisibilityChanged, onRangeChanged, onScaleChanged, onPointClick, label, chrome }: {\n readonly definition?: unknown; readonly width?: unknown; readonly height?: unknown; readonly onSeriesVisibilityChanged?: unknown;\n readonly onRangeChanged?: unknown; readonly onScaleChanged?: unknown; readonly onPointClick?: unknown; readonly label?: unknown;\n readonly chrome?: unknown;\n } = options;\n checkedChartChrome(chrome);\n if (!(definition instanceof ChartDefinition)) {\n throw new TypeError('An ExChart is given its definition, a ChartDefinition.');\n }\n for (const [name, value] of [['width', width], ['height', height]] as const) {\n if (value !== undefined && !(typeof value === 'number' && Number.isFinite(value) && value > 0)) {\n throw new RangeError(`An ExChart's ${name} is a finite, positive number of CSS pixels. (${name}: ${typeof value === 'number' ? String(value) : `a ${typeof value}`})`);\n }\n }\n for (const [name, value] of [['onSeriesVisibilityChanged', onSeriesVisibilityChanged], ['onRangeChanged', onRangeChanged],\n ['onScaleChanged', onScaleChanged], ['onPointClick', onPointClick], ['label', label]] as const) {\n if (value !== undefined && typeof value !== 'function') {\n throw new TypeError(`An ExChart's ${name} is a function.`);\n }\n }\n return options;\n }\n\n // Taken back as plain options (ADR-0272): an option that changed replaces what the user last did; one\n // that did not leaves it. Compared by what they hold, so a set or a range made again on every render is\n // the same option.\n #take(options: ChartOptions): void {\n const hidden = setOf(options.hiddenSeries);\n const range = options.range === undefined ? null : options.range;\n const taken = this.#taken;\n if (taken === undefined || !sameSet(taken.hidden, hidden)) {\n this.#hidden = hidden;\n }\n if (taken === undefined || !sameRange(taken.range, range)) {\n this.#range = range;\n }\n if (taken === undefined || taken.scale !== options.scale) {\n this.#scale = options.scale;\n }\n this.#taken = { hidden, range, scale: options.scale };\n }\n\n get #width(): number {\n const { width = 800 } = this.#options;\n return width;\n }\n\n get #height(): number {\n const { height = 400 } = this.#options;\n return height;\n }\n\n get #angle(): number {\n const style = this.#options.axisStyle;\n return style?.angle === undefined ? 0 : style.angle;\n }\n\n #word(id: string, ...args: readonly string[]): string {\n return chartWord(id, this.#options.label, ...args);\n }\n\n #alive(): void {\n if (this.#destroyed) {\n throw new Error('This chart was destroyed; create another.');\n }\n }\n\n // ---- The scene ----\n\n get #metrics(): ChartMetrics {\n return this.#built.metrics;\n }\n\n get #lineHeight(): number {\n return this.#built.lineHeight;\n }\n\n get #fontSize(): number {\n return this.#built.fontSize;\n }\n\n get #view(): ChartView {\n return this.#built.view;\n }\n\n get #scene(): ChartScene {\n return this.#built.scene;\n }\n\n get #summary(): string {\n return this.#built.summary;\n }\n\n get #density(): GridDensity {\n const { density = 'standard' } = this.#options;\n return density;\n }\n\n #inputs(): readonly unknown[] {\n const o = this.#options;\n return [o.definition, this.#width, this.#height, this.#density, o.legend, o.axisStyle, o.independentScales, o.colourSlots,\n this.#hidden, this.#range, this.#scale, o.yScale, o.title, o.description];\n }\n\n #rebuild(): void {\n const builtFrom = this.#inputs();\n if (builtFrom.every((v, i) => alike(v, this.#builtFrom[i]))) {\n return;\n }\n const definitionChanged = this.#builtFrom[0] !== this.#options.definition;\n this.#builtFrom = builtFrom;\n const previous = this.#scene;\n this.#built = this.#layout();\n this.#table = this.#tableOpen && !this.#thinnedAtSource ? chartTable(this.#options.definition, this.#metrics, this.#view) : null;\n\n const scene = this.#scene;\n if (definitionChanged || !alike(previous.positions, scene.positions) || !alike(previous.marks, scene.marks)\n || !alike(previous.edgeMarks, scene.edgeMarks) || !alike(previous.panels.map(p => p.plot), scene.panels.map(p => p.plot))) {\n this.#version += 1;\n this.#clearPointer();\n // A pointer at rest is read against the drawing now shown, as the Razor component's script re-reported it.\n if (this.#over !== null && this.#press === null && this.#pressAt === null) {\n this.#report(this.#over);\n }\n } else if (this.#pointerIndex !== null) {\n this.#read(this.#pointerIndex, this.#pointerPanel, this.#readingY);\n }\n }\n\n #layout(): Built {\n const o = this.#options;\n const density = this.#density;\n if (this.#text === undefined || this.#textDensity !== density) {\n this.#text = densityText(density);\n this.#textDensity = density;\n }\n const text = this.#text;\n const font = text.fontSizePx;\n const lineHeight = Math.ceil(font * 1.4);\n // Two device pixels a CSS pixel: Thinning keeps every peak at up to twice the resolution the chart is\n // told nothing about, and no more (ADR-0254).\n const metrics: ChartMetrics = {\n width: this.#width, height: this.#height, devicePixelRatio: 2, lineHeight, padding: roundHalfToEven(font * 0.6),\n panelGap: roundHalfToEven(font * 1.2), textWidth: s => text.textWidthPx(s), ...(o.colourSlots === undefined ? {} : { colourSlots: o.colourSlots }),\n };\n const range = this.#range;\n const view: ChartView = {\n hidden: this.#hidden,\n ...(range?.from === undefined ? {} : { from: range.from }),\n ...(range?.to === undefined ? {} : { to: range.to }),\n ...(this.#scale === undefined ? {} : { scale: this.#scale }),\n ...(range?.yFrom === undefined ? {} : { yFrom: range.yFrom }),\n ...(range?.yTo === undefined ? {} : { yTo: range.yTo }),\n ...(o.yScale === undefined ? {} : { yScale: o.yScale }),\n };\n const scene = buildScene(o.definition, metrics, {\n view,\n ...(o.axisStyle === undefined ? {} : { style: o.axisStyle }),\n ...(o.independentScales === undefined ? {} : { independentScales: o.independentScales }),\n ...(o.legend === undefined ? {} : { legend: o.legend }),\n });\n const summary = chartSummary(o.definition, scene, o.title, o.description);\n return { metrics, lineHeight, fontSize: font, view, scene, summary };\n }\n\n get #thinnedAtSource(): boolean {\n // A chart whose Chart Source thinned it holds only the points drawn (ADR-0344): a CSV or a table of\n // them would look like the data and not be it (spine rule 1), so neither is offered.\n return this.#options.definition.series.some(s => s.thinned.length > 0);\n }\n\n // ---- The pointer (ADR-0255, ADR-0270) ----\n\n #clearPointer(): void {\n this.#pointerIndex = null;\n this.#reading = null;\n this.#dots = [];\n }\n\n #read(index: number, panel: number, y: number): void {\n const scene = this.#scene;\n if (scene.scatter) {\n this.#readMark(index);\n return;\n }\n if (index < 0 || index >= scene.positions.length || panel < 0 || panel >= scene.panels.length) {\n this.#clearPointer();\n return;\n }\n this.#pointerIndex = index;\n this.#pointerPanel = panel;\n this.#readingY = y;\n const reading = readingAt(this.#options.definition, scene, this.#metrics, elementAt(scene.positions, index)[0], panel, y);\n this.#reading = reading;\n this.#dots = reading.lines.flatMap(l => (l.y === null ? [] : [{ y: l.y, look: l.look }]));\n }\n\n // On a scatter the pointer is over the nearest mark, if any (ADR-0290), or else the nearest edge,\n // counted after the marks (ADR-0321).\n #readMark(index: number): void {\n const scene = this.#scene;\n if (index < 0 || index >= scene.marks.length + scene.edgeMarks.length) {\n this.#clearPointer();\n return;\n }\n const at = this.#markAt(index);\n this.#pointerIndex = index;\n this.#pointerPanel = at.panel;\n this.#readingY = at.y;\n const reading = index < scene.marks.length\n ? readingOfMark(this.#options.definition, scene, index)\n : readingOfEdge(this.#options.definition, scene, index - scene.marks.length);\n this.#reading = reading;\n this.#dots = reading.lines.map(l => ({ y: at.y, look: l.look }));\n }\n\n // Where the pointer's mark stands: a marker's centre, or an edge's middle.\n #markAt(index: number): Pointer {\n const scene = this.#scene;\n if (index < scene.marks.length) {\n const m = elementAt(scene.marks, index);\n return { x: m.x, y: m.y, panel: m.panel };\n }\n const e = elementAt(scene.edgeMarks, index - scene.marks.length);\n return { x: (e.edge.x1 + e.edge.x2) / 2, y: (e.edge.y1 + e.edge.y2) / 2, panel: e.panel };\n }\n\n // The position nearest an offset: positions are sorted left to right, so the boundary between two is\n // halfway between them. Offsets are a hundredth of a pixel, as the Razor component handed them over.\n #nearest(x: number): number {\n const xs = this.#scene.positions;\n let lo = 0;\n let hi = xs.length - 1;\n if (hi < 0) {\n return -1;\n }\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n const between = (roundToDigits(elementAt(xs, mid)[1], 2) + roundToDigits(elementAt(xs, mid + 1)[1], 2)) / 2;\n if (x < between) {\n hi = mid;\n } else {\n lo = mid + 1;\n }\n }\n return lo;\n }\n\n // The mark nearest the point, in its panel and within reach; where none is, the nearest edge in reach,\n // counted after the marks (ADR-0321); or -1.\n #nearestMark(point: Pointer): number {\n const scene = this.#scene;\n const reach = roundToDigits(this.#lineHeight * 0.6, 2);\n let best = -1;\n let bestDistance = reach * reach;\n scene.marks.forEach((m, i) => {\n if (m.panel !== point.panel) {\n return;\n }\n const dx = roundToDigits(m.x, 2) - point.x;\n const dy = roundToDigits(m.y, 2) - point.y;\n const distance = dx * dx + dy * dy;\n if (distance <= bestDistance) {\n best = i;\n bestDistance = distance;\n }\n });\n if (best >= 0) {\n return best;\n }\n scene.edgeMarks.forEach((m, i) => {\n if (m.panel !== point.panel) {\n return;\n }\n const x1 = roundToDigits(m.edge.x1, 2);\n const y1 = roundToDigits(m.edge.y1, 2);\n const x2 = roundToDigits(m.edge.x2, 2);\n const y2 = roundToDigits(m.edge.y2, 2);\n const length = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\n const t = length === 0 ? 0 : Math.max(0, Math.min(1, ((point.x - x1) * (x2 - x1) + (point.y - y1) * (y2 - y1)) / length));\n const dx = x1 + t * (x2 - x1) - point.x;\n const dy = y1 + t * (y2 - y1) - point.y;\n const distance = dx * dx + dy * dy;\n if (distance <= bestDistance) {\n best = scene.marks.length + i;\n bestDistance = distance;\n }\n });\n return best;\n }\n\n #indexAt(point: Pointer): number {\n return this.#scene.scatter ? this.#nearestMark(point) : this.#nearest(point.x);\n }\n\n // Where on the drawing an event is: the hit layer's own offsets, which the chart wrote on it, plus the\n // event's offsets within it. During a drag the pointer is captured, so the target stays the layer the\n // press was on even when the pointer has left it.\n #locate(event: MouseEvent): Pointer | null {\n const layer = event.target instanceof Element ? event.target.closest('.ex-chart-hit') : null;\n if (layer === null || !this.#root.contains(layer)) {\n return null;\n }\n const left = Number(layer.getAttribute('data-ex-x'));\n const top = Number(layer.getAttribute('data-ex-y'));\n const panel = Number(layer.getAttribute('data-ex-panel'));\n if (!Number.isFinite(left) || !Number.isFinite(top) || !Number.isInteger(panel)) {\n throw new Error('Internal: a hit layer carries no offsets of its own.');\n }\n return { x: left + event.offsetX, y: top + event.offsetY, panel };\n }\n\n readonly #snap = (value: number): number => (Math.floor(value / dragCell) + 0.5) * dragCell;\n\n // A move onto another position or mark reads it; a move within one reads nothing again.\n #report(point: Pointer): void {\n if (this.#pressAt !== null) {\n const cell = `${String(Math.floor(point.x / dragCell))},${String(Math.floor(point.y / dragCell))}`;\n if (cell !== this.#lastCell) {\n this.#lastCell = cell;\n if (this.#pressAt.version === this.#version) {\n this.#dragAt = { x: this.#snap(point.x), y: this.#snap(point.y) };\n }\n }\n }\n const index = this.#indexAt(point);\n if (index === this.#pointerIndex && point.panel === this.#pointerPanel) {\n return;\n }\n if (index < 0) {\n this.#clearPointer();\n } else {\n this.#read(index, point.panel, point.y);\n }\n }\n\n #onMove(event: PointerEvent): void {\n const point = this.#locate(event);\n const pressed = this.#press !== null || this.#pressAt !== null;\n if (point === null) {\n if (!pressed) {\n this.#leave();\n }\n return;\n }\n if (!pressed) {\n this.#over = point;\n }\n this.#report(point);\n this.#paintPointer();\n }\n\n #leave(): void {\n this.#over = null;\n if (this.#pointerIndex === null) {\n return;\n }\n this.#clearPointer();\n this.#paintPointer();\n }\n\n #onLeave(): void {\n if (this.#press === null && this.#pressAt === null) {\n this.#leave();\n }\n }\n\n #onDown(event: PointerEvent): void {\n if (event.button !== 0) {\n return;\n }\n const at = this.#locate(event);\n if (at === null) {\n return;\n }\n if (event.target instanceof Element) {\n event.target.setPointerCapture(event.pointerId);\n }\n this.#lastCell = `${String(Math.floor(at.x / dragCell))},${String(Math.floor(at.y / dragCell))}`;\n const index = this.#indexAt(at);\n const scene = this.#scene;\n if (scene.scatter) {\n if (at.panel < 0 || at.panel >= scene.panels.length) {\n return;\n }\n this.#pressAt = { version: this.#version, index, x: this.#snap(at.x), y: this.#snap(at.y), panel: at.panel };\n this.#dragAt = null;\n return;\n }\n if (index < 0 || index >= scene.positions.length) {\n return;\n }\n this.#press = { version: this.#version, index };\n }\n\n #onUp(event: PointerEvent): void {\n if (this.#press === null && this.#pressAt === null) {\n return;\n }\n const point = this.#locate(event);\n this.#over = point;\n const index = point === null ? -1 : this.#indexAt(point);\n if (this.#scene.scatter || this.#pressAt !== null) {\n // A line chart's press that a scatter replaced while it was held ends here too.\n this.#press = null;\n this.#releaseScatter(index, point === null ? -1 : this.#snap(point.x), point === null ? -1 : this.#snap(point.y));\n } else {\n this.#pressAt = null;\n this.#release(index);\n }\n }\n\n // The browser took the gesture (a system gesture, a scroll): the press is dropped, never released, so\n // nothing is narrowed or clicked by a pointer that did not let go here.\n #onCancel(): void {\n if (this.#press === null && this.#pressAt === null) {\n return;\n }\n this.#press = null;\n this.#pressAt = null;\n this.#dragAt = null;\n this.#paintPointer();\n }\n\n // A drag ends (ADR-0273): narrowed to the positions it began and ended on, unless the drawing it began\n // against is no longer the one shown (ADR-0272).\n #release(index: number): void {\n const press = this.#press;\n this.#press = null;\n const scene = this.#scene;\n if (press === null) {\n return;\n }\n if (press.version !== this.#version || index < 0 || index >= scene.positions.length) {\n this.#paintPointer();\n return;\n }\n if (index === press.index) {\n this.#paintPointer();\n // A click, read from the reading the pointer's position holds: one taken at another position, or\n // none, names no point, and nothing is raised (spine rule 6).\n const reading = this.#pointerIndex === index ? this.#reading : null;\n let line: { readonly id: string; readonly distance: number } | undefined;\n for (const l of reading === null ? [] : reading.lines) {\n if (l.y === null || l.value === null) {\n continue;\n }\n const distance = Math.abs(l.y - this.#readingY);\n if (line === undefined || distance < line.distance) {\n line = { id: l.id, distance };\n }\n }\n if (line === undefined) {\n return;\n }\n const position = elementAt(scene.positions, index)[0];\n // A merged candle stands for no one row: a click narrows to its period (ADR-0300, ADR-0302).\n const lineId = line.id;\n const merged = scene.panels.flatMap(p => p.series).find(piece => piece.id === lineId && piece.period !== 'row');\n const candle = merged?.candles.find(c => c.from <= position && position <= c.to);\n if (candle !== undefined && candle.rows > 0) {\n this.#setRange({ from: candle.from, to: candle.to });\n } else {\n this.#options.onPointClick?.({ seriesId: lineId, position });\n }\n return;\n }\n const a = elementAt(scene.positions, Math.min(press.index, index))[0];\n const b = elementAt(scene.positions, Math.max(press.index, index))[0];\n this.#setRange({ from: a, to: b });\n }\n\n // A scatter's release (ADR-0290): on the mark it was pressed on, a click on that point; elsewhere, the\n // rectangle from the press narrows both axes. Against another drawing, nothing (spine rule 6).\n #releaseScatter(index: number, x: number, y: number): void {\n const press = this.#pressAt;\n this.#pressAt = null;\n this.#dragAt = null;\n if (press === null) {\n return;\n }\n const scene = this.#scene;\n if (press.version !== this.#version || x < 0 || y < 0) {\n this.#paintPointer();\n return;\n }\n // Within one cell of the lattice it was pressed on, a click; a slip of a pixel across a cell's edge is\n // still a click.\n if (Math.abs(x - press.x) <= dragCell && Math.abs(y - press.y) <= dragCell) {\n this.#paintPointer();\n if (index >= 0 && index === press.index && index < scene.marks.length) {\n const m = elementAt(scene.marks, index);\n const series = defined(this.#options.definition.series.find(s => s.id === m.seriesId), `the series ${m.seriesId}`);\n const point = elementAt(series.points, m.point);\n this.#options.onPointClick?.({ seriesId: m.seriesId, position: point.x, ...(point.row === undefined ? {} : { row: point.row }) });\n }\n return;\n }\n const panel = elementAt(scene.panels, press.panel);\n const x0 = positionAt(scene, Math.min(press.x, x));\n const x1 = positionAt(scene, Math.max(press.x, x));\n // The left axis is narrowed only where it is the chart's one vertical axis a rectangle can mean: one\n // panel. Elsewhere the rectangle narrows the axis across alone.\n if (panel.left === null || scene.panels.length > 1) {\n this.#setRange({ from: x0, to: x1 });\n return;\n }\n // Down the page is down the axis: the lower edge is the larger pixel.\n this.#setRange({\n from: x0, to: x1, yFrom: valueAt(panel.left, Math.max(press.y, y), panel.plot), yTo: valueAt(panel.left, Math.min(press.y, y), panel.plot),\n });\n }\n\n // ---- What the user changes ----\n\n #setRange(range: ChartRange | null): void {\n this.#showRange(range);\n this.#options.onRangeChanged?.(range);\n }\n\n #showRange(range: ChartRange | null): void {\n this.#range = range;\n this.#filterError = null;\n // Chart Filters shows the range as it now stands, however it was set (ADR-0273).\n this.#writeFilterTexts();\n this.#rebuild();\n this.#paint();\n }\n\n #writeFilterTexts(): void {\n const axis = this.#options.definition.axis;\n this.#fromText = this.#range?.from === undefined ? null : writeEnd(axis, this.#range.from);\n this.#toText = this.#range?.to === undefined ? null : writeEnd(axis, this.#range.to);\n if (this.#filters !== null) {\n found(this.#filters.querySelector<HTMLInputElement>('.ex-chart-from'), 'the From field').value = fieldText(this.#fromText);\n found(this.#filters.querySelector<HTMLInputElement>('.ex-chart-to'), 'the To field').value = fieldText(this.#toText);\n }\n }\n\n #resetRange(): void {\n if (this.#range !== null) {\n this.#setRange(null);\n }\n }\n\n #toggle(key: string): void {\n const hidden = new Set(this.#hidden);\n const nowHidden = !hidden.delete(key);\n if (nowHidden) {\n hidden.add(key);\n } else {\n // Shown again, an entry shows every series it stands for, even one hidden by its own key (ADR-0257).\n for (const member of legendMembers(this.#options.definition, key)) {\n hidden.delete(member);\n }\n }\n this.#hidden = hidden;\n this.#rebuild();\n this.#paint();\n this.#options.onSeriesVisibilityChanged?.({ key, hidden: nowHidden });\n }\n\n #toggleFilters(): void {\n this.#filtersOpen = !this.#filtersOpen;\n if (this.#filtersOpen) {\n this.#writeFilterTexts();\n this.#filterError = null;\n }\n this.#paint();\n }\n\n #toggleTable(): void {\n this.#tableOpen = !this.#tableOpen;\n this.#table = this.#tableOpen && !this.#thinnedAtSource ? chartTable(this.#options.definition, this.#metrics, this.#view) : null;\n this.#paint();\n }\n\n // The range typed under Chart Filters (ADR-0273), in the axis' own values. A value that does not read as\n // one is said, never guessed (spine rule 1).\n #applyTypedRange(): void {\n const axis = this.#options.definition.axis;\n const from = readEnd(axis, this.#fromText);\n const to = readEnd(axis, this.#toText);\n if (!from.read || !to.read) {\n const bad = !from.read ? this.#fromText : this.#toText;\n const kind = axis.values === 'dates' ? chartWordIds.aDate : axis.values === 'labels' ? chartWordIds.aCategory : chartWordIds.aNumber;\n this.#filterError = this.#word(chartWordIds.notOnAxis, found(bad, 'the text not read'), this.#word(kind));\n this.#paint();\n return;\n }\n if (from.position !== null && to.position !== null && from.position > to.position) {\n this.#filterError = this.#word(chartWordIds.fromAfterTo);\n this.#paint();\n return;\n }\n this.#setRange(from.position === null && to.position === null ? null : {\n ...(from.position === null ? {} : { from: from.position }),\n ...(to.position === null ? {} : { to: to.position }),\n });\n }\n\n #setScale(scale: AxisScale): void {\n if (scale !== 'proportional' && scale !== 'categories') {\n throw new RangeError(`The axis switch switches to 'proportional' or 'categories', not '${scale}' (ADR-0251).`);\n }\n if (!this.#scaleSwitchable) {\n throw new Error('This chart\\'s axis cannot be switched: it holds categories, or a series is sampled (ADR-0251).');\n }\n if (scale === (this.#scale ?? this.#options.definition.axis.effectiveScale)) {\n return;\n }\n this.#scale = scale;\n this.#rebuild();\n this.#paint();\n this.#options.onScaleChanged?.(scale);\n }\n\n get #scaleSwitchable(): boolean {\n const d = this.#options.definition;\n return d.axis.values !== 'labels' && d.series.every(s => s.sampler === undefined);\n }\n\n // ---- The DOM's events ----\n\n #onClick(event: MouseEvent): void {\n const target = event.target instanceof Element ? event.target : null;\n if (target === null) {\n return;\n }\n const entry = target.closest('.ex-chart-legend-entry');\n if (entry !== null) {\n this.#toggle(found(entry.getAttribute('data-series'), 'a legend entry\\'s key'));\n return;\n }\n if (target.closest('.ex-chart-menu-backdrop') !== null) {\n this.#closeMenu();\n return;\n }\n // A Chrome's contents run what they draw through their context, never through the built-in controls' classes.\n if (inSlot(target)) {\n return;\n }\n const button = target.closest('button');\n if (button === null || button.disabled || !this.#root.contains(button)) {\n return;\n }\n const command = button.getAttribute('data-ex-command');\n if (command !== null && button.closest('.ex-chart-menu') !== null) {\n const chosen = this.#menuCommands().find(c => c.id === command);\n if (chosen !== undefined && chosen.enabled) {\n this.#closeMenu();\n chosen.run();\n }\n return;\n }\n const toolbar = this.#toolbarCommands().find(c => button.classList.contains(toolbarClass(c.id)));\n if (toolbar !== undefined) {\n toolbar.run();\n return;\n }\n if (button.classList.contains('ex-chart-apply')) {\n this.#applyTypedRange();\n }\n }\n\n #onDoubleClick(event: MouseEvent): void {\n if (event.target instanceof Element && event.target.closest('.ex-chart-hit') !== null) {\n this.#resetRange();\n }\n }\n\n #onKey(event: KeyboardEvent): void {\n const target = event.target instanceof Element ? event.target : null;\n if (target === null) {\n return;\n }\n const entry = target.closest('.ex-chart-legend-entry');\n if (entry !== null && (event.key === 'Enter' || event.key === ' ')) {\n event.preventDefault();\n this.#toggle(found(entry.getAttribute('data-series'), 'a legend entry\\'s key'));\n return;\n }\n if (target.closest('.ex-chart-menu') !== null && event.key === 'Escape') {\n this.#closeMenu();\n }\n }\n\n // Asked for by the right button or by the keyboard (Shift+F10, the menu key), both of which the browser\n // raises as contextmenu on the chart. Its own menu replaces the browser's (ADR-0281).\n #onContextMenu(event: MouseEvent): void {\n const target = event.target instanceof Element ? event.target : null;\n if (target === null) {\n return;\n }\n if (target.closest('.ex-chart-menu-backdrop') !== null) {\n event.preventDefault();\n this.#closeMenu();\n return;\n }\n if (target.closest('.ex-chart-stage') !== null) {\n event.preventDefault();\n this.#menu = { x: event.clientX, y: event.clientY };\n this.#paint();\n const frame = this.#menuParts[1];\n if (frame !== undefined) {\n frame.focus();\n }\n }\n }\n\n #closeMenu(): void {\n this.#menu = null;\n this.#paint();\n }\n\n #onInput(event: Event): void {\n const target = event.target;\n if (!(target instanceof HTMLInputElement) || inSlot(target)) {\n return;\n }\n if (target.classList.contains('ex-chart-from')) {\n this.#fromText = target.value;\n } else if (target.classList.contains('ex-chart-to')) {\n this.#toText = target.value;\n }\n }\n\n #onChange(event: Event): void {\n const target = event.target;\n if (target instanceof HTMLSelectElement && target.classList.contains('ex-chart-scale') && !inSlot(target)) {\n const value = target.value;\n if (value !== 'Proportional' && value !== 'Categories') {\n throw new Error(`Internal: the axis switch offered '${value}', which is no scale it switches to.`);\n }\n this.#setScale(value === 'Proportional' ? 'proportional' : 'categories');\n }\n }\n\n // ---- Commands (ADR-0281) ----\n\n #toolbarCommands(): readonly Command[] {\n return [\n { id: chartWordIds.filters, label: this.#word(chartWordIds.filters), enabled: true, expanded: this.#filtersOpen, run: () => { this.#toggleFilters(); } },\n { id: chartWordIds.resetRange, label: this.#word(chartWordIds.resetRange), enabled: this.#range !== null, run: () => { this.#resetRange(); } },\n { id: chartWordIds.table, label: this.#word(chartWordIds.table), enabled: true, expanded: this.#tableOpen, run: () => { this.#toggleTable(); } },\n {\n id: chartWordIds.downloadCsv, label: this.#word(chartWordIds.downloadCsv), enabled: !this.#thinnedAtSource,\n ...(this.#thinnedAtSource ? { title: this.#word(chartWordIds.thinnedAtSource) } : {}), run: () => { void this.download('csv'); },\n },\n { id: chartWordIds.downloadSvg, label: this.#word(chartWordIds.downloadSvg), enabled: true, run: () => { void this.download('svg'); } },\n { id: chartWordIds.downloadPng, label: this.#word(chartWordIds.downloadPng), enabled: true, run: () => { void this.download('png'); } },\n ];\n }\n\n #menuCommands(): readonly Command[] {\n return [\n { id: chartWordIds.resetRange, label: this.#word(chartWordIds.resetRange), enabled: this.#range !== null, run: () => { this.#resetRange(); } },\n { id: chartWordIds.table, label: this.#word(this.#tableOpen ? chartWordIds.hideTable : chartWordIds.table), enabled: true, run: () => { this.#toggleTable(); } },\n { id: chartWordIds.downloadCsv, label: this.#word(chartWordIds.menuDownloadCsv), enabled: !this.#thinnedAtSource, run: () => { void this.download('csv'); } },\n { id: chartWordIds.downloadSvg, label: this.#word(chartWordIds.menuDownloadSvg), enabled: true, run: () => { void this.download('svg'); } },\n { id: chartWordIds.downloadPng, label: this.#word(chartWordIds.menuDownloadPng), enabled: true, run: () => { void this.download('png'); } },\n ];\n }\n\n // ---- Painting ----\n\n get #name(): string {\n const title = this.#options.title;\n return title === undefined || title.trim() === '' ? this.#word(chartWordIds.chart) : title;\n }\n\n #paint(): void {\n const root = this.#root;\n // Only the chart's own properties, so a style the Consumer gave the element stays.\n root.style.setProperty('width', `${n(this.#width)}px`);\n root.style.setProperty('font-size', `${n(this.#fontSize)}px`);\n root.style.setProperty('--ex-chart-line-height', `${n(this.#lineHeight)}px`);\n setText(this.#notice, this.#word(chartWordIds.stylesheetNotice));\n const toolbarMount = this.#options.chrome?.toolbar;\n if (toolbarMount === undefined) {\n this.#paintToolbar();\n this.#paintFilters();\n } else {\n this.#placeToolbarSlot();\n }\n this.#paintStage();\n this.#paintMenu();\n this.#paintNotes();\n this.#paintTable();\n // A Chrome's contents are mounted last: what the chart draws itself stands whatever they do.\n if (toolbarMount !== undefined) {\n this.#showToolbarSlot(toolbarMount);\n }\n this.#showMenuSlot();\n }\n\n #paintToolbar(): void {\n const toolbar = this.#toolbar;\n if (this.#toolbarSlot !== null) {\n this.#toolbarSlot.hide();\n this.#toolbarSlot.element.remove();\n this.#toolbarSlot = null;\n }\n if (toolbar.parentElement !== this.#root) {\n this.#stage.before(toolbar);\n }\n toolbar.setAttribute('aria-label', this.#name);\n if (toolbar.childElementCount === 0) {\n const downloads = document.createElement('span');\n downloads.className = 'ex-chart-downloads';\n downloads.setAttribute('role', 'group');\n for (const command of this.#toolbarCommands()) {\n const button = document.createElement('button');\n button.type = 'button';\n button.className = `ex-chart-button ${toolbarClass(command.id)}`;\n (command.id.startsWith('exchart.download.') ? downloads : toolbar).append(button);\n }\n toolbar.append(downloads);\n }\n toolbar.querySelector('.ex-chart-downloads')?.setAttribute('aria-label', this.#word(chartWordIds.downloads));\n for (const command of this.#toolbarCommands()) {\n const button = found(toolbar.querySelector<HTMLButtonElement>(`.${toolbarClass(command.id)}`), `the ${command.id} button`);\n setText(button, command.label);\n button.disabled = !command.enabled;\n if (command.id === chartWordIds.filters) {\n button.setAttribute('aria-expanded', this.#filtersOpen ? 'true' : 'false');\n } else if (command.id === chartWordIds.table) {\n button.setAttribute('aria-expanded', this.#tableOpen ? 'true' : 'false');\n }\n if (command.id === chartWordIds.downloadCsv && this.#thinnedAtSource) {\n button.title = this.#word(chartWordIds.thinnedAtSource);\n } else {\n button.removeAttribute('title');\n }\n }\n }\n\n // The toolbar a Chrome draws (ADR-0281, ADR-0390), in place of the built-in one.\n #placeToolbarSlot(): void {\n this.#toolbar.remove();\n this.#filters?.remove();\n this.#filters = null;\n let slot = this.#toolbarSlot;\n if (slot === null) {\n slot = new ChartSlot<ChartToolbarSlotContext>('toolbar', document.createElement('div'));\n slot.element.className = 'ex-chart-toolbar-slot';\n this.#toolbarSlot = slot;\n }\n if (slot.element.parentElement !== this.#root) {\n this.#stage.before(slot.element);\n }\n }\n\n // Its contents are mounted again only when what they are handed changed, so a pointer move draws nothing of them\n // (ADR-0252); the context is made only then.\n #showToolbarSlot(mount: NonNullable<ChartChrome['toolbar']>): void {\n const slot = this.#toolbarSlot;\n if (slot === null) {\n throw new Error('Internal: the toolbar slot is shown before it is placed.');\n }\n const commands = this.#toolbarCommands();\n const filters = this.#filtersView();\n const words = [chartWordIds.from, chartWordIds.to, chartWordIds.apply, chartWordIds.axis, chartWordIds.proportional, chartWordIds.categories,\n chartWordIds.downloads, chartWordIds.filters].map(id => this.#word(id));\n const key = JSON.stringify([this.#name, commandShape(commands), words, filters]);\n slot.show(mount, key, standing => Object.freeze({\n name: this.#name,\n commands: this.#slotCommands(commands, standing, false),\n ...(filters === undefined ? {} : { filters: this.#filtersContext(filters, standing) }),\n label: (id: string) => this.#word(id),\n }));\n }\n\n // What Chart Filters shows while it is open (ADR-0273): plain values, which tell whether its contents would be drawn\n // the same.\n #filtersView(): Omit<ChartFiltersSlotContext, 'apply' | 'setScale'> | undefined {\n if (!this.#filtersOpen) {\n return undefined;\n }\n const axis = this.#options.definition.axis;\n return {\n values: axis.values,\n labels: axis.values === 'labels' ? Object.freeze([...axis.labels]) : Object.freeze([]),\n from: this.#fromText,\n to: this.#toText,\n hint: this.#word(axis.values === 'dates' ? chartWordIds.dateHint : axis.values === 'labels' ? chartWordIds.categoryHint : chartWordIds.numberHint),\n error: this.#filterError,\n ...(this.#scaleSwitchable ? { scale: (this.#scale ?? axis.effectiveScale) === 'categories' ? 'categories' as const : 'proportional' as const } : {}),\n };\n }\n\n // Chart Filters as a Chrome is handed it: what it shows, and what it answers through while its contents stand.\n #filtersContext(view: Omit<ChartFiltersSlotContext, 'apply' | 'setScale'>, standing: () => boolean): ChartFiltersSlotContext {\n return Object.freeze({\n ...view,\n apply: (from: string | null, to: string | null) => {\n if ((from !== null && typeof from !== 'string') || (to !== null && typeof to !== 'string')) {\n throw new TypeError('Chart Filters applies the text typed for each end, or null for the axis\\' own end.');\n }\n if (!standing()) {\n return;\n }\n this.#fromText = from;\n this.#toText = to;\n this.#applyTypedRange();\n },\n setScale: (scale: AxisScale) => {\n if (standing()) {\n this.#setScale(scale);\n }\n },\n });\n }\n\n // The commands as a Chrome invokes them, as the built-in controls run them: one not enabled runs nothing, and none\n // runs once the contents it was handed to no longer stand (spine rule 6); from the menu, the menu closes first.\n #slotCommands(commands: readonly Command[], standing: () => boolean, closesMenu: boolean): readonly ChartCommand[] {\n return Object.freeze(commands.map(command => Object.freeze({\n id: command.id,\n label: command.label,\n enabled: command.enabled,\n ...(command.expanded === undefined ? {} : { expanded: command.expanded }),\n ...(command.title === undefined ? {} : { title: command.title }),\n invoke: () => {\n if (!standing() || !command.enabled) {\n return;\n }\n if (closesMenu) {\n this.#closeMenu();\n }\n command.run();\n },\n })));\n }\n\n #paintFilters(): void {\n if (!this.#filtersOpen) {\n this.#filters?.remove();\n this.#filters = null;\n return;\n }\n const axis = this.#options.definition.axis;\n const hint = this.#word(axis.values === 'dates' ? chartWordIds.dateHint : axis.values === 'labels' ? chartWordIds.categoryHint : chartWordIds.numberHint);\n let filters = this.#filters;\n if (filters === null) {\n filters = document.createElement('div');\n filters.className = 'ex-chart-filters';\n filters.setAttribute('role', 'group');\n const field = (cls: string, value: string | null): HTMLLabelElement => {\n const label = document.createElement('label');\n label.className = 'ex-chart-filter';\n const span = document.createElement('span');\n const input = document.createElement('input');\n input.className = cls;\n input.type = 'text';\n input.value = fieldText(value);\n label.append(span, input);\n return label;\n };\n const apply = document.createElement('button');\n apply.type = 'button';\n apply.className = 'ex-chart-button ex-chart-apply';\n filters.append(field('ex-chart-from', this.#fromText), field('ex-chart-to', this.#toText), apply);\n this.#toolbar.after(filters);\n this.#filters = filters;\n }\n filters.setAttribute('aria-label', this.#word(chartWordIds.filters));\n for (const input of filters.querySelectorAll('input')) {\n input.placeholder = hint;\n }\n // The words are written on every paint, so a label changed while the panel is open reaches them.\n for (const [cls, id] of [['ex-chart-from', chartWordIds.from], ['ex-chart-to', chartWordIds.to]] as const) {\n const input = found(filters.querySelector(`.${cls}`), `the ${cls} field`);\n setText(found(input.previousElementSibling, `the ${cls} field's label`), this.#word(id));\n }\n setText(found(filters.querySelector('.ex-chart-apply'), 'the Apply button'), this.#word(chartWordIds.apply));\n const existing = filters.querySelector('.ex-chart-scale');\n let scaleField = existing === null ? null : existing.closest('label');\n if (this.#scaleSwitchable && scaleField === null) {\n scaleField = document.createElement('label');\n scaleField.className = 'ex-chart-filter';\n const span = document.createElement('span');\n const select = document.createElement('select');\n select.className = 'ex-chart-scale';\n for (const value of ['Proportional', 'Categories']) {\n const option = document.createElement('option');\n option.value = value;\n select.append(option);\n }\n scaleField.append(span, select);\n found(filters.querySelector('.ex-chart-apply'), 'the Apply button').after(scaleField);\n } else if (!this.#scaleSwitchable && scaleField !== null) {\n scaleField.remove();\n scaleField = null;\n }\n const select = scaleField === null ? null : scaleField.querySelector('select');\n if (select !== null) {\n setText(found(select.previousElementSibling, 'the Axis label'), this.#word(chartWordIds.axis));\n for (const option of select.options) {\n setText(option, this.#word(option.value === 'Categories' ? chartWordIds.categories : chartWordIds.proportional));\n }\n select.value = (this.#scale ?? axis.effectiveScale) === 'categories' ? 'Categories' : 'Proportional';\n }\n let error = filters.querySelector('.ex-chart-filter-error');\n if (this.#filterError === null) {\n error?.remove();\n } else {\n if (error === null) {\n error = document.createElement('span');\n error.className = 'ex-chart-filter-error';\n error.setAttribute('role', 'alert');\n filters.append(error);\n }\n setText(error, this.#filterError);\n }\n }\n\n #paintStage(): void {\n const scene = this.#scene;\n const stage = this.#stage;\n const width = this.#width;\n const height = this.#height;\n stage.style.cssText = `width:${n(width)}px;height:${n(height)}px`;\n const svg = this.#svg;\n svg.setAttribute('width', n(width));\n svg.setAttribute('height', n(height));\n setText(this.#title, this.#summary);\n\n // The parts, each rewritten only when its markup changed, then the band and the guide over them.\n const lh = this.#lineHeight;\n const kept = new Map(this.#parts.map(p => [p.key, p]));\n const drawn = this.#drawn !== null && this.#drawn.built === this.#built && this.#drawn.angle === this.#angle\n ? this.#drawn : { built: this.#built, angle: this.#angle, parts: drawingParts(scene, lh, this.#angle) };\n this.#drawn = drawn;\n const parts = [...drawn.parts, this.#bandPart(), this.#guidePart()].map(part => {\n const old = kept.get(part.key);\n kept.delete(part.key);\n if (old !== undefined && old.markup === part.markup) {\n return old;\n }\n old?.nodes.forEach(node => { node.remove(); });\n return { ...part, nodes: svgNodes(part.markup) };\n });\n for (const gone of kept.values()) {\n gone.nodes.forEach(node => { node.remove(); });\n }\n let cursor: ChildNode = this.#title;\n for (const part of parts) {\n for (const node of part.nodes) {\n if (cursor.nextSibling !== node) {\n cursor.after(node);\n }\n cursor = node;\n }\n }\n this.#parts = parts;\n\n // A hit layer over each plot, carrying the plot's offsets, which the pointer's offsets are added to.\n const plots = scene.panels.map(p => `${n(p.plot.x)},${n(p.plot.y)},${n(p.plot.width)},${n(p.plot.height)}`).join(';');\n if (plots !== this.#hitPlots) {\n this.#hits.forEach(hit => { hit.remove(); });\n this.#hits = scene.panels.map((panel, i) => {\n const hit = document.createElement('div');\n hit.className = 'ex-chart-hit';\n hit.setAttribute('data-ex-panel', String(i));\n hit.setAttribute('data-ex-x', n(panel.plot.x));\n hit.setAttribute('data-ex-y', n(panel.plot.y));\n hit.style.cssText = `left:${n(panel.plot.x)}px;top:${n(panel.plot.y)}px;width:${n(panel.plot.width)}px;height:${n(panel.plot.height)}px`;\n return hit;\n });\n svg.after(...this.#hits);\n this.#hitPlots = plots;\n }\n this.#paintTooltip();\n }\n\n // What the pointer changes: the band, the guide and the tooltip, and nothing else (ADR-0252).\n #paintPointer(): void {\n const parts = [...this.#parts];\n for (const [i, fresh] of [[parts.length - 2, this.#bandPart()], [parts.length - 1, this.#guidePart()]] as const) {\n const old = elementAt(parts, i);\n if (old.markup === fresh.markup) {\n continue;\n }\n const nodes = svgNodes(fresh.markup);\n const before = parts.slice(0, i).flatMap(p => p.nodes).at(-1);\n old.nodes.forEach(node => { node.remove(); });\n if (before === undefined) {\n this.#title.after(...nodes);\n } else {\n before.after(...nodes);\n }\n parts[i] = { ...fresh, nodes };\n }\n this.#parts = parts;\n this.#paintTooltip();\n }\n\n #paintTooltip(): void {\n const markup = tooltipMarkup(this.#reading, this.#tooltipPlace(), this.#lineHeight,\n count => this.#word(count === 1 ? chartWordIds.oneMoreSeries : chartWordIds.moreSeries, String(count)));\n if (markup === this.#tooltipMarkup) {\n return;\n }\n this.#tooltipMarkup = markup;\n this.#tooltip?.remove();\n this.#tooltip = null;\n if (markup !== '') {\n const holder = document.createElement('div');\n holder.innerHTML = markup;\n const tooltip = found(holder.firstElementChild, 'the tooltip');\n this.#stage.append(tooltip);\n this.#tooltip = tooltip;\n }\n }\n\n get #plotsTop(): number {\n const first = this.#scene.panels[0];\n return first === undefined ? 0 : first.plot.y;\n }\n\n get #plotsBottom(): number {\n const last = this.#scene.panels.at(-1);\n return last === undefined ? 0 : last.plot.y + last.plot.height;\n }\n\n get #guideX(): number | null {\n const i = this.#pointerIndex;\n if (i === null) {\n return null;\n }\n return this.#scene.scatter ? this.#markAt(i).x : elementAt(this.#scene.positions, i)[1];\n }\n\n #guidePart(): DrawingPart {\n const i = this.#pointerIndex;\n const scatter = this.#scene.scatter && i !== null;\n const top = scatter ? this.#markAt(i).y : this.#plotsTop;\n const bottom = scatter ? this.#markAt(i).y : this.#plotsBottom;\n return { key: 'guide', markup: guideMarkup(this.#guideX, top, bottom, this.#dots, this.#lineHeight) };\n }\n\n #bandPart(): DrawingPart {\n const scene = this.#scene;\n if (scene.scatter) {\n const q = this.#pressAt;\n const d = this.#dragAt;\n const span = q !== null && q.version === this.#version && d !== null ? [q.x, d.x] as const : null;\n const top = q !== null && d !== null ? Math.min(q.y, d.y) : this.#plotsTop;\n const bottom = q !== null && d !== null ? Math.max(q.y, d.y) : this.#plotsBottom;\n return { key: 'band', markup: bandMarkup(span, top, bottom) };\n }\n const p = this.#press;\n const i = this.#pointerIndex;\n const span = p !== null && p.version === this.#version && i !== null && i !== p.index\n ? [elementAt(scene.positions, p.index)[1], elementAt(scene.positions, i)[1]] as const : null;\n return { key: 'band', markup: bandMarkup(span, this.#plotsTop, this.#plotsBottom) };\n }\n\n #tooltipPlace(): { readonly left: number; readonly top: number; readonly flip: boolean } {\n const x = this.#guideX;\n const flip = x !== null && x > this.#width / 2;\n const half = this.#lineHeight / 2;\n return {\n left: x === null ? 0 : flip ? x - half : x + half,\n top: this.#pointerIndex === null ? 0 : elementAt(this.#scene.panels, this.#pointerPanel).plot.y,\n flip,\n };\n }\n\n #paintMenu(): void {\n const at = this.#menu;\n const commands = this.#menuCommands();\n // An open menu is kept while it would be drawn the same, so a paint behind it never takes its focus. A Chrome's\n // frame is kept while it stands where it was asked for: its contents are mounted again in it (#showMenuSlot).\n const mount = this.#options.chrome?.menu;\n const shape = at === null ? null : JSON.stringify(mount === undefined ? [at, this.#name, commandShape(commands)] : [at, 'slot']);\n if (shape === this.#menuShape) {\n return;\n }\n this.#menuShape = shape;\n this.#menuSlot?.hide();\n this.#menuSlot = null;\n this.#menuParts.forEach(part => { part.remove(); });\n this.#menuParts = [];\n if (at === null) {\n return;\n }\n // The menu's frame is ExChart's (ADR-0281): it opens where it was asked for, and a click anywhere else,\n // Escape or a chosen command closes it.\n const backdrop = document.createElement('div');\n backdrop.className = 'ex-chart-menu-backdrop';\n const menu = document.createElement('div');\n menu.className = 'ex-chart-menu';\n menu.setAttribute('role', 'menu');\n menu.setAttribute('aria-label', this.#name);\n menu.tabIndex = -1;\n menu.style.cssText = `left:${n(at.x)}px;top:${n(at.y)}px`;\n if (mount !== undefined) {\n // A Chrome draws the items inside ExChart's frame: the frame is the slot.\n this.#stage.after(backdrop, menu);\n this.#menuParts = [backdrop, menu];\n this.#menuSlot = new ChartSlot<ChartMenuSlotContext>('menu', menu);\n return;\n }\n for (const command of commands) {\n const item = document.createElement('button');\n item.type = 'button';\n item.setAttribute('role', 'menuitem');\n item.className = 'ex-chart-menu-item';\n item.setAttribute('data-ex-command', command.id);\n item.disabled = !command.enabled;\n item.textContent = command.label;\n menu.append(item);\n }\n this.#stage.after(backdrop, menu);\n this.#menuParts = [backdrop, menu];\n }\n\n // The menu's contents a Chrome draws, mounted again in the frame only when what they are handed changed.\n #showMenuSlot(): void {\n const slot = this.#menuSlot;\n const mount = this.#options.chrome?.menu;\n if (slot === null || mount === undefined) {\n return;\n }\n const commands = this.#menuCommands();\n slot.show(mount, JSON.stringify([this.#name, commandShape(commands)]), standing => Object.freeze({\n name: this.#name,\n commands: this.#slotCommands(commands, standing, true),\n close: () => {\n if (standing()) {\n this.#closeMenu();\n }\n },\n }));\n }\n\n #paintNotes(): void {\n const notes = this.#scene.notes;\n if (alike(notes, this.#notesShown)) {\n return;\n }\n this.#notesShown = notes;\n this.#notes?.remove();\n this.#notes = null;\n if (notes.length === 0) {\n return;\n }\n const list = document.createElement('ul');\n list.className = 'ex-chart-notes';\n for (const note of notes) {\n const item = document.createElement('li');\n item.textContent = note;\n list.append(item);\n }\n (this.#menuParts.at(-1) ?? this.#stage).after(list);\n this.#notes = list;\n }\n\n #paintTable(): void {\n const shown: ChartTable | 'notice' | null = !this.#tableOpen ? null : this.#thinnedAtSource ? 'notice' : this.#table;\n const caption = this.#options.title === undefined || this.#options.title.trim() === '' ? this.#word(chartWordIds.chartData) : this.#options.title;\n if (shown === 'notice' && this.#tableShown === 'notice' && this.#tableBlock !== null) {\n setText(this.#tableBlock, this.#word(chartWordIds.thinnedAtSource));\n return;\n }\n if (shown === this.#tableShown && this.#tableBlock?.querySelector('caption')?.textContent === caption) {\n return;\n }\n if (shown === this.#tableShown && shown !== 'notice' && shown !== null) {\n setText(found(this.#tableBlock === null ? null : this.#tableBlock.querySelector('caption'), 'the table\\'s caption'), caption);\n return;\n }\n this.#tableShown = shown;\n this.#tableBlock?.remove();\n this.#tableBlock = null;\n if (shown === null) {\n return;\n }\n if (shown === 'notice') {\n const notice = document.createElement('p');\n notice.className = 'ex-chart-table-notice';\n notice.setAttribute('role', 'note');\n notice.textContent = this.#word(chartWordIds.thinnedAtSource);\n this.#root.append(notice);\n this.#tableBlock = notice;\n return;\n }\n const wrap = document.createElement('div');\n wrap.className = 'ex-chart-table-wrap';\n const table = document.createElement('table');\n table.className = 'ex-chart-table';\n const captionElement = document.createElement('caption');\n captionElement.textContent = caption;\n const head = document.createElement('thead');\n const headRow = document.createElement('tr');\n for (const h of shown.header) {\n const th = document.createElement('th');\n th.scope = 'col';\n th.textContent = h;\n headRow.append(th);\n }\n head.append(headRow);\n const body = document.createElement('tbody');\n for (const row of shown.rows) {\n const tr = document.createElement('tr');\n row.forEach((value, c) => {\n const cell = document.createElement(c === 0 ? 'th' : 'td');\n if (c === 0) {\n cell.setAttribute('scope', 'row');\n }\n cell.textContent = value;\n tr.append(cell);\n });\n body.append(tr);\n }\n table.append(captionElement, head, body);\n wrap.append(table);\n this.#root.append(wrap);\n this.#tableBlock = wrap;\n }\n}\n\n/** The class the built-in toolbar's button for a command carries, which the DOM contract and layer 3 name. */\nfunction toolbarClass(id: string): string {\n switch (id) {\n case chartWordIds.filters: return 'ex-chart-filters-toggle';\n case chartWordIds.resetRange: return 'ex-chart-reset';\n case chartWordIds.table: return 'ex-chart-table-toggle';\n case chartWordIds.downloadCsv: return 'ex-chart-download-csv';\n case chartWordIds.downloadSvg: return 'ex-chart-download-svg';\n case chartWordIds.downloadPng: return 'ex-chart-download-png';\n default: throw new Error(`Internal: the toolbar has no button for ${id}.`);\n }\n}\n\n// What a command shows, for telling whether a Chrome's part would be drawn the same (JSON writes an absent one as null).\nconst commandShape = (commands: readonly Command[]): unknown[] =>\n commands.map(c => [c.id, c.label, c.enabled, c.expanded, c.title]);\n\n// Whether `element` stands in a Chrome's slot, whose contents answer through their context (ADR-0390).\nconst inSlot = (element: Element): boolean => element.closest('[data-ex-chart-slot]') !== null;\n\n/** The value, which the chart knows is there: `null` throws, naming what was missing. */\nfunction found<T>(value: T | null, what: string): T {\n if (value === null) {\n throw new Error(`Internal: ${what} is missing.`);\n }\n return value;\n}\n\n// A field's text: an end not typed is an empty field.\nconst fieldText = (text: string | null): string => (text === null ? '' : text);\n\nfunction setText(element: Element, text: string): void {\n if (element.textContent !== text) {\n element.textContent = text;\n }\n}\n\n// SVG markup parsed in SVG's namespace, as the nodes it is.\nfunction svgNodes(markup: string): readonly ChildNode[] {\n if (markup === '') {\n return [];\n }\n const holder = document.createElementNS(svgNs, 'g');\n holder.innerHTML = markup;\n return [...holder.childNodes];\n}\n", "// ExChart's Chrome slots (ADR-0281, ADR-0390 section 3): the chart's toolbar, with Chart Filters, and its context\n// menu's contents, drawn by a Wrapper in place of the built-in markup, as the C# `IChartChrome` lets a Chrome do.\n// The chart makes the slot, an element where the part stands, and hands it to the slot's mount function with what\n// the part shows and the callbacks it answers through. What the part means is the chart's: the commands and their\n// order, which are enabled, what a typed range reads as, where the menu opens and what closes it. The contents only\n// draw, and call back. The legend, the tooltip and the plot are always the chart's own (ADR-0255).\n//\n// A context is handed whole at each mount and never changes under the contents. When what the chart hands changes,\n// the chart takes the contents away and mounts them again on the same slot, as the grid's slots are (ADR-0390): a\n// framework that keys its rendering by the slot, as `@ex-grid/react`'s portals do, keeps its component and that\n// component's state across the two. A context equal to the last is not mounted again, so a pointer moving over the\n// plot draws no part of the Chrome (ADR-0252).\n\nimport type { AxisScale, AxisValues } from '../model';\n\n/**\n * A Chrome slot's mount function (ADR-0350 section 9): it draws the part into `slot`, the element the chart made\n * for it, from `context`, and answers the function that takes what it drew away. The chart calls that cleanup\n * before the slot goes, and before it mounts again on the same slot with a new context.\n */\nexport type ChartChromeSlot<Context> = (slot: HTMLElement, context: Context) => () => void;\n\n/** One command the chart decides (ADR-0281): what it is called, whether it is available, and what it does. */\nexport interface ChartCommand {\n /** Stable, for an icon: one of `chartWordIds`' command ids. */\n readonly id: string;\n /** What it is called, in the chart's words. */\n readonly label: string;\n /** Whether it is available: Reset range is not while nothing is narrowed, CSV not on a chart its Chart Source thinned. */\n readonly enabled: boolean;\n /** For a toggle, Chart Filters and View as table, whether what it opens is open; absent on a plain command. */\n readonly expanded?: boolean;\n /** Why it is not available, where the chart says why (CSV on a thinned chart, ADR-0344); absent otherwise. */\n readonly title?: string;\n /** Runs it, as the built-in control's click does; from the context menu it closes the menu first. Nothing once\n * the contents it was handed to are taken away or handed another context: what they drew is no longer the\n * chart's (spine rule 6). */\n readonly invoke: () => void;\n}\n\n/**\n * Chart Filters (ADR-0273): the range typed in the axis' own values, and the axis switch. The contents hold what is\n * being typed; the chart reads it when it is applied, and says what it could not read rather than guess (spine\n * rule 1).\n */\nexport interface ChartFiltersSlotContext {\n /** What the axis holds: a date axis may take a date input, a category axis one of {@link ChartFiltersSlotContext.labels}. */\n readonly values: AxisValues;\n /** The categories of a category axis, in order; empty otherwise. */\n readonly labels: readonly string[];\n /** The range's start as the chart holds it, in the axis' text (a date as yyyy-MM-dd); `null` for the axis' own\n * start. It changes when Chart Filters opens, a drag narrows the range, or Reset range returns it, and what the\n * contents hold typed is then replaced by it. */\n readonly from: string | null;\n /** The range's end, likewise; `null` for the axis' own end. */\n readonly to: string | null;\n /** What a value looks like on this axis. */\n readonly hint: string;\n /** Why the last range applied was not taken; `null` when it was. */\n readonly error: string | null;\n /** Applies a typed range: an end empty or `null` is the axis' own end. Nothing once the contents are handed\n * another context, as a command's `invoke`. */\n readonly apply: (from: string | null, to: string | null) => void;\n /** How positions are spaced, where the axis can be switched; absent where it cannot. */\n readonly scale?: AxisScale;\n /** Switches the axis; nothing once the contents are handed another context. */\n readonly setScale: (scale: AxisScale) => void;\n}\n\n/** What the toolbar's contents are handed (ADR-0281). The slot stands above the plot; the contents draw the toolbar\n * (`role=\"toolbar\"`, named {@link ChartToolbarSlotContext.name}) and, while {@link ChartToolbarSlotContext.filters} is\n * given, Chart Filters below it. */\nexport interface ChartToolbarSlotContext {\n /** The toolbar's accessible name: the chart's title, or its word for a chart. */\n readonly name: string;\n /** Chart Filters' toggle, Reset range, View as table, then CSV, SVG and PNG, in that order. */\n readonly commands: readonly ChartCommand[];\n /** Chart Filters while it is open; absent while it is closed. */\n readonly filters?: ChartFiltersSlotContext;\n /** One of the chart's words by its id (`chartWordIds`): the Consumer's `label`, else the built-in English. */\n readonly label: (id: string) => string;\n}\n\n/** What the context menu's contents are handed (ADR-0281). The slot is the menu's frame (`role=\"menu\"`, named by\n * the chart), which opens where it was asked for and takes the keyboard; a click outside it, Escape on it or a\n * command invoked closes it. The contents draw one item per command, in this order. */\nexport interface ChartMenuSlotContext {\n /** The menu's accessible name. */\n readonly name: string;\n /** Reset range, View as table, then CSV, SVG and PNG. */\n readonly commands: readonly ChartCommand[];\n /** Closes the menu, for a dismissal of the contents' own; nothing once the menu has closed. */\n readonly close: () => void;\n}\n\n/** The Chrome slots a chart takes: the parts a Wrapper draws, each in place of the built-in markup's. A slot not\n * given is the built-in markup's. */\nexport interface ChartChrome {\n /** The toolbar, with Chart Filters' range and the axis switch (ADR-0273, ADR-0281). */\n readonly toolbar?: ChartChromeSlot<ChartToolbarSlotContext>;\n /** The context menu's contents (ADR-0281). */\n readonly menu?: ChartChromeSlot<ChartMenuSlotContext>;\n}\n\nconst slotNames: readonly (keyof ChartChrome)[] = ['toolbar', 'menu'];\n\n/** A chart's `chrome`, checked as a script may hand it: an object whose slots are each a mount function. */\nexport function checkedChartChrome(chrome: unknown): ChartChrome | undefined {\n if (chrome === undefined) return undefined;\n if (typeof chrome !== 'object' || chrome === null) {\n throw new TypeError('An ExChart\\'s chrome is an object of Chrome slots, each a mount function (ADR-0390).');\n }\n for (const [name, slot] of Object.entries(chrome)) {\n if (!(slotNames as readonly string[]).includes(name)) {\n throw new TypeError(`An ExChart's chrome has no slot '${name}': its slots are ${slotNames.join(', ')} (ADR-0390).`);\n }\n if (slot !== undefined && typeof slot !== 'function') {\n throw new TypeError(`An ExChart's chrome.${name} is a mount function, (slot, context) => cleanup (ADR-0350 section 9).`);\n }\n }\n return chrome;\n}\n\n/**\n * The contents a slot shows: mounted by a mount function with a context, mounted again only when the mount function\n * or what the context holds (its `key`) changed, and taken away when the part goes. A context's callbacks act only\n * while the contents it was handed to stand: one handed to contents taken away, or to contents since mounted again\n * with another, does nothing, as the grid's slots' do (ADR-0390), so a press on what is no longer drawn never acts on\n * what the chart now shows (spine rule 6).\n */\nexport class ChartSlot<Context> {\n readonly #name: string;\n /** The slot, which stands where the part does. */\n readonly element: HTMLElement;\n #mount: ChartChromeSlot<Context> | undefined;\n #key: string | undefined;\n #cleanup: (() => void) | undefined;\n // Counts the mounts, so a callback handed to one reaches nothing once another stands.\n #mounts = 0;\n // What failed to mount, which is not tried again on every paint: it is thrown once.\n #failed: { readonly mount: ChartChromeSlot<Context>; readonly key: string } | undefined;\n\n constructor(name: string, element: HTMLElement) {\n this.#name = name;\n this.element = element;\n // The chart's own handlers leave what happens inside the slot to its contents.\n element.setAttribute('data-ex-chart-slot', name);\n }\n\n /** Whether contents stand, mounted by `mount` for `key`. */\n shows(mount: ChartChromeSlot<Context>, key: string): boolean {\n return this.#cleanup !== undefined && this.#mount === mount && this.#key === key;\n }\n\n /** Shows the contents `mount` draws from the context `context` makes, unless they already stand for `key`.\n * `context` is handed whether the mount it is made for still stands, for its callbacks to ask. */\n show(mount: ChartChromeSlot<Context>, key: string, context: (standing: () => boolean) => Context): void {\n if (this.shows(mount, key) || (this.#failed?.mount === mount && this.#failed.key === key)) return;\n this.hide();\n this.#mounts += 1;\n const made = this.#mounts;\n const standing = (): boolean => this.#cleanup !== undefined && this.#mounts === made;\n const answered: unknown = (() => {\n try {\n return mount(this.element, context(standing));\n } catch (error) {\n this.#failed = { mount, key };\n throw error;\n }\n })();\n if (typeof answered !== 'function') {\n this.#failed = { mount, key };\n throw new TypeError(`An ExChart's chrome.${this.#name} answered ${typeof answered}: a mount function answers the function that takes its contents away.`);\n }\n this.#cleanup = () => { Reflect.apply(answered, undefined, []); };\n this.#mount = mount;\n this.#key = key;\n }\n\n /** The part shows nothing of the contents: they are taken away. */\n hide(): void {\n const cleanup = this.#cleanup;\n this.#cleanup = undefined;\n this.#mount = undefined;\n this.#key = undefined;\n this.#failed = undefined;\n cleanup?.();\n }\n}\n", "// The pieces SVG markup is written from (ADR-0252): numbers as the C# component writes them, text escaped,\n// a marker's outline, a look's classes. One writer serves the screen and a saved file, so the two cannot\n// drift (ADR-0282).\nimport type { MarkerShape, SeriesLook } from '../model';\nimport { roundToDigits } from '../numbers';\nimport { upToPlaces } from '../invariant-text';\nimport { unreachable } from '../must';\n\n/** A number written into an SVG attribute: invariant, to a hundredth of a pixel, as C#'s `Svg.N`. */\nexport function n(value: number): string {\n return upToPlaces(roundToDigits(value, 2), 2);\n}\n\nconst escapes: Readonly<Record<string, string>> = { '&': '&', '<': '<', '>': '>', '\"': '"', '\\'': ''' };\n\n/** Text as markup holds it, in content or in a quoted attribute: a Consumer's name is never markup. */\nexport function escapeText(text: string): string {\n return text.replace(/[&<>\"']/g, c => escapes[c] ?? c);\n}\n\n/** A marker's outline at (x, y): a circle, square, diamond or triangle of radius r, as one subpath. */\nexport function markerPath(shape: MarkerShape, x: number, y: number, r: number): string {\n switch (shape) {\n case 'square':\n return `M${n(x - r)},${n(y - r)}h${n(2 * r)}v${n(2 * r)}h${n(-2 * r)}Z`;\n case 'diamond':\n return `M${n(x)},${n(y - r * 1.25)}L${n(x + r * 1.25)},${n(y)}L${n(x)},${n(y + r * 1.25)}L${n(x - r * 1.25)},${n(y)}Z`;\n case 'triangle':\n return `M${n(x)},${n(y - r * 1.3)}L${n(x + r * 1.2)},${n(y + r * 0.8)}L${n(x - r * 1.2)},${n(y + r * 0.8)}Z`;\n case 'circle':\n return `M${n(x - r)},${n(y)}a${n(r)},${n(r)} 0 1,0 ${n(2 * r)},0a${n(r)},${n(r)} 0 1,0 ${n(-2 * r)},0Z`;\n default:\n return unreachable(shape);\n }\n}\n\n/** The classes a look is painted by: the stylesheet's Visual Tokens say what each slot looks like (ADR-0256). */\nexport function lookClasses(look: SeriesLook): string {\n return `ex-chart-colour-${String(look.colour)} ex-chart-line-${String(look.lineStyle)}`;\n}\n\n/** An element's markup: its attributes written in order, each value escaped. */\nexport function element(name: string, attributes: readonly (readonly [name: string, value: string])[], content = ''): string {\n const written = attributes.map(([key, value]) => ` ${key}=\"${escapeText(value)}\"`).join('');\n return `<${name}${written}>${content}</${name}>`;\n}\n", "// The parts of a chart's drawing as SVG markup (ADR-0252): a panel's axes, each series, a panel's legend,\n// the keys of colours and sizes, the pointer's guide and a drag's band, and the tooltip. Each part is\n// written from the immutable piece of the scene it draws, so the element that holds it is rewritten only\n// when its markup changed, and a move of the pointer rewrites the tooltip and the guide and nothing else.\n// The same writers draw a saved file (ADR-0282), so a file cannot drift from the screen.\nimport type { Box } from '../metrics';\nimport type { ChartReading } from '../reading';\nimport type { ColourKey, SizeKey } from '../point-scales';\nimport type { ChartScene, HorizontalTick, LegendEntry, PanelScene, SeriesPiece, VerticalAxis } from '../scene';\nimport type { DrawnWhisker } from '../series-drawing';\nimport type { SeriesLook } from '../model';\nimport { element, escapeText, lookClasses, markerPath, n } from './svg-markup';\n\n/** One part of the drawing: the key it is kept by between drawings, and its markup. */\nexport interface DrawingPart {\n readonly key: string;\n readonly markup: string;\n}\n\n/** A panel's plot frame, grid lines, zero line, break mark and vertical axes; under the last panel, the horizontal axis. */\nexport function axesMarkup(panel: PanelScene, xTicks: readonly HorizontalTick[], last: boolean, lineHeight: number, angle: number): string {\n const p = panel.plot;\n const right = p.x + p.width;\n const bottom = p.y + p.height;\n let out = element('rect', [['class', 'ex-chart-plot'], ['x', n(p.x)], ['y', n(p.y)], ['width', n(p.width)], ['height', n(p.height)]]);\n // Vertical grid lines at the horizontal axis' ticks, in every panel, so a date can be followed down.\n for (const [, x] of xTicks) {\n out += element('line', [['class', 'ex-chart-grid'], ['x1', n(x)], ['x2', n(x)], ['y1', n(p.y)], ['y2', n(bottom)]]);\n }\n if (panel.left !== null) {\n out += vertical(panel.left, p.x - lineHeight / 4, 'end', p, lineHeight);\n }\n if (panel.right !== null) {\n out += vertical(panel.right, right + lineHeight / 4, 'start', p, lineHeight);\n }\n if (panel.zeroY !== null) {\n out += element('line', [['class', 'ex-chart-zero'], ['x1', n(p.x)], ['x2', n(right)], ['y1', n(panel.zeroY)], ['y2', n(panel.zeroY)]]);\n }\n if (last) {\n const y = bottom + lineHeight;\n for (const [, x, label] of xTicks) {\n if (label === null) {\n continue;\n }\n const attributes: (readonly [string, string])[] = [\n ['class', 'ex-chart-tick ex-chart-tick-x'], ['x', n(x)], ['y', n(y)], ['text-anchor', angle === 0 ? 'middle' : 'end'],\n ];\n if (angle !== 0) {\n attributes.push(['transform', `rotate(${String(-angle)} ${n(x)} ${n(y)})`]);\n }\n out += element('text', attributes, escapeText(label));\n }\n }\n return element('g', [['class', 'ex-chart-axes']], out);\n}\n\nfunction vertical(axis: VerticalAxis, x: number, anchor: string, p: Box, lineHeight: number): string {\n let out = '';\n for (const [, y, label] of axis.ticks) {\n if (axis.side === 'left') {\n out += element('line', [['class', 'ex-chart-grid'], ['x1', n(p.x)], ['x2', n(p.x + p.width)], ['y1', n(y)], ['y2', n(y)]]);\n }\n out += element('text', [['class', 'ex-chart-tick'], ['x', n(x)], ['y', n(y)], ['dy', '0.35em'], ['text-anchor', anchor]], escapeText(label));\n }\n if (axis.broken) {\n // The axis does not reach zero (ADR-0253): a break mark at its foot says so.\n const edge = axis.side === 'left' ? p.x : p.x + p.width;\n const s = lineHeight / 4;\n const foot = p.y + p.height;\n out += element('path', [['class', 'ex-chart-break'],\n ['d', `M${n(edge - s)},${n(foot - s * 1.5)}l${n(2 * s)},${n(-s)}M${n(edge - s)},${n(foot - s * 0.5)}l${n(2 * s)},${n(-s)}`]]);\n }\n return out;\n}\n\nconst path = (cls: string, d: string): string => (d === '' ? '' : element('path', [['class', cls], ['d', d]]));\n\nconst rect = (x0: number, y0: number, x1: number, y1: number): string =>\n `M${n(x0)},${n(Math.min(y0, y1))}H${n(x1)}V${n(Math.max(y0, y1))}H${n(x0)}Z`;\n\nconst vLine = (x: number, y0: number, y1: number): string => `M${n(x)},${n(y0)}V${n(y1)}`;\n\n/** One series: its lines as one path, its markers as two (filled and open), its extrapolated ranges. Its node count does not grow with its points (CH-3). */\nexport function seriesMarkup(piece: SeriesPiece, plot: Box, lineHeight: number): string {\n let out = '';\n for (const [from, to] of piece.extrapolated) {\n out += element('rect', [['class', 'ex-chart-extrapolated'], ['x', n(from)], ['y', n(plot.y)], ['width', n(Math.max(0, to - from))], ['height', n(plot.height)]]);\n }\n if (piece.edges.length > 0) {\n // A node's edges, under its markers (ADR-0321).\n out += element('path', [['class', 'ex-chart-edges'], ['d', piece.edges.map(e => `M${n(e.x1)},${n(e.y1)}L${n(e.x2)},${n(e.y2)}`).join('')]]);\n }\n let d = '';\n for (const line of piece.lines) {\n line.forEach((point, i) => { d += `${i === 0 ? 'M' : 'L'}${n(point.x)},${n(point.y)}`; });\n }\n out += element('path', [['class', 'ex-chart-path'], ['d', d]]);\n\n const r = lineHeight / 5;\n let filled = '';\n let open = '';\n // A marker coloured from a column is filled with its band's Visual Token (ADR-0320).\n const banded = new Map<number, string[]>();\n for (const m of piece.markers) {\n const outline = markerPath(piece.look.shape, m.x, m.y, m.radius ?? r);\n if (!m.filled) {\n open += outline;\n } else if (m.band !== undefined) {\n const into = banded.get(m.band);\n if (into === undefined) {\n banded.set(m.band, [outline]);\n } else {\n into.push(outline);\n }\n } else {\n filled += outline;\n }\n }\n out += element('path', [['class', 'ex-chart-markers'], ['d', filled]]);\n out += element('path', [['class', 'ex-chart-markers ex-chart-markers-open'], ['d', open]]);\n for (const [band, outlines] of [...banded].toSorted(([a], [b]) => a - b)) {\n out += element('path', [['class', `ex-chart-markers ex-chart-${piece.colourDiverging ? 'diverge' : 'heat'}-${String(band)}`], ['d', outlines.join('')]]);\n }\n if (piece.candles.length > 0 || piece.volumes.length > 0) {\n out += candles(piece);\n }\n if (piece.whiskers.length > 0 || piece.bands.length > 0) {\n out += intervals(piece, r);\n }\n if (piece.markers.some(m => m.yBounds !== undefined || m.xBounds !== undefined)) {\n out += markIntervals(piece, r);\n }\n const classes = `ex-chart-series ${lookClasses(piece.look)}${piece.interpolated ? ' ex-chart-interpolated' : ''}`;\n return element('g', [['class', classes], ['data-series', piece.id]], out);\n}\n\n// A candle's wick runs from its high to the body and from the body to its low, never through a hollow\n// body; a High-Low-Close bar is its range with the close ticked to the right (ADR-0300).\nfunction candles(piece: SeriesPiece): string {\n let rising = '';\n let falling = '';\n let unchanged = '';\n let hlc = '';\n for (const c of piece.candles) {\n const o = c.openY;\n if (o === null) {\n hlc += `${vLine(c.x, c.highY, c.lowY)}M${n(c.x)},${n(c.closeY)}H${n(c.x + c.halfWidth)}`;\n continue;\n }\n if (c.unchanged) {\n unchanged += `${vLine(c.x, c.highY, c.lowY)}M${n(c.x - c.halfWidth)},${n(o)}H${n(c.x + c.halfWidth)}`;\n continue;\n }\n const top = Math.min(o, c.closeY);\n const bottom = Math.max(o, c.closeY);\n const d = vLine(c.x, c.highY, top) + vLine(c.x, bottom, c.lowY) + rect(c.x - c.halfWidth, top, c.x + c.halfWidth, bottom);\n if (c.rising) {\n rising += d;\n } else {\n falling += d;\n }\n }\n for (const v of piece.volumes) {\n const d = rect(v.x - v.halfWidth, v.topY, v.x + v.halfWidth, v.baseY);\n if (v.unchanged) {\n unchanged += d;\n } else if (v.rising) {\n rising += d;\n } else {\n falling += d;\n }\n }\n return path('ex-chart-candles ex-chart-rising', rising) + path('ex-chart-candles ex-chart-falling', falling)\n + path('ex-chart-candles ex-chart-unchanged', unchanged) + path('ex-chart-candles ex-chart-hlc', hlc);\n}\n\n// An Interval: whiskers with a cap at each bound, or a band between the bounds over each run of\n// neighbours; a run of one is drawn as a whisker, never dropped (ADR-0303).\nfunction intervals(piece: SeriesPiece, r: number): string {\n let whiskers = '';\n let band = '';\n const whisker = (w: DrawnWhisker): void => {\n whiskers += `${vLine(w.x, w.lower, w.upper)}M${n(w.x - r)},${n(w.lower)}h${n(2 * r)}M${n(w.x - r)},${n(w.upper)}h${n(2 * r)}`;\n };\n piece.whiskers.forEach(whisker);\n for (const run of piece.bands) {\n const [only] = run;\n if (run.length === 1 && only !== undefined) {\n whisker(only);\n continue;\n }\n run.forEach((w, i) => { band += `${i === 0 ? 'M' : 'L'}${n(w.x)},${n(w.upper)}`; });\n run.toReversed().forEach(w => { band += `L${n(w.x)},${n(w.lower)}`; });\n band += 'Z';\n }\n return path('ex-chart-interval-band', band) + path('ex-chart-whiskers', whiskers);\n}\n\n// An Observation's intervals: a whisker up and down and one across, each capped, through its mark; a\n// merged mark's is the union of its points' (ADR-0304).\nfunction markIntervals(piece: SeriesPiece, r: number): string {\n let d = '';\n for (const m of piece.markers) {\n if (m.yBounds !== undefined) {\n const [lower, upper] = m.yBounds;\n d += `${vLine(m.x, lower, upper)}M${n(m.x - r)},${n(lower)}h${n(2 * r)}M${n(m.x - r)},${n(upper)}h${n(2 * r)}`;\n }\n if (m.xBounds !== undefined) {\n const [lower, upper] = m.xBounds;\n d += `M${n(lower)},${n(m.y)}H${n(upper)}M${n(lower)},${n(m.y - r)}v${n(2 * r)}M${n(upper)},${n(m.y - r)}v${n(2 * r)}`;\n }\n }\n return path('ex-chart-whiskers', d);\n}\n\n/** A panel's legend (ADR-0271): every series of the panel, a hidden one faded; a click or Enter hides or shows it. */\nexport function legendMarkup(entries: readonly LegendEntry[], lineHeight: number): string {\n if (entries.length === 0) {\n return '';\n }\n const lh = lineHeight;\n const swatch = lh * 1.5;\n const written = entries.map(e => {\n const box = e.box;\n const mid = box.y + box.height / 2;\n const content = element('rect', [['class', 'ex-chart-legend-hit'], ['x', n(box.x)], ['y', n(box.y)], ['width', n(box.width)], ['height', n(box.height)]])\n + element('line', [['class', 'ex-chart-path'], ['x1', n(box.x)], ['x2', n(box.x + swatch)], ['y1', n(mid)], ['y2', n(mid)]])\n + element('path', [['class', 'ex-chart-markers'], ['d', markerPath(e.look.shape, box.x + swatch / 2, mid, lh / 5)]])\n + element('text', [['class', 'ex-chart-legend-name'], ['x', n(box.x + swatch + lh / 4)], ['y', n(mid)], ['dy', '0.35em']], escapeText(e.name));\n return element('g', [\n ['class', `ex-chart-legend-entry ${lookClasses(e.look)}${e.hidden ? ' ex-chart-hidden' : ''}`], ['role', 'button'], ['tabindex', '0'],\n ['aria-pressed', e.hidden ? 'false' : 'true'], ['data-series', e.id],\n ], content);\n });\n return element('g', [['class', 'ex-chart-legend']], written.join(''));\n}\n\nconst keyTitle = (title: string, x: number, y: number): string =>\n element('text', [['class', 'ex-chart-key-title'], ['x', n(x)], ['y', n(y)]], escapeText(title));\n\n/** The key of colours read from a column, beside the plot (ADR-0320): a colour bar of the bands with its ticks. */\nexport function colourKeyMarkup(key: ColourKey, lineHeight: number): string {\n const lh = lineHeight;\n const box = key.box;\n let out = keyTitle(key.title, box.x, box.y - lh / 2);\n const band = box.height / key.bands;\n for (let i = 0; i < key.bands; i++) {\n out += element('rect', [['class', `ex-chart-key-band ex-chart-${key.diverging ? 'diverge' : 'heat'}-${String(i)}`],\n ['x', n(box.x)], ['y', n(box.y + box.height - (i + 1) * band)], ['width', n(box.width)], ['height', n(band)]]);\n }\n out += element('rect', [['class', 'ex-chart-key-frame'], ['x', n(box.x)], ['y', n(box.y)], ['width', n(box.width)], ['height', n(box.height)]]);\n for (const t of key.ticks) {\n out += element('text', [['class', 'ex-chart-tick'], ['x', n(box.x + box.width + lh / 3)], ['y', n(t.y)], ['dy', '0.35em']], escapeText(t.label));\n }\n return element('g', [['class', 'ex-chart-key ex-chart-colour-key'], ['data-series', key.seriesId]], out);\n}\n\n/** The key of sizes read from a column (ADR-0320): markers at round values. */\nexport function sizeKeyMarkup(key: SizeKey, lineHeight: number): string {\n const lh = lineHeight;\n const box = key.box;\n let out = keyTitle(key.title, box.x, box.y - lh / 2);\n let y = box.y;\n const cx = box.x + box.width / 2;\n for (const e of key.entries) {\n const row = Math.max(2 * e.radius, lh);\n const cy = y + row / 2;\n out += element('circle', [['class', 'ex-chart-key-size'], ['cx', n(cx)], ['cy', n(cy)], ['r', n(e.radius)]]);\n out += element('text', [['class', 'ex-chart-tick'], ['x', n(box.x + box.width + lh / 3)], ['y', n(cy)], ['dy', '0.35em']], escapeText(e.label));\n y += row + lh / 4;\n }\n return element('g', [['class', 'ex-chart-key ex-chart-size-key'], ['data-series', key.seriesId]], out);\n}\n\n/** Every part of the panels, in drawing order and keyed as the screen keeps them: each panel's axes, series and legend, then the keys. */\nexport function drawingParts(scene: ChartScene, lineHeight: number, angle: number): DrawingPart[] {\n const parts: DrawingPart[] = [];\n scene.panels.forEach((panel, i) => {\n parts.push({ key: `axes:${panel.name}`, markup: axesMarkup(panel, scene.xTicks, i === scene.panels.length - 1, lineHeight, angle) });\n for (const piece of panel.series) {\n parts.push({ key: `${panel.volumeOf === null ? 'series:' : 'volume:'}${piece.id}`, markup: seriesMarkup(piece, panel.plot, lineHeight) });\n }\n parts.push({ key: `legend:${panel.name}`, markup: legendMarkup(panel.legend, lineHeight) });\n });\n for (const key of scene.colourKeys) {\n parts.push({ key: `colour:${key.seriesId}`, markup: colourKeyMarkup(key, lineHeight) });\n }\n for (const key of scene.sizeKeys) {\n parts.push({ key: `size:${key.seriesId}`, markup: sizeKeyMarkup(key, lineHeight) });\n }\n return parts;\n}\n\n/** A dot on the guide, where a series' value stands at the pointer's position. */\nexport interface GuideDot {\n readonly y: number;\n readonly look: SeriesLook;\n}\n\n/** The vertical guide at the pointer's position, across every panel, and the dots of the pointer's panel (ADR-0270). */\nexport function guideMarkup(x: number | null, top: number, bottom: number, dots: readonly GuideDot[], lineHeight: number): string {\n if (x === null) {\n return '';\n }\n const line = element('line', [['class', 'ex-chart-guide-line'], ['x1', n(x)], ['x2', n(x)], ['y1', n(top)], ['y2', n(bottom)]]);\n const circles = dots.map(d => element('circle', [['class', `ex-chart-dot ${lookClasses(d.look)}`], ['cx', n(x)], ['cy', n(d.y)], ['r', n(lineHeight / 5)]]));\n return element('g', [['class', 'ex-chart-guide']], line + circles.join(''));\n}\n\n/** The band a drag across the plot draws (ADR-0273). */\nexport function bandMarkup(span: readonly [from: number, to: number] | null, top: number, bottom: number): string {\n if (span === null) {\n return '';\n }\n const [from, to] = span;\n return element('rect', [['class', 'ex-chart-band'], ['x', n(Math.min(from, to))], ['y', n(top)], ['width', n(Math.abs(to - from))], ['height', n(bottom - top)]]);\n}\n\n/** Where the tooltip stands, and whether it opens to the left of the guide. */\nexport interface TooltipPlace {\n readonly left: number;\n readonly top: number;\n readonly flip: boolean;\n}\n\n/** The tooltip (ADR-0270): the position, then a line per series, then \"and M more series\", as HTML. */\nexport function tooltipMarkup(reading: ChartReading | null, place: TooltipPlace, lineHeight: number, more: (count: number) => string): string {\n if (reading === null) {\n return '';\n }\n const lh = lineHeight;\n let out = element('div', [['class', 'ex-chart-tooltip-position']], escapeText(reading.position));\n for (const line of reading.lines) {\n const swatch = element('svg', [['class', 'ex-chart-swatch'], ['width', n(lh * 1.5)], ['height', n(lh)], ['aria-hidden', 'true']],\n element('line', [['class', 'ex-chart-path'], ['x1', '0'], ['x2', n(lh * 1.5)], ['y1', n(lh / 2)], ['y2', n(lh / 2)]])\n + element('path', [['class', 'ex-chart-markers'], ['d', markerPath(line.look.shape, lh * 0.75, lh / 2, lh / 5)]]));\n const note = line.note === null ? '' : element('span', [['class', 'ex-chart-tooltip-note']], escapeText(line.note));\n out += element('div', [['class', `ex-chart-tooltip-line ${lookClasses(line.look)}`], ['data-series', line.id]],\n swatch\n + element('span', [['class', 'ex-chart-tooltip-name']], escapeText(line.name))\n // oxlint-disable-next-line ex-grid/no-stand-in-default -- ADR-0270: a series with no value at the position shows a dash, its note saying why\n + element('span', [['class', 'ex-chart-tooltip-value']], escapeText(line.value ?? '\u2013'))\n + note);\n }\n if (reading.more > 0) {\n out += element('div', [['class', 'ex-chart-tooltip-more']], escapeText(more(reading.more)));\n }\n return element('div', [\n ['class', `ex-chart-tooltip${place.flip ? ' ex-chart-tooltip-flip' : ''}`],\n ['style', `left:${n(place.left)}px;top:${n(place.top)}px;line-height:${n(lh)}px`],\n ], out);\n}\n", "// Written by tools/assets/minify.mjs (ADR-0123): do not edit. Edit dotnet/src/ExChart/Assets/ and run it\n// again, and commit what it writes. test/shipped-stylesheet.test.ts checks it against the source.\n\n/** The name of the stylesheet the chart draws against, by which its notice rules find the notice. */\nexport const stylesheetName = 'ex-chart.css';\n\n/** The SHA-256 of that stylesheet's source: the stamp its own notice rule hides the notice for. */\nexport const stylesheetStamp = '26a000a0c2197a34ec908d2b970d4aa57abbd522f53134cb2eab0ef21d694614';\n\n/** The stylesheet as it ships, minified, without its source map comment: what a saved SVG carries. */\nexport const stylesheetText = \"/*! ex-chart.css sha256:26a000a0c2197a34ec908d2b970d4aa57abbd522f53134cb2eab0ef21d694614 - generated by tools/assets/minify.mjs (ADR-0123): edit Assets/ex-chart.css and run it again */\\n.ex-chart{--_ex-chart-colour-0: var(--ex-chart-colour-0, #1f6fb4);--_ex-chart-colour-1: var(--ex-chart-colour-1, #e8710a);--_ex-chart-colour-2: var(--ex-chart-colour-2, #2a9d4b);--_ex-chart-colour-3: var(--ex-chart-colour-3, #c62828);--_ex-chart-colour-4: var(--ex-chart-colour-4, #7b52ab);--_ex-chart-colour-5: var(--ex-chart-colour-5, #8c564b);--_ex-chart-colour-6: var(--ex-chart-colour-6, #d6378f);--_ex-chart-colour-7: var(--ex-chart-colour-7, #5f6368);--_ex-chart-colour-8: var(--ex-chart-colour-8, #a8a000);--_ex-chart-colour-9: var(--ex-chart-colour-9, #00a3b4);--_ex-chart-dash-1: var(--ex-chart-dash-1, 6 4);--_ex-chart-dash-2: var(--ex-chart-dash-2, 1.5 3);--_ex-chart-dash-3: var(--ex-chart-dash-3, 8 3 1.5 3);--_ex-chart-stroke: var(--ex-chart-stroke, 1.75);--_ex-chart-text: var(--ex-chart-text, var(--ex-text, CanvasText));--_ex-chart-muted: var(--ex-chart-muted, color-mix(in srgb, var(--_ex-chart-text) 60%, transparent));--_ex-chart-background: var(--ex-chart-background, var(--ex-background, Canvas));--_ex-chart-grid: var(--ex-chart-grid, color-mix(in srgb, var(--_ex-chart-text) 12%, transparent));--_ex-chart-axis: var(--ex-chart-axis, color-mix(in srgb, var(--_ex-chart-text) 45%, transparent));--_ex-chart-guide: var(--ex-chart-guide, color-mix(in srgb, var(--_ex-chart-text) 55%, transparent));--_ex-chart-band: var(--ex-chart-band, color-mix(in srgb, var(--_ex-chart-colour-0) 15%, transparent));--_ex-chart-extrapolated: var(--ex-chart-extrapolated, color-mix(in srgb, var(--_ex-chart-text) 6%, transparent));--_ex-chart-error: var(--ex-chart-error, var(--ex-state-error-color, #b3261e));--_ex-chart-rise: var(--ex-chart-rise, currentColor);--_ex-chart-fall: var(--ex-chart-fall, currentColor);--_ex-chart-heat-0: var(--ex-chart-heat-0, #1a9850);--_ex-chart-heat-1: var(--ex-chart-heat-1, #66bd63);--_ex-chart-heat-2: var(--ex-chart-heat-2, #a6d96a);--_ex-chart-heat-3: var(--ex-chart-heat-3, #d9ef8b);--_ex-chart-heat-4: var(--ex-chart-heat-4, #fee08b);--_ex-chart-heat-5: var(--ex-chart-heat-5, #fdae61);--_ex-chart-heat-6: var(--ex-chart-heat-6, #f46d43);--_ex-chart-heat-7: var(--ex-chart-heat-7, #d73027);--_ex-chart-heat-8: var(--ex-chart-heat-8, #a50026);--_ex-chart-diverge-0: var(--ex-chart-diverge-0, #b2182b);--_ex-chart-diverge-1: var(--ex-chart-diverge-1, #d6604d);--_ex-chart-diverge-2: var(--ex-chart-diverge-2, #f4a582);--_ex-chart-diverge-3: var(--ex-chart-diverge-3, #fddbc7);--_ex-chart-diverge-4: var(--ex-chart-diverge-4, #f7f7f7);--_ex-chart-diverge-5: var(--ex-chart-diverge-5, #d1e5f0);--_ex-chart-diverge-6: var(--ex-chart-diverge-6, #92c5de);--_ex-chart-diverge-7: var(--ex-chart-diverge-7, #4393c3);--_ex-chart-diverge-8: var(--ex-chart-diverge-8, #2166ac);--_ex-chart-surface-wall: var(--ex-chart-surface-wall, color-mix(in srgb, var(--_ex-chart-text) 3%, var(--_ex-chart-background)));--_ex-chart-surface-mesh: var(--ex-chart-surface-mesh, color-mix(in srgb, var(--_ex-chart-text) 35%, transparent));position:relative;box-sizing:border-box;font-family:var(--ex-font-family, system-ui, sans-serif);line-height:var(--ex-chart-line-height);color:var(--_ex-chart-text);background:var(--_ex-chart-background)}.ex-chart-colour-0{color:var(--_ex-chart-colour-0)}.ex-chart-colour-1{color:var(--_ex-chart-colour-1)}.ex-chart-colour-2{color:var(--_ex-chart-colour-2)}.ex-chart-colour-3{color:var(--_ex-chart-colour-3)}.ex-chart-colour-4{color:var(--_ex-chart-colour-4)}.ex-chart-colour-5{color:var(--_ex-chart-colour-5)}.ex-chart-colour-6{color:var(--_ex-chart-colour-6)}.ex-chart-colour-7{color:var(--_ex-chart-colour-7)}.ex-chart-colour-8{color:var(--_ex-chart-colour-8)}.ex-chart-colour-9{color:var(--_ex-chart-colour-9)}.ex-chart-toolbar,.ex-chart-filters{display:flex;flex-wrap:wrap;align-items:center;gap:.5em;padding-bottom:.25em}.ex-chart-button{font:inherit;color:inherit;background:transparent;border:1px solid var(--_ex-chart-axis);border-radius:3px;padding:0 .6em;cursor:pointer}.ex-chart-button:disabled{opacity:.45;cursor:default}.ex-chart-button[aria-expanded=true]{background:var(--_ex-chart-grid)}.ex-chart-filter{display:inline-flex;gap:.35em;align-items:center}.ex-chart-filter input,.ex-chart-filter select{font:inherit;color:inherit;background:var(--_ex-chart-background);border:1px solid var(--_ex-chart-axis)}.ex-chart-filter-error{color:var(--_ex-chart-error)}.ex-chart-stage{position:relative}.ex-chart-svg{display:block;overflow:visible}.ex-chart-downloads{display:inline-flex;gap:.25em}.ex-chart-file-background{fill:var(--_ex-chart-background)}.ex-chart-svg *{pointer-events:none}.ex-chart-svg .ex-chart-legend-entry,.ex-chart-svg .ex-chart-legend-entry *{pointer-events:auto}.ex-chart-hit{position:absolute;cursor:crosshair;touch-action:none}.ex-chart-plot{fill:none;stroke:var(--_ex-chart-axis);stroke-width:1}.ex-chart-grid{stroke:var(--_ex-chart-grid);stroke-width:1}.ex-chart-zero{stroke:var(--_ex-chart-axis);stroke-width:1}.ex-chart-break{fill:none;stroke:var(--_ex-chart-text);stroke-width:1.25}.ex-chart-tick{fill:var(--_ex-chart-muted)}.ex-chart-path{fill:none;stroke:currentColor;stroke-width:var(--_ex-chart-stroke);stroke-linejoin:round}.ex-chart-line-1 .ex-chart-path{stroke-dasharray:var(--_ex-chart-dash-1)}.ex-chart-line-2 .ex-chart-path{stroke-dasharray:var(--_ex-chart-dash-2)}.ex-chart-line-3 .ex-chart-path{stroke-dasharray:var(--_ex-chart-dash-3)}.ex-chart-interpolated .ex-chart-path{opacity:.75}.ex-chart-markers{fill:currentColor;stroke:currentColor;stroke-width:1}.ex-chart-markers-open{fill:var(--_ex-chart-background)}.ex-chart-rising{fill:var(--_ex-chart-background);stroke:var(--_ex-chart-rise);stroke-width:1}.ex-chart-falling{fill:var(--_ex-chart-fall);stroke:var(--_ex-chart-fall);stroke-width:1}.ex-chart-unchanged,.ex-chart-hlc,.ex-chart-whiskers{fill:none;stroke:currentColor;stroke-width:1}.ex-chart-interval-band{fill:currentColor;fill-opacity:.18;stroke:none}.ex-chart-extrapolated{fill:var(--_ex-chart-extrapolated)}.ex-chart-legend-entry{cursor:pointer}.ex-chart-legend-entry:focus{outline:none}.ex-chart-legend-entry:focus-visible .ex-chart-legend-hit{stroke:var(--ex-focus-outline, Highlight);stroke-width:1.5}.ex-chart-legend-hit{fill:transparent}.ex-chart-legend-name{fill:var(--_ex-chart-text)}.ex-chart-hidden{opacity:.38}.ex-chart-guide-line{stroke:var(--_ex-chart-guide);stroke-width:1}.ex-chart-dot{fill:currentColor;stroke:var(--_ex-chart-background);stroke-width:1.5}.ex-chart-band{fill:var(--_ex-chart-band)}.ex-chart-tooltip{position:absolute;z-index:1;pointer-events:none;white-space:nowrap;padding:0 .5em;background:var(--_ex-chart-background);border:1px solid var(--_ex-chart-axis);border-radius:3px;box-shadow:0 1px 4px color-mix(in srgb,var(--_ex-chart-text) 18%,transparent)}.ex-chart-tooltip-flip{transform:translate(-100%)}.ex-chart-tooltip-position{font-weight:600}.ex-chart-tooltip-line{display:flex;flex-wrap:wrap;align-items:center;gap:0 .4em;max-width:30em}.ex-chart-swatch{flex:none;overflow:visible}.ex-chart-tooltip-name{color:var(--_ex-chart-text)}.ex-chart-tooltip-value{color:var(--_ex-chart-text);font-variant-numeric:tabular-nums;margin-left:auto}.ex-chart-tooltip-note,.ex-chart-tooltip-more{color:var(--_ex-chart-muted)}.ex-chart-tooltip-note{white-space:normal}.ex-chart-menu-backdrop{position:fixed;inset:0;z-index:2}.ex-chart-menu{position:fixed;z-index:3;display:flex;flex-direction:column;min-width:10em;padding:.25em 0;background:var(--_ex-chart-background);border:1px solid var(--_ex-chart-axis);border-radius:3px;box-shadow:0 2px 8px color-mix(in srgb,var(--_ex-chart-text) 22%,transparent)}.ex-chart-menu:focus{outline:none}.ex-chart-menu-item{font:inherit;color:inherit;background:transparent;border:0;padding:.15em 1em;text-align:left;cursor:pointer}.ex-chart-menu-item:hover:not(:disabled),.ex-chart-menu-item:focus-visible{background:var(--_ex-chart-grid);outline:none}.ex-chart-menu-item:disabled{opacity:.45;cursor:default}.ex-chart-notes{margin:.25em 0 0;padding-left:1.2em;color:var(--_ex-chart-muted)}.ex-chart-script-notice{margin:.25em 0 0;color:var(--_ex-chart-error)}.ex-chart [data-ex-notice]{box-sizing:border-box;padding:0 .5em;color:var(--_ex-chart-error);outline:1px solid var(--_ex-chart-error);outline-offset:-1px;user-select:text}.ex-chart-table-wrap{max-height:24em;overflow:auto;margin-top:.5em}.ex-chart-table{border-collapse:collapse;font-variant-numeric:tabular-nums}.ex-chart-table caption{text-align:left;font-weight:600}.ex-chart-table th,.ex-chart-table td{border:1px solid var(--_ex-chart-grid);padding:0 .5em;text-align:right}.ex-chart-table thead th,.ex-chart-table tbody th{text-align:left}.ex-chart-surface-row{display:flex;flex-wrap:wrap;gap:1em;align-items:flex-start}.ex-chart-surface-box{position:relative;cursor:grab;touch-action:none}.ex-chart-surface-box:active{cursor:grabbing}.ex-chart-surface-box:focus{outline:none}.ex-chart-surface-box:focus-visible{outline:2px solid var(--ex-focus-outline, Highlight);outline-offset:1px}.ex-chart-surface-svg{display:block;overflow:visible;pointer-events:none}.ex-chart-surface-wall{fill:var(--_ex-chart-surface-wall);stroke:var(--_ex-chart-grid);stroke-width:1}.ex-chart-surface-grid{stroke:var(--_ex-chart-grid);stroke-width:1}.ex-chart-surface-face{stroke:var(--_ex-chart-surface-mesh);stroke-width:.6}.ex-chart-surface-point{fill:var(--_ex-chart-text);opacity:.55}.ex-chart-surface-slice polyline{fill:none;stroke:var(--_ex-chart-text);stroke-width:2.5;stroke-linejoin:round}.ex-chart-surface-label{fill:var(--_ex-chart-muted);stroke:var(--_ex-chart-background);stroke-width:3px;paint-order:stroke;stroke-linejoin:round}.ex-chart-surface-title{fill:var(--_ex-chart-text);font-weight:600}.ex-chart-surface-bar-band{stroke:none}.ex-chart-key-title{fill:var(--_ex-chart-text)}.ex-chart-edges{fill:none;stroke:currentColor;stroke-opacity:.45;stroke-width:1}.ex-chart-key-band{stroke:none}.ex-chart-key-frame{fill:none;stroke:var(--_ex-chart-axis);stroke-width:1}.ex-chart-key-size{fill:none;stroke:var(--_ex-chart-text);stroke-width:1}.ex-chart-surface-bar-frame{fill:none;stroke:var(--_ex-chart-surface-mesh);stroke-width:1}.ex-chart-surface-bar-tick{stroke:var(--_ex-chart-muted);stroke-width:1}.ex-chart-heat-0{fill:var(--_ex-chart-heat-0)}.ex-chart-heat-1{fill:var(--_ex-chart-heat-1)}.ex-chart-heat-2{fill:var(--_ex-chart-heat-2)}.ex-chart-heat-3{fill:var(--_ex-chart-heat-3)}.ex-chart-heat-4{fill:var(--_ex-chart-heat-4)}.ex-chart-heat-5{fill:var(--_ex-chart-heat-5)}.ex-chart-heat-6{fill:var(--_ex-chart-heat-6)}.ex-chart-heat-7{fill:var(--_ex-chart-heat-7)}.ex-chart-heat-8{fill:var(--_ex-chart-heat-8)}.ex-chart-diverge-0{fill:var(--_ex-chart-diverge-0)}.ex-chart-diverge-1{fill:var(--_ex-chart-diverge-1)}.ex-chart-diverge-2{fill:var(--_ex-chart-diverge-2)}.ex-chart-diverge-3{fill:var(--_ex-chart-diverge-3)}.ex-chart-diverge-4{fill:var(--_ex-chart-diverge-4)}.ex-chart-diverge-5{fill:var(--_ex-chart-diverge-5)}.ex-chart-diverge-6{fill:var(--_ex-chart-diverge-6)}.ex-chart-diverge-7{fill:var(--_ex-chart-diverge-7)}.ex-chart-diverge-8{fill:var(--_ex-chart-diverge-8)}\\n[data-ex-stylesheet=\\\"ex-chart.css\\\"]{display:block!important}[data-ex-stylesheet=\\\"ex-chart.css\\\"][data-ex-stamp=\\\"26a000a0c2197a34ec908d2b970d4aa57abbd522f53134cb2eab0ef21d694614\\\"]{display:none!important}\";\n", "// The files a chart saves (ADR-0252, ADR-0282), written on the click and never during a drawing: CSV of\n// the visible series in the range shown, the SVG of the drawing on screen, or that SVG painted to PNG at\n// the screen's Device Pixel. The SVG is written by the same part writers as the screen, so a file cannot\n// drift from it, and carries the stylesheet inside it, since a file has no page to take it from.\nimport type { ChartScene } from '../scene';\nimport { drawingParts } from './chart-drawing';\nimport { stylesheetText } from './shipped-stylesheet';\nimport { element, escapeText, n } from './svg-markup';\n\n/** The formats a chart saves as. */\nexport type ChartFileFormat = 'csv' | 'svg' | 'png';\n\n/** The media type a format is saved as. */\nexport function mediaType(format: ChartFileFormat): string {\n return format === 'csv' ? 'text/csv' : format === 'svg' ? 'image/svg+xml' : 'image/png';\n}\n\n// The characters no file system takes in a name: Windows' set, which holds every other's.\n// oxlint-disable-next-line no-control-regex -- the control characters are what it matches: a name cannot hold them\nconst unsafe = /[\\u0000-\\u001f\\u007f-\\u009f/\\\\:*?\"<>|]/g;\n\n/** The file name: the chart's own, or its title's, made safe for a file system, with the format's extension. */\nexport function fileName(name: string | undefined, title: string | undefined, format: ChartFileFormat): string {\n const stem = name !== undefined && name.trim() !== '' ? name : title !== undefined && title.trim() !== '' ? title : 'chart';\n // A file system drops trailing dots, so \".\" or \"..\" would name no file at all.\n const safe = stem.trim().replace(unsafe, '_').replace(/[. ]+$/, '');\n return `${safe === '' ? 'chart' : safe}.${format}`;\n}\n\n/** The names of the Visual Tokens the stylesheet reads, without their prefix (ADR-0282). */\nexport const tokenNames: readonly string[] = Object.freeze([...new Set([...stylesheetText.matchAll(/--_ex-chart-([a-z0-9-]+):/g)].map(m => m[1]).filter(\n (name): name is string => name !== undefined))]);\n\n// A value that would end the declaration is left out, and the stylesheet's default stands for it.\nconst declarable = (value: string): boolean => value !== '' && !/[;{}<>]/.test(value);\n\n/**\n * The style a saved file's root carries: each token's value as the screen has it, then the font, so the\n * file has the theme's colours (ADR-0282). `values` are the tokens' values in {@link tokenNames}' order,\n * then the root's font family.\n */\nexport function themeStyle(values: readonly string[]): string {\n let style = '';\n tokenNames.forEach((name, i) => {\n const value = values[i];\n if (value !== undefined && declarable(value)) {\n style += `--ex-chart-${name}:${value};`;\n }\n });\n const font = values[tokenNames.length];\n if (font !== undefined && declarable(font)) {\n style += `font-family:${font};`;\n }\n return style;\n}\n\n/** The values of the chart's Visual Tokens on screen, and its font family, read from its root on the click. */\nexport function screenTheme(root: Element): string {\n const style = getComputedStyle(root);\n return themeStyle([...tokenNames.map(name => style.getPropertyValue(`--_ex-chart-${name}`).trim()), style.fontFamily]);\n}\n\n/** What a saved SVG is drawn from. */\nexport interface FileDrawing {\n readonly scene: ChartScene;\n readonly width: number;\n readonly height: number;\n readonly fontSize: number;\n readonly lineHeight: number;\n readonly angle: number;\n readonly summary: string;\n readonly theme: string;\n}\n\n// The stylesheet as an SVG's style element holds it: inside CDATA, so a selector's > stays CSS.\nconst styleMarkup = (): string => `<![CDATA[${stylesheetText.replaceAll(']]>', ']]]]><![CDATA[>')}]]>`;\n\n/** The SVG text of the drawing as it stands, without the pointer's guide, tooltip or band. */\nexport function svgFile(d: FileDrawing): string {\n const content = `<style>${styleMarkup()}</style>`\n + element('title', [], escapeText(d.summary))\n // A file has no page behind it: the background is drawn, so a PNG is not transparent.\n + element('rect', [['class', 'ex-chart-file-background'], ['width', n(d.width)], ['height', n(d.height)]])\n + drawingParts(d.scene, d.lineHeight, d.angle).map(p => p.markup).join('');\n return '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\\n' + element('svg', [\n ['xmlns', 'http://www.w3.org/2000/svg'], ['class', 'ex-chart ex-chart-svg ex-chart-file'], ['width', n(d.width)], ['height', n(d.height)],\n ['viewBox', `0 0 ${n(d.width)} ${n(d.height)}`], ['style', `font-size:${n(d.fontSize)}px;--ex-chart-line-height:${n(d.lineHeight)}px;${d.theme}`],\n ], content);\n}\n\n/** Saves bytes under a file name, through a Blob and an object URL revoked once the save has started: one click saves. */\nexport function save(name: string, type: string, data: BlobPart): void {\n const url = URL.createObjectURL(new Blob([data], { type }));\n const link = document.createElement('a');\n link.href = url;\n link.download = name;\n link.style.display = 'none';\n document.body.appendChild(link);\n try {\n link.click();\n } finally {\n link.remove();\n setTimeout(() => { URL.revokeObjectURL(url); }, 0);\n }\n}\n\n/**\n * Paints an SVG to PNG. The canvas is the drawing's size at the screen's Device Pixel, so a PNG taken at\n * 150% is drawn at 150% and not scaled up from 100% (ADR-0090); the browser lays out the text in the fonts\n * the screen shows.\n */\nexport async function paintPng(svgText: string, width: number, height: number): Promise<Blob> {\n const scale = window.devicePixelRatio;\n if (!(scale > 0)) {\n throw new RangeError(`The screen's Device Pixel is ${String(scale)} CSS pixels, so a PNG cannot be painted at it.`);\n }\n const url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }));\n try {\n const image = new Image();\n image.decoding = 'sync';\n await new Promise<void>((resolve, reject) => {\n image.addEventListener('load', () => { resolve(); }, { once: true });\n image.addEventListener('error', () => { reject(new Error('The chart\\'s SVG could not be painted.')); }, { once: true });\n image.src = url;\n });\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(width * scale);\n canvas.height = Math.round(height * scale);\n const context = canvas.getContext('2d');\n if (context === null) {\n throw new Error('The browser gave no canvas to paint the chart\\'s PNG on.');\n }\n context.scale(canvas.width / width, canvas.height / height);\n context.drawImage(image, 0, 0, width, height);\n return await new Promise<Blob>((resolve, reject) => {\n canvas.toBlob(blob => {\n if (blob === null) {\n reject(new Error('The chart\\'s PNG could not be encoded.'));\n } else {\n resolve(blob);\n }\n }, 'image/png');\n });\n } finally {\n URL.revokeObjectURL(url);\n }\n}\n", "// The words ExChart's own markup shows, by id, with their English (ADR-0370 section 10). A Consumer\n// replaces any of them through a function from id to text, answering undefined to keep the English;\n// ExChart's Japanese is bundled and chosen in one line, `label: japaneseChartWords`, never by the locale.\n// A word with {0} (and {1}) is a template, filled as .NET's string.Format fills one. The sentences the\n// layout writes (Notes, the tooltip's notes, the summary) are the engine's, in English, as C#'s are.\n\n/** The Consumer's word for an id, or `undefined` to keep the English. */\nexport type ChartLabel = (id: string) => string | undefined;\n\n/** The ids of the words ExChart's built-in markup shows. A command's id is its command id (`chartCommandIds`). */\nexport const chartWordIds = Object.freeze({\n /** Opens or closes Chart Filters (ADR-0273): `Chart Filters`. */\n filters: 'exchart.filters',\n /** Returns the range to the whole axis: `Reset range`. */\n resetRange: 'exchart.reset-range',\n /** Shows the chart's data as a table (ADR-0275): `View as table`. */\n table: 'exchart.table',\n /** The menu's word for the table while it is shown: `Hide table`. */\n hideTable: 'exchart.table.hide',\n /** The toolbar's CSV button (ADR-0282): `CSV`. */\n downloadCsv: 'exchart.download.csv',\n /** The toolbar's SVG button: `SVG`. */\n downloadSvg: 'exchart.download.svg',\n /** The toolbar's PNG button: `PNG`. */\n downloadPng: 'exchart.download.png',\n /** The menu's CSV command: `Download CSV`. */\n menuDownloadCsv: 'exchart.menu.download.csv',\n /** The menu's SVG command: `Download SVG`. */\n menuDownloadSvg: 'exchart.menu.download.svg',\n /** The menu's PNG command: `Download PNG`. */\n menuDownloadPng: 'exchart.menu.download.png',\n /** The downloads' group name: `Download`. */\n downloads: 'exchart.downloads',\n /** The chart's name where it has no title: `Chart`. */\n chart: 'exchart.chart',\n /** The table's caption where the chart has no title: `Chart data`. */\n chartData: 'exchart.chart-data',\n /** Chart Filters' start: `From`. */\n from: 'exchart.filters.from',\n /** Chart Filters' end: `To`. */\n to: 'exchart.filters.to',\n /** Applies the typed range: `Apply`. */\n apply: 'exchart.filters.apply',\n /** The axis switch: `Axis`. */\n axis: 'exchart.filters.axis',\n /** A proportional axis: `Proportional`. */\n proportional: 'exchart.filters.proportional',\n /** An axis of categories: `Categories`. */\n categories: 'exchart.filters.categories',\n /** What a value on a date axis looks like: `yyyy-MM-dd`. */\n dateHint: 'exchart.filters.hint.date',\n /** On a category axis: `category`. */\n categoryHint: 'exchart.filters.hint.category',\n /** On a number axis: `number`. */\n numberHint: 'exchart.filters.hint.number',\n /** A typed value the axis does not hold, `{0}` the text and `{1}` what the axis holds: `\u201C{0}\u201D is not {1} on this axis.` */\n notOnAxis: 'exchart.filters.not-on-axis',\n /** What a date axis holds: `a date (yyyy-MM-dd)`. */\n aDate: 'exchart.filters.a-date',\n /** What a category axis holds: `a category`. */\n aCategory: 'exchart.filters.a-category',\n /** What a number axis holds: `a number`. */\n aNumber: 'exchart.filters.a-number',\n /** A typed range backwards: `From is after To.` */\n fromAfterTo: 'exchart.filters.from-after-to',\n /** Why a chart its Chart Source thinned saves no CSV and shows no table (ADR-0344). */\n thinnedAtSource: 'exchart.thinned-at-source',\n /** The tooltip's count of the series it does not list, one: `and 1 more series`. */\n oneMoreSeries: 'exchart.tooltip.one-more',\n /** The same for more than one, `{0}` the count: `and {0} more series`. */\n moreSeries: 'exchart.tooltip.more',\n /** The notice of a stylesheet of another version (ADR-0123). */\n stylesheetNotice: 'exchart.notice.stylesheet',\n /** A 3D surface's button that returns its view (ADR-0274): `Reset view`. */\n resetView: 'exchart.surface.reset-view',\n /** A surface's name where it has no title: `Surface`. */\n surface: 'exchart.surface',\n /** A surface's table's caption where it has no title: `Surface data`. */\n surfaceData: 'exchart.surface.data',\n /** What a surface's box is announced as: `3D surface`. */\n surfaceRole: 'exchart.surface.role',\n /** The values' name where the surface gives none: `Value`. */\n surfaceValue: 'exchart.surface.value',\n /** The tooltip's note on a value the data holds, on a surface the Consumer interpolated (ADR-0257): `quoted`. */\n quoted: 'exchart.surface.quoted',\n /** The note on an interpolated value, `{0}` the method: `interpolated, {0}`. */\n interpolated: 'exchart.surface.interpolated',\n /** A slice a grid does not hold, `{0}` the axis and `{1}` the value: `No slice at {0} {1}: this surface has no such value.` */\n noSliceOnGrid: 'exchart.surface.no-slice.grid',\n /** A slice no triangle of a mesh crosses: `No slice at {0} {1}: no triangle of the mesh crosses there.` */\n noSliceOnMesh: 'exchart.surface.no-slice.mesh',\n});\n\nconst english: Readonly<Record<string, string>> = {\n 'exchart.filters': 'Chart Filters',\n 'exchart.reset-range': 'Reset range',\n 'exchart.table': 'View as table',\n 'exchart.table.hide': 'Hide table',\n 'exchart.download.csv': 'CSV',\n 'exchart.download.svg': 'SVG',\n 'exchart.download.png': 'PNG',\n 'exchart.menu.download.csv': 'Download CSV',\n 'exchart.menu.download.svg': 'Download SVG',\n 'exchart.menu.download.png': 'Download PNG',\n 'exchart.downloads': 'Download',\n 'exchart.chart': 'Chart',\n 'exchart.chart-data': 'Chart data',\n 'exchart.filters.from': 'From',\n 'exchart.filters.to': 'To',\n 'exchart.filters.apply': 'Apply',\n 'exchart.filters.axis': 'Axis',\n 'exchart.filters.proportional': 'Proportional',\n 'exchart.filters.categories': 'Categories',\n 'exchart.filters.hint.date': 'yyyy-MM-dd',\n 'exchart.filters.hint.category': 'category',\n 'exchart.filters.hint.number': 'number',\n 'exchart.filters.not-on-axis': '\u201C{0}\u201D is not {1} on this axis.',\n 'exchart.filters.a-date': 'a date (yyyy-MM-dd)',\n 'exchart.filters.a-category': 'a category',\n 'exchart.filters.a-number': 'a number',\n 'exchart.filters.from-after-to': 'From is after To.',\n 'exchart.thinned-at-source': 'The rows are where the data lives: this chart holds only the points drawn, each pixel\\'s first, last, lowest and highest, so it saves no CSV and shows no table.',\n 'exchart.tooltip.one-more': 'and 1 more series',\n 'exchart.tooltip.more': 'and {0} more series',\n 'exchart.notice.stylesheet': 'This page holds another version\\'s stylesheet. Reload the page.',\n 'exchart.surface.reset-view': 'Reset view',\n 'exchart.surface': 'Surface',\n 'exchart.surface.data': 'Surface data',\n 'exchart.surface.role': '3D surface',\n 'exchart.surface.value': 'Value',\n 'exchart.surface.quoted': 'quoted',\n 'exchart.surface.interpolated': 'interpolated, {0}',\n 'exchart.surface.no-slice.grid': 'No slice at {0} {1}: this surface has no such value.',\n 'exchart.surface.no-slice.mesh': 'No slice at {0} {1}: no triangle of the mesh crosses there.',\n};\n\n// Excel's Japanese edition's words where Excel shows the same thing (\u30B0\u30E9\u30D5 \u30D5\u30A3\u30EB\u30BF\u30FC, \u8868), the family's\n// own elsewhere.\nconst japanese: Readonly<Record<string, string>> = {\n 'exchart.filters': '\u30B0\u30E9\u30D5 \u30D5\u30A3\u30EB\u30BF\u30FC',\n 'exchart.reset-range': '\u7BC4\u56F2\u3092\u30EA\u30BB\u30C3\u30C8',\n 'exchart.table': '\u8868\u3068\u3057\u3066\u8868\u793A',\n 'exchart.table.hide': '\u8868\u3092\u96A0\u3059',\n 'exchart.download.csv': 'CSV',\n 'exchart.download.svg': 'SVG',\n 'exchart.download.png': 'PNG',\n 'exchart.menu.download.csv': 'CSV \u3092\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9',\n 'exchart.menu.download.svg': 'SVG \u3092\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9',\n 'exchart.menu.download.png': 'PNG \u3092\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9',\n 'exchart.downloads': '\u30C0\u30A6\u30F3\u30ED\u30FC\u30C9',\n 'exchart.chart': '\u30B0\u30E9\u30D5',\n 'exchart.chart-data': '\u30B0\u30E9\u30D5\u306E\u30C7\u30FC\u30BF',\n 'exchart.filters.from': '\u958B\u59CB',\n 'exchart.filters.to': '\u7D42\u4E86',\n 'exchart.filters.apply': '\u9069\u7528',\n 'exchart.filters.axis': '\u8EF8',\n 'exchart.filters.proportional': '\u6BD4\u4F8B',\n 'exchart.filters.categories': '\u9805\u76EE',\n 'exchart.filters.hint.date': 'yyyy-MM-dd',\n 'exchart.filters.hint.category': '\u9805\u76EE',\n 'exchart.filters.hint.number': '\u6570\u5024',\n 'exchart.filters.not-on-axis': '\u300C{0}\u300D\u306F\u3053\u306E\u8EF8\u306E{1}\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002',\n 'exchart.filters.a-date': '\u65E5\u4ED8 (yyyy-MM-dd)',\n 'exchart.filters.a-category': '\u9805\u76EE',\n 'exchart.filters.a-number': '\u6570\u5024',\n 'exchart.filters.from-after-to': '\u958B\u59CB\u304C\u7D42\u4E86\u3088\u308A\u5F8C\u3067\u3059\u3002',\n 'exchart.thinned-at-source': '\u30C7\u30FC\u30BF\u306E\u884C\u306F\u30C7\u30FC\u30BF\u5143\u306B\u3042\u308A\u307E\u3059\u3002\u3053\u306E\u30B0\u30E9\u30D5\u306F\u63CF\u3044\u305F\u70B9 (\u5404\u30D4\u30AF\u30BB\u30EB\u306E\u6700\u521D\u3001\u6700\u5F8C\u3001\u6700\u5C0F\u3001\u6700\u5927) \u3060\u3051\u3092\u6301\u3064\u305F\u3081\u3001CSV \u306E\u4FDD\u5B58\u3082\u8868\u306E\u8868\u793A\u3082\u3057\u307E\u305B\u3093\u3002',\n 'exchart.tooltip.one-more': '\u307B\u304B 1 \u7CFB\u5217',\n 'exchart.tooltip.more': '\u307B\u304B {0} \u7CFB\u5217',\n 'exchart.notice.stylesheet': '\u3053\u306E\u30DA\u30FC\u30B8\u306B\u306F\u5225\u306E\u30D0\u30FC\u30B8\u30E7\u30F3\u306E\u30B9\u30BF\u30A4\u30EB\u30B7\u30FC\u30C8\u304C\u3042\u308A\u307E\u3059\u3002\u30DA\u30FC\u30B8\u3092\u518D\u8AAD\u307F\u8FBC\u307F\u3057\u3066\u304F\u3060\u3055\u3044\u3002',\n 'exchart.surface.reset-view': '\u8868\u793A\u3092\u30EA\u30BB\u30C3\u30C8',\n 'exchart.surface': '\u30B5\u30FC\u30D5\u30A7\u30B9',\n 'exchart.surface.data': '\u30B5\u30FC\u30D5\u30A7\u30B9\u306E\u30C7\u30FC\u30BF',\n 'exchart.surface.role': '3D \u30B5\u30FC\u30D5\u30A7\u30B9',\n 'exchart.surface.value': '\u5024',\n 'exchart.surface.quoted': '\u6C17\u914D\u5024',\n 'exchart.surface.interpolated': '\u88DC\u9593 ({0})',\n 'exchart.surface.no-slice.grid': '{0} {1} \u306E\u65AD\u9762\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u3053\u306E\u30B5\u30FC\u30D5\u30A7\u30B9\u306B\u305D\u306E\u5024\u306F\u3042\u308A\u307E\u305B\u3093\u3002',\n 'exchart.surface.no-slice.mesh': '{0} {1} \u306E\u65AD\u9762\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30E1\u30C3\u30B7\u30E5\u306E\u3069\u306E\u4E09\u89D2\u5F62\u3082\u305D\u3053\u3092\u901A\u308A\u307E\u305B\u3093\u3002',\n};\n\n/** ExChart's Japanese: `label: japaneseChartWords`. A Consumer's own function may fall back to it. */\nexport const japaneseChartWords: ChartLabel = id => japanese[id];\n\n/** Every id of ExChart's words, in no particular order. */\nexport const chartWordIdList: readonly string[] = Object.freeze(Object.keys(english));\n\n/** The word for an id: the Consumer's, the English where it says nothing, and the id itself where neither\n * knows it \u2014 an id painted is a missing word seen, never a blank. Each `{i}` is filled with `args[i]`. */\nexport function chartWord(id: string, label: ChartLabel | undefined, ...args: readonly string[]): string {\n const template = label?.(id) ?? english[id] ?? id;\n return template.replace(/\\{(\\d+)\\}/g, (_whole, index: string) => {\n const arg = args[Number(index)];\n if (arg === undefined) {\n throw new Error(`Internal: the word ${id} names {${index}}, which it was not given.`);\n }\n return arg;\n });\n}\n", "// Chart Filters' range as text (ADR-0273): typed in the axis' own values \u2014 a date as yyyy-MM-dd, a\n// category by its label, a number invariantly or by a named position \u2014 and written back the same way.\n// A value that does not read as one is said, never guessed (spine rule 1).\nimport type { ChartAxis } from '../model';\nimport { dateOf, dayNumber, isoDate, wholeDay } from '../day-numbers';\nimport { roundTrip } from '../invariant-text';\nimport { elementAt, unreachable } from '../must';\n\n/** What a typed end reads as: the axis' own end where nothing was typed, a position, or nothing it holds. */\nexport type TypedEnd = { readonly read: true; readonly position: number | null } | { readonly read: false };\n\nconst unread: TypedEnd = Object.freeze({ read: false });\n\n// .NET's OrdinalIgnoreCase: each UTF-16 unit by its simple upper case, so no unit becomes two.\nfunction upper(text: string): string {\n return text.split('').map(c => {\n const u = c.toUpperCase();\n return u.length === c.length ? u : c;\n }).join('');\n}\n\n// .NET's NumberStyles.Float under the invariant culture, past the trimming already done: a sign, digits\n// with one point, and an exponent; no group separator.\nconst floatText = /^[+-]?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/;\n\nconst dateText = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n/** Reads `text` as a position of `axis`; empty or blank text is the axis' own end. */\nexport function readEnd(axis: ChartAxis, text: string | null): TypedEnd {\n if (text === null || text.trim() === '') {\n return { read: true, position: null };\n }\n const t = text.trim();\n switch (axis.values) {\n case 'dates': {\n const m = dateText.exec(t);\n if (m === null) {\n return unread;\n }\n const [year, month, day] = [Number(m[1]), Number(m[2]), Number(m[3])];\n if (year < 1 || month < 1 || month > 12 || day < 1) {\n return unread;\n }\n const position = dayNumber(year, month, day);\n // A day past its month's end is no date, as DateOnly.TryParseExact refuses 2026-02-30.\n return dateOf(position).day === day ? { read: true, position } : unread;\n }\n case 'labels': {\n let i = axis.labels.indexOf(t);\n if (i < 0) {\n i = axis.labels.findIndex(l => upper(l) === upper(t));\n }\n return i >= 0 ? { read: true, position: i } : unread;\n }\n case 'numbers': {\n const named = axis.named.find(([, label]) => upper(label) === upper(t));\n if (named !== undefined) {\n return { read: true, position: named[0] };\n }\n if (!floatText.test(t)) {\n return unread;\n }\n const value = Number(t);\n return Number.isFinite(value) ? { read: true, position: value } : unread;\n }\n default:\n return unreachable(axis.values);\n }\n}\n\n/** A position written as Chart Filters shows it: a date as yyyy-MM-dd, a category's label, a number round-trip. */\nexport function writeEnd(axis: ChartAxis, position: number): string {\n if (axis.values === 'dates') {\n return isoDate(dateOf(wholeDay(position)));\n }\n if (axis.values === 'labels' && position >= 0 && position < axis.labels.length) {\n return elementAt(axis.labels, Math.trunc(position));\n }\n return roundTrip(position);\n}\n", "import { ChartElement, type ChartOptions } from './chart-element';\nimport type { ChartFileFormat } from './chart-files';\n\n/** A chart drawn into an element, handed back by {@link createChart}. */\nexport interface ChartHandle {\n /** Takes the options again, whole: what did not change costs nothing, and a part of the drawing that did\n * not change is not touched (ADR-0252). */\n update(options: ChartOptions): void;\n /** Stops the chart: it hears nothing more and empties its element. */\n destroy(): void;\n /**\n * Saves the chart as a file, as the user sees it (ADR-0282): `csv`, the visible series in the range shown;\n * `svg`, the drawing; `png`, that drawing painted at the screen's Device Pixel. One call is one save. False\n * for a CSV of a chart its Chart Source thinned (ADR-0344), and once the chart is destroyed.\n */\n download(format: ChartFileFormat): Promise<boolean>;\n /**\n * Returns the range the user narrowed to the whole without raising `onRangeChanged`: for a Framework Adapter\n * whose host learns only after the release that the data was replaced before it (ADR-0272, spine rule 6).\n */\n dropRange(): void;\n}\n\n/**\n * Draws a chart into `element`, which becomes its instance root (ADR-0370 section 1): the chart owns\n * everything inside it, and the element's own class and style it writes. A Framework Adapter renders the\n * element and hands the chart its props; nothing here assumes React's lifecycle or Blazor's.\n */\nexport function createChart(element: HTMLElement, options: ChartOptions): ChartHandle {\n const chart = new ChartElement(element, options);\n return Object.freeze({\n update: (next: ChartOptions) => { chart.update(next); },\n destroy: () => { chart.destroy(); },\n download: (format: ChartFileFormat) => chart.download(format),\n dropRange: () => { chart.dropRange(); },\n });\n}\n", "// A 3D surface in the DOM (ADR-0274, ADR-0370 section 1): ExChart's Script Core builds the elements inside\n// the instance root to the DOM contract ExSurface.razor writes, so ex-chart.css and layer 3 read both alike.\n// It is turned by dragging or with the arrow keys, zoomed with the wheel or + and -, and panned with Shift or\n// the right button; the tooltip names the point nearest the pointer, and a click on a tenor or a strike draws\n// that slice as a 2D chart beside the surface, where its values are read exactly.\n//\n// The Razor component needed a script entry to project the surface while it turns (ADR-0255); here the\n// projection runs where the pointer is heard, with no round trip. It holds no view state of the Consumer's\n// (ADR-0272): the view and the slice are raised when a gesture ends and taken back as options, in the data's\n// terms. A gesture begun against one surface is ended unreported when another is drawn (spine rule 6).\nimport { densityText, type GridDensity } from '@ex-grid/core';\nimport type { ChartDefinition } from '../definition';\nimport { roundToDigits } from '../numbers';\nimport { defaultSurfaceView, SurfaceDefinition, type SurfaceSlice, type SurfaceView } from '../surface';\nimport { surfaceMesh, surfaceSlicePath, surfaceSummary, type SurfaceMesh, type SurfaceMeshPoint } from '../surface-mesh';\nimport { ChartElement } from './chart-element';\nimport { fileName, mediaType, paintPng, save, type ChartFileFormat } from './chart-files';\nimport { chartWord, chartWordIds, type ChartLabel } from './chart-words';\nimport { stylesheetName, stylesheetStamp } from './shipped-stylesheet';\nimport { clamp, drawSurface, sliceAxisAt, type DrawnSurfacePoint, type SurfaceDrawing } from './surface-drawing';\nimport { n } from './svg-markup';\n\n/** What a 3D surface is drawn from, and what it raises. */\nexport interface SurfaceOptions {\n /** The surface, in the data's terms. */\n readonly definition: SurfaceDefinition;\n /** Its width in CSS pixels: 640 when not given. Geometry is an option, never only a stylesheet value (ADR-0027). */\n readonly width?: number;\n /** Its height in CSS pixels, which the slice's chart beside it shares: 420 when not given. */\n readonly height?: number;\n /** The width of the slice's chart, in CSS pixels: 420 when not given. */\n readonly sliceWidth?: number;\n /** The density the font size is resolved from, as a grid's is (ADR-0028): `standard` when not given. */\n readonly density?: GridDensity;\n /** The surface's title, which opens its accessible summary. */\n readonly title?: string;\n /** A sentence the accessible summary ends with. */\n readonly description?: string;\n /** The view, taken back from `onViewChanged`; `null` or not given is the default view. */\n readonly view?: SurfaceView | null;\n /** Raised when the user ends a turn, a zoom or a pan, with the view it left (ADR-0272). */\n readonly onViewChanged?: (view: SurfaceView) => void;\n /** The slice drawn beside the surface, taken back from `onSliceChanged`; `null` or not given draws none. */\n readonly slice?: SurfaceSlice | null;\n /** Raised when the user clicks a tenor or a strike, with the slice it names (ADR-0274). */\n readonly onSliceChanged?: (slice: SurfaceSlice) => void;\n /** The name a saved file takes, without its extension; the title when not set, then `surface` (ADR-0282). */\n readonly fileName?: string;\n /** The Consumer's words for ExChart's own (ADR-0370 section 10); `japaneseChartWords` for Japanese. */\n readonly label?: ChartLabel;\n}\n\n/** How far, in CSS pixels, the pointer may be from a point and still read it. */\nconst reach = 32;\n\n/** How far a press may move and still be a click, not a turn. */\nconst clickSlop = 4;\n\n/** How far a drag turns the surface: a whole turn for a drag the box's height, either way (as Plotly's turntable and three.js's OrbitControls do). */\nconst turnPerHeight = 360;\n\n/** How far one wheel step of 100 pixels zooms; the wheel zooms in proportion to how far it moved. */\nconst wheelZoom = Math.log(1.1) / 100;\n\nconst svgNs = 'http://www.w3.org/2000/svg';\n\n/** How many raised views wait to be taken back before the oldest is forgotten. */\nconst raisedKept = 64;\n\ninterface Drag {\n readonly id: number;\n readonly x: number;\n readonly y: number;\n readonly view: SurfaceView;\n readonly pan: boolean;\n readonly version: number;\n moved: boolean;\n}\n\ninterface Tip {\n readonly k: number;\n readonly x: number;\n readonly y: number;\n}\n\n/** An angle brought into (-180, 180]. */\nfunction turn(degrees: number): number {\n const d = ((degrees % 360) + 360) % 360;\n return d > 180 ? d - 360 : d;\n}\n\nconst sameView = (a: SurfaceView, b: SurfaceView): boolean =>\n a.yaw === b.yaw && a.pitch === b.pitch && a.zoom === b.zoom && a.panX === b.panX && a.panY === b.panY;\n\nconst sameSlice = (a: SurfaceSlice | null, b: SurfaceSlice | null): boolean =>\n a === b || (a !== null && b !== null && a.axis === b.axis && a.value === b.value);\n\n// A view as it is raised: to a hundredth of a degree and a ten-thousandth of the zoom and the box, as the\n// Razor component rounds it, so a view taken back and raised again is the same view.\nconst rounded = (v: SurfaceView): SurfaceView => Object.freeze({\n yaw: roundToDigits(v.yaw, 2), pitch: roundToDigits(v.pitch, 2), zoom: roundToDigits(v.zoom, 4),\n panX: roundToDigits(v.panX, 4), panY: roundToDigits(v.panY, 4),\n});\n\nconst sameTakenView = (a: SurfaceView | null, b: SurfaceView | null): boolean =>\n a === b || (a !== null && b !== null && sameView(a, b));\n\nconst nameOr = (title: string, fallback: string): string => (title.trim() === '' ? fallback : title);\n\nconst blank = (text: string | undefined): text is undefined => text === undefined || text.trim() === '';\n\n/** A 3D surface drawn into an element, which becomes its instance root. */\nexport class SurfaceElement {\n readonly #root: HTMLElement;\n #options: SurfaceOptions;\n #destroyed = false;\n\n // What the user changed, as last taken from an option or a gesture.\n #view: SurfaceView = defaultSurfaceView;\n #held: SurfaceView = defaultSurfaceView;\n // The views raised and not yet taken back, oldest first: an echo of any of them is not the Consumer's own\n // view, however late it arrives (spine rule 6).\n #raised: SurfaceView[] = [];\n #slice: SurfaceSlice | null = null;\n #taken: { readonly view: SurfaceView | null; readonly slice: SurfaceSlice | null } | undefined;\n\n // The mesh and what it was built from.\n #builtFrom: readonly unknown[] = [];\n #mesh: SurfaceMesh | undefined;\n #summary = '';\n #version = 0;\n #slicePath: readonly (readonly SurfaceMeshPoint[])[] | null = null;\n #sliceChart: ChartDefinition | undefined;\n #sliceNote: string | null = null;\n #sliceFrom: readonly unknown[] = [];\n\n // The pointer.\n #drawing: SurfaceDrawing | null = null;\n #drawnFrom: readonly unknown[] = [];\n #drag: Drag | null = null;\n #tip: Tip | null = null;\n #tableOpen = false;\n\n // The elements.\n readonly #notice: HTMLDivElement;\n readonly #toolbar: HTMLDivElement;\n readonly #reset: HTMLButtonElement;\n readonly #tableToggle: HTMLButtonElement;\n readonly #downloads: HTMLSpanElement;\n readonly #svgButton: HTMLButtonElement;\n readonly #pngButton: HTMLButtonElement;\n readonly #row: HTMLDivElement;\n readonly #stage: HTMLDivElement;\n readonly #box: HTMLDivElement;\n readonly #svg: SVGSVGElement;\n #markup = '';\n #tooltip: HTMLDivElement | null = null;\n #tooltipShape = '';\n #sliceBlock: HTMLDivElement | null = null;\n #sliceHandle: ChartElement | null = null;\n #notes: HTMLUListElement | null = null;\n #notesShape = '';\n #tableBlock: HTMLDivElement | null = null;\n #tableShape = '';\n #tableOf: SurfaceDefinition | undefined;\n readonly #unlisten: readonly (() => void)[];\n\n constructor(root: HTMLElement, options: SurfaceOptions) {\n this.#root = root;\n this.#options = SurfaceElement.#checked(options);\n\n root.replaceChildren();\n root.classList.add('ex-chart', 'ex-chart-surface');\n this.#notice = document.createElement('div');\n this.#notice.setAttribute('data-ex-notice', 'stylesheet');\n this.#notice.setAttribute('data-ex-stylesheet', stylesheetName);\n this.#notice.setAttribute('data-ex-stamp', stylesheetStamp);\n this.#notice.style.display = 'none';\n this.#toolbar = document.createElement('div');\n this.#toolbar.className = 'ex-chart-toolbar';\n this.#toolbar.setAttribute('role', 'toolbar');\n this.#reset = toolbarButton('ex-chart-surface-reset');\n this.#tableToggle = toolbarButton('ex-chart-table-toggle');\n this.#downloads = document.createElement('span');\n this.#downloads.className = 'ex-chart-downloads';\n this.#downloads.setAttribute('role', 'group');\n this.#svgButton = toolbarButton('ex-chart-download-svg');\n this.#pngButton = toolbarButton('ex-chart-download-png');\n this.#downloads.append(this.#svgButton, this.#pngButton);\n this.#toolbar.append(this.#reset, this.#tableToggle, this.#downloads);\n this.#row = document.createElement('div');\n this.#row.className = 'ex-chart-surface-row';\n this.#stage = document.createElement('div');\n this.#stage.className = 'ex-chart-stage';\n this.#box = document.createElement('div');\n this.#box.className = 'ex-chart-surface-box';\n this.#box.tabIndex = 0;\n this.#box.setAttribute('role', 'img');\n this.#svg = document.createElementNS(svgNs, 'svg');\n this.#svg.setAttribute('class', 'ex-chart-surface-svg');\n this.#svg.setAttribute('aria-hidden', 'true');\n this.#box.append(this.#svg);\n this.#stage.append(this.#box);\n this.#row.append(this.#stage);\n root.append(this.#notice, this.#toolbar, this.#row);\n\n const unlisten: (() => void)[] = [];\n const listen = <K extends keyof HTMLElementEventMap>(target: HTMLElement, type: K, handle: (event: HTMLElementEventMap[K]) => void,\n passive = true): void => {\n target.addEventListener(type, handle, { passive });\n unlisten.push(() => { target.removeEventListener(type, handle); });\n };\n const box = this.#box;\n listen(box, 'pointerdown', e => { this.#onDown(e); });\n listen(box, 'pointermove', e => { this.#onMove(e); });\n listen(box, 'pointerup', e => { this.#onUp(e); });\n listen(box, 'pointercancel', e => { this.#onCancel(e); });\n listen(box, 'pointerleave', () => { this.#onLeave(); });\n listen(box, 'keydown', e => { this.#onKey(e); }, false);\n listen(box, 'wheel', e => { this.#onWheel(e); }, false);\n listen(box, 'contextmenu', e => { this.#onMenu(e); }, false);\n listen(this.#toolbar, 'click', e => { this.#onToolbar(e); });\n this.#unlisten = unlisten;\n this.#take(this.#options);\n this.#rebuild();\n this.#paint();\n }\n\n /** Takes the options again, whole: what did not change costs nothing. */\n update(options: SurfaceOptions): void {\n this.#alive();\n this.#options = SurfaceElement.#checked(options);\n this.#take(this.#options);\n this.#rebuild();\n this.#paint();\n }\n\n /** Stops the surface: it hears nothing more and empties its element. */\n destroy(): void {\n if (this.#destroyed) {\n return;\n }\n this.#destroyed = true;\n for (const stop of this.#unlisten) {\n stop();\n }\n this.#sliceHandle?.destroy();\n this.#sliceHandle = null;\n this.#root.replaceChildren();\n this.#root.classList.remove('ex-chart', 'ex-chart-surface');\n this.#root.style.removeProperty('font-size');\n this.#root.style.removeProperty('--ex-chart-line-height');\n }\n\n /**\n * The drawing as it stands \u2014 turned, zoomed and panned as the user left it \u2014 as SVG text that carries its\n * size and its colours resolved, for a file (ADR-0282): painted off the page, it has no stylesheet to read.\n * `undefined` once the surface is destroyed.\n */\n svgText(): string | undefined {\n if (this.#destroyed) {\n return undefined;\n }\n const width = this.#width;\n const height = this.#height;\n const svg = this.#svg;\n const copy = svg.cloneNode(true);\n if (!(copy instanceof SVGSVGElement)) {\n throw new Error('Internal: a copy of the surface\\'s drawing is not an SVG element.');\n }\n copy.setAttribute('xmlns', svgNs);\n copy.setAttribute('width', n(width));\n copy.setAttribute('height', n(height));\n copy.setAttribute('viewBox', `0 0 ${n(width)} ${n(height)}`);\n copy.removeAttribute('aria-hidden');\n copy.removeAttribute('class');\n const rootStyle = getComputedStyle(svg);\n const background = getComputedStyle(this.#root).backgroundColor;\n copy.setAttribute('style', `font-family:${rootStyle.fontFamily};font-size:${rootStyle.fontSize}`);\n const from = svg.querySelectorAll('*');\n const to = copy.querySelectorAll('*');\n const properties = ['fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-opacity', 'opacity', 'paint-order', 'stroke-linejoin', 'font-weight'];\n from.forEach((element, k) => {\n const style = getComputedStyle(element);\n const target = to.item(k);\n target.setAttribute('style', properties.map(p => `${p}:${style.getPropertyValue(p)}`).join(';'));\n target.removeAttribute('class');\n });\n // A file has no page behind it: the background is drawn, so a PNG is not transparent (ADR-0282).\n const backdrop = document.createElementNS(svgNs, 'rect');\n backdrop.setAttribute('width', n(width));\n backdrop.setAttribute('height', n(height));\n backdrop.setAttribute('style', `fill:${background}`);\n copy.prepend(backdrop);\n return new XMLSerializer().serializeToString(copy);\n }\n\n /**\n * Saves the drawing as it stands as an SVG or a PNG file, the PNG painted from that SVG at the screen's\n * Device Pixel (ADR-0282). One call is one save. False for a CSV \u2014 a surface's values are read in \"View as\n * table\" \u2014 and once the surface is destroyed.\n */\n async download(format: ChartFileFormat): Promise<boolean> {\n const text = format === 'csv' ? undefined : this.svgText();\n if (text === undefined) {\n return false;\n }\n const { title } = this.#options;\n const name = fileName(this.#options.fileName, blank(title) ? 'surface' : title, format);\n if (format === 'svg') {\n save(name, mediaType(format), text);\n } else {\n save(name, mediaType(format), await paintPng(text, this.#width, this.#height));\n }\n return true;\n }\n\n // ---- Options ----\n\n static #checked(options: SurfaceOptions): SurfaceOptions {\n // An untyped caller's options are checked here, at the boundary (CONVENTIONS.md).\n const { definition, width, height, sliceWidth, onViewChanged, onSliceChanged, label }: {\n readonly definition?: unknown; readonly width?: unknown; readonly height?: unknown; readonly sliceWidth?: unknown;\n readonly onViewChanged?: unknown; readonly onSliceChanged?: unknown; readonly label?: unknown;\n } = options;\n if (!(definition instanceof SurfaceDefinition)) {\n throw new TypeError('An ExSurface is given its definition, a SurfaceDefinition.');\n }\n for (const [name, value] of [['width', width], ['height', height], ['sliceWidth', sliceWidth]] as const) {\n if (value !== undefined && !(typeof value === 'number' && Number.isFinite(value) && value > 0)) {\n throw new RangeError(`An ExSurface's ${name} is a finite, positive number of CSS pixels. (${name}: ${typeof value === 'number' ? String(value) : `a ${typeof value}`})`);\n }\n }\n for (const [name, value] of [['onViewChanged', onViewChanged], ['onSliceChanged', onSliceChanged], ['label', label]] as const) {\n if (value !== undefined && typeof value !== 'function') {\n throw new TypeError(`An ExSurface's ${name} is a function.`);\n }\n }\n return options;\n }\n\n // Taken back as plain options (ADR-0272): an option that changed replaces what the user last did; one\n // that did not leaves it. A view raised here comes back as an echo, equal to what is held, and leaves the\n // view where the keys and the drags left it, unrounded.\n #take(options: SurfaceOptions): void {\n const view = options.view === undefined ? null : options.view;\n const slice = options.slice === undefined ? null : options.slice;\n const taken = this.#taken;\n if (taken === undefined || !sameTakenView(taken.view, view)) {\n const next = view === null ? defaultSurfaceView : rounded(view);\n const echoed = this.#raised.findIndex(v => sameView(v, next));\n if (echoed >= 0) {\n this.#raised.splice(0, echoed + 1);\n } else if (taken === undefined || !sameView(next, this.#held)) {\n this.#view = view === null ? defaultSurfaceView : view;\n this.#held = next;\n this.#raised = [];\n this.#drag = null;\n this.#tip = null;\n }\n }\n if (taken === undefined || !sameSlice(taken.slice, slice)) {\n this.#slice = slice;\n }\n this.#taken = { view, slice };\n }\n\n get #width(): number {\n const { width = 640 } = this.#options;\n return width;\n }\n\n get #height(): number {\n const { height = 420 } = this.#options;\n return height;\n }\n\n get #sliceWidth(): number {\n const { sliceWidth = 420 } = this.#options;\n return sliceWidth;\n }\n\n get #density(): GridDensity {\n const { density = 'standard' } = this.#options;\n return density;\n }\n\n get #definition(): SurfaceDefinition {\n return this.#options.definition;\n }\n\n #word(id: string, ...args: readonly string[]): string {\n return chartWord(id, this.#options.label, ...args);\n }\n\n #alive(): void {\n if (this.#destroyed) {\n throw new Error('This surface was destroyed; create another.');\n }\n }\n\n #rebuild(): void {\n const o = this.#options;\n const builtFrom = [o.definition, this.#width, this.#height, o.title, o.description];\n if (!builtFrom.every((v, i) => v === this.#builtFrom[i])) {\n if (this.#builtFrom[0] !== o.definition || this.#mesh === undefined) {\n this.#mesh = surfaceMesh(o.definition);\n }\n this.#builtFrom = builtFrom;\n this.#summary = surfaceSummary(o.definition, o.title, o.description);\n // A gesture begun against another surface ends unreported, and the point read on it is gone.\n this.#version += 1;\n this.#drag = null;\n this.#tip = null;\n }\n this.#buildSlice();\n }\n\n // The slice, in the data's terms: one the surface does not hold is said, not drawn (ADR-0272).\n #buildSlice(): void {\n const definition = this.#definition;\n const slice = this.#slice;\n const from = [definition, slice?.axis, slice?.value, this.#options.label];\n if (from.every((v, i) => v === this.#sliceFrom[i])) {\n return;\n }\n this.#sliceFrom = from;\n this.#sliceChart = slice === null ? undefined : definition.sliceChart(slice);\n this.#slicePath = slice === null || this.#sliceChart === undefined ? null : surfaceSlicePath(definition, slice);\n if (slice === null || this.#sliceChart !== undefined) {\n this.#sliceNote = null;\n return;\n }\n const axis = slice.axis === 'x' ? definition.x : definition.y;\n this.#sliceNote = this.#word(definition.isMesh ? chartWordIds.noSliceOnMesh : chartWordIds.noSliceOnGrid,\n nameOr(axis.title, slice.axis), axis.writeValue(slice.value));\n }\n\n // ---- The pointer and the keys (ADR-0274) ----\n\n #redraw(): void {\n const mesh = this.#mesh;\n if (mesh === undefined) {\n throw new Error('Internal: the surface is drawn before its mesh is built.');\n }\n const from = [mesh, this.#view, this.#slicePath, this.#width, this.#height];\n if (this.#drawing !== null && from.every((v, i) => v === this.#drawnFrom[i])) {\n return;\n }\n this.#drawnFrom = from;\n const drawing = drawSurface(mesh, this.#view, this.#slicePath, this.#width, this.#height);\n this.#drawing = drawing;\n const svg = this.#svg;\n svg.setAttribute('width', n(this.#width));\n svg.setAttribute('height', n(this.#height));\n svg.setAttribute('viewBox', `0 0 ${n(this.#width)} ${n(this.#height)}`);\n if (drawing.markup !== this.#markup) {\n this.#markup = drawing.markup;\n svg.innerHTML = drawing.markup;\n }\n }\n\n #nearest(x: number, y: number): DrawnSurfacePoint | null {\n let best: DrawnSurfacePoint | null = null;\n let bestDistance = reach * reach;\n for (const p of this.#drawing === null ? [] : this.#drawing.points) {\n const d = (p.x - x) ** 2 + (p.y - y) ** 2;\n if (d <= bestDistance) {\n best = p;\n bestDistance = d;\n }\n }\n return best;\n }\n\n // The point read in the tooltip changes only when the pointer comes nearer another (ADR-0255).\n #point(point: DrawnSurfacePoint | null, x: number, y: number): void {\n const tip = point === null || this.#definition.node(point.k)[2] === null ? null : { k: point.k, x, y };\n if ((tip === null) === (this.#tip === null) && (tip === null || tip.k === this.#tip?.k)) {\n return;\n }\n this.#tip = tip;\n this.#paintTooltip();\n }\n\n // The positions are the event's offsets on the box itself: the drawing takes no pointer events, so the\n // box is always the target.\n #own(event: Event): boolean {\n return event.target === this.#box;\n }\n\n #onDown(event: PointerEvent): void {\n // One pointer at a time: a second finger, or a second button, does not join the gesture.\n if (this.#drag !== null || (event.button !== 0 && event.button !== 2) || !this.#own(event)) {\n return;\n }\n // Captured first: a pointer the browser does not know throws here and starts no gesture to wait on.\n this.#box.setPointerCapture(event.pointerId);\n this.#drag = {\n id: event.pointerId, x: event.offsetX, y: event.offsetY, view: this.#view, pan: event.shiftKey || event.button === 2,\n moved: false, version: this.#version,\n };\n }\n\n #onMove(event: PointerEvent): void {\n const drag = this.#drag;\n if (drag !== null && event.pointerId !== drag.id) {\n return;\n }\n if (drag !== null) {\n const dx = event.offsetX - drag.x;\n const dy = event.offsetY - drag.y;\n if (!drag.moved && dx * dx + dy * dy < clickSlop * clickSlop) {\n return;\n }\n drag.moved = true;\n if (drag.pan) {\n this.#view = { ...drag.view, panX: drag.view.panX + dx / this.#width, panY: drag.view.panY + dy / this.#height };\n } else {\n // The surface is held where it was pressed: a drag to the right brings its near side to the\n // right, a drag down tips its top toward the viewer.\n const degrees = turnPerHeight / Math.max(1, this.#height);\n this.#view = { ...drag.view, yaw: turn(drag.view.yaw + dx * degrees), pitch: clamp(drag.view.pitch + dy * degrees, -90, 90) };\n }\n this.#point(null, 0, 0);\n this.#redraw();\n return;\n }\n if (!this.#own(event)) {\n return;\n }\n this.#point(this.#nearest(event.offsetX, event.offsetY), event.offsetX, event.offsetY);\n }\n\n #onUp(event: PointerEvent): void {\n const pressed = this.#drag;\n if (pressed !== null && event.pointerId !== pressed.id) {\n return;\n }\n this.#drag = null;\n if (pressed === null || pressed.version !== this.#version) {\n return;\n }\n if (pressed.moved) {\n this.#raiseView();\n return;\n }\n if (pressed.pan) {\n return;\n }\n const point = this.#nearest(pressed.x, pressed.y);\n const drawing = this.#drawing;\n if (point === null || drawing === null) {\n return;\n }\n const axis = sliceAxisAt(drawing, point, pressed.x, pressed.y);\n // A click slices along the line it fell on: a grid's tenor or strike, or on a mesh the position of\n // the node it fell on, which cuts its triangles (ADR-0311).\n const [x, y] = this.#definition.node(point.k);\n const slice: SurfaceSlice = Object.freeze({ axis, value: axis === 'x' ? x : y });\n this.#slice = slice;\n this.#buildSlice();\n this.#paint();\n this.#options.onSliceChanged?.(slice);\n }\n\n #onCancel(event: PointerEvent): void {\n const drag = this.#drag;\n if (drag !== null && event.pointerId !== drag.id) {\n return;\n }\n this.#drag = null;\n if (drag !== null && drag.moved && drag.version === this.#version) {\n this.#raiseView();\n }\n }\n\n #onLeave(): void {\n if (this.#drag === null) {\n this.#point(null, 0, 0);\n }\n }\n\n #onKey(event: KeyboardEvent): void {\n if (event.altKey || event.ctrlKey || event.metaKey) {\n return;\n }\n const step = arrowStep(event.key);\n const view = this.#view;\n if (step !== null && event.shiftKey) {\n this.#view = { ...view, panX: view.panX + step[0] * 0.05, panY: view.panY + step[1] * 0.05 };\n } else if (step !== null) {\n // An arrow turns the surface as a drag the same way would.\n this.#view = { ...view, yaw: turn(view.yaw + step[0] * 5), pitch: clamp(view.pitch + step[1] * 5, -90, 90) };\n } else if (event.key === '+' || event.key === '=') {\n this.#view = { ...view, zoom: clamp(view.zoom * 1.25, 0.5, 8) };\n } else if (event.key === '-') {\n this.#view = { ...view, zoom: clamp(view.zoom / 1.25, 0.5, 8) };\n } else {\n return;\n }\n event.preventDefault();\n // The point under the pointer has moved: the tooltip waits for the pointer's next move.\n this.#point(null, 0, 0);\n this.#redraw();\n this.#raiseView();\n }\n\n #onWheel(event: WheelEvent): void {\n if (event.deltaY === 0) {\n return;\n }\n event.preventDefault();\n // A trackpad sends many small steps and a mouse a few large ones; each zooms by how far it moved, in\n // pixels whatever the event's unit.\n const pixels = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? Math.max(1, this.#height) : 1);\n this.#view = { ...this.#view, zoom: clamp(this.#view.zoom * Math.exp(-pixels * wheelZoom), 0.5, 8) };\n this.#point(null, 0, 0);\n this.#redraw();\n this.#raiseView();\n }\n\n // The right button pans, so it opens no menu over the drawing.\n #onMenu(event: MouseEvent): void {\n if (this.#own(event)) {\n event.preventDefault();\n }\n }\n\n #raiseView(): void {\n const view = rounded(this.#view);\n if (sameView(view, this.#held)) {\n return;\n }\n this.#held = view;\n this.#raised.push(view);\n // A Consumer that never takes the view back keeps only the latest raised.\n if (this.#raised.length > raisedKept) {\n this.#raised.shift();\n }\n this.#paintToolbar();\n this.#options.onViewChanged?.(view);\n }\n\n #onToolbar(event: MouseEvent): void {\n const target = event.target;\n if (!(target instanceof Element)) {\n return;\n }\n const button = target.closest('button');\n if (button === this.#reset) {\n this.#view = defaultSurfaceView;\n this.#held = defaultSurfaceView;\n this.#raised = [defaultSurfaceView];\n this.#drag = null;\n this.#tip = null;\n this.#paint();\n this.#options.onViewChanged?.(defaultSurfaceView);\n } else if (button === this.#tableToggle) {\n this.#tableOpen = !this.#tableOpen;\n this.#paint();\n } else if (button === this.#svgButton) {\n void this.download('svg');\n } else if (button === this.#pngButton) {\n void this.download('png');\n }\n }\n\n // ---- Painting ----\n\n #paint(): void {\n const text = densityText(this.#density);\n const root = this.#root;\n // Only the surface's own properties, so a style the Consumer gave the element stays.\n root.style.setProperty('font-size', `${n(text.fontSizePx)}px`);\n root.style.setProperty('--ex-chart-line-height', `${n(Math.ceil(text.fontSizePx * 1.4))}px`);\n const size = `width:${n(this.#width)}px;height:${n(this.#height)}px`;\n this.#stage.style.cssText = size;\n this.#box.style.cssText = size;\n this.#box.setAttribute('aria-roledescription', this.#word(chartWordIds.surfaceRole));\n this.#box.setAttribute('aria-label', this.#summary);\n this.#paintToolbar();\n this.#redraw();\n this.#paintTooltip();\n this.#paintSliceChart();\n this.#paintNotes();\n this.#paintTable();\n }\n\n #paintToolbar(): void {\n setText(this.#notice, this.#word(chartWordIds.stylesheetNotice));\n const { title } = this.#options;\n this.#toolbar.setAttribute('aria-label', blank(title) ? this.#word(chartWordIds.surface) : title);\n setText(this.#reset, this.#word(chartWordIds.resetView));\n this.#reset.disabled = sameView(this.#held, defaultSurfaceView);\n setText(this.#tableToggle, this.#word(chartWordIds.table));\n this.#tableToggle.setAttribute('aria-expanded', this.#tableOpen ? 'true' : 'false');\n this.#downloads.setAttribute('aria-label', this.#word(chartWordIds.downloads));\n setText(this.#svgButton, this.#word(chartWordIds.downloadSvg));\n setText(this.#pngButton, this.#word(chartWordIds.downloadPng));\n }\n\n #paintTooltip(): void {\n const tip = this.#tip;\n const definition = this.#definition;\n const font = densityText(this.#density).fontSizePx;\n const lines: (readonly [cls: string, name: string, value: string])[] = [];\n let note: string | null = null;\n if (tip !== null) {\n const [x, y, z] = definition.node(tip.k);\n if (z === null) {\n throw new Error('Internal: the tooltip reads a hole.');\n }\n lines.push(['ex-chart-tooltip-line', nameOr(definition.x.title, 'x'), definition.x.writeValue(x)]);\n lines.push(['ex-chart-tooltip-line', nameOr(definition.y.title, 'y'), definition.y.writeValue(y)]);\n lines.push(['ex-chart-tooltip-line ex-chart-tooltip-position', nameOr(definition.zTitle, this.#word(chartWordIds.surfaceValue)), definition.writeZ(z)]);\n const method = definition.method;\n if (method !== undefined) {\n note = definition.isInterpolatedNode(tip.k) ? this.#word(chartWordIds.interpolated, method) : this.#word(chartWordIds.quoted);\n }\n }\n const gap = Math.ceil(font);\n const flip = tip !== null && tip.x > this.#width / 2;\n const left = tip === null ? 0 : flip ? tip.x - gap : tip.x + gap;\n const top = tip === null ? 0 : tip.y + gap;\n const shape = tip === null ? '' : JSON.stringify([lines, note, flip, left, top]);\n if (shape === this.#tooltipShape) {\n return;\n }\n this.#tooltipShape = shape;\n this.#tooltip?.remove();\n this.#tooltip = null;\n if (tip === null) {\n return;\n }\n const tooltip = document.createElement('div');\n tooltip.className = `ex-chart-tooltip ex-chart-surface-tooltip${flip ? ' ex-chart-tooltip-flip' : ''}`;\n tooltip.style.cssText = `left:${n(left)}px;top:${n(top)}px`;\n tooltip.setAttribute('role', 'status');\n for (const [cls, name, value] of lines) {\n const line = document.createElement('div');\n line.className = cls;\n const nameSpan = document.createElement('span');\n nameSpan.className = 'ex-chart-tooltip-name';\n nameSpan.textContent = name;\n const valueSpan = document.createElement('span');\n valueSpan.className = 'ex-chart-tooltip-value';\n valueSpan.textContent = value;\n line.append(nameSpan, valueSpan);\n tooltip.append(line);\n }\n if (note !== null) {\n const noteLine = document.createElement('div');\n noteLine.className = 'ex-chart-tooltip-note';\n noteLine.textContent = note;\n tooltip.append(noteLine);\n }\n this.#stage.append(tooltip);\n this.#tooltip = tooltip;\n }\n\n #paintSliceChart(): void {\n const chart = this.#sliceChart;\n if (chart === undefined) {\n this.#sliceHandle?.destroy();\n this.#sliceHandle = null;\n this.#sliceBlock?.remove();\n this.#sliceBlock = null;\n return;\n }\n const definition = this.#definition;\n const first = chart.series[0];\n const options = {\n definition: chart,\n ...(first === undefined ? {} : { title: first.name }),\n width: this.#sliceWidth,\n height: this.#height,\n density: this.#density,\n // The slice is read on the surface's vertical scale (ADR-0312).\n ...(definition.effectiveZScale === 'logarithmic' ? { yScale: 'logarithmic' as const } : {}),\n ...(this.#options.label === undefined ? {} : { label: this.#options.label }),\n };\n if (this.#sliceHandle === null || this.#sliceBlock === null) {\n const block = document.createElement('div');\n block.className = 'ex-chart-surface-slice-chart';\n const element = document.createElement('div');\n block.append(element);\n this.#row.append(block);\n this.#sliceBlock = block;\n this.#sliceHandle = new ChartElement(element, options);\n } else {\n this.#sliceHandle.update(options);\n }\n }\n\n #paintNotes(): void {\n const notes = [...this.#definition.allNotes, ...(this.#sliceNote === null ? [] : [this.#sliceNote])];\n const shape = JSON.stringify(notes);\n if (shape === this.#notesShape) {\n return;\n }\n this.#notesShape = shape;\n this.#notes?.remove();\n this.#notes = null;\n if (notes.length === 0) {\n return;\n }\n const list = document.createElement('ul');\n list.className = 'ex-chart-notes';\n for (const note of notes) {\n const item = document.createElement('li');\n item.textContent = note;\n list.append(item);\n }\n this.#row.after(list);\n this.#notes = list;\n }\n\n #paintTable(): void {\n const definition = this.#definition;\n const { title } = this.#options;\n const caption = blank(title) ? this.#word(chartWordIds.surfaceData) : title;\n const shape = this.#tableOpen ? JSON.stringify([caption, this.#word(chartWordIds.surfaceValue)]) : '';\n if (shape === this.#tableShape && this.#tableOf === definition) {\n return;\n }\n this.#tableShape = shape;\n this.#tableOf = definition;\n this.#tableBlock?.remove();\n this.#tableBlock = null;\n if (!this.#tableOpen) {\n return;\n }\n const x = nameOr(definition.x.title, 'x');\n const y = nameOr(definition.y.title, 'y');\n const headRow = document.createElement('tr');\n const body = document.createElement('tbody');\n const nodes = definition.nodes;\n if (nodes === undefined) {\n headRow.append(cell('th', `${y} \\\\ ${x}`, 'col'), ...definition.x.values.map((_, i) => cell('th', definition.x.write(i), 'col')));\n definition.y.values.forEach((_, j) => {\n const tr = document.createElement('tr');\n tr.append(cell('th', definition.y.write(j), 'row'));\n definition.x.values.forEach((__, i) => {\n const v = definition.at(i, j);\n tr.append(cell('td', v === null ? '' : definition.writeZ(v)));\n });\n body.append(tr);\n });\n } else {\n // A mesh has no grid to tabulate: its nodes are listed, each where it lies (ADR-0311).\n headRow.append(cell('th', x, 'col'), cell('th', y, 'col'), cell('th', nameOr(definition.zTitle, this.#word(chartWordIds.surfaceValue)), 'col'));\n for (const q of nodes) {\n const tr = document.createElement('tr');\n tr.append(cell('td', definition.x.writeValue(q.x)), cell('td', definition.y.writeValue(q.y)),\n cell('td', q.z === null ? '' : definition.writeZ(q.z)));\n body.append(tr);\n }\n }\n const head = document.createElement('thead');\n head.append(headRow);\n const captionElement = document.createElement('caption');\n captionElement.textContent = caption;\n const table = document.createElement('table');\n table.className = 'ex-chart-table';\n table.append(captionElement, head, body);\n const wrap = document.createElement('div');\n wrap.className = 'ex-chart-table-wrap';\n wrap.append(table);\n this.#root.append(wrap);\n this.#tableBlock = wrap;\n }\n\n}\n\nfunction toolbarButton(cls: string): HTMLButtonElement {\n const b = document.createElement('button');\n b.type = 'button';\n b.className = `ex-chart-button ${cls}`;\n return b;\n}\n\nfunction cell(tag: 'th' | 'td', content: string, scope?: 'col' | 'row'): HTMLTableCellElement {\n const c = document.createElement(tag);\n if (scope !== undefined) {\n c.setAttribute('scope', scope);\n }\n c.textContent = content;\n return c;\n}\n\nfunction arrowStep(key: string): readonly [number, number] | null {\n switch (key) {\n case 'ArrowLeft': return [-1, 0];\n case 'ArrowRight': return [1, 0];\n case 'ArrowUp': return [0, -1];\n case 'ArrowDown': return [0, 1];\n default: return null;\n }\n}\n\nfunction setText(element: Element, text: string): void {\n if (element.textContent !== text) {\n element.textContent = text;\n }\n}\n", "// A 3D surface projected and drawn (ADR-0255, ADR-0274): the port of ex-chart.js's drawSurface. Where each\n// point lies on the floor and on the vertical scale, and each face's colour band, are the mesh's (ADR-0312,\n// ADR-0310); this turns, projects, orders and writes them as SVG markup, and says where it drew each point,\n// each grid line through them, and how a step along x and along y is drawn, which the pointer is read\n// against. A hole is a hole: a face with a hole at a corner is not drawn, the hole has no point, and the\n// lines through it break there.\nimport type { SurfaceView } from '../surface';\nimport type { SurfaceMesh, SurfaceMeshPoint } from '../surface-mesh';\nimport { element, escapeText } from './svg-markup';\n\n/** A point as it was drawn: its node, and where on the box. */\nexport interface DrawnSurfacePoint {\n readonly k: number;\n readonly x: number;\n readonly y: number;\n}\n\ntype Screen = readonly [x: number, y: number];\n\n// A drawn point, with its depth or without it.\ntype Drawn = readonly [x: number, y: number, ...rest: number[]];\n\n/** What a drawing says besides its markup, for the pointer. */\nexport interface SurfaceDrawing {\n readonly markup: string;\n readonly points: readonly DrawnSurfacePoint[];\n /** A grid's lines along x and along y as drawn, each broken where a point is a hole; empty for a mesh. */\n readonly rows: readonly (readonly Screen[])[];\n readonly columns: readonly (readonly Screen[])[];\n /** How a step along x and along y is drawn at the floor's centre, for a click on a mesh; `null` when nothing is drawn. */\n readonly steps: { readonly x: Screen; readonly y: Screen } | null;\n}\n\n/** The strip at the right of a surface's drawing that holds its colour bar (ADR-0310). */\nexport const surfaceBarWidth = 80;\n\ntype Projected = readonly [x: number, y: number, depth: number];\n\nconst f1 = (v: number): string => v.toFixed(1);\n\n// A step beyond the floor's front edge, outward.\nconst out = (front: number, by: number): number => front + (front === 0 ? -by : by);\n\nconst pointsText = (pts: readonly Drawn[]): string => pts.map(p => `${f1(p[0])},${f1(p[1])}`).join(' ');\n\nconst poly = (pts: readonly Drawn[], cls: string): string => element('polygon', [['points', pointsText(pts)], ['class', cls]]);\n\nconst line = (p: Drawn, q: Drawn, cls: string): string =>\n element('line', [['x1', f1(p[0])], ['y1', f1(p[1])], ['x2', f1(q[0])], ['y2', f1(q[1])], ['class', cls]]);\n\nconst text = (x: number, y: number, anchor: string | null, cls: string, content: string): string =>\n element('text', [['x', f1(x)], ['y', f1(y)], ...(anchor === null ? [] : [['text-anchor', anchor] as const]), ['class', cls]], escapeText(content));\n\n/** Draws `mesh` as seen from `view` in a box `width` by `height`, with `slice` drawn on it. */\nexport function drawSurface(mesh: SurfaceMesh, view: SurfaceView, slice: readonly (readonly SurfaceMeshPoint[])[] | null,\n width: number, height: number): SurfaceDrawing {\n const nodes = mesh.nodes;\n if (nodes.length === 0 || width <= surfaceBarWidth || height <= 0) {\n return { markup: '', points: [], rows: [], columns: [], steps: null };\n }\n const { zMin, zMax } = mesh;\n const plotW = width - surfaceBarWidth;\n const a = (view.yaw * Math.PI) / 180;\n const b = (view.pitch * Math.PI) / 180;\n // World: x across the floor, y along it, z up; each within [-0.5, 0.5], z squashed.\n // A flat surface stands at the middle of its box.\n const zSpan = zMax - zMin === 0 ? 1 : zMax - zMin;\n const world = (x: number, y: number, z: number): Projected => [x - 0.5, y - 0.5, ((z - zMin) / zSpan - 0.5) * 0.6];\n // Turned by the yaw about the vertical, then seen from the front (\u2212y) and above by the pitch, or below\n // where it is negative: screen x, screen y down, and depth, larger farther. The axes stay right-handed,\n // x to y counterclockwise seen from above, so the picture is never a mirror.\n const raw = ([x, y, z]: Projected): Projected => {\n const x1 = x * Math.cos(a) - y * Math.sin(a);\n const y1 = x * Math.sin(a) + y * Math.cos(a);\n return [x1, -(y1 * Math.sin(b) + z * Math.cos(b)), y1 * Math.cos(b) - z * Math.sin(b)];\n };\n // Fitted to the box at every angle by the projected corners of the box the surface stands in, with room\n // round it for the labels; then zoomed about the centre and panned.\n const corners: Projected[] = [];\n for (const cx of [-0.5, 0.5]) {\n for (const cy of [-0.5, 0.5]) {\n for (const cz of [-0.3, 0.3]) {\n corners.push(raw([cx, cy, cz]));\n }\n }\n }\n const minX = Math.min(...corners.map(c => c[0]));\n const maxX = Math.max(...corners.map(c => c[0]));\n const minY = Math.min(...corners.map(c => c[1]));\n const maxY = Math.max(...corners.map(c => c[1]));\n const s = Math.max(1, Math.min((plotW * 0.78) / (maxX - minX), (height * 0.8) / (maxY - minY))) * view.zoom;\n const centreX = plotW / 2 + view.panX * width;\n const centreY = height / 2 + view.panY * height;\n const project = (p: Projected): Projected => {\n const [x, y, depth] = raw(p);\n return [centreX + (x - (minX + maxX) / 2) * s, centreY + (y - (minY + maxY) / 2) * s, depth];\n };\n const at = (x: number, y: number, z: number): Projected => project(world(x, y, z));\n const node = (k: number): Projected => {\n const q = nodes[k];\n if (q === undefined || q.z === null) {\n throw new Error(`Internal: the surface's face names node ${String(k)}, which holds no value.`);\n }\n return at(q.x, q.y, q.z);\n };\n const heat = mesh.bar.diverging ? 'ex-chart-diverge-' : 'ex-chart-heat-';\n let markup = '';\n\n // The floor and the two walls behind the surface, each with its grid; which walls are behind depends on\n // where the viewer stands. Seen from below, the box's top is behind it instead of its floor. The grid's x\n // and y lines run up the walls too, so a value is read across to them.\n const backX = Math.sin(a) > 0 ? 1 : 0;\n const backY = Math.cos(a) > 0 ? 1 : 0;\n // The vertical's labels, and its title, stand on the outer side of the edge they mark.\n const right = at(backX, 1 - backY, zMin)[0] > at(0.5, 0.5, zMin)[0];\n const zBack = view.pitch >= 0 ? zMin : zMax;\n let walls = poly([at(0, 0, zBack), at(1, 0, zBack), at(1, 1, zBack), at(0, 1, zBack)], 'ex-chart-surface-wall');\n const upright = Math.abs(view.pitch) < 89;\n if (upright) {\n walls += poly([at(0, backY, zMin), at(1, backY, zMin), at(1, backY, zMax), at(0, backY, zMax)], 'ex-chart-surface-wall');\n walls += poly([at(backX, 0, zMin), at(backX, 1, zMin), at(backX, 1, zMax), at(backX, 0, zMax)], 'ex-chart-surface-wall');\n for (const t of mesh.xLines) {\n walls += line(at(t.value, backY, zMin), at(t.value, backY, zMax), 'ex-chart-surface-grid');\n }\n for (const t of mesh.yLines) {\n walls += line(at(backX, t.value, zMin), at(backX, t.value, zMax), 'ex-chart-surface-grid');\n }\n for (const tick of mesh.zTicks) {\n walls += line(at(0, backY, tick.value), at(1, backY, tick.value), 'ex-chart-surface-grid');\n walls += line(at(backX, 0, tick.value), at(backX, 1, tick.value), 'ex-chart-surface-grid');\n const p = at(backX, 1 - backY, tick.value);\n walls += text(p[0] + (right ? 8 : -8), p[1] + 4, right ? 'start' : 'end', 'ex-chart-surface-label', labelOf(tick.label));\n }\n }\n for (const t of mesh.xLines) {\n walls += line(at(t.value, 0, zBack), at(t.value, 1, zBack), 'ex-chart-surface-grid');\n }\n for (const t of mesh.yLines) {\n walls += line(at(0, t.value, zBack), at(1, t.value, zBack), 'ex-chart-surface-grid');\n }\n markup += element('g', [['class', 'ex-chart-surface-walls']], walls);\n\n // The faces, the farthest first, each in its colour band.\n const faces = mesh.faces.map(face => {\n const pts = face.corners.map(node);\n return { pts, depth: pts.reduce((sum, p) => sum + p[2], 0) / pts.length, band: face.band };\n });\n faces.sort((p, q) => q.depth - p.depth);\n markup += element('g', [['class', 'ex-chart-surface-faces']],\n faces.map(face => poly(face.pts, `ex-chart-surface-face ${heat}${String(face.band)}`)).join(''));\n\n // The points, and a grid's lines through them, broken at a hole. A dot marks a value the data holds; an\n // interpolated one is the Consumer's surface between them.\n const points: DrawnSurfacePoint[] = [];\n const projected = new Map<number, Screen>();\n let dots = '';\n nodes.forEach((q, k) => {\n if (q.z === null) {\n return;\n }\n const p = at(q.x, q.y, q.z);\n projected.set(k, [p[0], p[1]]);\n points.push({ k, x: p[0], y: p[1] });\n if (!q.interpolated) {\n dots += element('circle', [['cx', f1(p[0])], ['cy', f1(p[1])], ['r', '2.4'], ['class', 'ex-chart-surface-point']]);\n }\n });\n markup += element('g', [['class', 'ex-chart-surface-points']], dots);\n const through = (ks: readonly number[]): readonly Screen[] => ks.flatMap(k => {\n const p = projected.get(k);\n return p === undefined ? [] : [p];\n });\n const rows = mesh.rows.map(through);\n const columns = mesh.columns.map(through);\n\n // The slice drawn on the surface, so the 2D chart beside it is seen to be this line.\n if (slice !== null && slice.length > 0) {\n markup += element('g', [['class', 'ex-chart-surface-slice']],\n slice.map(run => element('polyline', [['points', pointsText(run.map(q => at(q.x, q.y, q.z)))]])).join(''));\n }\n\n // The axes' labels along the front edges of the floor.\n const frontY = 1 - backY;\n const frontX = 1 - backX;\n let labels = '';\n const label = (p: Projected, content: string, cls: string): void => {\n labels += text(p[0], p[1] + 4, 'middle', cls, content);\n };\n for (const t of mesh.xLines) {\n if (t.label !== null) {\n label(at(t.value, out(frontY, 0.08), zMin), t.label, 'ex-chart-surface-label');\n }\n }\n for (const t of mesh.yLines) {\n if (t.label !== null) {\n label(at(out(frontX, 0.08), t.value, zMin), t.label, 'ex-chart-surface-label');\n }\n }\n label(at(0.5, out(frontY, 0.22), zMin), mesh.xTitle, 'ex-chart-surface-label ex-chart-surface-title');\n label(at(out(frontX, 0.26), 0.5, zMin), mesh.yTitle, 'ex-chart-surface-label ex-chart-surface-title');\n if (upright && mesh.zTitle !== '') {\n const p = at(backX, 1 - backY, zMax + (zMax - zMin) * 0.12);\n labels += text(p[0] + (right ? 8 : -8), p[1] + 4, right ? 'start' : 'end', 'ex-chart-surface-label ex-chart-surface-title', mesh.zTitle);\n }\n markup += element('g', [['class', 'ex-chart-surface-labels']], labels);\n\n // The colour bar, which does not turn with the surface: its bands low to high, each the colour a face\n // takes, and its values (ADR-0310).\n const top = height * 0.1;\n const bottom = height * 0.9;\n const left = width - surfaceBarWidth + 8;\n const count = mesh.bar.bands;\n const band = (bottom - top) / count;\n let bar = '';\n for (let k = 0; k < count; k++) {\n bar += element('rect', [['x', f1(left)], ['y', f1(bottom - (k + 1) * band)], ['width', '12'], ['height', f1(band)],\n ['class', `ex-chart-surface-bar-band ${heat}${String(k)}`]]);\n }\n bar += element('rect', [['x', f1(left)], ['y', f1(top)], ['width', '12'], ['height', f1(bottom - top)], ['class', 'ex-chart-surface-bar-frame']]);\n // A bar of one value puts its tick at the foot.\n const span = mesh.bar.to - mesh.bar.from === 0 ? 1 : mesh.bar.to - mesh.bar.from;\n for (const tick of mesh.bar.ticks) {\n const y = bottom - ((tick.value - mesh.bar.from) / span) * (bottom - top);\n bar += line([left + 12, y], [left + 16, y], 'ex-chart-surface-bar-tick');\n bar += text(left + 19, y + 4, null, 'ex-chart-surface-label', labelOf(tick.label));\n }\n markup += element('g', [['class', 'ex-chart-surface-bar']], bar);\n\n // How a step along x and along y is drawn at a point, for a click on a mesh, which has no grid line.\n const o = at(0.5, 0.5, zMin);\n const ox = at(0.6, 0.5, zMin);\n const oy = at(0.5, 0.6, zMin);\n const steps = { x: [ox[0] - o[0], ox[1] - o[1]] as const, y: [oy[0] - o[0], oy[1] - o[1]] as const };\n\n return { markup, points, rows, columns, steps };\n}\n\n// The vertical scale's ticks and the colour bar's are always labelled; the mesh says so with a label.\nfunction labelOf(label: string | null): string {\n if (label === null) {\n throw new Error('Internal: a tick of the surface\\'s vertical scale or colour bar has no label.');\n }\n return label;\n}\n\n/** `v` held within `lo` to `hi`. */\nexport const clamp = (v: number, lo: number, hi: number): number => Math.max(lo, Math.min(hi, v));\n\n/** The distance from (x, y) to a drawn line, or `Infinity` for a line with no point. */\nexport function distanceToLine(drawn: readonly Screen[] | undefined, x: number, y: number): number {\n if (drawn === undefined || drawn.length === 0) {\n return Infinity;\n }\n let best = Infinity;\n drawn.forEach((p, k) => {\n const q = drawn[k + 1];\n if (q === undefined) {\n best = Math.min(best, Math.hypot(p[0] - x, p[1] - y));\n return;\n }\n const dx = q[0] - p[0];\n const dy = q[1] - p[1];\n const length = dx * dx + dy * dy;\n const t = length === 0 ? 0 : clamp(((x - p[0]) * dx + (y - p[1]) * dy) / length, 0, 1);\n best = Math.min(best, Math.hypot(p[0] + t * dx - x, p[1] + t * dy - y));\n });\n return best;\n}\n\n/**\n * The line a click on a drawn point fell on, as the axis held fixed by the slice it draws. A grid point\n * lies on two lines, a tenor's and a strike's; the one nearer the pointer is the one it fell on. A tenor's\n * line runs along x, so a click on it slices that tenor (y held fixed). A mesh's node has no grid line\n * through it: the lines are those a step along x and along y draws through it, and the slice cuts its\n * triangles (ADR-0311).\n */\nexport function sliceAxisAt(drawing: SurfaceDrawing, point: DrawnSurfacePoint, x: number, y: number): 'x' | 'y' {\n const nx = drawing.columns.length;\n if (nx > 0) {\n const row = distanceToLine(drawing.rows[Math.floor(point.k / nx)], x, y);\n const column = distanceToLine(drawing.columns[point.k % nx], x, y);\n return column < row ? 'x' : 'y';\n }\n const steps = drawing.steps;\n if (steps === null) {\n throw new Error('Internal: a point was read on a surface with nothing drawn.');\n }\n // A step drawn as no length at all (seen edge-on) is measured as it stands.\n const off = (d: Screen): number => Math.abs((x - point.x) * d[1] - (y - point.y) * d[0]) / (Math.hypot(d[0], d[1]) === 0 ? 1 : Math.hypot(d[0], d[1]));\n return off(steps.y) < off(steps.x) ? 'x' : 'y';\n}\n", "import type { ChartFileFormat } from './chart-files';\nimport { SurfaceElement, type SurfaceOptions } from './surface-element';\n\n/** A 3D surface drawn into an element, handed back by {@link createSurface}. */\nexport interface SurfaceHandle {\n /** Takes the options again, whole: what did not change costs nothing. */\n update(options: SurfaceOptions): void;\n /** Stops the surface: it hears nothing more and empties its element. */\n destroy(): void;\n /**\n * Saves the drawing as it stands as `svg`, or as `png` painted at the screen's Device Pixel (ADR-0282). One\n * call is one save. False for `csv` \u2014 a surface's values are read in \"View as table\" \u2014 and once destroyed.\n */\n download(format: ChartFileFormat): Promise<boolean>;\n /** The drawing as it stands as SVG text, its colours resolved; `undefined` once destroyed (ADR-0282). */\n svgText(): string | undefined;\n}\n\n/**\n * Draws a 3D surface into `element`, which becomes its instance root (ADR-0274, ADR-0370 section 1): the\n * surface owns everything inside it. A Framework Adapter renders the element and hands the surface its props.\n */\nexport function createSurface(element: HTMLElement, options: SurfaceOptions): SurfaceHandle {\n const surface = new SurfaceElement(element, options);\n return Object.freeze({\n update: (next: SurfaceOptions) => { surface.update(next); },\n destroy: () => { surface.destroy(); },\n download: (format: ChartFileFormat) => surface.download(format),\n svgText: () => surface.svgText(),\n });\n}\n", "// Turns a grid selection into a GridChart, and a GridChart into a Chart Definition (ADR-0251, ADR-0258): the\n// counterpart of C#'s SelectionReader. What it cannot make sense of it refuses by name, rather than drawing\n// something plausible (spine rule 1). Nothing here is exported from the package: the bridge is its surface.\nimport type { GridColumn, GridHeaderGroup, RowKey, RowRange, SelectionRange } from '@ex-grid/core';\nimport { ChartDefinition } from '../definition';\nimport { dayNumber } from '../day-numbers';\nimport type { AppearanceKeys, ChartAxisOptions, ChartPoint, ChartSeriesOptions, ChartValue, SeriesKind } from '../model';\nimport { defined, elementAt, itemAt } from '../must';\nimport { ChartRefusedError, toNumber, writeObject } from '../values';\nimport type { ChartOrientation, ChartTarget, ColumnSeries, GridChart, GridChartSeries, KeyedPosition, RowSeries } from './grid-chart';\nimport type { GridChartDeclarations } from './grid-chart-declarations';\n\n/** What the bridge reads of a grid: its columns, groups and order, and the rows at positions in it. */\nexport interface BridgeGridState<Row> {\n readonly columns: readonly GridColumn<Row>[];\n readonly groups: readonly GridHeaderGroup[];\n readonly rowSequenceVersion: number;\n readonly window: readonly Row[];\n readonly windowStart: number;\n /** The rows of a run outside the Window, as many as there are; absent where nothing can be fetched. */\n readonly fetch?: (range: RowRange) => Promise<readonly Row[]>;\n /** The source's Row Sequence Version as it stands now, read again once a fetch has answered. */\n readonly versionNow: () => number;\n}\n\n/** A selection read: the chart it makes, or the sentence that says why it makes none. */\nexport type SelectionReading =\n | { readonly chart: GridChart; readonly refusal?: never }\n | { readonly chart?: never; readonly refusal: string };\n\n/** The refusal of a selection taken under another Row Sequence Version (ADR-0251, spine rule 6). */\nexport const stale = 'The rows were reordered after the selection was made. Select again.';\n\nconst refused = (refusal: string): SelectionReading => Object.freeze({ refusal });\n\nfunction isNumber<Row>(c: GridColumn<Row>): boolean {\n // A Mark Column carries no value (`queryable: false`), as an Action Column does (ADR-0020, ADR-0043).\n return c.type === 'number' && c.queryable !== false && (c.actions === undefined || c.actions.length === 0);\n}\n\nfunction axisColumnsOf<Row>(d: GridChartDeclarations<Row>): ReadonlySet<string> {\n const { axisColumns = [] } = d;\n return axisColumns instanceof Set ? axisColumns : new Set(axisColumns);\n}\n\nfunction isAxis<Row>(c: GridColumn<Row>, d: GridChartDeclarations<Row>): boolean {\n return c.type === 'date' || (isNumber(c) && axisColumnsOf(d).has(c.name));\n}\n\nfunction positionOf<Row>(c: GridColumn<Row>, d: GridChartDeclarations<Row>): number | undefined {\n return isNumber(c) && d.positionOf !== undefined ? d.positionOf(c.name) : undefined;\n}\n\nfunction headerOf<Row>(c: GridColumn<Row>): string {\n return c.header ?? c.name;\n}\n\nfunction headers<Row>(columns: readonly GridColumn<Row>[]): string {\n return columns.map(headerOf).join(', ');\n}\n\nconst range = (start: number, count: number): number[] => Array.from({ length: count }, (_, i) => start + i);\n\nfunction distinctOrdered(values: readonly number[]): number[] {\n return [...new Set(values)].toSorted((a, b) => a - b);\n}\n\n/** The orientations the selection's columns declare, before any orientation the Consumer fixed. */\nexport function declaredOrientations<Row>(\n g: BridgeGridState<Row>, ranges: readonly SelectionRange[], d: GridChartDeclarations<Row>): readonly ChartOrientation[] {\n const covered = coveredColumns(g, whole(g, ranges));\n const found: ChartOrientation[] = [];\n if (covered.some(c => isAxis(c, d))) found.push('seriesInColumns');\n if (covered.some(c => positionOf(c, d) !== undefined)) found.push('seriesInRows');\n return found;\n}\n\n// One cell is Excel's \"chart the table around it\": every column of the Window (ADR-0251).\nfunction isOneCell(ranges: readonly SelectionRange[]): boolean {\n return ranges.length === 1 && elementAt(ranges, 0).rowCount === 1 && elementAt(ranges, 0).columnCount === 1;\n}\n\nfunction whole<Row>(g: BridgeGridState<Row>, ranges: readonly SelectionRange[]): readonly SelectionRange[] {\n return isOneCell(ranges) && g.window.length > 0 && g.columns.length > 0\n ? [{ topRow: g.windowStart, leftColumn: 0, rowCount: g.window.length, columnCount: g.columns.length }]\n : ranges;\n}\n\nfunction coveredColumns<Row>(g: BridgeGridState<Row>, ranges: readonly SelectionRange[]): GridColumn<Row>[] {\n return distinctOrdered(ranges.flatMap(r => range(r.leftColumn, r.columnCount)).filter(i => i < g.columns.length))\n .map(i => elementAt(g.columns, i));\n}\n\nfunction isFirstTier(group: GridHeaderGroup): boolean {\n return group.tier === undefined || group.tier === 1;\n}\n\n// The Header Group a column stands under in the tier above the header row; empty for none, which is the\n// contract of RowSeries.group and of a panel (ADR-0251).\nfunction groupOf(groups: readonly GridHeaderGroup[], column: string): string {\n const group = groups.find(x => isFirstTier(x) && x.columns.includes(column));\n return group === undefined ? '' : group.label;\n}\n\n/**\n * Reads `selection`, taken under `version`, as `orientation`; into `target` when the series are added to a chart\n * already drawn (U7).\n */\nexport async function readSelection<Row>(\n g: BridgeGridState<Row>, selection: readonly SelectionRange[], version: number, d: GridChartDeclarations<Row>,\n orientation: ChartOrientation | undefined, target: ChartTarget | undefined): Promise<SelectionReading> {\n if (selection.length === 0) return refused('Nothing is selected.');\n // The gesture carries the order it was taken against; another order now means its positions name other\n // rows (spine rule 6).\n if (version !== g.rowSequenceVersion) return refused(stale);\n if (isOneCell(selection) && g.window.length === 0) return refused('The grid shows no rows to chart.');\n\n const oneCell = isOneCell(selection);\n const ranges = whole(g, selection);\n const covered = coveredColumns(g, ranges);\n const declared = declaredOrientations(g, ranges, d);\n\n let chosen: ChartOrientation;\n if (target !== undefined) {\n // An added series is read the target's way; a selection that declares only the other way is a curve\n // into a history, or a history into a curve, and is refused by name (ADR-0258).\n if (declared.length > 0 && !declared.includes(target.chart.orientation)) {\n return refused(target.chart.orientation === 'seriesInColumns'\n ? `The selection charts curves across declared positions, but '${target.name}' is drawn along ${axisHeader(g, target.chart)}.`\n : `The selection charts along ${headers(covered.filter(c => isAxis(c, d)))}, but '${target.name}' is drawn across declared positions.`);\n }\n chosen = target.chart.orientation;\n } else {\n const fixed = orientation ?? d.orientation ?? (declared.length === 1 ? elementAt(declared, 0) : undefined);\n if (fixed === undefined) {\n return refused(declared.length === 0\n ? 'The selection has no axis column (dates or numbers) and no columns with declared positions, so it has no horizontal axis.'\n : 'The selection can be charted with series in columns or in rows; choose one.');\n }\n chosen = fixed;\n }\n\n const positions = distinctOrdered(ranges.flatMap(r => range(r.topRow, r.rowCount)));\n const rows = await rowsAt(g, positions);\n if (rows === 'moved') return refused(stale);\n if (rows === undefined) return refused('The grid could not hand over every selected row; select fewer rows.');\n\n const made = chosen === 'seriesInColumns'\n ? columnsChart(g, ranges, covered, rows, d, oneCell, target)\n : rowsChart(g, ranges, covered, rows, d, oneCell, target);\n if (made.chart === undefined) return made;\n\n let chart = made.chart;\n if (target !== undefined) {\n chart = Object.freeze({ ...target.chart, series: Object.freeze([...target.chart.series, ...chart.series]) });\n }\n try {\n chart = ownPanelsForDiffs(g, chart, d, target === undefined ? 0 : target.chart.series.length);\n drawGridChart(g.columns, g.groups, chart, d);\n // oxlint-disable-next-line ex-grid/no-catch -- ADR-0258: a definition refused is the selection's refusal, said by name; anything else is rethrown\n } catch (error) {\n if (error instanceof ChartRefusedError) return refused(error.message);\n throw error;\n }\n return Object.freeze({ chart });\n}\n\n/** The axis column a chart of series in columns is drawn along; one that names none is the caller's defect. */\nfunction axisColumnOf(chart: GridChart): string {\n if (chart.axisColumn === undefined) {\n throw new TypeError('A chart of series in columns names its axis column (axisColumn), as the bridge makes one (ADR-0258).');\n }\n return chart.axisColumn;\n}\n\nfunction axisHeader<Row>(g: BridgeGridState<Row>, chart: GridChart): string {\n const name = axisColumnOf(chart);\n const column = g.columns.find(c => c.name === name);\n return column === undefined ? name : headerOf(column);\n}\n\n// The rows at `positions`, from the Window or fetched; `undefined` where the source cannot hand them all over, and\n// `moved` where the order moved while a fetch was out, so the rows fetched and the Window's stand under two\n// orders and name rows the user never selected (spine rule 6).\nasync function rowsAt<Row>(g: BridgeGridState<Row>, positions: readonly number[]): Promise<HeldRows<Row> | 'moved' | undefined> {\n const rows = new Map<number, { readonly row: Row }>();\n const end = g.windowStart + g.window.length;\n for (const run of runs(positions)) {\n if (run.start >= g.windowStart && run.start + run.count <= end) {\n for (let i = 0; i < run.count; i++) rows.set(run.start + i, { row: itemAt(g.window, run.start + i - g.windowStart) });\n continue;\n }\n if (g.fetch === undefined) return undefined;\n const fetched = await g.fetch(run);\n if (g.versionNow() !== g.rowSequenceVersion) return 'moved';\n if (fetched.length < run.count) return undefined;\n for (let i = 0; i < run.count; i++) rows.set(run.start + i, { row: itemAt(fetched, i) });\n }\n return rows;\n}\n\n// The rows handed over, by position: each in a box, so a Consumer's row that is itself undefined is not a miss.\ntype HeldRows<Row> = ReadonlyMap<number, { readonly row: Row }>;\n\nfunction rowAt<Row>(rows: HeldRows<Row>, position: number): Row {\n return defined(rows.get(position), `the row at ${position}`).row;\n}\n\nfunction runs(positions: readonly number[]): RowRange[] {\n const found: RowRange[] = [];\n for (let i = 0; i < positions.length;) {\n let j = i;\n while (j + 1 < positions.length && elementAt(positions, j + 1) === elementAt(positions, j) + 1) j++;\n found.push({ start: elementAt(positions, i), count: j - i + 1 });\n i = j + 1;\n }\n return found;\n}\n\nfunction columnsChart<Row>(\n g: BridgeGridState<Row>, ranges: readonly SelectionRange[], covered: readonly GridColumn<Row>[], rows: HeldRows<Row>,\n d: GridChartDeclarations<Row>, oneCell: boolean, target: ChartTarget | undefined): SelectionReading {\n const axes = covered.filter(c => isAxis(c, d));\n let axis: GridColumn<Row>;\n if (target !== undefined) {\n const name = axisColumnOf(target.chart);\n const found = g.columns.find(c => c.name === name);\n if (found === undefined) return refused(`'${target.name}' is drawn along ${name}, which is no longer in the grid.`);\n axis = found;\n const others = axes.filter(c => c.name !== found.name);\n if (others.length > 0) {\n return refused(`The selection charts along ${headers(others)}, but '${target.name}' is drawn along ${headerOf(found)}.`);\n }\n } else {\n if (axes.length === 0) return refused('The selection has no axis column (dates or numbers) to put along the horizontal axis.');\n if (axes.length > 1) return refused(`The selection has ${axes.length} axis columns (${headers(axes)}); choose one for the horizontal axis.`);\n axis = elementAt(axes, 0);\n }\n\n const others = covered.filter(c => c.name !== axis.name);\n const notNumbers = others.filter(c => !isNumber(c));\n if (notNumbers.length > 0 && !oneCell) return refused(`${headers(notNumbers)} cannot be plotted: not a number column.`);\n const figures = others.filter(c => isNumber(c));\n if (figures.length === 0) return refused(`The selection has only ${headerOf(axis)}; select the figures to plot beside it.`);\n\n const series: GridChartSeries[] = [];\n for (const column of figures) {\n if (target?.chart.series.some(s => s.type === 'column' && s.column === column.name) === true) {\n return refused(`${headerOf(column)} is already in '${target.name}'.`);\n }\n const index = g.columns.indexOf(column);\n const keyed: KeyedPosition[] = [];\n const seen = new Set<RowKey>();\n const at = distinctOrdered(ranges.filter(r => index >= r.leftColumn && index <= r.leftColumn + r.columnCount - 1)\n .flatMap(r => range(r.topRow, r.rowCount)));\n for (const position of at) {\n const row = rowAt(rows, position);\n const key = d.rowKey(row);\n if (seen.has(key)) continue;\n seen.add(key);\n const x = axisX(axis.value(row));\n if (x === undefined) return refused(`A selected row has no ${headerOf(axis)}, so it has no place along the axis.`);\n keyed.push(Object.freeze({ key, x }));\n }\n const made: ColumnSeries = Object.freeze({\n type: 'column', id: column.name, panel: groupOf(g.groups, column.name), column: column.name, rows: Object.freeze(keyed),\n });\n series.push(made);\n }\n return Object.freeze({ chart: Object.freeze({ orientation: 'seriesInColumns', axisColumn: axis.name, series: Object.freeze(series) }) });\n}\n\nfunction rowsChart<Row>(\n g: BridgeGridState<Row>, ranges: readonly SelectionRange[], covered: readonly GridColumn<Row>[], rows: HeldRows<Row>,\n d: GridChartDeclarations<Row>, oneCell: boolean, target: ChartTarget | undefined): SelectionReading {\n // A number column with no position was chosen and cannot be drawn on this axis: refused by name, not\n // dropped (ADR-0251). A text or date column names the row, and is not charted.\n const unpositioned = covered.filter(c => isNumber(c) && positionOf(c, d) === undefined);\n if (unpositioned.length > 0 && !oneCell) {\n return refused(`${headers(unpositioned)} has no declared position on the ${title(d)} axis, so it cannot be drawn here.`);\n }\n\n const all = g.columns.filter(c => positionOf(c, d) !== undefined);\n const chosen = covered.filter(c => positionOf(c, d) !== undefined);\n if (chosen.length === 0) return refused(`The selection covers no column with a position on the ${title(d)} axis.`);\n // A curve needs two points: a selection over one positioned column stands for its rows' whole curves.\n const wholeCurves = chosen.length <= 1;\n const groups = [...new Set(all.map(c => groupOf(g.groups, c.name)))];\n\n const series: GridChartSeries[] = [];\n const seen = new Set<RowKey>();\n const curves = new Set<string>();\n for (const position of distinctOrdered(ranges.flatMap(r => range(r.topRow, r.rowCount)))) {\n const row = rowAt(rows, position);\n const key = d.rowKey(row);\n if (seen.has(key)) continue;\n seen.add(key);\n const name = d.rowName === undefined ? writeObject(key) : d.rowName(row);\n for (const group of groups) {\n let inGroup = (wholeCurves ? all : chosen).filter(c => groupOf(g.groups, c.name) === group);\n if (inGroup.length === 0) continue;\n if (inGroup.length === 1 && !wholeCurves) inGroup = all.filter(c => groupOf(g.groups, c.name) === group);\n if (target?.chart.series.some(s => s.type === 'row' && s.rowKey === key && s.group === group) === true) {\n return refused(`${label(name, group)} is already in '${target.name}'.`);\n }\n // What makes a group one curve does not depend on the row: checked once a group.\n if (!curves.has(group)) {\n curves.add(group);\n const notOne = curveRefusal(inGroup, group, d);\n if (notOne !== undefined) return refused(notOne);\n }\n const ordered = inGroup\n .map(c => ({ name: c.name, at: definedPosition(c, d) }))\n .toSorted((a, b) => a.at - b.at)\n .map(c => c.name);\n const id = group.length === 0 ? writeObject(key) : `${writeObject(key)} \u00B7 ${group}`;\n const made: RowSeries = Object.freeze({ type: 'row', id, panel: '', rowKey: key, name, group, columns: Object.freeze(ordered) });\n series.push(made);\n }\n }\n return Object.freeze({ chart: Object.freeze({ orientation: 'seriesInRows', series: Object.freeze(series) }) });\n}\n\n// A positioned column's position: only columns with one reach here.\nfunction definedPosition<Row>(c: GridColumn<Row>, d: GridChartDeclarations<Row>): number {\n const at = positionOf(c, d);\n if (at === undefined) throw new Error(`Internal: column '${c.name}' was taken as positioned and has no position.`);\n return at;\n}\n\n// Why a group's columns are not one curve, or undefined: they mix Series Kinds, or read zero differently\n// (ADR-0253, ADR-0258), each column's declaration resolved by its Series Kind's default.\nfunction curveRefusal<Row>(columns: readonly GridColumn<Row>[], group: string, d: GridChartDeclarations<Row>): string | undefined {\n const name = group.length === 0 ? 'The positioned columns' : group;\n if (new Set(columns.map(c => kindOf(c.name, d))).size > 1) {\n return `${name} mix Series Kinds (${headers(columns)}), so they are not one curve.`;\n }\n const fromZero = columns.filter(c => reachesZero(c.name, d));\n const awayFromZero = columns.filter(c => !reachesZero(c.name, d));\n if (fromZero.length > 0 && awayFromZero.length > 0) {\n return `${name} are declared both from zero (${headers(fromZero)}) and away from it (${headers(awayFromZero)}), so they are not one curve.`;\n }\n return undefined;\n}\n\n// A column's Series Kind, or undefined where the Consumer declared none (C#'s SeriesKind.Undeclared).\nfunction kindOf<Row>(column: string, d: GridChartDeclarations<Row>): SeriesKind | undefined {\n return d.kindOf === undefined ? undefined : d.kindOf(column);\n}\n\nfunction fromZeroOf<Row>(column: string, d: GridChartDeclarations<Row>): boolean | undefined {\n return d.fromZeroOf === undefined ? undefined : d.fromZeroOf(column);\n}\n\n// Whether a column's values are read from zero: its declaration, or its Series Kind's default (ADR-0253), as\n// a ChartSeries resolves it; a kind not declared takes a Level's.\nfunction reachesZero<Row>(column: string, d: GridChartDeclarations<Row>): boolean {\n const kind = kindOf(column, d);\n const fromZero = fromZeroOf(column, d);\n return kind === 'amountPerPeriod'\n || (kind === 'observation' || kind === 'priceRange' ? fromZero === true : fromZero !== false);\n}\n\nfunction title<Row>(d: GridChartDeclarations<Row>): string {\n const { positionTitle = '' } = d;\n return positionTitle.length === 0 ? 'positions\\'' : positionTitle;\n}\n\nfunction label(name: string, group: string): string {\n return group.length === 0 ? name : `${name} \u00B7 ${group}`;\n}\n\n// A series with negative values beside positive ones (a Diff) goes to a panel of its own by default, because\n// aligning zeros for it costs the other series half the panel (ADR-0251). Decided once, when the series is\n// made, so a recalculation never moves it between panels.\nfunction ownPanelsForDiffs<Row>(g: BridgeGridState<Row>, chart: GridChart, d: GridChartDeclarations<Row>, kept: number): GridChart {\n const definition = drawGridChart(g.columns, g.groups, chart, d, false);\n const mixed = (i: number): boolean => {\n const values = elementAt(definition.series, i).points.flatMap(p => (p.y === null ? [] : [toNumber(p.y)]));\n return values.some(v => v < 0) && values.some(v => v > 0);\n };\n const series = [...chart.series];\n for (let i = kept; i < series.length; i++) {\n const panel = elementAt(series, i).panel;\n if (!mixed(i) || !series.some((s, j) => j !== i && s.panel === panel)) continue;\n series[i] = Object.freeze({ ...elementAt(series, i), panel: elementAt(definition.series, i).name });\n }\n return Object.freeze({ ...chart, series: Object.freeze(series) });\n}\n\n/** One series as the bridge draws it, before its Series Kind is checked: `undefined` where none is declared. */\nexport interface DrawnSeries {\n readonly id: string;\n readonly name: string;\n readonly kind: SeriesKind | undefined;\n readonly fromZero: boolean | undefined;\n readonly panel: string;\n readonly keys: AppearanceKeys;\n readonly points: readonly ChartPoint[];\n readonly format: ((value: unknown) => string) | undefined;\n}\n\n/** What a GridChart stands for now, before it is made a Chart Definition: what two drawings are compared by. */\nexport interface Drawing {\n readonly axis: ChartAxisOptions;\n readonly series: readonly DrawnSeries[];\n readonly notes: readonly string[];\n}\n\n/**\n * What `chart` stands for now: each value read by Row Key from the Consumer's data (ADR-0258), a row that no\n * longer exists a gap, and a Note that says how many.\n */\nexport function drawingOf<Row>(\n columns: readonly GridColumn<Row>[], groups: readonly GridHeaderGroup[], chart: GridChart, d: GridChartDeclarations<Row>): Drawing {\n const byName = new Map(columns.map(c => [c.name, c] as const));\n const gone = new Set<RowKey>();\n const missing: string[] = [];\n const rowOf = (key: RowKey): Row | undefined => {\n const row = d.rowOf(key);\n if (row === undefined) gone.add(key);\n return row;\n };\n\n let axis: ChartAxisOptions;\n const series: DrawnSeries[] = [];\n if (chart.orientation === 'seriesInColumns') {\n const name = axisColumnOf(chart);\n const x = byName.get(name);\n if (x === undefined) throw new ChartRefusedError(`The chart is drawn along ${name}, which is no longer in the grid.`);\n axis = { values: x.type === 'date' ? 'dates' : 'numbers', title: headerOf(x) };\n for (const s of chart.series) {\n if (s.type !== 'column') continue;\n const column = byName.get(s.column);\n if (column === undefined) missing.push(s.column);\n const points = s.rows.map((r): ChartPoint => {\n const row = rowOf(r.key);\n if (row === undefined) return Object.freeze({ x: r.x, y: null });\n return Object.freeze({ x: axisX(x.value(row)) ?? r.x, y: column === undefined ? null : valueOf(column.value(row)) });\n }).toSorted((a, b) => a.x - b.x);\n const path = groups.filter(gr => gr.columns.includes(s.column))\n .toSorted((a, b) => tierOf(b) - tierOf(a))\n .map(gr => gr.label);\n const header = column === undefined ? s.column : headerOf(column);\n const group = groupOf(groups, s.column);\n series.push(Object.freeze({\n id: s.id,\n name: [...path, header].join(' \u00B7 '),\n kind: kindOf(s.column, d),\n fromZero: fromZeroOf(s.column, d),\n panel: s.panel,\n keys: Object.freeze(group.length === 0 ? { colour: header } : { colour: header, lineStyle: group }),\n points: Object.freeze(points),\n format: column?.format,\n }));\n }\n } else {\n const used = new Map<string, readonly [number, string]>();\n for (const s of chart.series) {\n if (s.type !== 'row') continue;\n for (const n of s.columns) {\n const c = byName.get(n);\n if (c === undefined) continue;\n const named = [declaredPosition(c.name, d), headerOf(c)] as const;\n used.set(`${named[0]}\\u0000${named[1]}`, named);\n }\n }\n const { positionTitle = '', positionScale = 'proportional' } = d;\n axis = { values: 'numbers', title: positionTitle, scale: positionScale, named: [...used.values()].toSorted((a, b) => a[0] - b[0]) };\n for (const s of chart.series) {\n if (s.type !== 'row') continue;\n const row = rowOf(s.rowKey);\n const cols: GridColumn<Row>[] = [];\n for (const n of s.columns) {\n const c = byName.get(n);\n if (c === undefined) missing.push(n);\n else cols.push(c);\n }\n const points = cols\n .map((c): ChartPoint => Object.freeze({ x: declaredPosition(c.name, d), y: row === undefined ? null : valueOf(c.value(row)) }))\n .toSorted((a, b) => a.x - b.x);\n const name = row === undefined || d.rowName === undefined ? s.name : d.rowName(row);\n const first = cols[0];\n // Declarations are the Consumer's and may change after the chart was made: a curve whose columns no\n // longer read zero alike is refused, never drawn by one column's (ADR-0258).\n if (new Set(cols.map(c => reachesZero(c.name, d))).size > 1) {\n throw new ChartRefusedError(`${label(s.name, s.group)}: its columns are now declared both from zero and away from it, so they are not one curve.`);\n }\n series.push(Object.freeze({\n id: s.id,\n name: label(name, s.group),\n kind: first === undefined ? undefined : kindOf(first.name, d),\n fromZero: first === undefined ? undefined : fromZeroOf(first.name, d),\n panel: s.panel,\n keys: Object.freeze(s.group.length === 0 ? { colour: name } : { colour: name, lineStyle: s.group }),\n points: Object.freeze(points),\n format: first?.format,\n }));\n }\n }\n\n const notes: string[] = [];\n // A row that no longer exists is a gap, never zero, and the chart says so (ADR-0258, M3-Q3).\n if (gone.size === 1) notes.push('1 of the selected rows no longer exists.');\n else if (gone.size > 1) notes.push(`${gone.size} of the selected rows no longer exist.`);\n for (const name of new Set(missing)) notes.push(`${name} is no longer in the grid, so it is drawn without values.`);\n return Object.freeze({ axis, series: Object.freeze(series), notes: Object.freeze(notes) });\n}\n\nfunction tierOf(group: GridHeaderGroup): number {\n const { tier = 1 } = group;\n return tier;\n}\n\n// A column's declared position along a curve's axis. C#'s SelectionReader reads a position the Consumer no\n// longer declares as 0 (`PositionOf?.Invoke(c.Name) ?? 0`); the two cores draw alike, and the bridge's\n// report names it as a defect to settle rather than a rule (spine rule 1).\nfunction declaredPosition<Row>(column: string, d: GridChartDeclarations<Row>): number {\n // oxlint-disable-next-line ex-grid/no-stand-in-default -- parity with C#'s SelectionReader.Draw, a reported defect (see above)\n return d.positionOf?.(column) ?? 0;\n}\n\nfunction seriesOptions(s: DrawnSeries, kind: SeriesKind): ChartSeriesOptions {\n return {\n id: s.id, name: s.name, kind, panel: s.panel, keys: s.keys, points: s.points,\n ...(s.fromZero === undefined ? {} : { fromZero: s.fromZero }),\n ...(s.format === undefined ? {} : { format: s.format }),\n };\n}\n\n/**\n * The Chart Definition a drawing stands for. Read with `validate` false, a series with no Series Kind is read\n * as a Level, to see its values' signs before any is checked; otherwise it is refused by name, as the\n * definition refuses one, after every series before it was checked.\n */\nexport function definitionOf(drawing: Drawing, validate: boolean): ChartDefinition {\n const undeclared = validate ? drawing.series.findIndex(s => s.kind === undefined) : -1;\n if (undeclared >= 0) {\n // The series before it are checked first, as the definition checks them in order; then it is refused\n // in the definition's own words (definition.ts).\n const before = drawing.series.slice(0, undeclared);\n // oxlint-disable-next-line eslint/no-new -- made only for what it refuses of the series before the undeclared one\n new ChartDefinition({ axis: drawing.axis, series: before.map(s => seriesOptions(s, kindOrLevel(s))), notes: drawing.notes });\n const s = elementAt(drawing.series, undeclared);\n if (before.some(b => b.id === s.id)) {\n throw new ChartRefusedError(`Two series are named '${s.id}'; each series needs an identity of its own.`);\n }\n throw new ChartRefusedError(`'${s.name}' declares no Series Kind: say whether it is a Level, a Rate over an interval or an Amount per period.`);\n }\n return new ChartDefinition({ axis: drawing.axis, series: drawing.series.map(s => seriesOptions(s, kindOrLevel(s))), notes: drawing.notes });\n}\n\n// Only reached for a series whose kind is declared, or where an undeclared one is read as a Level to see its\n// signs (ADR-0251).\nfunction kindOrLevel(s: DrawnSeries): SeriesKind {\n return s.kind === undefined ? 'level' : s.kind;\n}\n\n/** The Chart Definition `chart` stands for now (ADR-0258). */\nexport function drawGridChart<Row>(\n columns: readonly GridColumn<Row>[], groups: readonly GridHeaderGroup[], chart: GridChart, d: GridChartDeclarations<Row>,\n validate = true): ChartDefinition {\n return definitionOf(drawingOf(columns, groups, chart, d), validate);\n}\n\n/** Whether two drawings are the same: what a chart is handed again unchanged, so it skips its render (ADR-0252). */\nexport function sameDrawing(a: Drawing, b: Drawing): boolean {\n return sameAxis(a.axis, b.axis)\n && a.series.length === b.series.length && a.series.every((s, i) => sameSeries(s, elementAt(b.series, i)))\n && a.notes.length === b.notes.length && a.notes.every((n, i) => n === b.notes[i]);\n}\n\nfunction sameAxis(a: ChartAxisOptions, b: ChartAxisOptions): boolean {\n const an = a.named === undefined ? [] : a.named;\n const bn = b.named === undefined ? [] : b.named;\n return a.values === b.values && a.title === b.title && a.scale === b.scale\n && an.length === bn.length && an.every((n, i) => n[0] === elementAt(bn, i)[0] && n[1] === elementAt(bn, i)[1]);\n}\n\nfunction sameSeries(a: DrawnSeries, b: DrawnSeries): boolean {\n return a.id === b.id && a.name === b.name && a.kind === b.kind && a.fromZero === b.fromZero && a.panel === b.panel\n && a.keys.colour === b.keys.colour && a.keys.lineStyle === b.keys.lineStyle && a.format === b.format\n && a.points.length === b.points.length\n && a.points.every((p, i) => p.x === elementAt(b.points, i).x && p.y === elementAt(b.points, i).y);\n}\n\n/** A cell's value as a chart value, in the type it came in (ADR-0251); null for an empty or non-numeric value. */\nexport function valueOf(value: unknown): ChartValue | null {\n if (typeof value === 'bigint') return value;\n return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\n// The day number of 1970-01-01, and a day's length, for an instant read in UTC, as the grid shows one.\nconst epochDay = dayNumber(1970, 1, 1);\nconst msPerDay = 86_400_000;\n\n/**\n * An axis cell's value as a position: a date's day number, or a number; `undefined` for one that has no place.\n * A `Temporal.PlainDate`, `PlainDateTime` or `ZonedDateTime` is its own ISO day, as C#'s `DateOnly`, `DateTime`\n * and `DateTimeOffset` are; a `Temporal.Instant` or a `Date` holds no offset, so it is its UTC day, the day the\n * grid shows it on (display-text.ts).\n */\nexport function axisX(value: unknown): number | undefined {\n if (typeof value === 'object' && value !== null) {\n switch (Object.prototype.toString.call(value)) {\n case '[object Temporal.PlainDate]':\n case '[object Temporal.PlainDateTime]':\n case '[object Temporal.ZonedDateTime]':\n return isoDayNumber(value);\n case '[object Temporal.Instant]':\n return utcDayNumber(Reflect.get(value, 'epochMilliseconds'));\n case '[object Date]':\n return value instanceof Date ? utcDayNumber(value.getTime()) : undefined;\n default:\n return undefined;\n }\n }\n const v = valueOf(value);\n return v === null ? undefined : toNumber(v);\n}\n\nfunction isoDayNumber(date: object): number | undefined {\n const iso = Reflect.get(date, 'calendarId') === 'iso8601' ? date : inIsoCalendar(date);\n if (iso === undefined) return undefined;\n const [year, month, day] = ['year', 'month', 'day'].map((name): unknown => Reflect.get(iso, name));\n return typeof year === 'number' && typeof month === 'number' && typeof day === 'number'\n && Number.isSafeInteger(year) && Number.isSafeInteger(month) && Number.isSafeInteger(day)\n ? dayNumber(year, month, day)\n : undefined;\n}\n\nfunction inIsoCalendar(date: object): object | undefined {\n const convert: unknown = Reflect.get(date, 'withCalendar');\n if (typeof convert !== 'function') return undefined;\n const iso: unknown = convert.call(date, 'iso8601');\n return typeof iso === 'object' && iso !== null ? iso : undefined;\n}\n\nfunction utcDayNumber(milliseconds: unknown): number | undefined {\n return typeof milliseconds === 'number' && Number.isFinite(milliseconds) ? Math.floor(milliseconds / msPerDay) + epochDay : undefined;\n}\n", "// The grid's side of a chart, ready-made (ADR-0258): the counterpart of C#'s GridChartBridge. ExGrid does not\n// know it exists (ADR-0250's dependency direction); where the chart is shown is the Consumer's.\nimport type {\n CellPosition, GridColumn, GridCommand, GridContextMenuContext, GridHeaderGroup, GridSource, SelectionRange,\n} from '@ex-grid/core';\nimport type { ChartDefinition } from '../definition';\nimport type { ChartPointClick } from '../dom/chart-element';\nimport type { ChartOrientation, ChartTarget, GridCell, GridChart } from './grid-chart';\nimport type { GridChartDeclarations } from './grid-chart-declarations';\nimport {\n axisX, declaredOrientations, definitionOf, drawingOf, readSelection, sameDrawing, type BridgeGridState, type Drawing,\n} from './selection-reader';\n\nconst addPrefix = 'exchart.add:';\n\n/** The stable identities of the commands a {@link GridChartBridge} adds to a grid's menu (ADR-0036). */\nexport const gridChartCommandIds = Object.freeze({\n /** \"Chart\": the selection in the one orientation its columns declare. */\n chart: 'exchart.chart',\n /** \"Series in columns\", offered beside `inRows` only when a selection declares both. */\n inColumns: 'exchart.chart.columns',\n /** \"Series in rows\", offered beside `inColumns` only when a selection declares both. */\n inRows: 'exchart.chart.rows',\n /** The prefix of \"Add to chart: <name>\"; the target's name follows it. */\n addPrefix,\n} as const);\n\n/** The wording of one of the bridge's commands, for the grid's `commandLabel`; `undefined` for any other. */\nexport function gridChartCommandLabel(id: string): string | undefined {\n switch (id) {\n case gridChartCommandIds.chart: return 'Chart';\n case gridChartCommandIds.inColumns: return 'Series in columns';\n case gridChartCommandIds.inRows: return 'Series in rows';\n default: return id.startsWith(addPrefix) ? `Add to chart: ${id.slice(addPrefix.length)}` : undefined;\n }\n}\n\n/**\n * The grid whose selections are charted, as the Consumer handed it to `createGrid` or `<ExGrid>`: its columns\n * and Header Groups as they stand, and the Grid Source its rows come from, whose snapshot is the Window and the\n * Row Sequence Version the grid shows.\n */\nexport interface GridChartGrid<Row> {\n /** The columns, in display order. */\n readonly columns: readonly GridColumn<Row>[];\n /** The Header Groups over them; none unless given. */\n readonly headerGroups?: readonly GridHeaderGroup[];\n /** The source the grid reads its rows from. */\n readonly source: GridSource<Row>;\n}\n\n/**\n * Where the bridge asks the grid to put the Focus (ADR-0258, M3-Q6): the cell a point stands for, as the\n * Selection, under the Row Sequence Version the bridge found it in, which the grid's placement refuses under\n * another order.\n */\nexport interface GridSelectionPlacement {\n /** The Selection to place: the one cell. */\n readonly range: SelectionRange;\n /** Where the Focus goes: the same cell. */\n readonly focus: CellPosition;\n /** The Row Sequence Version the positions are written in. */\n readonly rowSequenceVersion: number;\n}\n\n/** What a {@link GridChartBridge} is made with. */\nexport interface GridChartBridgeOptions<Row> {\n /** What the Consumer declared for the grid's selections. */\n readonly declarations: GridChartDeclarations<Row>;\n /** The grid whose selections are charted, read each time it is needed; `undefined` while there is none. */\n readonly grid: () => GridChartGrid<Row> | undefined;\n /** The open charts the menu offers \"Add to chart\" for (ADR-0258, U7), in the menu's order, read each time the\n * menu opens; none unless given. */\n readonly targets?: () => readonly ChartTarget[];\n /** Hears a chart made from the selection; the Consumer decides where it is shown. */\n readonly onChart?: (chart: GridChart) => void;\n /** Hears a target and the chart it becomes with the selection's series added. */\n readonly onAdded?: (target: ChartTarget, chart: GridChart) => void;\n /** Hears the sentence that says why a selection was not charted, or a point not shown in the grid. */\n readonly onRefused?: (why: string) => void;\n /**\n * Places the Selection and the Focus on a cell and scrolls the grid to it, as C#'s `PlaceSelectionAsync`\n * does, answering whether it was placed: the grid's `placeSelection`, reached through its handle (or\n * `ExGridApi` under React), which the bridge does not hold. Without it `showInGrid` refuses to be asked.\n */\n readonly placeSelection?: (placement: GridSelectionPlacement) => boolean | Promise<boolean>;\n}\n\n/**\n * The grid's side of a chart, ready-made (ADR-0258): context-menu commands a Consumer adds to a grid in one\n * line, which turn the selection into a {@link GridChart}, and the reading of that chart, by Row Key from the\n * Consumer's data, into the Chart Definition an ExChart draws. The grid does not know it exists; where the\n * chart is shown is the Consumer's.\n */\nexport class GridChartBridge<Row> {\n readonly #options: GridChartBridgeOptions<Row>;\n readonly #drawn = new WeakMap<GridChart, { readonly drawing: Drawing; readonly definition: ChartDefinition }>();\n\n /** A bridge that reads selections by `options.declarations`. */\n constructor(options: GridChartBridgeOptions<Row>) {\n // Checked as an untyped caller may hand them, where they arrive (CONVENTIONS.md).\n const given: { readonly declarations?: unknown; readonly grid?: unknown } = options;\n if (typeof given.grid !== 'function') throw new TypeError('A GridChartBridge reads its grid through a function: grid: () => the grid.');\n if (typeof given.declarations !== 'object' || given.declarations === null) {\n throw new TypeError('A GridChartBridge reads selections by declarations: { rowKey, rowOf, ... } (ADR-0258).');\n }\n const { rowKey, rowOf }: { readonly rowKey?: unknown; readonly rowOf?: unknown } = given.declarations;\n if (typeof rowKey !== 'function' || typeof rowOf !== 'function') {\n throw new TypeError('A chart follows its rows by Row Key: declarations name rowKey and rowOf, both functions (ADR-0258).');\n }\n this.#options = Object.freeze({ ...options });\n }\n\n /** What the Consumer declared for the grid's selections. */\n get declarations(): GridChartDeclarations<Row> {\n return this.#options.declarations;\n }\n\n /**\n * The commands for the grid's `contextCommands`, worded by {@link gridChartCommandLabel}: \"Chart\", or \"Series\n * in columns\" and \"Series in rows\" when the selection declares both, and \"Add to chart\" for each target. It is\n * one function for the bridge's life, so it can be handed to the grid as it is on every render (ADR-0003).\n */\n readonly commands = (context: GridContextMenuContext<Row>): readonly GridCommand[] => {\n const enabled = context.selection.length > 0;\n const g = this.#state();\n const both = this.declarations.orientation === undefined && g !== undefined\n && declaredOrientations(g, context.selection, this.declarations).length === 2;\n // The order the menu opened under, as the source says it: the Selection in the context was taken against\n // it, and a command run after it moved is refused (spine rule 6). The grid's own written version carries\n // an offset past a change of source, which the source cannot be compared with.\n const opened = g === undefined ? undefined : g.rowSequenceVersion;\n const command = (id: string, orientation: ChartOrientation | undefined, target: ChartTarget | undefined): GridCommand =>\n Object.freeze({ id, enabled, invoke: () => { void this.#make(context.selection, opened, orientation, target); } });\n const commands = both\n ? [command(gridChartCommandIds.inColumns, 'seriesInColumns', undefined), command(gridChartCommandIds.inRows, 'seriesInRows', undefined)]\n : [command(gridChartCommandIds.chart, undefined, undefined)];\n const targets = this.#options.targets === undefined ? [] : this.#options.targets();\n const names = new Set<string>();\n for (const target of targets) {\n // A target is told apart by its name, in the menu and in its command's id.\n if (names.has(target.name)) throw new Error(`Two chart targets are named '${target.name}'; each target of \"Add to chart\" has a name of its own (ADR-0258).`);\n names.add(target.name);\n commands.push(command(addPrefix + target.name, undefined, target));\n }\n return Object.freeze(commands);\n };\n\n /**\n * The Chart Definition `chart` stands for now, read by Row Key from the declarations' `rowOf`: a recalculated\n * value is redrawn, and a row that no longer exists is a gap with a Note (ADR-0258). While nothing it reads\n * has changed, the definition last returned for the same chart is returned again, so the chart skips its\n * render (ADR-0252). A chart that can no longer be drawn, such as one whose axis column left the grid, is\n * refused with a `ChartRefusedError`.\n */\n draw(chart: GridChart): ChartDefinition {\n const g = this.#state();\n if (g === undefined) throw new Error('The bridge has no grid to draw from; its grid() answered none.');\n const drawing = drawingOf(g.columns, g.groups, chart, this.declarations);\n const last = this.#drawn.get(chart);\n if (last !== undefined && sameDrawing(last.drawing, drawing)) return last.definition;\n const definition = definitionOf(drawing, true);\n this.#drawn.set(chart, { drawing, definition });\n return definition;\n }\n\n /** The grid cell a click on a point of `chart` stands for, or `undefined` when its row no longer exists. */\n cellOf(chart: GridChart, click: ChartPointClick): GridCell | undefined {\n const d = this.declarations;\n const series = chart.series.find(s => s.id === click.seriesId);\n if (series === undefined) return undefined;\n if (series.type === 'column') {\n const axis = this.#state()?.columns.find(c => c.name === chart.axisColumn);\n for (const r of series.rows) {\n const row = d.rowOf(r.key);\n if (row === undefined) continue;\n const x = axis === undefined ? r.x : axisX(axis.value(row)) ?? r.x;\n if (x === click.position) return Object.freeze({ rowKey: r.key, column: series.column });\n }\n return undefined;\n }\n if (d.rowOf(series.rowKey) === undefined) return undefined;\n const { positionOf } = d;\n const column = positionOf === undefined ? undefined : series.columns.find(c => positionOf(c) === click.position);\n return column === undefined ? undefined : Object.freeze({ rowKey: series.rowKey, column });\n }\n\n /**\n * Scrolls the grid to the cell a click on a point stands for and puts the Focus on it (ADR-0258, M3-Q6),\n * through the Consumer's `placeSelection`. Answers whether the Focus was placed; false where the point's row\n * no longer exists.\n */\n async showInGrid(chart: GridChart, click: ChartPointClick): Promise<boolean> {\n const cell = this.cellOf(chart, click);\n if (cell === undefined) {\n this.#refuse('That point\\'s row no longer exists, so it has no cell in the grid.');\n return false;\n }\n return this.showCellInGrid(cell);\n }\n\n /**\n * Scrolls the grid to `cell` and puts the Focus on it, as a click on a point does (ADR-0258): for a chart the\n * Consumer built by hand, such as a scatter whose points carry their Row Keys, whose click names the row\n * (ADR-0290). Answers whether the Focus was placed; when the row is not among the rows the grid shows,\n * `onRefused` says so.\n */\n async showCellInGrid(cell: GridCell): Promise<boolean> {\n const place = this.#options.placeSelection;\n if (place === undefined) {\n throw new Error('The bridge was given no placeSelection, so it cannot move the grid\\'s Focus (ADR-0258, M3-Q6).');\n }\n const g = this.#state();\n if (g === undefined) {\n this.#refuse('The bridge has no grid to show the point in.');\n return false;\n }\n const column = g.columns.findIndex(c => c.name === cell.column);\n const at = g.window.findIndex(r => this.declarations.rowKey(r) === cell.rowKey);\n const row = at < 0 ? -1 : g.windowStart + at;\n if (row < 0 || column < 0) {\n this.#refuse(row < 0\n ? 'That row is not among the rows the grid holds now: it may be filtered out, or not yet loaded.'\n : `${cell.column} is not among the grid's columns.`);\n return false;\n }\n const placed = await place(Object.freeze({\n range: Object.freeze({ topRow: row, leftColumn: column, rowCount: 1, columnCount: 1 }),\n focus: Object.freeze({ row, column }),\n rowSequenceVersion: g.rowSequenceVersion,\n }));\n if (!placed) this.#refuse('The grid did not move its Focus to that point: its rows or columns changed, or an open edit held it.');\n return placed;\n }\n\n #state(): BridgeGridState<Row> | undefined {\n const grid = this.#options.grid();\n if (grid === undefined) return undefined;\n const { source } = grid;\n // Changes a live source gathered are the order's before it is read, as the grid publishes them before it\n // compares a placement (ADR-0142 D5): read without them, a position taken now would be refused by chance.\n source.publishGathered?.();\n const snapshot = source.snapshot();\n return {\n columns: grid.columns,\n groups: grid.headerGroups === undefined ? [] : grid.headerGroups,\n rowSequenceVersion: snapshot.rowSequenceVersion,\n window: snapshot.window,\n windowStart: snapshot.windowStart,\n fetch: range => source.rows(range, new AbortController().signal),\n versionNow: () => source.snapshot().rowSequenceVersion,\n };\n }\n\n async #make(selection: readonly SelectionRange[], opened: number | undefined, orientation: ChartOrientation | undefined,\n target: ChartTarget | undefined): Promise<void> {\n const g = this.#state();\n if (g === undefined || opened === undefined) {\n this.#refuse('The bridge has no grid to read the selection from.');\n return;\n }\n const read = await readSelection(g, selection, opened, this.declarations, orientation, target);\n if (read.chart === undefined) this.#refuse(read.refusal);\n else if (target !== undefined) this.#options.onAdded?.(target, read.chart);\n else this.#options.onChart?.(read.chart);\n }\n\n #refuse(why: string): void {\n this.#options.onRefused?.(why);\n }\n}\n", "// A chart made from a grid selection (ADR-0258): the set of Row Keys and columns it was made from, never the\n// positions it was painted at. The C# records are plain frozen data here, as the rest of this package's\n// vocabulary is (model.ts).\nimport type { RowKey } from '@ex-grid/core';\n\n/**\n * Whether a selection's series run down its columns or along its rows (ADR-0258). It comes from the grid's\n * declarations, never from the selection's shape: `seriesInColumns` is a history, each column a series along\n * an axis column (dates or numbers); `seriesInRows` is a curve, each row a series across columns at declared\n * positions (tenors).\n */\nexport type ChartOrientation = 'seriesInColumns' | 'seriesInRows';\n\n/** A row a series was made from, by its Row Key, with the axis value it had then. */\nexport interface KeyedPosition {\n /** The row's Row Key (ADR-0140). */\n readonly key: RowKey;\n /** The row's axis value when the chart was made, which places its gap once the row is gone. */\n readonly x: number;\n}\n\n/** A column, by its name, at the rows it was made from (series in columns). */\nexport interface ColumnSeries {\n /** Says the series is a column. */\n readonly type: 'column';\n /** The series' identity in the Chart Definition: the column's name. */\n readonly id: string;\n /** The panel it was given when it was made: its Header Group, or a panel of its own for a Diff (ADR-0251). */\n readonly panel: string;\n /** The column's name. */\n readonly column: string;\n /** The rows it is charted at, by Row Key: its own, as every Excel series has its own ranges (U8). */\n readonly rows: readonly KeyedPosition[];\n}\n\n/** A row, by its Row Key, across columns at declared positions (series in rows). */\nexport interface RowSeries {\n /** Says the series is a row. */\n readonly type: 'row';\n /** The series' identity in the Chart Definition: the row's key and its Header Group. */\n readonly id: string;\n /** The panel it was given when it was made. */\n readonly panel: string;\n /** The row's Row Key (ADR-0140). */\n readonly rowKey: RowKey;\n /** The row's name when the chart was made, kept for the legend once the row is gone. */\n readonly name: string;\n /** The Header Group the columns stand under, or empty. */\n readonly group: string;\n /** The columns it is charted across, by name, in their positions' order. */\n readonly columns: readonly string[];\n}\n\n/** One series of a {@link GridChart}, in the data's terms (ADR-0251). */\nexport type GridChartSeries = ColumnSeries | RowSeries;\n\n/**\n * A chart made from a grid selection: the set of Row Keys and columns it was made from, never the positions\n * it was painted at (ADR-0258). A recalculated value is redrawn, a row that no longer exists becomes a gap,\n * and a new row is never added. Hold it as it was handed over: the bridge knows a chart it drew before by\n * its identity.\n */\nexport interface GridChart {\n /** Whether its series are columns or rows. */\n readonly orientation: ChartOrientation;\n /** The axis column of a chart of series in columns; absent for series in rows, whose axis is the declared positions. */\n readonly axisColumn?: string;\n /** Its series, in the order they were made and added. */\n readonly series: readonly GridChartSeries[];\n}\n\n/** A chart the user registered as a target of \"Add to chart\" (ADR-0258, U7). */\nexport interface ChartTarget {\n /** The chart's name, as the menu item says it. */\n readonly name: string;\n /** The chart as it stands. */\n readonly chart: GridChart;\n}\n\n/** Where a click on a chart's point lands in the grid (ADR-0258, M3-Q6). */\nexport interface GridCell {\n /** The point's row, by its Row Key. */\n readonly rowKey: RowKey;\n /** The point's column, by its name. */\n readonly column: string;\n}\n\n/** Every Row Key some series of `chart` is charted at. */\nexport function gridChartRowKeys(chart: GridChart): ReadonlySet<RowKey> {\n const keys = new Set<RowKey>();\n for (const s of chart.series) {\n if (s.type === 'column') {\n for (const r of s.rows) keys.add(r.key);\n } else {\n keys.add(s.rowKey);\n }\n }\n return keys;\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,kBAAkB;;;ACY3B,SAAS,SAAS,OAAe,SAAyB;AACtD,QAAM,QAAQ,iCAAiC,KAAK,OAAO;AAC3D,MAAI,UAAU,MAAM;AAChB,UAAM,IAAI,MAAM,aAAa,OAAO,oCAAoC;AAAA,EAC5E;AACA,QAAM,CAAC,EAAE,OAAO,MAAM,QAAQ,IAAI;AAClC,MAAI,UAAU,UAAa,aAAa,QAAW;AAC/C,UAAM,IAAI,MAAM,aAAa,OAAO,uCAAuC;AAAA,EAC/E;AACA,SAAO;AAAA,IACH,UAAU,QAAQ,KAAK,OAAO,GAAG,OAAO,EAAE;AAAA;AAAA,IAE1C,QAA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A,QAAQ,KAAmB;AACvB,SAAK,SAAS,YAAY,GAAG;AAAA,EACjC;AACJ;;;ACtLO,SAAS,iBAAiB,OAAuC;AACpE,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,KAAK,MAAM,QAAQ;AAC1B,QAAI,EAAE,SAAS,UAAU;AACrB,iBAAW,KAAK,EAAE,KAAM,MAAK,IAAI,EAAE,GAAG;AAAA,IAC1C,OAAO;AACH,WAAK,IAAI,EAAE,MAAM;AAAA,IACrB;AAAA,EACJ;AACA,SAAO;AACX;",
|
|
6
|
+
"names": ["point", "text", "whole", "kept", "out", "position", "n", "series", "reading", "position", "n", "edge", "n", "label", "text", "position", "label", "range", "reach", "n", "missing", "point", "series", "candles", "row", "title", "n", "reachesZero", "scaled", "interval", "series", "candles", "edge", "reading", "marker", "found", "text", "markers", "candles", "series", "range", "steps", "bounds", "line", "interval", "n", "kept", "point", "valueAt", "lookOf", "keyOf", "candles", "drawingOf", "colourKeys", "sizeKeys", "sample", "point", "n", "series", "position", "row", "range", "markers", "half", "reach", "shown", "count", "title", "distinct", "interval", "kept", "cell", "line", "edge", "position", "piece", "line", "shown", "ordered", "edge", "vertical", "note", "held", "point", "found", "interval", "candles", "volume", "b", "method", "observations", "title", "plain", "series", "kept", "bounds", "label", "title", "piece", "seen", "said", "position", "checkAxisCode", "position", "title", "method", "row", "ordered", "n", "runs", "series", "reading", "text", "distinct", "placed", "label", "point", "frame", "n", "reach", "runs", "title", "method", "text", "scaled", "row", "path", "kinds", "text", "series", "found", "reading", "title", "notes", "axisTitle", "n", "defined", "method", "scaled", "marked", "yOf", "label", "interval", "row", "ticksPerDay", "line", "placed", "distinct", "upper", "bounds", "two", "kindOf", "decimalText", "numberOf", "ordered", "row", "kept", "ticksPerDay", "n", "decimalText", "text", "reading", "said", "n", "missing", "kept", "line", "method", "half", "n", "scaled", "finite", "row", "position", "n", "slot", "element", "text", "out", "label", "edge", "piece", "line", "point", "intervals", "upper", "title", "row", "reading", "place", "title", "label", "text", "position", "label", "label", "range", "text", "summary", "reading", "point", "reach", "cell", "line", "position", "piece", "candle", "series", "valueAt", "frame", "title", "slot", "field", "select", "kept", "span", "half", "shown", "row", "element", "element", "densityText", "line", "text", "tick", "labelOf", "label", "steps", "point", "row", "svgNs", "rounded", "nameOr", "title", "blank", "text", "element", "label", "point", "densityText", "setText", "method", "line", "cell", "element", "positionOf", "found", "position", "others", "series", "keyed", "row", "ordered", "kindOf", "kept", "missing", "valueOf", "path", "n", "validate", "s", "series", "row", "positionOf", "cell", "place", "placed", "range"]
|
|
7
|
+
}
|