@joniguerini/lume 0.0.0-stage → 1.9.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/LICENSE +25 -0
- package/README.md +62 -2
- package/base.css +165 -0
- package/bin/lumeui.mjs +163 -0
- package/components/alert.css +156 -0
- package/components/banner.css +98 -0
- package/components/button.css +291 -0
- package/components/calendar.css +532 -0
- package/components/carousel.css +175 -0
- package/components/chart.css +813 -0
- package/components/chat.css +670 -0
- package/components/checkbox.css +212 -0
- package/components/chip.css +224 -0
- package/components/code.css +36 -0
- package/components/color-picker.css +192 -0
- package/components/command.css +148 -0
- package/components/content.css +211 -0
- package/components/editor.css +174 -0
- package/components/feedback.css +320 -0
- package/components/filters.css +103 -0
- package/components/form.css +455 -0
- package/components/image-viewer.css +237 -0
- package/components/layers.css +138 -0
- package/components/link.css +87 -0
- package/components/loading.css +260 -0
- package/components/menu.css +180 -0
- package/components/modal.css +209 -0
- package/components/navigation.css +507 -0
- package/components/notifications.css +186 -0
- package/components/number-field.css +52 -0
- package/components/otp.css +119 -0
- package/components/panel.css +208 -0
- package/components/picker.css +207 -0
- package/components/rating.css +143 -0
- package/components/resizable.css +173 -0
- package/components/scrollbar.css +110 -0
- package/components/select.css +477 -0
- package/components/shell.css +837 -0
- package/components/slider.css +189 -0
- package/components/sortable.css +287 -0
- package/components/surfaces.css +182 -0
- package/components/switch.css +115 -0
- package/components/table.css +228 -0
- package/components/tabs.css +190 -0
- package/components/tags.css +83 -0
- package/components/toast.css +164 -0
- package/components/toolbar.css +80 -0
- package/components/upload.css +181 -0
- package/ds.css +48 -0
- package/fonts/Geist-LICENSE.txt +92 -0
- package/fonts/Geist-Variable.woff2 +0 -0
- package/fonts/GeistSerif-Regular.woff2 +0 -0
- package/fonts/JetBrainsMono-LICENSE.txt +93 -0
- package/fonts/JetBrainsMono-Variable.woff2 +0 -0
- package/fonts.css +29 -0
- package/icons/icons.d.ts +5 -0
- package/icons/icons.js +266 -0
- package/js/back-to-top.d.ts +2 -0
- package/js/back-to-top.js +62 -0
- package/js/banner.js +87 -0
- package/js/calendar.d.ts +3 -0
- package/js/calendar.js +472 -0
- package/js/carousel.d.ts +2 -0
- package/js/carousel.js +258 -0
- package/js/charts/bar.js +361 -0
- package/js/charts/core.js +604 -0
- package/js/charts/donut.js +206 -0
- package/js/charts/figures.js +97 -0
- package/js/charts/heatmap.js +410 -0
- package/js/charts/line.js +268 -0
- package/js/charts/scatter.js +211 -0
- package/js/charts.d.ts +12 -0
- package/js/charts.js +27 -0
- package/js/code-block.d.ts +3 -0
- package/js/code-block.js +32 -0
- package/js/color-picker.d.ts +4 -0
- package/js/color-picker.js +448 -0
- package/js/command-palette.js +233 -0
- package/js/composer.js +573 -0
- package/js/context-menu.d.ts +2 -0
- package/js/context-menu.js +154 -0
- package/js/date-picker.d.ts +2 -0
- package/js/date-picker.js +430 -0
- package/js/drawer.js +48 -0
- package/js/editor.d.ts +5 -0
- package/js/editor.js +615 -0
- package/js/field-support.js +77 -0
- package/js/file-upload.d.ts +2 -0
- package/js/file-upload.js +230 -0
- package/js/filters.js +266 -0
- package/js/form.d.ts +2 -0
- package/js/form.js +409 -0
- package/js/i18n.d.ts +14 -0
- package/js/i18n.js +83 -0
- package/js/image-viewer.d.ts +4 -0
- package/js/image-viewer.js +275 -0
- package/js/menu.d.ts +4 -0
- package/js/menu.js +237 -0
- package/js/messages.js +908 -0
- package/js/modal.d.ts +7 -0
- package/js/modal.js +183 -0
- package/js/notifications.d.ts +4 -0
- package/js/notifications.js +204 -0
- package/js/number-field.d.ts +2 -0
- package/js/number-field.js +175 -0
- package/js/otp-field.d.ts +2 -0
- package/js/otp-field.js +107 -0
- package/js/pagination.d.ts +3 -0
- package/js/pagination.js +143 -0
- package/js/popover.d.ts +2 -0
- package/js/popover.js +155 -0
- package/js/progress-ring.js +48 -0
- package/js/rating.d.ts +3 -0
- package/js/rating.js +130 -0
- package/js/resizable.d.ts +2 -0
- package/js/resizable.js +311 -0
- package/js/scrollbar.d.ts +2 -0
- package/js/scrollbar.js +273 -0
- package/js/segmented.js +60 -0
- package/js/select.d.ts +3 -0
- package/js/select.js +784 -0
- package/js/shell.d.ts +6 -0
- package/js/shell.js +373 -0
- package/js/slider.d.ts +2 -0
- package/js/slider.js +89 -0
- package/js/sortable.d.ts +5 -0
- package/js/sortable.js +463 -0
- package/js/stepper.d.ts +2 -0
- package/js/stepper.js +72 -0
- package/js/tabs.js +99 -0
- package/js/tag-field.d.ts +2 -0
- package/js/tag-field.js +177 -0
- package/js/theme.d.ts +9 -0
- package/js/theme.js +114 -0
- package/js/time-picker.d.ts +2 -0
- package/js/time-picker.js +279 -0
- package/js/toast.d.ts +17 -0
- package/js/toast.js +171 -0
- package/js/toolbar.d.ts +2 -0
- package/js/toolbar.js +107 -0
- package/js/tooltip.d.ts +2 -0
- package/js/tooltip.js +208 -0
- package/js/tree.d.ts +2 -0
- package/js/tree.js +168 -0
- package/lume.css +11574 -0
- package/lume.d.ts +104 -0
- package/lume.js +67 -0
- package/package.json +66 -4
- package/react/Alert.d.ts +24 -0
- package/react/Alert.js +21 -0
- package/react/AppShell.d.ts +67 -0
- package/react/AppShell.js +94 -0
- package/react/Avatar.d.ts +39 -0
- package/react/Avatar.js +40 -0
- package/react/Badge.d.ts +17 -0
- package/react/Badge.js +10 -0
- package/react/Button.d.ts +32 -0
- package/react/Button.js +17 -0
- package/react/Calendar.d.ts +48 -0
- package/react/Calendar.js +67 -0
- package/react/Carousel.d.ts +30 -0
- package/react/Carousel.js +38 -0
- package/react/Charts.d.ts +186 -0
- package/react/Charts.js +58 -0
- package/react/Chip.d.ts +34 -0
- package/react/Chip.js +26 -0
- package/react/Choice.d.ts +72 -0
- package/react/Choice.js +51 -0
- package/react/ColorPicker.d.ts +43 -0
- package/react/ColorPicker.js +73 -0
- package/react/Content.d.ts +58 -0
- package/react/Content.js +42 -0
- package/react/Controls.d.ts +97 -0
- package/react/Controls.js +118 -0
- package/react/Editor.d.ts +28 -0
- package/react/Editor.js +57 -0
- package/react/Field.d.ts +90 -0
- package/react/Field.js +65 -0
- package/react/Form.d.ts +36 -0
- package/react/Form.js +45 -0
- package/react/Icon.d.ts +13 -0
- package/react/Icon.js +8 -0
- package/react/IconButton.d.ts +19 -0
- package/react/IconButton.js +12 -0
- package/react/ImageViewer.d.ts +20 -0
- package/react/ImageViewer.js +22 -0
- package/react/InlineAction.d.ts +15 -0
- package/react/InlineAction.js +12 -0
- package/react/Layers.d.ts +118 -0
- package/react/Layers.js +115 -0
- package/react/Link.d.ts +32 -0
- package/react/Link.js +26 -0
- package/react/Loading.d.ts +67 -0
- package/react/Loading.js +49 -0
- package/react/Navigation.d.ts +181 -0
- package/react/Navigation.js +197 -0
- package/react/Notices.d.ts +43 -0
- package/react/Notices.js +89 -0
- package/react/Panel.d.ts +57 -0
- package/react/Panel.js +33 -0
- package/react/Pickers.d.ts +83 -0
- package/react/Pickers.js +70 -0
- package/react/Rating.d.ts +39 -0
- package/react/Rating.js +41 -0
- package/react/Resizable.d.ts +44 -0
- package/react/Resizable.js +30 -0
- package/react/Select.d.ts +53 -0
- package/react/Select.js +79 -0
- package/react/Sortable.d.ts +52 -0
- package/react/Sortable.js +113 -0
- package/react/Table.d.ts +60 -0
- package/react/Table.js +34 -0
- package/react/Toolbar.d.ts +45 -0
- package/react/Toolbar.js +45 -0
- package/react/cx.d.ts +2 -0
- package/react/cx.js +5 -0
- package/react/icon-names.d.ts +1 -0
- package/react/icon-names.js +2 -0
- package/react/index.d.ts +42 -0
- package/react/index.js +52 -0
- package/react/useController.d.ts +8 -0
- package/react/useController.js +16 -0
- package/react/useLocale.d.ts +5 -0
- package/react/useLocale.js +15 -0
- package/tokens.css +739 -0
- package/tokens.js +4911 -0
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lume — gráficos: núcleo compartilhado.
|
|
3
|
+
*
|
|
4
|
+
* Tudo o que os gráficos têm em comum: formatação de números (pt-BR), escalas, cores por papel,
|
|
5
|
+
* medição de texto, a moldura (<figure> com título, legenda, tooltip, tabela e região ao vivo)
|
|
6
|
+
* e a camada de interação (ponteiro + teclado).
|
|
7
|
+
*
|
|
8
|
+
* Os gráficos em si ficam em bar.js, line.js, donut.js, heatmap.js, scatter.js e figures.js.
|
|
9
|
+
*/
|
|
10
|
+
import { icon } from '../../icons/icons.js';
|
|
11
|
+
import { locale, msg } from '../i18n.js';
|
|
12
|
+
|
|
13
|
+
let uid = 0;
|
|
14
|
+
export const nextId = (prefix = 'chart') => `ds-${prefix}-${++uid}`;
|
|
15
|
+
|
|
16
|
+
export const escapeHtml = (s) =>
|
|
17
|
+
String(s ?? '')
|
|
18
|
+
.replace(/&/g, '&')
|
|
19
|
+
.replace(/</g, '<')
|
|
20
|
+
.replace(/>/g, '>')
|
|
21
|
+
.replace(/"/g, '"');
|
|
22
|
+
|
|
23
|
+
export const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
|
|
24
|
+
export const round = (n, d = 2) => Math.round(n * 10 ** d) / 10 ** d;
|
|
25
|
+
export const reducedMotion = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
26
|
+
|
|
27
|
+
/* ───────── Números ───────── */
|
|
28
|
+
|
|
29
|
+
// no idioma atual: o gráfico pega o formato quando é desenhado (trocar o idioma redesenha a página)
|
|
30
|
+
const NF = (options) => new Intl.NumberFormat(locale(), options);
|
|
31
|
+
|
|
32
|
+
const byLocale = new Map();
|
|
33
|
+
function presets() {
|
|
34
|
+
if (!byLocale.has(locale())) {
|
|
35
|
+
const p = {
|
|
36
|
+
number: NF({ maximumFractionDigits: 1 }).format,
|
|
37
|
+
integer: NF({ maximumFractionDigits: 0 }).format,
|
|
38
|
+
compact: NF({ notation: 'compact', maximumFractionDigits: 1 }).format,
|
|
39
|
+
percent: NF({ style: 'percent', maximumFractionDigits: 1 }).format,
|
|
40
|
+
currency: NF({ style: 'currency', currency: 'BRL', currencyDisplay: 'narrowSymbol', maximumFractionDigits: 0 }).format,
|
|
41
|
+
'currency-compact': NF({ style: 'currency', currency: 'BRL', currencyDisplay: 'narrowSymbol', notation: 'compact', maximumFractionDigits: 1 }).format,
|
|
42
|
+
};
|
|
43
|
+
const axis = { percent: NF({ style: 'percent', maximumFractionDigits: 0 }).format, currency: p['currency-compact'], 'currency-compact': p['currency-compact'] };
|
|
44
|
+
byLocale.set(locale(), { p, axis });
|
|
45
|
+
}
|
|
46
|
+
return byLocale.get(locale());
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Formatação de valores: um preset ('number', 'integer', 'compact', 'percent' — razão 0–1 —,
|
|
51
|
+
* 'currency', 'currency-compact'), opções de Intl.NumberFormat ou uma função.
|
|
52
|
+
*/
|
|
53
|
+
export function formatter(format = 'number') {
|
|
54
|
+
if (typeof format === 'function') return format;
|
|
55
|
+
if (format && typeof format === 'object') return NF(format).format;
|
|
56
|
+
const { p } = presets();
|
|
57
|
+
return p[format] ?? p.number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Eixos arredondam e compactam a partir de mil (0 · 1 mil · 2 mil). */
|
|
61
|
+
export function axisFormatter(format = 'number', axisFormat) {
|
|
62
|
+
if (axisFormat) return formatter(axisFormat);
|
|
63
|
+
if (typeof format === 'function' || (format && typeof format === 'object')) return formatter(format);
|
|
64
|
+
const { p, axis } = presets();
|
|
65
|
+
return axis[format] ?? p.compact;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/* ───────── Escalas ───────── */
|
|
69
|
+
|
|
70
|
+
/** Marcas "redondas" para o eixo: 0, 25, 50… ou 0, 2 mil, 4 mil… */
|
|
71
|
+
export function niceTicks(min, max, count = 5) {
|
|
72
|
+
if (!Number.isFinite(min) || !Number.isFinite(max)) return { min: 0, max: 1, step: 1, ticks: [0, 1] };
|
|
73
|
+
if (min === max) {
|
|
74
|
+
if (min === 0) max = 1;
|
|
75
|
+
else if (min > 0) min = 0;
|
|
76
|
+
else max = 0;
|
|
77
|
+
}
|
|
78
|
+
const raw = (max - min) / Math.max(1, count);
|
|
79
|
+
const mag = 10 ** Math.floor(Math.log10(raw));
|
|
80
|
+
const norm = raw / mag;
|
|
81
|
+
const step = (norm > 5 ? 10 : norm > 2.5 ? 5 : norm > 2 ? 2.5 : norm > 1 ? 2 : 1) * mag;
|
|
82
|
+
const lo = Math.floor(min / step + 1e-9) * step;
|
|
83
|
+
const hi = Math.ceil(max / step - 1e-9) * step;
|
|
84
|
+
const ticks = [];
|
|
85
|
+
for (let v = lo; v <= hi + step / 2; v += step) ticks.push(round(v, 10));
|
|
86
|
+
return { min: lo, max: hi, step, ticks };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export const linear = (d0, d1, r0, r1) => {
|
|
90
|
+
const k = d1 === d0 ? 0 : (r1 - r0) / (d1 - d0);
|
|
91
|
+
return (v) => r0 + (v - d0) * k;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/* ───────── Cores (sempre por papel, nunca por posição na tela) ───────── */
|
|
95
|
+
|
|
96
|
+
/** Status (bom/ruim) usa a escala reservada dos gráficos — sempre com ícone e rótulo. */
|
|
97
|
+
const STATUS = {
|
|
98
|
+
success: 'var(--ds-color-chart-status-good)',
|
|
99
|
+
good: 'var(--ds-color-chart-status-good)',
|
|
100
|
+
warning: 'var(--ds-color-chart-status-warning)',
|
|
101
|
+
danger: 'var(--ds-color-chart-status-critical)',
|
|
102
|
+
critical: 'var(--ds-color-chart-status-critical)',
|
|
103
|
+
info: 'var(--ds-color-info-solid)',
|
|
104
|
+
};
|
|
105
|
+
let warnedPalette = false;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* color: número do slot (1–8), 'muted' | 'other', 'success' | 'warning' | 'danger' | 'info' (status),
|
|
109
|
+
* 'seq-N' | 'ord-N' | 'div-N' ou qualquer cor CSS. Sem cor, a série usa o slot da sua posição
|
|
110
|
+
* original — então esconder uma série não repinta as outras. Da 9ª em diante: 'other', nunca um tom novo.
|
|
111
|
+
*/
|
|
112
|
+
export function paint(color, index = 0) {
|
|
113
|
+
if (color == null) {
|
|
114
|
+
if (index < 8) return `var(--ds-color-chart-series-${index + 1})`;
|
|
115
|
+
if (!warnedPalette) {
|
|
116
|
+
warnedPalette = true;
|
|
117
|
+
console.warn(`[Lume] ${msg('chart.tooManySeries')}`);
|
|
118
|
+
}
|
|
119
|
+
return 'var(--ds-color-chart-other)';
|
|
120
|
+
}
|
|
121
|
+
if (typeof color === 'number') return `var(--ds-color-chart-series-${clamp(color, 1, 8)})`;
|
|
122
|
+
if (color === 'muted' || color === 'other') return `var(--ds-color-chart-${color})`;
|
|
123
|
+
if (STATUS[color]) return STATUS[color];
|
|
124
|
+
if (/^(seq|ord|div)-\d$/.test(color)) return `var(--ds-color-chart-${color})`;
|
|
125
|
+
return color;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/* ───────── Texto ───────── */
|
|
129
|
+
|
|
130
|
+
export const FONTS = {
|
|
131
|
+
tick: '400 12px Geist, system-ui, sans-serif',
|
|
132
|
+
label: '500 13px Geist, system-ui, sans-serif',
|
|
133
|
+
value: '600 12px Geist, system-ui, sans-serif',
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
let ctx;
|
|
137
|
+
export function textWidth(text, font = FONTS.tick) {
|
|
138
|
+
ctx ??= document.createElement('canvas').getContext('2d');
|
|
139
|
+
ctx.font = font;
|
|
140
|
+
return ctx.measureText(String(text)).width;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Corta o texto com reticências para caber em `max` px. */
|
|
144
|
+
export function fitText(text, max, font = FONTS.label) {
|
|
145
|
+
const s = String(text);
|
|
146
|
+
if (textWidth(s, font) <= max) return s;
|
|
147
|
+
let lo = 0;
|
|
148
|
+
let hi = s.length;
|
|
149
|
+
while (lo < hi) {
|
|
150
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
151
|
+
if (textWidth(`${s.slice(0, mid)}…`, font) <= max) lo = mid;
|
|
152
|
+
else hi = mid - 1;
|
|
153
|
+
}
|
|
154
|
+
return lo ? `${s.slice(0, lo).trimEnd()}…` : '';
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** De quantos em quantos rótulos mostrar para que não colidam. */
|
|
158
|
+
export function labelStep(labels, band, font = FONTS.tick, pad = 12) {
|
|
159
|
+
const widest = Math.max(0, ...labels.map((l) => textWidth(l, font)));
|
|
160
|
+
return Math.max(1, Math.ceil((widest + pad) / Math.max(1, band)));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/* ───────── SVG ───────── */
|
|
164
|
+
|
|
165
|
+
export function attrs(o) {
|
|
166
|
+
return Object.entries(o)
|
|
167
|
+
.filter(([, v]) => v !== undefined && v !== null && v !== false)
|
|
168
|
+
.map(([k, v]) => (v === true ? k : `${k}="${escapeHtml(v)}"`))
|
|
169
|
+
.join(' ');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export const tag = (name, o = {}, children) => (children === undefined ? `<${name} ${attrs(o)}/>` : `<${name} ${attrs(o)}>${children}</${name}>`);
|
|
173
|
+
|
|
174
|
+
/** Retângulo com a ponta de dados arredondada e a base reta. end: 'top' | 'bottom' | 'right' | 'left' | 'none'. */
|
|
175
|
+
export function barPath(x, y, w, h, end = 'top', radius = 4) {
|
|
176
|
+
if (w <= 0 || h <= 0) return '';
|
|
177
|
+
const vertical = end === 'top' || end === 'bottom';
|
|
178
|
+
const r = end === 'none' ? 0 : Math.max(0, Math.min(radius, vertical ? w / 2 : h / 2, vertical ? h : w));
|
|
179
|
+
const f = (n) => round(n, 2);
|
|
180
|
+
const [x0, y0, x1, y1] = [f(x), f(y), f(x + w), f(y + h)];
|
|
181
|
+
if (!r) return `M${x0} ${y0}H${x1}V${y1}H${x0}Z`;
|
|
182
|
+
const a = (tx, ty, sweep = 1) => `A${f(r)} ${f(r)} 0 0 ${sweep} ${f(tx)} ${f(ty)}`;
|
|
183
|
+
switch (end) {
|
|
184
|
+
case 'top':
|
|
185
|
+
return `M${x0} ${y1}V${f(y + r)}${a(x + r, y)}H${f(x + w - r)}${a(x + w, y + r)}V${y1}Z`;
|
|
186
|
+
case 'bottom':
|
|
187
|
+
return `M${x0} ${y0}V${f(y + h - r)}${a(x + r, y + h, 0)}H${f(x + w - r)}${a(x + w, y + h - r, 0)}V${y0}Z`;
|
|
188
|
+
case 'right':
|
|
189
|
+
return `M${x0} ${y0}H${f(x + w - r)}${a(x + w, y + r)}V${f(y + h - r)}${a(x + w - r, y + h)}H${x0}Z`;
|
|
190
|
+
case 'left':
|
|
191
|
+
return `M${x1} ${y0}H${f(x + r)}${a(x, y + r, 0)}V${f(y + h - r)}${a(x + r, y + h, 0)}H${x1}Z`;
|
|
192
|
+
default:
|
|
193
|
+
return `M${x0} ${y0}H${x1}V${y1}H${x0}Z`;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Curva monotônica (Fritsch–Carlson): suaviza sem inventar picos entre os pontos. */
|
|
198
|
+
export function monotonePath(pts) {
|
|
199
|
+
const n = pts.length;
|
|
200
|
+
if (n < 3) return linePath(pts);
|
|
201
|
+
const dx = [];
|
|
202
|
+
const m = [];
|
|
203
|
+
for (let i = 0; i < n - 1; i++) {
|
|
204
|
+
dx[i] = pts[i + 1][0] - pts[i][0];
|
|
205
|
+
m[i] = (pts[i + 1][1] - pts[i][1]) / (dx[i] || 1);
|
|
206
|
+
}
|
|
207
|
+
const t = [m[0]];
|
|
208
|
+
for (let i = 1; i < n - 1; i++) t[i] = m[i - 1] * m[i] <= 0 ? 0 : (3 * (dx[i - 1] + dx[i])) / ((2 * dx[i] + dx[i - 1]) / m[i - 1] + (dx[i] + 2 * dx[i - 1]) / m[i]);
|
|
209
|
+
t[n - 1] = m[n - 2];
|
|
210
|
+
const f = (v) => round(v, 2);
|
|
211
|
+
let d = `M${f(pts[0][0])} ${f(pts[0][1])}`;
|
|
212
|
+
for (let i = 0; i < n - 1; i++) {
|
|
213
|
+
const h = dx[i] / 3;
|
|
214
|
+
d += `C${f(pts[i][0] + h)} ${f(pts[i][1] + t[i] * h)} ${f(pts[i + 1][0] - h)} ${f(pts[i + 1][1] - t[i + 1] * h)} ${f(pts[i + 1][0])} ${f(pts[i + 1][1])}`;
|
|
215
|
+
}
|
|
216
|
+
return d;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export const linePath = (pts) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${round(x, 2)} ${round(y, 2)}`).join('');
|
|
220
|
+
|
|
221
|
+
/** Divide uma série nos trechos sem lacunas (valores nulos quebram a linha). */
|
|
222
|
+
export function segments(points) {
|
|
223
|
+
const out = [];
|
|
224
|
+
let cur = [];
|
|
225
|
+
for (const p of points) {
|
|
226
|
+
if (p == null) {
|
|
227
|
+
if (cur.length) out.push(cur);
|
|
228
|
+
cur = [];
|
|
229
|
+
} else cur.push(p);
|
|
230
|
+
}
|
|
231
|
+
if (cur.length) out.push(cur);
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/* Textura: o canal de reserva para daltonismo total, impressão e alto contraste. Só 45° e 135°. */
|
|
236
|
+
export function texturePatterns(id, colors) {
|
|
237
|
+
return colors
|
|
238
|
+
.map((c, i) => {
|
|
239
|
+
const angle = i % 2 ? 135 : 45;
|
|
240
|
+
const gap = [4, 4, 6, 6][i % 4];
|
|
241
|
+
return `<pattern id="${id}-t${i}" patternUnits="userSpaceOnUse" width="${gap}" height="${gap}" patternTransform="rotate(${angle})">
|
|
242
|
+
<rect width="${gap}" height="${gap}" style="fill:${c}"/><line x1="0" y1="0" x2="0" y2="${gap}" class="ds-chart__hatch"/></pattern>`;
|
|
243
|
+
})
|
|
244
|
+
.join('');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/* ───────── Moldura ───────── */
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Monta a <figure> do gráfico dentro de `host`.
|
|
252
|
+
* options: { title, subtitle, label, card, table (true), empty, height }
|
|
253
|
+
*/
|
|
254
|
+
export function createFrame(host, options, { kind, describe: summary } = {}) {
|
|
255
|
+
const id = nextId(kind);
|
|
256
|
+
const figure = document.createElement('figure');
|
|
257
|
+
figure.className = ['ds-chart', options.card && 'ds-chart--card', options.className].filter(Boolean).join(' ');
|
|
258
|
+
figure.dataset.kind = kind;
|
|
259
|
+
if (options.texture) figure.dataset.texture = '';
|
|
260
|
+
|
|
261
|
+
const hasHead = options.title || options.subtitle || options.table !== false || options.actions;
|
|
262
|
+
figure.innerHTML = `
|
|
263
|
+
${
|
|
264
|
+
hasHead
|
|
265
|
+
? `<figcaption class="ds-chart__head">
|
|
266
|
+
<div class="ds-chart__titles">
|
|
267
|
+
${options.title ? `<p class="ds-chart__title" id="${id}-title">${escapeHtml(options.title)}</p>` : ''}
|
|
268
|
+
${options.subtitle ? `<p class="ds-chart__subtitle">${escapeHtml(options.subtitle)}</p>` : ''}
|
|
269
|
+
</div>
|
|
270
|
+
<div class="ds-chart__actions">
|
|
271
|
+
${options.actions ?? ''}
|
|
272
|
+
${
|
|
273
|
+
options.table !== false
|
|
274
|
+
? `<button type="button" class="ds-icon-btn ds-icon-btn--sm ds-icon-btn--muted ds-chart__toggle" data-chart-toggle aria-pressed="false" aria-label="${msg('chart.asTable')}" data-ds-tooltip="${msg('chart.asTable')}">${icon('table', { size: 16 })}</button>`
|
|
275
|
+
: ''
|
|
276
|
+
}
|
|
277
|
+
</div>
|
|
278
|
+
</figcaption>`
|
|
279
|
+
: ''
|
|
280
|
+
}
|
|
281
|
+
<div class="ds-chart__legend" data-legend hidden></div>
|
|
282
|
+
<div class="ds-chart__body" data-body>
|
|
283
|
+
<div class="ds-chart__plot" data-plot tabindex="0" role="group" aria-roledescription="${msg('chart.chart').toLocaleLowerCase(locale())}" aria-describedby="${id}-hint"></div>
|
|
284
|
+
<div class="ds-chart__tooltip" data-tooltip hidden></div>
|
|
285
|
+
</div>
|
|
286
|
+
<div class="ds-chart__table" data-table hidden></div>
|
|
287
|
+
<p class="ds-visually-hidden" id="${id}-hint">${msg('chart.keysHint')}</p>
|
|
288
|
+
<p class="ds-visually-hidden" aria-live="polite" data-live></p>`;
|
|
289
|
+
host.replaceChildren(figure);
|
|
290
|
+
|
|
291
|
+
const $ = (sel) => figure.querySelector(sel);
|
|
292
|
+
const body = $('[data-body]');
|
|
293
|
+
const plot = $('[data-plot]');
|
|
294
|
+
const tip = $('[data-tooltip]');
|
|
295
|
+
const legendEl = $('[data-legend]');
|
|
296
|
+
const tableEl = $('[data-table]');
|
|
297
|
+
const live = $('[data-live]');
|
|
298
|
+
const toggle = $('[data-chart-toggle]');
|
|
299
|
+
const cleanups = [];
|
|
300
|
+
|
|
301
|
+
plot.setAttribute('aria-label', [options.title ?? options.label ?? msg('chart.chart'), summary].filter(Boolean).join('. '));
|
|
302
|
+
|
|
303
|
+
/* Tabela: o gêmeo acessível de todo gráfico */
|
|
304
|
+
const onToggle = () => {
|
|
305
|
+
const showTable = figure.dataset.view !== 'table';
|
|
306
|
+
figure.dataset.view = showTable ? 'table' : 'chart';
|
|
307
|
+
body.hidden = showTable;
|
|
308
|
+
legendEl.hidden = showTable || !legendEl.childElementCount;
|
|
309
|
+
tableEl.hidden = !showTable;
|
|
310
|
+
toggle.setAttribute('aria-pressed', String(showTable));
|
|
311
|
+
const label = msg(showTable ? 'chart.asChart' : 'chart.asTable');
|
|
312
|
+
toggle.setAttribute('aria-label', label);
|
|
313
|
+
toggle.dataset.dsTooltip = label;
|
|
314
|
+
toggle.innerHTML = icon(showTable ? 'bar-chart' : 'table', { size: 16 });
|
|
315
|
+
};
|
|
316
|
+
toggle?.addEventListener('click', onToggle);
|
|
317
|
+
cleanups.push(() => toggle?.removeEventListener('click', onToggle));
|
|
318
|
+
|
|
319
|
+
/* Tamanho */
|
|
320
|
+
let width = 0;
|
|
321
|
+
const resizeHandlers = [];
|
|
322
|
+
let frameReq = 0;
|
|
323
|
+
const ro = new ResizeObserver((entries) => {
|
|
324
|
+
const w = Math.floor(entries[0].contentRect.width);
|
|
325
|
+
if (!w || w === width) return;
|
|
326
|
+
width = w;
|
|
327
|
+
cancelAnimationFrame(frameReq);
|
|
328
|
+
frameReq = requestAnimationFrame(() => resizeHandlers.forEach((fn) => fn(width)));
|
|
329
|
+
});
|
|
330
|
+
ro.observe(body);
|
|
331
|
+
cleanups.push(() => ro.disconnect());
|
|
332
|
+
|
|
333
|
+
// As fontes podem chegar depois do primeiro desenho; a medição de texto precisa delas.
|
|
334
|
+
document.fonts?.ready.then(() => figure.isConnected && resizeHandlers.forEach((fn) => fn(width)));
|
|
335
|
+
|
|
336
|
+
/* Entrada: anima uma vez, quando o gráfico aparece na tela */
|
|
337
|
+
let entered = false;
|
|
338
|
+
const io = new IntersectionObserver(
|
|
339
|
+
(entries) => {
|
|
340
|
+
if (entered || !entries.some((e) => e.isIntersecting)) return;
|
|
341
|
+
entered = true;
|
|
342
|
+
io.disconnect();
|
|
343
|
+
if (reducedMotion()) return;
|
|
344
|
+
figure.dataset.animate = '';
|
|
345
|
+
setTimeout(() => delete figure.dataset.animate, 1100);
|
|
346
|
+
},
|
|
347
|
+
{ threshold: 0.25 },
|
|
348
|
+
);
|
|
349
|
+
io.observe(figure);
|
|
350
|
+
cleanups.push(() => io.disconnect());
|
|
351
|
+
|
|
352
|
+
/* Tooltip */
|
|
353
|
+
function renderTooltip(content) {
|
|
354
|
+
tip.replaceChildren();
|
|
355
|
+
if (content.title) {
|
|
356
|
+
const t = document.createElement('p');
|
|
357
|
+
t.className = 'ds-chart__tooltip-title';
|
|
358
|
+
t.textContent = content.title;
|
|
359
|
+
tip.append(t);
|
|
360
|
+
}
|
|
361
|
+
if (content.rows?.length) {
|
|
362
|
+
const list = document.createElement('ul');
|
|
363
|
+
list.className = 'ds-chart__tooltip-rows';
|
|
364
|
+
for (const row of content.rows) {
|
|
365
|
+
const li = document.createElement('li');
|
|
366
|
+
li.className = 'ds-chart__tooltip-row';
|
|
367
|
+
if (row.active) li.dataset.active = '';
|
|
368
|
+
if (row.color) {
|
|
369
|
+
const key = document.createElement('span');
|
|
370
|
+
key.className = 'ds-chart__key-mark';
|
|
371
|
+
key.dataset.mark = row.mark ?? 'line';
|
|
372
|
+
key.style.setProperty('--c', row.color);
|
|
373
|
+
li.append(key);
|
|
374
|
+
}
|
|
375
|
+
const value = document.createElement('span');
|
|
376
|
+
value.className = 'ds-chart__tooltip-value';
|
|
377
|
+
value.textContent = row.value;
|
|
378
|
+
const name = document.createElement('span');
|
|
379
|
+
name.className = 'ds-chart__tooltip-name';
|
|
380
|
+
name.textContent = row.name ?? '';
|
|
381
|
+
li.append(value, name);
|
|
382
|
+
list.append(li);
|
|
383
|
+
}
|
|
384
|
+
tip.append(list);
|
|
385
|
+
}
|
|
386
|
+
if (content.note) {
|
|
387
|
+
const n = document.createElement('p');
|
|
388
|
+
n.className = 'ds-chart__tooltip-note';
|
|
389
|
+
n.textContent = content.note;
|
|
390
|
+
tip.append(n);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function placeTooltip({ x, y }) {
|
|
395
|
+
tip.hidden = false;
|
|
396
|
+
const bw = body.clientWidth;
|
|
397
|
+
const { offsetWidth: tw, offsetHeight: th } = tip;
|
|
398
|
+
const gap = 12;
|
|
399
|
+
let left = x + gap;
|
|
400
|
+
if (left + tw > bw) left = x - gap - tw;
|
|
401
|
+
if (left < 0) left = clamp(x - tw / 2, 0, Math.max(0, bw - tw));
|
|
402
|
+
// acima da marca; sem espaço, ao lado (já deslocado na horizontal), dentro da área
|
|
403
|
+
let top = y - th - gap;
|
|
404
|
+
if (top < 0) top = clamp(y - th / 2, 0, Math.max(0, body.clientHeight - th));
|
|
405
|
+
tip.style.transform = `translate(${Math.round(left)}px, ${Math.round(top)}px)`;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const plainText = (c) => [c.title, ...(c.rows ?? []).map((r) => `${r.name ? `${r.name}: ` : ''}${r.value}`), c.note].filter(Boolean).join('. ');
|
|
409
|
+
|
|
410
|
+
/* Interação: ponteiro + teclado, com a mesma informação nos dois */
|
|
411
|
+
let api = null;
|
|
412
|
+
let active = null;
|
|
413
|
+
|
|
414
|
+
function show(index, { keyboard = false } = {}) {
|
|
415
|
+
if (!api || index == null) return hide();
|
|
416
|
+
active = index;
|
|
417
|
+
api.highlight(index);
|
|
418
|
+
const content = api.describe(index);
|
|
419
|
+
if (api.tooltip === false) tip.hidden = true;
|
|
420
|
+
else {
|
|
421
|
+
renderTooltip(content);
|
|
422
|
+
placeTooltip(api.anchor(index));
|
|
423
|
+
}
|
|
424
|
+
if (keyboard) live.textContent = plainText(content);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
function hide() {
|
|
428
|
+
active = null;
|
|
429
|
+
api?.highlight(null);
|
|
430
|
+
tip.hidden = true;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
const point = (event) => {
|
|
434
|
+
const r = plot.getBoundingClientRect();
|
|
435
|
+
return [event.clientX - r.left, event.clientY - r.top];
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
const onMove = (event) => {
|
|
439
|
+
if (!api) return;
|
|
440
|
+
const i = api.hit(...point(event), event);
|
|
441
|
+
if (i == null) hide();
|
|
442
|
+
else if (i !== active || (tip.hidden && api.tooltip !== false)) show(i);
|
|
443
|
+
else if (api.tooltip !== false) placeTooltip(api.anchor(i));
|
|
444
|
+
};
|
|
445
|
+
const onLeave = (event) => {
|
|
446
|
+
if (event.pointerType === 'touch') return;
|
|
447
|
+
hide();
|
|
448
|
+
};
|
|
449
|
+
const onKey = (event) => {
|
|
450
|
+
if (!api) return;
|
|
451
|
+
if (event.key === 'Escape') return hide();
|
|
452
|
+
const next = api.move ? api.move(active, event.key) : moveLinear(active, event.key, api.count());
|
|
453
|
+
if (next === undefined) return;
|
|
454
|
+
event.preventDefault();
|
|
455
|
+
show(next, { keyboard: true });
|
|
456
|
+
};
|
|
457
|
+
const onFocus = () => {
|
|
458
|
+
if (plot.matches(':focus-visible') && api?.count()) show(active ?? api.first?.() ?? 0, { keyboard: true });
|
|
459
|
+
};
|
|
460
|
+
const onBlur = () => hide();
|
|
461
|
+
|
|
462
|
+
plot.addEventListener('pointermove', onMove);
|
|
463
|
+
plot.addEventListener('pointerdown', onMove);
|
|
464
|
+
plot.addEventListener('pointerleave', onLeave);
|
|
465
|
+
plot.addEventListener('keydown', onKey);
|
|
466
|
+
plot.addEventListener('focus', onFocus);
|
|
467
|
+
plot.addEventListener('blur', onBlur);
|
|
468
|
+
cleanups.push(() => {
|
|
469
|
+
plot.removeEventListener('pointermove', onMove);
|
|
470
|
+
plot.removeEventListener('pointerdown', onMove);
|
|
471
|
+
plot.removeEventListener('pointerleave', onLeave);
|
|
472
|
+
plot.removeEventListener('keydown', onKey);
|
|
473
|
+
plot.removeEventListener('focus', onFocus);
|
|
474
|
+
plot.removeEventListener('blur', onBlur);
|
|
475
|
+
});
|
|
476
|
+
|
|
477
|
+
return {
|
|
478
|
+
id,
|
|
479
|
+
figure,
|
|
480
|
+
plot,
|
|
481
|
+
body,
|
|
482
|
+
get width() {
|
|
483
|
+
return width || Math.floor(body.clientWidth);
|
|
484
|
+
},
|
|
485
|
+
onResize(fn) {
|
|
486
|
+
resizeHandlers.push(fn);
|
|
487
|
+
},
|
|
488
|
+
/** api: { count(), hit(x, y), anchor(i), describe(i), highlight(i|null), move?(i, key), first?() } */
|
|
489
|
+
interact(next) {
|
|
490
|
+
api = next;
|
|
491
|
+
},
|
|
492
|
+
refresh() {
|
|
493
|
+
if (active == null) return;
|
|
494
|
+
if (api && active < api.count()) show(active);
|
|
495
|
+
else hide();
|
|
496
|
+
},
|
|
497
|
+
hide,
|
|
498
|
+
setLabel(text) {
|
|
499
|
+
plot.setAttribute('aria-label', text);
|
|
500
|
+
},
|
|
501
|
+
/** Título e subtítulo novos num update(). */
|
|
502
|
+
setHead({ title, subtitle }) {
|
|
503
|
+
const titles = figure.querySelector('.ds-chart__titles');
|
|
504
|
+
if (!titles) return;
|
|
505
|
+
titles.innerHTML = `${title ? `<p class="ds-chart__title" id="${id}-title">${escapeHtml(title)}</p>` : ''}${subtitle ? `<p class="ds-chart__subtitle">${escapeHtml(subtitle)}</p>` : ''}`;
|
|
506
|
+
},
|
|
507
|
+
/** items: [{ name, color, mark, hidden }] · onToggle(index) ou null para legenda estática */
|
|
508
|
+
setLegend(items, onToggle) {
|
|
509
|
+
legendEl.replaceChildren();
|
|
510
|
+
if (!items?.length) {
|
|
511
|
+
legendEl.hidden = true;
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
for (const [i, item] of items.entries()) {
|
|
515
|
+
const el = document.createElement(onToggle ? 'button' : 'span');
|
|
516
|
+
el.className = 'ds-chart__legend-item';
|
|
517
|
+
if (onToggle) {
|
|
518
|
+
el.type = 'button';
|
|
519
|
+
el.setAttribute('aria-pressed', String(!item.hidden));
|
|
520
|
+
el.addEventListener('click', () => onToggle(i));
|
|
521
|
+
}
|
|
522
|
+
const mark = document.createElement('span');
|
|
523
|
+
mark.className = 'ds-chart__key-mark';
|
|
524
|
+
mark.dataset.mark = item.mark ?? 'rect';
|
|
525
|
+
mark.style.setProperty('--c', item.color);
|
|
526
|
+
const name = document.createElement('span');
|
|
527
|
+
name.textContent = item.name;
|
|
528
|
+
el.append(mark, name);
|
|
529
|
+
legendEl.append(el);
|
|
530
|
+
}
|
|
531
|
+
legendEl.setAttribute('role', 'group');
|
|
532
|
+
legendEl.setAttribute('aria-label', msg(onToggle ? 'chart.legendHint' : 'chart.legend'));
|
|
533
|
+
legendEl.hidden = figure.dataset.view === 'table';
|
|
534
|
+
},
|
|
535
|
+
/** { caption?, columns: [{ label, num? }], rows: [[...cells]] } */
|
|
536
|
+
setTable({ columns, rows, caption }) {
|
|
537
|
+
const head = columns.map((c) => `<th scope="col"${c.num ? ' class="ds-table__num"' : ''}>${escapeHtml(c.label)}</th>`).join('');
|
|
538
|
+
const bodyRows = rows
|
|
539
|
+
.map(
|
|
540
|
+
(row) =>
|
|
541
|
+
`<tr>${row
|
|
542
|
+
.map((cell, i) => (i === 0 ? `<th scope="row">${escapeHtml(cell)}</th>` : `<td${columns[i]?.num ? ' class="ds-table__num"' : ''}>${escapeHtml(cell)}</td>`))
|
|
543
|
+
.join('')}</tr>`,
|
|
544
|
+
)
|
|
545
|
+
.join('');
|
|
546
|
+
tableEl.innerHTML = `<div class="ds-table-wrap" role="region" tabindex="0" aria-label="${escapeHtml(caption ?? options.title ?? msg('chart.data'))}">
|
|
547
|
+
<table class="ds-table ds-table--compact"><thead><tr>${head}</tr></thead><tbody>${bodyRows}</tbody></table></div>`;
|
|
548
|
+
},
|
|
549
|
+
setLoading(on) {
|
|
550
|
+
figure.toggleAttribute('data-loading', !!on);
|
|
551
|
+
figure.setAttribute('aria-busy', String(!!on));
|
|
552
|
+
},
|
|
553
|
+
empty(text = options.empty ?? msg('chart.noData')) {
|
|
554
|
+
plot.innerHTML = `<div class="ds-chart__empty" style="height:${options.height ?? 240}px">${icon('bar-chart', { size: 20 })}<span>${escapeHtml(text)}</span></div>`;
|
|
555
|
+
},
|
|
556
|
+
destroy() {
|
|
557
|
+
cleanups.forEach((fn) => fn());
|
|
558
|
+
host.replaceChildren();
|
|
559
|
+
},
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/** Setas percorrem índices 0…n-1; Home e End vão às pontas. */
|
|
564
|
+
export function moveLinear(active, key, count) {
|
|
565
|
+
if (!count) return undefined;
|
|
566
|
+
const i = active ?? -1;
|
|
567
|
+
if (key === 'ArrowRight' || key === 'ArrowDown') return Math.min(count - 1, i + 1);
|
|
568
|
+
if (key === 'ArrowLeft' || key === 'ArrowUp') return Math.max(0, i < 0 ? 0 : i - 1);
|
|
569
|
+
if (key === 'Home') return 0;
|
|
570
|
+
if (key === 'End') return count - 1;
|
|
571
|
+
return undefined;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/* ───────── Eixos ───────── */
|
|
575
|
+
|
|
576
|
+
/** Grade horizontal + rótulos do eixo y (valores). */
|
|
577
|
+
export function yAxis({ ticks, y, left, right, format, baseline = 0, grid = true }) {
|
|
578
|
+
return ticks
|
|
579
|
+
.map((t) => {
|
|
580
|
+
const py = round(Math.round(y(t)) + 0.5, 1);
|
|
581
|
+
const isBase = t === baseline;
|
|
582
|
+
const line = grid || isBase ? tag('line', { x1: left, x2: right, y1: py, y2: py, class: isBase ? 'ds-chart__baseline' : 'ds-chart__grid' }) : '';
|
|
583
|
+
return `${line}${tag('text', { x: left - 10, y: py, class: 'ds-chart__tick', 'text-anchor': 'end', 'dominant-baseline': 'middle' }, escapeHtml(format(t)))}`;
|
|
584
|
+
})
|
|
585
|
+
.join('');
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Grade vertical + rótulos do eixo x (valores) — para barras horizontais e dispersão. */
|
|
589
|
+
export function xAxis({ ticks, x, top, bottom, format, baseline = 0, grid = true, labels = true }) {
|
|
590
|
+
return ticks
|
|
591
|
+
.map((t) => {
|
|
592
|
+
const px = round(Math.round(x(t)) + 0.5, 1);
|
|
593
|
+
const isBase = t === baseline;
|
|
594
|
+
const line = grid || isBase ? tag('line', { x1: px, x2: px, y1: top, y2: bottom, class: isBase ? 'ds-chart__baseline' : 'ds-chart__grid' }) : '';
|
|
595
|
+
const text = labels ? tag('text', { x: px, y: bottom + 18, class: 'ds-chart__tick', 'text-anchor': 'middle' }, escapeHtml(format(t))) : '';
|
|
596
|
+
return line + text;
|
|
597
|
+
})
|
|
598
|
+
.join('');
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Normaliza as séries de bar/line: { name, values, color, … } com o slot da posição original. */
|
|
602
|
+
export function normalizeSeries(series = []) {
|
|
603
|
+
return series.map((s, i) => ({ ...s, index: i, values: (s.values ?? []).map((v) => (v == null || Number.isNaN(+v) ? null : +v)), paint: paint(s.color, i) }));
|
|
604
|
+
}
|