@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/fills.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// @clarity-js/charts — fills that are more than a colour: gradients and patterns, given wherever a
|
|
2
|
+
// colour is (backgroundColor, borderColor, a slice, a cell). Written the native way, Highcharts's
|
|
3
|
+
// way or as a pattern's name:
|
|
4
|
+
//
|
|
5
|
+
// { type: 'linear', angle: 90, stops: [[0, '#3d7dd8'], [1, 'rgba(61,125,216,0)']] } // top to bottom
|
|
6
|
+
// { colors: ['#3d7dd8', '#2a9d8f'] } // left to right
|
|
7
|
+
// { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [[0, '#fff'], [1, '#000']] } // Highcharts
|
|
8
|
+
// { radialGradient: { cx: 0.5, cy: 0.5, r: 0.5 }, stops: [...] }
|
|
9
|
+
// { pattern: 'diagonal' | 'dots' | 'cross' | 'horizontal' | 'vertical' | 'grid', color, background, size }
|
|
10
|
+
// { pattern: { path: 'M 0 0 L 10 10', color, width: 10, height: 10, backgroundColor } } // Highcharts
|
|
11
|
+
//
|
|
12
|
+
// The box a gradient spans is the mark's own (objectBoundingBox): one spec fits every bar.
|
|
13
|
+
|
|
14
|
+
export const isPaint = (v) => !!v && typeof v === 'object' && !Array.isArray(v) && !!(v.stops || v.colors || v.linearGradient || v.radialGradient || v.pattern);
|
|
15
|
+
|
|
16
|
+
/** A paint spec in one shape: { kind: 'linear' | 'radial' | 'pattern', x1, y1, x2, y2 | cx, cy, r, stops: [[offset, colour]], … } */
|
|
17
|
+
export function normalizePaint(v) {
|
|
18
|
+
if (v.pattern) {
|
|
19
|
+
const p = typeof v.pattern === 'string' ? { name: v.pattern } : v.pattern;
|
|
20
|
+
return { kind: 'pattern', name: p.name ?? (p.path ? null : 'diagonal'), path: typeof p.path === 'string' ? p.path : p.path?.d ?? null, color: p.color ?? v.color ?? '#3d7dd8', background: p.backgroundColor ?? p.background ?? v.background ?? 'transparent', size: p.size ?? v.size ?? p.width ?? 8, width: p.width ?? p.size ?? v.size ?? 8, height: p.height ?? p.size ?? v.size ?? 8, lineWidth: p.lineWidth ?? v.lineWidth ?? (p.path?.strokeWidth ?? 1.5) };
|
|
21
|
+
}
|
|
22
|
+
const stops = (v.stops ?? (v.colors ?? []).map((c, i, a) => [a.length > 1 ? i / (a.length - 1) : 0, c])).map((s) => (Array.isArray(s) ? [Number(s[0]), s[1]] : [Number(s.offset ?? 0), s.color]));
|
|
23
|
+
if (v.radialGradient || v.type === 'radial') {
|
|
24
|
+
const r = v.radialGradient ?? v;
|
|
25
|
+
return { kind: 'radial', cx: r.cx ?? 0.5, cy: r.cy ?? 0.5, r: r.r ?? 0.5, stops };
|
|
26
|
+
}
|
|
27
|
+
let g = v.linearGradient;
|
|
28
|
+
if (Array.isArray(g)) g = { x1: g[0], y1: g[1], x2: g[2], y2: g[3] };
|
|
29
|
+
if (!g) {
|
|
30
|
+
// an angle in degrees: 0 left → right, 90 top → bottom (as CSS's 90deg turned to read top-down)
|
|
31
|
+
const dir = { left: 0, right: 180, top: 90, bottom: 270, vertical: 90, horizontal: 0 }[v.from ?? v.direction];
|
|
32
|
+
const a = ((v.angle ?? dir ?? 0) * Math.PI) / 180, c = Math.cos(a) / 2, s = Math.sin(a) / 2;
|
|
33
|
+
g = { x1: 0.5 - c, y1: 0.5 - s, x2: 0.5 + c, y2: 0.5 + s };
|
|
34
|
+
}
|
|
35
|
+
return { kind: 'linear', x1: g.x1 ?? 0, y1: g.y1 ?? 0, x2: g.x2 ?? 1, y2: g.y2 ?? 0, stops };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const PATTERNS = {
|
|
39
|
+
diagonal: (s) => `M0,${s}L${s},0M${-s / 4},${s / 4}L${s / 4},${-s / 4}M${s - s / 4},${s + s / 4}L${s + s / 4},${s - s / 4}`,
|
|
40
|
+
diagonalBack: (s) => `M0,0L${s},${s}M${-s / 4},${s - s / 4}L${s / 4},${s + s / 4}M${s - s / 4},${-s / 4}L${s + s / 4},${s / 4}`,
|
|
41
|
+
horizontal: (s) => `M0,${s / 2}H${s}`,
|
|
42
|
+
vertical: (s) => `M${s / 2},0V${s}`,
|
|
43
|
+
cross: (s) => `M0,${s / 2}H${s}M${s / 2},0V${s}`,
|
|
44
|
+
grid: (s) => `M0,0H${s}M0,0V${s}`,
|
|
45
|
+
zigzag: (s) => `M0,${s * 0.75}L${s / 2},${s / 4}L${s},${s * 0.75}`,
|
|
46
|
+
};
|
|
47
|
+
/** The tile of a pattern: its path, and whether the path is filled (dots) or stroked (lines). */
|
|
48
|
+
export function patternTile(p) {
|
|
49
|
+
const s = p.size;
|
|
50
|
+
if (p.path) return { d: p.path, stroke: true, w: p.width, h: p.height };
|
|
51
|
+
if (p.name === 'dots') return { d: `M${s / 2 - s / 6},${s / 2}a${s / 6},${s / 6} 0 1,0 ${s / 3},0a${s / 6},${s / 6} 0 1,0 ${-s / 3},0Z`, stroke: false, w: s, h: s };
|
|
52
|
+
return { d: (PATTERNS[p.name] ?? PATTERNS.diagonal)(s), stroke: true, w: s, h: s };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A paint as CSS (a tooltip's swatch, an HTML legend): a gradient as linear-gradient(), a pattern as its colour. */
|
|
56
|
+
export function cssPaint(v) {
|
|
57
|
+
if (!isPaint(v)) return v;
|
|
58
|
+
const p = normalizePaint(v);
|
|
59
|
+
if (p.kind === 'pattern') return p.color;
|
|
60
|
+
const stops = p.stops.map(([o, c]) => `${c} ${Math.round(o * 100)}%`).join(', ');
|
|
61
|
+
if (p.kind === 'radial') return `radial-gradient(circle at ${p.cx * 100}% ${p.cy * 100}%, ${stops})`;
|
|
62
|
+
const deg = Math.round((Math.atan2(p.x2 - p.x1, -(p.y2 - p.y1)) * 180) / Math.PI);
|
|
63
|
+
return `linear-gradient(${deg}deg, ${stops})`;
|
|
64
|
+
}
|
|
65
|
+
/** One colour that stands for a paint (to choose a label's contrast, or for a legend that wants one). */
|
|
66
|
+
export const solidOf = (v) => (!isPaint(v) ? v : (() => { const p = normalizePaint(v); return p.kind === 'pattern' ? p.color : p.stops[Math.floor(p.stops.length / 2)]?.[1] ?? p.stops[0]?.[1]; })());
|
|
67
|
+
|
|
68
|
+
/** A paint as a small tree of SVG elements ({ tag, attrs, children }): a gradient or a pattern with this id. */
|
|
69
|
+
export function paintTree(v, id) {
|
|
70
|
+
const p = normalizePaint(v);
|
|
71
|
+
const stops = (p.stops ?? []).map(([o, c]) => ({ tag: 'stop', attrs: { offset: o, 'stop-color': c } }));
|
|
72
|
+
if (p.kind === 'linear') return { tag: 'linearGradient', attrs: { id, x1: p.x1, y1: p.y1, x2: p.x2, y2: p.y2 }, children: stops };
|
|
73
|
+
if (p.kind === 'radial') return { tag: 'radialGradient', attrs: { id, cx: p.cx, cy: p.cy, r: p.r }, children: stops };
|
|
74
|
+
const t = patternTile(p), kids = [];
|
|
75
|
+
if (p.background && p.background !== 'transparent') kids.push({ tag: 'rect', attrs: { width: t.w, height: t.h, fill: p.background } });
|
|
76
|
+
kids.push({ tag: 'path', attrs: t.stroke ? { d: t.d, fill: 'none', stroke: p.color, 'stroke-width': p.lineWidth } : { d: t.d, fill: p.color } });
|
|
77
|
+
return { tag: 'pattern', attrs: { id, patternUnits: 'userSpaceOnUse', width: t.w, height: t.h }, children: kids };
|
|
78
|
+
}
|
|
79
|
+
const escAttr = (v) => String(v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
80
|
+
/** A tree of paintTree() as markup. */
|
|
81
|
+
export const treeMarkup = (n) => `<${n.tag}${Object.entries(n.attrs).map(([k, v]) => ` ${k}="${escAttr(v)}"`).join('')}>${(n.children ?? []).map(treeMarkup).join('')}</${n.tag}>`;
|
|
82
|
+
|
|
83
|
+
/** Paints for an SVG: each spec becomes one element in <defs>, made once per drawing. */
|
|
84
|
+
export function svgPaints(addDef) {
|
|
85
|
+
const made = new Map(); let n = 0;
|
|
86
|
+
return {
|
|
87
|
+
url(v) {
|
|
88
|
+
if (!isPaint(v)) return v;
|
|
89
|
+
const k = JSON.stringify(v);
|
|
90
|
+
if (!made.has(k)) { const id = `cg${++n}-${Math.random().toString(36).slice(2, 6)}`; addDef(paintTree(v, id)); made.set(k, `url(#${id})`); }
|
|
91
|
+
return made.get(k);
|
|
92
|
+
},
|
|
93
|
+
clear() { made.clear(); },
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The box a path covers (absolute and relative commands): what a canvas gradient spans. */
|
|
98
|
+
export function pathBox(d) {
|
|
99
|
+
let x = 0, y = 0, sx = 0, sy = 0, l = Infinity, t = Infinity, r = -Infinity, b = -Infinity;
|
|
100
|
+
const add = (px, py) => { if (px < l) l = px; if (px > r) r = px; if (py < t) t = py; if (py > b) b = py; };
|
|
101
|
+
const re = /([MLHVCSQTAZmlhvcsqtaz])([^MLHVCSQTAZmlhvcsqtaz]*)/g;
|
|
102
|
+
let m;
|
|
103
|
+
while ((m = re.exec(d))) {
|
|
104
|
+
const c = m[1], v = (m[2].match(/-?\d*\.?\d+(?:e-?\d+)?/gi) ?? []).map(Number), rel = c === c.toLowerCase(), C = c.toUpperCase();
|
|
105
|
+
const step = { M: 2, L: 2, T: 2, H: 1, V: 1, C: 6, S: 4, Q: 4, A: 7, Z: 0 }[C];
|
|
106
|
+
if (!step) { x = sx; y = sy; continue; }
|
|
107
|
+
for (let i = 0; i + step <= v.length; i += step) {
|
|
108
|
+
const q = v.slice(i, i + step);
|
|
109
|
+
if (C === 'H') { x = rel ? x + q[0] : q[0]; add(x, y); continue; }
|
|
110
|
+
if (C === 'V') { y = rel ? y + q[0] : q[0]; add(x, y); continue; }
|
|
111
|
+
if (C === 'A') { const nx = rel ? x + q[5] : q[5], ny = rel ? y + q[6] : q[6], mx = (x + nx) / 2, my = (y + ny) / 2; add(x, y); add(nx, ny); add(mx - q[0], my - q[1]); add(mx + q[0], my + q[1]); x = nx; y = ny; continue; }
|
|
112
|
+
for (let k = 0; k < step; k += 2) add(rel ? x + q[k] : q[k], rel ? y + q[k + 1] : q[k + 1]);
|
|
113
|
+
x = rel ? x + q[step - 2] : q[step - 2]; y = rel ? y + q[step - 1] : q[step - 1];
|
|
114
|
+
if (C === 'M' && i === 0) { sx = x; sy = y; }
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return Number.isFinite(l) ? { x: l, y: t, w: r - l, h: b - t } : { x: 0, y: 0, w: 1, h: 1 };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** A paint as a canvas fill style, over the box of what it fills. */
|
|
121
|
+
export function canvasPaint(ctx, v, box, colour = (c) => c) {
|
|
122
|
+
const p = normalizePaint(v);
|
|
123
|
+
if (p.kind === 'pattern') {
|
|
124
|
+
const t = patternTile(p), doc = globalThis.document;
|
|
125
|
+
const tile = typeof OffscreenCanvas === 'function' ? new OffscreenCanvas(t.w, t.h) : doc?.createElement('canvas');
|
|
126
|
+
if (!tile) return colour(p.color);
|
|
127
|
+
tile.width = t.w; tile.height = t.h;
|
|
128
|
+
const g = tile.getContext('2d');
|
|
129
|
+
if (p.background && p.background !== 'transparent') { g.fillStyle = colour(p.background); g.fillRect(0, 0, t.w, t.h); }
|
|
130
|
+
const path = new Path2D(t.d);
|
|
131
|
+
if (t.stroke) { g.strokeStyle = colour(p.color); g.lineWidth = p.lineWidth; g.stroke(path); } else { g.fillStyle = colour(p.color); g.fill(path); }
|
|
132
|
+
return ctx.createPattern(tile, 'repeat') ?? colour(p.color);
|
|
133
|
+
}
|
|
134
|
+
const w = Math.max(1, box.w), h = Math.max(1, box.h);
|
|
135
|
+
const grad = p.kind === 'radial'
|
|
136
|
+
? ctx.createRadialGradient(box.x + p.cx * w, box.y + p.cy * h, 0, box.x + p.cx * w, box.y + p.cy * h, p.r * Math.max(w, h))
|
|
137
|
+
: ctx.createLinearGradient(box.x + p.x1 * w, box.y + p.y1 * h, box.x + p.x2 * w, box.y + p.y2 * h);
|
|
138
|
+
for (const [o, c] of p.stops) grad.addColorStop(Math.min(1, Math.max(0, o)), colour(c));
|
|
139
|
+
return grad;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ── colours as numbers: to mix them (a colour axis) and to choose a label's contrast ──────────
|
|
143
|
+
/** A CSS colour (#rgb, #rrggbb, #rrggbbaa, rgb(), rgba(), hsl()) → [r, g, b, a], or null. */
|
|
144
|
+
export function parseColor(c) {
|
|
145
|
+
if (typeof c !== 'string') return null;
|
|
146
|
+
const s = c.trim();
|
|
147
|
+
let m = /^#([0-9a-f]{3,8})$/i.exec(s);
|
|
148
|
+
if (m) {
|
|
149
|
+
let h = m[1];
|
|
150
|
+
if (h.length <= 4) h = [...h].map((x) => x + x).join('');
|
|
151
|
+
const n = parseInt(h.slice(0, 6), 16);
|
|
152
|
+
return [n >> 16, (n >> 8) & 255, n & 255, h.length === 8 ? parseInt(h.slice(6), 16) / 255 : 1];
|
|
153
|
+
}
|
|
154
|
+
m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/i.exec(s);
|
|
155
|
+
if (m) return [+m[1], +m[2], +m[3], m[4] == null ? 1 : m[4].endsWith('%') ? parseFloat(m[4]) / 100 : +m[4]];
|
|
156
|
+
m = /^hsla?\(\s*([\d.]+)(?:deg)?[\s,]+([\d.]+)%[\s,]+([\d.]+)%(?:[\s,/]+([\d.]+%?))?\s*\)$/i.exec(s);
|
|
157
|
+
if (m) {
|
|
158
|
+
const h = +m[1] / 360, sat = +m[2] / 100, l = +m[3] / 100;
|
|
159
|
+
const q = l < 0.5 ? l * (1 + sat) : l + sat - l * sat, p = 2 * l - q;
|
|
160
|
+
const f = (t) => { t = (t + 1) % 1; return Math.round(255 * (t < 1 / 6 ? p + (q - p) * 6 * t : t < 0.5 ? q : t < 2 / 3 ? p + (q - p) * (2 / 3 - t) * 6 : p)); };
|
|
161
|
+
return [f(h + 1 / 3), f(h), f(h - 1 / 3), m[4] == null ? 1 : m[4].endsWith('%') ? parseFloat(m[4]) / 100 : +m[4]];
|
|
162
|
+
}
|
|
163
|
+
m = /^var\(\s*--[\w-]+\s*,\s*(.+)\)$/.exec(s);
|
|
164
|
+
if (m) return parseColor(m[1]);
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
export const toCss = ([r, g, b, a = 1]) => (a >= 1 ? `#${[r, g, b].map((v) => Math.round(Math.max(0, Math.min(255, v))).toString(16).padStart(2, '0')).join('')}` : `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${+a.toFixed(3)})`);
|
|
168
|
+
/** Two colours mixed: t = 0 the first, 1 the second. */
|
|
169
|
+
export function mix(a, b, t) {
|
|
170
|
+
const p = parseColor(a), q = parseColor(b);
|
|
171
|
+
if (!p || !q) return t < 0.5 ? a : b;
|
|
172
|
+
return toCss(p.map((v, i) => v + (q[i] - v) * t));
|
|
173
|
+
}
|
|
174
|
+
/** A colour with its opacity changed. */
|
|
175
|
+
export function withAlpha(c, a) { const p = parseColor(c); return p ? toCss([p[0], p[1], p[2], a]) : c; }
|
|
176
|
+
/** A colour lighter (k > 0, towards white) or darker (k < 0, towards black). */
|
|
177
|
+
export function shade(c, k) { return k >= 0 ? mix(c, '#ffffff', k) : mix(c, '#000000', -k); }
|
|
178
|
+
/** How light a colour looks (0 black … 1 white), as WCAG reads it. */
|
|
179
|
+
export function luminance(c) {
|
|
180
|
+
const p = parseColor(solidOf(c));
|
|
181
|
+
if (!p) return 1;
|
|
182
|
+
const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
|
|
183
|
+
const L = 0.2126 * f(p[0]) + 0.7152 * f(p[1]) + 0.0722 * f(p[2]);
|
|
184
|
+
return p[3] < 1 ? L * p[3] + (1 - p[3]) : L;
|
|
185
|
+
}
|
|
186
|
+
/** The text colour to read on a fill: near black on light, white on dark. */
|
|
187
|
+
export const contrastOn = (fill) => (luminance(fill) > 0.42 ? '#1b2430' : '#ffffff');
|
package/src/format.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// @clarity-js/charts — how numbers and dates are written on axes and in tooltips.
|
|
2
|
+
|
|
3
|
+
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A number for people to read: 1234 → "1,234", with compact: 1.2k, 3.4M; decimals as asked, or
|
|
7
|
+
* as many as the step between ticks needs. locale: any the browser knows ('tr-TR' → "1.234").
|
|
8
|
+
*/
|
|
9
|
+
export function formatNumber(v, { compact = false, decimals, step, locale = 'en-US', prefix = '', suffix = '' } = {}) {
|
|
10
|
+
if (!Number.isFinite(v)) return '';
|
|
11
|
+
const d = decimals ?? (step ? Math.max(0, Math.min(6, -Math.floor(Math.log10(Math.abs(step)) + 1e-9))) : Math.abs(v) >= 100 ? 0 : 2);
|
|
12
|
+
let text;
|
|
13
|
+
if (compact && Math.abs(v) >= 1000) {
|
|
14
|
+
const units = [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'k']], [k, u] = units.find(([k]) => Math.abs(v) >= k);
|
|
15
|
+
const n = v / k;
|
|
16
|
+
text = new Intl.NumberFormat(locale, { maximumFractionDigits: Math.abs(n) >= 100 ? 0 : 1 }).format(n) + u;
|
|
17
|
+
} else text = new Intl.NumberFormat(locale, { minimumFractionDigits: decimals ?? 0, maximumFractionDigits: d }).format(v);
|
|
18
|
+
return prefix + text + suffix;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
22
|
+
/** A time (ms) written for a tick of the given unit ('s', 'm', 'h', 'd', 'w', 'mo', 'y'), in UTC. */
|
|
23
|
+
export function formatDate(ms, unit = 'd') {
|
|
24
|
+
const t = new Date(ms);
|
|
25
|
+
if (!Number.isFinite(t.getTime())) return '';
|
|
26
|
+
const y = t.getUTCFullYear(), mo = MONTHS[t.getUTCMonth()], d = t.getUTCDate();
|
|
27
|
+
switch (unit) {
|
|
28
|
+
case 'y': return String(y);
|
|
29
|
+
case 'mo': return t.getUTCMonth() === 0 ? `${mo} ${y}` : mo;
|
|
30
|
+
case 'w': case 'd': return `${mo} ${d}`;
|
|
31
|
+
case 'h': return t.getUTCHours() === 0 ? `${mo} ${d}` : `${pad(t.getUTCHours())}:00`;
|
|
32
|
+
case 'm': return `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}`;
|
|
33
|
+
default: return `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** A time written in full, for a tooltip: "Mar 4, 2026" or "Mar 4, 2026 14:05". */
|
|
37
|
+
export function formatFull(ms) {
|
|
38
|
+
const t = new Date(ms);
|
|
39
|
+
if (!Number.isFinite(t.getTime())) return '';
|
|
40
|
+
const day = `${MONTHS[t.getUTCMonth()]} ${t.getUTCDate()}, ${t.getUTCFullYear()}`;
|
|
41
|
+
return t.getUTCHours() || t.getUTCMinutes() ? `${day} ${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}` : day;
|
|
42
|
+
}
|
package/src/full.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// @clarity-js/charts — the whole package: Chart.js's eight types and plugins (core.js) and what Highcharts and
|
|
2
|
+
// ApexCharts have beyond them, registered for every chart. '@clarity-js/charts' loads this; '@clarity-js/charts/lite'
|
|
3
|
+
// does not, and is a third of the size.
|
|
4
|
+
|
|
5
|
+
import { Chart } from './core.js';
|
|
6
|
+
import { MORE_TYPES } from './types.js';
|
|
7
|
+
import { MAP_TYPES } from './maps.js';
|
|
8
|
+
import { DEPTH_TYPES, rotate3d } from './depth.js';
|
|
9
|
+
import { GRAPH_TYPES, nodeDrag } from './graphs.js';
|
|
10
|
+
import { MORE_PLUGINS, sonify, toCSV, viewToken, applyViewToken, zoomBy, panBy, drillDown, drillUp } from './features.js';
|
|
11
|
+
|
|
12
|
+
let done = false;
|
|
13
|
+
/** Register the types, the plugins and the functions behind zoom, drilldown, CSV, saved views and sound. */
|
|
14
|
+
export function installMore() {
|
|
15
|
+
if (done) return Chart;
|
|
16
|
+
done = true;
|
|
17
|
+
const r = Chart.registry;
|
|
18
|
+
for (const [id, controller] of Object.entries({ ...MORE_TYPES, ...MAP_TYPES, ...DEPTH_TYPES, ...GRAPH_TYPES })) if (!r.controllers[id]) r.controllers[id] = controller;
|
|
19
|
+
for (const p of [...MORE_PLUGINS, rotate3d, nodeDrag]) if (!r.plugins.some((q) => q.id === p.id)) r.plugins.push(p);
|
|
20
|
+
Object.assign(r.extras, { sonify, toCSV, viewToken, applyViewToken, zoomBy, panBy, drillDown, drillUp });
|
|
21
|
+
return Chart;
|
|
22
|
+
}
|
|
23
|
+
installMore();
|
package/src/graphs.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
// @clarity-js/charts — graphs and sets, as Highcharts has them: a network of nodes and links laid out
|
|
2
|
+
// by forces (networkgraph, a node can be dragged), an organization chart and a tree graph, a Venn
|
|
3
|
+
// diagram of up to a handful of sets, and parallel coordinates (a line through an axis for each
|
|
4
|
+
// dimension). Each is a controller with the hooks the others have.
|
|
5
|
+
|
|
6
|
+
import { formatNumber } from './format.js';
|
|
7
|
+
import { shade, withAlpha, contrastOn, mix } from './fills.js';
|
|
8
|
+
import { niceStep } from './scale.js';
|
|
9
|
+
import { PALETTE } from './plugins.js';
|
|
10
|
+
import { num } from './controllers.js';
|
|
11
|
+
|
|
12
|
+
const themeOf = (chart) => chart.resolved.theme ?? {};
|
|
13
|
+
const fontOf = (chart, own) => ({ ...chart.resolved.font, ...(own ?? {}) });
|
|
14
|
+
const paletteOf = (chart, meta) => meta?.auto?.palette ?? chart.resolved.plugins?.colors?.palette ?? PALETTE;
|
|
15
|
+
const r1 = (v) => Math.round(v * 10) / 10;
|
|
16
|
+
const clip = (painter, text, w, f) => { const s = String(text ?? ''); if (painter.measure(s, f) <= w) return s; let k = s.length; while (k > 1 && painter.measure(s.slice(0, k) + '…', f) > w) k--; return k > 1 ? s.slice(0, k) + '…' : ''; };
|
|
17
|
+
const segDist = (x, y, x1, y1, x2, y2) => { const dx = x2 - x1, dy = y2 - y1, l = dx * dx + dy * dy || 1, t = Math.max(0, Math.min(1, ((x - x1) * dx + (y - y1) * dy) / l)); return Math.hypot(x - x1 - t * dx, y - y1 - t * dy); };
|
|
18
|
+
|
|
19
|
+
// links [from, to] or { from, to, weight }; nodes [{ id, name, color, radius }] optional
|
|
20
|
+
function graphOf(meta) {
|
|
21
|
+
const ds = meta.dataset, idx = new Map(), nodes = [];
|
|
22
|
+
const node = (id, extra = {}) => { const k = String(id); if (!idx.has(k)) { idx.set(k, nodes.length); nodes.push({ id: k, name: k, links: 0, ...extra }); } else Object.assign(nodes[idx.get(k)], extra); return idx.get(k); };
|
|
23
|
+
for (const n of ds.nodes ?? []) node(n.id ?? n.name, { ...n, id: String(n.id ?? n.name), name: String(n.name ?? n.id) });
|
|
24
|
+
const links = (ds.data ?? []).map((raw, i) => { const o = Array.isArray(raw) ? { from: raw[0], to: raw[1], weight: raw[2] } : raw ?? {}; const s = node(o.from), t = node(o.to); nodes[s].links++; nodes[t].links++; return { s, t, weight: num(o.weight ?? o.value ?? 1) || 1, raw, i }; });
|
|
25
|
+
return { nodes, links, idx };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ── a network laid out by forces (Fruchterman and Reingold), the same picture every time ─────────────
|
|
29
|
+
export function forceLayout(n, links, { w = 1, h = 1, iterations = 300, fixed = new Map() } = {}) {
|
|
30
|
+
const k = Math.sqrt((w * h) / Math.max(1, n)) * 0.75, pos = Array.from({ length: n }, (_, i) => { const a = (i / Math.max(1, n)) * Math.PI * 2 * 1.618, r = 0.35 * Math.min(w, h) * Math.sqrt((i + 0.5) / n); return { x: w / 2 + Math.cos(a) * r, y: h / 2 + Math.sin(a) * r }; });
|
|
31
|
+
for (const [i, p] of fixed) if (pos[i]) pos[i] = { ...p };
|
|
32
|
+
let temp = Math.min(w, h) / 8;
|
|
33
|
+
for (let it = 0; it < iterations; it++) {
|
|
34
|
+
const disp = pos.map(() => ({ x: 0, y: 0 }));
|
|
35
|
+
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) {
|
|
36
|
+
let dx = pos[i].x - pos[j].x, dy = pos[i].y - pos[j].y, d = Math.hypot(dx, dy);
|
|
37
|
+
if (d < 0.01) { dx = 0.01 * ((i * 7 + j) % 3 - 1 || 1); dy = 0.01; d = 0.015; }
|
|
38
|
+
const f = (k * k) / d; disp[i].x += (dx / d) * f; disp[i].y += (dy / d) * f; disp[j].x -= (dx / d) * f; disp[j].y -= (dy / d) * f;
|
|
39
|
+
}
|
|
40
|
+
for (const l of links) { const a = pos[l.s], b = pos[l.t]; const dx = a.x - b.x, dy = a.y - b.y, d = Math.hypot(dx, dy) || 0.01, f = ((d * d) / k) * Math.min(3, l.weight ?? 1) ** 0.3; disp[l.s].x -= (dx / d) * f; disp[l.s].y -= (dy / d) * f; disp[l.t].x += (dx / d) * f; disp[l.t].y += (dy / d) * f; }
|
|
41
|
+
for (let i = 0; i < n; i++) {
|
|
42
|
+
if (fixed.has(i)) continue;
|
|
43
|
+
// a pull to the middle keeps parts that are not linked from drifting off
|
|
44
|
+
disp[i].x += (w / 2 - pos[i].x) * 0.02 * k; disp[i].y += (h / 2 - pos[i].y) * 0.02 * k;
|
|
45
|
+
const d = Math.hypot(disp[i].x, disp[i].y) || 1, step = Math.min(d, temp);
|
|
46
|
+
pos[i].x = Math.max(0, Math.min(w, pos[i].x + (disp[i].x / d) * step)); pos[i].y = Math.max(0, Math.min(h, pos[i].y + (disp[i].y / d) * step));
|
|
47
|
+
}
|
|
48
|
+
temp *= 0.985;
|
|
49
|
+
}
|
|
50
|
+
return pos;
|
|
51
|
+
}
|
|
52
|
+
const network = {
|
|
53
|
+
element: 'node', name: 'Network graph', axes: 'none', legend: 'none', colors: 'none',
|
|
54
|
+
defaults: { aspectRatio: 1.5, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
55
|
+
parse(chart, meta) { const g = graphOf(meta); meta.graph = g; return g.links.map((l) => ({ index: l.i, value: l.weight, name: `${g.nodes[l.s].name} — ${g.nodes[l.t].name}`, raw: l.raw, i: l.i })); },
|
|
56
|
+
limits: () => [Infinity, -Infinity],
|
|
57
|
+
update(chart, meta) {
|
|
58
|
+
const a = chart.chartArea, g = meta.graph, pad = 24, top = pad + 10, W = a.right - a.left - pad * 2, H = a.bottom - a.top - pad - top, key = `${W}|${H}|${g.nodes.length}|${g.links.length}`;
|
|
59
|
+
// the layout and the dragged nodes outlive an update (metas are made again on each)
|
|
60
|
+
let st = NET.get(meta.dataset); if (!st) NET.set(meta.dataset, (st = { dragged: new Map() }));
|
|
61
|
+
meta.dragged = st.dragged;
|
|
62
|
+
if (st.key !== key || !st.layout) { st.layout = forceLayout(g.nodes.length, g.links, { w: W, h: H, iterations: meta.dataset.iterations ?? 300 }); st.key = key; }
|
|
63
|
+
meta.layout = st.layout;
|
|
64
|
+
const pal = paletteOf(chart, meta), maxDeg = Math.max(1, ...g.nodes.map((n) => n.links));
|
|
65
|
+
const pos = g.nodes.map((n, i) => { const d = meta.dragged.get(n.id); return d ? { x: d.x, y: d.y } : { x: a.left + pad + meta.layout[i].x, y: a.top + top + meta.layout[i].y }; });
|
|
66
|
+
const n0 = meta.parsed.length;
|
|
67
|
+
const links = g.links.map((l) => { const p = pos[l.s], q = pos[l.t]; return { kind: 'link', datasetIndex: meta.index, index: l.i, x1: p.x, y1: p.y, x2: q.x, y2: q.y, s: l.s, t: l.t, weight: l.weight, skip: false, raw: l.raw, parsed: meta.parsed[l.i], hit: (x, y) => segDist(x, y, p.x, p.y, q.x, q.y) < 4, center: { x: (p.x + q.x) / 2, y: (p.y + q.y) / 2 } }; });
|
|
68
|
+
const nodes = g.nodes.map((n, i) => {
|
|
69
|
+
const r = n.radius ?? n.marker?.radius ?? (meta.dataset.nodeRadius ?? 5) + 7 * Math.sqrt(n.links / maxDeg), c = n.color ?? pal[(n.group != null ? hash(n.group) : i) % pal.length];
|
|
70
|
+
return { kind: 'node', datasetIndex: meta.index, index: n0 + i, k: i, node: n, x: pos[i].x, y: pos[i].y, radius: r, color: c, skip: false, parsed: { index: n0 + i, value: n.links, name: n.name }, hit: (x, y) => Math.hypot(x - pos[i].x, y - pos[i].y) <= r + 2, center: { x: pos[i].x, y: pos[i].y }, tip: { x: pos[i].x, y: pos[i].y - r } };
|
|
71
|
+
});
|
|
72
|
+
meta.elements = [...links, ...nodes];
|
|
73
|
+
},
|
|
74
|
+
initial(el) { return el; },
|
|
75
|
+
draw(painter, meta, chart) {
|
|
76
|
+
const th = themeOf(chart), f = fontOf(chart, { size: 11 }), act = meta.elements.find((e) => e.kind === 'node' && chart.isActive(meta.index, e.index));
|
|
77
|
+
const near = act ? new Set([act.k, ...meta.elements.filter((e) => e.kind === 'link' && (e.s === act.k || e.t === act.k)).flatMap((e) => [e.s, e.t])]) : null;
|
|
78
|
+
for (const e of meta.elements) if (e.kind === 'link') { const on = !near || (near.has(e.s) && near.has(e.t) && (e.s === act.k || e.t === act.k)); painter.line(e.x1, e.y1, e.x2, e.y2, { stroke: chart.isActive(meta.index, e.index) ? th.ink : on && act ? shade(act.color, -0.1) : th.axis, width: Math.min(4, 0.8 + Math.log2(1 + e.weight) * 0.6) * (chart.isActive(meta.index, e.index) ? 2 : 1), opacity: on ? 1 : 0.25 }); }
|
|
79
|
+
for (const e of meta.elements) if (e.kind === 'node') {
|
|
80
|
+
const on = !near || near.has(e.k);
|
|
81
|
+
painter.circle(e.x, e.y, e.radius, { fill: e.color, stroke: act === e ? th.ink : th.bg, width: act === e ? 2 : 1.5, opacity: on ? 1 : 0.3 });
|
|
82
|
+
if (meta.dataset.labels !== false && (e.radius > 7 || act === e || (near && near.has(e.k)))) painter.text(e.node.name, e.x, e.y - e.radius - 4, { fill: th.ink, font: f, align: 'center', baseline: 'bottom', opacity: on ? 1 : 0.3 });
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
label(chart, meta, el) { return el.kind === 'node' ? el.node.name : el.parsed?.name ?? ''; },
|
|
86
|
+
format(chart, meta, el) { return el.kind === 'node' ? `${el.node.links} link${el.node.links === 1 ? '' : 's'}` : `weight ${formatNumber(el.weight, { locale: chart.resolved.locale })}`; },
|
|
87
|
+
swatch(chart, meta, el) { return el.color ?? themeOf(chart).axis; },
|
|
88
|
+
describe(chart, meta) { const g = meta.graph, top = g.nodes.slice().sort((a, b) => b.links - a.links).slice(0, 3); return `${meta.label ? meta.label + ': ' : ''}${g.nodes.length} nodes and ${g.links.length} links; the most linked ${top.map((n) => `${n.name} (${n.links})`).join(', ')}`; },
|
|
89
|
+
};
|
|
90
|
+
const NET = new WeakMap();
|
|
91
|
+
const hash = (s) => [...String(s)].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7);
|
|
92
|
+
|
|
93
|
+
// ── trees: an organization chart (boxes, top down) and a tree graph (circles, left to right) ─────────
|
|
94
|
+
// [from, to] links (Highcharts's organization) or rows { id, parent, name, title } (its treegraph)
|
|
95
|
+
function treeOfRows(meta) {
|
|
96
|
+
const ds = meta.dataset, byId = new Map(), order = [];
|
|
97
|
+
// a row's own parent and children are words in the data; the tree's are the nodes themselves
|
|
98
|
+
const node = (id, extra = {}) => { const k = String(id); if (!byId.has(k)) { byId.set(k, { id: k, name: k, children: [], parent: null }); order.push(k); } const { parent, children, ...own } = extra; void parent; void children; Object.assign(byId.get(k), own); return byId.get(k); };
|
|
99
|
+
for (const n of ds.nodes ?? []) node(n.id, { ...n, id: String(n.id), name: String(n.name ?? n.id) });
|
|
100
|
+
const rows = ds.data ?? [];
|
|
101
|
+
rows.forEach((raw, i) => {
|
|
102
|
+
if (Array.isArray(raw) || (raw && raw.from != null)) { const o = Array.isArray(raw) ? { from: raw[0], to: raw[1] } : raw; const p = node(o.from), c = node(o.to); if (!c.parent) { c.parent = p; p.children.push(c); } c.dataIndex = i; return; }
|
|
103
|
+
if (raw && typeof raw === 'object') { const c = node(raw.id ?? raw.name ?? i, { ...raw, id: String(raw.id ?? raw.name ?? i), name: String(raw.name ?? raw.id ?? i), dataIndex: i }); if (raw.parent != null && raw.parent !== '') { const p = node(raw.parent); if (!c.parent) { c.parent = p; p.children.push(c); } } }
|
|
104
|
+
});
|
|
105
|
+
const nodes = order.map((k) => byId.get(k)), roots = nodes.filter((n) => !n.parent);
|
|
106
|
+
const depth = (n, d) => { n.depth = d; n.children.forEach((c) => depth(c, d + 1)); };
|
|
107
|
+
roots.forEach((r) => depth(r, 0));
|
|
108
|
+
return { nodes, roots };
|
|
109
|
+
}
|
|
110
|
+
// places for a tree: leaves one after another, a parent over the middle of its children (a tidy tree, simply)
|
|
111
|
+
export function treeLayout(roots) {
|
|
112
|
+
let next = 0;
|
|
113
|
+
const place = (n) => { if (!n.children.length || n.collapsed) { n.u = next++; return; } n.children.forEach(place); n.u = (n.children[0].u + n.children.at(-1).u) / 2; };
|
|
114
|
+
roots.forEach((r) => { place(r); next += 0.5; });
|
|
115
|
+
return { span: Math.max(1, next - 0.5) };
|
|
116
|
+
}
|
|
117
|
+
function treeType(kind) {
|
|
118
|
+
const org = kind === 'organization';
|
|
119
|
+
return {
|
|
120
|
+
element: 'node', name: org ? 'Organization chart' : 'Tree graph', axes: 'none', legend: 'none', colors: 'none',
|
|
121
|
+
defaults: { aspectRatio: org ? 1.7 : 1.5, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
122
|
+
parse(chart, meta) { const t = treeOfRows(meta); meta.tree = t; return t.nodes.map((n, i) => ({ index: i, value: n.children.length, name: n.name, raw: n, i })); },
|
|
123
|
+
limits: () => [Infinity, -Infinity],
|
|
124
|
+
update(chart, meta) {
|
|
125
|
+
const a = chart.chartArea, t = meta.tree, { span } = treeLayout(t.roots), levels = Math.max(1, ...t.nodes.map((n) => n.depth)) + 1, across = meta.dataset.inverted ?? !org;
|
|
126
|
+
const W = a.right - a.left, H = a.bottom - a.top, pal = paletteOf(chart, meta);
|
|
127
|
+
// boxes as wide as the room for the leaves allows, as tall as the room for the levels
|
|
128
|
+
const along = across ? W : H, wide = across ? H : W, gapL = along / levels, gapU = wide / Math.max(1, span);
|
|
129
|
+
const bw = org ? Math.min(meta.dataset.nodeWidth ?? 170, (across ? gapL : gapU) * 0.92) : 0, bh = org ? Math.min(meta.dataset.nodeHeight ?? 52, (across ? gapU : gapL) * 0.66) : 0;
|
|
130
|
+
const pos = (n) => { const l = (n.depth + 0.5) * gapL, u = (n.u + 0.5) * gapU; return across ? { x: a.left + l, y: a.top + u } : { x: a.left + u, y: a.top + l }; };
|
|
131
|
+
const colorOf = (n) => n.color ?? (n.depth === 0 ? themeOf(chart).ink : pal[(n.parent?.depth === 0 ? n.parent.children.indexOf(n) : topIndex(n)) % pal.length]);
|
|
132
|
+
meta.box = { bw, bh, across };
|
|
133
|
+
meta.elements = t.nodes.map((n, i) => {
|
|
134
|
+
const p = pos(n), r = org ? 0 : (meta.dataset.nodeRadius ?? 7), c = colorOf(n);
|
|
135
|
+
const bounds = org ? { l: p.x - bw / 2, r: p.x + bw / 2, t: p.y - bh / 2, b: p.y + bh / 2 } : { l: p.x - r - 2, r: p.x + r + 2, t: p.y - r - 2, b: p.y + r + 2 };
|
|
136
|
+
return { kind: 'node', datasetIndex: meta.index, index: i, node: n, x: p.x, y: p.y, radius: r, color: c, skip: false, raw: n, parsed: meta.parsed[i], bounds, center: p, tip: { x: p.x, y: bounds.t } };
|
|
137
|
+
});
|
|
138
|
+
},
|
|
139
|
+
initial(el) { return el; },
|
|
140
|
+
draw(painter, meta, chart) {
|
|
141
|
+
const th = themeOf(chart), f = fontOf(chart, { size: 11 }), { bw, bh, across } = meta.box, byNode = new Map(meta.elements.map((e) => [e.node, e]));
|
|
142
|
+
// the lines first: elbows for an organization, curves for a tree graph
|
|
143
|
+
for (const e of meta.elements) for (const c of e.node.children) {
|
|
144
|
+
const q = byNode.get(c); if (!q) continue;
|
|
145
|
+
if (org) {
|
|
146
|
+
if (across) { const x0 = e.x + bw / 2, x1 = q.x - bw / 2, xm = (x0 + x1) / 2; painter.path(`M${r1(x0)},${r1(e.y)}H${r1(xm)}V${r1(q.y)}H${r1(x1)}`, { stroke: th.axis, width: 1.5 }); }
|
|
147
|
+
else { const y0 = e.y + bh / 2, y1 = q.y - bh / 2, ym = (y0 + y1) / 2; painter.path(`M${r1(e.x)},${r1(y0)}V${r1(ym)}H${r1(q.x)}V${r1(y1)}`, { stroke: th.axis, width: 1.5 }); }
|
|
148
|
+
} else { const mx = (e.x + q.x) / 2, my = (e.y + q.y) / 2; painter.path(across ? `M${r1(e.x)},${r1(e.y)}C${r1(mx)},${r1(e.y)} ${r1(mx)},${r1(q.y)} ${r1(q.x)},${r1(q.y)}` : `M${r1(e.x)},${r1(e.y)}C${r1(e.x)},${r1(my)} ${r1(q.x)},${r1(my)} ${r1(q.x)},${r1(q.y)}`, { stroke: withAlpha(typeof q.color === 'string' ? q.color : '#888', 0.6), width: 1.5 }); }
|
|
149
|
+
}
|
|
150
|
+
for (const e of meta.elements) {
|
|
151
|
+
const n = e.node, active = chart.isActive(meta.index, e.index);
|
|
152
|
+
if (org) {
|
|
153
|
+
const l = e.x - bw / 2, t = e.y - bh / 2, card = th.mode === 'dark' ? '#1e252e' : '#ffffff';
|
|
154
|
+
painter.rect(l, t, bw, bh, { fill: active ? mix(card, e.color, 0.12) : card, stroke: active ? e.color : th.grid, width: active ? 2 : 1, radius: 6 });
|
|
155
|
+
painter.rect(l, t, 5, bh, { fill: e.color, radius: 2 });
|
|
156
|
+
const title = n.title ?? n.description, { big, small } = meta.box.fonts ??= orgFonts(painter, meta.elements, f, bw, bh);
|
|
157
|
+
painter.text(clip(painter, n.name, bw - 18, big), l + 12, t + (title ? bh * 0.38 : bh / 2), { fill: th.ink, font: big, baseline: 'middle' });
|
|
158
|
+
if (title) painter.text(clip(painter, title, bw - 18, small), l + 12, t + bh * 0.7, { fill: chart.resolved.color, font: small, baseline: 'middle' });
|
|
159
|
+
} else {
|
|
160
|
+
painter.circle(e.x, e.y, active ? e.radius + 2 : e.radius, { fill: e.color, stroke: th.bg, width: 1.5 });
|
|
161
|
+
// leaves name themselves after the node, the root before it, the ones between above it (clear of the lines)
|
|
162
|
+
const leaf = !n.children.length, root = !n.parent;
|
|
163
|
+
if (across) painter.text(n.name, leaf ? e.x + e.radius + 5 : root ? e.x - e.radius - 5 : e.x, leaf || root ? e.y : e.y - e.radius - 4, { fill: th.ink, font: f, align: leaf ? 'left' : root ? 'right' : 'center', baseline: leaf || root ? 'middle' : 'bottom' });
|
|
164
|
+
else painter.text(n.name, leaf ? e.x : e.x + e.radius + 5, leaf ? e.y + e.radius + 12 : e.y, { fill: th.ink, font: f, align: leaf ? 'center' : 'left', baseline: 'middle' });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
label(chart, meta, el) { return el.node.name; },
|
|
169
|
+
format(chart, meta, el) { const n = el.node; return [n.title, n.children.length ? `${n.children.length} under` : null].filter(Boolean).join(' · ') || (n.parent ? `under ${n.parent.name}` : 'top'); },
|
|
170
|
+
swatch(chart, meta, el) { return el.color; },
|
|
171
|
+
describe(chart, meta) { const t = meta.tree, levels = Math.max(0, ...t.nodes.map((n) => n.depth)) + 1; return `${meta.label ? meta.label + ': ' : ''}${t.nodes.length} people in ${levels} levels; at the top ${t.roots.map((r) => r.name + (r.title ? ` (${r.title})` : '')).join(', ')}`; },
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
// one size of type for every box: the largest at which (nearly) every name and title fits
|
|
175
|
+
function orgFonts(painter, els, f, bw, bh) {
|
|
176
|
+
const room = bw - 18, fit = (key, size, min, weight) => { let z = size; for (const e of els) { const t = String(e.node[key] ?? (key === 'title' ? e.node.description ?? '' : '')); while (z > min && painter.measure(t, { ...f, size: z, weight }) > room) z -= 0.5; } return { ...f, size: z, weight }; };
|
|
177
|
+
return { big: fit('name', Math.min(13, Math.max(9, bh / 3.6)), 9, '600'), small: fit('title', Math.min(11, Math.max(8, bh / 4.6)), 8) };
|
|
178
|
+
}
|
|
179
|
+
const topIndex = (n) => { let q = n; while (q.parent && q.parent.parent) q = q.parent; return q.parent ? q.parent.children.indexOf(q) : 0; };
|
|
180
|
+
|
|
181
|
+
// ── a Venn diagram ───────────────────────────────────────────────────────────────────────────────
|
|
182
|
+
// the area two circles of radius r1 and r2 share at distance d
|
|
183
|
+
export function overlap(ra, rb, d) {
|
|
184
|
+
if (d >= ra + rb) return 0;
|
|
185
|
+
if (d <= Math.abs(ra - rb)) return Math.PI * Math.min(ra, rb) ** 2;
|
|
186
|
+
const a = ra * ra * Math.acos((d * d + ra * ra - rb * rb) / (2 * d * ra)), b = rb * rb * Math.acos((d * d + rb * rb - ra * ra) / (2 * d * rb));
|
|
187
|
+
return a + b - 0.5 * Math.sqrt((-d + ra + rb) * (d + ra - rb) * (d - ra + rb) * (d + ra + rb));
|
|
188
|
+
}
|
|
189
|
+
/** The distance at which two circles share an area (by halving). */
|
|
190
|
+
export function distanceFor(ra, rb, area) {
|
|
191
|
+
if (area <= 0) return ra + rb + 1e-9;
|
|
192
|
+
if (area >= Math.PI * Math.min(ra, rb) ** 2) return Math.abs(ra - rb);
|
|
193
|
+
let lo = Math.abs(ra - rb), hi = ra + rb;
|
|
194
|
+
for (let k = 0; k < 60; k++) { const mid = (lo + hi) / 2; if (overlap(ra, rb, mid) > area) lo = mid; else hi = mid; }
|
|
195
|
+
return (lo + hi) / 2;
|
|
196
|
+
}
|
|
197
|
+
/** Circles for sets: [{ sets: ['A'], value }, { sets: ['A', 'B'], value }, …] → { A: { x, y, r }, … } (exact for two, close for more). */
|
|
198
|
+
export function vennLayout(rows) {
|
|
199
|
+
const singles = rows.filter((r) => r.sets.length === 1), names = singles.map((r) => r.sets[0]);
|
|
200
|
+
const rad = Object.fromEntries(singles.map((r) => [r.sets[0], Math.sqrt(Math.max(0, r.value) / Math.PI)]));
|
|
201
|
+
const pair = (a, b) => rows.find((r) => r.sets.length === 2 && r.sets.includes(a) && r.sets.includes(b))?.value ?? 0;
|
|
202
|
+
const dist = (a, b) => distanceFor(rad[a], rad[b], pair(a, b));
|
|
203
|
+
const pos = {};
|
|
204
|
+
if (names[0]) pos[names[0]] = { x: 0, y: 0 };
|
|
205
|
+
if (names[1]) pos[names[1]] = { x: dist(names[0], names[1]), y: 0 };
|
|
206
|
+
// each further set: where its distances to the first two meet (the law of cosines), then nudged towards all of them
|
|
207
|
+
for (let k = 2; k < names.length; k++) {
|
|
208
|
+
const c = names[k], a = names[0], b = names[1], dab = Math.max(1e-9, pos[b].x), dac = dist(a, c), dbc = dist(b, c);
|
|
209
|
+
const x = (dac * dac - dbc * dbc + dab * dab) / (2 * dab), y = -Math.sqrt(Math.max(0, dac * dac - x * x));
|
|
210
|
+
pos[c] = { x, y };
|
|
211
|
+
}
|
|
212
|
+
for (let it = 0; it < (names.length > 3 ? 400 : 0); it++) for (let i = 0; i < names.length; i++) for (let j = 0; j < names.length; j++) {
|
|
213
|
+
if (i === j) continue;
|
|
214
|
+
const a = names[i], b = names[j], want = dist(a, b), p = pos[a], q = pos[b], d = Math.hypot(p.x - q.x, p.y - q.y) || 1e-6, f = ((d - want) / d) * 0.02;
|
|
215
|
+
p.x -= (p.x - q.x) * f; p.y -= (p.y - q.y) * f;
|
|
216
|
+
}
|
|
217
|
+
return Object.fromEntries(names.map((n) => [n, { ...pos[n], r: rad[n] }]));
|
|
218
|
+
}
|
|
219
|
+
const venn = {
|
|
220
|
+
element: 'region', name: 'Venn diagram', axes: 'none', legend: 'points', colors: 'none',
|
|
221
|
+
defaults: { aspectRatio: 1.4, interaction: { mode: 'nearest', intersect: true }, plugins: { legend: { display: false } } },
|
|
222
|
+
parse(chart, meta) {
|
|
223
|
+
return (meta.dataset.data ?? []).map((raw, i) => { const sets = (raw.sets ?? (Array.isArray(raw) ? raw[0] : [])).map(String); return { index: i, value: num(raw.value ?? raw.size ?? (Array.isArray(raw) ? raw[1] : NaN)), sets, name: raw.name ?? sets.join(' ∩ '), raw, i }; });
|
|
224
|
+
},
|
|
225
|
+
limits: () => [Infinity, -Infinity],
|
|
226
|
+
update(chart, meta) {
|
|
227
|
+
const a = chart.chartArea, lay = vennLayout(meta.parsed.filter((p) => Number.isFinite(p.value))), names = Object.keys(lay), pal = paletteOf(chart, meta);
|
|
228
|
+
const xs = names.flatMap((n) => [lay[n].x - lay[n].r, lay[n].x + lay[n].r]), ys = names.flatMap((n) => [lay[n].y - lay[n].r, lay[n].y + lay[n].r]);
|
|
229
|
+
const bw = Math.max(...xs) - Math.min(...xs) || 1, bh = Math.max(...ys) - Math.min(...ys) || 1, s = Math.min((a.right - a.left) / bw, (a.bottom - a.top) / bh) * 0.92;
|
|
230
|
+
const ox = (a.left + a.right) / 2 - ((Math.max(...xs) + Math.min(...xs)) / 2) * s, oy = (a.top + a.bottom) / 2 - ((Math.max(...ys) + Math.min(...ys)) / 2) * s;
|
|
231
|
+
const circles = Object.fromEntries(names.map((n, k) => [n, { x: ox + lay[n].x * s, y: oy + lay[n].y * s, r: lay[n].r * s, color: meta.parsed.find((p) => p.sets.length === 1 && p.sets[0] === n)?.raw?.color ?? pal[k % pal.length] }]));
|
|
232
|
+
meta.circles = circles;
|
|
233
|
+
const inside = (x, y) => names.filter((n) => Math.hypot(x - circles[n].x, y - circles[n].y) <= circles[n].r);
|
|
234
|
+
// where a region's label goes: the point inside exactly its sets furthest from every edge (on a grid)
|
|
235
|
+
const spot = (sets) => { let best = null; const c = sets.map((n) => circles[n]).filter(Boolean); if (!c.length) return null; const x0 = Math.min(...c.map((q) => q.x - q.r)), x1 = Math.max(...c.map((q) => q.x + q.r)), y0 = Math.min(...c.map((q) => q.y - q.r)), y1 = Math.max(...c.map((q) => q.y + q.r)); for (let gx = 0; gx <= 24; gx++) for (let gy = 0; gy <= 24; gy++) { const x = x0 + ((x1 - x0) * gx) / 24, y = y0 + ((y1 - y0) * gy) / 24, inn = inside(x, y); if (inn.length !== sets.length || !sets.every((n) => inn.includes(n))) continue; const m = Math.min(...names.map((n) => Math.abs(Math.hypot(x - circles[n].x, y - circles[n].y) - circles[n].r))); if (!best || m > best.m) best = { x, y, m }; } return best; };
|
|
236
|
+
meta.elements = meta.parsed.map((p) => {
|
|
237
|
+
const at = spot(p.sets), c = p.sets.length === 1 ? circles[p.sets[0]] : null;
|
|
238
|
+
return { kind: 'region', datasetIndex: meta.index, index: p.i, sets: p.sets, color: c?.color ?? mix(circles[p.sets[0]]?.color ?? '#888', circles[p.sets[1]]?.color ?? '#888', 0.5), skip: !at, raw: p.raw, parsed: p, hit: (x, y) => { const inn = inside(x, y); return inn.length === p.sets.length && p.sets.every((n) => inn.includes(n)); }, center: at ? { x: at.x, y: at.y } : { x: 0, y: 0 }, tip: at ? { x: at.x, y: at.y - 6 } : { x: 0, y: 0 } };
|
|
239
|
+
});
|
|
240
|
+
},
|
|
241
|
+
initial(el) { return el; },
|
|
242
|
+
draw(painter, meta, chart) {
|
|
243
|
+
const th = themeOf(chart), f = fontOf(chart, { size: 12 }), fmt = (v) => formatNumber(v, { locale: chart.resolved.locale });
|
|
244
|
+
for (const [, c] of Object.entries(meta.circles)) painter.circle(c.x, c.y, c.r, { fill: withAlpha(typeof c.color === 'string' ? c.color : '#3d7dd8', 0.35), stroke: c.color, width: 1.5 });
|
|
245
|
+
for (const e of meta.elements) {
|
|
246
|
+
if (e.skip) continue;
|
|
247
|
+
if (chart.isActive(meta.index, e.index)) painter.circle(e.center.x, e.center.y, 5, { fill: th.ink });
|
|
248
|
+
const single = e.sets.length === 1, text = single ? `${e.parsed.name}` : fmt(e.parsed.value);
|
|
249
|
+
painter.text(text, e.center.x, e.center.y, { fill: th.ink, font: single ? { ...f, weight: '600' } : f, align: 'center', baseline: 'middle' });
|
|
250
|
+
if (single) painter.text(fmt(e.parsed.value), e.center.x, e.center.y + f.size * 1.2, { fill: chart.resolved.color, font: { ...f, size: f.size - 1 }, align: 'center', baseline: 'middle' });
|
|
251
|
+
}
|
|
252
|
+
},
|
|
253
|
+
label(chart, meta, el) { return el.parsed.name; },
|
|
254
|
+
format(chart, meta, el, fmt) { return fmt(el.parsed.value); },
|
|
255
|
+
swatch(chart, meta, el) { return el.color; },
|
|
256
|
+
legendItems(chart, meta) { return meta.parsed.filter((p) => p.sets.length === 1).map((p) => ({ text: p.name, fillStyle: meta.circles?.[p.sets[0]]?.color ?? '#888', strokeStyle: 'transparent', lineWidth: 0, hidden: false, index: p.i, pointStyle: 'circle' })); },
|
|
257
|
+
describe(chart, meta, fmt) { return `${meta.label ? meta.label + ': ' : ''}${meta.parsed.map((p) => `${p.name} ${fmt(p.value)}`).join(', ')}`; },
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
// ── parallel coordinates ───────────────────────────────────────────────────────────────────────
|
|
261
|
+
// the dimensions are the labels; a row is an array (one value per dimension) or an object by dimension
|
|
262
|
+
const parallel = {
|
|
263
|
+
element: 'line', name: 'Parallel coordinates', axes: 'none', alpha: 0.55,
|
|
264
|
+
defaults: { aspectRatio: 1.9, interaction: { mode: 'nearest', intersect: true } },
|
|
265
|
+
parse(chart, meta) {
|
|
266
|
+
const dims = chart.data.labels ?? [];
|
|
267
|
+
return (meta.dataset.data ?? []).map((raw, i) => ({ index: i, values: dims.map((d, k) => (Array.isArray(raw) ? raw[k] : raw?.[d])), value: NaN, name: raw?.name ?? `${meta.label || 'Row'} ${i + 1}`, raw, i }));
|
|
268
|
+
},
|
|
269
|
+
limits: () => [Infinity, -Infinity],
|
|
270
|
+
update(chart, meta) {
|
|
271
|
+
const dims = chart.data.labels ?? [], a = chart.chartArea, f = fontOf(chart), all = chart.metas.filter((m) => m.type === meta.type && chart.isDatasetVisible(m.index)).flatMap((m) => m.parsed);
|
|
272
|
+
const top = a.top + f.size * 2.4, bottom = a.bottom - 6;
|
|
273
|
+
// an axis for each dimension: numbers on a round scale, words in the order first met
|
|
274
|
+
if (!chart._pcAxes || chart._pcStamp !== chart._updates) {
|
|
275
|
+
chart._pcAxes = dims.map((d, k) => {
|
|
276
|
+
const vals = all.map((p) => p.values[k]).filter((v) => v != null && v !== '');
|
|
277
|
+
if (vals.length && vals.every((v) => typeof v === 'string' && !Number.isFinite(Number(v)))) { const cats = [...new Set(vals)]; return { name: String(d), cats, at: (v) => cats.indexOf(v) / Math.max(1, cats.length - 1), ticks: cats.map((c, j) => ({ v: c, t: j / Math.max(1, cats.length - 1), label: c })) }; }
|
|
278
|
+
const own = chart.resolved.parallelAxes?.[k] ?? chart.resolved.parallelAxes?.[d] ?? {};
|
|
279
|
+
let lo = own.min ?? Math.min(...vals.map(Number)), hi = own.max ?? Math.max(...vals.map(Number)); if (!(hi > lo)) { lo -= 1; hi += 1; }
|
|
280
|
+
const step = niceStep(hi - lo, 4); if (own.min == null) lo = Math.floor(lo / step) * step; if (own.max == null) hi = Math.ceil(hi / step) * step;
|
|
281
|
+
const ticks = []; for (let v = lo, j = 0; v <= hi + step * 1e-9 && j < 12; v += step, j++) ticks.push({ v, t: (v - lo) / (hi - lo), label: formatNumber(+v.toPrecision(10), { locale: chart.resolved.locale }) });
|
|
282
|
+
return { name: String(d), at: (v) => (Number(v) - lo) / (hi - lo || 1), ticks, reversed: !!own.reversed };
|
|
283
|
+
});
|
|
284
|
+
chart._pcStamp = chart._updates;
|
|
285
|
+
}
|
|
286
|
+
const axes = chart._pcAxes, n = Math.max(1, axes.length - 1), X = (k) => a.left + 30 + ((a.right - a.left - 60) * k) / n, Y = (ax, t) => (ax.reversed ? top + (bottom - top) * t : bottom - (bottom - top) * t);
|
|
287
|
+
meta.pc = { axes, X, Y, top, bottom };
|
|
288
|
+
meta.elements = meta.parsed.map((p) => {
|
|
289
|
+
const pts = axes.map((ax, k) => { const v = p.values[k]; const t = v == null || v === '' ? NaN : ax.at(v); return Number.isFinite(t) ? [X(k), Y(ax, t)] : null; });
|
|
290
|
+
const ok = pts.filter(Boolean);
|
|
291
|
+
return { kind: 'line', datasetIndex: meta.index, index: p.i, pts, skip: ok.length < 2, raw: p.raw, parsed: p, hit: (x, y) => { for (let k = 1; k < pts.length; k++) if (pts[k - 1] && pts[k] && segDist(x, y, pts[k - 1][0], pts[k - 1][1], pts[k][0], pts[k][1]) < 4) return true; return false; }, center: ok.length ? { x: ok[Math.floor(ok.length / 2)][0], y: ok[Math.floor(ok.length / 2)][1] } : { x: 0, y: 0 } };
|
|
292
|
+
});
|
|
293
|
+
},
|
|
294
|
+
initial(el) { return el; },
|
|
295
|
+
draw(painter, meta, chart) {
|
|
296
|
+
const { axes, X, Y, top, bottom } = meta.pc, th = themeOf(chart), f = fontOf(chart, { size: 10 }), c = chart.option(meta, 'borderColor', 0) ?? meta.auto?.borderColor ?? PALETTE[0];
|
|
297
|
+
const first = chart.metas.find((m) => m.type === meta.type && chart.isDatasetVisible(m.index));
|
|
298
|
+
if (first === meta) {
|
|
299
|
+
painter.layer('grid');
|
|
300
|
+
axes.forEach((ax, k) => {
|
|
301
|
+
painter.line(X(k), top, X(k), bottom, { stroke: th.axis, width: 1 });
|
|
302
|
+
painter.text(ax.name, X(k), top - f.size * 1.3, { fill: th.ink, font: { ...f, size: 11, weight: '600' }, align: 'center', baseline: 'middle' });
|
|
303
|
+
for (const tk of ax.ticks) { const y = Y(ax, tk.t); painter.line(X(k) - 3, y, X(k), y, { stroke: th.axis, width: 1 }); painter.text(tk.label, X(k) - 5, y, { fill: chart.resolved.color, font: f, align: 'right', baseline: 'middle' }); }
|
|
304
|
+
});
|
|
305
|
+
painter.layer('datasets');
|
|
306
|
+
}
|
|
307
|
+
const act = meta.elements.find((e) => chart.isActive(meta.index, e.index));
|
|
308
|
+
for (const e of meta.elements) {
|
|
309
|
+
if (e.skip || e === act) continue;
|
|
310
|
+
const own = chart.option(meta, 'borderColor', e.index) ?? c;
|
|
311
|
+
painter.path(runs(e.pts), { stroke: withAlpha(typeof own === 'string' ? own : PALETTE[0], act ? 0.15 : chart.option(meta, 'opacity', 0, null, 0.55)), width: chart.option(meta, 'borderWidth', 0, null, 1.5), join: 'round' });
|
|
312
|
+
}
|
|
313
|
+
if (act) painter.path(runs(act.pts), { stroke: shade(typeof c === 'string' ? c : PALETTE[0], -0.15), width: 3, join: 'round' });
|
|
314
|
+
},
|
|
315
|
+
label(chart, meta, el) { return el.parsed.name; },
|
|
316
|
+
lines(chart, meta, el) { return meta.pc.axes.map((ax, k) => `${ax.name}: ${el.parsed.values[k] ?? '–'}`); },
|
|
317
|
+
format(chart, meta, el) { return meta.pc.axes.map((ax, k) => `${ax.name} ${el.parsed.values[k] ?? '–'}`).join(', '); },
|
|
318
|
+
swatch(chart, meta) { return chart.option(meta, 'borderColor', 0) ?? meta.auto?.borderColor; },
|
|
319
|
+
describe(chart, meta) { return `${meta.label ? meta.label + ': ' : ''}${meta.parsed.length} rows across ${(chart.data.labels ?? []).length} dimensions (${(chart.data.labels ?? []).join(', ')})`; },
|
|
320
|
+
};
|
|
321
|
+
const runs = (pts) => { let d = '', pen = false; for (const p of pts) { if (!p) { pen = false; continue; } d += `${pen ? 'L' : 'M'}${r1(p[0])},${r1(p[1])}`; pen = true; } return d; };
|
|
322
|
+
|
|
323
|
+
// ── dragging a node of a network ─────────────────────────────────────────────────────────────────
|
|
324
|
+
export const nodeDrag = {
|
|
325
|
+
id: 'nodeDrag',
|
|
326
|
+
defaults: { enabled: true },
|
|
327
|
+
afterInit(chart) {
|
|
328
|
+
if (typeof chart.surface?.addEventListener !== 'function') return;
|
|
329
|
+
let drag = null;
|
|
330
|
+
chart.surface.addEventListener('pointerdown', (e) => {
|
|
331
|
+
if (chart.resolved?.plugins?.nodeDrag?.enabled === false) return;
|
|
332
|
+
const p = chart._pos(e);
|
|
333
|
+
for (const m of chart.metas) if (m.type === 'network' || m.type === 'networkgraph') { const n = m.elements.find((q) => q.kind === 'node' && Math.hypot(q.x - p.x, q.y - p.y) <= q.radius + 3); if (n) { drag = { m, id: n.node.id }; chart.surface.setPointerCapture?.(e.pointerId); e.stopPropagation(); return; } }
|
|
334
|
+
});
|
|
335
|
+
chart.surface.addEventListener('pointermove', (e) => { if (!drag) return; const p = chart._pos(e), a = chart.chartArea; drag.m.dragged.set(drag.id, { x: Math.max(a.left, Math.min(a.right, p.x)), y: Math.max(a.top, Math.min(a.bottom, p.y)) }); drag.moved = true; chart.update('none'); });
|
|
336
|
+
const end = () => { if (drag?.moved) chart._justDragged = true; drag = null; };
|
|
337
|
+
chart.surface.addEventListener('pointerup', end); chart.surface.addEventListener('pointercancel', end);
|
|
338
|
+
},
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
export const GRAPH_TYPES = { network, networkgraph: network, organization: treeType('organization'), treegraph: treeType('treegraph'), venn, parallel, parallelCoordinates: parallel };
|
|
342
|
+
void contrastOn;
|