@tylix/charts 1.2.0 → 1.3.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/a11y.js ADDED
@@ -0,0 +1,50 @@
1
+ import { isDate } from './time.js'
2
+ // Screen-reader text for charts.
3
+
4
+ const esc = (s) =>
5
+ String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
6
+
7
+ /**
8
+ * One-sentence summary of xy series: what is plotted and the range of
9
+ * each series, e.g. "2 series over 12 points. Revenue: 10 to 80, last 64."
10
+ */
11
+ export function describeSeries(series = [], { formatY = (v) => String(v) } = {}) {
12
+ if (!series.length) return 'No data.'
13
+ const parts = series.map((s) => {
14
+ const ys = (s.points ?? s.bars ?? s.data ?? [])
15
+ .map((p) => (typeof p === 'number' ? p : p?.value ?? p?.y))
16
+ .filter((v) => typeof v === 'number' && Number.isFinite(v))
17
+ if (!ys.length) return `${s.name}: no values`
18
+ return `${s.name}: ${formatY(Math.min(...ys))} to ${formatY(Math.max(...ys))}, last ${formatY(ys.at(-1))}`
19
+ })
20
+ const n = Math.max(...series.map((s) => (s.points ?? s.bars ?? s.data ?? []).length))
21
+ return `${series.length} series over ${n} points. ${parts.join('. ')}.`
22
+ }
23
+
24
+ /**
25
+ * An HTML <table> of xy series (one row per x, one column per series),
26
+ * for a visually hidden alternative to the chart.
27
+ * dataTable([{ name: 'CPU', data: [...] }], { caption: 'CPU load', formatX, formatY })
28
+ */
29
+ export function dataTable(series = [], { caption, formatX = (v) => String(v), formatY = (v) => String(v), className = 'tylix-chart-table' } = {}) {
30
+ const rows = new Map()
31
+ series.forEach((s, i) => {
32
+ ;(s.data ?? []).forEach((d, k) => {
33
+ const x = typeof d === 'number' || d == null ? k : isDate(d.x) ? d.x.getTime() : d.x ?? k
34
+ const y = typeof d === 'number' ? d : d?.y ?? null
35
+ if (!rows.has(x)) rows.set(x, [])
36
+ rows.get(x)[i] = y
37
+ })
38
+ })
39
+ const time = series.some((s) => (s.data ?? []).some((d) => isDate(d?.x)))
40
+ const head = `<tr><th scope="col">${time ? 'Date' : 'x'}</th>${series.map((s, i) => `<th scope="col">${esc(s.name ?? `Series ${i + 1}`)}</th>`).join('')}</tr>`
41
+ const body = [...rows.entries()]
42
+ .sort((a, b) => (typeof a[0] === 'number' && typeof b[0] === 'number' ? a[0] - b[0] : 0))
43
+ .map(([x, ys]) => `<tr><th scope="row">${esc(formatX(time ? new Date(x) : x))}</th>${series.map((_, i) => `<td>${ys[i] == null ? '' : esc(formatY(ys[i]))}</td>`).join('')}</tr>`)
44
+ .join('')
45
+ return `<table class="${esc(className)}">${caption ? `<caption>${esc(caption)}</caption>` : ''}<thead>${head}</thead><tbody>${body}</tbody></table>`
46
+ }
47
+
48
+ /** CSS that hides an element visually but keeps it for screen readers. */
49
+ export const SR_ONLY_STYLE =
50
+ 'position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0'
package/src/area.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { linearScale } from './scales.js'
2
2
  import { linePath, bandPath } from './path.js'
3
3
  import { extent } from './ticks.js'
4
- import { DEFAULT_PALETTE, normalizeData } from './line.js'
4
+ import { DEFAULT_PALETTE, normalizeData, xAxis, anchorTicks } from './line.js'
5
5
 
6
6
  /**
7
7
  * Computes area chart geometry. Same shape as lineChart() plus `py0` (the
@@ -23,7 +23,9 @@ export function areaChart(
23
23
  curve = 'linear',
24
24
  stacked = false,
25
25
  zeroBaseline = true,
26
- formatX = (v) => String(v),
26
+ formatX,
27
+ timeZone,
28
+ locale,
27
29
  formatY = (v) => String(v),
28
30
  } = {}
29
31
  ) {
@@ -78,6 +80,7 @@ export function areaChart(
78
80
  }
79
81
 
80
82
  const x = linearScale({ domain: xd, range: [plot.x, plot.x + plot.width] })
83
+ const xa = xAxis(series, x, xd, xTicks, { formatX, timeZone, locale })
81
84
  const y = linearScale({ domain: yd, range: [plot.y + plot.height, plot.y] })
82
85
  const baselineY = yd[0] <= 0 && yd[1] >= 0 ? y(0) : y(yd[0])
83
86
 
@@ -88,11 +91,9 @@ export function areaChart(
88
91
  stacked,
89
92
  xScale: x,
90
93
  yScale: y,
91
- xTicks: x.ticks(xTicks).filter((v) => v >= xd[0] && v <= xd[1]).map((v) => ({
92
- value: v,
93
- x: x(v),
94
- label: formatX(v),
95
- })),
94
+ xTicks: anchorTicks(xa.ticks, width),
95
+ time: xa.time,
96
+ formatX: xa.format,
96
97
  yTicks: y.ticks(yTicks).filter((v) => v >= yd[0] && v <= yd[1]).map((v) => ({
97
98
  value: v,
98
99
  y: y(v),
package/src/crosshair.js CHANGED
@@ -47,7 +47,7 @@ export function nearestPoints(chart, px) {
47
47
  */
48
48
  export function attachCrosshair(svg, chart, options = {}) {
49
49
  const {
50
- formatX = (v) => String(v),
50
+ formatX = chart.formatX ?? ((v) => String(v)),
51
51
  formatY = (v) => String(v),
52
52
  tooltip = true,
53
53
  onChange,
@@ -0,0 +1,23 @@
1
+ import type { CSSProperties, FC } from 'react'
2
+ import type { ChartType } from '../index.js'
3
+
4
+ /** Chart options are passed as props (width, height, formatY, legend…), or together in `options`. */
5
+ interface Common {
6
+ options?: Record<string, unknown>
7
+ /** Line / area: the interactive hover tooltip. Default true. */
8
+ crosshair?: boolean
9
+ id?: string
10
+ className?: string
11
+ style?: CSSProperties
12
+ [option: string]: unknown
13
+ }
14
+ export const Chart: FC<Common & { type: ChartType; series?: unknown[]; data?: unknown; value?: number }>
15
+ export const Sparkline: FC<Common & { data: Array<number | null> }>
16
+ export const LineChart: FC<Common & { series: unknown[] }>
17
+ export const AreaChart: FC<Common & { series: unknown[] }>
18
+ export const BarChart: FC<Common & { series: unknown[]; categories?: unknown[] }>
19
+ export const PieChart: FC<Common & { data: unknown[] }>
20
+ export const DonutChart: FC<Common & { data: unknown[] }>
21
+ export const ScatterChart: FC<Common & { series: unknown[] }>
22
+ export const Gauge: FC<Common & { value: number }>
23
+ export const Heatmap: FC<Common & { data: unknown }>
@@ -0,0 +1,38 @@
1
+ // React wrappers. Plain createElement, so no JSX build step is needed.
2
+ //
3
+ // import { LineChart, BarChart, Gauge } from '@tylix/charts/react'
4
+ // <LineChart series={series} height={260} formatY={(v) => `${v}%`} />
5
+ // <Chart type="heatmap" data={days} />
6
+ import { createElement, useEffect, useId, useMemo, useRef } from 'react'
7
+ import { chartProps, cleanId, enhance, svgFor } from './shared.js'
8
+
9
+ export function Chart(props) {
10
+ const ref = useRef(null)
11
+ const reactId = useId() // stable between server render and hydration
12
+ const id = props.id ?? cleanId(reactId)
13
+ const spec = chartProps(props)
14
+ const svg = svgFor(spec, id)
15
+ useEffect(() => enhance(ref.current, spec, id), [svg])
16
+ return createElement('div', {
17
+ ref,
18
+ className: ['tylix-chart-host', props.className ?? props.class].filter(Boolean).join(' '),
19
+ style: props.style,
20
+ dangerouslySetInnerHTML: { __html: svg },
21
+ })
22
+ }
23
+
24
+ const named = (type) => {
25
+ const C = (props) => createElement(Chart, { ...props, type })
26
+ C.displayName = `${type[0].toUpperCase()}${type.slice(1)}Chart`
27
+ return C
28
+ }
29
+
30
+ export const Sparkline = named('sparkline')
31
+ export const LineChart = named('line')
32
+ export const AreaChart = named('area')
33
+ export const BarChart = named('bar')
34
+ export const PieChart = named('pie')
35
+ export const DonutChart = named('donut')
36
+ export const ScatterChart = named('scatter')
37
+ export const Gauge = named('gauge')
38
+ export const Heatmap = named('heatmap')
@@ -0,0 +1,37 @@
1
+ // What every framework wrapper does: props -> SVG string, and after
2
+ // mount, the interactive crosshair for line / area charts.
3
+ import { renderChart, chartGeometry } from '../svg.js'
4
+ import { attachCrosshair } from '../crosshair.js'
5
+
6
+ // The prop holding the data, per chart type.
7
+ export const DATA_PROP = {
8
+ sparkline: 'data', line: 'series', area: 'series', bar: 'series', scatter: 'series',
9
+ pie: 'data', donut: 'data', gauge: 'value', heatmap: 'data',
10
+ }
11
+
12
+ const WRAPPER_PROPS = new Set(['type', 'series', 'data', 'value', 'options', 'crosshair', 'class', 'className', 'style', 'children'])
13
+
14
+ // { type, series | data | value, options?, ...chart options } -> pieces
15
+ export function chartProps(props, type = props.type) {
16
+ const options = { ...(props.options ?? {}) }
17
+ for (const [k, v] of Object.entries(props)) if (!WRAPPER_PROPS.has(k) && v !== undefined) options[k] = v
18
+ const data = props[DATA_PROP[type]] ?? props.data ?? props.series ?? props.value
19
+ const interactive = props.crosshair !== false && (type === 'line' || type === 'area') && options.interactive !== false
20
+ return { type, data, options, interactive }
21
+ }
22
+
23
+ export function svgFor({ type, data, options, interactive }, id) {
24
+ // With the crosshair, the static per-point tooltips are not needed.
25
+ return renderChart(type, data, { id, ...options, ...(interactive ? { interactive: false } : {}) })
26
+ }
27
+
28
+ // Returns a cleanup function.
29
+ export function enhance(host, { type, data, options, interactive }, id) {
30
+ if (!interactive || !host || typeof document === 'undefined') return () => {}
31
+ const svg = host.querySelector('svg')
32
+ if (!svg) return () => {}
33
+ const handle = attachCrosshair(svg, chartGeometry(type, data, { id, ...options }), options)
34
+ return () => handle.destroy()
35
+ }
36
+
37
+ export const cleanId = (id) => `tc${String(id).replace(/[^A-Za-z0-9_-]/g, '')}`
@@ -0,0 +1,24 @@
1
+ <!--
2
+ Svelte 5 wrapper.
3
+ import { Chart } from '@tylix/charts/svelte'
4
+ <Chart type="line" series={series} height={260} />
5
+ -->
6
+ <script>
7
+ import { chartProps, cleanId, enhance, svgFor } from '../shared.js'
8
+
9
+ let { class: className = '', style = '', ...rest } = $props()
10
+ // stable between server render and hydration
11
+ const uid = $props.id()
12
+ const id = rest.id ?? cleanId(uid)
13
+ let host = $state(null)
14
+
15
+ const spec = $derived(chartProps(rest))
16
+ const svg = $derived(svgFor(spec, id))
17
+
18
+ $effect(() => {
19
+ svg
20
+ return enhance(host, spec, id)
21
+ })
22
+ </script>
23
+
24
+ <div bind:this={host} class="tylix-chart-host {className}" {style}>{@html svg}</div>
@@ -0,0 +1,15 @@
1
+ import type { Component } from 'svelte'
2
+ import type { ChartType } from '../../index.js'
3
+
4
+ export const Chart: Component<{
5
+ type: ChartType
6
+ series?: unknown[]
7
+ data?: unknown
8
+ value?: number
9
+ options?: Record<string, unknown>
10
+ crosshair?: boolean
11
+ id?: string
12
+ class?: string
13
+ style?: string
14
+ [option: string]: unknown
15
+ }>
@@ -0,0 +1 @@
1
+ export { default as Chart } from './Chart.svelte'
@@ -0,0 +1,21 @@
1
+ import type { DefineComponent } from 'vue'
2
+
3
+ type ChartComponent = DefineComponent<{
4
+ type?: string
5
+ series?: unknown[]
6
+ data?: unknown
7
+ value?: number
8
+ options?: Record<string, unknown>
9
+ crosshair?: boolean
10
+ id?: string
11
+ }>
12
+ export const Chart: ChartComponent
13
+ export const Sparkline: ChartComponent
14
+ export const LineChart: ChartComponent
15
+ export const AreaChart: ChartComponent
16
+ export const BarChart: ChartComponent
17
+ export const PieChart: ChartComponent
18
+ export const DonutChart: ChartComponent
19
+ export const ScatterChart: ChartComponent
20
+ export const Gauge: ChartComponent
21
+ export const Heatmap: ChartComponent
@@ -0,0 +1,64 @@
1
+ // Vue 3 wrappers.
2
+ //
3
+ // import { LineChart, Gauge } from '@tylix/charts/vue'
4
+ // <LineChart :series="series" :height="260" />
5
+ // <Chart type="heatmap" :data="days" />
6
+ import * as vue from 'vue'
7
+ import { chartProps, cleanId, enhance, svgFor } from './shared.js'
8
+
9
+ const { defineComponent, h, onBeforeUnmount, onMounted, ref, watch } = vue
10
+ let counter = 0
11
+
12
+ function makeChart(fixedType) {
13
+ return defineComponent({
14
+ name: fixedType ? `${fixedType[0].toUpperCase()}${fixedType.slice(1)}Chart` : 'TylixChart',
15
+ inheritAttrs: false,
16
+ props: {
17
+ type: String,
18
+ series: Array,
19
+ data: [Array, Object],
20
+ value: Number,
21
+ options: Object,
22
+ crosshair: { type: Boolean, default: true },
23
+ id: String,
24
+ },
25
+ setup(props, { attrs }) {
26
+ const host = ref(null)
27
+ // useId (Vue 3.5+) keeps server and client ids equal.
28
+ const id = props.id ?? cleanId(typeof vue.useId === 'function' ? vue.useId() : `v${++counter}`)
29
+ const spec = () => {
30
+ const { class: cls, style, ...rest } = attrs
31
+ return chartProps({ ...rest, ...props, type: fixedType ?? props.type })
32
+ }
33
+ let cleanup = () => {}
34
+ const svg = () => svgFor(spec(), id)
35
+ onMounted(() => {
36
+ cleanup = enhance(host.value, spec(), id)
37
+ watch(svg, () => {
38
+ cleanup()
39
+ // after the DOM update
40
+ queueMicrotask(() => (cleanup = enhance(host.value, spec(), id)))
41
+ })
42
+ })
43
+ onBeforeUnmount(() => cleanup())
44
+ return () =>
45
+ h('div', {
46
+ ref: host,
47
+ class: ['tylix-chart-host', attrs.class],
48
+ style: attrs.style,
49
+ innerHTML: svg(),
50
+ })
51
+ },
52
+ })
53
+ }
54
+
55
+ export const Chart = makeChart(null)
56
+ export const Sparkline = makeChart('sparkline')
57
+ export const LineChart = makeChart('line')
58
+ export const AreaChart = makeChart('area')
59
+ export const BarChart = makeChart('bar')
60
+ export const PieChart = makeChart('pie')
61
+ export const DonutChart = makeChart('donut')
62
+ export const ScatterChart = makeChart('scatter')
63
+ export const Gauge = makeChart('gauge')
64
+ export const Heatmap = makeChart('heatmap')
package/src/gauge.js ADDED
@@ -0,0 +1,81 @@
1
+ import { arcPath } from './pie.js'
2
+
3
+ const RAD = Math.PI / 180
4
+
5
+ /**
6
+ * Radial gauge geometry (a meter from min to max).
7
+ *
8
+ * gauge(72, { min: 0, max: 100, thresholds: [
9
+ * { value: 0, color: '#16a34a' }, { value: 70, color: '#f59e0b' }, { value: 90, color: '#dc2626' },
10
+ * ] })
11
+ *
12
+ * Angles are in degrees from 12 o'clock, clockwise (default -120..120).
13
+ * thresholds colour the value arc by the band the value falls in and
14
+ * are drawn as a thin band under the track when `bands` is true.
15
+ *
16
+ * Returns { size, cx, cy, track, value, color, angle, needle: { x, y },
17
+ * percent, label, min, max, bands: [{ path, color }] }
18
+ */
19
+ export function gauge(
20
+ value,
21
+ {
22
+ min = 0,
23
+ max = 100,
24
+ size = 200,
25
+ thickness = 0.16,
26
+ startAngle = -120,
27
+ endAngle = 120,
28
+ cornerRadius = 4,
29
+ thresholds = [],
30
+ bands = false,
31
+ color = 'var(--tylix-chart-1, #2563eb)',
32
+ format = (v) => String(Math.round(v * 10) / 10),
33
+ } = {},
34
+ ) {
35
+ const r = size / 2
36
+ const cx = r
37
+ const cy = r
38
+ // leave room outside the track for the threshold bands
39
+ const outer = r - (bands ? 9 : 2)
40
+ const inner = outer - Math.max(4, outer * thickness * 2)
41
+ const v = Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : min
42
+ const t = max === min ? 0 : (v - min) / (max - min)
43
+ const a0 = startAngle * RAD
44
+ const a1 = endAngle * RAD
45
+ const at = a0 + t * (a1 - a0)
46
+
47
+ const sorted = [...thresholds].sort((a, b) => a.value - b.value)
48
+ const band = sorted.filter((b) => v >= b.value).at(-1)
49
+ const fill = band?.color ?? color
50
+
51
+ const arc = (from, to, ir = inner, or = outer, cr = cornerRadius) =>
52
+ arcPath({ cx, cy, innerRadius: ir, outerRadius: or, startAngle: from, endAngle: to, cornerRadius: cr })
53
+
54
+ const angleOf = (x) => a0 + ((Math.min(max, Math.max(min, x)) - min) / (max - min || 1)) * (a1 - a0)
55
+ const bandArcs = bands
56
+ ? sorted.map((b, i) => ({
57
+ color: b.color,
58
+ path: arc(angleOf(b.value), angleOf(sorted[i + 1]?.value ?? max), outer + 3, outer + 6, 0),
59
+ }))
60
+ : []
61
+
62
+ const needleR = inner - 6
63
+ return {
64
+ size,
65
+ cx,
66
+ cy,
67
+ min,
68
+ max,
69
+ value: v,
70
+ percent: t,
71
+ angle: Math.round((at / RAD) * 1e6) / 1e6,
72
+ color: fill,
73
+ label: format(v),
74
+ track: arc(a0, a1),
75
+ valuePath: t > 0 ? arc(a0, at) : '',
76
+ needle: { x: cx + needleR * Math.sin(at), y: cy - needleR * Math.cos(at) },
77
+ bands: bandArcs,
78
+ // the lowest point the arc reaches, to size the SVG
79
+ bottom: Math.max(cy + outer * Math.max(-Math.cos(a0), -Math.cos(a1), 0), cy + 8),
80
+ }
81
+ }
package/src/heatmap.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Calendar heatmap geometry: one cell per day, columns are weeks.
3
+ *
4
+ * calendarHeatmap([{ date: '2024-05-01', value: 3 }, ...])
5
+ * calendarHeatmap({ '2024-05-01': 3, ... })
6
+ *
7
+ * options: from / to (default: the 53 weeks ending at the last date),
8
+ * weekStart 0 (Sunday) | 1 (Monday), cell 11, gap 3, levels 5,
9
+ * max (default: the largest value), locale.
10
+ * Days are calendar dates (YYYY-MM-DD, UTC); times are ignored.
11
+ *
12
+ * Returns { width, height, cells: [{ date, value, level, x, y }],
13
+ * months: [{ label, x }], days: [{ label, y }], levels, max, total }
14
+ */
15
+ const DAY = 86400000
16
+
17
+ const dayKey = (d) => new Date(d).toISOString().slice(0, 10)
18
+ const dayMs = (d) => Date.parse(`${typeof d === 'string' ? d.slice(0, 10) : dayKey(d)}T00:00:00Z`)
19
+
20
+ export function calendarHeatmap(
21
+ data = [],
22
+ { from, to, weekStart = 0, cell = 11, gap = 3, levels = 5, max, locale = 'en-US', labels = true } = {},
23
+ ) {
24
+ const values = new Map()
25
+ const entries = Array.isArray(data)
26
+ ? data.map((d) => [d.date, d.value])
27
+ : Object.entries(data)
28
+ for (const [date, value] of entries) {
29
+ const t = dayMs(date)
30
+ if (Number.isFinite(t)) values.set(t, (values.get(t) ?? 0) + (Number(value) || 0))
31
+ }
32
+
33
+ const known = [...values.keys()]
34
+ const end = to != null ? dayMs(to) : known.length ? Math.max(...known) : dayMs(new Date())
35
+ let start = from != null ? dayMs(from) : end - 52 * 7 * DAY
36
+ // back up to the first day of that week
37
+ start -= ((new Date(start).getUTCDay() - weekStart + 7) % 7) * DAY
38
+
39
+ const top = max ?? Math.max(0, ...values.values())
40
+ const levelOf = (v) => (v <= 0 || top <= 0 ? 0 : Math.min(levels - 1, Math.ceil((v / top) * (levels - 1))))
41
+
42
+ const left = labels ? 28 : 0
43
+ const head = labels ? 16 : 0
44
+ const step = cell + gap
45
+ const cells = []
46
+ const months = []
47
+ let lastMonth = -1
48
+ let total = 0
49
+ for (let t = start, i = 0; t <= end; t += DAY, i++) {
50
+ const col = Math.floor(i / 7)
51
+ const row = i % 7
52
+ const value = values.get(t) ?? 0
53
+ total += value
54
+ cells.push({ date: dayKey(t), value, level: levelOf(value), x: left + col * step, y: head + row * step })
55
+ const month = new Date(t).getUTCMonth()
56
+ if (row === 0 && month !== lastMonth) {
57
+ // label a month at the first week that starts in it
58
+ if (new Date(t).getUTCDate() <= 7 || months.length === 0) {
59
+ months.push({ label: new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' }).format(t), x: left + col * step })
60
+ }
61
+ lastMonth = month
62
+ }
63
+ }
64
+ const weeks = Math.ceil(cells.length / 7)
65
+ const dayFormat = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' })
66
+ const days = labels
67
+ ? [1, 3, 5].map((row) => ({ label: dayFormat.format(Date.UTC(2024, 0, 7 + ((row + weekStart) % 7))), y: head + row * step + cell / 2 }))
68
+ : []
69
+
70
+ return {
71
+ width: left + weeks * step - gap,
72
+ height: head + 7 * step - gap,
73
+ cell,
74
+ cells,
75
+ // a label too close to the next one is dropped (the earlier one:
76
+ // that is a stray partial month at the start)
77
+ months: months.filter((m, i) => i === months.length - 1 || months[i + 1].x - m.x >= step * 2.5),
78
+ days,
79
+ levels,
80
+ max: top,
81
+ total,
82
+ }
83
+ }