@stacksjs/components 0.2.990 → 0.2.997
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/dist/ApiOperation-369y1zgt.stx +114 -0
- package/dist/ApiReference-ww45jj32.stx +92 -0
- package/dist/ApiSchema-dsx4tsv4.stx +47 -0
- package/dist/AreaChart-8fy34adp.stx +77 -0
- package/dist/BarChart-4xdrjhhn.stx +77 -0
- package/dist/{Combobox-9n04ec5w.stx → Combobox-fgbpxbty.stx} +174 -5
- package/dist/ComboboxOptions-sfkc98a9.stx +36 -0
- package/dist/{CommandPalette-cj6pe5ph.stx → CommandPalette-sf03s7b2.stx} +3 -1
- package/dist/LineChart-ctebkkm8.stx +77 -0
- package/dist/{List-5ey6k813.stx → List-mjkged1z.stx} +1 -1
- package/dist/{Notification-b3cz24f0.stx → Notification-1pvt347q.stx} +16 -4
- package/dist/{Popover-jjt7p7sn.stx → Popover-gntg33xd.stx} +1 -1
- package/dist/PricingPlan-h7jt2696.stx +67 -0
- package/dist/PricingTable-v3vdn6av.stx +149 -0
- package/dist/SecretField-q2xgth94.stx +219 -0
- package/dist/{Select-36s22z6d.stx → Select-yhmtvqcx.stx} +7 -4
- package/dist/Sparkline-gp859n4h.stx +29 -0
- package/dist/StatCard-gff0yx6b.stx +93 -0
- package/dist/StatGroup-e0d5dmt7.stx +17 -0
- package/dist/components/CodeBlock.d.ts +4 -1
- package/dist/components/CodeGroup.d.ts +34 -0
- package/dist/components/code-group.d.ts +19 -0
- package/dist/components/index.d.ts +2 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +25 -22
- package/dist/ui/api-reference/ApiOperation.d.ts +17 -0
- package/dist/ui/api-reference/ApiReference.d.ts +28 -0
- package/dist/ui/api-reference/ApiSchema.d.ts +17 -0
- package/dist/ui/api-reference/index.d.ts +30 -0
- package/dist/ui/api-reference/openapi.d.ts +137 -0
- package/dist/ui/chart/AreaChart.d.ts +33 -0
- package/dist/ui/chart/BarChart.d.ts +33 -0
- package/dist/ui/chart/LineChart.d.ts +33 -0
- package/dist/ui/chart/Sparkline.d.ts +19 -0
- package/dist/ui/chart/core.d.ts +111 -0
- package/dist/ui/chart/index.d.ts +51 -0
- package/dist/ui/chart/interaction.d.ts +11 -0
- package/dist/ui/combobox/Combobox.d.ts +10 -1
- package/dist/ui/combobox/ComboboxOptions.d.ts +6 -0
- package/dist/ui/combobox/index.d.ts +7 -0
- package/dist/ui/command-palette/CommandPalette.d.ts +2 -0
- package/dist/ui/input/SecretField.d.ts +56 -0
- package/dist/ui/input/index.d.ts +21 -0
- package/dist/ui/notification/Notification.d.ts +2 -0
- package/dist/ui/pricing/PricingPlan.d.ts +21 -0
- package/dist/ui/pricing/PricingTable.d.ts +50 -0
- package/dist/ui/pricing/index.d.ts +38 -0
- package/dist/ui/pricing/pricing.d.ts +64 -0
- package/dist/ui/select/Select.d.ts +2 -0
- package/dist/ui/stat/StatCard.d.ts +42 -0
- package/dist/ui/stat/StatGroup.d.ts +12 -0
- package/dist/ui/stat/format.d.ts +37 -0
- package/dist/ui/stat/index.d.ts +23 -0
- package/package.json +3 -3
- package/src/components/CodeBlock.stx +4 -1
- package/src/components/CodeGroup.stx +217 -0
- package/src/components/code-group.ts +57 -0
- package/src/components/index.ts +2 -0
- package/src/index.ts +18 -0
- package/src/ui/api-reference/ApiOperation.stx +114 -0
- package/src/ui/api-reference/ApiReference.stx +92 -0
- package/src/ui/api-reference/ApiSchema.stx +47 -0
- package/src/ui/api-reference/README.md +44 -0
- package/src/ui/api-reference/index.ts +35 -0
- package/src/ui/api-reference/openapi.ts +825 -0
- package/src/ui/chart/AreaChart.stx +77 -0
- package/src/ui/chart/BarChart.stx +77 -0
- package/src/ui/chart/LineChart.stx +77 -0
- package/src/ui/chart/README.md +97 -0
- package/src/ui/chart/Sparkline.stx +29 -0
- package/src/ui/chart/core.ts +730 -0
- package/src/ui/chart/index.ts +71 -0
- package/src/ui/chart/interaction.ts +175 -0
- package/src/ui/combobox/Combobox.stx +174 -5
- package/src/ui/combobox/ComboboxOptions.stx +20 -0
- package/src/ui/combobox/README.md +41 -0
- package/src/ui/combobox/index.ts +13 -0
- package/src/ui/command-palette/CommandPalette.stx +3 -1
- package/src/ui/input/SecretField.stx +219 -0
- package/src/ui/input/index.ts +32 -0
- package/src/ui/list/List.stx +1 -1
- package/src/ui/notification/Notification.stx +16 -4
- package/src/ui/popover/Popover.stx +1 -1
- package/src/ui/pricing/PricingPlan.stx +67 -0
- package/src/ui/pricing/PricingTable.stx +149 -0
- package/src/ui/pricing/README.md +74 -0
- package/src/ui/pricing/index.ts +49 -0
- package/src/ui/pricing/pricing.ts +177 -0
- package/src/ui/select/Select.stx +7 -4
- package/src/ui/stat/README.md +60 -0
- package/src/ui/stat/StatCard.stx +93 -0
- package/src/ui/stat/StatGroup.stx +17 -0
- package/src/ui/stat/format.ts +147 -0
- package/src/ui/stat/index.ts +38 -0
- package/dist/ComboboxOptions-zhr9b6rx.stx +0 -16
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chart engine behind `<LineChart>`, `<AreaChart>`, `<BarChart>` and
|
|
3
|
+
* `<Sparkline>` (stacksjs/stx#2318).
|
|
4
|
+
*
|
|
5
|
+
* Hand-built SVG with no dependency, in two halves:
|
|
6
|
+
*
|
|
7
|
+
* - `buildChartModel` runs on the server. It reads the records, applies the
|
|
8
|
+
* accessors and the formatters (which may be functions, so they can only
|
|
9
|
+
* run there), works out the domains and ticks, and answers a JSON-safe
|
|
10
|
+
* model: every label already a string.
|
|
11
|
+
* - `renderChartSvg(model, width)` and `layoutChart` lay that model out at a
|
|
12
|
+
* width. The server calls them for the first paint, so a chart is visible
|
|
13
|
+
* before any script runs; the client calls them again when the container
|
|
14
|
+
* resizes, and uses the same layout to find the point under the pointer.
|
|
15
|
+
*
|
|
16
|
+
* Every string that reaches the SVG goes through `escapeXml`.
|
|
17
|
+
*/
|
|
18
|
+
import { formatStat, isStatFormat } from '../stat/format'
|
|
19
|
+
|
|
20
|
+
export type ChartType = 'line' | 'area' | 'bar' | 'sparkline'
|
|
21
|
+
export type ChartXType = 'time' | 'linear' | 'band'
|
|
22
|
+
export type ChartCurve = 'linear' | 'monotone' | 'step'
|
|
23
|
+
export type Accessor = string | ((datum: any, index: number) => unknown)
|
|
24
|
+
export type Formatter = string | ((value: any, index?: number) => string)
|
|
25
|
+
|
|
26
|
+
export interface ChartSeriesInput {
|
|
27
|
+
key: Accessor
|
|
28
|
+
label?: string
|
|
29
|
+
color?: string
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ChartInput {
|
|
33
|
+
type?: ChartType
|
|
34
|
+
data?: unknown
|
|
35
|
+
/** Key or function for the x value. Default `x`, or the index for a plain number array. */
|
|
36
|
+
x?: Accessor
|
|
37
|
+
/** Key or function for the y value; an array of keys draws one series each. Default `y`. */
|
|
38
|
+
y?: Accessor | Accessor[]
|
|
39
|
+
/** Series, each a key or `{ key, label, color }`. Overrides `y`. */
|
|
40
|
+
series?: Array<Accessor | ChartSeriesInput>
|
|
41
|
+
xType?: ChartXType
|
|
42
|
+
/** `[min, max]`; a `null` end is worked out from the data. */
|
|
43
|
+
yDomain?: [number | null | undefined, number | null | undefined]
|
|
44
|
+
curve?: ChartCurve
|
|
45
|
+
colors?: string[]
|
|
46
|
+
/** A function, or a stat format name for y (`number`, `percent`, `duration`, `bytes`, `currency`). */
|
|
47
|
+
formatX?: Formatter
|
|
48
|
+
formatY?: Formatter
|
|
49
|
+
height?: number
|
|
50
|
+
label?: string
|
|
51
|
+
locale?: string
|
|
52
|
+
/** IANA zone for time labels. Default `UTC`, so the server and the browser agree. */
|
|
53
|
+
timeZone?: string
|
|
54
|
+
/** Approximate number of ticks on each axis. Default 5. */
|
|
55
|
+
ticks?: number
|
|
56
|
+
/** Draw axes and grid. Default true, false for a sparkline. */
|
|
57
|
+
axes?: boolean
|
|
58
|
+
/** Fill under the line. Always for an area chart; optional for a sparkline. */
|
|
59
|
+
fill?: boolean
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ChartSeries {
|
|
63
|
+
key: string
|
|
64
|
+
label: string
|
|
65
|
+
color: string
|
|
66
|
+
values: Array<number | null>
|
|
67
|
+
labels: string[]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ChartTick {
|
|
71
|
+
value: number
|
|
72
|
+
label: string
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ChartModel {
|
|
76
|
+
type: ChartType
|
|
77
|
+
curve: ChartCurve
|
|
78
|
+
xType: ChartXType
|
|
79
|
+
height: number
|
|
80
|
+
axes: boolean
|
|
81
|
+
fill: boolean
|
|
82
|
+
label: string
|
|
83
|
+
/** Numeric x per datum: epoch ms, a number, or the band index. */
|
|
84
|
+
xs: number[]
|
|
85
|
+
xLabels: string[]
|
|
86
|
+
xDomain: [number, number]
|
|
87
|
+
yDomain: [number, number]
|
|
88
|
+
xTicks: ChartTick[]
|
|
89
|
+
yTicks: ChartTick[]
|
|
90
|
+
series: ChartSeries[]
|
|
91
|
+
/** The records, for the `hover` event. */
|
|
92
|
+
data: unknown[]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Role tokens, so a chart follows dark mode and an app's palette. */
|
|
96
|
+
export const DEFAULT_COLORS = [
|
|
97
|
+
'var(--stx-accent, #2563eb)',
|
|
98
|
+
'var(--stx-info, #0891b2)',
|
|
99
|
+
'var(--stx-success, #16a34a)',
|
|
100
|
+
'var(--stx-warning, #d97706)',
|
|
101
|
+
'var(--stx-danger, #dc2626)',
|
|
102
|
+
'var(--stx-secondary, #7c3aed)',
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
const CHART_TYPES: readonly ChartType[] = ['line', 'area', 'bar', 'sparkline']
|
|
106
|
+
const X_TYPES: readonly ChartXType[] = ['time', 'linear', 'band']
|
|
107
|
+
const CURVES: readonly ChartCurve[] = ['linear', 'monotone', 'step']
|
|
108
|
+
const TICK_TOLERANCE = 0.000000001
|
|
109
|
+
|
|
110
|
+
export function escapeXml(value: unknown): string {
|
|
111
|
+
return String(value ?? '')
|
|
112
|
+
.replace(/&/g, '&')
|
|
113
|
+
.replace(/</g, '<')
|
|
114
|
+
.replace(/>/g, '>')
|
|
115
|
+
.replace(/"/g, '"')
|
|
116
|
+
.replace(/'/g, ''')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A colour for a `style` attribute: a CSS value, never a way out of the attribute. */
|
|
120
|
+
function safeColor(value: string): string {
|
|
121
|
+
return /^[\w#%(),.\s-]+$/.test(value) ? value : DEFAULT_COLORS[0]!
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function read(datum: unknown, accessor: Accessor | undefined, index: number, fallback: unknown): unknown {
|
|
125
|
+
if (typeof accessor === 'function')
|
|
126
|
+
return accessor(datum, index)
|
|
127
|
+
if (typeof accessor === 'string' && datum !== null && typeof datum === 'object')
|
|
128
|
+
return (datum as Record<string, unknown>)[accessor]
|
|
129
|
+
return fallback
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function toNumberOrNull(value: unknown): number | null {
|
|
133
|
+
if (value === null || value === undefined || value === '')
|
|
134
|
+
return null
|
|
135
|
+
const n = typeof value === 'number' ? value : Number(value)
|
|
136
|
+
return Number.isFinite(n) ? n : null
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function toTime(value: unknown): number | null {
|
|
140
|
+
if (value instanceof Date)
|
|
141
|
+
return Number.isFinite(value.getTime()) ? value.getTime() : null
|
|
142
|
+
if (typeof value === 'number')
|
|
143
|
+
return Number.isFinite(value) ? value : null
|
|
144
|
+
if (typeof value === 'string' && value) {
|
|
145
|
+
const t = Date.parse(value)
|
|
146
|
+
return Number.isFinite(t) ? t : null
|
|
147
|
+
}
|
|
148
|
+
return null
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function accessorName(accessor: Accessor, index: number): string {
|
|
152
|
+
return typeof accessor === 'string' ? accessor : `series${index + 1}`
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Round step for `span / count`: 1, 2, 2.5 or 5 times a power of ten. */
|
|
156
|
+
function niceStep(span: number, count: number): number {
|
|
157
|
+
const raw = span / Math.max(1, count)
|
|
158
|
+
const power = 10 ** Math.floor(Math.log10(raw))
|
|
159
|
+
const fraction = raw / power
|
|
160
|
+
const nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 2.5 ? 2.5 : fraction <= 5 ? 5 : 10
|
|
161
|
+
return nice * power
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Extend a domain to round ends and list the ticks inside it. */
|
|
165
|
+
export function niceLinear(min: number, max: number, count = 5): { domain: [number, number], ticks: number[] } {
|
|
166
|
+
if (min === max) {
|
|
167
|
+
const pad = min === 0 ? 1 : Math.abs(min) * 0.1
|
|
168
|
+
min -= pad
|
|
169
|
+
max += pad
|
|
170
|
+
}
|
|
171
|
+
const step = niceStep(max - min, count)
|
|
172
|
+
const lo = Math.floor(min / step) * step
|
|
173
|
+
const hi = Math.ceil(max / step) * step
|
|
174
|
+
const ticks: number[] = []
|
|
175
|
+
// Rounded to the step's precision, so 0.1 + 0.2 does not label as 0.30000000000000004.
|
|
176
|
+
const digits = Math.max(0, -Math.floor(Math.log10(step)) + 2)
|
|
177
|
+
for (let v = lo; v <= hi + step / 2; v += step)
|
|
178
|
+
ticks.push(Number(v.toFixed(digits)))
|
|
179
|
+
return { domain: [lo, hi], ticks }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const SECOND = 1000
|
|
183
|
+
const MINUTE = 60 * SECOND
|
|
184
|
+
const HOUR = 60 * MINUTE
|
|
185
|
+
const DAY = 24 * HOUR
|
|
186
|
+
const TIME_STEPS = [SECOND, 5 * SECOND, 15 * SECOND, 30 * SECOND, MINUTE, 5 * MINUTE, 15 * MINUTE, 30 * MINUTE, HOUR, 3 * HOUR, 6 * HOUR, 12 * HOUR, DAY, 2 * DAY, 7 * DAY]
|
|
187
|
+
|
|
188
|
+
/** Ticks on round instants: aligned multiples up to a week, then calendar months and years (UTC). */
|
|
189
|
+
export function timeTicks(min: number, max: number, count = 5): { ticks: number[], step: number } {
|
|
190
|
+
const span = Math.max(1, max - min)
|
|
191
|
+
const target = span / Math.max(1, count)
|
|
192
|
+
const step = TIME_STEPS.find(s => s >= target)
|
|
193
|
+
if (step) {
|
|
194
|
+
const ticks: number[] = []
|
|
195
|
+
for (let t = Math.ceil(min / step) * step; t <= max; t += step)
|
|
196
|
+
ticks.push(t)
|
|
197
|
+
return { ticks, step }
|
|
198
|
+
}
|
|
199
|
+
// Months: 1, 3 or 6 of them; beyond that, years.
|
|
200
|
+
const months = [1, 3, 6].find(m => m * 30 * DAY >= target)
|
|
201
|
+
const ticks: number[] = []
|
|
202
|
+
const start = new Date(min)
|
|
203
|
+
if (months) {
|
|
204
|
+
let y = start.getUTCFullYear()
|
|
205
|
+
let m = Math.ceil(start.getUTCMonth() / months) * months
|
|
206
|
+
for (;; ) {
|
|
207
|
+
const t = Date.UTC(y, m, 1)
|
|
208
|
+
if (t > max)
|
|
209
|
+
break
|
|
210
|
+
if (t >= min)
|
|
211
|
+
ticks.push(t)
|
|
212
|
+
m += months
|
|
213
|
+
if (m >= 12) {
|
|
214
|
+
y += Math.floor(m / 12)
|
|
215
|
+
m %= 12
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return { ticks, step: months * 30 * DAY }
|
|
219
|
+
}
|
|
220
|
+
const years = Math.max(1, Math.round(niceStep(span / (365 * DAY), count)))
|
|
221
|
+
for (let y = Math.ceil(start.getUTCFullYear() / years) * years; Date.UTC(y, 0, 1) <= max; y += years) {
|
|
222
|
+
const t = Date.UTC(y, 0, 1)
|
|
223
|
+
if (t >= min)
|
|
224
|
+
ticks.push(t)
|
|
225
|
+
}
|
|
226
|
+
return { ticks, step: years * 365 * DAY }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function dateFormatter(locale: string, timeZone: string, options: Intl.DateTimeFormatOptions): (t: number) => string {
|
|
230
|
+
let format: Intl.DateTimeFormat
|
|
231
|
+
try {
|
|
232
|
+
format = new Intl.DateTimeFormat(locale, { timeZone, ...options })
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
format = new Intl.DateTimeFormat('en-US', { timeZone: 'UTC', ...options })
|
|
236
|
+
}
|
|
237
|
+
return t => format.format(new Date(t))
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function tickTimeOptions(step: number): Intl.DateTimeFormatOptions {
|
|
241
|
+
if (step < MINUTE)
|
|
242
|
+
return { hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }
|
|
243
|
+
if (step < DAY)
|
|
244
|
+
return { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }
|
|
245
|
+
if (step < 28 * DAY)
|
|
246
|
+
return { month: 'short', day: 'numeric' }
|
|
247
|
+
if (step < 365 * DAY)
|
|
248
|
+
return { month: 'short', year: 'numeric' }
|
|
249
|
+
return { year: 'numeric' }
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function makeFormatter(formatter: Formatter | undefined, locale: string, fallback: (value: number, index?: number) => string): (value: any, index?: number) => string {
|
|
253
|
+
if (typeof formatter === 'function') {
|
|
254
|
+
return (value, index) => {
|
|
255
|
+
try {
|
|
256
|
+
return String(formatter(value, index) ?? '')
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return fallback(value, index)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
if (isStatFormat(formatter))
|
|
264
|
+
return value => formatStat(value, formatter, { locale }).short
|
|
265
|
+
return fallback
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Build the JSON-safe model of a chart from its props. Never throws on bad data; it draws less. */
|
|
269
|
+
export function buildChartModel(input: ChartInput): ChartModel {
|
|
270
|
+
const type = CHART_TYPES.includes(input.type as ChartType) ? input.type as ChartType : 'line'
|
|
271
|
+
const rawData = Array.isArray(input.data) ? input.data : []
|
|
272
|
+
const plain = rawData.length > 0 && rawData.every(d => typeof d === 'number' || d === null)
|
|
273
|
+
const locale = input.locale || 'en-US'
|
|
274
|
+
const timeZone = input.timeZone || 'UTC'
|
|
275
|
+
const tickCount = Math.max(2, Math.round(Number(input.ticks) || 5))
|
|
276
|
+
const height = Math.max(16, Number(input.height) || (type === 'sparkline' ? 32 : 240))
|
|
277
|
+
const axes = input.axes ?? type !== 'sparkline'
|
|
278
|
+
const curve = CURVES.includes(input.curve as ChartCurve) ? input.curve as ChartCurve : (type === 'bar' ? 'linear' : 'monotone')
|
|
279
|
+
const colors = (Array.isArray(input.colors) && input.colors.length ? input.colors : DEFAULT_COLORS).map(c => safeColor(String(c)))
|
|
280
|
+
|
|
281
|
+
// Series: explicit, else one per y key, else `y`.
|
|
282
|
+
let seriesSource: Array<Accessor | ChartSeriesInput> = [input.y as Accessor ?? 'y']
|
|
283
|
+
if (Array.isArray(input.series) && input.series.length)
|
|
284
|
+
seriesSource = input.series
|
|
285
|
+
else if (Array.isArray(input.y))
|
|
286
|
+
seriesSource = input.y
|
|
287
|
+
const seriesInputs: ChartSeriesInput[] = seriesSource.map(s => (s !== null && typeof s === 'object' && 'key' in s) ? s : { key: s as Accessor })
|
|
288
|
+
|
|
289
|
+
// x values, and which kind of axis they make.
|
|
290
|
+
const xRaw = rawData.map((d, i) => plain ? i : read(d, input.x ?? 'x', i, i))
|
|
291
|
+
let xType: ChartXType = X_TYPES.includes(input.xType as ChartXType) ? input.xType as ChartXType : 'linear'
|
|
292
|
+
if (!input.xType) {
|
|
293
|
+
if (type === 'bar')
|
|
294
|
+
xType = 'band'
|
|
295
|
+
else if (xRaw.some(v => v instanceof Date || (typeof v === 'string' && Number.isNaN(Number(v)) && Number.isFinite(Date.parse(v)))))
|
|
296
|
+
xType = 'time'
|
|
297
|
+
else if (xRaw.some(v => typeof v === 'string' && v !== '' && Number.isNaN(Number(v))))
|
|
298
|
+
xType = 'band'
|
|
299
|
+
}
|
|
300
|
+
let xs = xRaw.map((v, i) => xType === 'band' ? i : xType === 'time' ? toTime(v) : toNumberOrNull(v))
|
|
301
|
+
// A datum with no usable x cannot be placed; it is dropped, with its records.
|
|
302
|
+
const keep = xs.map(v => v !== null)
|
|
303
|
+
const data = rawData.filter((_, i) => keep[i])
|
|
304
|
+
const xRawKept = xRaw.filter((_, i) => keep[i])
|
|
305
|
+
xs = xs.filter((_, i) => keep[i])
|
|
306
|
+
const xNums = xs as number[]
|
|
307
|
+
|
|
308
|
+
const series: ChartSeries[] = seriesInputs.map((s, si) => {
|
|
309
|
+
const values = data.map((d, i) => toNumberOrNull(plain ? d : read(d, s.key, i, undefined)))
|
|
310
|
+
return {
|
|
311
|
+
key: accessorName(s.key, si),
|
|
312
|
+
label: s.label || (typeof s.key === 'string' ? s.key : `Series ${si + 1}`),
|
|
313
|
+
color: s.color ? safeColor(String(s.color)) : colors[si % colors.length]!,
|
|
314
|
+
values,
|
|
315
|
+
labels: [],
|
|
316
|
+
}
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
// y domain: the data, with zero in it for bars and areas, then nice ends.
|
|
320
|
+
const all = series.flatMap(s => s.values).filter((v): v is number => v !== null)
|
|
321
|
+
let yMin = all.length ? Math.min(...all) : 0
|
|
322
|
+
let yMax = all.length ? Math.max(...all) : 1
|
|
323
|
+
if (type === 'bar' || type === 'area') {
|
|
324
|
+
yMin = Math.min(0, yMin)
|
|
325
|
+
yMax = Math.max(0, yMax)
|
|
326
|
+
}
|
|
327
|
+
const fixedMin = toNumberOrNull(input.yDomain?.[0])
|
|
328
|
+
const fixedMax = toNumberOrNull(input.yDomain?.[1])
|
|
329
|
+
if (fixedMin !== null)
|
|
330
|
+
yMin = fixedMin
|
|
331
|
+
if (fixedMax !== null)
|
|
332
|
+
yMax = fixedMax
|
|
333
|
+
const niceY = niceLinear(yMin, yMax, tickCount)
|
|
334
|
+
const yDomain: [number, number] = [fixedMin ?? niceY.domain[0], fixedMax ?? niceY.domain[1]]
|
|
335
|
+
// A tick on a fixed end survives float rounding. Written out, not as an
|
|
336
|
+
// exponent literal: the formatter split `1e-9` into `1e - 9`, which does not parse.
|
|
337
|
+
const yTicksRaw = niceY.ticks.filter(t => t >= yDomain[0] - TICK_TOLERANCE && t <= yDomain[1] + TICK_TOLERANCE)
|
|
338
|
+
|
|
339
|
+
const formatY = makeFormatter(input.formatY, locale, v => new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(v))
|
|
340
|
+
const yTicks = (type === 'sparkline' ? [] : yTicksRaw).map(v => ({ value: v, label: formatY(v) }))
|
|
341
|
+
for (const s of series)
|
|
342
|
+
s.labels = s.values.map(v => v === null ? '—' : formatY(v))
|
|
343
|
+
|
|
344
|
+
// x domain and ticks.
|
|
345
|
+
let xDomain: [number, number]
|
|
346
|
+
let xTicks: ChartTick[] = []
|
|
347
|
+
let xLabels: string[]
|
|
348
|
+
if (xType === 'band') {
|
|
349
|
+
xDomain = [0, Math.max(1, xNums.length)]
|
|
350
|
+
// Bars over days are common; a date reads as one rather than as an ISO string.
|
|
351
|
+
const dayLabel = dateFormatter(locale, timeZone, { month: 'short', day: 'numeric' })
|
|
352
|
+
const formatX = makeFormatter(input.formatX, locale, (_v, i) => {
|
|
353
|
+
const raw = xRawKept[i ?? 0]
|
|
354
|
+
const isDate = raw instanceof Date || (typeof raw === 'string' && Number.isNaN(Number(raw)) && Number.isFinite(Date.parse(raw)))
|
|
355
|
+
return isDate ? dayLabel(toTime(raw)!) : String(raw ?? '')
|
|
356
|
+
})
|
|
357
|
+
xLabels = xRawKept.map((v, i) => formatX(v, i))
|
|
358
|
+
const every = Math.max(1, Math.ceil(xNums.length / Math.max(tickCount, 8)))
|
|
359
|
+
xTicks = xNums.filter((_, i) => i % every === 0).map(i => ({ value: i, label: xLabels[i]! }))
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
const lo = xNums.length ? Math.min(...xNums) : 0
|
|
363
|
+
const hi = xNums.length ? Math.max(...xNums) : 1
|
|
364
|
+
if (xType === 'time') {
|
|
365
|
+
xDomain = lo === hi ? [lo - HOUR, hi + HOUR] : [lo, hi]
|
|
366
|
+
const { ticks, step } = timeTicks(xDomain[0], xDomain[1], tickCount)
|
|
367
|
+
const tickFormat = makeFormatter(input.formatX, locale, dateFormatter(locale, timeZone, tickTimeOptions(step)))
|
|
368
|
+
const datumFormat = makeFormatter(input.formatX, locale, dateFormatter(locale, timeZone, step < DAY
|
|
369
|
+
? { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }
|
|
370
|
+
: { year: 'numeric', month: 'short', day: 'numeric' }))
|
|
371
|
+
xTicks = ticks.map(t => ({ value: t, label: tickFormat(new Date(t)) }))
|
|
372
|
+
xLabels = xNums.map((t, i) => datumFormat(new Date(t), i))
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
const nice = niceLinear(lo, hi, tickCount)
|
|
376
|
+
xDomain = lo === hi ? nice.domain : [lo, hi]
|
|
377
|
+
const formatX = makeFormatter(input.formatX, locale, v => new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(v))
|
|
378
|
+
xTicks = nice.ticks.filter(t => t >= xDomain[0] && t <= xDomain[1]).map(t => ({ value: t, label: formatX(t) }))
|
|
379
|
+
xLabels = xNums.map((v, i) => formatX(v, i))
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (!axes)
|
|
383
|
+
xTicks = []
|
|
384
|
+
|
|
385
|
+
return {
|
|
386
|
+
type,
|
|
387
|
+
curve,
|
|
388
|
+
xType,
|
|
389
|
+
height,
|
|
390
|
+
axes,
|
|
391
|
+
fill: type === 'area' || (type !== 'bar' && input.fill === true),
|
|
392
|
+
label: input.label || '',
|
|
393
|
+
xs: xNums,
|
|
394
|
+
xLabels,
|
|
395
|
+
xDomain,
|
|
396
|
+
yDomain,
|
|
397
|
+
xTicks,
|
|
398
|
+
yTicks,
|
|
399
|
+
series,
|
|
400
|
+
data: data.map(d => toJsonSafe(d)),
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function toJsonSafe(value: unknown): unknown {
|
|
405
|
+
if (value instanceof Date)
|
|
406
|
+
return value.toISOString()
|
|
407
|
+
if (value === null || typeof value !== 'object')
|
|
408
|
+
return typeof value === 'function' ? undefined : value
|
|
409
|
+
try {
|
|
410
|
+
return JSON.parse(JSON.stringify(value))
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
return undefined
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export interface ChartLayout {
|
|
418
|
+
width: number
|
|
419
|
+
height: number
|
|
420
|
+
left: number
|
|
421
|
+
top: number
|
|
422
|
+
plotWidth: number
|
|
423
|
+
plotHeight: number
|
|
424
|
+
/** Pixel x of datum `i` (the band centre for bars). */
|
|
425
|
+
x: (i: number) => number
|
|
426
|
+
/** Pixel x of an x value on a continuous axis, or a band index. */
|
|
427
|
+
xValue: (value: number) => number
|
|
428
|
+
y: (value: number) => number
|
|
429
|
+
bandWidth: number
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Where everything goes at `width`. Shared by the server render and the client's hit testing. */
|
|
433
|
+
export function layoutChart(model: ChartModel, width: number): ChartLayout {
|
|
434
|
+
const w = Math.max(40, Math.round(width))
|
|
435
|
+
const h = model.height
|
|
436
|
+
const longest = model.yTicks.reduce((n, t) => Math.max(n, t.label.length), 0)
|
|
437
|
+
const left = model.axes ? Math.min(96, 10 + longest * 7) : 2
|
|
438
|
+
const top = model.axes ? 8 : 2
|
|
439
|
+
const right = model.axes ? 12 : 2
|
|
440
|
+
const bottom = model.axes ? 26 : 2
|
|
441
|
+
const plotWidth = Math.max(1, w - left - right)
|
|
442
|
+
const plotHeight = Math.max(1, h - top - bottom)
|
|
443
|
+
const [x0, x1] = model.xDomain
|
|
444
|
+
const [y0, y1] = model.yDomain
|
|
445
|
+
const n = Math.max(1, model.xs.length)
|
|
446
|
+
const bandWidth = model.xType === 'band' ? plotWidth / n : 0
|
|
447
|
+
const xValue = model.xType === 'band'
|
|
448
|
+
? (v: number) => left + (v + 0.5) * bandWidth
|
|
449
|
+
: (v: number) => left + (x1 === x0 ? plotWidth / 2 : ((v - x0) / (x1 - x0)) * plotWidth)
|
|
450
|
+
const y = (v: number) => {
|
|
451
|
+
const clamped = Math.min(Math.max(v, Math.min(y0, y1)), Math.max(y0, y1))
|
|
452
|
+
return top + plotHeight - (y1 === y0 ? 0.5 : (clamped - y0) / (y1 - y0)) * plotHeight
|
|
453
|
+
}
|
|
454
|
+
return {
|
|
455
|
+
width: w,
|
|
456
|
+
height: h,
|
|
457
|
+
left,
|
|
458
|
+
top,
|
|
459
|
+
plotWidth,
|
|
460
|
+
plotHeight,
|
|
461
|
+
x: i => xValue(model.xs[i] ?? i),
|
|
462
|
+
xValue,
|
|
463
|
+
y,
|
|
464
|
+
bandWidth,
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
const r = (n: number): string => String(Math.round(n * 100) / 100)
|
|
469
|
+
|
|
470
|
+
type Point = [number, number]
|
|
471
|
+
|
|
472
|
+
/** Runs of consecutive points, split where a value is missing. */
|
|
473
|
+
function segments(values: Array<number | null>, layout: ChartLayout): Point[][] {
|
|
474
|
+
const runs: Point[][] = []
|
|
475
|
+
let run: Point[] = []
|
|
476
|
+
values.forEach((v, i) => {
|
|
477
|
+
if (v === null) {
|
|
478
|
+
if (run.length)
|
|
479
|
+
runs.push(run)
|
|
480
|
+
run = []
|
|
481
|
+
return
|
|
482
|
+
}
|
|
483
|
+
run.push([layout.x(i), layout.y(v)])
|
|
484
|
+
})
|
|
485
|
+
if (run.length)
|
|
486
|
+
runs.push(run)
|
|
487
|
+
return runs
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/** Monotone cubic interpolation in x (Fritsch-Carlson), so a curve never overshoots a point. */
|
|
491
|
+
function monotonePath(points: Point[]): string {
|
|
492
|
+
const n = points.length
|
|
493
|
+
if (n < 3)
|
|
494
|
+
return linearPath(points)
|
|
495
|
+
const dx: number[] = []
|
|
496
|
+
const slope: number[] = []
|
|
497
|
+
for (let i = 0; i < n - 1; i++) {
|
|
498
|
+
dx[i] = points[i + 1]![0] - points[i]![0]
|
|
499
|
+
slope[i] = dx[i] === 0 ? 0 : (points[i + 1]![1] - points[i]![1]) / dx[i]!
|
|
500
|
+
}
|
|
501
|
+
const tangent: number[] = [slope[0]!]
|
|
502
|
+
for (let i = 1; i < n - 1; i++) {
|
|
503
|
+
const a = slope[i - 1]!
|
|
504
|
+
const b = slope[i]!
|
|
505
|
+
if (a * b <= 0) {
|
|
506
|
+
tangent[i] = 0
|
|
507
|
+
}
|
|
508
|
+
else {
|
|
509
|
+
const w1 = 2 * dx[i]! + dx[i - 1]!
|
|
510
|
+
const w2 = dx[i]! + 2 * dx[i - 1]!
|
|
511
|
+
tangent[i] = (w1 + w2) / (w1 / a + w2 / b)
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
tangent[n - 1] = slope[n - 2]!
|
|
515
|
+
let d = `M${r(points[0]![0])},${r(points[0]![1])}`
|
|
516
|
+
for (let i = 0; i < n - 1; i++) {
|
|
517
|
+
const [xa, ya] = points[i]!
|
|
518
|
+
const [xb, yb] = points[i + 1]!
|
|
519
|
+
const h = dx[i]! / 3
|
|
520
|
+
d += `C${r(xa + h)},${r(ya + h * tangent[i]!)},${r(xb - h)},${r(yb - h * tangent[i + 1]!)},${r(xb)},${r(yb)}`
|
|
521
|
+
}
|
|
522
|
+
return d
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function linearPath(points: Point[]): string {
|
|
526
|
+
return points.map(([x, y], i) => `${i ? 'L' : 'M'}${r(x)},${r(y)}`).join('')
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function stepPath(points: Point[]): string {
|
|
530
|
+
let d = ''
|
|
531
|
+
points.forEach(([x, y], i) => {
|
|
532
|
+
if (i === 0) {
|
|
533
|
+
d = `M${r(x)},${r(y)}`
|
|
534
|
+
return
|
|
535
|
+
}
|
|
536
|
+
const mid = (points[i - 1]![0] + x) / 2
|
|
537
|
+
d += `H${r(mid)}V${r(y)}H${r(x)}`
|
|
538
|
+
})
|
|
539
|
+
return d
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function curvePath(points: Point[], curve: ChartCurve): string {
|
|
543
|
+
if (curve === 'step')
|
|
544
|
+
return stepPath(points)
|
|
545
|
+
if (curve === 'monotone')
|
|
546
|
+
return monotonePath(points)
|
|
547
|
+
return linearPath(points)
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** The whole chart as an SVG string at `width`, with the interaction layer drawn hidden. */
|
|
551
|
+
export function renderChartSvg(model: ChartModel, width: number): string {
|
|
552
|
+
const L = layoutChart(model, width)
|
|
553
|
+
const parts: string[] = []
|
|
554
|
+
const baseline = L.y(Math.max(model.yDomain[0], Math.min(0, model.yDomain[1])))
|
|
555
|
+
|
|
556
|
+
if (model.axes) {
|
|
557
|
+
parts.push('<g data-chart-grid aria-hidden="true">')
|
|
558
|
+
for (const t of model.yTicks) {
|
|
559
|
+
const y = r(L.y(t.value))
|
|
560
|
+
parts.push(`<line x1="${r(L.left)}" x2="${r(L.left + L.plotWidth)}" y1="${y}" y2="${y}" style="stroke:var(--stx-line, #e5e5e5)" stroke-width="1" />`)
|
|
561
|
+
parts.push(`<text x="${r(L.left - 8)}" y="${y}" dy="0.32em" text-anchor="end" font-size="11" style="fill:var(--stx-fg-soft, #737373)">${escapeXml(t.label)}</text>`)
|
|
562
|
+
}
|
|
563
|
+
// At a narrow width the x labels would overlap; keep each one only if it
|
|
564
|
+
// clears the last one drawn.
|
|
565
|
+
let lastRight = Number.NEGATIVE_INFINITY
|
|
566
|
+
for (const t of model.xTicks) {
|
|
567
|
+
const half = (t.label.length * 6.5) / 2
|
|
568
|
+
const px = L.xValue(t.value)
|
|
569
|
+
if (px - half < lastRight + 8)
|
|
570
|
+
continue
|
|
571
|
+
lastRight = px + half
|
|
572
|
+
const x = r(px)
|
|
573
|
+
parts.push(`<text data-chart-x-tick x="${x}" y="${r(L.top + L.plotHeight + 18)}" text-anchor="middle" font-size="11" style="fill:var(--stx-fg-soft, #737373)">${escapeXml(t.label)}</text>`)
|
|
574
|
+
}
|
|
575
|
+
parts.push(`<line x1="${r(L.left)}" x2="${r(L.left + L.plotWidth)}" y1="${r(baseline)}" y2="${r(baseline)}" style="stroke:var(--stx-line-strong, #d4d4d4)" stroke-width="1" />`)
|
|
576
|
+
parts.push('</g>')
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
model.series.forEach((s, si) => {
|
|
580
|
+
const style = `stroke:${s.color};fill:${s.color}`
|
|
581
|
+
parts.push(`<g data-chart-series="${si}" style="${style}">`)
|
|
582
|
+
if (model.type === 'bar') {
|
|
583
|
+
const groups = model.series.length
|
|
584
|
+
const inner = L.bandWidth * 0.72
|
|
585
|
+
const barW = Math.max(1, inner / groups)
|
|
586
|
+
s.values.forEach((v, i) => {
|
|
587
|
+
if (v === null)
|
|
588
|
+
return
|
|
589
|
+
const x = L.x(i) - inner / 2 + si * barW
|
|
590
|
+
const y = L.y(v)
|
|
591
|
+
const top = Math.min(y, baseline)
|
|
592
|
+
const height = Math.max(v === 0 ? 0 : 1, Math.abs(baseline - y))
|
|
593
|
+
parts.push(`<rect x="${r(x)}" y="${r(top)}" width="${r(Math.max(1, barW - 1))}" height="${r(height)}" rx="2" stroke="none" />`)
|
|
594
|
+
})
|
|
595
|
+
}
|
|
596
|
+
else {
|
|
597
|
+
for (const run of segments(s.values, L)) {
|
|
598
|
+
if (model.fill && run.length > 1) {
|
|
599
|
+
const line = curvePath(run, model.curve)
|
|
600
|
+
const area = `${line}L${r(run[run.length - 1]![0])},${r(baseline)}L${r(run[0]![0])},${r(baseline)}Z`
|
|
601
|
+
parts.push(`<path d="${area}" fill-opacity="0.16" stroke="none" />`)
|
|
602
|
+
}
|
|
603
|
+
if (run.length > 1)
|
|
604
|
+
parts.push(`<path d="${curvePath(run, model.curve)}" fill="none" stroke-width="${model.type === 'sparkline' ? 1.5 : 2}" stroke-linejoin="round" stroke-linecap="round"${model.type === 'sparkline' ? ' vector-effect="non-scaling-stroke"' : ''} />`)
|
|
605
|
+
else
|
|
606
|
+
// A point with no neighbour (a single datum, or one between gaps) is a dot, or it would not show at all.
|
|
607
|
+
parts.push(`<circle cx="${r(run[0]![0])}" cy="${r(run[0]![1])}" r="3" stroke="none" />`)
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
parts.push('</g>')
|
|
611
|
+
})
|
|
612
|
+
|
|
613
|
+
// The crosshair and point markers the client moves; hidden until a datum is active.
|
|
614
|
+
if (model.type !== 'sparkline') {
|
|
615
|
+
parts.push(`<g data-chart-focus visibility="hidden" aria-hidden="true"><line data-chart-crosshair x1="0" x2="0" y1="${r(L.top)}" y2="${r(L.top + L.plotHeight)}" style="stroke:var(--stx-fg-soft, #737373)" stroke-width="1" stroke-dasharray="3 3" />`)
|
|
616
|
+
model.series.forEach((s, si) => {
|
|
617
|
+
parts.push(`<circle data-chart-marker="${si}" cx="0" cy="0" r="4" stroke-width="2" style="fill:var(--stx-panel, #fff);stroke:${s.color}" />`)
|
|
618
|
+
})
|
|
619
|
+
parts.push('</g>')
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
// A sparkline has no text, so it stretches to its box at a fixed height.
|
|
623
|
+
if (model.type === 'sparkline')
|
|
624
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${L.width} ${L.height}" preserveAspectRatio="none" aria-hidden="true" focusable="false" style="display:block;width:100%;height:${L.height}px;overflow:visible">${parts.join('')}</svg>`
|
|
625
|
+
// Scales uniformly with its container until the client lays it out again at
|
|
626
|
+
// the container's real width, so text is never stretched before a script runs.
|
|
627
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${L.width} ${L.height}" aria-hidden="true" focusable="false" data-chart-width="${L.width}" style="display:block;width:100%;height:auto;overflow:visible">${parts.join('')}</svg>`
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Index of the datum nearest a pixel x. */
|
|
631
|
+
export function nearestIndex(model: ChartModel, layout: ChartLayout, px: number): number {
|
|
632
|
+
let best = -1
|
|
633
|
+
let bestDistance = Number.POSITIVE_INFINITY
|
|
634
|
+
for (let i = 0; i < model.xs.length; i++) {
|
|
635
|
+
const d = Math.abs(layout.x(i) - px)
|
|
636
|
+
if (d < bestDistance) {
|
|
637
|
+
best = i
|
|
638
|
+
bestDistance = d
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return best
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** What a datum says in words: "Mar 3, 2026: Requests 1,234, Errors 12". */
|
|
645
|
+
export function describeDatum(model: ChartModel, index: number): string {
|
|
646
|
+
const values = model.series.map(s => `${s.label} ${s.labels[index] ?? '—'}`).join(', ')
|
|
647
|
+
return `${model.xLabels[index] ?? ''}: ${values}`
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** A one-sentence summary for a sparkline or a chart's description. */
|
|
651
|
+
export function summarize(model: ChartModel): string {
|
|
652
|
+
if (!model.xs.length)
|
|
653
|
+
return 'No data'
|
|
654
|
+
return model.series.map((s) => {
|
|
655
|
+
const present = s.values.map((v, i) => [v, i] as const).filter(([v]) => v !== null) as Array<readonly [number, number]>
|
|
656
|
+
if (!present.length)
|
|
657
|
+
return `${s.label}: no values`
|
|
658
|
+
const first = present[0]!
|
|
659
|
+
const last = present[present.length - 1]!
|
|
660
|
+
const low = present.reduce((a, b) => (b[0] < a[0] ? b : a))
|
|
661
|
+
const high = present.reduce((a, b) => (b[0] > a[0] ? b : a))
|
|
662
|
+
if (present.length === 1)
|
|
663
|
+
return `${s.label}: ${s.labels[first[1]]}`
|
|
664
|
+
return `${s.label}: from ${s.labels[first[1]]} to ${s.labels[last[1]]}, low ${s.labels[low[1]]}, high ${s.labels[high[1]]}`
|
|
665
|
+
}).join('. ')
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** JSON for a `<script>`: no `</script>` or `<!--` can close or confuse the element. */
|
|
669
|
+
export function scriptJson(value: unknown): string {
|
|
670
|
+
return JSON.stringify(value)
|
|
671
|
+
.replace(/</g, '\\u003c')
|
|
672
|
+
.replace(/>/g, '\\u003e')
|
|
673
|
+
.replace(/&/g, '\\u0026')
|
|
674
|
+
.replace(/\u2028/g, '\\u2028')
|
|
675
|
+
.replace(/\u2029/g, '\\u2029')
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
export interface PreparedChart {
|
|
679
|
+
model: ChartModel
|
|
680
|
+
empty: boolean
|
|
681
|
+
svg: string
|
|
682
|
+
modelJson: string
|
|
683
|
+
summary: string
|
|
684
|
+
/** Header row and body rows of the text alternative. */
|
|
685
|
+
tableHead: string[]
|
|
686
|
+
tableRows: string[][]
|
|
687
|
+
legend: Array<{ label: string, color: string }>
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Everything a chart component's template needs, from its props. Each of the
|
|
692
|
+
* four components calls this with its type, so they differ only in markup.
|
|
693
|
+
*/
|
|
694
|
+
export function prepareChart(type: ChartType, props: Record<string, any>, width = 640): PreparedChart {
|
|
695
|
+
const num = (v: unknown): number | undefined => {
|
|
696
|
+
const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() !== '' ? Number(v) : Number.NaN
|
|
697
|
+
return Number.isFinite(n) ? n : undefined
|
|
698
|
+
}
|
|
699
|
+
const yDomain = Array.isArray(props.yDomain) ? props.yDomain as [number | null, number | null] : undefined
|
|
700
|
+
const model = buildChartModel({
|
|
701
|
+
type,
|
|
702
|
+
data: props.data,
|
|
703
|
+
x: props.x,
|
|
704
|
+
y: props.y,
|
|
705
|
+
series: props.series,
|
|
706
|
+
xType: props.xType,
|
|
707
|
+
yDomain,
|
|
708
|
+
curve: props.curve,
|
|
709
|
+
colors: props.colors,
|
|
710
|
+
formatX: props.formatX,
|
|
711
|
+
formatY: props.formatY,
|
|
712
|
+
height: num(props.height),
|
|
713
|
+
label: props.label,
|
|
714
|
+
locale: props.locale,
|
|
715
|
+
timeZone: props.timeZone,
|
|
716
|
+
ticks: num(props.ticks),
|
|
717
|
+
fill: props.area === true || props.area === '' || props.area === 'true',
|
|
718
|
+
})
|
|
719
|
+
const empty = model.xs.length === 0
|
|
720
|
+
return {
|
|
721
|
+
model,
|
|
722
|
+
empty,
|
|
723
|
+
svg: empty ? '' : renderChartSvg(model, width),
|
|
724
|
+
modelJson: scriptJson(model),
|
|
725
|
+
summary: summarize(model),
|
|
726
|
+
tableHead: [props.xLabel || (model.xType === 'time' ? 'Time' : 'X'), ...model.series.map(s => s.label)],
|
|
727
|
+
tableRows: model.xs.map((_, i) => [model.xLabels[i] ?? '', ...model.series.map(s => s.labels[i] ?? '—')]),
|
|
728
|
+
legend: model.series.length > 1 ? model.series.map(s => ({ label: s.label, color: s.color })) : [],
|
|
729
|
+
}
|
|
730
|
+
}
|