@tylix/charts 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.d.ts CHANGED
@@ -103,7 +103,8 @@ export function sparklineSvg(data?: Array<number | null>, options?: SparklineOpt
103
103
  export interface LineSeriesInput {
104
104
  name?: string
105
105
  color?: string
106
- data: Array<number | null | { x?: number; y: number | null }>
106
+ /** x may be a Date: the chart then gets a time axis. */
107
+ data: Array<number | null | { x?: number | Date; y: number | null }>
107
108
  }
108
109
 
109
110
  export interface LineChartOptions {
@@ -117,9 +118,14 @@ export interface LineChartOptions {
117
118
  curve?: Curve
118
119
  area?: boolean
119
120
  zeroBaseline?: boolean
120
- formatX?: (value: number) => string
121
+ /** With Date x values this receives a Date. Default: String, or a date format for time axes. */
122
+ formatX?: (value: any) => string
121
123
  formatY?: (value: number) => string
122
124
  label?: string
125
+ /** Time axes: 'UTC' (default), 'local', or an IANA zone like 'Europe/Paris'. */
126
+ timeZone?: string
127
+ /** Time axes: Intl locale for labels. Default 'en-US'. */
128
+ locale?: string
123
129
  }
124
130
 
125
131
  export interface XYTick {
@@ -133,6 +139,10 @@ export interface LineChartGeometry {
133
139
  plot: { x: number; y: number; width: number; height: number }
134
140
  xScale: LinearScale
135
141
  yScale: LinearScale
142
+ /** true when x values are Dates (plotted as milliseconds). */
143
+ time: boolean
144
+ /** Formats an x value for tooltips (dates for time axes). */
145
+ formatX: (value: number) => string
136
146
  xTicks: Array<XYTick & { x: number }>
137
147
  yTicks: Array<XYTick & { y: number }>
138
148
  series: Array<{
@@ -381,3 +391,143 @@ export function attachCrosshair(
381
391
  chart: LineChartGeometry | AreaChartGeometry,
382
392
  options?: CrosshairOptions
383
393
  ): { show(px: number): void; hide(): void; destroy(): void }
394
+
395
+ // ---------------------------------------------------------------- time
396
+
397
+ export type TimeUnit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'
398
+ export interface TimeAxisOptions { timeZone?: string; locale?: string }
399
+ export function isTimeData(series: Array<{ data?: unknown[] }>): boolean
400
+ export function timeInterval(start: number, end: number, count?: number): { unit: TimeUnit; step: number }
401
+ export function timeTicks(start: number, end: number, count?: number, options?: TimeAxisOptions): { ticks: number[]; unit: TimeUnit; step: number }
402
+ export function timeFormatter(unit: TimeUnit, options?: TimeAxisOptions): (ms: number) => string
403
+ export function timeAxis(
404
+ start: number | Date,
405
+ end: number | Date,
406
+ count?: number,
407
+ options?: TimeAxisOptions,
408
+ ): { ticks: { value: number; label: string }[]; unit: TimeUnit; step: number; format: (ms: number) => string; tooltip: (ms: number) => string }
409
+
410
+ // ------------------------------------------------------- scatter / bubble
411
+
412
+ export interface ScatterPointInput { x: number | Date; y: number; size?: number; label?: string }
413
+ export interface ScatterSeriesInput { name?: string; color?: string; data: ScatterPointInput[] }
414
+ export interface ScatterChartOptions {
415
+ width?: number
416
+ height?: number
417
+ margin?: Partial<Margin>
418
+ xDomain?: [number | Date, number | Date]
419
+ yDomain?: [number, number]
420
+ xTicks?: number
421
+ yTicks?: number
422
+ /** Bubble radius range for points with `size`. Default [4, 22]. */
423
+ radius?: [number, number]
424
+ /** Radius of points without `size`. Default 4.5. */
425
+ pointRadius?: number
426
+ formatX?: (value: any) => string
427
+ formatY?: (value: number) => string
428
+ timeZone?: string
429
+ locale?: string
430
+ }
431
+ export interface ScatterPoint { x: number; y: number; size: number | null; label: string | null; px: number; py: number; r: number }
432
+ export interface ScatterChartGeometry {
433
+ width: number
434
+ height: number
435
+ plot: { x: number; y: number; width: number; height: number }
436
+ time: boolean
437
+ formatX: (value: number) => string
438
+ formatY: (value: number) => string
439
+ xTicks: Array<XYTick & { x: number }>
440
+ yTicks: Array<XYTick & { y: number }>
441
+ series: Array<{ name: string; color: string; points: ScatterPoint[] }>
442
+ }
443
+ export function scatterChart(series?: ScatterSeriesInput[], options?: ScatterChartOptions): ScatterChartGeometry
444
+ export function nearestScatterPoint(chart: ScatterChartGeometry, px: number, py: number, max?: number): (ScatterPoint & { name: string; color: string }) | null
445
+ export function scatterChartSvg(series?: ScatterSeriesInput[], options?: ScatterChartOptions & SvgOptions): string
446
+
447
+ // ---------------------------------------------------------------- gauge
448
+
449
+ export interface GaugeOptions {
450
+ min?: number
451
+ max?: number
452
+ size?: number
453
+ /** Ring thickness as a share of the radius. Default 0.16. */
454
+ thickness?: number
455
+ /** Degrees from 12 o'clock, clockwise. Default -120 / 120. */
456
+ startAngle?: number
457
+ endAngle?: number
458
+ cornerRadius?: number
459
+ /** The value arc takes the colour of the band the value is in. */
460
+ thresholds?: Array<{ value: number; color: string }>
461
+ /** Draw the threshold bands outside the track. */
462
+ bands?: boolean
463
+ color?: string
464
+ format?: (value: number) => string
465
+ }
466
+ export interface GaugeGeometry {
467
+ size: number
468
+ cx: number
469
+ cy: number
470
+ min: number
471
+ max: number
472
+ value: number
473
+ percent: number
474
+ angle: number
475
+ color: string
476
+ label: string
477
+ track: string
478
+ valuePath: string
479
+ needle: { x: number; y: number }
480
+ bands: Array<{ path: string; color: string }>
481
+ bottom: number
482
+ }
483
+ export function gauge(value: number, options?: GaugeOptions): GaugeGeometry
484
+ export function gaugeSvg(value: number, options?: GaugeOptions & SvgOptions & { caption?: string; needle?: boolean; showMinMax?: boolean }): string
485
+
486
+ // ------------------------------------------------------ calendar heatmap
487
+
488
+ export type HeatmapInput = Array<{ date: string | Date; value: number }> | Record<string, number>
489
+ export interface CalendarHeatmapOptions {
490
+ from?: string | Date
491
+ to?: string | Date
492
+ /** 0 = Sunday (default), 1 = Monday */
493
+ weekStart?: 0 | 1
494
+ cell?: number
495
+ gap?: number
496
+ levels?: number
497
+ max?: number
498
+ locale?: string
499
+ labels?: boolean
500
+ }
501
+ export interface HeatmapCell { date: string; value: number; level: number; x: number; y: number }
502
+ export interface CalendarHeatmapGeometry {
503
+ width: number
504
+ height: number
505
+ cell: number
506
+ cells: HeatmapCell[]
507
+ months: Array<{ label: string; x: number }>
508
+ days: Array<{ label: string; y: number }>
509
+ levels: number
510
+ max: number
511
+ total: number
512
+ }
513
+ export function calendarHeatmap(data?: HeatmapInput, options?: CalendarHeatmapOptions): CalendarHeatmapGeometry
514
+ export function calendarHeatmapSvg(
515
+ data?: HeatmapInput,
516
+ options?: CalendarHeatmapOptions & SvgOptions & { color?: string; formatValue?: (v: number) => string; legend?: boolean },
517
+ ): string
518
+
519
+ // ------------------------------------------------------------ a11y
520
+
521
+ export function describeSeries(series: Array<{ name?: string; data?: unknown[]; points?: unknown[] }>, options?: { formatY?: (v: number) => string }): string
522
+ export function dataTable(
523
+ series: Array<{ name?: string; data?: unknown[] }>,
524
+ options?: { caption?: string; formatX?: (v: any) => string; formatY?: (v: number) => string; className?: string },
525
+ ): string
526
+ export const SR_ONLY_STYLE: string
527
+
528
+ // --------------------------------------------------------- any chart
529
+
530
+ export type ChartType = 'sparkline' | 'line' | 'area' | 'bar' | 'pie' | 'donut' | 'scatter' | 'gauge' | 'heatmap'
531
+ export const CHART_TYPES: Record<ChartType, (data: any, options?: any) => string>
532
+ export function renderChart(type: ChartType, data: unknown, options?: Record<string, unknown>): string
533
+ export function chartGeometry(type: ChartType, data: unknown, options?: Record<string, unknown>): LineChartGeometry | AreaChartGeometry | null
package/src/index.js CHANGED
@@ -14,5 +14,16 @@ export {
14
14
  barChartSvg,
15
15
  pieChartSvg,
16
16
  donutChartSvg,
17
+ scatterChartSvg,
18
+ gaugeSvg,
19
+ calendarHeatmapSvg,
20
+ renderChart,
21
+ chartGeometry,
22
+ CHART_TYPES,
17
23
  } from './svg.js'
24
+ export { scatterChart, nearestScatterPoint } from './scatter.js'
25
+ export { gauge } from './gauge.js'
26
+ export { calendarHeatmap } from './heatmap.js'
27
+ export { timeAxis, timeTicks, timeInterval, timeFormatter, isTimeData } from './time.js'
28
+ export { describeSeries, dataTable, SR_ONLY_STYLE } from './a11y.js'
18
29
  export { attachCrosshair, nearestPoints, snapPositions } from './crosshair.js'
package/src/line.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { linearScale } from './scales.js'
2
2
  import { linePath, areaPath } from './path.js'
3
3
  import { extent } from './ticks.js'
4
+ import { isTimeData, timeAxis, isDate } from './time.js'
4
5
 
5
6
  export const DEFAULT_PALETTE = [
6
7
  'var(--tylix-chart-1, #2563eb)',
@@ -10,15 +11,45 @@ export const DEFAULT_PALETTE = [
10
11
  'var(--tylix-chart-5, #7c3aed)',
11
12
  ]
12
13
 
13
- // Accepts [1, 2, 3] (x = index) or [{ x, y }, ...]
14
+ // Accepts [1, 2, 3] (x = index) or [{ x, y }, ...]. Date x values
15
+ // become milliseconds (see time.js).
14
16
  export function normalizeData(data = []) {
15
17
  return data.map((d, i) => {
16
18
  if (typeof d === 'number') return { x: i, y: d }
17
19
  if (d == null) return { x: i, y: null }
18
- return { x: d.x ?? i, y: d.y ?? null }
20
+ const x = isDate(d.x) ? d.x.getTime() : d.x ?? i
21
+ return { x, y: d.y ?? null }
19
22
  })
20
23
  }
21
24
 
25
+ // A label that would run past the chart edge is anchored inward.
26
+ export function anchorTicks(ticks, width, charWidth = 6.2) {
27
+ return ticks.map((t) => {
28
+ const half = (String(t.label).length * charWidth) / 2
29
+ const anchor = t.x - half < 0 ? 'start' : t.x + half > width ? 'end' : 'middle'
30
+ return anchor === 'middle' ? t : { ...t, anchor }
31
+ })
32
+ }
33
+
34
+ // X ticks and the x formatter, for numbers or time.
35
+ export function xAxis(series, xScale, xd, count, { formatX, timeZone, locale } = {}) {
36
+ if (isTimeData(series)) {
37
+ const axis = timeAxis(xd[0], xd[1], count, { timeZone, locale })
38
+ return {
39
+ time: true,
40
+ ticks: axis.ticks.map((t) => ({ value: t.value, x: xScale(t.value), label: formatX ? formatX(new Date(t.value)) : t.label })),
41
+ // Tooltips get a fuller date than the tick labels.
42
+ format: formatX ? (v) => formatX(new Date(v)) : axis.tooltip,
43
+ }
44
+ }
45
+ const format = formatX ?? ((v) => String(v))
46
+ return {
47
+ time: false,
48
+ ticks: xScale.ticks(count).filter((v) => v >= xd[0] && v <= xd[1]).map((v) => ({ value: v, x: xScale(v), label: format(v) })),
49
+ format,
50
+ }
51
+ }
52
+
22
53
  /**
23
54
  * Computes line chart geometry. Returns plain data so a .tyx template can
24
55
  * render it with {{#each}}, or pass it to lineChartSvg() for a string.
@@ -38,7 +69,9 @@ export function lineChart(
38
69
  curve = 'linear',
39
70
  area = false,
40
71
  zeroBaseline = false,
41
- formatX = (v) => String(v),
72
+ formatX,
73
+ timeZone,
74
+ locale,
42
75
  formatY = (v) => String(v),
43
76
  } = {}
44
77
  ) {
@@ -71,6 +104,7 @@ export function lineChart(
71
104
  }
72
105
 
73
106
  const x = linearScale({ domain: xd, range: [plot.x, plot.x + plot.width] })
107
+ const xa = xAxis(series, x, xd, xTicks, { formatX, timeZone, locale })
74
108
  const y = linearScale({ domain: yd, range: [plot.y + plot.height, plot.y] })
75
109
  // Fill down to zero when it is inside the domain, otherwise to the bottom edge.
76
110
  const baselineY = yd[0] <= 0 && yd[1] >= 0 ? y(0) : y(yd[0])
@@ -81,11 +115,9 @@ export function lineChart(
81
115
  plot,
82
116
  xScale: x,
83
117
  yScale: y,
84
- xTicks: x.ticks(xTicks).filter((v) => v >= xd[0] && v <= xd[1]).map((v) => ({
85
- value: v,
86
- x: x(v),
87
- label: formatX(v),
88
- })),
118
+ xTicks: anchorTicks(xa.ticks, width),
119
+ time: xa.time,
120
+ formatX: xa.format,
89
121
  yTicks: y.ticks(yTicks).filter((v) => v >= yd[0] && v <= yd[1]).map((v) => ({
90
122
  value: v,
91
123
  y: y(v),
package/src/scatter.js ADDED
@@ -0,0 +1,109 @@
1
+ import { linearScale } from './scales.js'
2
+ import { extent } from './ticks.js'
3
+ import { DEFAULT_PALETTE, xAxis, anchorTicks } from './line.js'
4
+ import { toTime, isDate } from './time.js'
5
+
6
+ /**
7
+ * Scatter / bubble chart geometry.
8
+ *
9
+ * series: [{ name, color?, data: [{ x, y, size?, label? }] }]
10
+ * x may be a number or a Date. With `size` on points it becomes a
11
+ * bubble chart: radius grows with the square root of size (area is
12
+ * proportional to the value), between radius[0] and radius[1].
13
+ *
14
+ * Returns { width, height, plot, xTicks, yTicks, series: [{ name,
15
+ * color, points: [{ x, y, size, label, px, py, r }] }], formatX, time }
16
+ */
17
+ export function scatterChart(
18
+ series = [],
19
+ {
20
+ width = 480,
21
+ height = 280,
22
+ margin = {},
23
+ xDomain,
24
+ yDomain,
25
+ xTicks = 6,
26
+ yTicks = 5,
27
+ radius = [4, 22],
28
+ pointRadius = 4.5,
29
+ formatX,
30
+ formatY = (v) => String(v),
31
+ timeZone,
32
+ locale,
33
+ } = {},
34
+ ) {
35
+ const m = { top: 12, right: 16, bottom: 28, left: 44, ...margin }
36
+ const plot = {
37
+ x: m.left,
38
+ y: m.top,
39
+ width: Math.max(0, width - m.left - m.right),
40
+ height: Math.max(0, height - m.top - m.bottom),
41
+ }
42
+ const normalized = series.map((s, i) => ({
43
+ name: s.name ?? `Series ${i + 1}`,
44
+ color: s.color ?? DEFAULT_PALETTE[i % DEFAULT_PALETTE.length],
45
+ data: (s.data ?? [])
46
+ .map((d) => ({ x: toTime(d.x), y: d.y, size: d.size ?? null, label: d.label ?? null }))
47
+ .filter((d) => Number.isFinite(d.x) && Number.isFinite(d.y)),
48
+ }))
49
+ const all = normalized.flatMap((s) => s.data)
50
+ const pad = (ext) => {
51
+ if (!ext) return [0, 1]
52
+ if (ext[0] === ext[1]) return [ext[0] - 1, ext[1] + 1]
53
+ const t = linearScale({ domain: ext }).ticks(5)
54
+ return t.length > 1 ? [t[0], t.at(-1)] : ext
55
+ }
56
+ const time = series.some((s) => (s.data ?? []).some((d) => isDate(d?.x)))
57
+ const xd = xDomain?.map(toTime) ?? (time ? extent(all.map((d) => d.x)) ?? [0, 1] : pad(extent(all.map((d) => d.x))))
58
+ const yd = yDomain ?? pad(extent(all.map((d) => d.y)))
59
+ // inset by the largest radius so edge points are not clipped
60
+ const inset = Math.min(plot.width / 4, plot.height / 4, all.some((d) => d.size != null) ? radius[1] : pointRadius + 1)
61
+ const x = linearScale({ domain: xd, range: [plot.x + inset, plot.x + plot.width - inset] })
62
+ const y = linearScale({ domain: yd, range: [plot.y + plot.height - inset, plot.y + inset] })
63
+ const xa = xAxis(series, x, xd, xTicks, { formatX, timeZone, locale })
64
+
65
+ const sizes = extent(all.map((d) => d.size))
66
+ const rOf = (size) => {
67
+ if (size == null || !sizes) return pointRadius
68
+ const [lo, hi] = sizes
69
+ const t = hi === lo ? 1 : (Math.sqrt(Math.max(0, size)) - Math.sqrt(Math.max(0, lo))) / (Math.sqrt(hi) - Math.sqrt(Math.max(0, lo)))
70
+ return radius[0] + t * (radius[1] - radius[0])
71
+ }
72
+
73
+ return {
74
+ width,
75
+ height,
76
+ plot,
77
+ time: xa.time,
78
+ formatX: xa.format,
79
+ formatY,
80
+ xScale: x,
81
+ yScale: y,
82
+ xTicks: anchorTicks(xa.ticks, width),
83
+ yTicks: y.ticks(yTicks).filter((v) => v >= yd[0] && v <= yd[1]).map((v) => ({ value: v, y: y(v), label: formatY(v) })),
84
+ series: normalized.map((s) => ({
85
+ name: s.name,
86
+ color: s.color,
87
+ // biggest first, so small bubbles stay on top
88
+ points: s.data
89
+ .map((d) => ({ ...d, px: x(d.x), py: y(d.y), r: rOf(d.size) }))
90
+ .sort((a, b) => b.r - a.r),
91
+ })),
92
+ }
93
+ }
94
+
95
+ /** The point under (px, py), or the nearest within `max` pixels. */
96
+ export function nearestScatterPoint(chart, px, py, max = 24) {
97
+ let best = null
98
+ let bestD = Infinity
99
+ for (const s of chart.series) {
100
+ for (const p of s.points) {
101
+ const d = Math.hypot(p.px - px, p.py - py) - p.r
102
+ if (d < bestD) {
103
+ bestD = d
104
+ best = { ...p, name: s.name, color: s.color }
105
+ }
106
+ }
107
+ }
108
+ return best && bestD <= max ? best : null
109
+ }
package/src/svg.js CHANGED
@@ -3,6 +3,10 @@ import { lineChart, DEFAULT_PALETTE } from './line.js'
3
3
  import { areaChart } from './area.js'
4
4
  import { barChart } from './bar.js'
5
5
  import { pieChart } from './pie.js'
6
+ import { scatterChart } from './scatter.js'
7
+ import { gauge } from './gauge.js'
8
+ import { calendarHeatmap } from './heatmap.js'
9
+ import { describeSeries } from './a11y.js'
6
10
 
7
11
  // ---------------------------------------------------------------------------
8
12
  // Shared helpers
@@ -27,10 +31,13 @@ const CHAR_W = 6.2
27
31
  let uid = 0
28
32
  const nextId = () => `tc${++uid}`
29
33
 
30
- const open = (id, w, h, label, kind) =>
34
+ // role="img" with a <title> and <desc>: screen readers announce the
35
+ // label and the plain-language summary.
36
+ const open = (id, w, h, label, kind, desc = '') =>
31
37
  `<svg xmlns="http://www.w3.org/2000/svg" class="tylix-chart tylix-chart--${kind} ${id}" ` +
32
- `width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-label="${escapeXml(label)}" ` +
33
- `font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-size="11">`
38
+ `width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img" aria-labelledby="${id}-t${desc ? ` ${id}-d` : ''}" ` +
39
+ `font-family="system-ui, -apple-system, 'Segoe UI', sans-serif" font-size="11">` +
40
+ `<title id="${id}-t">${escapeXml(label)}</title>${desc ? `<desc id="${id}-d">${escapeXml(desc)}</desc>` : ''}`
34
41
 
35
42
  const MUTED = 'fill="currentColor" fill-opacity="0.6"'
36
43
 
@@ -97,7 +104,7 @@ function gridlines(ticks, plot, horizontalLines) {
97
104
  const x = t.pos
98
105
  out +=
99
106
  `<line x1="${fmt(x)}" x2="${fmt(x)}" y1="${plot.y}" y2="${plot.y + plot.height}" ${stroke}/>` +
100
- `<text x="${fmt(x)}" y="${plot.y + plot.height + 16}" text-anchor="middle" ${MUTED}>${escapeXml(t.label)}</text>`
107
+ `<text x="${fmt(x)}" y="${plot.y + plot.height + 16}" text-anchor="${t.anchor ?? 'middle'}" ${MUTED}>${escapeXml(t.label)}</text>`
101
108
  }
102
109
  }
103
110
  return out
@@ -137,7 +144,7 @@ function xyChartSvg(c, o) {
137
144
  const { id, label, kind, fill, dots, formatX, formatY, layout, interactive } = o
138
145
  const { plot } = c
139
146
  const stacked = !!c.stacked
140
- const out = [open(id, c.width, c.height, label, kind)]
147
+ const out = [open(id, c.width, c.height, label, kind, describeSeries(c.series, { formatY }))]
141
148
 
142
149
  if (interactive && dots === 'hover') {
143
150
  out.push(
@@ -162,7 +169,7 @@ function xyChartSvg(c, o) {
162
169
  out.push(gridlines(c.yTicks, plot, true))
163
170
  for (const t of c.xTicks) {
164
171
  out.push(
165
- `<text x="${fmt(t.x)}" y="${plot.y + plot.height + 16}" text-anchor="middle" ${MUTED}>${escapeXml(t.label)}</text>`
172
+ `<text x="${fmt(t.x)}" y="${plot.y + plot.height + 16}" text-anchor="${t.anchor ?? 'middle'}" ${MUTED}>${escapeXml(t.label)}</text>`
166
173
  )
167
174
  }
168
175
 
@@ -222,7 +229,7 @@ export function lineChartSvg(series, options = {}) {
222
229
  label: options.label ?? 'Line chart',
223
230
  fill: !!options.area,
224
231
  dots: options.dots ?? 'hover',
225
- formatX: options.formatX ?? ((v) => String(v)),
232
+ formatX: options.formatX ? (v) => options.formatX(c.time ? new Date(v) : v) : c.formatX,
226
233
  formatY: options.formatY ?? ((v) => String(v)),
227
234
  layout: plan.layout,
228
235
  interactive: options.interactive ?? true,
@@ -240,7 +247,7 @@ export function areaChartSvg(series, options = {}) {
240
247
  label: options.label ?? 'Area chart',
241
248
  fill: true,
242
249
  dots: options.dots ?? 'hover',
243
- formatX: options.formatX ?? ((v) => String(v)),
250
+ formatX: options.formatX ? (v) => options.formatX(c.time ? new Date(v) : v) : c.formatX,
244
251
  formatY: options.formatY ?? ((v) => String(v)),
245
252
  layout: plan.layout,
246
253
  interactive: options.interactive ?? true,
@@ -262,7 +269,7 @@ export function barChartSvg(series, options = {}) {
262
269
  const c = barChart(series, plan.options)
263
270
  const { plot } = c
264
271
  const horizontal = c.orientation === 'horizontal'
265
- const out = [open(id, c.width, c.height, label, 'bar')]
272
+ const out = [open(id, c.width, c.height, label, 'bar', describeSeries(c.series ?? [], { formatY: options.formatValue }))]
266
273
 
267
274
  if (interactive) {
268
275
  out.push(
@@ -289,7 +296,7 @@ export function barChartSvg(series, options = {}) {
289
296
  out.push(
290
297
  horizontal
291
298
  ? `<text x="${plot.x - 8}" y="${fmt(t.pos)}" text-anchor="end" dominant-baseline="middle" ${MUTED}>${escapeXml(t.label)}</text>`
292
- : `<text x="${fmt(t.pos)}" y="${plot.y + plot.height + 16}" text-anchor="middle" ${MUTED}>${escapeXml(t.label)}</text>`
299
+ : `<text x="${fmt(t.pos)}" y="${plot.y + plot.height + 16}" text-anchor="${t.anchor ?? 'middle'}" ${MUTED}>${escapeXml(t.label)}</text>`
293
300
  )
294
301
  })
295
302
 
@@ -367,7 +374,7 @@ function pieSvg(data, options, defaultInner, kind) {
367
374
  })
368
375
  }
369
376
 
370
- const out = [open(id, fmt(W), fmt(H), label, kind)]
377
+ const out = [open(id, fmt(W), fmt(H), label, kind, g.slices.map((sl) => `${sl.label}: ${sl.valueLabel} (${sl.percentLabel})`).join(', '))]
371
378
  if (interactive) {
372
379
  out.push(
373
380
  `<style>.${id} .tc-slice{transition:opacity .15s}.${id}:hover .tc-slice{opacity:.45}.${id} .tc-slice:hover{opacity:1}</style>`
@@ -424,3 +431,163 @@ export function pieChartSvg(data, options = {}) {
424
431
  export function donutChartSvg(data, options = {}) {
425
432
  return pieSvg(data, options, 0.62, 'donut')
426
433
  }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // Scatter / bubble
437
+ // ---------------------------------------------------------------------------
438
+
439
+ /**
440
+ * Renders a scatter (or bubble, with point `size`) chart as an SVG string.
441
+ * Extra options: id, label, legend (default: 2+ series), interactive.
442
+ */
443
+ export function scatterChartSvg(series, options = {}) {
444
+ const id = options.id ?? nextId()
445
+ const { label = 'Scatter chart', interactive = true } = options
446
+ const plan = planLegend(options, seriesMeta(series))
447
+ const c = scatterChart(series, plan.options)
448
+ const { plot } = c
449
+ const fx = options.formatX ? (v) => options.formatX(c.time ? new Date(v) : v) : c.formatX
450
+ const out = [open(id, c.width, c.height, label, 'scatter', describeSeries(c.series.map((s) => ({ name: s.name, data: s.points.map((p) => p.y) })), { formatY: c.formatY }))]
451
+ if (interactive) out.push(`<style>.${id} .tc-pt{transition:fill-opacity .12s}.${id} .tc-pt:hover{fill-opacity:.95}</style>`)
452
+ if (plan.layout) out.push(legendMarkup(plan.layout, plot.x, 4))
453
+ out.push(gridlines(c.yTicks, plot, true))
454
+ for (const t of c.xTicks) {
455
+ out.push(`<line x1="${fmt(t.x)}" x2="${fmt(t.x)}" y1="${plot.y}" y2="${plot.y + plot.height}" stroke="currentColor" stroke-opacity="0.08"/>`)
456
+ out.push(`<text x="${fmt(t.x)}" y="${plot.y + plot.height + 16}" text-anchor="${t.anchor ?? 'middle'}" ${MUTED}>${escapeXml(t.label)}</text>`)
457
+ }
458
+ for (const s of c.series) {
459
+ for (const p of s.points) {
460
+ const tip = `${p.label ? `${p.label} · ` : ''}${s.name}: ${fx(p.x)}, ${c.formatY(p.y)}${p.size != null ? ` (${p.size})` : ''}`
461
+ out.push(
462
+ `<circle class="tc-pt" cx="${fmt(p.px)}" cy="${fmt(p.py)}" r="${fmt(p.r)}" fill="${escapeXml(s.color)}" fill-opacity="${p.size != null ? 0.55 : 0.85}" stroke="${escapeXml(s.color)}" stroke-width="1"><title>${escapeXml(tip)}</title></circle>`,
463
+ )
464
+ }
465
+ }
466
+ out.push('</svg>')
467
+ return out.join('')
468
+ }
469
+
470
+ // ---------------------------------------------------------------------------
471
+ // Gauge
472
+ // ---------------------------------------------------------------------------
473
+
474
+ /**
475
+ * Renders a gauge as an SVG string.
476
+ * options: everything gauge() takes, plus id, label, caption (text under
477
+ * the value), needle (default false), showMinMax (default true).
478
+ */
479
+ export function gaugeSvg(value, options = {}) {
480
+ const id = options.id ?? nextId()
481
+ const g = gauge(value, options)
482
+ const { label = 'Gauge', caption = '', needle = false, showMinMax = true } = options
483
+ const vy = needle ? g.cy + g.size * 0.22 : g.cy + 8
484
+ const captionY = vy + g.size * 0.1
485
+ const H = Math.ceil(Math.max(g.bottom + (showMinMax ? 18 : 6), (caption ? captionY : vy) + 8))
486
+ const desc = `${g.label} of ${g.min} to ${g.max} (${Math.round(g.percent * 100)}%)${caption ? `, ${caption}` : ''}`
487
+ const out = [open(id, g.size, H, label, 'gauge', desc)]
488
+ for (const b of g.bands) out.push(`<path d="${b.path}" fill="${escapeXml(b.color)}" fill-opacity="0.5"/>`)
489
+ out.push(`<path d="${g.track}" fill="currentColor" fill-opacity="0.1"/>`)
490
+ if (g.valuePath) out.push(`<path d="${g.valuePath}" fill="${escapeXml(g.color)}"/>`)
491
+ if (needle) {
492
+ out.push(
493
+ `<line x1="${g.cx}" y1="${g.cy}" x2="${fmt(g.needle.x)}" y2="${fmt(g.needle.y)}" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/>` +
494
+ `<circle cx="${g.cx}" cy="${g.cy}" r="5" fill="currentColor"/>`,
495
+ )
496
+ }
497
+ out.push(`<text x="${g.cx}" y="${fmt(vy)}" text-anchor="middle" font-size="${fmt(g.size * 0.16)}" font-weight="600" fill="currentColor">${escapeXml(g.label)}</text>`)
498
+ if (caption) out.push(`<text x="${g.cx}" y="${fmt(captionY)}" text-anchor="middle" ${MUTED}>${escapeXml(caption)}</text>`)
499
+ if (showMinMax) {
500
+ const a0 = ((options.startAngle ?? -120) * Math.PI) / 180
501
+ const a1 = ((options.endAngle ?? 120) * Math.PI) / 180
502
+ const r = g.size / 2 - 2
503
+ const at = (a) => ({ x: g.cx + r * 0.82 * Math.sin(a), y: Math.min(H - 4, g.cy - r * Math.cos(a) + 14) })
504
+ const lo = at(a0)
505
+ const hi = at(a1)
506
+ out.push(`<text x="${fmt(lo.x)}" y="${fmt(lo.y)}" text-anchor="middle" ${MUTED}>${escapeXml(String(g.min))}</text>`)
507
+ out.push(`<text x="${fmt(hi.x)}" y="${fmt(hi.y)}" text-anchor="middle" ${MUTED}>${escapeXml(String(g.max))}</text>`)
508
+ }
509
+ out.push('</svg>')
510
+ return out.join('')
511
+ }
512
+
513
+ // ---------------------------------------------------------------------------
514
+ // Calendar heatmap
515
+ // ---------------------------------------------------------------------------
516
+
517
+ // Empty days use the text color faintly; levels 1+ step up the series color.
518
+ const levelFill = (level, levels, color) =>
519
+ level === 0
520
+ ? 'fill="currentColor" fill-opacity="0.08"'
521
+ : `fill="${escapeXml(color)}" fill-opacity="${fmt(0.2 + (0.8 * level) / (levels - 1))}"`
522
+
523
+ /**
524
+ * Renders a calendar heatmap as an SVG string.
525
+ * options: everything calendarHeatmap() takes, plus id, label, color,
526
+ * formatValue, legend (default true: a "Less … More" scale).
527
+ */
528
+ export function calendarHeatmapSvg(data, options = {}) {
529
+ const id = options.id ?? nextId()
530
+ const h = calendarHeatmap(data, options)
531
+ const { label = 'Calendar heatmap', color = 'var(--tylix-chart-1, #2563eb)', formatValue = (v) => String(v), legend = true } = options
532
+ const H = h.height + (legend ? 24 : 0)
533
+ const busiest = h.cells.reduce((a, c) => (c.value > (a?.value ?? 0) ? c : a), null)
534
+ const desc = `${h.cells.length} days from ${h.cells[0]?.date} to ${h.cells.at(-1)?.date}. Total ${formatValue(h.total)}${busiest ? `, highest ${formatValue(busiest.value)} on ${busiest.date}` : ''}.`
535
+ const out = [open(id, h.width, H, label, 'heatmap', desc)]
536
+ for (const m of h.months) out.push(`<text x="${m.x}" y="10" ${MUTED}>${escapeXml(m.label)}</text>`)
537
+ for (const d of h.days) out.push(`<text x="0" y="${fmt(d.y)}" dominant-baseline="middle" ${MUTED}>${escapeXml(d.label)}</text>`)
538
+ for (const c of h.cells) {
539
+ out.push(
540
+ `<rect x="${c.x}" y="${c.y}" width="${h.cell}" height="${h.cell}" rx="2" ${levelFill(c.level, h.levels, color)}><title>${escapeXml(`${c.date}: ${formatValue(c.value)}`)}</title></rect>`,
541
+ )
542
+ }
543
+ if (legend) {
544
+ const y = h.height + 10
545
+ let x = h.width - h.levels * (h.cell + 3) - 34
546
+ out.push(`<text x="${x - 6}" y="${y + h.cell - 2}" text-anchor="end" ${MUTED}>Less</text>`)
547
+ for (let l = 0; l < h.levels; l++) {
548
+ out.push(`<rect x="${x}" y="${y}" width="${h.cell}" height="${h.cell}" rx="2" ${levelFill(l, h.levels, color)}/>`)
549
+ x += h.cell + 3
550
+ }
551
+ out.push(`<text x="${x + 3}" y="${y + h.cell - 2}" ${MUTED}>More</text>`)
552
+ }
553
+ out.push('</svg>')
554
+ return out.join('')
555
+ }
556
+
557
+ // ---------------------------------------------------------------------------
558
+ // One entry point for every chart type (used by the React / Vue / Svelte
559
+ // wrappers, and handy anywhere a string of SVG is wanted).
560
+ // ---------------------------------------------------------------------------
561
+
562
+ export const CHART_TYPES = {
563
+ sparkline: sparklineSvg,
564
+ line: lineChartSvg,
565
+ area: areaChartSvg,
566
+ bar: barChartSvg,
567
+ pie: pieChartSvg,
568
+ donut: donutChartSvg,
569
+ scatter: scatterChartSvg,
570
+ gauge: gaugeSvg,
571
+ heatmap: calendarHeatmapSvg,
572
+ }
573
+
574
+ /**
575
+ * renderChart('line', series, options) -> SVG string.
576
+ * data is: series for line / area / bar / scatter, slices for pie /
577
+ * donut, numbers for sparkline, a number for gauge, days for heatmap.
578
+ */
579
+ export function renderChart(type, data, options = {}) {
580
+ const render = CHART_TYPES[type]
581
+ if (!render) throw new Error(`Unknown chart type "${type}". Use ${Object.keys(CHART_TYPES).join(', ')}.`)
582
+ return render(data, options)
583
+ }
584
+
585
+ /**
586
+ * The geometry a line / area SVG was drawn from (same legend spacing),
587
+ * for attachCrosshair() on the rendered <svg>. null for other types.
588
+ */
589
+ export function chartGeometry(type, data, options = {}) {
590
+ if (type !== 'line' && type !== 'area') return null
591
+ const plan = planLegend(options, seriesMeta(data))
592
+ return type === 'line' ? lineChart(data, plan.options) : areaChart(data, plan.options)
593
+ }