@parallelogram-js/dashboard 0.0.0-stage → 0.1.1

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 (77) hide show
  1. package/CHANGELOG.md +113 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1390 -2
  4. package/dist/parallelogram-dashboard.css +9401 -0
  5. package/dist/parallelogram-dashboard.css.map +1 -0
  6. package/dist/parallelogram-dashboard.min.css +1 -0
  7. package/package.json +72 -4
  8. package/scss/_base.scss +403 -0
  9. package/scss/_datetime.scss +50 -0
  10. package/scss/_icon.scss +40 -0
  11. package/scss/_index.scss +60 -0
  12. package/scss/_mixins.scss +396 -0
  13. package/scss/_tokens.scss +340 -0
  14. package/scss/_utilities.scss +464 -0
  15. package/scss/_variables.scss +219 -0
  16. package/scss/components/_accordion.scss +297 -0
  17. package/scss/components/_actionbar.scss +333 -0
  18. package/scss/components/_alert.scss +183 -0
  19. package/scss/components/_avatar.scss +203 -0
  20. package/scss/components/_badge.scss +176 -0
  21. package/scss/components/_banner.scss +344 -0
  22. package/scss/components/_breadcrumb.scss +220 -0
  23. package/scss/components/_button.scss +264 -0
  24. package/scss/components/_card.scss +256 -0
  25. package/scss/components/_chart.scss +246 -0
  26. package/scss/components/_command.scss +267 -0
  27. package/scss/components/_dashboard.scss +681 -0
  28. package/scss/components/_data-list.scss +280 -0
  29. package/scss/components/_dropdown.scss +318 -0
  30. package/scss/components/_empty.scss +226 -0
  31. package/scss/components/_filebrowser.scss +906 -0
  32. package/scss/components/_form-layout.scss +332 -0
  33. package/scss/components/_input.scss +310 -0
  34. package/scss/components/_list.scss +130 -0
  35. package/scss/components/_media.scss +239 -0
  36. package/scss/components/_modal.scss +298 -0
  37. package/scss/components/_navbar.scss +312 -0
  38. package/scss/components/_notification.scss +59 -0
  39. package/scss/components/_pageheader.scss +99 -0
  40. package/scss/components/_pagination.scss +165 -0
  41. package/scss/components/_progress.scss +333 -0
  42. package/scss/components/_separator.scss +129 -0
  43. package/scss/components/_sheet.scss +286 -0
  44. package/scss/components/_sidebar.scss +324 -0
  45. package/scss/components/_skeleton.scss +246 -0
  46. package/scss/components/_stat.scss +218 -0
  47. package/scss/components/_table.scss +589 -0
  48. package/scss/components/_tabs.scss +266 -0
  49. package/scss/components/_timeline.scss +339 -0
  50. package/scss/components/_toast.scss +259 -0
  51. package/scss/components/_toolbar.scss +301 -0
  52. package/scss/components/_tooltip.scss +250 -0
  53. package/scss/main.scss +6 -0
  54. package/src/js/behaviours/accordion.js +58 -0
  55. package/src/js/behaviours/action-bar-list.js +406 -0
  56. package/src/js/behaviours/action-bar.js +29 -0
  57. package/src/js/behaviours/chart.js +339 -0
  58. package/src/js/behaviours/collapsible.js +34 -0
  59. package/src/js/behaviours/editable-table.js +91 -0
  60. package/src/js/behaviours/expandable.js +80 -0
  61. package/src/js/behaviours/overflow-actions.js +137 -0
  62. package/src/js/behaviours/publish-schedule.js +91 -0
  63. package/src/js/behaviours/search-clear.js +19 -0
  64. package/src/js/behaviours/segmented-control.js +43 -0
  65. package/src/js/behaviours/submenu.js +73 -0
  66. package/src/js/behaviours/table-columns.js +77 -0
  67. package/src/js/behaviours/table-paste.js +305 -0
  68. package/src/js/behaviours/table-reorder.js +252 -0
  69. package/src/js/behaviours/table-sort.js +101 -0
  70. package/src/js/behaviours/tabs.js +148 -0
  71. package/src/js/behaviours/toast-manager.js +106 -0
  72. package/src/js/behaviours/toggle.js +186 -0
  73. package/src/js/behaviours/unsaved-guard.js +88 -0
  74. package/src/js/core-loader.js +26 -0
  75. package/src/js/index.js +85 -0
  76. package/src/js/polyfills/dialog-commands.js +20 -0
  77. package/src/js/util/dom.js +39 -0
@@ -0,0 +1,339 @@
1
+ // ============================================================================
2
+ // Chart Component
3
+ // ============================================================================
4
+
5
+ const SVG_NS = 'http://www.w3.org/2000/svg';
6
+
7
+ function svgEl(tag, attrs = {}, parent = null) {
8
+ const el = document.createElementNS(SVG_NS, tag);
9
+ for (const [key, value] of Object.entries(attrs)) el.setAttribute(key, value);
10
+ parent?.append(el);
11
+ return el;
12
+ }
13
+
14
+ /** Round up to a clean axis maximum: 1, 2, 2.5 or 5 times a power of ten. */
15
+ function niceMax(value) {
16
+ if (value <= 0) return 1;
17
+ const power = 10 ** Math.floor(Math.log10(value));
18
+ return [1, 2, 2.5, 5, 10].find(step => step * power >= value) * power;
19
+ }
20
+
21
+ /**
22
+ * Renders a data <table> inside <figure class="chart" data-chart="..."> as an SVG chart.
23
+ *
24
+ * Types: line, area, bar (grouped when there are several series) and stacked-bar.
25
+ * The first column holds the x labels and every other column is a series. Cells may carry
26
+ * data-value when their text is formatted. data-chart-format is "number", "currency" or
27
+ * "percent". The table stays in the page as the accessible table view.
28
+ */
29
+ export class Chart {
30
+ constructor() {
31
+ this.elements = new WeakMap();
32
+ }
33
+
34
+ mount(figure) {
35
+ if (this.elements.has(figure)) return;
36
+ const table = figure.querySelector('table');
37
+ if (!table) return;
38
+
39
+ const data = this._parse(table);
40
+ if (!data.rows.length || !data.series.length) return;
41
+
42
+ const state = {
43
+ figure,
44
+ table,
45
+ data,
46
+ type: figure.dataset.chart || 'line',
47
+ format: this._formatter(figure.dataset.chartFormat),
48
+ plot: document.createElement('div'),
49
+ tooltip: document.createElement('div'),
50
+ index: null,
51
+ };
52
+
53
+ table.classList.add('chart__table');
54
+ table.hidden = true;
55
+
56
+ state.plot.className = 'chart__plot';
57
+ state.plot.tabIndex = 0;
58
+ state.plot.setAttribute('role', 'group');
59
+ const title = figure.querySelector('.chart__title')?.textContent.trim() || 'Chart';
60
+ state.plot.setAttribute('aria-label', `${title}. Use the arrow keys to read values.`);
61
+
62
+ state.tooltip.className = 'chart__tooltip';
63
+ state.tooltip.hidden = true;
64
+ state.tooltip.setAttribute('aria-live', 'polite');
65
+
66
+ const legend = data.series.length > 1 ? this._legend(state) : null;
67
+ table.before(...[legend, state.plot].filter(Boolean));
68
+ this._addTableToggle(state, legend);
69
+
70
+ state.plot.addEventListener('keydown', (e) => this._handleKey(e, state));
71
+ state.plot.addEventListener('focus', () => this._show(state, state.index ?? data.rows.length - 1));
72
+ state.plot.addEventListener('blur', () => this._hide(state));
73
+ state.plot.addEventListener('pointerleave', () => this._hide(state));
74
+
75
+ // Render now; the observer re-renders on resize (it may not fire in a background tab)
76
+ this._render(state);
77
+ new ResizeObserver(() => this._render(state)).observe(state.plot);
78
+ figure.setAttribute('data-chart-enhanced', 'true');
79
+ this.elements.set(figure, state);
80
+ }
81
+
82
+ _parse(table) {
83
+ const headers = [...table.querySelectorAll('thead th')].map(th => th.textContent.trim());
84
+ const rows = [...table.querySelectorAll('tbody tr')].map(tr => {
85
+ const cells = [...tr.children];
86
+ return {
87
+ label: cells[0]?.textContent.trim() ?? '',
88
+ values: cells.slice(1).map(cell => {
89
+ const raw = cell.dataset.value ?? cell.textContent.replace(/[^0-9.\-]/g, '');
90
+ return Number.parseFloat(raw) || 0;
91
+ }),
92
+ };
93
+ });
94
+ return { series: headers.slice(1), rows };
95
+ }
96
+
97
+ _formatter(kind) {
98
+ const options = {
99
+ currency: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 },
100
+ percent: { style: 'percent', maximumFractionDigits: 1 },
101
+ }[kind] || { maximumFractionDigits: 1 };
102
+ const full = new Intl.NumberFormat('en-US', options);
103
+ const compact = new Intl.NumberFormat('en-US', { ...options, notation: 'compact', maximumFractionDigits: 1 });
104
+ const scale = kind === 'percent' ? 0.01 : 1;
105
+ return {
106
+ full: value => full.format(value * scale),
107
+ compact: value => compact.format(value * scale),
108
+ };
109
+ }
110
+
111
+ _legend(state) {
112
+ const legend = document.createElement('ul');
113
+ legend.className = 'chart__legend';
114
+ const isBar = state.type.includes('bar');
115
+ state.data.series.forEach((name, i) => {
116
+ const item = document.createElement('li');
117
+ item.className = 'chart__legend-item';
118
+ const key = document.createElement('span');
119
+ key.className = isBar ? 'chart__key chart__key--box' : 'chart__key';
120
+ key.style.color = `var(--chart-${i + 1})`;
121
+ item.append(key, document.createTextNode(name));
122
+ legend.append(item);
123
+ });
124
+ return legend;
125
+ }
126
+
127
+ _addTableToggle(state, legend) {
128
+ const header = state.figure.querySelector('.chart__header');
129
+ if (!header) return;
130
+ const button = document.createElement('button');
131
+ button.type = 'button';
132
+ button.className = 'btn btn--ghost btn--sm';
133
+ button.textContent = 'Table';
134
+ button.setAttribute('aria-pressed', 'false');
135
+ button.addEventListener('click', () => {
136
+ const showTable = button.getAttribute('aria-pressed') !== 'true';
137
+ button.setAttribute('aria-pressed', String(showTable));
138
+ state.table.hidden = !showTable;
139
+ state.plot.hidden = showTable;
140
+ if (legend) legend.hidden = showTable;
141
+ });
142
+ header.append(button);
143
+ }
144
+
145
+ _render(state) {
146
+ const { plot, data, type, format } = state;
147
+ const width = plot.clientWidth;
148
+ const height = plot.clientHeight;
149
+ if (!width || !height) return;
150
+
151
+ const stacked = type === 'stacked-bar';
152
+ const isBar = type.includes('bar');
153
+ const n = data.rows.length;
154
+ const peak = Math.max(...data.rows.map(r => (stacked ? r.values.reduce((a, b) => a + b, 0) : Math.max(...r.values))));
155
+ const max = niceMax(peak);
156
+ const ticks = [0, 0.25, 0.5, 0.75, 1].map(t => t * max);
157
+
158
+ const tickWidth = Math.max(...ticks.map(t => format.compact(t).length)) * 6.5 + 8;
159
+ const endLabel = !isBar && data.series.length === 1 ? format.compact(data.rows[n - 1].values[0]).length * 6.5 + 10 : 8;
160
+ const box = { left: tickWidth, right: width - endLabel, top: 8, bottom: height - 22 };
161
+ const y = value => box.bottom - (value / max) * (box.bottom - box.top);
162
+ const band = (box.right - box.left) / n;
163
+ const x = isBar
164
+ ? i => box.left + band * (i + 0.5)
165
+ : i => box.left + (n === 1 ? 0 : (i * (box.right - box.left)) / (n - 1));
166
+ state.geometry = { box, x, band, isBar };
167
+
168
+ const root = svgEl('svg', { 'aria-hidden': 'true' });
169
+
170
+ for (const t of ticks) {
171
+ svgEl('line', { class: t ? 'chart__grid' : 'chart__baseline', x1: box.left, x2: box.right, y1: y(t), y2: y(t) }, root);
172
+ svgEl('text', { class: 'chart__tick', x: box.left - 8, y: y(t), 'text-anchor': 'end', 'dominant-baseline': 'middle' }, root)
173
+ .textContent = format.compact(t);
174
+ }
175
+
176
+ const labelWidth = Math.max(...data.rows.map(r => r.label.length)) * 6.5 + 12;
177
+ const slot = (box.right - box.left) / (isBar ? n : Math.max(1, n - 1));
178
+ const every = Math.max(1, Math.ceil(labelWidth / slot));
179
+ data.rows.forEach((row, i) => {
180
+ // Skip labels that would crowd their neighbours, keeping the last one and the space before it
181
+ if (i % every !== 0 && i !== n - 1) return;
182
+ if (i !== n - 1 && i % every === 0 && n - 1 - i < every) return;
183
+ const anchor = isBar ? 'middle' : i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle';
184
+ svgEl('text', { class: 'chart__tick', x: x(i), y: height - 6, 'text-anchor': anchor }, root).textContent = row.label;
185
+ });
186
+
187
+ if (isBar) {
188
+ this._renderBars(state, root, y, stacked);
189
+ } else {
190
+ this._renderLines(state, root, y, type === 'area');
191
+ }
192
+
193
+ state.crosshair = svgEl('line', { class: 'chart__crosshair', y1: box.top, y2: box.bottom, visibility: 'hidden' }, root);
194
+ state.hoverDots = data.series.map((_, s) => svgEl('circle', { class: 'chart__dot', r: 4, fill: `var(--chart-${s + 1})`, visibility: 'hidden' }, root));
195
+ if (isBar) state.hoverDots.forEach(dot => dot.remove());
196
+
197
+ const hit = svgEl('rect', { class: 'chart__hit', x: box.left, y: box.top, width: box.right - box.left, height: box.bottom - box.top }, root);
198
+ hit.addEventListener('pointermove', (e) => {
199
+ const bounds = plot.getBoundingClientRect();
200
+ const px = e.clientX - bounds.left;
201
+ const i = isBar
202
+ ? Math.floor((px - box.left) / band)
203
+ : Math.round(((px - box.left) / (box.right - box.left)) * (n - 1));
204
+ this._show(state, Math.min(n - 1, Math.max(0, i)));
205
+ });
206
+
207
+ plot.replaceChildren(root, state.tooltip);
208
+ if (state.index !== null && !state.tooltip.hidden) this._show(state, state.index);
209
+ }
210
+
211
+ _renderLines(state, root, y, area) {
212
+ const { data, format } = state;
213
+ const { box, x } = state.geometry;
214
+ data.series.forEach((name, s) => {
215
+ const color = `var(--chart-${s + 1})`;
216
+ const points = data.rows.map((row, i) => [x(i), y(row.values[s])]);
217
+ const line = points.map(([px, py], i) => `${i ? 'L' : 'M'}${px},${py}`).join(' ');
218
+ if (area || data.series.length === 1) {
219
+ svgEl('path', { class: 'chart__area', d: `${line} L${points.at(-1)[0]},${box.bottom} L${points[0][0]},${box.bottom} Z`, fill: color }, root);
220
+ }
221
+ svgEl('path', { class: 'chart__line', d: line, stroke: color }, root);
222
+ const [ex, ey] = points.at(-1);
223
+ svgEl('circle', { class: 'chart__dot', cx: ex, cy: ey, r: 4, fill: color }, root);
224
+ if (data.series.length === 1) {
225
+ svgEl('text', { class: 'chart__label', x: ex + 8, y: ey, 'dominant-baseline': 'middle' }, root)
226
+ .textContent = format.compact(data.rows.at(-1).values[s]);
227
+ }
228
+ });
229
+ }
230
+
231
+ _renderBars(state, root, y, stacked) {
232
+ const { data } = state;
233
+ const { box, x, band } = state.geometry;
234
+ const groups = stacked ? 1 : data.series.length;
235
+ const gap = 2;
236
+ const barWidth = Math.max(2, Math.min(24, (band * 0.7 - gap * (groups - 1)) / groups));
237
+ const groupWidth = barWidth * groups + gap * (groups - 1);
238
+ state.bars = data.rows.map(() => []);
239
+
240
+ data.rows.forEach((row, i) => {
241
+ let base = 0;
242
+ row.values.forEach((value, s) => {
243
+ if (value <= 0) return;
244
+ const left = x(i) - groupWidth / 2 + (stacked ? 0 : s * (barWidth + gap));
245
+ const bottom = y(base);
246
+ const top = y(base + value);
247
+ const isTop = !stacked || row.values.slice(s + 1).every(v => v <= 0);
248
+ const r = isTop ? Math.min(4, barWidth / 2, bottom - top) : 0;
249
+ const d = `M${left},${bottom} V${top + r} Q${left},${top} ${left + r},${top} H${left + barWidth - r} Q${left + barWidth},${top} ${left + barWidth},${top + r} V${bottom} Z`;
250
+ state.bars[i].push(svgEl('path', { class: 'chart__bar', d, fill: `var(--chart-${s + 1})` }, root));
251
+ if (stacked) base += value;
252
+ });
253
+ });
254
+ }
255
+
256
+ _show(state, index) {
257
+ const { data, format, tooltip, geometry } = state;
258
+ if (!geometry) return;
259
+ state.index = index;
260
+ const row = data.rows[index];
261
+ const { box, x, isBar } = geometry;
262
+ const px = x(index);
263
+
264
+ if (isBar) {
265
+ state.bars.flat().forEach(bar => bar.classList.remove('chart__bar--active'));
266
+ state.bars[index].forEach(bar => bar.classList.add('chart__bar--active'));
267
+ } else {
268
+ state.crosshair.setAttribute('x1', px);
269
+ state.crosshair.setAttribute('x2', px);
270
+ state.crosshair.setAttribute('visibility', 'visible');
271
+ const max = niceMax(Math.max(...data.rows.map(r => Math.max(...r.values))));
272
+ state.hoverDots.forEach((dot, s) => {
273
+ dot.setAttribute('cx', px);
274
+ dot.setAttribute('cy', box.bottom - (row.values[s] / max) * (box.bottom - box.top));
275
+ dot.setAttribute('visibility', 'visible');
276
+ });
277
+ }
278
+
279
+ const heading = document.createElement('div');
280
+ heading.className = 'chart__tooltip-title';
281
+ heading.textContent = row.label;
282
+ const rows = data.series.map((name, s) => {
283
+ const line = document.createElement('div');
284
+ line.className = 'chart__tooltip-row';
285
+ const key = document.createElement('span');
286
+ key.className = 'chart__key';
287
+ key.style.color = `var(--chart-${s + 1})`;
288
+ const value = document.createElement('strong');
289
+ value.textContent = format.full(row.values[s]);
290
+ const label = document.createElement('span');
291
+ label.textContent = name;
292
+ line.append(key, value, label);
293
+ return line;
294
+ });
295
+ if (state.type === 'stacked-bar' && data.series.length > 1) {
296
+ const total = document.createElement('div');
297
+ total.className = 'chart__tooltip-row';
298
+ const value = document.createElement('strong');
299
+ value.textContent = format.full(row.values.reduce((a, b) => a + b, 0));
300
+ const label = document.createElement('span');
301
+ label.textContent = 'Total';
302
+ total.append(document.createElement('span'), value, label);
303
+ rows.push(total);
304
+ }
305
+ tooltip.replaceChildren(heading, ...rows);
306
+ tooltip.hidden = false;
307
+
308
+ const tipWidth = tooltip.offsetWidth;
309
+ const left = px + 12 + tipWidth > state.plot.clientWidth ? px - 12 - tipWidth : px + 12;
310
+ tooltip.style.left = `${Math.max(0, left)}px`;
311
+ tooltip.style.top = `${box.top}px`;
312
+ }
313
+
314
+ _hide(state) {
315
+ state.tooltip.hidden = true;
316
+ state.crosshair?.setAttribute('visibility', 'hidden');
317
+ state.hoverDots?.forEach(dot => dot.setAttribute('visibility', 'hidden'));
318
+ state.bars?.flat().forEach(bar => bar.classList.remove('chart__bar--active'));
319
+ }
320
+
321
+ _handleKey(event, state) {
322
+ const last = state.data.rows.length - 1;
323
+ const current = state.index ?? last;
324
+ const next = { ArrowLeft: current - 1, ArrowRight: current + 1, Home: 0, End: last }[event.key];
325
+ if (event.key === 'Escape') {
326
+ this._hide(state);
327
+ return;
328
+ }
329
+ if (next === undefined) return;
330
+ event.preventDefault();
331
+ this._show(state, Math.min(last, Math.max(0, next)));
332
+ }
333
+
334
+ static enhanceAll(selector = '[data-chart]', root = document) {
335
+ const instance = new Chart();
336
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
337
+ return instance;
338
+ }
339
+ }
@@ -0,0 +1,34 @@
1
+ import { linkTrigger } from '../util/dom.js';
2
+
3
+ // ============================================================================
4
+ // Collapsible Component
5
+ // ============================================================================
6
+
7
+ /**
8
+ * Wires a .collapsible whose trigger is a <button>; <details class="collapsible"> needs no JS.
9
+ */
10
+ export class Collapsible {
11
+ constructor() {
12
+ this.elements = new WeakSet();
13
+ }
14
+
15
+ mount(element) {
16
+ if (this.elements.has(element)) return;
17
+
18
+ const trigger = element.querySelector(':scope > button.collapsible__trigger');
19
+ if (!trigger) return;
20
+
21
+ linkTrigger(trigger, element.querySelector(':scope > .collapsible__content'));
22
+ trigger.addEventListener('click', () => {
23
+ trigger.setAttribute('aria-expanded', String(trigger.getAttribute('aria-expanded') !== 'true'));
24
+ });
25
+
26
+ this.elements.add(element);
27
+ }
28
+
29
+ static enhanceAll(selector = '.collapsible', root = document) {
30
+ const instance = new Collapsible();
31
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
32
+ return instance;
33
+ }
34
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Spreadsheet-style keyboard movement between the .table__control cells of a .table--editable.
3
+ *
4
+ * Up and down move to the same column in the next row; left and right move to the next cell
5
+ * while a field's whole value is selected (as it is on arrival) or once the caret reaches its
6
+ * edge, and straight away from a select. Enter moves
7
+ * down and Shift+Enter up. Escape puts back the value the cell had when it was focused, and
8
+ * Ctrl or Cmd+D copies the value from the cell above. Changes fire input and change events, so
9
+ * the page's own handlers see them.
10
+ */
11
+ export class EditableTable {
12
+ static elements = new WeakSet();
13
+
14
+ constructor() {
15
+ this.original = new WeakMap();
16
+ }
17
+
18
+ mount(table) {
19
+ if (EditableTable.elements.has(table)) return;
20
+ EditableTable.elements.add(table);
21
+ table.addEventListener('focusin', (e) => {
22
+ if (e.target.matches('.table__control')) this.original.set(e.target, e.target.value);
23
+ });
24
+ table.addEventListener('keydown', e => this._keyDown(e, table));
25
+ }
26
+
27
+ /** Every visible row's controls, as a grid of [row][column]. */
28
+ _grid(table) {
29
+ return [...table.querySelectorAll('.table__body > .table__row')]
30
+ .filter(row => row.offsetParent !== null)
31
+ // Skip controls in hidden columns
32
+ .map(row => [...row.querySelectorAll('.table__control')].filter(control => control.getClientRects().length));
33
+ }
34
+
35
+ _neighbour(table, control, rows, columns) {
36
+ const grid = this._grid(table);
37
+ const r = grid.findIndex(cells => cells.includes(control));
38
+ if (r === -1) return null;
39
+ return grid[r + rows]?.[grid[r].indexOf(control) + columns] || null;
40
+ }
41
+
42
+ _go(target) {
43
+ if (!target) return;
44
+ target.focus();
45
+ if (target.matches('input')) target.select();
46
+ }
47
+
48
+ _set(control, value) {
49
+ control.value = value;
50
+ control.dispatchEvent(new Event('input', { bubbles: true }));
51
+ control.dispatchEvent(new Event('change', { bubbles: true }));
52
+ }
53
+
54
+ _keyDown(event, table) {
55
+ const control = event.target.closest('.table__control');
56
+ if (!control || event.altKey) return;
57
+ const text = control.matches('input');
58
+ const { selectionStart: from, selectionEnd: to, value } = control;
59
+ // A cell arrived at by keyboard has its whole value selected, so arrows keep moving, as in a spreadsheet
60
+ const whole = text && from === 0 && to === value.length;
61
+ const atStart = !text || whole || (from === 0 && to === 0);
62
+ const atEnd = !text || whole || (from === value.length && to === value.length);
63
+ const step = {
64
+ ArrowUp: [-1, 0],
65
+ ArrowDown: [1, 0],
66
+ ArrowLeft: atStart ? [0, -1] : null,
67
+ ArrowRight: atEnd ? [0, 1] : null,
68
+ Enter: event.shiftKey ? [-1, 0] : [1, 0],
69
+ }[event.key];
70
+
71
+ if (step && !event.metaKey && !event.ctrlKey) {
72
+ event.preventDefault();
73
+ this._go(this._neighbour(table, control, ...step));
74
+ } else if (event.key === 'Escape' && this.original.has(control) && control.value !== this.original.get(control)) {
75
+ event.preventDefault();
76
+ this._set(control, this.original.get(control));
77
+ if (text) control.select();
78
+ } else if (event.key.toLowerCase() === 'd' && (event.metaKey || event.ctrlKey)) {
79
+ const above = this._neighbour(table, control, -1, 0);
80
+ if (!above) return;
81
+ event.preventDefault();
82
+ this._set(control, above.value);
83
+ }
84
+ }
85
+
86
+ static enhanceAll(selector = '.table--editable', root = document) {
87
+ const instance = new EditableTable();
88
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
89
+ return instance;
90
+ }
91
+ }
@@ -0,0 +1,80 @@
1
+ import { Toggle } from './toggle.js';
2
+
3
+ /**
4
+ * Shows a [data-expandable] element full-screen and back again.
5
+ *
6
+ * A [data-expand] button inside it moves the element into a full-window <dialog> (and back on
7
+ * the next press, Escape or the dialog closing), so its state, focus handling and top-layer
8
+ * menus carry over. While expanded the element has data-expanded and the button aria-pressed;
9
+ * give the button data-expand-label and data-collapse-label to swap its accessible name. The
10
+ * element fires "expandable:change" with { expanded }.
11
+ */
12
+ export class Expandable {
13
+ static elements = new WeakMap();
14
+
15
+ mount(element) {
16
+ if (Expandable.elements.has(element)) return;
17
+ const state = { dialog: null, placeholder: null };
18
+ Expandable.elements.set(element, state);
19
+ element.addEventListener('click', (e) => {
20
+ const button = e.target.closest('[data-expand]');
21
+ if (button && button.closest('[data-expandable]') === element) this.toggle(element);
22
+ });
23
+ }
24
+
25
+ toggle(element) {
26
+ const state = Expandable.elements.get(element);
27
+ if (state?.dialog) this.collapse(element);
28
+ else this.expand(element);
29
+ }
30
+
31
+ expand(element) {
32
+ const state = Expandable.elements.get(element);
33
+ if (!state || state.dialog) return;
34
+ state.placeholder = document.createComment('expandable');
35
+ element.before(state.placeholder);
36
+ const dialog = document.createElement('dialog');
37
+ dialog.className = 'expandable';
38
+ dialog.setAttribute('aria-label', element.dataset.expandableLabel || 'Full screen');
39
+ dialog.addEventListener('cancel', (e) => {
40
+ e.preventDefault();
41
+ this.collapse(element);
42
+ });
43
+ dialog.append(element);
44
+ document.body.append(dialog);
45
+ state.dialog = dialog;
46
+ dialog.showModal();
47
+ this._changed(element, true);
48
+ }
49
+
50
+ collapse(element) {
51
+ const state = Expandable.elements.get(element);
52
+ if (!state?.dialog) return;
53
+ Toggle.closeAll();
54
+ state.placeholder.replaceWith(element);
55
+ state.dialog.close();
56
+ state.dialog.remove();
57
+ state.dialog = null;
58
+ this._changed(element, false);
59
+ }
60
+
61
+ _changed(element, expanded) {
62
+ element.toggleAttribute('data-expanded', expanded);
63
+ element.querySelectorAll('[data-expand]').forEach((button) => {
64
+ button.setAttribute('aria-pressed', String(expanded));
65
+ const label = expanded ? button.dataset.collapseLabel : button.dataset.expandLabel;
66
+ if (label) {
67
+ button.setAttribute('aria-label', label);
68
+ if (button.hasAttribute('data-tooltip')) button.dataset.tooltip = label;
69
+ }
70
+ });
71
+ element.querySelector('[data-expand]')?.focus();
72
+ element.dispatchEvent(new CustomEvent('expandable:change', { bubbles: true, detail: { expanded } }));
73
+ }
74
+
75
+ static enhanceAll(selector = '[data-expandable]', root = document) {
76
+ const instance = new Expandable();
77
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
78
+ return instance;
79
+ }
80
+ }
@@ -0,0 +1,137 @@
1
+ import { Toggle } from './toggle.js';
2
+
3
+ const ACTIONBAR_MORE_ICON = '<svg class="icon" viewBox="0 0 24 24"><path d="M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/><path d="M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"/></svg>';
4
+ const OVERFLOW_RANK = { low: 1, medium: 2 };
5
+ let overflowMenuCount = 0;
6
+
7
+ /**
8
+ * Folds lower-priority actions into a "more" menu when they don't fit.
9
+ *
10
+ * Mark a container with data-overflow-actions and give foldable children data-priority="low"
11
+ * (folded first) or "medium". Containers in the same boundary (data-overflow-boundary, else the
12
+ * nearest .table__wrapper, else the container itself) fold together, so table rows stay
13
+ * aligned. A boundary is full when it scrolls sideways or when protected text inside it is cut
14
+ * off: text inputs in a table, or anything marked data-overflow-protect. The script only
15
+ * measures and sets data-overflow-level on the boundary; the stylesheet hides what that level
16
+ * folds. The menu is built when it opens: buttons and links
17
+ * become items that click the original, and a switch or checkbox becomes a menuitemcheckbox kept
18
+ * in sync. Items take their text from data-label, then aria-label, then the action's own text.
19
+ */
20
+ export class OverflowActions {
21
+ // Shared by every instance, so content enhanced later joins its boundary's group
22
+ static elements = new WeakMap();
23
+ static groups = new WeakMap();
24
+
25
+ mount(container, options = {}) {
26
+ if (OverflowActions.elements.has(container)) return;
27
+ if (![...container.children].some(el => el.dataset.priority in OVERFLOW_RANK)) return;
28
+
29
+ container.setAttribute('data-overflow-actions', '');
30
+ // A copied row brings the original's menu along; it gets a fresh one
31
+ container.querySelector(':scope > [data-overflow-more]')?.remove();
32
+ this._createMore(container, options);
33
+
34
+ const selector = container.dataset.overflowBoundary;
35
+ const boundary = options.boundary || (selector && container.closest(selector)) || container.closest('.table__wrapper') || container;
36
+ OverflowActions.elements.set(container, { boundary });
37
+
38
+ let group = OverflowActions.groups.get(boundary);
39
+ if (!group) {
40
+ group = { boundary, members: new Set(), protect: options.protect || 'input.table__control, [data-overflow-protect]' };
41
+ OverflowActions.groups.set(boundary, group);
42
+ new ResizeObserver(() => this._schedule(group)).observe(boundary);
43
+ }
44
+ group.members.add(container);
45
+ this._schedule(group);
46
+ }
47
+
48
+ /** Fit on the next frame, once layout has settled, running at most once per frame. */
49
+ _schedule(group) {
50
+ if (group.pending) return;
51
+ group.pending = requestAnimationFrame(() => {
52
+ group.pending = 0;
53
+ this._fit(group);
54
+ });
55
+ }
56
+
57
+ _createMore(container, { moreClass = 'dropdown dropdown--right', triggerClass = 'btn btn--ghost btn--icon btn--sm dropdown__trigger' }) {
58
+ const id = `overflow-menu-${++overflowMenuCount}`;
59
+ const more = document.createElement('div');
60
+ more.className = moreClass;
61
+ more.setAttribute('data-overflow-more', '');
62
+ more.innerHTML = `<button type="button" class="${triggerClass}" aria-label="More actions" aria-haspopup="menu" data-toggle data-toggle-target="#${id}" data-toggle-capture="true">${ACTIONBAR_MORE_ICON}</button>`
63
+ + `<div class="dropdown__menu" id="${id}" role="menu" popover="manual"></div>`;
64
+ // Capture phase, so the menu is filled before Toggle opens it
65
+ more.addEventListener('click', (e) => {
66
+ if (e.target.closest('.dropdown__trigger')) this._fillMenu(container, more.querySelector('[role="menu"]'));
67
+ }, true);
68
+ container.append(more);
69
+ }
70
+
71
+ /** Raise the boundary's level one priority at a time until it no longer overflows. */
72
+ _fit(group) {
73
+ const members = [...group.members].filter(member => member.isConnected);
74
+ group.members = new Set(members);
75
+ const ranks = new Set(members.flatMap(member => [...member.children].map(el => OVERFLOW_RANK[el.dataset.priority]).filter(Boolean)));
76
+ for (const level of [0, ...[...ranks].sort()]) {
77
+ group.boundary.dataset.overflowLevel = level;
78
+ if (!this._overflows(group)) break;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Tables and flex rows squeeze content rather than scrolling, so a boundary also counts as
84
+ * full when protected text inside it can no longer show in full.
85
+ */
86
+ _overflows({ boundary, protect }) {
87
+ if (boundary.scrollWidth > boundary.clientWidth) return true;
88
+ return [...boundary.querySelectorAll(protect)].some(el => el.scrollWidth > el.clientWidth + 1);
89
+ }
90
+
91
+ _fillMenu(container, menu) {
92
+ const level = Number(OverflowActions.elements.get(container).boundary.dataset.overflowLevel) || 0;
93
+ const folded = [...container.children].filter(el => OVERFLOW_RANK[el.dataset.priority] <= level);
94
+ menu.replaceChildren(...folded.map(source => this._menuItem(source)));
95
+ }
96
+
97
+ _menuItem(source) {
98
+ const item = document.createElement('button');
99
+ item.type = 'button';
100
+ item.className = 'dropdown__item';
101
+ const icon = source.matches('a, button') && source.querySelector('svg.icon');
102
+ if (icon) {
103
+ const copy = icon.cloneNode(true);
104
+ copy.classList.add('dropdown__item-icon');
105
+ item.append(copy);
106
+ }
107
+ const text = document.createElement('span');
108
+ text.className = 'dropdown__item-text';
109
+ text.textContent = source.dataset.label || source.getAttribute('aria-label') || source.textContent.trim();
110
+ item.append(text);
111
+
112
+ const input = source.querySelector('input[type="checkbox"]');
113
+ if (input) {
114
+ item.setAttribute('role', 'menuitemcheckbox');
115
+ item.setAttribute('aria-checked', String(input.checked));
116
+ item.insertAdjacentHTML('beforeend', '<svg class="icon dropdown__item-check" viewBox="0 0 24 24"><path d="M5 12l5 5l10 -10"/></svg>');
117
+ item.addEventListener('click', () => {
118
+ input.click();
119
+ item.setAttribute('aria-checked', String(input.checked));
120
+ });
121
+ } else {
122
+ item.setAttribute('role', 'menuitem');
123
+ const target = source.matches('a, button') ? source : source.querySelector('a, button');
124
+ item.addEventListener('click', () => {
125
+ Toggle.closeAll();
126
+ target?.click();
127
+ });
128
+ }
129
+ return item;
130
+ }
131
+
132
+ static enhanceAll(selector = '[data-overflow-actions]', root = document) {
133
+ const instance = new OverflowActions();
134
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
135
+ return instance;
136
+ }
137
+ }