@clarity-js/charts 0.0.0-stage → 1.1.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/README.md +132 -2
- package/index.d.ts +407 -0
- package/maps/index.d.ts +5 -0
- package/maps/turkey.js +3 -0
- package/maps/world.js +3 -0
- package/package.json +21 -4
- package/src/axes.js +281 -0
- package/src/compat.js +414 -0
- package/src/components.js +111 -0
- package/src/controllers.js +321 -0
- package/src/core.js +914 -0
- package/src/depth.js +316 -0
- package/src/features.js +783 -0
- package/src/fills.js +187 -0
- package/src/format.js +42 -0
- package/src/full.js +23 -0
- package/src/graphs.js +342 -0
- package/src/index.js +53 -0
- package/src/layouts.js +272 -0
- package/src/lite.js +40 -0
- package/src/maps.js +227 -0
- package/src/painter.js +162 -0
- package/src/plugins.js +381 -0
- package/src/scale.js +108 -0
- package/src/shape.js +119 -0
- package/src/themes.js +79 -0
- package/src/types.js +1193 -0
package/src/painter.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// @clarity-js/charts — the two surfaces a chart draws on, behind one small set of calls. SVG (the
|
|
2
|
+
// default) keeps every mark as an element: a screen reader finds the chart, the server can draw
|
|
3
|
+
// it, and a strict Content-Security-Policy lets it through. Canvas draws a million points and lets
|
|
4
|
+
// a plugin draw with `chart.ctx`, as Chart.js plugins do. A path is an SVG path string on both
|
|
5
|
+
// (Path2D reads the same string on a canvas).
|
|
6
|
+
|
|
7
|
+
import { isPaint, svgPaints, treeMarkup, canvasPaint, pathBox } from './fills.js';
|
|
8
|
+
|
|
9
|
+
const SVG = 'http://www.w3.org/2000/svg';
|
|
10
|
+
|
|
11
|
+
/** The width of a line of text in a font, in pixels (a canvas measures it; without one, a close guess). */
|
|
12
|
+
let measurer = null;
|
|
13
|
+
export function measureText(text, font) {
|
|
14
|
+
const s = String(text ?? '');
|
|
15
|
+
if (measurer === null) {
|
|
16
|
+
try { const c = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(1, 1) : globalThis.document?.createElement('canvas'); measurer = c?.getContext?.('2d') ?? false; } catch { measurer = false; }
|
|
17
|
+
}
|
|
18
|
+
if (measurer) { measurer.font = fontString(font); return measurer.measureText(s).width; }
|
|
19
|
+
// no canvas (a server): each letter's width as a share of the size, near a sans-serif's
|
|
20
|
+
let w = 0;
|
|
21
|
+
for (const ch of s) w += /[il.,:;'|!]/.test(ch) ? 0.28 : /[ftjrI()[\]\-]/.test(ch) ? 0.36 : /[mwMW@]/.test(ch) ? 0.86 : /[A-Z]/.test(ch) ? 0.68 : /[0-9]/.test(ch) ? 0.57 : ch === ' ' ? 0.28 : /[a-z]/.test(ch) ? 0.53 : 0.6;
|
|
22
|
+
const bold = font?.weight === 'bold' || Number(font?.weight) >= 600;
|
|
23
|
+
return w * (font?.size ?? 12) * (bold ? 1.06 : 1);
|
|
24
|
+
}
|
|
25
|
+
export const fontString = (f = {}) => `${f.style ?? 'normal'} ${f.weight ?? 'normal'} ${f.size ?? 12}px ${f.family ?? 'system-ui, sans-serif'}`;
|
|
26
|
+
|
|
27
|
+
/** An SVG surface. */
|
|
28
|
+
export function svgPainter(svg) {
|
|
29
|
+
let parent = svg, clipId = 0, defs = null;
|
|
30
|
+
const groups = new Map();
|
|
31
|
+
const attr = (e, a) => { for (const k in a) if (a[k] != null && a[k] !== '') e.setAttribute(k, a[k]); return e; };
|
|
32
|
+
const make = (tag, a) => { const e = attr(document.createElementNS(SVG, tag), a); parent.appendChild(e); return e; };
|
|
33
|
+
const build = (n) => { const e = attr(document.createElementNS(SVG, n.tag), n.attrs); for (const c of n.children ?? []) e.appendChild(build(c)); return e; };
|
|
34
|
+
const paints = svgPaints((tree) => { if (!defs) { defs = document.createElementNS(SVG, 'defs'); svg.insertBefore(defs, svg.firstChild); } defs.appendChild(build(tree)); });
|
|
35
|
+
const stroke = (st) => ({
|
|
36
|
+
fill: paints.url(st.fill) ?? 'none', stroke: paints.url(st.stroke) ?? 'none', 'stroke-width': st.stroke ? st.width ?? 1 : null,
|
|
37
|
+
'stroke-dasharray': st.dash?.length ? st.dash.join(' ') : null, 'stroke-dashoffset': st.dashOffset || null, opacity: st.opacity != null && st.opacity < 1 ? st.opacity : null,
|
|
38
|
+
'stroke-linecap': st.cap ?? null, 'stroke-linejoin': st.join ?? null, 'clip-path': st.clip ?? null,
|
|
39
|
+
});
|
|
40
|
+
return {
|
|
41
|
+
kind: 'svg', element: svg,
|
|
42
|
+
// the picture fills its container's width and keeps its shape: it never pushes the container wider
|
|
43
|
+
size(w, h) { attr(svg, { width: w, height: h, viewBox: `0 0 ${w} ${h}` }); svg.style.width = '100%'; svg.style.height = 'auto'; svg.style.maxWidth = '100%'; },
|
|
44
|
+
clear() { svg.replaceChildren(); groups.clear(); parent = svg; defs = null; paints.clear(); },
|
|
45
|
+
paint: (v) => paints.url(v),
|
|
46
|
+
/** Draw into a named layer from here on (layers keep the order they were first asked for). */
|
|
47
|
+
layer(name) { let g = groups.get(name); if (!g) { g = document.createElementNS(SVG, 'g'); g.setAttribute('data-layer', name); svg.appendChild(g); groups.set(name, g); } parent = g; return g; },
|
|
48
|
+
path(d, st = {}) { if (d) return make('path', { d, ...stroke(st) }); return null; },
|
|
49
|
+
rect(x, y, w, h, st = {}) { return make('rect', { x, y, width: Math.max(0, w), height: Math.max(0, h), rx: st.radius || null, ...stroke(st) }); },
|
|
50
|
+
circle(cx, cy, r, st = {}) { return make('circle', { cx, cy, r: Math.max(0, r), ...stroke(st) }); },
|
|
51
|
+
line(x1, y1, x2, y2, st = {}) { return make('line', { x1, y1, x2, y2, ...stroke({ ...st, fill: null }) }); },
|
|
52
|
+
text(str, x, y, st = {}) {
|
|
53
|
+
const f = st.font ?? {}, e = make('text', {
|
|
54
|
+
x, y, fill: paints.url(st.fill) ?? '#666', 'font-size': f.size ?? 12, 'font-family': f.family ?? null, 'font-weight': f.weight ?? null, 'font-style': f.style ?? null,
|
|
55
|
+
'text-anchor': { left: 'start', center: 'middle', right: 'end', start: 'start', end: 'end' }[st.align ?? 'left'],
|
|
56
|
+
'dominant-baseline': { top: 'hanging', middle: 'central', bottom: 'text-after-edge', alphabetic: null }[st.baseline ?? 'alphabetic'],
|
|
57
|
+
transform: st.rotate ? `rotate(${st.rotate} ${x} ${y})` : null, opacity: st.opacity != null && st.opacity < 1 ? st.opacity : null,
|
|
58
|
+
});
|
|
59
|
+
e.textContent = String(str);
|
|
60
|
+
return e;
|
|
61
|
+
},
|
|
62
|
+
/** A clipping rectangle: the id to give marks as st.clip. */
|
|
63
|
+
clipRect(x, y, w, h) { const id = `cc${++clipId}-${Math.random().toString(36).slice(2, 7)}`; const defs = make('defs', {}); const cp = attr(document.createElementNS(SVG, 'clipPath'), { id }); defs.appendChild(cp); cp.appendChild(attr(document.createElementNS(SVG, 'rect'), { x, y, width: Math.max(0, w), height: Math.max(0, h) })); return `url(#${id})`; },
|
|
64
|
+
/** A clipping path (any SVG path): the id to give marks as st.clip. */
|
|
65
|
+
clipPath(d) { const id = `cp${++clipId}-${Math.random().toString(36).slice(2, 7)}`; const defs = make('defs', {}); const cp = attr(document.createElementNS(SVG, 'clipPath'), { id }); defs.appendChild(cp); cp.appendChild(attr(document.createElementNS(SVG, 'path'), { d })); return `url(#${id})`; },
|
|
66
|
+
measure: measureText,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// a colour a canvas can take: a CSS variable is looked up on the element
|
|
71
|
+
function resolver(canvas) {
|
|
72
|
+
const cache = new Map();
|
|
73
|
+
return (c) => {
|
|
74
|
+
if (typeof c !== 'string' || !c.includes('var(')) return c;
|
|
75
|
+
if (cache.has(c)) return cache.get(c);
|
|
76
|
+
const m = /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)/.exec(c);
|
|
77
|
+
let v = m ? globalThis.getComputedStyle?.(canvas).getPropertyValue(m[1]).trim() : '';
|
|
78
|
+
if (!v) v = m?.[2]?.trim() ?? '#666';
|
|
79
|
+
cache.set(c, v);
|
|
80
|
+
return v;
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A canvas surface (drawn at the screen's pixel ratio). */
|
|
85
|
+
export function canvasPainter(canvas, { pixelRatio } = {}) {
|
|
86
|
+
const ctx = canvas.getContext('2d');
|
|
87
|
+
const colour = resolver(canvas);
|
|
88
|
+
let w = 0, h = 0, clipBox = null;
|
|
89
|
+
const ratio = () => pixelRatio ?? globalThis.devicePixelRatio ?? 1;
|
|
90
|
+
const apply = (st) => {
|
|
91
|
+
ctx.globalAlpha = st.opacity ?? 1;
|
|
92
|
+
ctx.setLineDash(st.dash ?? []); ctx.lineDashOffset = st.dashOffset ?? 0;
|
|
93
|
+
ctx.lineCap = st.cap ?? 'butt'; ctx.lineJoin = st.join ?? 'miter'; ctx.lineWidth = st.width ?? 1;
|
|
94
|
+
};
|
|
95
|
+
const clips = new Map();
|
|
96
|
+
const style = (v, box) => (isPaint(v) ? canvasPaint(ctx, v, box(), colour) : colour(v));
|
|
97
|
+
const finish = (p, st, box = () => ({ x: 0, y: 0, w, h })) => {
|
|
98
|
+
ctx.save();
|
|
99
|
+
if (st.clip && clips.has(st.clip)) ctx.clip(clips.get(st.clip));
|
|
100
|
+
else if (st.clip && clipBox) { ctx.beginPath(); ctx.rect(...clipBox); ctx.clip(); }
|
|
101
|
+
apply(st);
|
|
102
|
+
if (st.fill && st.fill !== 'none') { ctx.fillStyle = style(st.fill, box); ctx.fill(p); }
|
|
103
|
+
if (st.stroke && st.stroke !== 'none' && (st.width ?? 1) > 0) { ctx.strokeStyle = style(st.stroke, box); ctx.stroke(p); }
|
|
104
|
+
ctx.restore();
|
|
105
|
+
};
|
|
106
|
+
return {
|
|
107
|
+
kind: 'canvas', element: canvas, ctx,
|
|
108
|
+
size(cw, ch) {
|
|
109
|
+
w = cw; h = ch; const r = ratio();
|
|
110
|
+
canvas.width = Math.round(cw * r); canvas.height = Math.round(ch * r);
|
|
111
|
+
canvas.style.width = '100%'; canvas.style.maxWidth = cw + 'px'; canvas.style.height = 'auto';
|
|
112
|
+
ctx.setTransform(r, 0, 0, r, 0, 0);
|
|
113
|
+
},
|
|
114
|
+
clear() { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.restore(); clips.clear(); clipBox = null; },
|
|
115
|
+
layer() { return null; },
|
|
116
|
+
path(d, st = {}) { if (d) finish(new Path2D(d), st, () => pathBox(d)); },
|
|
117
|
+
rect(x, y, rw, rh, st = {}) { const p = new Path2D(); if (st.radius && p.roundRect) p.roundRect(x, y, Math.max(0, rw), Math.max(0, rh), st.radius); else p.rect(x, y, Math.max(0, rw), Math.max(0, rh)); finish(p, st, () => ({ x, y, w: rw, h: rh })); },
|
|
118
|
+
circle(cx, cy, r, st = {}) { const p = new Path2D(); p.arc(cx, cy, Math.max(0, r), 0, Math.PI * 2); finish(p, st, () => ({ x: cx - r, y: cy - r, w: 2 * r, h: 2 * r })); },
|
|
119
|
+
paint: (v) => v,
|
|
120
|
+
line(x1, y1, x2, y2, st = {}) { const p = new Path2D(); p.moveTo(x1, y1); p.lineTo(x2, y2); finish(p, { ...st, fill: null }); },
|
|
121
|
+
text(str, x, y, st = {}) {
|
|
122
|
+
ctx.save();
|
|
123
|
+
ctx.globalAlpha = st.opacity ?? 1; ctx.fillStyle = colour(st.fill ?? '#666'); ctx.font = fontString(st.font);
|
|
124
|
+
ctx.textAlign = st.align === 'center' ? 'center' : st.align === 'right' || st.align === 'end' ? 'right' : 'left';
|
|
125
|
+
ctx.textBaseline = st.baseline ?? 'alphabetic';
|
|
126
|
+
if (st.rotate) { ctx.translate(x, y); ctx.rotate((st.rotate * Math.PI) / 180); ctx.fillText(String(str), 0, 0); } else ctx.fillText(String(str), x, y);
|
|
127
|
+
ctx.restore();
|
|
128
|
+
},
|
|
129
|
+
clipRect(x, y, cw, ch) { clipBox = [x, y, cw, ch]; return 'area'; },
|
|
130
|
+
clipPath(d) { const id = 'p' + clips.size; clips.set(id, new Path2D(d)); return id; },
|
|
131
|
+
measure: measureText,
|
|
132
|
+
get width() { return w; }, get height() { return h; },
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const esc = (v) => String(v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
137
|
+
/** An SVG drawn as a string (for a server, an e-mail or a file): the same calls, no DOM. */
|
|
138
|
+
let strings = 0;
|
|
139
|
+
export function stringPainter() {
|
|
140
|
+
// ids are unique across the SVGs of one page (several charts drawn on a server into one HTML)
|
|
141
|
+
const layers = new Map(), order = [], rid = (++strings).toString(36); let cur = null, w = 0, h = 0, clipId = 0; const defs = [];
|
|
142
|
+
const paints = svgPaints((tree) => defs.push(treeMarkup(tree)));
|
|
143
|
+
const put = (s) => { if (!cur) { cur = []; layers.set('_', cur); order.push('_'); } cur.push(s); };
|
|
144
|
+
const a = (o) => Object.entries(o).filter(([, v]) => v != null && v !== '').map(([k, v]) => ` ${k}="${esc(v)}"`).join('');
|
|
145
|
+
const st = (s) => ({ fill: paints.url(s.fill) ?? 'none', stroke: paints.url(s.stroke) ?? 'none', 'stroke-width': s.stroke ? s.width ?? 1 : null, 'stroke-dasharray': s.dash?.length ? s.dash.join(' ') : null, opacity: s.opacity != null && s.opacity < 1 ? s.opacity : null, 'stroke-linecap': s.cap ?? null, 'stroke-linejoin': s.join ?? null, 'clip-path': s.clip ?? null });
|
|
146
|
+
return {
|
|
147
|
+
kind: 'string',
|
|
148
|
+
size(cw, ch) { w = cw; h = ch; },
|
|
149
|
+
clear() { layers.clear(); order.length = 0; cur = null; defs.length = 0; paints.clear(); },
|
|
150
|
+
paint: (v) => paints.url(v),
|
|
151
|
+
layer(name) { if (!layers.has(name)) { layers.set(name, []); order.push(name); } cur = layers.get(name); return null; },
|
|
152
|
+
path(d, s = {}) { if (d) put(`<path${a({ d, ...st(s) })}/>`); },
|
|
153
|
+
rect(x, y, rw, rh, s = {}) { put(`<rect${a({ x, y, width: Math.max(0, rw), height: Math.max(0, rh), rx: s.radius || null, ...st(s) })}/>`); },
|
|
154
|
+
circle(cx, cy, r, s = {}) { put(`<circle${a({ cx, cy, r: Math.max(0, r), ...st(s) })}/>`); },
|
|
155
|
+
line(x1, y1, x2, y2, s = {}) { put(`<line${a({ x1, y1, x2, y2, ...st({ ...s, fill: null }) })}/>`); },
|
|
156
|
+
text(str, x, y, s = {}) { const f = s.font ?? {}; put(`<text${a({ x, y, fill: paints.url(s.fill) ?? '#666', 'font-size': f.size ?? 12, 'font-family': f.family ?? null, 'font-weight': f.weight ?? null, 'text-anchor': { left: 'start', center: 'middle', right: 'end', start: 'start', end: 'end' }[s.align ?? 'left'], 'dominant-baseline': { top: 'hanging', middle: 'central', bottom: 'text-after-edge', alphabetic: null }[s.baseline ?? 'alphabetic'], transform: s.rotate ? `rotate(${s.rotate} ${x} ${y})` : null })}>${esc(str)}</text>`); },
|
|
157
|
+
clipRect(x, y, cw, ch) { const id = `sc${rid}-${++clipId}`; defs.push(`<clipPath id="${id}"><rect${a({ x, y, width: Math.max(0, cw), height: Math.max(0, ch) })}/></clipPath>`); return `url(#${id})`; },
|
|
158
|
+
clipPath(d) { const id = `sp${rid}-${++clipId}`; defs.push(`<clipPath id="${id}"><path${a({ d })}/></clipPath>`); return `url(#${id})`; },
|
|
159
|
+
measure: measureText,
|
|
160
|
+
toString(label = '') { return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}" viewBox="0 0 ${w} ${h}" role="img"${label ? ` aria-label="${esc(label)}"` : ''}><defs>${defs.join('')}</defs>${order.map((n) => `<g data-layer="${esc(n)}">${layers.get(n).join('')}</g>`).join('')}</svg>`; },
|
|
161
|
+
};
|
|
162
|
+
}
|
package/src/plugins.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
// @clarity-js/charts — the plugins Chart.js has built in: title, subtitle, legend, tooltip, filler,
|
|
2
|
+
// decimation and colors. Each is a plain object with hooks (beforeDraw, afterEvent …) and its
|
|
3
|
+
// defaults, as a plugin of your own would be: Chart.register(myPlugin), or config.plugins.
|
|
4
|
+
|
|
5
|
+
import { pointShape, runsOf, pathThrough, tipPoint } from './controllers.js';
|
|
6
|
+
import { cssPaint } from './fills.js';
|
|
7
|
+
import { formatNumber } from './format.js';
|
|
8
|
+
import { formatTime, TIME_FORMATS } from './axes.js';
|
|
9
|
+
|
|
10
|
+
const lineOf = (f) => (f?.size ?? 12) * (f?.lineHeight ?? 1.2);
|
|
11
|
+
const font = (chart, own) => ({ ...chart.resolved.font, ...(own ?? {}) });
|
|
12
|
+
const ROUND = new Set(['pie', 'doughnut', 'polarArea']);
|
|
13
|
+
// a type whose legend and tooltip speak of its points (slices, cells, segments, nodes), not its datasets
|
|
14
|
+
export const perPoint = (m) => !!m && (ROUND.has(m.type) || m.controller?.legend === 'points');
|
|
15
|
+
|
|
16
|
+
/** The colours datasets take when they name none (the colors plugin; Chart.defaults.plugins.colors.palette to change them). */
|
|
17
|
+
export const PALETTE = ['#3d7dd8', '#e0793a', '#2a9d8f', '#c94f7c', '#8a6fd1', '#c99a1e', '#5b8c3a', '#6f7d8c'];
|
|
18
|
+
const alpha = (hex, a) => { const m = /^#([0-9a-f]{6})$/i.exec(hex); if (!m) return hex; const n = parseInt(m[1], 16); return `rgba(${n >> 16}, ${(n >> 8) & 255}, ${n & 255}, ${a})`; };
|
|
19
|
+
export function colorize(chart) {
|
|
20
|
+
const o = chart.resolved.plugins?.colors ?? {};
|
|
21
|
+
if (o.enabled === false) return;
|
|
22
|
+
const pal = o.palette ?? PALETTE;
|
|
23
|
+
let k = 0;
|
|
24
|
+
for (const m of chart.metas) {
|
|
25
|
+
const ds = m.dataset, own = ds.backgroundColor != null || ds.borderColor != null;
|
|
26
|
+
m.auto = null;
|
|
27
|
+
if (m.controller.colors === 'none') continue;
|
|
28
|
+
if (own && !o.forceOverride) continue;
|
|
29
|
+
if (ROUND.has(m.type)) { const n = (ds.data ?? []).length; m.auto = { backgroundColor: Array.from({ length: n }, (_, i) => (m.type === 'polarArea' ? alpha(pal[i % pal.length], 0.6) : pal[i % pal.length])), borderColor: chart.resolved.theme?.bg ?? 'var(--clarity-chart-bg, #fff)' }; continue; }
|
|
30
|
+
if (m.controller.colors === 'points') { const n = m.controller.count?.(m, chart) ?? (ds.data ?? []).length; m.auto = { backgroundColor: Array.from({ length: n }, (_, i) => pal[i % pal.length]), borderColor: chart.resolved.theme?.bg ?? 'var(--clarity-chart-bg, #fff)', palette: pal }; continue; }
|
|
31
|
+
const c = pal[k++ % pal.length];
|
|
32
|
+
m.auto = { borderColor: c, backgroundColor: m.type === 'bar' || m.controller.solid ? c : alpha(c, m.type === 'bubble' || m.type === 'radar' ? 0.35 : m.controller.alpha ?? 0.5), palette: pal, colorIndex: k - 1 };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const colors = { id: 'colors', defaults: { enabled: true, forceOverride: false } };
|
|
36
|
+
|
|
37
|
+
// ── title and subtitle ───────────────────────────────────────────────────────────
|
|
38
|
+
function titleBox(id, weight, defaultsOwn) {
|
|
39
|
+
return {
|
|
40
|
+
id, defaults: defaultsOwn,
|
|
41
|
+
beforeLayout(chart, _args, o) {
|
|
42
|
+
if (!o.display) return;
|
|
43
|
+
const lines = [o.text].flat().filter((t) => t != null && t !== '').map(String);
|
|
44
|
+
if (!lines.length) return;
|
|
45
|
+
const f = font(chart, o.font), pad = typeof o.padding === 'number' ? { top: o.padding, bottom: o.padding } : { top: 0, bottom: 0, ...(o.padding ?? {}) };
|
|
46
|
+
const vertical = o.position === 'left' || o.position === 'right';
|
|
47
|
+
chart.addBox({
|
|
48
|
+
id, weight: o.weight ?? weight, position: o.position ?? 'top',
|
|
49
|
+
size: () => lines.length * lineOf(f) + pad.top + pad.bottom,
|
|
50
|
+
draw(p, r) {
|
|
51
|
+
const x = o.align === 'start' ? r.left : o.align === 'end' ? r.right : (r.left + r.right) / 2;
|
|
52
|
+
lines.forEach((line, i) => {
|
|
53
|
+
if (vertical) { const cx = o.position === 'left' ? r.left + pad.top + lineOf(f) * (i + 0.8) : r.right - pad.top - lineOf(f) * (lines.length - i - 0.8); p.text(line, cx, (r.top + r.bottom) / 2, { fill: o.color ?? chart.resolved.color, font: f, align: 'center', rotate: o.position === 'left' ? -90 : 90 }); }
|
|
54
|
+
else p.text(line, x, r.top + pad.top + lineOf(f) * (i + 0.8), { fill: o.color ?? chart.resolved.theme?.ink ?? 'var(--clarity-chart-ink, #1b2430)', font: f, align: o.align === 'start' ? 'left' : o.align === 'end' ? 'right' : 'center' });
|
|
55
|
+
});
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const title = titleBox('title', 2000, { display: false, text: '', position: 'top', align: 'center', padding: 10, font: { weight: 'bold', size: 14 } });
|
|
62
|
+
const subtitle = titleBox('subtitle', 1500, { display: false, text: '', position: 'top', align: 'center', padding: { top: 0, bottom: 10 }, font: { size: 12 } });
|
|
63
|
+
|
|
64
|
+
// ── legend ────────────────────────────────────────────────────────────────────
|
|
65
|
+
/** The legend's items, as Chart.js makes them: a dataset each, or a data point each for pie, doughnut and polar area. */
|
|
66
|
+
export function generateLabels(chart) {
|
|
67
|
+
const m0 = chart.metas[0], round = chart.metas.length && perPoint(m0) && (ROUND.has(chart.type) || m0.type === chart.type);
|
|
68
|
+
if (round && m0.controller.legendItems) return m0.controller.legendItems(chart, m0);
|
|
69
|
+
if (round && !ROUND.has(m0.type)) { const labels = chart.data.labels ?? []; return (m0.parsed ?? []).map((p, i) => ({ text: String(p.name ?? labels[i] ?? i + 1), fillStyle: chart.fillOf(m0, i), strokeStyle: chart.strokeOf(m0, i), lineWidth: 0, hidden: !chart.getDataVisibility(i), index: i, pointStyle: 'circle' })); }
|
|
70
|
+
if (round) {
|
|
71
|
+
const m = chart.metas[0], labels = chart.data.labels ?? [];
|
|
72
|
+
return (m.dataset.data ?? []).map((_, i) => { const o = chart.arcOptions(m, i); return { text: String(labels[i] ?? i + 1), fillStyle: o.backgroundColor, strokeStyle: o.borderColor, lineWidth: o.borderWidth, hidden: !chart.getDataVisibility(i), index: i, pointStyle: 'circle' }; });
|
|
73
|
+
}
|
|
74
|
+
return chart.metas.filter((m) => m.controller.legend !== 'none').map((m) => {
|
|
75
|
+
const line = m.type === 'line' || m.type === 'radar' || m.type === 'scatter' || m.type === 'bubble';
|
|
76
|
+
const lo = line ? chart.lineOptions(m) : null, po = chart.pointOptions(m, 0), bo = m.type === 'bar' ? chart.barOptions(m, 0) : null;
|
|
77
|
+
const item = { text: m.label || `Dataset ${m.index + 1}`, fillStyle: bo?.backgroundColor ?? po.backgroundColor, strokeStyle: lo?.borderColor ?? bo?.borderColor ?? po.borderColor, lineWidth: line ? Math.min(3, lo.borderWidth) : bo?.borderWidth ?? 0, lineDash: lo?.borderDash, hidden: !chart.isDatasetVisible(m.index), datasetIndex: m.index, pointStyle: po.pointStyle };
|
|
78
|
+
return m.controller.legendItem ? Object.assign(item, m.controller.legendItem(chart, m)) : item;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
const legend = {
|
|
82
|
+
id: 'legend',
|
|
83
|
+
defaults: { display: true, position: 'top', align: 'center', fullSize: true, reverse: false, weight: 1000, onClick: null, onHover: null, onLeave: null, labels: { boxWidth: 40, boxHeight: undefined, padding: 10, usePointStyle: false, pointStyle: undefined, color: undefined, font: {}, filter: null, sort: null, generateLabels: null, textAlign: 'left' }, title: { display: false, text: '', padding: 10 } },
|
|
84
|
+
beforeLayout(chart, _args, o) {
|
|
85
|
+
const want = o.display && !(o.display === 'auto' && chart.metas.length < 2) && !(ROUND.has(chart.type) ? false : chart.metas.length === 0 || chart.metas.every((m) => m.controller.legend === 'none'));
|
|
86
|
+
chart.legend = { items: [], hits: [], options: o, get legendItems() { return this.items; }, chart };
|
|
87
|
+
if (!want) return;
|
|
88
|
+
let items = (o.labels.generateLabels ?? generateLabels)(chart);
|
|
89
|
+
if (o.labels.filter) items = items.filter((it, i) => o.labels.filter(it, { chart, ...chart.data }));
|
|
90
|
+
if (o.labels.sort) items.sort((a, b) => o.labels.sort(a, b, chart.data));
|
|
91
|
+
if (o.reverse) items.reverse();
|
|
92
|
+
chart.legend.items = items;
|
|
93
|
+
const f = font(chart, o.labels.font), lh = lineOf(f), boxW = o.labels.usePointStyle ? Math.min(f.size, o.labels.boxWidth) : o.labels.boxWidth, boxH = o.labels.usePointStyle ? f.size : o.labels.boxHeight ?? f.size, pad = o.labels.padding;
|
|
94
|
+
const itemW = (it) => boxW + f.size / 2 + chart.painter.measure(it.text, f);
|
|
95
|
+
const vertical = o.position === 'left' || o.position === 'right';
|
|
96
|
+
const titleH = o.title?.display ? lineOf(font(chart, o.title.font)) + (o.title.padding ?? 10) : 0;
|
|
97
|
+
let rows = [];
|
|
98
|
+
const layoutRows = (maxW) => {
|
|
99
|
+
rows = [[]]; let w = 0;
|
|
100
|
+
for (const it of items) { const iw = itemW(it) + pad; if (!vertical && w + iw > maxW && rows.at(-1).length) { rows.push([]); w = 0; } rows.at(-1).push(it); w += iw; if (vertical) { rows.push([]); w = 0; } }
|
|
101
|
+
rows = rows.filter((r) => r.length);
|
|
102
|
+
};
|
|
103
|
+
chart.addBox({
|
|
104
|
+
id: 'legend', weight: o.weight ?? 1000, position: o.position,
|
|
105
|
+
size(len, horizontal) {
|
|
106
|
+
if (horizontal) { layoutRows(len); return titleH + rows.length * (lh + pad) + pad / 2; }
|
|
107
|
+
layoutRows(Infinity); return Math.min(len * 0.4, Math.max(...items.map(itemW)) + pad * 2);
|
|
108
|
+
},
|
|
109
|
+
draw(p, r) {
|
|
110
|
+
chart.legend.hits = [];
|
|
111
|
+
let y = r.top + pad / 2 + titleH;
|
|
112
|
+
if (titleH) p.text(o.title.text, (r.left + r.right) / 2, r.top + lineOf(font(chart, o.title.font)), { fill: o.title.color ?? chart.resolved.color, font: font(chart, o.title.font), align: 'center' });
|
|
113
|
+
for (const row of rows) {
|
|
114
|
+
const width = row.reduce((s, it) => s + itemW(it) + pad, -pad);
|
|
115
|
+
let x = vertical ? r.left + pad : o.align === 'start' ? r.left : o.align === 'end' ? r.right - width : (r.left + r.right - width) / 2;
|
|
116
|
+
for (const it of row) {
|
|
117
|
+
const w = itemW(it), cy = y + lh / 2, colour = o.labels.color ?? chart.resolved.color, op = it.hidden ? 0.4 : 1;
|
|
118
|
+
if (o.labels.usePointStyle) { const d = pointShape(o.labels.pointStyle ?? it.pointStyle ?? 'circle', x + boxW / 2, cy, boxH / 2.2); p.path(d, { fill: it.fillStyle, stroke: it.strokeStyle, width: Math.max(1, Math.min(2, it.lineWidth ?? 1)), opacity: op }); }
|
|
119
|
+
else p.rect(x, cy - boxH / 2, boxW, boxH, { fill: it.fillStyle, stroke: it.lineWidth ? it.strokeStyle : null, width: it.lineWidth, dash: it.lineDash, opacity: op });
|
|
120
|
+
const t = p.text(it.text, x + boxW + f.size / 2, cy, { fill: colour, font: f, baseline: 'middle', opacity: op });
|
|
121
|
+
if (it.hidden && t?.setAttribute) t.setAttribute('text-decoration', 'line-through');
|
|
122
|
+
if (it.hidden && !t) p.line(x + boxW + f.size / 2, cy, x + w, cy, { stroke: colour, width: 1 });
|
|
123
|
+
chart.legend.hits.push({ left: x, top: y, right: x + w, bottom: y + lh, item: it });
|
|
124
|
+
x += w + pad;
|
|
125
|
+
}
|
|
126
|
+
y += lh + pad;
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
handle(event) {
|
|
130
|
+
const hit = chart.legend.hits.find((h) => event.x >= h.left && event.x <= h.right && event.y >= h.top && event.y <= h.bottom);
|
|
131
|
+
if (!hit) { if (chart._legendHover) { o.onLeave?.call(chart.legend, event, chart._legendHover, chart.legend); chart._legendHover = null; } return false; }
|
|
132
|
+
if (event.type === 'mousemove') { if (chart._legendHover !== hit.item) { chart._legendHover = hit.item; o.onHover?.call(chart.legend, event, hit.item, chart.legend); } return true; }
|
|
133
|
+
if (event.type !== 'click') return true;
|
|
134
|
+
if (o.onClick) o.onClick.call(chart.legend, event, hit.item, chart.legend);
|
|
135
|
+
else toggle(chart, hit.item);
|
|
136
|
+
return true;
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
},
|
|
140
|
+
afterDraw(chart) { syncLegendButtons(chart); },
|
|
141
|
+
};
|
|
142
|
+
function toggle(chart, item) {
|
|
143
|
+
if (item.datasetIndex != null) chart.setDatasetVisibility(item.datasetIndex, !chart.isDatasetVisible(item.datasetIndex));
|
|
144
|
+
else chart.toggleDataVisibility(item.index);
|
|
145
|
+
chart.update();
|
|
146
|
+
}
|
|
147
|
+
// the legend for the keyboard: a button per item, read by screen readers, seen when it has focus
|
|
148
|
+
function syncLegendButtons(chart) {
|
|
149
|
+
const box = chart._a11yEl;
|
|
150
|
+
if (!box || !chart.legend?.items?.length) return;
|
|
151
|
+
let wrap = box.querySelector?.('.clarity-chart-legend');
|
|
152
|
+
if (!wrap) { wrap = document.createElement('div'); wrap.className = 'clarity-chart-legend'; wrap.setAttribute('role', 'group'); wrap.setAttribute('aria-label', 'Legend'); box.prepend(wrap); }
|
|
153
|
+
const key = chart.legend.items.map((it) => it.text + it.hidden).join('|');
|
|
154
|
+
if (wrap.dataset.key === key) return;
|
|
155
|
+
wrap.dataset.key = key; wrap.replaceChildren();
|
|
156
|
+
for (const it of chart.legend.items) {
|
|
157
|
+
const b = document.createElement('button');
|
|
158
|
+
b.type = 'button'; b.textContent = it.text; b.setAttribute('aria-pressed', it.hidden ? 'false' : 'true');
|
|
159
|
+
b.addEventListener('click', () => toggle(chart, it));
|
|
160
|
+
wrap.appendChild(b);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ── tooltip ───────────────────────────────────────────────────────────────────
|
|
165
|
+
export function formattedValue(chart, meta, el) {
|
|
166
|
+
if (meta.controller.format) return meta.controller.format(chart, meta, el, (v) => formatNumber(v, { locale: chart.resolved.locale }));
|
|
167
|
+
const p = el.parsed, v = p?.value, ax = chart.scales[meta.vAxisID];
|
|
168
|
+
if (Number.isFinite(p?.low)) return `[${formatNumber(p.low, { locale: chart.resolved.locale })}, ${formatNumber(v, { locale: chart.resolved.locale })}]`;
|
|
169
|
+
if (meta.type === 'bubble') return `(${p.index}, ${v}, ${p.r})`;
|
|
170
|
+
if (meta.type === 'scatter') return `(${formatNumber(p.index, { locale: chart.resolved.locale })}, ${formatNumber(v, { locale: chart.resolved.locale })})`;
|
|
171
|
+
void ax;
|
|
172
|
+
return formatNumber(v, { locale: chart.resolved.locale });
|
|
173
|
+
}
|
|
174
|
+
function labelFor(chart, meta, el) {
|
|
175
|
+
if (meta.controller.label) return meta.controller.label(chart, meta, el);
|
|
176
|
+
const labels = chart.data.labels ?? [], ix = chart.scales[meta.iAxisID];
|
|
177
|
+
if (labels[el.index] != null) return String(labels[el.index]);
|
|
178
|
+
if (ix?.type?.startsWith('time')) return formatTime(el.parsed.index, ix.options.time?.tooltipFormat ?? 'MMM d, yyyy HH:mm');
|
|
179
|
+
return el.parsed?.index != null && meta.type !== 'scatter' && meta.type !== 'bubble' ? String(el.parsed.index) : '';
|
|
180
|
+
}
|
|
181
|
+
const tooltip = {
|
|
182
|
+
id: 'tooltip',
|
|
183
|
+
defaults: { enabled: true, external: null, position: 'average', backgroundColor: 'rgba(20, 32, 43, 0.92)', titleColor: '#fff', bodyColor: '#fff', footerColor: '#fff', displayColors: true, padding: 8, cornerRadius: 6, boxWidth: 10, boxHeight: 10, usePointStyle: false, callbacks: {}, filter: null, itemSort: null, titleFont: { weight: 'bold' }, bodyFont: {}, footerFont: { weight: 'bold' }, caretPadding: 8 },
|
|
184
|
+
afterInit(chart) {
|
|
185
|
+
if (!chart.container?.appendChild) return;
|
|
186
|
+
const el = document.createElement('div');
|
|
187
|
+
el.className = 'clarity-chart-tooltip'; el.setAttribute('role', 'status'); el.setAttribute('aria-live', 'polite');
|
|
188
|
+
Object.assign(el.style, { position: 'absolute', pointerEvents: 'none', display: 'none', zIndex: '3', whiteSpace: 'nowrap', transform: 'translate(-50%, calc(-100% - 8px))', transition: 'opacity .12s' });
|
|
189
|
+
chart.container.appendChild(el);
|
|
190
|
+
chart._tipEl = el;
|
|
191
|
+
chart.tooltip = {
|
|
192
|
+
getActiveElements: () => chart._tipActive ?? [],
|
|
193
|
+
setActiveElements: (list, at) => { chart._tipActive = (list ?? []).map((a) => ({ ...a, element: chart._elementAt(a.datasetIndex, a.index) })); chart._tipAt = at; show(chart); },
|
|
194
|
+
};
|
|
195
|
+
chart._tip = () => { chart._tipActive = chart.getActiveElements(); show(chart); };
|
|
196
|
+
},
|
|
197
|
+
tooltipEvent(chart, { event }, o) {
|
|
198
|
+
if (!o.enabled && !o.external) return;
|
|
199
|
+
const els = event.type === 'mouseout' ? [] : chart.getElementsAtEventForMode(event, o.mode, { intersect: o.intersect, axis: o.axis ?? chart.resolved.interaction.axis });
|
|
200
|
+
chart._tipActive = els; chart._tipAt = o.position === 'nearest' ? { x: event.x, y: event.y } : null;
|
|
201
|
+
show(chart);
|
|
202
|
+
},
|
|
203
|
+
afterUpdate(chart) { if (chart._tipActive?.length) { chart._tipActive = chart._tipActive.map((a) => ({ ...a, element: chart._elementAt(a.datasetIndex, a.index) })).filter((a) => a.element); show(chart); } },
|
|
204
|
+
};
|
|
205
|
+
function show(chart) {
|
|
206
|
+
const o = chart.resolved.plugins.tooltip, el = chart._tipEl;
|
|
207
|
+
if (!el) return;
|
|
208
|
+
let items = (chart._tipActive ?? []).filter((a) => a.element && !a.element.skip);
|
|
209
|
+
const cb = o.callbacks ?? {};
|
|
210
|
+
const dataPoints = items.map((a) => {
|
|
211
|
+
const meta = chart.metas[a.datasetIndex], e = a.element;
|
|
212
|
+
return { chart, dataset: meta.dataset, datasetIndex: a.datasetIndex, dataIndex: a.index, element: e, raw: e.raw, parsed: { x: e.parsed?.index, y: e.parsed?.value, r: e.parsed?.r }, label: labelFor(chart, meta, e), formattedValue: formattedValue(chart, meta, e) };
|
|
213
|
+
}).filter((d) => !o.filter || o.filter(d, 0, [], chart.data));
|
|
214
|
+
if (o.itemSort) dataPoints.sort((a, b) => o.itemSort(a, b, chart.data));
|
|
215
|
+
const model = { opacity: dataPoints.length ? 1 : 0, dataPoints, title: [], body: [], footer: [], labelColors: [], x: 0, y: 0 };
|
|
216
|
+
if (dataPoints.length) {
|
|
217
|
+
const arr = (v) => (v == null ? [] : [v].flat().map(String));
|
|
218
|
+
const round = perPoint(chart.metas[dataPoints[0].datasetIndex]);
|
|
219
|
+
model.title = [...arr(cb.beforeTitle?.(dataPoints)), ...(cb.title ? arr(cb.title(dataPoints)) : round ? [] : arr(dataPoints[0].label)), ...arr(cb.afterTitle?.(dataPoints))];
|
|
220
|
+
model.beforeBody = arr(cb.beforeBody?.(dataPoints));
|
|
221
|
+
for (const d of dataPoints) {
|
|
222
|
+
const meta = chart.metas[d.datasetIndex];
|
|
223
|
+
const def = round ? `${d.label}: ${d.formattedValue}` : `${d.dataset.label ? d.dataset.label + ': ' : ''}${d.formattedValue}`;
|
|
224
|
+
const own = !cb.label && meta.controller.lines ? meta.controller.lines(chart, meta, d.element, (v) => formatNumber(v, { locale: chart.resolved.locale })) : null;
|
|
225
|
+
model.body.push({ before: arr(cb.beforeLabel?.(d)), lines: cb.label ? arr(cb.label(d)) : own ? [meta.label, ...own].filter(Boolean) : [def], after: arr(cb.afterLabel?.(d)) });
|
|
226
|
+
const fill = meta.controller.swatch ? meta.controller.swatch(chart, meta, d.element) : ROUND.has(meta.type) ? chart.arcOptions(meta, d.dataIndex).backgroundColor : round ? chart.fillOf(meta, d.dataIndex) : meta.type === 'bar' ? chart.barOptions(meta, d.dataIndex).backgroundColor : chart.lineOptions(meta).borderColor;
|
|
227
|
+
model.labelColors.push(cb.labelColor?.(d) ?? { backgroundColor: fill, borderColor: fill });
|
|
228
|
+
}
|
|
229
|
+
model.afterBody = arr(cb.afterBody?.(dataPoints));
|
|
230
|
+
model.footer = [...arr(cb.beforeFooter?.(dataPoints)), ...arr(cb.footer?.(dataPoints)), ...arr(cb.afterFooter?.(dataPoints))];
|
|
231
|
+
const pts = dataPoints.map((d) => tipPoint(d.element));
|
|
232
|
+
const at = chart._tipAt ?? { x: pts.reduce((s, p) => s + p.x, 0) / pts.length, y: Math.min(...pts.map((p) => p.y)) };
|
|
233
|
+
model.x = at.x; model.y = at.y;
|
|
234
|
+
}
|
|
235
|
+
chart.tooltip.model = model;
|
|
236
|
+
if (o.external) { el.style.display = 'none'; o.external({ chart, tooltip: model }); return; }
|
|
237
|
+
if (!o.enabled || !model.opacity) { el.style.display = 'none'; return; }
|
|
238
|
+
el.replaceChildren();
|
|
239
|
+
Object.assign(el.style, { background: o.backgroundColor, color: o.bodyColor, padding: o.padding + 'px', borderRadius: o.cornerRadius + 'px', font: `12px/1.45 ${chart.resolved.font.family}` });
|
|
240
|
+
const line = (text, style) => { const d = document.createElement('div'); d.textContent = text; Object.assign(d.style, style); el.appendChild(d); return d; };
|
|
241
|
+
for (const t of model.title) line(t, { fontWeight: '600', color: o.titleColor });
|
|
242
|
+
for (const t of model.beforeBody ?? []) line(t, {});
|
|
243
|
+
model.body.forEach((b, k) => {
|
|
244
|
+
for (const t of b.before) line(t, {});
|
|
245
|
+
b.lines.forEach((t, j) => {
|
|
246
|
+
const row = line('', { display: 'flex', alignItems: 'center', gap: '6px' });
|
|
247
|
+
if (o.displayColors && j === 0) { const sw = document.createElement('i'); Object.assign(sw.style, { width: o.boxWidth + 'px', height: o.boxHeight + 'px', background: cssPaint(model.labelColors[k].backgroundColor), border: `1px solid ${cssPaint(model.labelColors[k].borderColor)}`, borderRadius: o.usePointStyle ? '50%' : '2px', display: 'inline-block', flex: 'none' }); row.appendChild(sw); }
|
|
248
|
+
row.appendChild(document.createTextNode(t));
|
|
249
|
+
});
|
|
250
|
+
for (const t of b.after) line(t, {});
|
|
251
|
+
});
|
|
252
|
+
for (const t of model.afterBody ?? []) line(t, {});
|
|
253
|
+
for (const t of model.footer) line(t, { fontWeight: '600', color: o.footerColor, marginTop: '4px' });
|
|
254
|
+
const w = chart.width;
|
|
255
|
+
el.style.left = Math.max(70, Math.min(w - 70, model.x)) + 'px'; el.style.top = Math.max(16, model.y) + 'px';
|
|
256
|
+
el.style.display = 'block';
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// ── filler: the area under a line, to its base, to another dataset, or to a value ────
|
|
260
|
+
const filler = {
|
|
261
|
+
id: 'filler',
|
|
262
|
+
defaults: { propagate: true, drawTime: 'beforeDatasetDraw' },
|
|
263
|
+
beforeDatasetsDraw(chart, _args, o) {
|
|
264
|
+
const metas = chart.getSortedVisibleDatasetMetas().filter((m) => m.type === 'line' || m.type === 'radar' || m.controller.filled);
|
|
265
|
+
for (const m of metas.slice().reverse()) {
|
|
266
|
+
const lo = chart.lineOptions(m), fill = lo.fill;
|
|
267
|
+
if (fill === false || fill == null) continue;
|
|
268
|
+
const els = (m.drawn ?? m.elements);
|
|
269
|
+
const spec = typeof fill === 'object' && fill !== null ? fill : { target: fill };
|
|
270
|
+
let target = spec.target === true ? 'origin' : spec.target;
|
|
271
|
+
const colour = spec.above ?? lo.backgroundColor, below = spec.below ?? colour;
|
|
272
|
+
const lower = boundary(chart, m, target, o.propagate);
|
|
273
|
+
if (!lower) continue;
|
|
274
|
+
chart.painter.layer('fill');
|
|
275
|
+
for (const run of runsOf(els, lo.spanGaps, (e) => e.parsed.index)) {
|
|
276
|
+
if (run.length < 1) continue;
|
|
277
|
+
const top = pathThrough(run, { ...lo, closed: m.type === 'radar' });
|
|
278
|
+
let d;
|
|
279
|
+
if (m.type === 'radar') d = lower.radar ? top + ' ' + lower.radar(run) : top;
|
|
280
|
+
else {
|
|
281
|
+
const back = lower.path(run);
|
|
282
|
+
d = top + back + 'Z';
|
|
283
|
+
}
|
|
284
|
+
const st = { fill: colour, clip: chart.clip };
|
|
285
|
+
if (below !== colour && lower.level != null) {
|
|
286
|
+
const a = chart.chartArea;
|
|
287
|
+
chart.painter.path(d, { fill: colour, clip: chart.painter.clipRect(a.left, a.top, a.right - a.left, Math.max(0, lower.level - a.top)) });
|
|
288
|
+
chart.painter.path(d, { fill: below, clip: chart.painter.clipRect(a.left, lower.level, a.right - a.left, Math.max(0, a.bottom - lower.level)) });
|
|
289
|
+
} else chart.painter.path(d, m.type === 'radar' ? { fill: colour, ...(lower.radar ? { } : {}) } : st);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
// what an area is filled down (or across) to
|
|
295
|
+
function boundary(chart, m, target, propagate) {
|
|
296
|
+
const horiz = m.indexAxis === 'y', vx = chart.scales[m.vAxisID], area = chart.chartArea;
|
|
297
|
+
const level = (px) => ({ level: px, path: (run) => { const a = run[0], b = run.at(-1); return horiz ? `L${px},${b.y}L${px},${a.y}` : `L${b.x},${px}L${a.x},${px}`; }, radar: null });
|
|
298
|
+
if (m.type === 'radar') {
|
|
299
|
+
const r = chart.scales.r;
|
|
300
|
+
if (target === 'origin' || target === 'start') return { radar: null };
|
|
301
|
+
const other = otherMeta(chart, m, target, propagate);
|
|
302
|
+
if (!other) return { radar: null };
|
|
303
|
+
const pts = (other.drawn ?? other.elements).filter((e) => !e.skip).slice().reverse();
|
|
304
|
+
return { radar: () => 'M' + pts.map((p) => `${p.x.toFixed(2)},${p.y.toFixed(2)}`).join('L') + 'Z', fillRule: 'evenodd', r };
|
|
305
|
+
}
|
|
306
|
+
if (target === 'origin') return level(vx.getBasePixel());
|
|
307
|
+
if (target === 'start') return level(horiz ? area.left : area.bottom);
|
|
308
|
+
if (target === 'end') return level(horiz ? area.right : area.top);
|
|
309
|
+
if (target && typeof target === 'object' && 'value' in target) return level(vx.getPixelForValue(target.value));
|
|
310
|
+
if (target === 'stack') {
|
|
311
|
+
if (!m.stack) return level(vx.getBasePixel());
|
|
312
|
+
// the line below, drawn with the same curve as the line above, so the two meet with no gap
|
|
313
|
+
const lo = chart.lineOptions(m);
|
|
314
|
+
return { level: null, path: (run) => pathThrough(run.slice().reverse().map((e) => { const s = m.stack[e.index], p = vx.getPixelForValue(s ? s[0] : 0); return horiz ? { x: p, y: e.y } : { x: e.x, y: p }; }), lo).replace(/^M/, 'L') };
|
|
315
|
+
}
|
|
316
|
+
const other = otherMeta(chart, m, target, propagate);
|
|
317
|
+
if (!other) return level(vx.getBasePixel());
|
|
318
|
+
const lo = chart.lineOptions(other);
|
|
319
|
+
return { level: null, path: (run) => { const idx = new Set(run.map((e) => e.index)); const pts = (other.drawn ?? other.elements).filter((e) => !e.skip && idx.has(e.index)).reverse(); return pts.length ? pathThrough(pts, lo).replace(/^M/, 'L') : ''; } };
|
|
320
|
+
}
|
|
321
|
+
function otherMeta(chart, m, target, propagate) {
|
|
322
|
+
let i = typeof target === 'number' ? target : typeof target === 'string' && /^[+-]\d+$/.test(target) ? m.index + Number(target) : NaN;
|
|
323
|
+
if (!Number.isInteger(i)) return null;
|
|
324
|
+
const seen = new Set();
|
|
325
|
+
while (chart.metas[i] && !chart.isDatasetVisible(i) && propagate && !seen.has(i)) { seen.add(i); const f = chart.lineOptions(chart.metas[i]).fill; const next = typeof f === 'number' ? f : typeof f === 'string' && /^[+-]\d+$/.test(f) ? i + Number(f) : NaN; if (!Number.isInteger(next)) return null; i = next; }
|
|
326
|
+
return chart.metas[i] && chart.isDatasetVisible(i) ? chart.metas[i] : null;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ── decimation: long lines cut down to what the picture can show ────────────────────
|
|
330
|
+
/** Largest-Triangle-Three-Buckets: `samples` points that keep the shape of a long line. */
|
|
331
|
+
export function lttb(points, samples) {
|
|
332
|
+
const n = points.length;
|
|
333
|
+
if (samples >= n || samples < 3) return points.slice();
|
|
334
|
+
const out = [points[0]], every = (n - 2) / (samples - 2);
|
|
335
|
+
let a = 0;
|
|
336
|
+
for (let i = 0; i < samples - 2; i++) {
|
|
337
|
+
const s = Math.floor((i + 1) * every) + 1, e = Math.min(n, Math.floor((i + 2) * every) + 1);
|
|
338
|
+
let ax = 0, ay = 0; for (let j = s; j < e; j++) { ax += points[j].index; ay += points[j].value; } ax /= Math.max(1, e - s); ay /= Math.max(1, e - s);
|
|
339
|
+
const rs = Math.floor(i * every) + 1, re = Math.floor((i + 1) * every) + 1, pa = points[a];
|
|
340
|
+
let best = -1, pick = rs;
|
|
341
|
+
for (let j = rs; j < re; j++) { const area = Math.abs((pa.index - ax) * (points[j].value - pa.value) - (pa.index - points[j].index) * (ay - pa.value)); if (area > best) { best = area; pick = j; } }
|
|
342
|
+
out.push(points[pick]); a = pick;
|
|
343
|
+
}
|
|
344
|
+
out.push(points[n - 1]);
|
|
345
|
+
return out;
|
|
346
|
+
}
|
|
347
|
+
/** For each pixel's column, the first, lowest, highest and last point: no peak is lost. */
|
|
348
|
+
export function minMax(points, width, x0, x1) {
|
|
349
|
+
const out = [], span = (x1 - x0) || 1;
|
|
350
|
+
let col = -1, f, lo, hi, last;
|
|
351
|
+
const flush = () => { if (!f) return; const s = new Set(); for (const q of [f, lo, hi, last].sort((a, b) => a.index - b.index)) if (!s.has(q)) { s.add(q); out.push(q); } };
|
|
352
|
+
for (const p of points) {
|
|
353
|
+
if (!Number.isFinite(p.value)) continue;
|
|
354
|
+
const c = Math.floor(((p.index - x0) / span) * width);
|
|
355
|
+
if (c !== col) { flush(); col = c; f = lo = hi = last = p; continue; }
|
|
356
|
+
if (p.value < lo.value) lo = p; if (p.value > hi.value) hi = p; last = p;
|
|
357
|
+
}
|
|
358
|
+
flush();
|
|
359
|
+
return out;
|
|
360
|
+
}
|
|
361
|
+
const decimation = {
|
|
362
|
+
id: 'decimation',
|
|
363
|
+
defaults: { enabled: false, algorithm: 'min-max', samples: undefined, threshold: undefined },
|
|
364
|
+
beforeDatasetsUpdate(chart, _args, o) {
|
|
365
|
+
if (!o.enabled) return;
|
|
366
|
+
const w = Math.max(1, Math.round(chart.chartArea.width));
|
|
367
|
+
for (const m of chart.metas) {
|
|
368
|
+
if (m.type !== 'line' || m.indexAxis !== 'x') continue;
|
|
369
|
+
const ix = chart.scales[m.iAxisID];
|
|
370
|
+
if (!ix || ix.type === 'category' || m.stack) continue;
|
|
371
|
+
const pts = m.parsed, limit = o.threshold ?? w * 4;
|
|
372
|
+
if (pts.length <= limit) continue;
|
|
373
|
+
const inView = pts.filter((p) => p.index >= ix.min && p.index <= ix.max);
|
|
374
|
+
m.decimated = o.algorithm === 'lttb' ? lttb(inView.filter((p) => Number.isFinite(p.value)), o.samples ?? w) : minMax(inView, w, ix.min, ix.max);
|
|
375
|
+
}
|
|
376
|
+
},
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
export const BUILT_IN_PLUGINS = [colors, decimation, filler, title, subtitle, legend, tooltip];
|
|
380
|
+
export { title as Title, subtitle as SubTitle, legend as Legend, tooltip as Tooltip, filler as Filler, decimation as Decimation, colors as Colors };
|
|
381
|
+
void TIME_FORMATS;
|