@cognitap/radiant 0.0.68 → 0.0.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/library/Carousel.d.ts +46 -0
  3. package/dist/library/Carousel.d.ts.map +1 -0
  4. package/dist/library/Carousel.js +317 -0
  5. package/dist/library/Carousel.js.map +1 -0
  6. package/dist/library/charts/Charts.d.ts +44 -0
  7. package/dist/library/charts/Charts.d.ts.map +1 -0
  8. package/dist/library/charts/Charts.js +92 -0
  9. package/dist/library/charts/Charts.js.map +1 -0
  10. package/dist/library/charts/index.d.ts +3 -0
  11. package/dist/library/charts/index.d.ts.map +1 -0
  12. package/dist/library/charts/index.js +3 -0
  13. package/dist/library/charts/index.js.map +1 -0
  14. package/dist/library/charts/palette.d.ts +20 -0
  15. package/dist/library/charts/palette.d.ts.map +1 -0
  16. package/dist/library/charts/palette.js +11 -0
  17. package/dist/library/charts/palette.js.map +1 -0
  18. package/dist/library/cn.d.ts.map +1 -1
  19. package/dist/library/cn.js +6 -1
  20. package/dist/library/cn.js.map +1 -1
  21. package/dist/library/index.d.ts +1 -0
  22. package/dist/library/index.d.ts.map +1 -1
  23. package/dist/library/index.js +1 -0
  24. package/dist/library/index.js.map +1 -1
  25. package/dist/library/internal/charts.d.ts +45 -0
  26. package/dist/library/internal/charts.d.ts.map +1 -0
  27. package/dist/library/internal/charts.js +98 -0
  28. package/dist/library/internal/charts.js.map +1 -0
  29. package/dist/library/styles.css +1 -1
  30. package/dist/library/themes/components.d.ts +17 -0
  31. package/dist/library/themes/components.d.ts.map +1 -1
  32. package/dist/library/themes/components.js +13 -0
  33. package/dist/library/themes/components.js.map +1 -1
  34. package/docs/architecture.md +10 -10
  35. package/package.json +5 -1
  36. package/src/Carousel.tsx +540 -0
  37. package/src/charts/Charts.tsx +442 -0
  38. package/src/charts/index.ts +16 -0
  39. package/src/charts/palette.ts +21 -0
  40. package/src/cn.ts +6 -1
  41. package/src/index.ts +16 -0
  42. package/src/internal/charts.ts +150 -0
  43. package/src/themes/components.ts +13 -0
@@ -0,0 +1,442 @@
1
+ 'use client'
2
+ import {
3
+ useId,
4
+ useLayoutEffect,
5
+ useRef,
6
+ useState,
7
+ type ComponentProps,
8
+ type ReactNode
9
+ } from 'react'
10
+ import { cn } from '../cn.js'
11
+ import { joinIds } from '../internal/ids.js'
12
+ import {
13
+ chartGeometry,
14
+ validateChart,
15
+ type ChartDatum,
16
+ type ChartSeries,
17
+ type ChartKind
18
+ } from '../internal/charts.js'
19
+ import { ScrollArea } from '../ScrollArea.js'
20
+ import { Tooltip, TooltipTrigger, TooltipContent } from '../Tooltip.js'
21
+ import {
22
+ Table,
23
+ TableCaption,
24
+ TableHead,
25
+ TableBody,
26
+ TableRow,
27
+ TableHeader,
28
+ TableCell,
29
+ type TableProps
30
+ } from '../Table.js'
31
+ import type { PartStyle } from '../presentation.js'
32
+ import type { ThemeStyle } from '../themes/defineTheme.js'
33
+ export type { ChartDatum, ChartSeries } from '../internal/charts.js'
34
+ export type ChartProps = Omit<
35
+ ComponentProps<'figure'>,
36
+ 'children' | 'style' | 'aria-labelledby' | 'aria-label' | 'role'
37
+ > & {
38
+ label: ReactNode
39
+ description?: ReactNode
40
+ data: readonly ChartDatum[]
41
+ series: readonly ChartSeries[]
42
+ formatValue?: (value: number, series: ChartSeries) => string
43
+ categoryLabel?: string
44
+ plotLabel?: string
45
+ legendLabel?: string
46
+ tableLabel?: string
47
+ emptyText?: string
48
+ style?: ThemeStyle
49
+ parts?: {
50
+ caption?: PartStyle
51
+ description?: PartStyle
52
+ plot?: PartStyle
53
+ legend?: PartStyle
54
+ point?: PartStyle
55
+ tooltip?: PartStyle
56
+ table?: PartStyle
57
+ }
58
+ 'data-slot'?: string
59
+ }
60
+ export type LineChartProps = ChartProps
61
+ export type BarChartProps = ChartProps
62
+ export type AreaChartProps = ChartProps
63
+ export type PieChartProps = Omit<ChartProps, 'series'> & { series: readonly [ChartSeries] }
64
+ const colors = [
65
+ 'var(--rad-chart-series1,color-mix(in oklab,var(--rad-color-accent) 55%,var(--rad-color-foreground)))',
66
+ 'var(--rad-chart-series2,color-mix(in oklab,var(--rad-color-focus) 65%,var(--rad-color-foreground)))',
67
+ 'var(--rad-chart-series3,color-mix(in oklab,var(--rad-color-warning) 45%,var(--rad-color-foreground)))',
68
+ 'var(--rad-chart-series4,color-mix(in oklab,var(--rad-color-danger) 65%,var(--rad-color-foreground)))',
69
+ 'var(--rad-chart-series5,var(--rad-color-foreground))',
70
+ 'var(--rad-chart-series6,var(--rad-color-muted-foreground))'
71
+ ]
72
+ const color = (index: number) => colors[index % colors.length]!
73
+ const dashes = ['', '8 4', '2 4', '10 3 2 3', '4 3', '12 6']
74
+ const format = (value: number) => String(value)
75
+ export type ChartDataTableProps = Omit<TableProps, 'children'> &
76
+ Pick<ChartProps, 'data' | 'series' | 'formatValue' | 'categoryLabel'> & { label: string }
77
+ export function ChartDataTable({
78
+ data,
79
+ series,
80
+ label,
81
+ formatValue = format,
82
+ categoryLabel = 'Category',
83
+ ...props
84
+ }: ChartDataTableProps) {
85
+ validateChart(data, series)
86
+ return (
87
+ <Table
88
+ {...props}
89
+ data-slot={joinIds('chart-data-table', props['data-slot'])}
90
+ >
91
+ <TableCaption>{label}</TableCaption>
92
+ <TableHead>
93
+ <TableRow>
94
+ <TableHeader scope="col">{categoryLabel}</TableHeader>
95
+ {series.map(item => (
96
+ <TableHeader
97
+ key={item.key}
98
+ scope="col"
99
+ >
100
+ {item.label}
101
+ </TableHeader>
102
+ ))}
103
+ </TableRow>
104
+ </TableHead>
105
+ <TableBody>
106
+ {data.map(row => (
107
+ <TableRow key={row.key}>
108
+ <TableHeader scope="row">{row.label}</TableHeader>
109
+ {series.map(item => (
110
+ <TableCell key={item.key}>
111
+ {row.values[item.key] == null ? '—' : formatValue(row.values[item.key]!, item)}
112
+ </TableCell>
113
+ ))}
114
+ </TableRow>
115
+ ))}
116
+ </TableBody>
117
+ </Table>
118
+ )
119
+ }
120
+ function Chart({
121
+ kind,
122
+ label,
123
+ description,
124
+ data,
125
+ series,
126
+ formatValue = format,
127
+ categoryLabel = 'Category',
128
+ plotLabel = 'Chart plot',
129
+ legendLabel = 'Chart legend',
130
+ tableLabel = 'View chart data',
131
+ emptyText = 'No chart data to display.',
132
+ parts,
133
+ className,
134
+ 'aria-describedby': describedBy,
135
+ ...props
136
+ }: ChartProps & { kind: ChartKind }) {
137
+ if (label == null || label === false || label === '')
138
+ throw new TypeError('Charts require a visible label.')
139
+ const [size, setSize] = useState<{ width: number; height: number } | null>(null)
140
+ const nativeProps = { ...props, role: undefined }
141
+ const id = useId(),
142
+ captionId = `${id}-caption`,
143
+ descriptionId = description ? `${id}-description` : undefined,
144
+ model = chartGeometry(kind, data, series, size),
145
+ root = useRef<HTMLDivElement>(null),
146
+ [focused, setFocused] = useState(0)
147
+ const ordered = [...model.marks].sort((a, b) => a.row - b.row || a.series - b.series)
148
+ const showPlot = ordered.length > 0
149
+ useLayoutEffect(() => {
150
+ const node = root.current
151
+ if (!node || !showPlot) return
152
+ const view = node.ownerDocument.defaultView!
153
+ const measure = () => {
154
+ const width = node.clientWidth,
155
+ height = node.clientHeight
156
+ setSize(previous =>
157
+ previous?.width === width && previous.height === height ? previous : { width, height }
158
+ )
159
+ }
160
+ measure()
161
+ const observer = new view.ResizeObserver(measure)
162
+ observer.observe(node)
163
+ return () => observer.disconnect()
164
+ }, [showPlot])
165
+ return (
166
+ <figure
167
+ {...nativeProps}
168
+ aria-labelledby={captionId}
169
+ aria-describedby={joinIds(descriptionId, describedBy)}
170
+ data-slot={joinIds('chart', `${kind}-chart`, props['data-slot'])}
171
+ data-kind={kind}
172
+ className={cn(
173
+ 'm-0 grid min-w-0 gap-[var(--rad-chart-gap,var(--rad-spacing-group-gap,1rem))] text-[var(--rad-color-foreground)] font-[family-name:var(--rad-typography-roles-ui-body-family,system-ui,sans-serif)] text-[length:var(--rad-typography-roles-ui-body-size,0.875rem)] leading-[var(--rad-typography-roles-ui-body-line-height,1.5)]',
174
+ className
175
+ )}
176
+ >
177
+ <figcaption
178
+ id={captionId}
179
+ className={cn('font-semibold', parts?.caption?.className)}
180
+ style={parts?.caption?.style}
181
+ >
182
+ {label}
183
+ </figcaption>
184
+ {description && (
185
+ <div
186
+ id={descriptionId}
187
+ className={parts?.description?.className}
188
+ style={parts?.description?.style}
189
+ >
190
+ {description}
191
+ </div>
192
+ )}
193
+ {ordered.length ? (
194
+ <ScrollArea
195
+ aria-label={plotLabel}
196
+ orientation="horizontal"
197
+ >
198
+ <div
199
+ ref={root}
200
+ className={cn('relative h-[var(--rad-chart-height,20rem)]', parts?.plot?.className)}
201
+ style={{ minWidth: Math.max(480, data.length * 72), ...parts?.plot?.style }}
202
+ >
203
+ <svg
204
+ aria-hidden="true"
205
+ focusable="false"
206
+ viewBox={`0 0 ${model.width} ${model.height}`}
207
+ preserveAspectRatio="none"
208
+ className="block size-full overflow-visible"
209
+ >
210
+ {model.ticks.map((tick, index) => (
211
+ <g key={index}>
212
+ <line
213
+ x1={48}
214
+ x2={model.width - 24}
215
+ y1={tick.y}
216
+ y2={tick.y}
217
+ stroke="var(--rad-chart-grid-color,var(--rad-color-border))"
218
+ className="forced-colors:stroke-[CanvasText]"
219
+ />
220
+ <text
221
+ x={40}
222
+ y={tick.y + 4}
223
+ textAnchor="end"
224
+ fill="var(--rad-color-muted-foreground)"
225
+ fontSize={12}
226
+ >
227
+ {formatValue(tick.value, series[0]!)}
228
+ </text>
229
+ </g>
230
+ ))}
231
+ {model.labels.map((item, index) => (
232
+ <text
233
+ key={index}
234
+ x={item.x}
235
+ y={model.height - 16}
236
+ textAnchor="middle"
237
+ fill="var(--rad-color-foreground)"
238
+ fontSize={12}
239
+ >
240
+ {item.label}
241
+ </text>
242
+ ))}
243
+ {model.paths.map((path, index) => (
244
+ <g key={index}>
245
+ {kind === 'area' && (
246
+ <path
247
+ d={path.area}
248
+ fill={color(path.series)}
249
+ opacity={0.15}
250
+ className="forced-colors:fill-[Canvas]"
251
+ />
252
+ )}
253
+ {kind !== 'bar' && (
254
+ <path
255
+ d={path.line}
256
+ fill="none"
257
+ stroke={color(path.series)}
258
+ strokeWidth="var(--rad-chart-stroke-width,2)"
259
+ strokeDasharray={dashes[path.series]}
260
+ className="forced-colors:stroke-[CanvasText]"
261
+ />
262
+ )}
263
+ </g>
264
+ ))}
265
+ {ordered.map(mark => {
266
+ const index = kind === 'pie' ? mark.row : mark.series
267
+ return kind === 'pie' ? (
268
+ <path
269
+ key={`${mark.row}-${mark.series}`}
270
+ d={mark.path}
271
+ fill={color(index)}
272
+ stroke="var(--rad-color-surface)"
273
+ strokeWidth={2}
274
+ className="forced-colors:fill-[Canvas] forced-colors:stroke-[CanvasText]"
275
+ />
276
+ ) : kind === 'bar' ? (
277
+ <rect
278
+ key={`${mark.row}-${mark.series}`}
279
+ x={mark.x - mark.width! / 2}
280
+ y={mark.top}
281
+ width={mark.width}
282
+ height={mark.height}
283
+ fill={color(index)}
284
+ stroke={color(index)}
285
+ className="forced-colors:fill-[Canvas] forced-colors:stroke-[CanvasText]"
286
+ />
287
+ ) : (
288
+ <circle
289
+ key={`${mark.row}-${mark.series}`}
290
+ cx={mark.x}
291
+ cy={mark.y}
292
+ r={3}
293
+ fill={color(index)}
294
+ className="forced-colors:fill-[CanvasText]"
295
+ />
296
+ )
297
+ })}
298
+ </svg>
299
+ {ordered.map((mark, index) => {
300
+ const row = data[mark.row]!,
301
+ item = series[mark.series]!,
302
+ text = `${row.label}, ${item.label}: ${formatValue(mark.value, item)}`
303
+ return (
304
+ <div
305
+ key={`${row.key}-${item.key}`}
306
+ className="absolute -translate-x-1/2 -translate-y-1/2"
307
+ style={{
308
+ left: `${(mark.x / model.width) * 100}%`,
309
+ top: `${(mark.y / model.height) * 100}%`
310
+ }}
311
+ >
312
+ <Tooltip openDelay={150}>
313
+ <TooltipTrigger
314
+ aria-label={text}
315
+ data-slot="chart-point"
316
+ tabIndex={Math.min(focused, ordered.length - 1) === index ? 0 : -1}
317
+ variant="ghost"
318
+ tone="neutral"
319
+ className={cn(
320
+ 'size-6 min-h-0 rounded-full border-0 bg-transparent bg-none p-0 shadow-none',
321
+ parts?.point?.className
322
+ )}
323
+ style={parts?.point?.style}
324
+ onClick={event => event.preventDefault()}
325
+ onFocus={() => setFocused(index)}
326
+ onKeyDown={event => {
327
+ if (event.altKey || event.ctrlKey || event.metaKey) return
328
+ const rtl =
329
+ event.currentTarget.ownerDocument.defaultView!.getComputedStyle(
330
+ event.currentTarget
331
+ ).direction === 'rtl'
332
+ let next: number | undefined
333
+ if (event.key === 'Home') next = 0
334
+ else if (event.key === 'End') next = ordered.length - 1
335
+ else if (event.key === 'ArrowRight') next = index + (rtl ? -1 : 1)
336
+ else if (event.key === 'ArrowLeft') next = index + (rtl ? 1 : -1)
337
+ else if (event.key === 'ArrowDown') next = index + 1
338
+ else if (event.key === 'ArrowUp') next = index - 1
339
+ if (next !== undefined) {
340
+ event.preventDefault()
341
+ root.current
342
+ ?.querySelectorAll<HTMLButtonElement>('[data-slot~="chart-point"]')
343
+ [Math.max(0, Math.min(ordered.length - 1, next))]?.focus()
344
+ }
345
+ }}
346
+ >
347
+ <span aria-hidden="true">·</span>
348
+ </TooltipTrigger>
349
+ <TooltipContent
350
+ className={parts?.tooltip?.className}
351
+ style={parts?.tooltip?.style}
352
+ >
353
+ {text}
354
+ </TooltipContent>
355
+ </Tooltip>
356
+ </div>
357
+ )
358
+ })}
359
+ </div>
360
+ </ScrollArea>
361
+ ) : (
362
+ <p>{emptyText}</p>
363
+ )}
364
+ <ul
365
+ className={cn('m-0 flex list-none flex-wrap gap-4 p-0', parts?.legend?.className)}
366
+ style={parts?.legend?.style}
367
+ aria-label={legendLabel}
368
+ >
369
+ {(kind === 'pie' ? data.map(row => ({ key: row.key, label: row.label })) : series).map(
370
+ (item, index) => (
371
+ <li
372
+ key={item.key}
373
+ className="flex items-center gap-2"
374
+ >
375
+ <svg
376
+ aria-hidden="true"
377
+ width={28}
378
+ height={12}
379
+ >
380
+ <line
381
+ x1={0}
382
+ x2={28}
383
+ y1={6}
384
+ y2={6}
385
+ stroke={color(index)}
386
+ strokeWidth={3}
387
+ strokeDasharray={dashes[index % dashes.length]}
388
+ className="forced-colors:stroke-[CanvasText]"
389
+ />
390
+ </svg>
391
+ {index + 1}. {item.label}
392
+ </li>
393
+ )
394
+ )}
395
+ </ul>
396
+ <details>
397
+ <summary className="cursor-pointer">{tableLabel}</summary>
398
+ <ChartDataTable
399
+ label={typeof label === 'string' ? `${label} data` : 'Chart data'}
400
+ data={data}
401
+ series={series}
402
+ formatValue={formatValue}
403
+ categoryLabel={categoryLabel}
404
+ className={parts?.table?.className}
405
+ style={parts?.table?.style}
406
+ />
407
+ </details>
408
+ </figure>
409
+ )
410
+ }
411
+ export function LineChart(props: ChartProps) {
412
+ return (
413
+ <Chart
414
+ {...props}
415
+ kind="line"
416
+ />
417
+ )
418
+ }
419
+ export function BarChart(props: ChartProps) {
420
+ return (
421
+ <Chart
422
+ {...props}
423
+ kind="bar"
424
+ />
425
+ )
426
+ }
427
+ export function AreaChart(props: ChartProps) {
428
+ return (
429
+ <Chart
430
+ {...props}
431
+ kind="area"
432
+ />
433
+ )
434
+ }
435
+ export function PieChart(props: PieChartProps) {
436
+ return (
437
+ <Chart
438
+ {...props}
439
+ kind="pie"
440
+ />
441
+ )
442
+ }
@@ -0,0 +1,16 @@
1
+ export {
2
+ LineChart,
3
+ BarChart,
4
+ AreaChart,
5
+ PieChart,
6
+ ChartDataTable,
7
+ type ChartProps,
8
+ type LineChartProps,
9
+ type BarChartProps,
10
+ type AreaChartProps,
11
+ type PieChartProps,
12
+ type ChartDataTableProps,
13
+ type ChartDatum,
14
+ type ChartSeries
15
+ } from './Charts.js'
16
+ export { chartPalette } from './palette.js'
@@ -0,0 +1,21 @@
1
+ import type { ColorPalette } from '../color/recommendColorPalette.js'
2
+ export function chartPalette(palette: ColorPalette) {
3
+ const roles = ['primary', 'support', 'success', 'warning', 'danger', 'neutral'] as const
4
+ const mode = (mode: 'light' | 'dark') =>
5
+ Object.fromEntries(
6
+ roles.map((role, index) => [
7
+ `series${index + 1}`,
8
+ role === 'neutral'
9
+ ? palette.working[role][mode].foreground
10
+ : palette.working[role][mode].background
11
+ ])
12
+ ) as {
13
+ series1: string
14
+ series2: string
15
+ series3: string
16
+ series4: string
17
+ series5: string
18
+ series6: string
19
+ }
20
+ return { light: mode('light'), dark: mode('dark') }
21
+ }
package/src/cn.ts CHANGED
@@ -72,6 +72,7 @@ export const cn: CnFunction = createCn({
72
72
  'text-(--rad-tabs-font-size)'
73
73
  ],
74
74
  h: [
75
+ 'h-(--rad-chart-height)',
75
76
  'h-(--rad-resizable-handle-size)',
76
77
  'h-(--rad-meter-height)',
77
78
  'h-(--rad-native-select-height)',
@@ -118,6 +119,9 @@ export const cn: CnFunction = createCn({
118
119
  ],
119
120
  mb: ['mb-(--rad-multi-select-gap)', 'mb-(--rad-fieldset-gap)'],
120
121
  gap: [
122
+ 'gap-(--rad-chart-gap)',
123
+ 'gap-(--rad-carousel-gap)',
124
+ 'gap-(--rad-carousel-slide-gap)',
121
125
  'gap-(--rad-form-gap)',
122
126
  'gap-(--rad-sidebar-gap)',
123
127
  'gap-(--rad-navigation-menu-gap)',
@@ -199,6 +203,7 @@ export const cn: CnFunction = createCn({
199
203
  'p-(--rad-tabs-content-padding)'
200
204
  ],
201
205
  rounded: [
206
+ 'rounded-(--rad-carousel-radius)',
202
207
  'rounded-(--rad-navigation-menu-radius)',
203
208
  'rounded-(--rad-code-block-radius)',
204
209
  'rounded-(--rad-inline-code-radius)',
@@ -342,7 +347,7 @@ export const cn: CnFunction = createCn({
342
347
  '[animation-duration:var(--rad-spinner-duration)]',
343
348
  '[animation-duration:var(--rad-skeleton-duration)]'
344
349
  ],
345
- 'stroke-w': ['stroke-(--rad-spinner-stroke-width)'],
350
+ 'stroke-w': ['stroke-(--rad-chart-stroke-width)', 'stroke-(--rad-spinner-stroke-width)'],
346
351
  opacity: ['opacity-(--rad-spinner-track-opacity)', 'opacity-(--rad-tabs-disabled-opacity)'],
347
352
  'backdrop-filter': [
348
353
  '[backdrop-filter:var(--rad-popover-backdrop-filter)]',
package/src/index.ts CHANGED
@@ -751,3 +751,19 @@ export {
751
751
  type FormState,
752
752
  type FormSubmitContext
753
753
  } from './Form.js'
754
+
755
+ export {
756
+ Carousel,
757
+ CarouselViewport,
758
+ CarouselPrevious,
759
+ CarouselNext,
760
+ CarouselIndicators,
761
+ CarouselAutoPlay,
762
+ useCarousel,
763
+ type CarouselProps,
764
+ type CarouselItem,
765
+ type CarouselState,
766
+ type CarouselViewportProps,
767
+ type CarouselActionProps,
768
+ type CarouselIndicatorsProps
769
+ } from './Carousel.js'
@@ -0,0 +1,150 @@
1
+ export type ChartDatum = {
2
+ key: string
3
+ label: string
4
+ values: Readonly<Record<string, number | null>>
5
+ }
6
+ export type ChartSeries = { key: string; label: string }
7
+ export type ChartKind = 'line' | 'bar' | 'area' | 'pie'
8
+ export type ChartMark = {
9
+ row: number
10
+ series: number
11
+ value: number
12
+ x: number
13
+ y: number
14
+ path?: string
15
+ width?: number
16
+ height?: number
17
+ top?: number
18
+ }
19
+ export function validateChart(
20
+ data: readonly ChartDatum[],
21
+ series: readonly ChartSeries[],
22
+ pie = false
23
+ ) {
24
+ for (const [name, values] of [
25
+ ['data', data],
26
+ ['series', series]
27
+ ] as const) {
28
+ const keys = values.map(item => item.key)
29
+ if (
30
+ keys.some(key => !key.trim()) ||
31
+ new Set(keys).size !== keys.length ||
32
+ values.some(item => !item.label.trim())
33
+ )
34
+ throw new TypeError(`Chart ${name} needs unique nonempty keys and nonempty labels.`)
35
+ }
36
+ if (!series.length || series.length > 6 || (pie && series.length !== 1))
37
+ throw new TypeError(pie ? 'PieChart needs one series.' : 'Charts need one to six series.')
38
+ for (const row of data)
39
+ for (const item of series) {
40
+ const value = row.values[item.key]
41
+ if (value != null && (!Number.isFinite(value) || (pie && value < 0)))
42
+ throw new TypeError('Chart values must be finite; pie values must also be nonnegative.')
43
+ }
44
+ }
45
+ const point = (x: number, y: number) => `${Number(x.toFixed(4))} ${Number(y.toFixed(4))}`
46
+ export function chartGeometry(
47
+ kind: ChartKind,
48
+ data: readonly ChartDatum[],
49
+ series: readonly ChartSeries[],
50
+ viewport?: { width: number; height: number } | null
51
+ ) {
52
+ validateChart(data, series, kind === 'pie')
53
+ const width = Math.max(480, data.length * 72, viewport?.width ?? 0),
54
+ height = Math.max(160, viewport?.height ?? 320),
55
+ left = 48,
56
+ right = 24,
57
+ top = 24,
58
+ bottom = 44,
59
+ innerWidth = width - left - right,
60
+ innerHeight = height - top - bottom
61
+ const marks: ChartMark[] = [],
62
+ paths: { series: number; line: string; area: string }[] = [],
63
+ ticks: { value: number; y: number }[] = []
64
+ if (kind === 'pie') {
65
+ const values = data.map(row => row.values[series[0]!.key] ?? 0),
66
+ magnitude = Math.max(1, ...values),
67
+ total = values.reduce((sum, value) => sum + value / magnitude, 0),
68
+ cx = width / 2,
69
+ cy = (height - bottom) / 2,
70
+ radius = Math.min(width / 2 - 32, (height - bottom) / 2 - 16)
71
+ let start = -Math.PI / 2
72
+ values.forEach((value, row) => {
73
+ if (value <= 0 || total <= 0) return
74
+ const angle = (value / magnitude / total) * Math.PI * 2,
75
+ end = start + angle,
76
+ middle = start + angle / 2,
77
+ coords = (a: number) => point(cx + Math.cos(a) * radius, cy + Math.sin(a) * radius)
78
+ marks.push({
79
+ row,
80
+ series: 0,
81
+ value,
82
+ x: cx + Math.cos(middle) * radius * 0.65,
83
+ y: cy + Math.sin(middle) * radius * 0.65,
84
+ path: `M ${point(cx, cy)} L ${coords(start)} A ${radius} ${radius} 0 0 1 ${coords(middle)} A ${radius} ${radius} 0 0 1 ${coords(end)} Z`
85
+ })
86
+ start = end
87
+ })
88
+ return { width, height, marks, paths, ticks, zero: cy, labels: [] }
89
+ }
90
+ const values = data.flatMap(row => series.flatMap(item => row.values[item.key] ?? [])),
91
+ magnitude = Math.max(1, ...values.map(Math.abs)),
92
+ low = Math.min(0, ...values.map(value => value / magnitude)),
93
+ rawHigh = Math.max(0, ...values.map(value => value / magnitude)),
94
+ high = rawHigh === low ? low + 1 : rawHigh,
95
+ span = high - low
96
+ const y = (value: number) => top + ((high - value / magnitude) / span) * innerHeight,
97
+ zero = y(0),
98
+ step = innerWidth / Math.max(1, data.length)
99
+ for (let i = 0; i < 5; i++) {
100
+ const normalized = low + (span * i) / 4
101
+ ticks.push({ value: normalized * magnitude, y: top + innerHeight - (innerHeight * i) / 4 })
102
+ }
103
+ series.forEach((item, seriesIndex) => {
104
+ let segment: ChartMark[] = []
105
+ const close = () => {
106
+ if (!segment.length) return
107
+ const line = segment
108
+ .map((mark, index) => `${index ? 'L' : 'M'} ${point(mark.x, mark.y)}`)
109
+ .join(' ')
110
+ paths.push({
111
+ series: seriesIndex,
112
+ line,
113
+ area: `${line} L ${point(segment.at(-1)!.x, zero)} L ${point(segment[0]!.x, zero)} Z`
114
+ })
115
+ segment = []
116
+ }
117
+ data.forEach((row, rowIndex) => {
118
+ const value = row.values[item.key]
119
+ if (value == null) {
120
+ close()
121
+ return
122
+ }
123
+ const x = left + step * (rowIndex + 0.5),
124
+ barWidth = (step * 0.75) / series.length,
125
+ barLeft = x - step * 0.375 + seriesIndex * barWidth
126
+ const mark: ChartMark = {
127
+ row: rowIndex,
128
+ series: seriesIndex,
129
+ value,
130
+ x: kind === 'bar' ? barLeft + barWidth / 2 : x,
131
+ y: y(value),
132
+ width: barWidth * 0.9,
133
+ height: Math.abs(y(value) - zero),
134
+ top: Math.min(y(value), zero)
135
+ }
136
+ marks.push(mark)
137
+ segment.push(mark)
138
+ })
139
+ close()
140
+ })
141
+ return {
142
+ width,
143
+ height,
144
+ marks,
145
+ paths,
146
+ ticks,
147
+ zero,
148
+ labels: data.map((row, index) => ({ label: row.label, x: left + step * (index + 0.5) }))
149
+ }
150
+ }