@bitsandbricks/widgets 0.0.0-stage → 0.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.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -2
  3. package/dist/FitWidget.d.ts +12 -0
  4. package/dist/FitWidget.js +51 -0
  5. package/dist/TileCard.d.ts +35 -0
  6. package/dist/TileCard.js +39 -0
  7. package/dist/TimeChart.d.ts +14 -0
  8. package/dist/TimeChart.js +30 -0
  9. package/dist/WidgetBody.d.ts +4 -0
  10. package/dist/WidgetBody.js +37 -0
  11. package/dist/autoPage.d.ts +5 -0
  12. package/dist/autoPage.js +6 -0
  13. package/dist/drill.d.ts +3 -0
  14. package/dist/drill.js +4 -0
  15. package/dist/index.d.ts +22 -0
  16. package/dist/index.js +24 -0
  17. package/dist/kinds/Bars.d.ts +15 -0
  18. package/dist/kinds/Bars.js +41 -0
  19. package/dist/kinds/Columns.d.ts +19 -0
  20. package/dist/kinds/Columns.js +101 -0
  21. package/dist/kinds/Gauge.d.ts +11 -0
  22. package/dist/kinds/Gauge.js +29 -0
  23. package/dist/kinds/Graph.d.ts +36 -0
  24. package/dist/kinds/Graph.js +103 -0
  25. package/dist/kinds/Histogram.d.ts +12 -0
  26. package/dist/kinds/Histogram.js +26 -0
  27. package/dist/kinds/Pie.d.ts +12 -0
  28. package/dist/kinds/Pie.js +32 -0
  29. package/dist/kinds/Rows.d.ts +14 -0
  30. package/dist/kinds/Rows.js +81 -0
  31. package/dist/kinds/Stat.d.ts +14 -0
  32. package/dist/kinds/Stat.js +32 -0
  33. package/dist/kinds/combine.d.ts +39 -0
  34. package/dist/kinds/combine.js +161 -0
  35. package/dist/kinds/display.d.ts +64 -0
  36. package/dist/kinds/display.js +113 -0
  37. package/dist/kinds/shape.d.ts +168 -0
  38. package/dist/kinds/shape.js +296 -0
  39. package/dist/level.d.ts +18 -0
  40. package/dist/level.js +37 -0
  41. package/dist/levelReport.d.ts +15 -0
  42. package/dist/levelReport.js +2 -0
  43. package/dist/messages.d.ts +89 -0
  44. package/dist/messages.js +99 -0
  45. package/dist/styles.css +192 -0
  46. package/dist/time.d.ts +6 -0
  47. package/dist/time.js +6 -0
  48. package/dist/useBox.d.ts +5 -0
  49. package/dist/useBox.js +19 -0
  50. package/package.json +40 -3
@@ -0,0 +1,113 @@
1
+ import { createContext, useContext } from 'react';
2
+ import { PALETTE, formatValue, numberColumns } from './shape.js';
3
+ export const SORTS = ['value-desc', 'value-asc', 'name-asc', 'name-desc'];
4
+ /** The colours a series or row can be given, named in the palette's order (floorbit/dashboards.py). */
5
+ export const SERIES_COLOURS = ['green', 'cyan', 'violet', 'pink', 'orange', 'blue', 'grey'];
6
+ export const seriesColour = (c) => PALETTE[SERIES_COLOURS.indexOf(c)];
7
+ export const MAX_OVERRIDES = 10;
8
+ export const NumberStyleContext = createContext({});
9
+ /** The pane's decimals and short numbers, for the kinds that format numbers. */
10
+ export const useNumberStyle = () => useContext(NumberStyleContext);
11
+ /** The tone for a value: the highest threshold it reaches. ``max`` turns it into a share. */
12
+ export function toneAt(v, d, max) {
13
+ if (!d.thresholds?.length)
14
+ return null;
15
+ const x = d.threshold_mode === 'percent' ? (max ? (v / max) * 100 : null) : v;
16
+ if (x == null)
17
+ return null;
18
+ let tone = null;
19
+ for (const t of [...d.thresholds].sort((a, b) => a.at - b.at))
20
+ if (x >= t.at)
21
+ tone = t.tone;
22
+ return tone;
23
+ }
24
+ export function mappingFor(v, d) {
25
+ return d.mappings?.find((m) => (m.from == null || v >= m.from) && (m.to == null || v <= m.to)) ?? null;
26
+ }
27
+ const text = (v, unit, d, lang) => {
28
+ const f = formatValue(v, unit, lang, d);
29
+ return `${f.value}${f.unit ? ` ${f.unit}` : ''}`;
30
+ };
31
+ /** The widget as the pane shows it: unit, mappings, tones from thresholds, then sort and top N. */
32
+ export function applyDisplay(w, d, lang) {
33
+ switch (w.type) {
34
+ case 'stat': {
35
+ const unit = d.unit ?? w.unit;
36
+ if (typeof w.value !== 'number')
37
+ return { ...w, unit };
38
+ const m = mappingFor(w.value, d);
39
+ const tone = m?.tone ?? toneAt(w.value, d, w.max) ?? w.tone;
40
+ return { ...w, unit: m ? '' : unit, tone, text: m?.text };
41
+ }
42
+ case 'sparkline':
43
+ return d.unit != null ? { ...w, unit: d.unit } : w;
44
+ case 'series': {
45
+ const series = overridden(w.series, d.overrides, (s, o) => ({ ...s, label: o.name || s.label, ...(o.colour ? { colour: seriesColour(o.colour) } : {}) }));
46
+ return { ...w, series, unit: d.unit ?? w.unit };
47
+ }
48
+ case 'list': {
49
+ let items = overridden(w.items, d.overrides, (i, o) => ({ ...i, label: o.name || i.label, ...(o.colour ? { colour: seriesColour(o.colour) } : {}) })).map((i) => {
50
+ if (i.number == null)
51
+ return i;
52
+ const m = mappingFor(i.number, d);
53
+ const tone = m?.tone ?? toneAt(i.number, d, i.max) ?? i.tone;
54
+ const changed = m || d.unit != null || d.decimals != null || d.short;
55
+ // A value with its own max reads "21 / 24": keep that, only re-tone it.
56
+ const value = m ? m.text : changed && i.max == null ? text(i.number, d.unit ?? '', d, lang) : i.value;
57
+ return { ...i, tone, value };
58
+ });
59
+ if (d.hide_zero)
60
+ items = items.filter((i) => i.number == null || i.number !== 0);
61
+ items = sortRows(items, d.sort, (i) => i.number ?? null, (i) => i.label);
62
+ return { ...w, items: d.limit ? items.slice(0, d.limit) : items };
63
+ }
64
+ case 'status': {
65
+ const items = sortRows(w.items, d.sort?.startsWith('name') ? d.sort : undefined, () => null, (i) => i.label);
66
+ return { ...w, items: d.limit ? items.slice(0, d.limit) : items };
67
+ }
68
+ case 'table': {
69
+ // The value of a row is its last number column: labels come first.
70
+ const num = numberColumns(w).pop();
71
+ let rows = d.hide_zero && num ? w.rows.filter((r) => Number(r[num]) !== 0) : w.rows;
72
+ rows = sortRows(rows, d.sort, (r) => (num ? Number(r[num]) : null), (r) => r[w.columns[0]?.key] ?? '');
73
+ if (num && d.mappings?.length)
74
+ rows = rows.map((r) => { const m = mappingFor(Number(r[num]), d); return m ? { ...r, [num]: m.text } : r; });
75
+ return { ...w, rows: d.limit ? rows.slice(0, d.limit) : rows };
76
+ }
77
+ }
78
+ }
79
+ /** Applies the per-series settings: hidden ones go, the rest are renamed or recoloured. */
80
+ function overridden(rows, overrides, apply) {
81
+ if (!overrides?.length)
82
+ return rows;
83
+ return rows.flatMap((r) => {
84
+ const o = overrides.find((x) => x.match === r.label);
85
+ return !o ? [r] : o.hide ? [] : [apply(r, o)];
86
+ });
87
+ }
88
+ function sortRows(rows, sort, value, name) {
89
+ if (!sort)
90
+ return rows;
91
+ const dir = sort.endsWith('asc') ? 1 : -1;
92
+ const out = [...rows];
93
+ if (sort.startsWith('name'))
94
+ out.sort((a, b) => dir * name(a).localeCompare(name(b), undefined, { numeric: true }));
95
+ else
96
+ out.sort((a, b) => dir * ((value(a) ?? -Infinity) - (value(b) ?? -Infinity)));
97
+ return out;
98
+ }
99
+ /** The labels a pane can set a name, colour or hide for: a graph's series, or a list's rows. */
100
+ export function seriesLabels(w) {
101
+ if (w.type === 'series')
102
+ return w.series.map((s) => s.label);
103
+ if (w.type === 'list')
104
+ return [...new Set(w.items.map((i) => i.label))].slice(0, 100);
105
+ return [];
106
+ }
107
+ /** Which display settings mean something for this data: numbers to format and colour, rows to
108
+ * sort and cut. */
109
+ export function displaysFor(w) {
110
+ const numbers = (w.type === 'stat' && typeof w.value === 'number') || w.type === 'sparkline' || w.type === 'series'
111
+ || (w.type === 'list' && w.items.some((i) => i.number != null)) || numberColumns(w).length > 0;
112
+ return { numbers, colours: numbers, rows: w.type === 'list' || w.type === 'status' || w.type === 'table' };
113
+ }
@@ -0,0 +1,168 @@
1
+ import type { WidgetState as State, MaybeTone as Tone, Widget } from '@bitsandbricks/ui';
2
+ import type { Kind, KindPick } from '../level.js';
3
+ import type { Calc } from './combine.js';
4
+ import type { NumberStyle, Threshold } from './display.js';
5
+ /** What a widget's data can be drawn as. The first is its own kind. A stat counts anything; only
6
+ * time data draws as a graph; a gauge needs a scale and bars or a pie need numbers. */
7
+ export declare function kindsFor(w: Widget): Kind[];
8
+ /** The kind to draw: the pane's pick when the data allows it, else the data's own. */
9
+ export declare function resolveKind(w: Widget, pick?: KindPick): Kind;
10
+ /** A number for a tile: bits and bytes scale (5.2 Gbit/s), counts get thousands separators.
11
+ * ``style`` fixes the decimals or shortens big numbers (1.2k), as a pane sets it (issue #960). */
12
+ export declare function formatValue(v: number, unit?: string, lang?: string, style?: NumberStyle): {
13
+ value: string;
14
+ unit: string;
15
+ };
16
+ export interface StatData {
17
+ value: string;
18
+ unit: string;
19
+ tone: Tone;
20
+ of?: number;
21
+ }
22
+ /** One number for any shape: a stat as is, how many are up, how many rows, the latest reading. */
23
+ export declare function statOf(w: Widget, lang?: string, style?: NumberStyle): StatData;
24
+ export interface Column {
25
+ key: string;
26
+ label: string;
27
+ }
28
+ /** ``device``: the inventory device the row is about, for its glance in a large widget (#925). */
29
+ export interface Row {
30
+ cells: Record<string, string>;
31
+ state?: State;
32
+ tone?: Tone;
33
+ device?: string;
34
+ }
35
+ /** Rows for a list or table: status items worst first, so the problem is what fits. */
36
+ export declare function rowsOf(w: Widget, labels: {
37
+ name: string;
38
+ value: string;
39
+ state: string;
40
+ }): {
41
+ columns: Column[];
42
+ rows: Row[];
43
+ };
44
+ /** ``colour``: a pane's per-series setting (#960); otherwise the palette in order. */
45
+ export interface Line {
46
+ label: string;
47
+ points: [number, number][];
48
+ colour?: string;
49
+ ghost?: boolean;
50
+ }
51
+ export declare const lineColour: (l: Line, i: number) => string;
52
+ /** Lines over time. A sparkline has no times: its points are evenly spaced. */
53
+ export declare function linesOf(w: Widget): {
54
+ lines: Line[];
55
+ unit: string;
56
+ timed: boolean;
57
+ };
58
+ /** How a stat with a history moved (issue #960): against an hour before its latest sample when the
59
+ * history goes back that far, else against its first sample. ``pct`` is left out when the earlier
60
+ * value is 0; ``at`` is the earlier sample's time (unix seconds) for a timed history. */
61
+ export interface Change {
62
+ from: number;
63
+ to: number;
64
+ pct?: number;
65
+ hour: boolean;
66
+ at?: number;
67
+ }
68
+ export declare function changeOf(w: Widget): Change | null;
69
+ /** How many of each state, worst first, for a status at its small level. */
70
+ export declare function stateCounts(w: Widget): [State, number][];
71
+ export interface Segment {
72
+ label: string;
73
+ value: number;
74
+ colour: string;
75
+ }
76
+ /** One bar: its value, or (a table row) the sum of its segments, one per number column. */
77
+ export interface Part {
78
+ label: string;
79
+ value: number;
80
+ max?: number;
81
+ text: string;
82
+ colour: string;
83
+ segments?: Segment[];
84
+ }
85
+ /** How bars and lines with more than one series sit: next to each other (or over each other, for
86
+ * lines), stacked, or stacked to 100 %. */
87
+ export type Stack = 'none' | 'stacked' | 'percent';
88
+ export declare const STACKS: Stack[];
89
+ export type LineStyle = 'line' | 'area';
90
+ export declare const LINE_STYLES: LineStyle[];
91
+ /** A dashed line over each series: a straight fit over the time shown, or a rolling average. */
92
+ export type Trend = 'none' | 'linear' | 'average';
93
+ export declare const TRENDS: Trend[];
94
+ /** ``legend``: the calculations each line's legend entry shows, instead of the latest value (and
95
+ * max and average at large). */
96
+ /** ``axis``: a graph's fixed value ends and log scale (#960). */
97
+ export interface Axis {
98
+ min?: number;
99
+ max?: number;
100
+ log?: boolean;
101
+ }
102
+ /** ``spark`` and ``change``: a stat's history as a sparkline under it, and how it moved; ``text``: the
103
+ * size of the big number (issue #960). */
104
+ export interface Look {
105
+ stack?: Stack;
106
+ style?: LineStyle;
107
+ trend?: Trend;
108
+ legend?: Calc[];
109
+ thresholds?: Threshold[];
110
+ number?: NumberStyle;
111
+ axis?: Axis;
112
+ spark?: boolean;
113
+ change?: boolean;
114
+ text?: 's' | 'l';
115
+ }
116
+ /** Which look options mean something for this data drawn as this kind: stacking needs two or
117
+ * more series (or number columns), the line style needs a graph, a trend needs time. */
118
+ export type LookKey = 'stack' | 'style' | 'trend' | 'legend' | 'spark' | 'change';
119
+ export declare function looksFor(w: Widget, kind: Kind): LookKey[];
120
+ /** Columns of a table where every row holds a plain number. */
121
+ export declare function numberColumns(w: Widget): string[];
122
+ /** State colours, fixed like the dots: a theme never changes what "down" looks like. */
123
+ export declare const STATE_COLOUR: Record<State, string>;
124
+ /** Categories that are not states: accent, trace, then colours that never read as up or down. */
125
+ export declare const PALETTE: string[];
126
+ /** Numbered parts for bars and a pie: how many in each state, or a list's numbers. A list's rows
127
+ * are one measure, so bars draw them in one colour (issue #1043); a pie needs ``each`` its own. */
128
+ export declare function partsOf(w: Widget, stateLabel: (s: State) => string, lang?: string, each?: boolean): Part[];
129
+ /** A pie reads up to seven slices; the smallest rest become one "other" slice. */
130
+ export declare function slices(parts: Part[], other: string, lang?: string): Part[];
131
+ /** A stat or sparkline on its scale, for a gauge. */
132
+ export declare function scaleOf(w: Widget): {
133
+ value: number;
134
+ min: number;
135
+ max: number;
136
+ } | null;
137
+ export interface Bucket {
138
+ from: number;
139
+ to: number;
140
+ values: (number | null)[];
141
+ }
142
+ /** Time data in at most ``n`` columns: each the average of the samples in its slice of time, one
143
+ * value per line (null where a line has no sample in it). */
144
+ export declare function bucketsOf(lines: Line[], n: number): Bucket[];
145
+ /** Stacked lines: per sample of the longest line, each line's [time, bottom, top]. Lines are read
146
+ * at the nearest sample, so lines sampled at slightly different times still stack. */
147
+ export declare function stackLines(lines: Line[], mode: Stack): [number, number, number][][];
148
+ /** All the numbers a widget holds, for a histogram: a list's or table's numbers, or every sample. */
149
+ export declare function valuesOf(w: Widget): number[];
150
+ export interface Bin {
151
+ from: number;
152
+ to: number;
153
+ count: number;
154
+ }
155
+ /** Values counted in ranges of a round width (1, 2 or 5 times a power of ten), about the square
156
+ * root of the count of ranges and at most ``most``. */
157
+ export declare function binsOf(values: number[], most?: number): Bin[];
158
+ /** The trend of one line, at its own sample times. A rolling average spans about a twelfth of the
159
+ * samples (at least three); a linear fit is the least-squares line. */
160
+ export declare function trendOf(points: [number, number][], mode: Trend): [number, number][];
161
+ /** A part's tooltip: its value, its share of its own max, and each segment. */
162
+ export declare function partTip(part: Part, pct: number): string;
163
+ /** Where a tooltip sits: right of what it describes in the left half, left of it in the right
164
+ * half, so a wide tooltip never runs out of the box. */
165
+ export declare function tipAt(from: number, to: number, width: number): {
166
+ left?: number;
167
+ right?: number;
168
+ };
@@ -0,0 +1,296 @@
1
+ /** What a widget's data can be drawn as. The first is its own kind. A stat counts anything; only
2
+ * time data draws as a graph; a gauge needs a scale and bars or a pie need numbers. */
3
+ export function kindsFor(w) {
4
+ switch (w.type) {
5
+ case 'stat': return typeof w.value === 'number' && w.max != null ? ['stat', 'gauge'] : ['stat'];
6
+ case 'status': return ['status', 'stat', 'bar', 'column', 'pie', 'list', 'table'];
7
+ case 'list': return w.items.some((i) => i.number != null) ? ['list', 'bar', 'column', 'pie', 'histogram', 'stat', 'table'] : ['list', 'stat', 'table'];
8
+ case 'table': return numberColumns(w).length ? ['table', 'bar', 'column', 'histogram', 'stat', 'list'] : ['table', 'stat', 'list'];
9
+ case 'sparkline': return w.max != null ? ['graph', 'column', 'histogram', 'stat', 'gauge'] : ['graph', 'column', 'histogram', 'stat'];
10
+ case 'series': return ['graph', 'column', 'histogram', 'stat'];
11
+ default: return ['stat'];
12
+ }
13
+ }
14
+ /** The kind to draw: the pane's pick when the data allows it, else the data's own. */
15
+ export function resolveKind(w, pick = 'auto') {
16
+ const ok = kindsFor(w);
17
+ return pick !== 'auto' && ok.includes(pick) ? pick : ok[0];
18
+ }
19
+ const SI = ['', 'k', 'M', 'G', 'T'];
20
+ /** A number for a tile: bits and bytes scale (5.2 Gbit/s), counts get thousands separators.
21
+ * ``style`` fixes the decimals or shortens big numbers (1.2k), as a pane sets it (issue #960). */
22
+ export function formatValue(v, unit = '', lang, style = {}) {
23
+ const digits = (auto) => (style.decimals != null
24
+ ? { minimumFractionDigits: style.decimals, maximumFractionDigits: style.decimals }
25
+ : { maximumFractionDigits: auto });
26
+ if (/^(bit|B)(\/s)?$/.test(unit) && Math.abs(v) >= 1000) {
27
+ let i = 0;
28
+ while (Math.abs(v) >= 1000 && i < SI.length - 1) {
29
+ v /= 1000;
30
+ i++;
31
+ }
32
+ return { value: v.toLocaleString(lang, digits(v < 10 ? 1 : 0)), unit: `${SI[i]}${unit}` };
33
+ }
34
+ if (style.short && Math.abs(v) >= 1000) {
35
+ let i = 0;
36
+ while (Math.abs(v) >= 1000 && i < SI.length - 1) {
37
+ v /= 1000;
38
+ i++;
39
+ }
40
+ return { value: `${v.toLocaleString(lang, digits(Math.abs(v) < 10 ? 1 : 0))}${SI[i]}`, unit };
41
+ }
42
+ return { value: v.toLocaleString(lang, digits(Math.abs(v) < 10 ? 2 : 1)), unit };
43
+ }
44
+ const BAD = { down: 0, warn: 1, unknown: 2, up: 3 };
45
+ /** One number for any shape: a stat as is, how many are up, how many rows, the latest reading. */
46
+ export function statOf(w, lang, style = {}) {
47
+ switch (w.type) {
48
+ case 'stat':
49
+ if (w.text != null)
50
+ return { value: w.text, unit: '', tone: w.tone };
51
+ return typeof w.value === 'number' ? { ...formatValue(w.value, w.unit, lang, style), tone: w.tone } : { value: w.value, unit: w.unit, tone: w.tone };
52
+ case 'status': {
53
+ const up = w.items.filter((i) => i.state === 'up').length;
54
+ const tone = w.items.some((i) => i.state === 'down') ? 'err' : w.items.some((i) => i.state === 'warn') ? 'warn' : w.items.length ? 'ok' : '';
55
+ return { value: up.toLocaleString(lang), unit: '', tone, of: w.items.length };
56
+ }
57
+ case 'list': return { value: w.items.length.toLocaleString(lang), unit: '', tone: '' };
58
+ case 'table': return { value: w.rows.length.toLocaleString(lang), unit: '', tone: '' };
59
+ case 'sparkline': {
60
+ const v = w.value ?? w.points[w.points.length - 1];
61
+ return v == null ? { value: '–', unit: w.unit, tone: '' } : { ...formatValue(v, w.unit, lang, style), tone: '' };
62
+ }
63
+ case 'series': {
64
+ const pts = w.series[0]?.points ?? [];
65
+ const v = pts[pts.length - 1]?.[1];
66
+ return v == null ? { value: '–', unit: w.unit, tone: '' } : { ...formatValue(v, w.unit, lang, style), tone: '' };
67
+ }
68
+ }
69
+ }
70
+ /** Rows for a list or table: status items worst first, so the problem is what fits. */
71
+ export function rowsOf(w, labels) {
72
+ switch (w.type) {
73
+ case 'status':
74
+ return {
75
+ columns: [{ key: 'label', label: labels.name }, { key: 'detail', label: labels.state }],
76
+ rows: [...w.items].sort((a, b) => BAD[a.state] - BAD[b.state])
77
+ .map((i) => ({ cells: { label: i.label, detail: i.detail }, state: i.state, device: i.device })),
78
+ };
79
+ case 'list':
80
+ return {
81
+ columns: [{ key: 'label', label: labels.name }, { key: 'value', label: labels.value }],
82
+ rows: w.items.map((i) => ({ cells: { label: i.label, value: i.value }, tone: i.tone, device: i.device })),
83
+ };
84
+ case 'table':
85
+ return { columns: w.columns, rows: w.rows.map((r) => ({ cells: r })) };
86
+ default:
87
+ return { columns: [], rows: [] };
88
+ }
89
+ }
90
+ export const lineColour = (l, i) => l.colour ?? PALETTE[i % PALETTE.length];
91
+ /** Lines over time. A sparkline has no times: its points are evenly spaced. */
92
+ export function linesOf(w) {
93
+ if (w.type === 'series')
94
+ return { lines: w.series, unit: w.unit, timed: true };
95
+ if (w.type === 'sparkline')
96
+ return { lines: [{ label: w.label, points: w.points.map((v, i) => [i, v]) }], unit: w.unit, timed: false };
97
+ return { lines: [], unit: '', timed: false };
98
+ }
99
+ export function changeOf(w) {
100
+ const { lines, timed } = linesOf(w);
101
+ const pts = lines.find((l) => !l.ghost)?.points ?? [];
102
+ if (pts.length < 2)
103
+ return null;
104
+ const last = pts[pts.length - 1];
105
+ const target = last[0] - 3600;
106
+ const hour = timed && pts[0][0] <= target;
107
+ const prev = hour ? pts.reduce((a, b) => (Math.abs(b[0] - target) < Math.abs(a[0] - target) ? b : a)) : pts[0];
108
+ const to = w.type === 'sparkline' && w.value != null ? w.value : last[1];
109
+ return { from: prev[1], to, hour, ...(prev[1] ? { pct: ((to - prev[1]) / Math.abs(prev[1])) * 100 } : {}),
110
+ ...(timed ? { at: prev[0] } : {}) };
111
+ }
112
+ /** How many of each state, worst first, for a status at its small level. */
113
+ export function stateCounts(w) {
114
+ if (w.type !== 'status')
115
+ return [];
116
+ const n = {};
117
+ for (const i of w.items)
118
+ n[i.state] = (n[i.state] ?? 0) + 1;
119
+ return Object.keys(BAD).filter((s) => n[s]).map((s) => [s, n[s]]);
120
+ }
121
+ export const STACKS = ['none', 'stacked', 'percent'];
122
+ export const LINE_STYLES = ['line', 'area'];
123
+ export const TRENDS = ['none', 'linear', 'average'];
124
+ export function looksFor(w, kind) {
125
+ const timed = w.type === 'series' || w.type === 'sparkline';
126
+ const many = w.type === 'series' ? w.series.length > 1 : numberColumns(w).length > 1;
127
+ const out = [];
128
+ if (many && ['graph', 'column', 'bar'].includes(kind))
129
+ out.push('stack');
130
+ if (kind === 'graph')
131
+ out.push('style');
132
+ if (timed && (kind === 'graph' || kind === 'column'))
133
+ out.push('trend');
134
+ if (kind === 'graph')
135
+ out.push('legend');
136
+ if (timed && kind === 'stat')
137
+ out.push('spark', 'change');
138
+ return out;
139
+ }
140
+ /** Columns of a table where every row holds a plain number. */
141
+ export function numberColumns(w) {
142
+ if (w.type !== 'table' || !w.rows.length)
143
+ return [];
144
+ return w.columns.map((c) => c.key).filter((k) => w.rows.every((r) => isNumber(r[k])));
145
+ }
146
+ const isNumber = (v) => v != null && v.trim() !== '' && Number.isFinite(Number(v));
147
+ /** State colours, fixed like the dots: a theme never changes what "down" looks like. */
148
+ export const STATE_COLOUR = {
149
+ down: 'var(--bnb-err)', warn: 'var(--bnb-warn)', unknown: 'var(--bnb-off)', up: 'var(--bnb-ok)',
150
+ };
151
+ const TONE_COLOUR = { err: 'var(--bnb-err)', warn: 'var(--bnb-warn)', ok: 'var(--bnb-ok)' };
152
+ /** Categories that are not states: accent, trace, then colours that never read as up or down. */
153
+ export const PALETTE = ['var(--bnb-accent)', 'var(--bnb-info)', '#a78bfa', '#f472b6', '#fb923c', '#60a5fa', '#94a3b8'];
154
+ /** Numbered parts for bars and a pie: how many in each state, or a list's numbers. A list's rows
155
+ * are one measure, so bars draw them in one colour (issue #1043); a pie needs ``each`` its own. */
156
+ export function partsOf(w, stateLabel, lang, each = false) {
157
+ if (w.type === 'status') {
158
+ return stateCounts(w).map(([s, n]) => ({ label: stateLabel(s), value: n, text: n.toLocaleString(lang), colour: STATE_COLOUR[s] }));
159
+ }
160
+ if (w.type === 'list') {
161
+ return w.items.filter((i) => i.number != null).map((i, k) => ({
162
+ label: i.label, value: i.number, max: i.max, text: i.value || i.number.toLocaleString(lang),
163
+ colour: i.colour || (i.tone && TONE_COLOUR[i.tone]) || PALETTE[each ? k % PALETTE.length : 0],
164
+ }));
165
+ }
166
+ if (w.type === 'table') {
167
+ const nums = numberColumns(w);
168
+ if (!nums.length)
169
+ return [];
170
+ const name = w.columns.find((c) => !nums.includes(c.key))?.key;
171
+ return w.rows.map((r, k) => {
172
+ const segments = nums.map((key, i) => ({ label: w.columns.find((c) => c.key === key).label, value: Number(r[key]), colour: PALETTE[i % PALETTE.length] }));
173
+ const value = segments.reduce((a, g) => a + g.value, 0);
174
+ return { label: name ? r[name] ?? '' : String(k + 1), value, text: value.toLocaleString(lang), colour: PALETTE[0],
175
+ ...(segments.length > 1 ? { segments } : {}) };
176
+ });
177
+ }
178
+ return [];
179
+ }
180
+ /** A pie reads up to seven slices; the smallest rest become one "other" slice. */
181
+ export function slices(parts, other, lang) {
182
+ const sorted = [...parts].filter((p) => p.value > 0).sort((a, b) => b.value - a.value);
183
+ if (sorted.length <= 7)
184
+ return sorted;
185
+ const rest = sorted.slice(6).reduce((a, p) => a + p.value, 0);
186
+ return [...sorted.slice(0, 6), { label: other, value: rest, text: rest.toLocaleString(lang), colour: 'var(--bnb-faint)' }];
187
+ }
188
+ /** A stat or sparkline on its scale, for a gauge. */
189
+ export function scaleOf(w) {
190
+ if (w.type === 'stat' && typeof w.value === 'number' && w.max != null)
191
+ return { value: w.value, min: w.min ?? 0, max: w.max };
192
+ if (w.type === 'sparkline' && w.max != null) {
193
+ const v = w.value ?? w.points[w.points.length - 1];
194
+ return v == null ? null : { value: v, min: w.min ?? 0, max: w.max };
195
+ }
196
+ return null;
197
+ }
198
+ /** Time data in at most ``n`` columns: each the average of the samples in its slice of time, one
199
+ * value per line (null where a line has no sample in it). */
200
+ export function bucketsOf(lines, n) {
201
+ const all = lines.flatMap((l) => l.points);
202
+ if (!all.length || n < 1)
203
+ return [];
204
+ const t0 = Math.min(...all.map((p) => p[0]));
205
+ const t1 = Math.max(...all.map((p) => p[0]));
206
+ const count = Math.max(1, Math.min(n, Math.max(...lines.map((l) => l.points.length))));
207
+ const step = (t1 - t0) / count || 1;
208
+ const out = Array.from({ length: count }, (_, i) => ({ from: t0 + i * step, to: t0 + (i + 1) * step, values: [] }));
209
+ lines.forEach((l, li) => {
210
+ const sums = new Array(count).fill(0), ns = new Array(count).fill(0);
211
+ for (const [t, v] of l.points) {
212
+ const i = Math.min(count - 1, Math.floor((t - t0) / step));
213
+ sums[i] += v;
214
+ ns[i] += 1;
215
+ }
216
+ out.forEach((b, i) => { b.values[li] = ns[i] ? sums[i] / ns[i] : null; });
217
+ });
218
+ return out;
219
+ }
220
+ /** Stacked lines: per sample of the longest line, each line's [time, bottom, top]. Lines are read
221
+ * at the nearest sample, so lines sampled at slightly different times still stack. */
222
+ export function stackLines(lines, mode) {
223
+ if (!lines.length)
224
+ return [];
225
+ const base = lines.reduce((a, b) => (b.points.length > a.points.length ? b : a));
226
+ const at = (pts, t) => pts.length ? pts.reduce((a, b) => (Math.abs(b[0] - t) < Math.abs(a[0] - t) ? b : a))[1] : 0;
227
+ const values = base.points.map(([t]) => lines.map((l) => Math.max(0, at(l.points, t))));
228
+ return lines.map((_, li) => base.points.map(([t], k) => {
229
+ const row = values[k];
230
+ const sum = row.reduce((a, v) => a + v, 0) || 1;
231
+ const scale = mode === 'percent' ? 100 / sum : 1;
232
+ const lo = row.slice(0, li).reduce((a, v) => a + v, 0) * scale;
233
+ return [t, lo, lo + row[li] * scale];
234
+ }));
235
+ }
236
+ /** All the numbers a widget holds, for a histogram: a list's or table's numbers, or every sample. */
237
+ export function valuesOf(w) {
238
+ switch (w.type) {
239
+ case 'list': return w.items.filter((i) => i.number != null).map((i) => i.number);
240
+ case 'table': {
241
+ const k = numberColumns(w)[0];
242
+ return k ? w.rows.map((r) => Number(r[k])) : [];
243
+ }
244
+ case 'sparkline': return w.points;
245
+ case 'series': return w.series.flatMap((l) => l.points.map((p) => p[1]));
246
+ default: return [];
247
+ }
248
+ }
249
+ /** Values counted in ranges of a round width (1, 2 or 5 times a power of ten), about the square
250
+ * root of the count of ranges and at most ``most``. */
251
+ export function binsOf(values, most = 20) {
252
+ if (!values.length)
253
+ return [];
254
+ const lo = Math.min(...values), hi = Math.max(...values);
255
+ if (lo === hi)
256
+ return [{ from: lo, to: hi, count: values.length }];
257
+ const want = Math.max(2, Math.min(most, Math.ceil(Math.sqrt(values.length))));
258
+ const raw = (hi - lo) / want;
259
+ const mag = 10 ** Math.floor(Math.log10(raw));
260
+ const step = [1, 2, 5, 10].map((f) => f * mag).find((x) => x >= raw);
261
+ const start = Math.floor(lo / step) * step;
262
+ const n = Math.max(1, Math.ceil((hi - start) / step + 1e-9));
263
+ const bins = Array.from({ length: n }, (_, i) => ({ from: start + i * step, to: start + (i + 1) * step, count: 0 }));
264
+ for (const v of values)
265
+ bins[Math.min(n - 1, Math.floor((v - start) / step))].count++;
266
+ return bins;
267
+ }
268
+ /** The trend of one line, at its own sample times. A rolling average spans about a twelfth of the
269
+ * samples (at least three); a linear fit is the least-squares line. */
270
+ export function trendOf(points, mode) {
271
+ if (mode === 'none' || points.length < 2)
272
+ return [];
273
+ if (mode === 'average') {
274
+ const half = Math.max(1, Math.round(points.length / 24));
275
+ return points.map(([t], i) => {
276
+ const win = points.slice(Math.max(0, i - half), i + half + 1);
277
+ return [t, win.reduce((a, p) => a + p[1], 0) / win.length];
278
+ });
279
+ }
280
+ const n = points.length;
281
+ const mx = points.reduce((a, p) => a + p[0], 0) / n;
282
+ const my = points.reduce((a, p) => a + p[1], 0) / n;
283
+ const sxx = points.reduce((a, p) => a + (p[0] - mx) ** 2, 0);
284
+ const slope = sxx ? points.reduce((a, p) => a + (p[0] - mx) * (p[1] - my), 0) / sxx : 0;
285
+ return [points[0], points[n - 1]].map(([t]) => [t, my + slope * (t - mx)]);
286
+ }
287
+ /** A part's tooltip: its value, its share of its own max, and each segment. */
288
+ export function partTip(part, pct) {
289
+ const head = part.max != null ? `${part.label}: ${part.text} (${Math.round(pct)} %)` : `${part.label}: ${part.text}`;
290
+ return part.segments ? `${head}\n${part.segments.map((g) => `${g.label}: ${g.value}`).join('\n')}` : head;
291
+ }
292
+ /** Where a tooltip sits: right of what it describes in the left half, left of it in the right
293
+ * half, so a wide tooltip never runs out of the box. */
294
+ export function tipAt(from, to, width) {
295
+ return to <= width / 2 ? { left: Math.max(0, to) } : { right: Math.max(0, width - from) };
296
+ }
@@ -0,0 +1,18 @@
1
+ /** Widget levels (issue #924): the same data drawn small (a number and a state), medium (a short
2
+ * list or a graph) or large (the details), picked from the size of the box it sits in. Any box
3
+ * size works; these are only where each kind starts to read well. */
4
+ export type Level = 's' | 'm' | 'l';
5
+ export type LevelPin = 'auto' | Level;
6
+ export declare const LEVEL_PINS: LevelPin[];
7
+ export type Kind = 'stat' | 'status' | 'graph' | 'table' | 'list' | 'gauge' | 'bar' | 'column' | 'histogram' | 'pie';
8
+ export type KindPick = 'auto' | Kind;
9
+ export declare const KIND_PICKS: KindPick[];
10
+ /** Below this box (px) even the small level is cut off: the editor warns (#928). */
11
+ export declare const SMALL_MIN: [number, number];
12
+ export declare const tooSmall: (w: number, h: number) => boolean;
13
+ /** The level for a box of ``w`` × ``h`` px, unless the pane pins one. */
14
+ export declare function pickLevel(kind: Kind, w: number, h: number, pin?: LevelPin): Level;
15
+ /** One list or table row, in px: what "rows that fit" counts with. */
16
+ export declare const ROW_H = 28;
17
+ /** Rows that fit ``h`` px after ``reserve`` px of head and footer, at least one. */
18
+ export declare const rowsThatFit: (h: number, reserve?: number) => number;
package/dist/level.js ADDED
@@ -0,0 +1,37 @@
1
+ /** Widget levels (issue #924): the same data drawn small (a number and a state), medium (a short
2
+ * list or a graph) or large (the details), picked from the size of the box it sits in. Any box
3
+ * size works; these are only where each kind starts to read well. */
4
+ export const LEVEL_PINS = ['auto', 's', 'm', 'l'];
5
+ export const KIND_PICKS = ['auto', 'stat', 'gauge', 'status', 'list', 'table', 'bar', 'column', 'histogram', 'pie', 'graph'];
6
+ /** Smallest box in px (width, height) for medium and for large. Roughly 3×2 and 6×3 cells on the
7
+ * 12-column grid of a 1080p screen, the thresholds Mike agreed on. */
8
+ const FLOOR = {
9
+ stat: { m: [240, 150], l: [480, 300] },
10
+ status: { m: [220, 120], l: [460, 280] },
11
+ list: { m: [220, 120], l: [460, 280] },
12
+ graph: { m: [260, 130], l: [520, 280] },
13
+ table: { m: [300, 150], l: [560, 280] },
14
+ gauge: { m: [200, 150], l: [420, 300] },
15
+ bar: { m: [240, 120], l: [480, 280] },
16
+ column: { m: [240, 140], l: [480, 280] },
17
+ histogram: { m: [240, 140], l: [480, 280] },
18
+ pie: { m: [280, 160], l: [480, 300] },
19
+ };
20
+ /** Below this box (px) even the small level is cut off: the editor warns (#928). */
21
+ export const SMALL_MIN = [110, 56];
22
+ export const tooSmall = (w, h) => w < SMALL_MIN[0] || h < SMALL_MIN[1];
23
+ /** The level for a box of ``w`` × ``h`` px, unless the pane pins one. */
24
+ export function pickLevel(kind, w, h, pin = 'auto') {
25
+ if (pin !== 'auto')
26
+ return pin;
27
+ const f = FLOOR[kind];
28
+ if (w >= f.l[0] && h >= f.l[1])
29
+ return 'l';
30
+ if (w >= f.m[0] && h >= f.m[1])
31
+ return 'm';
32
+ return 's';
33
+ }
34
+ /** One list or table row, in px: what "rows that fit" counts with. */
35
+ export const ROW_H = 28;
36
+ /** Rows that fit ``h`` px after ``reserve`` px of head and footer, at least one. */
37
+ export const rowsThatFit = (h, reserve = 0) => Math.max(1, Math.floor((h - reserve) / ROW_H));
@@ -0,0 +1,15 @@
1
+ import type { Level } from './level.js';
2
+ /** In the dashboard editor, a widget tells its pane how it fits (issue #928): the level it drew at (and whether the box is too small even for that),
3
+ * and for a list how many of its rows show. Null everywhere else. */
4
+ export interface FitReport {
5
+ /** ``tight``: the box is below what even small needs. */
6
+ level: (level: Level, tight: boolean) => void;
7
+ rows: (shown: number, total: number) => void;
8
+ }
9
+ /** How the picked pane draws, for the editor's settings panel (#928). ``rows``: shown and total for a cut list. */
10
+ export interface PaneFit {
11
+ level: Level;
12
+ tight: boolean;
13
+ rows: [number, number] | null;
14
+ }
15
+ export declare const LevelReport: import("react").Context<FitReport | null>;
@@ -0,0 +1,2 @@
1
+ import { createContext } from 'react';
2
+ export const LevelReport = createContext(null);