@tylix/charts 0.6.0 → 0.7.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.
@@ -0,0 +1,57 @@
1
+ component Sparkline
2
+
3
+ props
4
+ data: Array
5
+ width?: number
6
+ height?: number
7
+ curve?: string
8
+ label?: string
9
+ class?: string
10
+
11
+ state
12
+ ready: false
13
+
14
+ computed
15
+ s() {
16
+ if not this.ready {
17
+ return null
18
+ }
19
+ return window.__tylixCharts.sparkline(this.data ?? [], {
20
+ width: this.width ?? 120,
21
+ height: this.height ?? 32,
22
+ curve: this.curve ?? "smooth",
23
+ })
24
+ }
25
+
26
+ rootClass() {
27
+ return `shrink-0 ${this.class ?? "text-emerald-500"}`
28
+ }
29
+
30
+ box() {
31
+ return `width:${this.width ?? 120}px;height:${this.height ?? 32}px`
32
+ }
33
+
34
+ onMount
35
+ async {
36
+ const load = window.__tylixChartsLoad ?? (window.__tylixChartsLoad = import("/_tylix/charts/index.js").then(m => { window.__tylixCharts = m }))
37
+ try {
38
+ await load
39
+ this.ready = true
40
+ } catch (e) {
41
+ console.error("[tylix/charts] could not load geometry", e)
42
+ window.__tylixChartsLoad = null
43
+ }
44
+ }
45
+
46
+ template
47
+ {{#if s}}
48
+ <svg class="{{ rootClass }}" width="{{ s.width }}" height="{{ s.height }}" viewBox="{{ `0 0 ${s.width} ${s.height}` }}" role="img" aria-label="{{ label or 'Sparkline' }}">
49
+ <path d="{{ s.areaPath }}" fill="currentColor" fill-opacity="0.12" stroke="none" />
50
+ <path d="{{ s.path }}" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
51
+ {{#if s.last}}
52
+ <circle cx="{{ s.last.x }}" cy="{{ s.last.y }}" r="2" fill="currentColor" />
53
+ {{/if}}
54
+ </svg>
55
+ {{#else}}
56
+ <span class="inline-block shrink-0" style="{{ box }}"></span>
57
+ {{/if}}
package/package.json CHANGED
@@ -1,8 +1,28 @@
1
1
  {
2
2
  "name": "@tylix/charts",
3
- "version": "0.6.0",
4
- "description": "Hand-rolled SVG charts for Tylix: sparkline and line chart",
3
+ "version": "0.7.0",
4
+ "description": "Hand-rolled SVG charts for Tylix: sparkline, line, area, bar, pie and donut",
5
+ "license": "MIT",
6
+ "author": "Mbiyrukzz",
5
7
  "type": "module",
8
+ "keywords": [
9
+ "tylix",
10
+ "charts",
11
+ "svg",
12
+ "components"
13
+ ],
14
+ "homepage": "https://github.com/Mbiyrukzz/tylix/tree/main/packages/charts#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/Mbiyrukzz/tylix.git",
18
+ "directory": "packages/charts"
19
+ },
20
+ "bugs": {
21
+ "url": "https://github.com/Mbiyrukzz/tylix/issues"
22
+ },
23
+ "engines": {
24
+ "node": ">=22.13"
25
+ },
6
26
  "main": "./src/index.js",
7
27
  "types": "./src/index.d.ts",
8
28
  "exports": {
@@ -12,13 +32,18 @@
12
32
  }
13
33
  },
14
34
  "files": [
15
- "src"
35
+ "src",
36
+ "components",
37
+ "tylix-components.json",
38
+ "!**/*.test.js",
39
+ "!**/*.test.mjs",
40
+ "README.md",
41
+ "LICENSE"
16
42
  ],
17
- "scripts": {
18
- "test": "node --test"
19
- },
20
- "license": "MIT",
21
43
  "publishConfig": {
22
44
  "access": "public"
45
+ },
46
+ "scripts": {
47
+ "test": "node --test"
23
48
  }
24
49
  }
package/src/area.js ADDED
@@ -0,0 +1,119 @@
1
+ import { linearScale } from './scales.js'
2
+ import { linePath, bandPath } from './path.js'
3
+ import { extent } from './ticks.js'
4
+ import { DEFAULT_PALETTE, normalizeData } from './line.js'
5
+
6
+ /**
7
+ * Computes area chart geometry. Same shape as lineChart() plus `py0` (the
8
+ * lower edge of each point) so stacked bands can be drawn.
9
+ *
10
+ * stacked: series are summed per x position (index-aligned, null counts as 0,
11
+ * values are expected to be >= 0).
12
+ */
13
+ export function areaChart(
14
+ series = [],
15
+ {
16
+ width = 480,
17
+ height = 240,
18
+ margin = {},
19
+ xDomain,
20
+ yDomain,
21
+ xTicks = 6,
22
+ yTicks = 5,
23
+ curve = 'linear',
24
+ stacked = false,
25
+ zeroBaseline = true,
26
+ formatX = (v) => String(v),
27
+ formatY = (v) => String(v),
28
+ } = {}
29
+ ) {
30
+ const m = { top: 12, right: 12, bottom: 28, left: 40, ...margin }
31
+ const plot = {
32
+ x: m.left,
33
+ y: m.top,
34
+ width: Math.max(0, width - m.left - m.right),
35
+ height: Math.max(0, height - m.top - m.bottom),
36
+ }
37
+
38
+ const normalized = series.map((s, i) => ({
39
+ name: s.name ?? `Series ${i + 1}`,
40
+ color: s.color ?? DEFAULT_PALETTE[i % DEFAULT_PALETTE.length],
41
+ data: normalizeData(s.data),
42
+ }))
43
+
44
+ const finite = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
45
+
46
+ let layers
47
+ if (stacked) {
48
+ const longest = normalized.reduce((a, s) => (s.data.length > a.length ? s.data : a), [])
49
+ const totals = longest.map(() => 0)
50
+ layers = normalized.map((s) =>
51
+ longest.map((ref, i) => {
52
+ const raw = finite(s.data[i]?.y)
53
+ const lo = totals[i]
54
+ totals[i] += raw ?? 0
55
+ return { x: ref.x, value: raw, lo, hi: totals[i] }
56
+ })
57
+ )
58
+ } else {
59
+ layers = normalized.map((s) =>
60
+ s.data.map((p) => ({ x: p.x, value: finite(p.y), lo: null, hi: finite(p.y) }))
61
+ )
62
+ }
63
+
64
+ const flat = layers.flat()
65
+ const xExt = extent(flat.map((p) => p.x)) ?? [0, 1]
66
+ const yVals = flat.flatMap((p) => (p.hi === null ? [] : stacked ? [p.hi, p.lo] : [p.hi]))
67
+ let yExt = extent(yVals) ?? [0, 1]
68
+ if (zeroBaseline || stacked) yExt = [Math.min(0, yExt[0]), Math.max(0, yExt[1])]
69
+
70
+ const xd = xDomain ?? xExt
71
+ let yd = yDomain ?? yExt
72
+ if (!yDomain) {
73
+ if (yd[0] === yd[1]) yd = yd[0] === 0 ? [0, 1] : [yd[0] - 1, yd[1] + 1]
74
+ else {
75
+ const t = linearScale({ domain: yd }).ticks(yTicks)
76
+ if (t.length > 1) yd = [t[0], t[t.length - 1]]
77
+ }
78
+ }
79
+
80
+ const x = linearScale({ domain: xd, range: [plot.x, plot.x + plot.width] })
81
+ const y = linearScale({ domain: yd, range: [plot.y + plot.height, plot.y] })
82
+ const baselineY = yd[0] <= 0 && yd[1] >= 0 ? y(0) : y(yd[0])
83
+
84
+ return {
85
+ width,
86
+ height,
87
+ plot,
88
+ stacked,
89
+ xScale: x,
90
+ 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
+ })),
96
+ yTicks: y.ticks(yTicks).filter((v) => v >= yd[0] && v <= yd[1]).map((v) => ({
97
+ value: v,
98
+ y: y(v),
99
+ label: formatY(v),
100
+ })),
101
+ series: normalized.map((s, si) => {
102
+ const points = layers[si].map((p) => ({
103
+ value: p.value,
104
+ x: p.x,
105
+ px: x(p.x),
106
+ py: p.hi === null ? null : y(p.hi),
107
+ py0: stacked ? y(p.lo) : baselineY,
108
+ }))
109
+ const top = points.map((p) => ({ x: p.px, y: p.py, y0: p.py0 }))
110
+ return {
111
+ name: s.name,
112
+ color: s.color,
113
+ points,
114
+ path: linePath(top, { curve }),
115
+ areaPath: bandPath(top, { curve }),
116
+ }
117
+ }),
118
+ }
119
+ }
package/src/band.js ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Band scale: maps discrete values to evenly spaced bands (for bar charts).
3
+ *
4
+ * const x = bandScale({ domain: ['a', 'b', 'c'], range: [0, 300] })
5
+ * x('b') // start of the band
6
+ * x.bandwidth() // width of one band
7
+ * x.center('b') // middle of the band
8
+ */
9
+ export function bandScale({
10
+ domain = [],
11
+ range = [0, 1],
12
+ padding = 0.2,
13
+ paddingInner = padding,
14
+ paddingOuter = padding / 2,
15
+ } = {}) {
16
+ const [r0, r1] = range
17
+ const n = domain.length
18
+ const span = r1 - r0
19
+ const step = n === 0 ? 0 : span / Math.max(1, n - paddingInner + paddingOuter * 2)
20
+ const bandwidth = step * (1 - paddingInner)
21
+ const start = r0 + (span - step * (n - paddingInner)) / 2
22
+ const index = new Map(domain.map((v, i) => [v, i]))
23
+
24
+ const scale = (value) => {
25
+ const i = index.get(value)
26
+ return i === undefined ? undefined : start + step * i
27
+ }
28
+ scale.bandwidth = () => bandwidth
29
+ scale.step = () => step
30
+ scale.center = (value) => {
31
+ const s = scale(value)
32
+ return s === undefined ? undefined : s + bandwidth / 2
33
+ }
34
+ scale.domain = () => domain.slice()
35
+ scale.range = () => [r0, r1]
36
+ return scale
37
+ }
package/src/bar.js ADDED
@@ -0,0 +1,218 @@
1
+ import { linearScale } from './scales.js'
2
+ import { bandScale } from './band.js'
3
+ import { extent } from './ticks.js'
4
+ import { DEFAULT_PALETTE } from './line.js'
5
+
6
+ const fmt = (n) => Math.round(n * 100) / 100
7
+ const f = fmt
8
+
9
+ /**
10
+ * Rect path with only the outer end rounded.
11
+ * side: 'top' | 'bottom' | 'left' | 'right' | 'none'
12
+ */
13
+ export function roundedBarPath(x, y, w, h, r = 0, side = 'none') {
14
+ if (!(w > 0) || !(h > 0)) return ''
15
+ const vertical = side === 'top' || side === 'bottom'
16
+ r =
17
+ side === 'none'
18
+ ? 0
19
+ : Math.max(0, Math.min(r, vertical ? w / 2 : h / 2, vertical ? h : w))
20
+ const x2 = x + w
21
+ const y2 = y + h
22
+ if (r < 0.01) return `M${f(x)},${f(y)}H${f(x2)}V${f(y2)}H${f(x)}Z`
23
+ const a = `A${f(r)},${f(r)} 0 0 `
24
+ switch (side) {
25
+ case 'top':
26
+ return `M${f(x)},${f(y2)}V${f(y + r)}${a}1 ${f(x + r)},${f(y)}H${f(x2 - r)}${a}1 ${f(x2)},${f(y + r)}V${f(y2)}Z`
27
+ case 'bottom':
28
+ return `M${f(x)},${f(y)}V${f(y2 - r)}${a}0 ${f(x + r)},${f(y2)}H${f(x2 - r)}${a}0 ${f(x2)},${f(y2 - r)}V${f(y)}Z`
29
+ case 'right':
30
+ return `M${f(x)},${f(y)}H${f(x2 - r)}${a}1 ${f(x2)},${f(y + r)}V${f(y2 - r)}${a}1 ${f(x2 - r)},${f(y2)}H${f(x)}Z`
31
+ default: // left
32
+ return `M${f(x2)},${f(y)}H${f(x + r)}${a}0 ${f(x)},${f(y + r)}V${f(y2 - r)}${a}0 ${f(x + r)},${f(y2)}H${f(x2)}Z`
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Computes bar chart geometry (grouped, stacked, vertical or horizontal).
38
+ *
39
+ * series: [{ name, color?, data: Array<number | null> }]
40
+ * options.categories: labels for each position along the category axis.
41
+ */
42
+ export function barChart(
43
+ series = [],
44
+ {
45
+ categories,
46
+ orientation = 'vertical',
47
+ stacked = false,
48
+ width = 480,
49
+ height = 240,
50
+ margin = {},
51
+ yDomain,
52
+ yTicks = 5,
53
+ zeroBaseline = true,
54
+ padding = 0.3,
55
+ groupPadding = 0.08,
56
+ radius = 4,
57
+ formatValue = (v) => String(v),
58
+ formatCategory = (c) => String(c),
59
+ } = {}
60
+ ) {
61
+ const horizontal = orientation === 'horizontal'
62
+ const norm = series.map((s, i) => ({
63
+ name: s.name ?? `Series ${i + 1}`,
64
+ color: s.color ?? DEFAULT_PALETTE[i % DEFAULT_PALETTE.length],
65
+ data: (s.data ?? []).map((v) => (typeof v === 'number' && Number.isFinite(v) ? v : null)),
66
+ }))
67
+ const count = categories?.length ?? Math.max(0, ...norm.map((s) => s.data.length))
68
+ const cats = categories ?? Array.from({ length: count }, (_, i) => String(i + 1))
69
+ const idx = cats.map((_, i) => i)
70
+
71
+ const labelW = horizontal
72
+ ? Math.min(140, Math.max(0, ...cats.map((c) => formatCategory(c).length)) * 6.2 + 16)
73
+ : 0
74
+ const m = {
75
+ top: 12,
76
+ right: horizontal ? 24 : 12,
77
+ bottom: 28,
78
+ left: horizontal ? Math.max(40, labelW) : 40,
79
+ ...margin,
80
+ }
81
+ const plot = {
82
+ x: m.left,
83
+ y: m.top,
84
+ width: Math.max(0, width - m.left - m.right),
85
+ height: Math.max(0, height - m.top - m.bottom),
86
+ }
87
+
88
+ // ---- value domain
89
+ const valueAt = (s, i) => s.data[i] ?? null
90
+ let vals
91
+ if (stacked) {
92
+ const pos = cats.map(() => 0)
93
+ const neg = cats.map(() => 0)
94
+ norm.forEach((s) =>
95
+ cats.forEach((_, i) => {
96
+ const v = valueAt(s, i)
97
+ if (v === null) return
98
+ if (v >= 0) pos[i] += v
99
+ else neg[i] += v
100
+ })
101
+ )
102
+ vals = [...pos, ...neg]
103
+ } else {
104
+ vals = norm.flatMap((s) => s.data.filter((v) => v !== null))
105
+ }
106
+ let ext = extent(vals) ?? [0, 1]
107
+ if (zeroBaseline || stacked) ext = [Math.min(0, ext[0]), Math.max(0, ext[1])]
108
+ let vd = yDomain ?? ext
109
+ if (!yDomain) {
110
+ if (vd[0] === vd[1]) vd = vd[0] === 0 ? [0, 1] : [vd[0] - 1, vd[1] + 1]
111
+ else {
112
+ const t = linearScale({ domain: vd }).ticks(yTicks)
113
+ if (t.length > 1) vd = [t[0], t[t.length - 1]]
114
+ }
115
+ }
116
+
117
+ const vRange = horizontal ? [plot.x, plot.x + plot.width] : [plot.y + plot.height, plot.y]
118
+ const cRange = horizontal ? [plot.y, plot.y + plot.height] : [plot.x, plot.x + plot.width]
119
+ const vScale = linearScale({ domain: vd, range: vRange })
120
+ const band = bandScale({ domain: idx, range: cRange, padding })
121
+ const grouped = !stacked && norm.length > 1
122
+ const inner = grouped
123
+ ? bandScale({
124
+ domain: norm.map((_, i) => i),
125
+ range: [0, band.bandwidth()],
126
+ paddingInner: groupPadding,
127
+ paddingOuter: 0,
128
+ })
129
+ : null
130
+ const thickness = grouped ? inner.bandwidth() : band.bandwidth()
131
+ const base = Math.min(Math.max(0, vd[0]), vd[1])
132
+
133
+ // ---- which stacked segment is outermost (gets the rounded end)
134
+ const lastPos = cats.map(() => -1)
135
+ const lastNeg = cats.map(() => -1)
136
+ norm.forEach((s, si) =>
137
+ cats.forEach((_, i) => {
138
+ const v = valueAt(s, i)
139
+ if (v === null || v === 0) return
140
+ if (v > 0) lastPos[i] = si
141
+ else lastNeg[i] = si
142
+ })
143
+ )
144
+
145
+ const posCum = cats.map(() => 0)
146
+ const negCum = cats.map(() => 0)
147
+
148
+ const out = norm.map((s, si) => ({
149
+ name: s.name,
150
+ color: s.color,
151
+ bars: cats.map((cat, i) => {
152
+ const v = valueAt(s, i)
153
+ const empty = {
154
+ index: i, category: cat, categoryLabel: formatCategory(cat), value: v,
155
+ label: v === null ? '' : formatValue(v), x: 0, y: 0, width: 0, height: 0, path: '',
156
+ }
157
+ if (v === null || v === 0) return empty
158
+
159
+ let a
160
+ let b
161
+ if (!stacked) {
162
+ a = base
163
+ b = v
164
+ } else if (v > 0) {
165
+ a = posCum[i]
166
+ b = a + v
167
+ posCum[i] = b
168
+ } else {
169
+ a = negCum[i]
170
+ b = a + v
171
+ negCum[i] = b
172
+ }
173
+ const pa = vScale(a)
174
+ const pb = vScale(b)
175
+ const lo = Math.min(pa, pb)
176
+ const size = Math.abs(pa - pb)
177
+ const offset = grouped ? inner(si) : 0
178
+ const start = band(i) + offset
179
+
180
+ const round = !stacked || (v > 0 ? lastPos[i] === si : lastNeg[i] === si)
181
+ const side = !round
182
+ ? 'none'
183
+ : horizontal
184
+ ? (v > 0 ? 'right' : 'left')
185
+ : (v > 0 ? 'top' : 'bottom')
186
+
187
+ const box = horizontal
188
+ ? { x: lo, y: start, width: size, height: thickness }
189
+ : { x: start, y: lo, width: thickness, height: size }
190
+ return {
191
+ ...empty,
192
+ ...box,
193
+ path: roundedBarPath(box.x, box.y, box.width, box.height, radius, side),
194
+ }
195
+ }),
196
+ }))
197
+
198
+ return {
199
+ width,
200
+ height,
201
+ plot,
202
+ orientation: horizontal ? 'horizontal' : 'vertical',
203
+ stacked,
204
+ baseline: vScale(base),
205
+ valueScale: vScale,
206
+ categoryScale: band,
207
+ valueTicks: vScale
208
+ .ticks(yTicks)
209
+ .filter((v) => v >= vd[0] && v <= vd[1])
210
+ .map((v) => ({ value: v, pos: vScale(v), label: formatValue(v) })),
211
+ categoryTicks: cats.map((c, i) => ({
212
+ index: i,
213
+ label: formatCategory(c),
214
+ pos: band.center(i),
215
+ })),
216
+ series: out,
217
+ }
218
+ }
@@ -0,0 +1,162 @@
1
+ const fmt = (n) => Math.round(n * 100) / 100
2
+ const esc = (s) =>
3
+ String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
4
+ const BG = 'var(--tylix-chart-bg, #fff)'
5
+
6
+ /** Sorted, de-duplicated pixel x positions that hold at least one point. */
7
+ export function snapPositions(chart) {
8
+ const xs = []
9
+ for (const s of chart.series) for (const p of s.points) if (p.py !== null) xs.push(p.px)
10
+ xs.sort((a, b) => a - b)
11
+ return xs.filter((x, i) => i === 0 || x - xs[i - 1] > 0.01)
12
+ }
13
+
14
+ /**
15
+ * Finds the data position nearest to pixel x on a lineChart() / areaChart()
16
+ * geometry. Returns null when the chart has no points.
17
+ * { index, px, x, rows: [{ name, color, value, x, px, py }] }
18
+ */
19
+ export function nearestPoints(chart, px) {
20
+ const xs = snapPositions(chart)
21
+ if (!xs.length) return null
22
+ let index = 0
23
+ for (let i = 1; i < xs.length; i++) {
24
+ if (Math.abs(xs[i] - px) < Math.abs(xs[index] - px)) index = i
25
+ }
26
+ const at = xs[index]
27
+ const rows = []
28
+ for (const s of chart.series) {
29
+ const p = s.points.find((q) => q.py !== null && Math.abs(q.px - at) < 0.01)
30
+ if (p) rows.push({ name: s.name, color: s.color, value: p.value, x: p.x, px: p.px, py: p.py })
31
+ }
32
+ return { index, px: at, x: rows[0]?.x ?? 0, rows }
33
+ }
34
+
35
+ /**
36
+ * Adds a hover / touch / keyboard crosshair to an SVG made from a
37
+ * lineChart() or areaChart() geometry (pass the same geometry you rendered).
38
+ *
39
+ * const { destroy } = attachCrosshair(svgEl, chart, { formatY: (v) => `KES ${v}` })
40
+ *
41
+ * options:
42
+ * formatX, formatY - tooltip formatting
43
+ * tooltip - draw the built-in SVG tooltip (default true)
44
+ * onChange(state) - called with nearestPoints() result, or null on leave;
45
+ * use it with tooltip:false to render your own tooltip
46
+ * Returns { show(px), hide(), destroy() }. Browser only.
47
+ */
48
+ export function attachCrosshair(svg, chart, options = {}) {
49
+ const {
50
+ formatX = (v) => String(v),
51
+ formatY = (v) => String(v),
52
+ tooltip = true,
53
+ onChange,
54
+ } = options
55
+ const { plot } = chart
56
+ const NS = 'http://www.w3.org/2000/svg'
57
+ const g = document.createElementNS(NS, 'g')
58
+ g.setAttribute('class', 'tylix-crosshair')
59
+ g.setAttribute('pointer-events', 'none')
60
+ g.style.display = 'none'
61
+ svg.appendChild(g)
62
+ svg.style.touchAction = 'pan-y'
63
+ if (!svg.hasAttribute('tabindex')) svg.setAttribute('tabindex', '0')
64
+
65
+ let current = null
66
+
67
+ function draw(state) {
68
+ let out =
69
+ `<line x1="${fmt(state.px)}" x2="${fmt(state.px)}" y1="${plot.y}" y2="${plot.y + plot.height}" ` +
70
+ `stroke="currentColor" stroke-opacity="0.25" stroke-dasharray="3 3"/>`
71
+ for (const r of state.rows) {
72
+ out += `<circle cx="${fmt(r.px)}" cy="${fmt(r.py)}" r="4.5" fill="${esc(r.color)}" stroke="${BG}" stroke-width="2"/>`
73
+ }
74
+ if (tooltip && state.rows.length) {
75
+ const head = formatX(state.x)
76
+ const lines = state.rows.map((r) => ({
77
+ color: r.color,
78
+ name: r.name,
79
+ value: r.value === null ? '–' : formatY(r.value),
80
+ }))
81
+ const chars = Math.max(
82
+ String(head).length,
83
+ ...lines.map((l) => l.name.length + String(l.value).length + 3)
84
+ )
85
+ const w = Math.ceil(chars * 6.2 + 28)
86
+ const h = 26 + lines.length * 16
87
+ let tx = state.px + 12
88
+ if (tx + w > chart.width - 4) tx = state.px - 12 - w
89
+ tx = Math.max(4, tx)
90
+ const ty = plot.y + 4
91
+ out +=
92
+ `<g transform="translate(${fmt(tx)},${fmt(ty)})">` +
93
+ `<rect width="${w}" height="${h}" rx="6" fill="${BG}" stroke="currentColor" stroke-opacity="0.18"/>` +
94
+ `<text x="10" y="16" font-size="11" font-weight="600" fill="currentColor">${esc(head)}</text>`
95
+ lines.forEach((l, i) => {
96
+ const y = 16 + (i + 1) * 16
97
+ out +=
98
+ `<circle cx="14" cy="${y - 4}" r="3.5" fill="${esc(l.color)}"/>` +
99
+ `<text x="24" y="${y}" font-size="11" fill="currentColor" fill-opacity="0.7">${esc(l.name)}</text>` +
100
+ `<text x="${w - 10}" y="${y}" font-size="11" text-anchor="end" font-weight="600" fill="currentColor">${esc(l.value)}</text>`
101
+ })
102
+ out += '</g>'
103
+ }
104
+ g.innerHTML = out
105
+ }
106
+
107
+ function show(px) {
108
+ const state = nearestPoints(chart, px)
109
+ if (!state) return hide()
110
+ current = state
111
+ g.style.display = ''
112
+ draw(state)
113
+ onChange?.(state)
114
+ }
115
+
116
+ function hide() {
117
+ if (!current) return
118
+ current = null
119
+ g.style.display = 'none'
120
+ g.innerHTML = ''
121
+ onChange?.(null)
122
+ }
123
+
124
+ const toUser = (e) => {
125
+ const r = svg.getBoundingClientRect()
126
+ return r.width ? ((e.clientX - r.left) * chart.width) / r.width : NaN
127
+ }
128
+
129
+ const onMove = (e) => {
130
+ const x = toUser(e)
131
+ if (x >= plot.x && x <= plot.x + plot.width) show(x)
132
+ else hide()
133
+ }
134
+ const onKey = (e) => {
135
+ if (e.key === 'Escape') return hide()
136
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return
137
+ const xs = snapPositions(chart)
138
+ if (!xs.length) return
139
+ e.preventDefault()
140
+ const i = current ? current.index + (e.key === 'ArrowRight' ? 1 : -1) : e.key === 'ArrowRight' ? 0 : xs.length - 1
141
+ show(xs[Math.min(xs.length - 1, Math.max(0, i))])
142
+ }
143
+
144
+ svg.addEventListener('pointermove', onMove)
145
+ svg.addEventListener('pointerdown', onMove)
146
+ svg.addEventListener('pointerleave', hide)
147
+ svg.addEventListener('keydown', onKey)
148
+ svg.addEventListener('blur', hide)
149
+
150
+ return {
151
+ show,
152
+ hide,
153
+ destroy() {
154
+ svg.removeEventListener('pointermove', onMove)
155
+ svg.removeEventListener('pointerdown', onMove)
156
+ svg.removeEventListener('pointerleave', hide)
157
+ svg.removeEventListener('keydown', onKey)
158
+ svg.removeEventListener('blur', hide)
159
+ g.remove()
160
+ },
161
+ }
162
+ }