@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.
package/src/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ // ---------------------------------------------------------------- scales & ticks
1
2
  export interface LinearScale {
2
3
  (value: number): number
3
4
  invert(px: number): number
@@ -12,14 +13,37 @@ export function linearScale(options?: {
12
13
  clamp?: boolean
13
14
  }): LinearScale
14
15
 
16
+ export interface BandScale<T = unknown> {
17
+ (value: T): number | undefined
18
+ bandwidth(): number
19
+ step(): number
20
+ center(value: T): number | undefined
21
+ domain(): T[]
22
+ range(): [number, number]
23
+ }
24
+
25
+ export function bandScale<T = unknown>(options?: {
26
+ domain?: T[]
27
+ range?: [number, number]
28
+ padding?: number
29
+ paddingInner?: number
30
+ paddingOuter?: number
31
+ }): BandScale<T>
32
+
15
33
  export function niceTicks(min: number, max: number, count?: number): number[]
16
34
  export function extent(values: Iterable<unknown>): [number, number] | null
17
35
 
36
+ // ---------------------------------------------------------------- paths
18
37
  export interface PixelPoint {
19
38
  x: number | null
20
39
  y: number | null
21
40
  }
22
- export type Curve = 'linear' | 'step'
41
+ export interface BandPoint extends PixelPoint {
42
+ /** Bottom edge (pixel y) of the band at this x. */
43
+ y0: number | null
44
+ }
45
+ /** 'smooth' is a monotone cubic: it never overshoots the data. */
46
+ export type Curve = 'linear' | 'step' | 'smooth'
23
47
 
24
48
  export function segments<T extends PixelPoint>(points: Array<T | null>): T[][]
25
49
  export function linePath(points: Array<PixelPoint | null>, options?: { curve?: Curve }): string
@@ -28,7 +52,29 @@ export function areaPath(
28
52
  baselineY: number,
29
53
  options?: { curve?: Curve }
30
54
  ): string
55
+ export function bandPath(points: Array<BandPoint | null>, options?: { curve?: Curve }): string
56
+
57
+ // ---------------------------------------------------------------- shared
58
+ export const DEFAULT_PALETTE: string[]
59
+
60
+ export interface Margin {
61
+ top: number
62
+ right: number
63
+ bottom: number
64
+ left: number
65
+ }
31
66
 
67
+ /** Options accepted by every *Svg() renderer. */
68
+ export interface SvgOptions {
69
+ /** Accessible name (aria-label). */
70
+ label?: string
71
+ /** Stable id for the generated gradients / scoped styles (set it for SSR + hydration). */
72
+ id?: string
73
+ /** Hover tooltips, hover dots and hover highlight. Default true. */
74
+ interactive?: boolean
75
+ }
76
+
77
+ // ---------------------------------------------------------------- sparkline
32
78
  export interface SparklineOptions {
33
79
  width?: number
34
80
  height?: number
@@ -53,6 +99,7 @@ export interface SparklineGeometry {
53
99
  export function sparkline(data?: Array<number | null>, options?: SparklineOptions): SparklineGeometry
54
100
  export function sparklineSvg(data?: Array<number | null>, options?: SparklineOptions): string
55
101
 
102
+ // ---------------------------------------------------------------- line
56
103
  export interface LineSeriesInput {
57
104
  name?: string
58
105
  color?: string
@@ -62,7 +109,7 @@ export interface LineSeriesInput {
62
109
  export interface LineChartOptions {
63
110
  width?: number
64
111
  height?: number
65
- margin?: Partial<{ top: number; right: number; bottom: number; left: number }>
112
+ margin?: Partial<Margin>
66
113
  xDomain?: [number, number]
67
114
  yDomain?: [number, number]
68
115
  xTicks?: number
@@ -75,14 +122,19 @@ export interface LineChartOptions {
75
122
  label?: string
76
123
  }
77
124
 
125
+ export interface XYTick {
126
+ value: number
127
+ label: string
128
+ }
129
+
78
130
  export interface LineChartGeometry {
79
131
  width: number
80
132
  height: number
81
133
  plot: { x: number; y: number; width: number; height: number }
82
134
  xScale: LinearScale
83
135
  yScale: LinearScale
84
- xTicks: Array<{ value: number; x: number; label: string }>
85
- yTicks: Array<{ value: number; y: number; label: string }>
136
+ xTicks: Array<XYTick & { x: number }>
137
+ yTicks: Array<XYTick & { y: number }>
86
138
  series: Array<{
87
139
  name: string
88
140
  color: string
@@ -92,6 +144,240 @@ export interface LineChartGeometry {
92
144
  }>
93
145
  }
94
146
 
95
- export const DEFAULT_PALETTE: string[]
147
+ export interface LineChartSvgOptions extends LineChartOptions, SvgOptions {
148
+ /** Default: shown when there are 2+ series. */
149
+ legend?: boolean
150
+ /** 'hover' (default): dot appears on hover. 'all': always. 'none': no dots, no tooltips. */
151
+ dots?: 'hover' | 'all' | 'none'
152
+ }
153
+
96
154
  export function lineChart(series?: LineSeriesInput[], options?: LineChartOptions): LineChartGeometry
97
- export function lineChartSvg(series?: LineSeriesInput[], options?: LineChartOptions): string
155
+ export function lineChartSvg(series?: LineSeriesInput[], options?: LineChartSvgOptions): string
156
+
157
+ // ---------------------------------------------------------------- area
158
+ export interface AreaChartOptions extends Omit<LineChartOptions, 'area'> {
159
+ /** Sum series per x position (index-aligned, null counts as 0, values >= 0). */
160
+ stacked?: boolean
161
+ }
162
+
163
+ export interface AreaChartGeometry extends Omit<LineChartGeometry, 'series'> {
164
+ stacked: boolean
165
+ series: Array<{
166
+ name: string
167
+ color: string
168
+ points: Array<{
169
+ value: number | null
170
+ x: number
171
+ px: number
172
+ py: number | null
173
+ /** Lower edge of the band (baseline, or the series below when stacked). */
174
+ py0: number
175
+ }>
176
+ path: string
177
+ areaPath: string
178
+ }>
179
+ }
180
+
181
+ export interface AreaChartSvgOptions extends AreaChartOptions, SvgOptions {
182
+ legend?: boolean
183
+ dots?: 'hover' | 'all' | 'none'
184
+ }
185
+
186
+ export function areaChart(series?: LineSeriesInput[], options?: AreaChartOptions): AreaChartGeometry
187
+ export function areaChartSvg(series?: LineSeriesInput[], options?: AreaChartSvgOptions): string
188
+
189
+ // ---------------------------------------------------------------- bar
190
+ export interface BarSeriesInput {
191
+ name?: string
192
+ color?: string
193
+ data: Array<number | null>
194
+ }
195
+
196
+ export interface BarChartOptions {
197
+ /** Labels along the category axis. Defaults to "1", "2", … */
198
+ categories?: unknown[]
199
+ orientation?: 'vertical' | 'horizontal'
200
+ stacked?: boolean
201
+ width?: number
202
+ height?: number
203
+ margin?: Partial<Margin>
204
+ yDomain?: [number, number]
205
+ yTicks?: number
206
+ /** Include 0 in the value domain. Default true. */
207
+ zeroBaseline?: boolean
208
+ /** Space between categories, 0..1. Default 0.3. */
209
+ padding?: number
210
+ /** Space between bars inside a group, 0..1. Default 0.08. */
211
+ groupPadding?: number
212
+ /** Corner radius of the outer end of each bar, px. Default 4. */
213
+ radius?: number
214
+ formatValue?: (value: number) => string
215
+ formatCategory?: (category: unknown) => string
216
+ label?: string
217
+ }
218
+
219
+ export interface Bar {
220
+ index: number
221
+ category: unknown
222
+ categoryLabel: string
223
+ value: number | null
224
+ label: string
225
+ x: number
226
+ y: number
227
+ width: number
228
+ height: number
229
+ /** Empty string when the value is null or 0. */
230
+ path: string
231
+ }
232
+
233
+ export interface BarChartGeometry {
234
+ width: number
235
+ height: number
236
+ plot: { x: number; y: number; width: number; height: number }
237
+ orientation: 'vertical' | 'horizontal'
238
+ stacked: boolean
239
+ /** Pixel position of the zero line along the value axis. */
240
+ baseline: number
241
+ valueScale: LinearScale
242
+ categoryScale: BandScale<number>
243
+ /** `pos` is y for vertical charts, x for horizontal ones. */
244
+ valueTicks: Array<{ value: number; pos: number; label: string }>
245
+ categoryTicks: Array<{ index: number; label: string; pos: number }>
246
+ series: Array<{ name: string; color: string; bars: Bar[] }>
247
+ }
248
+
249
+ export interface BarChartSvgOptions extends BarChartOptions, SvgOptions {
250
+ legend?: boolean
251
+ /** Print the value next to each bar (grouped charts only). */
252
+ valueLabels?: boolean
253
+ }
254
+
255
+ export function roundedBarPath(
256
+ x: number,
257
+ y: number,
258
+ w: number,
259
+ h: number,
260
+ r?: number,
261
+ side?: 'top' | 'bottom' | 'left' | 'right' | 'none'
262
+ ): string
263
+ export function barChart(series?: BarSeriesInput[], options?: BarChartOptions): BarChartGeometry
264
+ export function barChartSvg(series?: BarSeriesInput[], options?: BarChartSvgOptions): string
265
+
266
+ // ---------------------------------------------------------------- pie / donut
267
+ export interface PieDatum {
268
+ label?: string
269
+ value: number
270
+ color?: string
271
+ }
272
+
273
+ export interface PieChartOptions {
274
+ width?: number
275
+ height?: number
276
+ /** 0..1, fraction of the outer radius. 0 = pie. donutChart() defaults to 0.62. */
277
+ innerRadius?: number
278
+ /** Rounded slice corners, px. Default 4. */
279
+ cornerRadius?: number
280
+ /** Gap between slices, px. Default 2. */
281
+ gap?: number
282
+ /** Degrees; 0 = 12 o'clock, clockwise. */
283
+ startAngle?: number
284
+ sort?: 'none' | 'desc' | 'asc'
285
+ /** Free space around the chart, px. Default 4. */
286
+ margin?: number
287
+ formatValue?: (value: number) => string
288
+ formatPercent?: (fraction: number) => string
289
+ }
290
+
291
+ export interface PieSlice {
292
+ index: number
293
+ label: string
294
+ value: number
295
+ valueLabel: string
296
+ /** 0..1 */
297
+ percent: number
298
+ percentLabel: string
299
+ color: string
300
+ startAngle: number
301
+ endAngle: number
302
+ midAngle: number
303
+ /** Empty string for zero-value slices. Render with fill-rule="evenodd". */
304
+ path: string
305
+ centroid: { x: number; y: number }
306
+ /** A point just outside the slice, for external labels. */
307
+ labelPoint: { x: number; y: number }
308
+ }
309
+
310
+ export interface PieChartGeometry {
311
+ width: number
312
+ height: number
313
+ cx: number
314
+ cy: number
315
+ outerRadius: number
316
+ innerRadius: number
317
+ total: number
318
+ slices: PieSlice[]
319
+ }
320
+
321
+ export interface PieChartSvgOptions extends Omit<PieChartOptions, 'width' | 'height'>, SvgOptions {
322
+ /** Chart diameter box in px. Default 220. */
323
+ size?: number
324
+ /** Default 'right'. */
325
+ legend?: 'right' | 'bottom' | false
326
+ /** Donut only. Defaults to the formatted total; false hides it. */
327
+ centerLabel?: string | false
328
+ /** Donut only. Default "Total"; false or '' hides it. */
329
+ centerSubLabel?: string | false
330
+ }
331
+
332
+ export function arcPath(options?: {
333
+ cx?: number
334
+ cy?: number
335
+ innerRadius?: number
336
+ outerRadius?: number
337
+ startAngle?: number
338
+ endAngle?: number
339
+ cornerRadius?: number
340
+ }): string
341
+ export function pieChart(data?: Array<number | PieDatum>, options?: PieChartOptions): PieChartGeometry
342
+ export function donutChart(data?: Array<number | PieDatum>, options?: PieChartOptions): PieChartGeometry
343
+ export function pieChartSvg(data?: Array<number | PieDatum>, options?: PieChartSvgOptions): string
344
+ export function donutChartSvg(data?: Array<number | PieDatum>, options?: PieChartSvgOptions): string
345
+
346
+ // ---------------------------------------------------------------- crosshair
347
+ export interface CrosshairRow {
348
+ name: string
349
+ color: string
350
+ value: number | null
351
+ x: number
352
+ px: number
353
+ py: number
354
+ }
355
+
356
+ export interface CrosshairState {
357
+ /** Position in the snap list. */
358
+ index: number
359
+ /** Pixel x of the snapped data position. */
360
+ px: number
361
+ /** Data x value. */
362
+ x: number
363
+ rows: CrosshairRow[]
364
+ }
365
+
366
+ export function snapPositions(chart: LineChartGeometry | AreaChartGeometry): number[]
367
+ export function nearestPoints(chart: LineChartGeometry | AreaChartGeometry, px: number): CrosshairState | null
368
+
369
+ export interface CrosshairOptions {
370
+ formatX?: (value: number) => string
371
+ formatY?: (value: number) => string
372
+ /** Draw the built-in SVG tooltip. Default true. */
373
+ tooltip?: boolean
374
+ /** Called with the snapped state, or null when the pointer leaves. */
375
+ onChange?: (state: CrosshairState | null) => void
376
+ }
377
+
378
+ /** Browser only. Pass the same geometry the SVG was rendered from. */
379
+ export function attachCrosshair(
380
+ svg: SVGSVGElement,
381
+ chart: LineChartGeometry | AreaChartGeometry,
382
+ options?: CrosshairOptions
383
+ ): { show(px: number): void; hide(): void; destroy(): void }
package/src/index.js CHANGED
@@ -1,6 +1,18 @@
1
1
  export { linearScale } from './scales.js'
2
+ export { bandScale } from './band.js'
2
3
  export { niceTicks, extent } from './ticks.js'
3
- export { linePath, areaPath, segments } from './path.js'
4
+ export { linePath, areaPath, bandPath, segments } from './path.js'
4
5
  export { sparkline } from './sparkline.js'
5
6
  export { lineChart, DEFAULT_PALETTE } from './line.js'
6
- export { sparklineSvg, lineChartSvg } from './svg.js'
7
+ export { areaChart } from './area.js'
8
+ export { barChart, roundedBarPath } from './bar.js'
9
+ export { pieChart, donutChart, arcPath } from './pie.js'
10
+ export {
11
+ sparklineSvg,
12
+ lineChartSvg,
13
+ areaChartSvg,
14
+ barChartSvg,
15
+ pieChartSvg,
16
+ donutChartSvg,
17
+ } from './svg.js'
18
+ export { attachCrosshair, nearestPoints, snapPositions } from './crosshair.js'
package/src/line.js CHANGED
@@ -11,7 +11,7 @@ export const DEFAULT_PALETTE = [
11
11
  ]
12
12
 
13
13
  // Accepts [1, 2, 3] (x = index) or [{ x, y }, ...]
14
- function normalizeData(data = []) {
14
+ export function normalizeData(data = []) {
15
15
  return data.map((d, i) => {
16
16
  if (typeof d === 'number') return { x: i, y: d }
17
17
  if (d == null) return { x: i, y: null }
package/src/path.js CHANGED
@@ -1,7 +1,9 @@
1
1
  // SVG path-data builders. Points are { x, y } in pixel space.
2
2
  // A point with a null / non-finite x or y breaks the line (a gap).
3
+ // Curves: 'linear' (default) | 'step' | 'smooth' (monotone cubic, never overshoots).
3
4
 
4
5
  const fmt = (n) => Math.round(n * 100) / 100
6
+ const pt = (x, y) => `${fmt(x)},${fmt(y)}`
5
7
 
6
8
  const isValid = (p) =>
7
9
  p != null &&
@@ -26,43 +28,117 @@ export function segments(points) {
26
28
  return runs
27
29
  }
28
30
 
31
+ // Monotone-X tangents (Fritsch–Carlson, as in d3.curveMonotoneX).
32
+ function tangents(run) {
33
+ const n = run.length
34
+ const dx = []
35
+ const m = []
36
+ for (let i = 0; i < n - 1; i++) {
37
+ dx[i] = run[i + 1].x - run[i].x
38
+ m[i] = (run[i + 1].y - run[i].y) / dx[i]
39
+ }
40
+ const t = new Array(n)
41
+ if (n === 2) {
42
+ t[0] = t[1] = m[0]
43
+ return t
44
+ }
45
+ for (let i = 1; i < n - 1; i++) {
46
+ const s0 = m[i - 1]
47
+ const s1 = m[i]
48
+ if (s0 * s1 <= 0) {
49
+ t[i] = 0
50
+ continue
51
+ }
52
+ const p = (s0 * dx[i] + s1 * dx[i - 1]) / (dx[i - 1] + dx[i])
53
+ t[i] =
54
+ (Math.sign(s0) + Math.sign(s1)) *
55
+ Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p))
56
+ }
57
+ t[0] = (3 * m[0] - t[1]) / 2
58
+ t[n - 1] = (3 * m[n - 2] - t[n - 2]) / 2
59
+ return t
60
+ }
61
+
62
+ const strictlyIncreasing = (run) => run.every((p, i) => i === 0 || p.x > run[i - 1].x)
63
+
64
+ // One cubic Bézier per segment: { c1, c2, to }
65
+ function cubics(run) {
66
+ const t = tangents(run)
67
+ return run.slice(1).map((p, i) => {
68
+ const a = run[i]
69
+ const d = (p.x - a.x) / 3
70
+ return { c1: [a.x + d, a.y + t[i] * d], c2: [p.x - d, p.y - t[i + 1] * d], to: p }
71
+ })
72
+ }
73
+
74
+ const useSmooth = (run, curve) => curve === 'smooth' && run.length > 2 && strictlyIncreasing(run)
75
+
29
76
  function runPath(run, curve) {
30
- let d = `M${fmt(run[0].x)},${fmt(run[0].y)}`
77
+ let d = `M${pt(run[0].x, run[0].y)}`
78
+ if (useSmooth(run, curve)) {
79
+ for (const s of cubics(run)) {
80
+ d += `C${pt(...s.c1)} ${pt(...s.c2)} ${pt(s.to.x, s.to.y)}`
81
+ }
82
+ return d
83
+ }
31
84
  for (let i = 1; i < run.length; i++) {
32
85
  const p = run[i]
86
+ d += curve === 'step' ? `H${fmt(p.x)}V${fmt(p.y)}` : `L${pt(p.x, p.y)}`
87
+ }
88
+ return d
89
+ }
90
+
91
+ // Draws the run backwards, assuming the pen already sits on its last point.
92
+ function reversePath(run, curve) {
93
+ let d = ''
94
+ if (useSmooth(run, curve)) {
95
+ const cs = cubics(run)
96
+ for (let i = cs.length - 1; i >= 0; i--) {
97
+ d += `C${pt(...cs[i].c2)} ${pt(...cs[i].c1)} ${pt(run[i].x, run[i].y)}`
98
+ }
99
+ return d
100
+ }
101
+ for (let i = run.length - 1; i > 0; i--) {
33
102
  d +=
34
103
  curve === 'step'
35
- ? `H${fmt(p.x)}V${fmt(p.y)}`
36
- : `L${fmt(p.x)},${fmt(p.y)}`
104
+ ? `V${fmt(run[i - 1].y)}H${fmt(run[i - 1].x)}`
105
+ : `L${pt(run[i - 1].x, run[i - 1].y)}`
37
106
  }
38
107
  return d
39
108
  }
40
109
 
41
110
  /**
42
- * Line path. curve: 'linear' (default) | 'step'.
111
+ * Line path. curve: 'linear' (default) | 'step' | 'smooth'.
43
112
  * A lone point renders as a zero-length segment so it stays visible with round caps.
44
113
  */
45
114
  export function linePath(points, { curve = 'linear' } = {}) {
46
115
  return segments(points)
47
116
  .map((run) =>
48
- run.length === 1
49
- ? `M${fmt(run[0].x)},${fmt(run[0].y)}h0`
50
- : runPath(run, curve)
117
+ run.length === 1 ? `M${pt(run[0].x, run[0].y)}h0` : runPath(run, curve)
51
118
  )
52
119
  .join('')
53
120
  }
54
121
 
55
- /** Closed area path between the line and a horizontal baseline (pixel y). */
56
- export function areaPath(points, baselineY, { curve = 'linear' } = {}) {
57
- return segments(points)
122
+ /**
123
+ * Closed band between two lines. Points are { x, y, y0 }: y is the top edge,
124
+ * y0 the bottom edge. Used for stacked areas; areaPath() is the y0 = baseline case.
125
+ */
126
+ export function bandPath(points, { curve = 'linear' } = {}) {
127
+ const valid = points.map((p) => (isValid(p) && Number.isFinite(p.y0) ? p : null))
128
+ return segments(valid)
58
129
  .filter((run) => run.length > 1)
59
130
  .map((run) => {
60
- const first = run[0]
61
- const last = run[run.length - 1]
62
- return (
63
- runPath(run, curve) +
64
- `L${fmt(last.x)},${fmt(baselineY)}L${fmt(first.x)},${fmt(baselineY)}Z`
65
- )
131
+ const bottom = run.map((p) => ({ x: p.x, y: p.y0 }))
132
+ const last = bottom[bottom.length - 1]
133
+ return `${runPath(run, curve)}L${pt(last.x, last.y)}${reversePath(bottom, curve)}Z`
66
134
  })
67
135
  .join('')
68
136
  }
137
+
138
+ /** Closed area path between the line and a horizontal baseline (pixel y). */
139
+ export function areaPath(points, baselineY, { curve = 'linear' } = {}) {
140
+ return bandPath(
141
+ points.map((p) => (isValid(p) ? { x: p.x, y: p.y, y0: baselineY } : null)),
142
+ { curve }
143
+ )
144
+ }