@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,91 @@
1
+ /**
2
+ * Scheduled publishing for a record.
3
+ *
4
+ * Inside [data-publish-schedule], the status radios (name="status" with values draft, active and
5
+ * archived) and two optional dates decide what the record shows as: a [data-publish-at] field for
6
+ * when it goes live and a [data-expire-at] field for when it comes down. Each date is switched on
7
+ * by a .segmented-control with data-publish-toggle="#fieldId", whose item marked data-later
8
+ * shows the field; on the other item ("Now", "Never") the field is hidden and disabled, so it
9
+ * isn't submitted but keeps its value.
10
+ *
11
+ * The area gets data-publish-state: "draft", "scheduled" (active, going live later), "live",
12
+ * "expired" (active, past its take-down date) or "archived". Elements marked
13
+ * data-publish-show="scheduled live" only show in the states listed, and [data-publish-date] and
14
+ * [data-expire-date] elements show the dates in words. The area fires "publish:change" with
15
+ * { state, publishAt, expireAt } when the state or a date changes.
16
+ */
17
+ export class PublishSchedule {
18
+ static elements = new WeakSet();
19
+
20
+ static format = new Intl.DateTimeFormat(undefined, { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' });
21
+
22
+ mount(area) {
23
+ if (PublishSchedule.elements.has(area)) return;
24
+ PublishSchedule.elements.add(area);
25
+
26
+ const toggles = [...area.querySelectorAll('[data-publish-toggle]')];
27
+ const fieldFor = toggle => area.querySelector(toggle.dataset.publishToggle);
28
+ const setLater = (toggle, later) => {
29
+ const field = fieldFor(toggle);
30
+ toggle.querySelectorAll('.segmented-control__item').forEach((item) => {
31
+ item.setAttribute('aria-checked', String(item.hasAttribute('data-later') === later));
32
+ });
33
+ if (!field) return;
34
+ field.hidden = !later;
35
+ field.toggleAttribute('disabled', !later);
36
+ };
37
+
38
+ // Start on "Later" wherever a date is already set
39
+ toggles.forEach(toggle => setLater(toggle, !!fieldFor(toggle)?.getAttribute('value')));
40
+
41
+ let last = '';
42
+ const update = () => {
43
+ const detail = PublishSchedule.state(area);
44
+ area.dataset.publishState = detail.state;
45
+ area.querySelectorAll('[data-publish-date]').forEach((el) => { el.textContent = detail.publishAt ? PublishSchedule.format.format(detail.publishAt) : ''; });
46
+ area.querySelectorAll('[data-expire-date]').forEach((el) => { el.textContent = detail.expireAt ? PublishSchedule.format.format(detail.expireAt) : ''; });
47
+ const key = `${detail.state}|${detail.publishAt}|${detail.expireAt}`;
48
+ if (key !== last) {
49
+ last = key;
50
+ area.dispatchEvent(new CustomEvent('publish:change', { detail }));
51
+ }
52
+ };
53
+
54
+ area.addEventListener('segmented-control:change', (e) => {
55
+ const toggle = toggles.find(t => t.contains(e.target));
56
+ if (!toggle) return;
57
+ setLater(toggle, e.detail.item.hasAttribute('data-later'));
58
+ // Let the unsaved-changes guard and anything else watching fields know
59
+ fieldFor(toggle)?.dispatchEvent(new Event('change', { bubbles: true }));
60
+ if (e.detail.item.hasAttribute('data-later')) fieldFor(toggle)?.focus();
61
+ });
62
+ area.addEventListener('change', update);
63
+ area.addEventListener('input', update);
64
+ update();
65
+ // Custom date fields may load after this runs
66
+ customElements.whenDefined?.('p-datetime').then(update);
67
+ }
68
+
69
+ /** What a record shows as, from its status and dates, at a given time. */
70
+ static state(area, now = Date.now()) {
71
+ const status = area.querySelector('input[name="status"]:checked')?.value || 'draft';
72
+ const date = (selector) => {
73
+ const field = area.querySelector(selector);
74
+ const value = field && !field.hasAttribute('disabled') ? (field.value ?? field.getAttribute('value')) : '';
75
+ const time = value ? new Date(value) : null;
76
+ return time && !Number.isNaN(time.getTime()) ? time : null;
77
+ };
78
+ const publishAt = date('[data-publish-at]');
79
+ const expireAt = date('[data-expire-at]');
80
+ let state = status === 'active' ? 'live' : status;
81
+ if (status === 'active' && expireAt && expireAt.getTime() <= now) state = 'expired';
82
+ else if (status === 'active' && publishAt && publishAt.getTime() > now) state = 'scheduled';
83
+ return { state, publishAt, expireAt };
84
+ }
85
+
86
+ static enhanceAll(selector = '[data-publish-schedule]', root = document) {
87
+ const instance = new PublishSchedule();
88
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
89
+ return instance;
90
+ }
91
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The clear button in a toolbar search.
3
+ *
4
+ * A .toolbar__clear empties the .toolbar__input in its .toolbar__group, fires "input" so
5
+ * anything filtering on it updates, and puts focus back in the field. CSS shows the button only
6
+ * while the field has a value (the field needs a placeholder for that).
7
+ */
8
+ export class SearchClear {
9
+ static {
10
+ document.addEventListener('click', (e) => {
11
+ const button = e.target.closest('.toolbar__clear');
12
+ const input = button?.closest('.toolbar__group')?.querySelector('.toolbar__input');
13
+ if (!input) return;
14
+ input.value = '';
15
+ input.dispatchEvent(new Event('input', { bubbles: true }));
16
+ input.focus();
17
+ });
18
+ }
19
+ }
@@ -0,0 +1,43 @@
1
+ import { isDisabled } from '../util/dom.js';
2
+
3
+ // ============================================================================
4
+ // Segmented Control
5
+ // ============================================================================
6
+
7
+ /**
8
+ * Keeps exactly one .segmented-control__item pressed: aria-pressed on toggle buttons, or
9
+ * aria-checked when the items are role="radio".
10
+ */
11
+ export class SegmentedControl {
12
+ constructor() {
13
+ this.elements = new WeakSet();
14
+ }
15
+
16
+ mount(element) {
17
+ if (this.elements.has(element)) return;
18
+
19
+ const items = [...element.querySelectorAll('.segmented-control__item')];
20
+ if (!items.length) return;
21
+
22
+ const attribute = items[0].getAttribute('role') === 'radio' ? 'aria-checked' : 'aria-pressed';
23
+ const select = (selected) => {
24
+ items.forEach(item => item.setAttribute(attribute, String(item === selected)));
25
+ element.dispatchEvent(new CustomEvent('segmented-control:change', { bubbles: true, detail: { item: selected } }));
26
+ };
27
+
28
+ items.forEach(item => {
29
+ if (!item.hasAttribute(attribute)) item.setAttribute(attribute, 'false');
30
+ item.addEventListener('click', () => {
31
+ if (!isDisabled(item) && item.getAttribute(attribute) !== 'true') select(item);
32
+ });
33
+ });
34
+
35
+ this.elements.add(element);
36
+ }
37
+
38
+ static enhanceAll(selector = '.segmented-control', root = document) {
39
+ const instance = new SegmentedControl();
40
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
41
+ return instance;
42
+ }
43
+ }
@@ -0,0 +1,73 @@
1
+ import { ensureId } from '../util/dom.js';
2
+
3
+ // ============================================================================
4
+ // Dropdown Submenu
5
+ // ============================================================================
6
+
7
+ /**
8
+ * Lets keyboard and touch users open a .dropdown__submenu; pointer hover is handled in CSS.
9
+ *
10
+ * Click or ArrowRight on the trigger opens it and focuses the first item; ArrowLeft or Escape
11
+ * inside it closes it and returns focus to the trigger.
12
+ */
13
+ export class Submenu {
14
+ constructor() {
15
+ this.elements = new WeakSet();
16
+ }
17
+
18
+ mount(element) {
19
+ if (this.elements.has(element)) return;
20
+
21
+ const trigger = element.querySelector(':scope > .dropdown__submenu-trigger');
22
+ const content = element.querySelector(':scope > .dropdown__submenu-content');
23
+ if (!trigger || !content) return;
24
+
25
+ trigger.setAttribute('aria-haspopup', 'menu');
26
+ trigger.setAttribute('aria-controls', ensureId(content, 'submenu'));
27
+ if (!trigger.hasAttribute('aria-expanded')) trigger.setAttribute('aria-expanded', 'false');
28
+
29
+ const firstItem = () => content.querySelector('[role^="menuitem"]:not(:disabled), button:not(:disabled), a[href]');
30
+ const open = (focus) => {
31
+ trigger.setAttribute('aria-expanded', 'true');
32
+ if (focus) firstItem()?.focus();
33
+ };
34
+ const close = () => {
35
+ trigger.setAttribute('aria-expanded', 'false');
36
+ trigger.focus();
37
+ };
38
+
39
+ trigger.addEventListener('click', (e) => {
40
+ e.preventDefault();
41
+ e.stopPropagation();
42
+ if (trigger.getAttribute('aria-expanded') === 'true') {
43
+ trigger.setAttribute('aria-expanded', 'false');
44
+ } else {
45
+ open(e.detail === 0);
46
+ }
47
+ });
48
+ trigger.addEventListener('keydown', (e) => {
49
+ if (e.key === 'ArrowRight') {
50
+ e.preventDefault();
51
+ open(true);
52
+ }
53
+ });
54
+ content.addEventListener('keydown', (e) => {
55
+ if (e.key === 'ArrowLeft' || e.key === 'Escape') {
56
+ e.preventDefault();
57
+ e.stopPropagation();
58
+ close();
59
+ }
60
+ });
61
+ element.addEventListener('focusout', (e) => {
62
+ if (!element.contains(e.relatedTarget)) trigger.setAttribute('aria-expanded', 'false');
63
+ });
64
+
65
+ this.elements.add(element);
66
+ }
67
+
68
+ static enhanceAll(selector = '.dropdown__submenu', root = document) {
69
+ const instance = new Submenu();
70
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
71
+ return instance;
72
+ }
73
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * A column picker for a table.
3
+ *
4
+ * A menu with data-table-columns="#tableId" holds items with data-column-toggle="key"; each
5
+ * shows or hides every cell in that table marked data-column="key", and reflects it with
6
+ * aria-checked. Choices are remembered per table in localStorage, and rows added later follow
7
+ * them. Cells (and picker items) marked data-column-expanded only show while the table is in a
8
+ * [data-expanded] area. A cell marked data-column-span (such as the first cell of a footer row)
9
+ * spans whatever columns are left over.
10
+ */
11
+ export class TableColumns {
12
+ static elements = new WeakSet();
13
+
14
+ mount(menu) {
15
+ if (TableColumns.elements.has(menu)) return;
16
+ const table = document.querySelector(menu.dataset.tableColumns);
17
+ if (!table) return;
18
+ TableColumns.elements.add(menu);
19
+ const key = `pd-table-columns:${table.id}`;
20
+ let hidden = new Set();
21
+ try {
22
+ hidden = new Set(JSON.parse(localStorage.getItem(key)) || []);
23
+ } catch (e) {
24
+ // Storage can be unavailable (private mode, blocked); the picker still works for the visit
25
+ }
26
+
27
+ const apply = () => {
28
+ table.querySelectorAll('[data-column]').forEach((cell) => { cell.hidden = hidden.has(cell.dataset.column); });
29
+ menu.querySelectorAll('[data-column-toggle]').forEach((item) => {
30
+ item.setAttribute('role', 'menuitemcheckbox');
31
+ item.setAttribute('aria-checked', String(!hidden.has(item.dataset.columnToggle)));
32
+ });
33
+ TableColumns.span(table);
34
+ };
35
+
36
+ menu.addEventListener('click', (e) => {
37
+ const item = e.target.closest('[data-column-toggle]');
38
+ if (!item) return;
39
+ const column = item.dataset.columnToggle;
40
+ if (hidden.has(column)) hidden.delete(column);
41
+ else hidden.add(column);
42
+ try {
43
+ localStorage.setItem(key, JSON.stringify([...hidden]));
44
+ } catch (err) {
45
+ // Not remembered, but still applied
46
+ }
47
+ apply();
48
+ });
49
+
50
+ new MutationObserver(apply).observe(table.tBodies[0] || table, { childList: true });
51
+ table.closest('[data-expandable]')?.addEventListener('expandable:change', () => TableColumns.span(table));
52
+ apply();
53
+ }
54
+
55
+ /**
56
+ * Sizes each [data-column-span] cell to cover the columns its row's other cells leave, so a
57
+ * footer cell stays lined up as columns are hidden or shown. Uses computed display rather than
58
+ * layout, which also works while the table sits in a hidden tab.
59
+ */
60
+ static span(table) {
61
+ const shown = cell => getComputedStyle(cell).display !== 'none';
62
+ const width = cells => cells.filter(shown).reduce((total, cell) => total + cell.colSpan, 0);
63
+ const head = table.tHead?.rows[0];
64
+ if (!head) return;
65
+ const columns = width([...head.cells]);
66
+ table.querySelectorAll('[data-column-span]').forEach((cell) => {
67
+ const others = [...cell.parentElement.cells].filter(other => other !== cell);
68
+ cell.colSpan = Math.max(1, columns - width(others));
69
+ });
70
+ }
71
+
72
+ static enhanceAll(selector = '[data-table-columns]', root = document) {
73
+ const instance = new TableColumns();
74
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
75
+ return instance;
76
+ }
77
+ }
@@ -0,0 +1,305 @@
1
+ import { TableSort } from './table-sort.js';
2
+ import { escapeHtml } from '../util/dom.js';
3
+
4
+ /**
5
+ * Pasting a block copied from a spreadsheet into an editable table.
6
+ *
7
+ * In a table with data-table-paste, pasting more than one cell into a .table__control opens a
8
+ * dialog instead of filling the one field. It previews the block with a column picker above each
9
+ * pasted column (matched by heading when the first row looks like headings, otherwise by position
10
+ * from the column pasted into), and asks whether to update rows starting at the one pasted into
11
+ * or add the block as new rows; lines that run past the last row can become new rows. Values a
12
+ * select has no option for, or text in a number column, are marked and skipped. Give the
13
+ * attribute a <template> selector (data-table-paste="#rowTemplate") to allow adding rows.
14
+ *
15
+ * Applying sets each control's value and fires input and change, so the page's own edit
16
+ * handling runs, then the table fires "table:paste" with { updated, added, undo }.
17
+ */
18
+ export class TablePaste {
19
+ static elements = new WeakSet();
20
+
21
+ static PREVIEW_ROWS = 6;
22
+
23
+ mount(table) {
24
+ if (TablePaste.elements.has(table) || !table.tBodies[0]) return;
25
+ TablePaste.elements.add(table);
26
+ table.tBodies[0].addEventListener('paste', (event) => {
27
+ const control = event.target.closest('.table__control');
28
+ const text = event.clipboardData?.getData('text/plain') ?? '';
29
+ if (!control || !/[\t\n]/.test(text.replace(/\r?\n$/, ''))) return;
30
+ const grid = TablePaste.parse(text);
31
+ if (grid.length < 2 && grid[0].length < 2) return;
32
+ event.preventDefault();
33
+ this._open(table, control, grid);
34
+ });
35
+ }
36
+
37
+ /** Tab-separated text as copied from a spreadsheet, honouring quoted cells. */
38
+ static parse(text) {
39
+ const rows = [[]];
40
+ let cell = '';
41
+ let quoted = false;
42
+ for (let i = 0; i < text.length; i++) {
43
+ const char = text[i];
44
+ if (quoted) {
45
+ if (char === '"' && text[i + 1] === '"') {
46
+ cell += '"';
47
+ i++;
48
+ } else if (char === '"') {
49
+ quoted = false;
50
+ } else {
51
+ cell += char;
52
+ }
53
+ } else if (char === '"' && cell === '') {
54
+ quoted = true;
55
+ } else if (char === '\t') {
56
+ rows.at(-1).push(cell);
57
+ cell = '';
58
+ } else if (char === '\n' || char === '\r') {
59
+ if (char === '\r' && text[i + 1] === '\n') i++;
60
+ rows.at(-1).push(cell);
61
+ cell = '';
62
+ rows.push([]);
63
+ } else {
64
+ cell += char;
65
+ }
66
+ }
67
+ rows.at(-1).push(cell);
68
+ if (rows.length > 1 && rows.at(-1).every(value => value === '')) rows.pop();
69
+ const width = Math.max(...rows.map(row => row.length));
70
+ return rows.map(row => [...row, ...Array(width - row.length).fill('')].map(value => value.trim()));
71
+ }
72
+
73
+ /** The table's editable columns: header label and cell index, in order. */
74
+ _columns(table) {
75
+ const sample = [...table.tBodies[0].rows].find(row => row.querySelector('.table__control'));
76
+ const head = table.tHead?.rows[0];
77
+ if (!sample || !head) return [];
78
+ return [...sample.cells]
79
+ .map((cell, index) => ({ index, control: cell.querySelector('.table__control') }))
80
+ .filter(({ control }) => control)
81
+ .map(({ index, control }) => {
82
+ const th = head.cells[index];
83
+ return {
84
+ index,
85
+ label: th?.textContent.trim() || control.getAttribute('aria-label') || `Column ${index + 1}`,
86
+ hidden: th ? getComputedStyle(th).display === 'none' : false,
87
+ };
88
+ });
89
+ }
90
+
91
+ /** What a pasted value becomes in a control, or null when it can't go there. */
92
+ static convert(control, value) {
93
+ if (value === '') return '';
94
+ if (control.tagName === 'SELECT') {
95
+ const wanted = value.toLowerCase();
96
+ const option = [...control.options].find(o => o.value.toLowerCase() === wanted || o.text.trim().toLowerCase() === wanted);
97
+ return option ? option.value : null;
98
+ }
99
+ const numeric = control.classList.contains('table__control--number') || /numeric|decimal/.test(control.inputMode);
100
+ if (numeric) {
101
+ const number = value.replace(/[^\d.-]/g, '');
102
+ return /^-?\d*\.?\d+$/.test(number) ? number : null;
103
+ }
104
+ return value;
105
+ }
106
+
107
+ _open(table, control, grid) {
108
+ const body = table.tBodies[0];
109
+ const columns = this._columns(table);
110
+ const startRow = control.closest('tr');
111
+ const startIndex = control.closest('td').cellIndex;
112
+ const template = table.dataset.tablePaste ? document.querySelector(table.dataset.tablePaste) : null;
113
+ const labels = columns.map(c => c.label.toLowerCase());
114
+ const headed = grid.length > 1 && grid[0].filter(v => labels.includes(v.toLowerCase())).length >= Math.ceil(grid[0].length / 2);
115
+ const name = (row) => {
116
+ const cell = [...row.cells].find(c => !c.matches('.table__handle, .table__checkbox'));
117
+ return (cell && TableSort.value(cell)) || 'this row';
118
+ };
119
+
120
+ const state = { mode: 'update', headed, extend: true, map: [] };
121
+ // By position across the columns on screen, from the one pasted into
122
+ const mapByPosition = () => {
123
+ const visible = columns.map((c, i) => i).filter(i => !columns[i].hidden);
124
+ const start = Math.max(0, visible.findIndex(i => columns[i].index === startIndex));
125
+ return grid[0].map((_, i) => visible[start + i] ?? -1);
126
+ };
127
+ const mapByName = () => grid[0].map(v => labels.indexOf(v.toLowerCase()));
128
+ state.map = headed ? mapByName() : mapByPosition();
129
+
130
+ const dialog = document.createElement('dialog');
131
+ dialog.className = 'modal';
132
+ dialog.setAttribute('aria-labelledby', 'tablePasteTitle');
133
+ dialog.innerHTML = `
134
+ <div class="modal__dialog modal__dialog--lg">
135
+ <div class="modal__header">
136
+ <div>
137
+ <h2 class="modal__title" id="tablePasteTitle">Paste into table</h2>
138
+ <p class="modal__description" data-paste-size></p>
139
+ </div>
140
+ <button type="button" class="modal__close" aria-label="Close" data-paste-cancel><svg class="icon" viewBox="0 0 24 24"><path d="M18 6l-12 12"/><path d="M6 6l12 12"/></svg></button>
141
+ </div>
142
+ <div class="modal__content stack stack--md">
143
+ <div class="stack stack--xs" role="radiogroup" aria-label="How to paste">
144
+ <label class="radio"><input type="radio" class="radio__input" name="tablePasteMode" value="update" checked><span class="radio__label">Update rows, starting at ${escapeHtml(name(startRow))}</span></label>
145
+ <label class="radio"><input type="radio" class="radio__input" name="tablePasteMode" value="add"${template ? '' : ' disabled'}><span class="radio__label">Add as new rows at the end</span></label>
146
+ </div>
147
+ <div class="stack stack--xs">
148
+ <label class="checkbox"><input type="checkbox" class="checkbox__input" data-paste-headed${headed ? ' checked' : ''}${grid.length > 1 ? '' : ' disabled'}><span class="checkbox__label">First row is headings</span></label>
149
+ <label class="checkbox" data-paste-extend-option><input type="checkbox" class="checkbox__input" data-paste-extend checked><span class="checkbox__label" data-paste-extend-label></span></label>
150
+ </div>
151
+ <div class="table__wrapper"><table class="table table--compact"><thead class="table__header"></thead><tbody class="table__body"></tbody></table></div>
152
+ </div>
153
+ <div class="modal__footer modal__footer--between">
154
+ <p class="text--sm text--muted" data-paste-summary aria-live="polite"></p>
155
+ <div class="cluster cluster--sm">
156
+ <button type="button" class="btn btn--outline" data-paste-cancel>Cancel</button>
157
+ <button type="button" class="btn btn--primary" data-paste-apply><svg class="icon" viewBox="0 0 24 24"><path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"/><path d="M9 3m0 2a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2v0a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z"/></svg>Paste</button>
158
+ </div>
159
+ </div>
160
+ </div>`;
161
+
162
+ const $ = selector => dialog.querySelector(selector);
163
+ const sampleControls = [...startRow.cells].map(cell => cell.querySelector('.table__control'));
164
+ const rowsBelow = () => {
165
+ const rows = [...body.rows].filter(row => row.offsetParent !== null);
166
+ return rows.slice(rows.indexOf(startRow));
167
+ };
168
+
169
+ /** Every value that would be written: { row (or null for a new row), line, column, value }. */
170
+ const plan = () => {
171
+ const lines = state.headed ? grid.slice(1) : grid;
172
+ const existing = state.mode === 'update' ? rowsBelow() : [];
173
+ const writes = [];
174
+ let skipped = 0;
175
+ let added = 0;
176
+ let dropped = 0;
177
+ lines.forEach((line, l) => {
178
+ const row = existing[l] || null;
179
+ if (!row && state.mode === 'update' && !(state.extend && template)) {
180
+ dropped++;
181
+ return;
182
+ }
183
+ if (!row) added++;
184
+ line.forEach((value, i) => {
185
+ const target = columns[state.map[i]];
186
+ if (!target) return;
187
+ const control = (row || startRow).cells[target.index]?.querySelector('.table__control') || sampleControls[target.index];
188
+ const converted = TablePaste.convert(control, value);
189
+ if (converted === null) {
190
+ skipped++;
191
+ return;
192
+ }
193
+ writes.push({ row, line: l, index: target.index, value: converted });
194
+ });
195
+ });
196
+ return { lines, existing, writes, skipped, added, dropped, extra: Math.max(0, lines.length - existing.length) };
197
+ };
198
+
199
+ const render = () => {
200
+ const result = plan();
201
+ const options = ['<option value="-1">Skip</option>']
202
+ .concat(columns.map((c, i) => `<option value="${i}">${escapeHtml(c.label)}${c.hidden ? ' (hidden)' : ''}</option>`)).join('');
203
+ $('thead').innerHTML = `<tr class="table__row">${grid[0].map((_, i) => `<th class="table__head"><select class="table__control" data-paste-column="${i}" aria-label="Column ${i + 1} goes into">${options}</select></th>`).join('')}</tr>`;
204
+ dialog.querySelectorAll('[data-paste-column]').forEach((select, i) => { select.value = String(state.map[i]); });
205
+
206
+ const shown = result.lines.slice(0, TablePaste.PREVIEW_ROWS);
207
+ const rows = shown.map(line => `<tr class="table__row">${line.map((value, i) => {
208
+ const target = columns[state.map[i]];
209
+ const control = target && sampleControls[target.index];
210
+ const invalid = control && TablePaste.convert(control, value) === null;
211
+ const attrs = !target ? ' data-paste-skipped' : invalid ? ` data-paste-invalid title="${escapeHtml(control.tagName === 'SELECT' ? `Not one of the ${target.label} options` : `${target.label} needs a number`)}"` : '';
212
+ return `<td class="table__cell"${attrs}>${escapeHtml(value) || '<span class="text--muted">–</span>'}</td>`;
213
+ }).join('')}</tr>`);
214
+ if (result.lines.length > shown.length) {
215
+ rows.push(`<tr class="table__row"><td class="table__cell text--muted" colspan="${grid[0].length}">and ${result.lines.length - shown.length} more ${result.lines.length - shown.length === 1 ? 'row' : 'rows'}</td></tr>`);
216
+ }
217
+ $('tbody').innerHTML = rows.join('');
218
+
219
+ $('[data-paste-size]').textContent = `${result.lines.length} ${result.lines.length === 1 ? 'row' : 'rows'} × ${grid[0].length} ${grid[0].length === 1 ? 'column' : 'columns'} from the clipboard`;
220
+ $('[data-paste-extend-option]').hidden = !template || state.mode !== 'update' || result.extra === 0;
221
+ $('[data-paste-extend-label]').textContent = `Add ${result.extra} new ${result.extra === 1 ? 'row' : 'rows'} for the lines past the last row`;
222
+
223
+ const updatedRows = new Set(result.writes.filter(w => w.row).map(w => w.row)).size;
224
+ const parts = [];
225
+ if (updatedRows) parts.push(`Updates ${updatedRows} ${updatedRows === 1 ? 'row' : 'rows'}`);
226
+ if (result.added) parts.push(`${parts.length ? 'adds' : 'Adds'} ${result.added} ${result.added === 1 ? 'row' : 'rows'}`);
227
+ if (result.skipped) parts.push(`skips ${result.skipped} ${result.skipped === 1 ? 'value' : 'values'}`);
228
+ if (result.dropped) parts.push(`leaves out ${result.dropped} ${result.dropped === 1 ? 'line' : 'lines'} past the last row`);
229
+ $('[data-paste-summary]').textContent = parts.length ? `${parts.join(', ')}.` : 'Nothing to paste with these columns.';
230
+ $('[data-paste-apply]').disabled = !result.writes.length && !result.added;
231
+ };
232
+
233
+ const close = () => {
234
+ dialog.close();
235
+ dialog.remove();
236
+ control.focus();
237
+ };
238
+
239
+ const apply = () => {
240
+ const result = plan();
241
+ const added = [];
242
+ const previous = [];
243
+ const newRows = new Map();
244
+ result.writes.forEach((write) => {
245
+ let row = write.row;
246
+ if (!row) {
247
+ row = newRows.get(write.line);
248
+ if (!row) {
249
+ row = template.content.querySelector('tr').cloneNode(true);
250
+ row.classList.add('table__row--new');
251
+ body.append(row);
252
+ init(row);
253
+ newRows.set(write.line, row);
254
+ added.push(row);
255
+ }
256
+ }
257
+ const target = row.cells[write.index].querySelector('.table__control');
258
+ if (row === write.row) previous.push({ control: target, value: target.value });
259
+ target.value = write.value;
260
+ target.dispatchEvent(new Event('input', { bubbles: true }));
261
+ target.dispatchEvent(new Event('change', { bubbles: true }));
262
+ });
263
+ close();
264
+ const updated = [...new Set(result.writes.filter(w => w.row).map(w => w.row))];
265
+ const undo = () => {
266
+ previous.reverse().forEach(({ control: target, value }) => {
267
+ target.value = value;
268
+ target.dispatchEvent(new Event('input', { bubbles: true }));
269
+ target.dispatchEvent(new Event('change', { bubbles: true }));
270
+ });
271
+ added.forEach(row => row.remove());
272
+ };
273
+ table.dispatchEvent(new CustomEvent('table:paste', { bubbles: true, detail: { updated, added, undo } }));
274
+ };
275
+
276
+ dialog.addEventListener('change', (e) => {
277
+ if (e.target.name === 'tablePasteMode') state.mode = e.target.value;
278
+ else if (e.target.matches('[data-paste-headed]')) {
279
+ state.headed = e.target.checked;
280
+ state.map = state.headed ? mapByName() : mapByPosition();
281
+ } else if (e.target.matches('[data-paste-extend]')) state.extend = e.target.checked;
282
+ else if (e.target.matches('[data-paste-column]')) state.map[Number(e.target.dataset.pasteColumn)] = Number(e.target.value);
283
+ render();
284
+ });
285
+ dialog.addEventListener('click', (e) => {
286
+ if (e.target.closest('[data-paste-cancel]') || e.target === dialog) close();
287
+ else if (e.target.closest('[data-paste-apply]')) apply();
288
+ });
289
+ dialog.addEventListener('cancel', (e) => {
290
+ e.preventDefault();
291
+ close();
292
+ });
293
+
294
+ render();
295
+ (table.closest('dialog[open]') || document.body).append(dialog);
296
+ dialog.showModal();
297
+ $('[data-paste-apply]').focus();
298
+ }
299
+
300
+ static enhanceAll(selector = '[data-table-paste]', root = document) {
301
+ const instance = new TablePaste();
302
+ root.querySelectorAll(selector).forEach(el => instance.mount(el));
303
+ return instance;
304
+ }
305
+ }