@peter.prib/renderengine 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ import { GaugeChart } from './GaugeChart.js';
2
+ import { Sparkline } from '../gauges/Sparkline.js';
3
+
4
+ /**
5
+ * KpiTile — a key figure on a card: its title, its value large, the change
6
+ * since the previous value (▲ / ▼, coloured good or bad), and a sparkline of
7
+ * its history.
8
+ *
9
+ * Data: a number, or `{ value, previous?, history?, target? }` (`history` ends
10
+ * with the current value; without `previous` the one before it is used).
11
+ * Options: x, y, width, height (10, 10, 220, 120), format and units (a
12
+ * number with thousands grouped by default), change ('percent', or 'value'
13
+ * for the difference), upIsGood (true: up is green; false for costs, errors,
14
+ * ...), bands (the value takes its band's colour), sparkColor, background,
15
+ * and title.
16
+ */
17
+ export class KpiTile extends GaugeChart {
18
+ static chartType = 'kpiTile';
19
+ static LAYOUT = { x: 10, y: 10, width: 220, height: 120 };
20
+ static GOOD = '#2e9e5b';
21
+ static BAD = '#d64545';
22
+
23
+ /** A figure reads as it is, its thousands grouped ("12,345"). */
24
+ defaultFormat() { return { grouping: true }; }
25
+
26
+ /** The value as it is: a tile has no range to hold it to. */
27
+ get value() { return this.gaugeValue.value; }
28
+
29
+ /** The value's colour: its band's when there are bands, else the text colour. */
30
+ valueColor(value = this.value) {
31
+ if (this.options.color != null || this.bands.length) return super.valueColor(value);
32
+ return '#2f3542';
33
+ }
34
+
35
+ /** The change line: "▲ 10.0%" or "▼ 3", and whether it is good; null without a previous value. */
36
+ get changeText() {
37
+ const { change, changeRatio } = this.gaugeValue;
38
+ if (change == null) return null;
39
+ const { change: as = 'percent', upIsGood = true } = this.options;
40
+ const arrow = change > 0 ? '▲' : change < 0 ? '▼' : '■';
41
+ const amount = as === 'value' || changeRatio == null
42
+ ? this.scale.label(Math.abs(change))
43
+ : `${(Math.abs(changeRatio) * 100).toFixed(1)}%`;
44
+ const good = change === 0 ? null : (change > 0) === upIsGood;
45
+ return { text: `${arrow} ${amount}`, good };
46
+ }
47
+
48
+ _render() {
49
+ const { x, y, width, height } = this.layout;
50
+ const { title, background = '#ffffff', sparkColor = '#5352ed' } = this.options;
51
+ const pad = 12;
52
+ this.renderer.rect(x, y, width, height, background, { color: '#e1e4e8', width: 1 }, { rx: 8, ry: 8 });
53
+ if (title) {
54
+ this.renderer.text(title, x + pad, y + pad + 6, { textAnchor: 'start', verticalAlign: 'middle', fontSize: '12px', fill: '#747d8c' });
55
+ }
56
+ const valueSize = Math.max(14, Math.round(height * 0.26));
57
+ const valueY = y + pad + 18 + valueSize / 2;
58
+ this.renderer.text(this.scale.label(this.value), x + pad, valueY, {
59
+ textAnchor: 'start', verticalAlign: 'middle', fontSize: `${valueSize}px`, fontWeight: 'bold', fill: this.valueColor(),
60
+ });
61
+ const change = this.changeText;
62
+ if (change) {
63
+ const color = change.good == null ? '#747d8c' : change.good ? KpiTile.GOOD : KpiTile.BAD;
64
+ this.renderer.text(change.text, x + width - pad, valueY, { textAnchor: 'end', verticalAlign: 'middle', fontSize: '12px', fontWeight: 'bold', fill: color });
65
+ }
66
+ const sparkTop = valueY + valueSize / 2 + 8;
67
+ const sparkHeight = y + height - pad - sparkTop;
68
+ if (sparkHeight > 4) {
69
+ new Sparkline(this.gaugeValue.history, { x: x + pad, y: sparkTop, width: width - 2 * pad, height: sparkHeight }).draw(this.renderer, { color: sparkColor });
70
+ }
71
+ }
72
+ }
@@ -0,0 +1,54 @@
1
+ import { GaugeChart } from './GaugeChart.js';
2
+ import { ArcTrack } from '../gauges/ArcTrack.js';
3
+ import { GaugeScale } from '../gauges/GaugeScale.js';
4
+
5
+ /**
6
+ * MultiRingGauge — several values as rings one inside the other ("activity
7
+ * rings"), each filled to its value on its own scale, with a legend.
8
+ *
9
+ * Data: `[{ value, label?, color?, min?, max? }]` (or plain numbers), outer
10
+ * ring first; each ring's min and max default to the options'.
11
+ * Options: cx, cy, r (the outer ring: 100, 100, 70), thickness (12), gap (4),
12
+ * startAngle (-90) and sweep (360), colors (a colour per ring without its
13
+ * own), legend (true: each ring's label and value to the right), and the
14
+ * GaugeChart options min, max, format, units.
15
+ */
16
+ export class MultiRingGauge extends GaugeChart {
17
+ static chartType = 'multiRingGauge';
18
+ static LAYOUT = { cx: 100, cy: 100, r: 70, thickness: 12, gap: 4, startAngle: -90, sweep: 360 };
19
+ static COLORS = ['#5352ed', '#2ed573', '#ffa502', '#ff4757', '#1e90ff'];
20
+
21
+ /** One per value: its track, scale and colour. */
22
+ get rings() {
23
+ const { cx, cy, r, thickness, gap, startAngle, sweep } = this.layout;
24
+ const { min, max, format, units, colors = MultiRingGauge.COLORS } = this.options;
25
+ return this.gaugeValue.values.map((v, i) => ({
26
+ ...v,
27
+ track: new ArcTrack({ cx, cy, r: r - i * (thickness + gap), thickness, startAngle, sweep }),
28
+ scale: new GaugeScale({ min: v.min ?? min, max: v.max ?? max, format: format ?? null, units }),
29
+ color: v.color ?? colors[i % colors.length],
30
+ })).filter(ring => ring.track.r > ring.track.thickness / 2);
31
+ }
32
+
33
+ _render() {
34
+ const { title, legend = true } = this.options;
35
+ const { cx, cy, r, thickness } = this.layout;
36
+ const rings = this.rings;
37
+ for (const ring of rings) {
38
+ this.drawBackground(ring.track);
39
+ this.drawValue(ring.track, { value: ring.scale.clamp(ring.value), scale: ring.scale, color: ring.color, cap: 'round' });
40
+ }
41
+ if (legend) {
42
+ const x = cx + r + thickness / 2 + 16;
43
+ const top = cy - ((rings.length - 1) * 18) / 2;
44
+ rings.forEach((ring, i) => {
45
+ const y = top + i * 18;
46
+ this.renderer.circle(x + 4, y, 4, ring.color);
47
+ this.renderer.text(`${ring.label ?? `#${i + 1}`} ${ring.scale.label(ring.scale.clamp(ring.value))}`, x + 14, y, {
48
+ textAnchor: 'start', verticalAlign: 'middle', fontSize: '12px', fill: '#2f3542',
49
+ });
50
+ });
51
+ }
52
+ this._renderTitle(title, cx, cy + r + thickness / 2 + 18, { textAnchor: 'middle', fontSize: '12px', fill: '#747d8c' });
53
+ }
54
+ }
@@ -0,0 +1,23 @@
1
+ import { ArcGauge } from './ArcGauge.js';
2
+
3
+ /**
4
+ * RingGauge — a progress ring: a whole circle filled clockwise from the top
5
+ * to the value, its number in the middle.
6
+ *
7
+ * Options as ArcGauge's, drawn as a ring: cx, cy, r (100, 100, 60),
8
+ * thickness (14), startAngle (-90, the top) and sweep (360).
9
+ */
10
+ export class RingGauge extends ArcGauge {
11
+ static chartType = 'ringGauge';
12
+ static LAYOUT = { cx: 100, cy: 100, r: 60, thickness: 14, startAngle: -90, sweep: 360 };
13
+
14
+ /** The number in the very middle. */
15
+ drawLabels(track) {
16
+ this._renderValueLabel(track.cx, track.cy, { fontSize: `${Math.max(12, Math.round(track.r * 0.36))}px`, fill: '#2f3542', fontWeight: 'bold' });
17
+ }
18
+
19
+ /** A ring's two ends are one point: no end labels. */
20
+ drawEnds() {}
21
+
22
+ titleY(track) { return track.cy + track.r + track.thickness / 2 + 18; }
23
+ }
@@ -0,0 +1,43 @@
1
+ import { GaugeChart } from './GaugeChart.js';
2
+ import { VerticalTrack } from '../gauges/VerticalTrack.js';
3
+
4
+ /**
5
+ * ThermometerGauge — a tube filled from a bulb at its foot up to the value.
6
+ *
7
+ * Options: x, y, width, height (the tube: 40, 20, 18, 200), bulb (its radius:
8
+ * 16), and every GaugeChart option (min, max, units, bands, target, ticks,
9
+ * segments, ...). The value's label sits under the bulb.
10
+ */
11
+ export class ThermometerGauge extends GaugeChart {
12
+ static chartType = 'thermometerGauge';
13
+ static LAYOUT = { x: 40, y: 20, width: 18, height: 200, bulb: 16 };
14
+ static defaultColor = '#ff4757';
15
+
16
+ track() {
17
+ const { x, y, width, height } = this.layout;
18
+ return new VerticalTrack({ x, y, length: height, thickness: width, radius: width / 2 });
19
+ }
20
+
21
+ /** The bulb's centre: under the tube, overlapping its foot so the two join. */
22
+ bulbCenter(track) {
23
+ const { bulb } = this.layout;
24
+ const foot = track.point(0);
25
+ return { x: foot.x, y: foot.y + bulb * 0.75 };
26
+ }
27
+
28
+ _render() {
29
+ const { title } = this.options;
30
+ const { bulb } = this.layout;
31
+ const track = this.track();
32
+ const centre = this.bulbCenter(track);
33
+ this._renderTitle(title, centre.x, track.y - 10, { textAnchor: 'middle', fontSize: '12px', fill: '#747d8c' });
34
+ this.drawBackground(track);
35
+ this.drawValue(track);
36
+ // The bulb is always full: the value's colour, round a lighter ring.
37
+ this.renderer.circle(centre.x, centre.y, bulb, this.constructor.trackColor);
38
+ this.renderer.circle(centre.x, centre.y, bulb - 3, this.valueColor());
39
+ this.drawTarget(track);
40
+ this.drawTicks(track);
41
+ this._renderValueLabel(centre.x, centre.y + bulb + 14, { fontWeight: 'bold', fill: '#2f3542' });
42
+ }
43
+ }
@@ -0,0 +1,51 @@
1
+ import { Gauge } from '../Gauge.js';
2
+ import { GaugeTrack } from './GaugeTrack.js';
3
+
4
+ /**
5
+ * ArcTrack — a gauge track along a circle's arc: the dial's 270°, a half
6
+ * circle, a full ring. Angles are degrees clockwise from 3 o'clock (the
7
+ * screen's own direction), so 135° with a 270° sweep is the dial's
8
+ * bottom-left to bottom-right, and 180° with 180° is a half circle over the top.
9
+ */
10
+ export class ArcTrack extends GaugeTrack {
11
+ /**
12
+ * @param {Object} options
13
+ * @param {number} options.cx
14
+ * @param {number} options.cy
15
+ * @param {number} options.r - The radius of the track's centre line
16
+ * @param {number} options.thickness
17
+ * @param {number} [options.startAngle=135]
18
+ * @param {number} [options.sweep=270]
19
+ */
20
+ constructor({ cx, cy, r, thickness, startAngle = 135, sweep = 270 }) {
21
+ super(thickness);
22
+ Object.assign(this, { cx, cy, r, startAngle, sweep });
23
+ }
24
+
25
+ /** The arc's length along its centre line, in pixels. */
26
+ get length() { return this.r * Math.abs(this.sweep) * Math.PI / 180; }
27
+
28
+ /** The angle in degrees at a fraction along. */
29
+ angleAt(fraction) { return this.startAngle + fraction * this.sweep; }
30
+
31
+ point(fraction, offset = 0) {
32
+ const a = this.angleAt(fraction) * Math.PI / 180;
33
+ const r = this.r + offset;
34
+ return { x: this.cx + r * Math.cos(a), y: this.cy + r * Math.sin(a) };
35
+ }
36
+
37
+ draw(renderer, from, to, color, { thickness = this.thickness, cap } = {}) {
38
+ const rad = Math.PI / 180;
39
+ const a0 = this.angleAt(Math.min(from, to)) * rad;
40
+ const a1 = this.angleAt(Math.max(from, to)) * rad;
41
+ renderer.path(Gauge.arcPath(this.cx, this.cy, this.r, a0, a1), 'none', { color, width: thickness, ...(cap ? { cap } : {}) });
42
+ }
43
+
44
+ get center() { return { x: this.cx, y: this.cy }; }
45
+
46
+ /** A label outside the arc leans away from the centre: 'start' on the right, 'end' on the left. */
47
+ anchorAt(fraction) {
48
+ const dx = Math.cos(this.angleAt(fraction) * Math.PI / 180);
49
+ return dx > 0.3 ? 'start' : dx < -0.3 ? 'end' : 'middle';
50
+ }
51
+ }
@@ -0,0 +1,51 @@
1
+ import { GaugeValue } from './GaugeValue.js';
2
+
3
+ /**
4
+ * GaugeAnimation — eases a gauge from the value it shows to a new one, so a
5
+ * needle or fill moves instead of jumping.
6
+ *
7
+ * Each frame draws the gauge from `GaugeValue.between(from, to, t)`: the
8
+ * value, the target and each of several values move together; the history
9
+ * and the previous value are the new ones throughout. The clock is
10
+ * injectable (`schedule`, `now`) so it runs without a browser in tests.
11
+ */
12
+ export class GaugeAnimation {
13
+ /** Ease out (cubic): quick at first, settling on the value. */
14
+ static ease(t) { return 1 - (1 - t) ** 3; }
15
+
16
+ /**
17
+ * @param {Object} options
18
+ * @param {GaugeValue} options.from
19
+ * @param {GaugeValue} options.to
20
+ * @param {number} [options.duration=400] - Milliseconds
21
+ * @param {(data: Object) => void} options.draw - Draws one frame from its gauge data
22
+ * @param {(callback: Function) => *} [options.schedule] - requestAnimationFrame, else a 16ms timer
23
+ * @param {() => number} [options.now]
24
+ */
25
+ constructor({ from, to, duration = 400, draw, schedule = GaugeAnimation.defaultSchedule(), now = () => Date.now() }) {
26
+ Object.assign(this, { from, to, duration, draw, schedule, now });
27
+ this.stopped = false;
28
+ }
29
+
30
+ static defaultSchedule() {
31
+ return typeof globalThis.requestAnimationFrame === 'function'
32
+ ? (callback) => globalThis.requestAnimationFrame(callback)
33
+ : (callback) => setTimeout(callback, 16);
34
+ }
35
+
36
+ /** Draw the first frame now and the rest on the clock, ending exactly on `to`. */
37
+ start() {
38
+ const started = this.now();
39
+ const frame = () => {
40
+ if (this.stopped) return;
41
+ const t = this.duration > 0 ? Math.min(1, (this.now() - started) / this.duration) : 1;
42
+ this.draw(GaugeValue.between(this.from, this.to, GaugeAnimation.ease(t)));
43
+ if (t < 1) this.schedule(frame);
44
+ };
45
+ frame();
46
+ return this;
47
+ }
48
+
49
+ /** No more frames (a newer value has started its own). */
50
+ stop() { this.stopped = true; }
51
+ }
@@ -0,0 +1,48 @@
1
+ import { ColorPalette } from '../ColorPalette.js';
2
+
3
+ /**
4
+ * GaugeBands — ranges along a gauge's scale ("poor", "ok", "good"), each with
5
+ * its colour and label.
6
+ *
7
+ * Given as `[{ to, color?, label? }]` in order: each band runs from where the
8
+ * one before it ended (the scale's min for the first) to its `to` (`max` is
9
+ * read the same, as the bullet graph has always taken it). Every gauge draws
10
+ * its bands from here, and a value takes the colour of the band it falls in.
11
+ */
12
+ export class GaugeBands {
13
+ /** Band colours used when a band has none of its own: bad, warning, good. */
14
+ static COLORS = ['#ff6b6b', '#ffd93d', '#6bcb77'];
15
+
16
+ /** How far a band's colour is mixed toward white when drawn behind a value. */
17
+ static TINT = 0.65;
18
+
19
+ /**
20
+ * @param {Array<{to?:number, max?:number, color?:string, label?:string}>} bands
21
+ * @param {import('./GaugeScale.js').GaugeScale} scale
22
+ * @param {Object} [options]
23
+ * @param {string[]} [options.colors] - Colours for bands without their own
24
+ */
25
+ constructor(bands = [], scale, { colors = GaugeBands.COLORS } = {}) {
26
+ this.scale = scale;
27
+ let from = scale.min;
28
+ this.list = (bands ?? []).map((band, index) => {
29
+ const to = scale.clamp(band.to ?? band.max ?? scale.max);
30
+ const entry = { from, to, color: band.color ?? colors[index % colors.length], label: band.label ?? null, index };
31
+ from = to;
32
+ return entry;
33
+ });
34
+ }
35
+
36
+ get length() { return this.list.length; }
37
+
38
+ /** The band a value falls in (the last one at a shared edge), or null. */
39
+ at(value) {
40
+ const v = this.scale.clamp(value);
41
+ return this.list.find(b => v >= b.from && v < b.to) ?? this.list.findLast(b => v >= b.from && v <= b.to) ?? null;
42
+ }
43
+
44
+ /** A band's colour as drawn behind the value: lighter, so the value shows on it. */
45
+ static tint(color) {
46
+ return /^#[0-9a-f]{6}$/i.test(color) ? ColorPalette.interpolate(color, '#ffffff', GaugeBands.TINT) : color;
47
+ }
48
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * GaugeScale — the range a gauge measures and how its numbers read.
3
+ *
4
+ * One scale per gauge: it turns a value into a 0-1 fraction of the way along
5
+ * the track, gives the tick values, and formats the value and tick labels.
6
+ * Every gauge draws from it, so `min`, `max` and `format` mean the same on
7
+ * all of them.
8
+ */
9
+ export class GaugeScale {
10
+ /**
11
+ * @param {Object} [options]
12
+ * @param {number} [options.min=0]
13
+ * @param {number} [options.max=100]
14
+ * @param {Function|Object} [options.format] - `(value) => string`, or
15
+ * `{ decimals, prefix, suffix, grouping, compact }`. Without one, a
16
+ * 0-100 scale reads as a percentage ("75.0%"), any other as its number.
17
+ * @param {string} [options.units] - The suffix when no format is given ("ms", "°C")
18
+ */
19
+ constructor({ min = 0, max = 100, format = null, units = null } = {}) {
20
+ this.min = Number(min);
21
+ this.max = Number(max);
22
+ this.format = format ?? { decimals: 1, suffix: units != null ? ` ${units}` : (this.isPercent ? '%' : '') };
23
+ }
24
+
25
+ /** True for the plain 0-100 scale a percentage gauge has. */
26
+ get isPercent() { return this.min === 0 && this.max === 100; }
27
+
28
+ get span() { return (this.max - this.min) || 1; }
29
+
30
+ /** The value held to the scale's range. */
31
+ clamp(value) {
32
+ const v = Number(value);
33
+ if (!Number.isFinite(v)) return this.min;
34
+ return Math.min(Math.max(v, Math.min(this.min, this.max)), Math.max(this.min, this.max));
35
+ }
36
+
37
+ /** How far along the scale a value is, 0-1 (held to the range). */
38
+ fraction(value) { return (this.clamp(value) - this.min) / this.span; }
39
+
40
+ /** The value at a fraction of the way along. */
41
+ valueAt(fraction) { return this.min + fraction * this.span; }
42
+
43
+ /** `count` equal steps: count + 1 values from min to max. */
44
+ ticks(count = 5) {
45
+ const n = Math.max(1, Math.round(count));
46
+ return Array.from({ length: n + 1 }, (_, i) => this.valueAt(i / n));
47
+ }
48
+
49
+ /** A value as the gauge shows it. */
50
+ label(value) { return GaugeScale.formatNumber(value, this.format); }
51
+
52
+ /**
53
+ * A tick's label: the value's prefix and suffix, with only the decimals a
54
+ * step of `span / count` needs ("0", "25", ... not "0.0%", "25.0%").
55
+ */
56
+ tickLabel(value, count = 5) {
57
+ if (typeof this.format === 'function') return this.format(value);
58
+ const step = this.span / Math.max(1, Math.round(count));
59
+ // The fewest decimals that show the step exactly (0.25 needs 2), at most 6.
60
+ let decimals = 0;
61
+ while (decimals < 6 && Math.abs(step * 10 ** decimals - Math.round(step * 10 ** decimals)) > 1e-9) decimals++;
62
+ return GaugeScale.formatNumber(value, { ...this.format, decimals });
63
+ }
64
+
65
+ /**
66
+ * Format a number: a function format is called; an object one gives
67
+ * decimals (null: as it is), prefix, suffix, grouping (1,234) and compact (1.2K).
68
+ */
69
+ static formatNumber(value, format = {}) {
70
+ if (typeof format === 'function') return format(value);
71
+ const { decimals = null, prefix = '', suffix = '', grouping = false, compact = false } = format ?? {};
72
+ const v = Number(value);
73
+ if (!Number.isFinite(v)) return `${prefix}${value}${suffix}`;
74
+ let text;
75
+ if (compact || grouping) {
76
+ const digits = decimals ?? (compact ? 1 : undefined);
77
+ text = new Intl.NumberFormat('en', {
78
+ notation: compact ? 'compact' : 'standard',
79
+ useGrouping: true,
80
+ ...(digits != null ? { minimumFractionDigits: compact ? 0 : digits, maximumFractionDigits: digits } : {}),
81
+ }).format(v);
82
+ } else {
83
+ text = decimals == null ? String(v) : v.toFixed(decimals);
84
+ }
85
+ return `${prefix}${text}${suffix}`;
86
+ }
87
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * GaugeTrack — the path a gauge's value moves along, as fractions 0-1.
3
+ *
4
+ * A subclass is one geometry (a straight bar, an arc). The gauge asks it for
5
+ * points and draws segments on it, so bands, the value, ticks and a target
6
+ * marker are drawn the same way on every gauge whatever its shape.
7
+ *
8
+ * A track has a `length` (pixels along it) as well as its `thickness`.
9
+ * Offsets are across the track from its centre line: positive is outward
10
+ * (below a horizontal bar, right of a vertical one, away from an arc's centre).
11
+ */
12
+ export class GaugeTrack {
13
+ /** @param {number} thickness - The track's width across */
14
+ constructor(thickness) {
15
+ if (new.target === GaugeTrack) throw new TypeError('GaugeTrack is abstract — subclass it');
16
+ this.thickness = thickness;
17
+ }
18
+
19
+ /** The point at a fraction along, `offset` across. @returns {{x:number, y:number}} */
20
+ point(fraction, offset = 0) { throw new Error(`${this.constructor.name} must implement point()`); }
21
+
22
+ /**
23
+ * Draw the track from one fraction to another, in a colour.
24
+ * @param {Object} renderer
25
+ * @param {number} from - 0-1
26
+ * @param {number} to - 0-1
27
+ * @param {string} color
28
+ * @param {Object} [options] - `thickness` (this track's by default), `cap` ('round' ends)
29
+ */
30
+ draw(renderer, from, to, color, options = {}) { throw new Error(`${this.constructor.name} must implement draw()`); }
31
+
32
+ /** Where a label sits in the middle of the gauge. @returns {{x:number, y:number}} */
33
+ get center() { throw new Error(`${this.constructor.name} must implement center`); }
34
+
35
+ /** A straight line across the track at a fraction, between two offsets (a tick, a target). */
36
+ line(renderer, fraction, fromOffset, toOffset, stroke) {
37
+ const a = this.point(fraction, fromOffset);
38
+ const b = this.point(fraction, toOffset);
39
+ renderer.path(`M${a.x},${a.y} L${b.x},${b.y}`, 'none', stroke);
40
+ }
41
+
42
+ /** How a label at a point outside the track is anchored ('start', 'middle' or 'end'). */
43
+ anchorAt(fraction) { return 'middle'; }
44
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * GaugeValue — what a gauge's data says: the value, and what it is compared
3
+ * with.
4
+ *
5
+ * Data is a plain number, or `{ value, target?, previous?, history?, values? }`;
6
+ * options of the same names win over the data's. `values` is for gauges that
7
+ * show several (one ring each): numbers, or `{ value, label?, color?, min?, max? }`;
8
+ * an array as the data is read as `values`.
9
+ */
10
+ export class GaugeValue {
11
+ constructor({ value = 0, target = null, previous = null, history = [], values = [] } = {}) {
12
+ this.value = Number(value) || 0;
13
+ this.target = target == null ? null : Number(target);
14
+ this.history = (history ?? []).map(Number).filter(Number.isFinite);
15
+ // The value before this one: given, or the one before the last in the history.
16
+ this.previous = previous != null ? Number(previous) : (this.history.length > 1 ? this.history.at(-2) : null);
17
+ this.values = (values ?? []).map(v => (typeof v === 'object' && v !== null ? { ...v, value: Number(v.value) || 0 } : { value: Number(v) || 0 }));
18
+ }
19
+
20
+ /** The change from the previous value, or null without one. */
21
+ get change() { return this.previous == null ? null : this.value - this.previous; }
22
+
23
+ /** The change as a fraction of the previous value (0.1 is up 10%), or null. */
24
+ get changeRatio() { return this.previous ? this.change / Math.abs(this.previous) : null; }
25
+
26
+ /** As gauge data again (`{ value, target, previous, history, values }`). */
27
+ toData() {
28
+ const { value, target, previous, history, values } = this;
29
+ return { value, target, previous, history: [...history], values: values.map(v => ({ ...v })) };
30
+ }
31
+
32
+ /**
33
+ * The data part of the way (t, 0-1) from one value to another: the value,
34
+ * the target and each of several values in between (one that is new
35
+ * starts from the first value); the rest as `to` has them.
36
+ */
37
+ static between(from, to, t) {
38
+ const mix = (a, b) => (a == null || b == null ? b : a + (b - a) * t);
39
+ const data = to.toData();
40
+ data.value = mix(from.value, to.value);
41
+ data.target = mix(from.target, to.target);
42
+ data.values = to.values.map((v, i) => ({ ...v, value: mix(from.values[i]?.value ?? from.value, v.value) }));
43
+ return data;
44
+ }
45
+
46
+ static from(data, options = {}) {
47
+ const given = Array.isArray(data) ? { values: data } : (typeof data === 'object' && data !== null ? data : { value: data });
48
+ const pick = (key) => options[key] ?? given[key];
49
+ const values = pick('values') ?? [];
50
+ const history = pick('history') ?? [];
51
+ // Without a value: the first of several, else the last of the history.
52
+ const first = values.length ? (typeof values[0] === 'object' ? values[0].value : values[0]) : history.at(-1);
53
+ return new GaugeValue({
54
+ value: given.value ?? first ?? 0,
55
+ target: pick('target'),
56
+ previous: pick('previous'),
57
+ history,
58
+ values,
59
+ });
60
+ }
61
+ }
@@ -0,0 +1,14 @@
1
+ import { LinearTrack } from './LinearTrack.js';
2
+
3
+ /** A track left to right. */
4
+ export class HorizontalTrack extends LinearTrack {
5
+ point(fraction, offset = 0) {
6
+ return { x: this.x + fraction * this.length, y: this.y + this.thickness / 2 + offset };
7
+ }
8
+
9
+ rectangle(from, to, thickness) {
10
+ return { x: this.x + from * this.length, y: this.y + (this.thickness - thickness) / 2, width: (to - from) * this.length, height: thickness };
11
+ }
12
+
13
+ get center() { return this.point(0.5); }
14
+ }
@@ -0,0 +1,29 @@
1
+ import { GaugeTrack } from './GaugeTrack.js';
2
+
3
+ /**
4
+ * LinearTrack — a straight gauge track: a box `length` long and `thickness`
5
+ * across, its segments drawn as rectangles. A subclass gives the direction.
6
+ */
7
+ export class LinearTrack extends GaugeTrack {
8
+ /**
9
+ * @param {Object} options
10
+ * @param {number} options.x - The box's left
11
+ * @param {number} options.y - The box's top
12
+ * @param {number} options.length
13
+ * @param {number} options.thickness
14
+ * @param {number} [options.radius=0] - Corner radius of the drawn segments
15
+ */
16
+ constructor({ x, y, length, thickness, radius = 0 }) {
17
+ super(thickness);
18
+ if (new.target === LinearTrack) throw new TypeError('LinearTrack is abstract — use HorizontalTrack or VerticalTrack');
19
+ Object.assign(this, { x, y, length, radius });
20
+ }
21
+
22
+ /** The rectangle covering from one fraction to another, `thickness` across and centred. */
23
+ rectangle(from, to, thickness) { throw new Error(`${this.constructor.name} must implement rectangle()`); }
24
+
25
+ draw(renderer, from, to, color, { thickness = this.thickness } = {}) {
26
+ const r = this.rectangle(Math.min(from, to), Math.max(from, to), thickness);
27
+ renderer.rect(r.x, r.y, r.width, r.height, color, null, this.radius ? { rx: this.radius, ry: this.radius } : {});
28
+ }
29
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Sparkline — a small line of a series' recent values, fitted to a box:
3
+ * the first value at the left, the last at the right, the lowest at the
4
+ * bottom and the highest at the top.
5
+ */
6
+ export class Sparkline {
7
+ /**
8
+ * @param {number[]} values - At least two to draw a line
9
+ * @param {{x:number, y:number, width:number, height:number}} box
10
+ */
11
+ constructor(values, box) {
12
+ this.values = values.map(Number).filter(Number.isFinite);
13
+ this.box = box;
14
+ }
15
+
16
+ /** Each value's point in the box (none for fewer than two values). */
17
+ get points() {
18
+ const { values, box } = this;
19
+ if (values.length < 2) return [];
20
+ const lo = Math.min(...values);
21
+ const hi = Math.max(...values);
22
+ const span = (hi - lo) || 1;
23
+ // A flat series sits across the middle.
24
+ const flat = hi === lo;
25
+ return values.map((v, i) => ({
26
+ x: box.x + (i / (values.length - 1)) * box.width,
27
+ y: flat ? box.y + box.height / 2 : box.y + box.height - ((v - lo) / span) * box.height,
28
+ }));
29
+ }
30
+
31
+ /** The line as a path `d` (empty for fewer than two values). */
32
+ get d() { return this.points.map((p, i) => `${i ? 'L' : 'M'}${p.x},${p.y}`).join(' '); }
33
+
34
+ /** Draw the line and a dot on its last value. */
35
+ draw(renderer, { color = '#5352ed', width = 1.5 } = {}) {
36
+ const points = this.points;
37
+ if (!points.length) return;
38
+ renderer.path(this.d, 'none', { color, width });
39
+ const last = points.at(-1);
40
+ renderer.circle(last.x, last.y, 2.5, color);
41
+ }
42
+ }
@@ -0,0 +1,17 @@
1
+ import { LinearTrack } from './LinearTrack.js';
2
+
3
+ /** A track bottom to top. */
4
+ export class VerticalTrack extends LinearTrack {
5
+ point(fraction, offset = 0) {
6
+ return { x: this.x + this.thickness / 2 + offset, y: this.y + this.length - fraction * this.length };
7
+ }
8
+
9
+ rectangle(from, to, thickness) {
10
+ return { x: this.x + (this.thickness - thickness) / 2, y: this.y + this.length - to * this.length, width: thickness, height: (to - from) * this.length };
11
+ }
12
+
13
+ get center() { return this.point(0.5); }
14
+
15
+ /** Labels beside a vertical track start at their point. */
16
+ anchorAt() { return 'start'; }
17
+ }