@telepath-computer/television 1.5.10 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/THIRD-PARTY-NOTICES.txt +701 -0
  2. package/dist/cli.cjs +9035 -596
  3. package/dist/onboarding/tv-guide/welcome.html +14 -4
  4. package/dist/skills/television/SKILL.md +39 -33
  5. package/dist/skills/television/resources.md +4 -4
  6. package/dist/skills/television/templates.md +77 -0
  7. package/dist/skills/television/theming.md +31 -17
  8. package/dist/templates/calendar/README.md +17 -0
  9. package/dist/{skills/tv-tasks → templates/calendar}/THIRD-PARTY-NOTICES.txt +22 -22
  10. package/dist/templates/calendar/calendar-attendees.js +131 -0
  11. package/dist/templates/calendar/calendar-event.js +22 -0
  12. package/dist/templates/calendar/calendar-motion.js +273 -0
  13. package/dist/templates/calendar/calendar-page.js +403 -0
  14. package/dist/templates/calendar/calendar-time-axis.js +32 -0
  15. package/dist/templates/calendar/calendar-week.js +711 -0
  16. package/dist/templates/calendar/data.json +3 -0
  17. package/dist/templates/calendar/icon.svg +1 -0
  18. package/dist/templates/calendar/index.html +27 -0
  19. package/dist/templates/calendar/manifest.json +148 -0
  20. package/dist/templates/calendar/styles.css +771 -0
  21. package/dist/templates/checklist/README.md +45 -0
  22. package/dist/templates/checklist/THIRD-PARTY-NOTICES.txt +29 -0
  23. package/dist/templates/checklist/data.json +1 -0
  24. package/dist/templates/checklist/icon.svg +8 -0
  25. package/dist/templates/checklist/icons.css +61 -0
  26. package/dist/templates/checklist/index.html +47 -0
  27. package/dist/templates/checklist/manifest.json +49 -0
  28. package/dist/templates/checklist/model.d.ts +30 -0
  29. package/dist/templates/checklist/model.js +60 -0
  30. package/dist/templates/checklist/page.js +425 -0
  31. package/dist/templates/checklist/styles.css +206 -0
  32. package/dist/templates/document/README.md +55 -0
  33. package/dist/templates/document/THIRD-PARTY-NOTICES.txt +1080 -0
  34. package/dist/templates/document/data.json +3 -0
  35. package/dist/templates/document/editor.css +1 -0
  36. package/dist/templates/document/editor.js +37 -0
  37. package/dist/templates/document/icon.svg +6 -0
  38. package/dist/templates/document/index.html +29 -0
  39. package/dist/templates/document/manifest.json +22 -0
  40. package/dist/templates/document/page.js +190 -0
  41. package/dist/templates/document/styles.css +76 -0
  42. package/dist/templates/map/README.md +85 -0
  43. package/dist/templates/map/THIRD-PARTY-NOTICES.txt +84 -0
  44. package/dist/templates/map/data.json +1 -0
  45. package/dist/templates/map/icon.svg +8 -0
  46. package/dist/templates/map/icons.svg +43 -0
  47. package/dist/templates/map/index.html +95 -0
  48. package/dist/templates/map/manifest.json +227 -0
  49. package/dist/templates/map/map-model.js +18 -0
  50. package/dist/templates/map/map.css +202 -0
  51. package/dist/templates/map/map.js +728 -0
  52. package/dist/templates/map/vendor/LICENSE +26 -0
  53. package/dist/templates/map/vendor/README.md +11 -0
  54. package/dist/templates/map/vendor/leaflet.css +661 -0
  55. package/dist/templates/map/vendor/leaflet.js +6 -0
  56. package/dist/templates/map/vendor/lucide/LICENSE +43 -0
  57. package/dist/templates/map/vendor/lucide/README.md +46 -0
  58. package/dist/templates/map/vendor/lucide/icons.js +832 -0
  59. package/dist/templates/map/vendor/lucide/svg/airport.svg +15 -0
  60. package/dist/templates/map/vendor/lucide/svg/bar.svg +17 -0
  61. package/dist/templates/map/vendor/lucide/svg/beach.svg +17 -0
  62. package/dist/templates/map/vendor/lucide/svg/bridge.svg +20 -0
  63. package/dist/templates/map/vendor/lucide/svg/bus.svg +21 -0
  64. package/dist/templates/map/vendor/lucide/svg/church.svg +19 -0
  65. package/dist/templates/map/vendor/lucide/svg/coffee.svg +18 -0
  66. package/dist/templates/map/vendor/lucide/svg/ferry.svg +19 -0
  67. package/dist/templates/map/vendor/lucide/svg/flag.svg +15 -0
  68. package/dist/templates/map/vendor/lucide/svg/heart.svg +15 -0
  69. package/dist/templates/map/vendor/lucide/svg/home.svg +16 -0
  70. package/dist/templates/map/vendor/lucide/svg/hospital.svg +19 -0
  71. package/dist/templates/map/vendor/lucide/svg/hotel.svg +24 -0
  72. package/dist/templates/map/vendor/lucide/svg/info.svg +17 -0
  73. package/dist/templates/map/vendor/lucide/svg/landmark.svg +20 -0
  74. package/dist/templates/map/vendor/lucide/svg/mountain.svg +15 -0
  75. package/dist/templates/map/vendor/lucide/svg/museum.svg +20 -0
  76. package/dist/templates/map/vendor/lucide/svg/music.svg +17 -0
  77. package/dist/templates/map/vendor/lucide/svg/park.svg +18 -0
  78. package/dist/templates/map/vendor/lucide/svg/parking.svg +16 -0
  79. package/dist/templates/map/vendor/lucide/svg/pin.svg +16 -0
  80. package/dist/templates/map/vendor/lucide/svg/restaurant.svg +17 -0
  81. package/dist/templates/map/vendor/lucide/svg/school.svg +20 -0
  82. package/dist/templates/map/vendor/lucide/svg/shop.svg +17 -0
  83. package/dist/templates/map/vendor/lucide/svg/sports.svg +19 -0
  84. package/dist/templates/map/vendor/lucide/svg/star.svg +15 -0
  85. package/dist/templates/map/vendor/lucide/svg/theatre.svg +23 -0
  86. package/dist/templates/map/vendor/lucide/svg/train.svg +20 -0
  87. package/dist/templates/map/vendor/lucide/svg/viewpoint.svg +20 -0
  88. package/dist/templates/map/vendor/lucide/svg/work.svg +18 -0
  89. package/dist/templates/sticky-note/Caveat-Medium.woff2 +0 -0
  90. package/dist/templates/sticky-note/README.md +47 -0
  91. package/dist/templates/sticky-note/THIRD-PARTY-NOTICES.txt +127 -0
  92. package/dist/templates/sticky-note/data.json +1 -0
  93. package/dist/templates/sticky-note/icon.svg +16 -0
  94. package/dist/templates/sticky-note/icons.css +61 -0
  95. package/dist/templates/sticky-note/index.html +31 -0
  96. package/dist/templates/sticky-note/manifest.json +27 -0
  97. package/dist/templates/sticky-note/model.d.ts +33 -0
  98. package/dist/templates/sticky-note/model.js +152 -0
  99. package/dist/templates/sticky-note/page.js +84 -0
  100. package/dist/templates/sticky-note/styles.css +140 -0
  101. package/dist/templates/table/README.md +107 -0
  102. package/dist/templates/table/data.json +4 -0
  103. package/dist/templates/table/icon.svg +6 -0
  104. package/dist/templates/table/index.html +15 -0
  105. package/dist/templates/table/manifest.json +70 -0
  106. package/dist/templates/table/model.d.ts +164 -0
  107. package/dist/templates/table/model.js +395 -0
  108. package/dist/templates/table/page.js +1045 -0
  109. package/dist/templates/table/selection-model.d.ts +67 -0
  110. package/dist/templates/table/selection-model.js +163 -0
  111. package/dist/templates/table/styles.css +522 -0
  112. package/dist/views/markdown/THIRD-PARTY-NOTICES.txt +408 -0
  113. package/dist/views/markdown/index.html +21 -21
  114. package/dist/web/assets/main-CRSNodQt.js +864 -0
  115. package/dist/web/assets/main-DnvQkpg4.css +1 -0
  116. package/dist/web/index.html +2 -2
  117. package/package.json +1 -1
  118. package/dist/skills/tv-calendar/SKILL.md +0 -100
  119. package/dist/skills/tv-calendar/calendar.css +0 -1
  120. package/dist/skills/tv-calendar/calendar.js +0 -400
  121. package/dist/skills/tv-table/SKILL.md +0 -95
  122. package/dist/skills/tv-tasks/SKILL.md +0 -269
  123. package/dist/skills/tv-tasks/task.css +0 -180
  124. package/dist/skills/tv-tasks/task.js +0 -304
  125. package/dist/web/assets/calendar-DToAnkzj.png +0 -0
  126. package/dist/web/assets/main-CekDfJPz.js +0 -848
  127. package/dist/web/assets/main-CunC2_Nx.css +0 -1
  128. package/dist/web/assets/markdown-DdDrJuVK.png +0 -0
  129. package/dist/web/assets/table-oeG9uAN1.png +0 -0
  130. package/dist/web/assets/tasks-D4xqXFPl.png +0 -0
@@ -0,0 +1,1045 @@
1
+ /** Editable Table page: renders tolerant store state and scopes interactive writes. */
2
+ import {
3
+ deleteValue, getAccess, getConnectionStatus, getStore, onAccessChanged,
4
+ onConnectionStatusChanged, onValue, push, ref, remove, runTransaction, set, update,
5
+ } from "/sdk/v1/resources.js";
6
+ import {
7
+ AXIS_SIZES, MINIMUM_AXIS_SIZE, createAxisRenumberUpdate, displayAxis, planAdd,
8
+ planCellCommit, planClear, planDelete, planInsert, planResize, planSetHeader, readTable,
9
+ } from "./model.js";
10
+ import {
11
+ cellSelectionAt, enterTable, moveSelection, reconcileSelection,
12
+ selectAxis, selectionAfterAdd, selectionAfterDelete, selectionAfterInsert, selectionForMenu,
13
+ } from "./selection-model.js";
14
+
15
+ const main = document.querySelector(".table-page");
16
+ const statusRegion = main.querySelector(".table-status");
17
+ const resizeAnnouncement = main.querySelector(".table-resize-announcement");
18
+ const store = getStore();
19
+ const root = ref(store);
20
+ const KEYBOARD_RESIZE_STEP = 8;
21
+
22
+ let value;
23
+ let model;
24
+ let received = false;
25
+ let unavailable = false;
26
+ let access = null;
27
+ let accessKnown = false;
28
+ let connection = getConnectionStatus();
29
+ let unsubscribe = null;
30
+ let selection = null;
31
+ let editing = null;
32
+ let menu = null;
33
+ let resizing = null;
34
+ let failure = false;
35
+ let failureAfterReconnect = false;
36
+ let failureTimer;
37
+ let suppressGridEntry = false;
38
+ // A pointer press outside the editor lets the click handler choose what follows
39
+ // the commit instead of the editor focusout handler choosing first.
40
+ let pointerMovedFocus = false;
41
+ let rendering = false;
42
+ let interactionVersion = 0;
43
+ let menuObserver = null;
44
+ let renderedAxes = { columns: displayAxis([]), rows: displayAxis([]) };
45
+ let pageActionSelection = null;
46
+ let gridEntryScrollPosition = { left: 0, top: 0 };
47
+
48
+ const rejectedNoWriteReasons = new Set([
49
+ "unreadable", "invalid-target", "invalid-selection", "missing-keys", "invalid-keys",
50
+ "multiple-renumbering-required",
51
+ ]);
52
+
53
+ function escapeHtml(value) {
54
+ return String(value ?? "").replace(/[&<>"']/g, character => ({
55
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
56
+ })[character]);
57
+ }
58
+
59
+ function shownText(text) {
60
+ return text.replace(/\r\n|[\r\n]/g, " ");
61
+ }
62
+
63
+ function columnLetter(index) {
64
+ let label = "";
65
+ let value = index + 1;
66
+ while (value > 0) {
67
+ value -= 1;
68
+ label = String.fromCharCode(65 + value % 26) + label;
69
+ value = Math.floor(value / 26);
70
+ }
71
+ return label;
72
+ }
73
+
74
+ function canWrite() {
75
+ return received && !unavailable && model !== null && access === "read-write" && connection === "connected";
76
+ }
77
+
78
+ function buildAxes() {
79
+ return {
80
+ columns: displayAxis(model?.columns ?? []),
81
+ rows: displayAxis(model?.rows ?? []),
82
+ };
83
+ }
84
+
85
+ function axes() {
86
+ return renderedAxes;
87
+ }
88
+
89
+ function indexOf(items, id) {
90
+ return items.findIndex(item => item.id === id);
91
+ }
92
+
93
+ function axisRange(kind, selected = selection) {
94
+ if (selected?.kind !== kind) return null;
95
+ const items = axes()[kind];
96
+ const positions = selected.ids.map(id => indexOf(items, id)).sort((left, right) => left - right);
97
+ return positions.some(position => position < 0) ? null : { start: positions[0], end: positions.at(-1) };
98
+ }
99
+
100
+ function selectedCellPosition(selected = selection) {
101
+ if (selected?.kind !== "cell") return null;
102
+ const displayed = axes();
103
+ const rowIndex = indexOf(displayed.rows, selected.rowId);
104
+ const columnIndex = indexOf(displayed.columns, selected.columnId);
105
+ return rowIndex < 0 || columnIndex < 0 ? null : { rowIndex, columnIndex };
106
+ }
107
+
108
+ function rowSelected(rowIndex) {
109
+ return selection?.kind === "rows" && selection.ids.includes(axes().rows[rowIndex]?.id);
110
+ }
111
+
112
+ function columnSelected(columnIndex) {
113
+ return selection?.kind === "columns" && selection.ids.includes(axes().columns[columnIndex]?.id);
114
+ }
115
+
116
+ function cellSelectionKind(rowIndex, columnIndex) {
117
+ const position = selectedCellPosition();
118
+ if (position?.rowIndex === rowIndex && position.columnIndex === columnIndex) return "cell";
119
+ if (rowSelected(rowIndex) || columnSelected(columnIndex)) return "range";
120
+ return "none";
121
+ }
122
+
123
+ function referenceEmphasis(axis, index) {
124
+ if (axis === "rows" && rowSelected(index) || axis === "columns" && columnSelected(index)) return "selected";
125
+ const cell = selectedCellPosition();
126
+ if (axis === "rows" && cell?.rowIndex === index || axis === "columns" && cell?.columnIndex === index) return "related";
127
+ return "none";
128
+ }
129
+
130
+ function menuTrigger(kind, index) {
131
+ return menu?.kind === kind && menu.triggerId === axes()[kind][index]?.id;
132
+ }
133
+
134
+ function referenceButton(kind, index) {
135
+ const isRows = kind === "rows";
136
+ const selected = isRows ? rowSelected(index) : columnSelected(index);
137
+ const label = isRows ? `Select row ${index + 1}` : `Select column ${columnLetter(index)}`;
138
+ const anchorId = selection?.kind === kind ? selection.anchorId : null;
139
+ const item = axes()[kind][index];
140
+ const size = displayedSize(kind, index);
141
+ const axisName = isRows ? "row" : "column";
142
+ const dimension = isRows ? "tall" : "wide";
143
+ const description = `${size} pixels ${dimension}.${canWrite() ? " Select this " + axisName + ", then use plus or minus to resize." : ""}`;
144
+ const style = isRows ? `--table-current-row-height: ${size}px` : `width: ${size}px`;
145
+ return `<div class="table-${axisName}-reference-item" style="${style}">
146
+ <button type="button" class="table-reference-item" id="table-${axisName}-reference-${index + 1}"
147
+ data-${isRows ? "row" : "column"}-select data-${isRows ? "row" : "column"}-index="${index}"
148
+ data-emphasis="${referenceEmphasis(kind, index)}"
149
+ aria-label="${label}" aria-haspopup="${canWrite() ? "menu" : "false"}" aria-pressed="${selected}"
150
+ aria-description="${description}" ${canWrite() ? `aria-expanded="${menuTrigger(kind, index)}"` : ""}
151
+ tabindex="${anchorId === item?.id ? 0 : -1}">${isRows ? index + 1 : columnLetter(index)}</button>
152
+ ${canWrite() ? `<span class="table-${axisName}-resize-handle" aria-hidden="true"></span>` : ""}
153
+ </div>`;
154
+ }
155
+
156
+ function displayedSize(kind, index) {
157
+ const item = axes()[kind][index];
158
+ if (resizing?.axis === kind && resizing.targetId === item?.id) return resizing.previewSize;
159
+ const rules = AXIS_SIZES[kind];
160
+ return item?.[rules.field] ?? rules.defaultValue;
161
+ }
162
+
163
+ function bodyCellText(rowIndex, columnKey) {
164
+ const cells = model.rows[rowIndex]?.cells;
165
+ return cells && Object.hasOwn(cells, columnKey) ? cells[columnKey] : "";
166
+ }
167
+
168
+ function bodyCell(row, column, rowIndex, columnIndex) {
169
+ const selected = cellSelectionKind(rowIndex, columnIndex);
170
+ const text = row.kind === "stored" && column.kind === "stored"
171
+ ? bodyCellText(rowIndex, column.key) : "";
172
+ const isEditing = editing?.kind === "cell" && editing.rowIndex === rowIndex && editing.columnIndex === columnIndex
173
+ && editing.rowId === row.id && editing.columnId === column.id;
174
+ const content = isEditing
175
+ ? `<textarea class="table-input table-cell-input" rows="1" aria-label="Row ${rowIndex + 1}, column ${columnLetter(columnIndex)}" spellcheck="false">${escapeHtml(editing.text)}</textarea>`
176
+ : `<span>${escapeHtml(shownText(text))}</span>`;
177
+ const isHeader = model.headerRow && rowIndex === 0;
178
+ return `<td class="table-cell" role="${isHeader ? "columnheader" : "gridcell"}" data-header="${isHeader}" data-cell data-row-index="${rowIndex}" data-column-index="${columnIndex}"
179
+ ${row.kind === "stored" ? `data-row-key="${escapeHtml(row.key)}"` : ""}
180
+ ${column.kind === "stored" ? `data-column-key="${escapeHtml(column.key)}"` : ""}
181
+ data-selection="${selected}" aria-selected="${selected !== "none"}" aria-colindex="${columnIndex + 1}"
182
+ tabindex="${selected === "cell" && !isEditing ? 0 : -1}">${content}</td>`;
183
+ }
184
+
185
+ function contextMenu() {
186
+ if (!menu || (selection?.kind !== "rows" && selection?.kind !== "columns") || !canWrite()) return "";
187
+ const isRows = selection.kind === "rows";
188
+ const range = axisRange(selection.kind);
189
+ const items = axes()[selection.kind].slice(range?.start ?? 0, (range?.end ?? -1) + 1);
190
+ const storedCount = items.filter(item => item.kind === "stored").length;
191
+ const noun = isRows ? "row" : "column";
192
+ const before = isRows ? "above" : "left";
193
+ const after = isRows ? "below" : "right";
194
+ const trigger = `table-${noun}-reference-${menu.index + 1}`;
195
+ const headerAction = isRows && menu.index === 0
196
+ ? `<hr><tv-menu-item role="menuitem" data-menu-action="toggle-header"><span>${model.headerRow ? "Remove" : "Make"} header row</span></tv-menu-item>` : "";
197
+ return `<tv-menu class="table-context-menu table-${noun}-context-menu" trigger="${trigger}" open role="menu" aria-label="${isRows ? "Row" : "Column"} actions">
198
+ <tv-menu-item role="menuitem" data-menu-action="insert-before"><span>Insert ${noun} ${before}</span></tv-menu-item>
199
+ <tv-menu-item role="menuitem" data-menu-action="insert-after"><span>Insert ${noun} ${after}</span></tv-menu-item>
200
+ ${storedCount ? `<tv-menu-item role="menuitem" data-menu-action="delete" intent="danger"><span>Delete ${noun}${storedCount === 1 ? "" : "s"}</span></tv-menu-item>` : ""}
201
+ ${headerAction}
202
+ </tv-menu>`;
203
+ }
204
+
205
+ function selectionTarget() {
206
+ if (selection?.kind === "cell") {
207
+ const position = selectedCellPosition();
208
+ return position && main.querySelector(`[data-cell][data-row-index="${position.rowIndex}"][data-column-index="${position.columnIndex}"]`);
209
+ }
210
+ if (selection?.kind === "rows" || selection?.kind === "columns") {
211
+ const index = indexOf(axes()[selection.kind], selection.anchorId);
212
+ return main.querySelector(`[data-${selection.kind === "rows" ? "row" : "column"}-index="${index}"]`);
213
+ }
214
+ return null;
215
+ }
216
+
217
+ function selectionAtSamePosition(selected, sourceAxes, targetAxes) {
218
+ if (selected?.kind === "cell") {
219
+ return cellSelectionAt(targetAxes, indexOf(sourceAxes.rows, selected.rowId), indexOf(sourceAxes.columns, selected.columnId));
220
+ }
221
+ if (selected?.kind === "rows" || selected?.kind === "columns") {
222
+ const sourceItems = sourceAxes[selected.kind];
223
+ const anchorIndex = indexOf(sourceItems, selected.anchorId);
224
+ const activeIndex = indexOf(sourceItems, selected.activeId);
225
+ if (anchorIndex < 0 || activeIndex < 0) return null;
226
+ const anchor = selectAxis(null, selected.kind, anchorIndex, false, targetAxes);
227
+ return anchor && selectAxis(anchor, selected.kind, activeIndex, true, targetAxes);
228
+ }
229
+ return null;
230
+ }
231
+
232
+ function replaceContents(markup) {
233
+ menuObserver?.disconnect();
234
+ menuObserver = null;
235
+ rendering = true;
236
+ for (const child of [...main.children]) {
237
+ if (child !== statusRegion && child !== resizeAnnouncement) child.remove();
238
+ }
239
+ statusRegion.insertAdjacentHTML("beforebegin", markup);
240
+ rendering = false;
241
+ const menuElement = main.querySelector("tv-menu");
242
+ if (!menuElement) return;
243
+ menuObserver = new MutationObserver(() => {
244
+ if (!menuElement.isConnected || menuElement.hasAttribute("open")) return;
245
+ menuObserver?.disconnect();
246
+ menuObserver = null;
247
+ if (menu === null) return;
248
+ menu = null;
249
+ render("selection");
250
+ });
251
+ menuObserver.observe(menuElement, { attributes: true, attributeFilter: ["open"] });
252
+ }
253
+
254
+ function keepClearOfFrozenAreas(target) {
255
+ const scroll = main.querySelector(".table-scroll");
256
+ if (!(scroll instanceof HTMLElement) || !(target instanceof HTMLElement)) return;
257
+ const scrollBox = scroll.getBoundingClientRect();
258
+ const targetBox = target.getBoundingClientRect();
259
+ const columnStripBox = main.querySelector(".table-column-strip")?.getBoundingClientRect();
260
+ const rowStripBox = main.querySelector(".table-row-strip")?.getBoundingClientRect();
261
+ const sheet = main.querySelector(".table-sheet");
262
+ const sheetStyle = sheet instanceof HTMLElement ? getComputedStyle(sheet) : null;
263
+ const columnGap = Number.parseFloat(sheetStyle?.columnGap ?? "0");
264
+ const rowGap = Number.parseFloat(sheetStyle?.rowGap ?? "0");
265
+ const headerBox = model?.headerRow && !target.closest('[data-row-index="0"]')
266
+ ? main.querySelector('[data-cell][data-row-index="0"]')?.getBoundingClientRect() : null;
267
+ const minimumX = (rowStripBox?.right ?? scrollBox.left) + columnGap;
268
+ const minimumY = Math.max(
269
+ (columnStripBox?.bottom ?? scrollBox.top) + rowGap,
270
+ headerBox?.bottom ?? scrollBox.top,
271
+ );
272
+ let left = 0;
273
+ let top = 0;
274
+ if (!target.closest(".table-row-strip") && targetBox.left < minimumX) left = targetBox.left - minimumX;
275
+ else if (targetBox.right > scrollBox.right) left = targetBox.right - scrollBox.right;
276
+ if (!target.closest(".table-column-strip") && targetBox.top < minimumY) top = targetBox.top - minimumY;
277
+ else if (targetBox.bottom > scrollBox.bottom) top = targetBox.bottom - scrollBox.bottom;
278
+ if (left !== 0 || top !== 0) scroll.scrollBy({ left, top });
279
+ }
280
+
281
+ // "none" preserves existing focus, "leave" preserves none, and the other
282
+ // modes focus the named control after render replaces the page contents.
283
+ function render(focus = "none", nextAxes = buildAxes()) {
284
+ const previousSelectionTarget = selectionTarget();
285
+ const selectionFocused = previousSelectionTarget !== null && document.activeElement === previousSelectionTarget;
286
+ const gridFocused = document.activeElement === main.querySelector(".table-grid");
287
+ const focusedMenuItem = document.activeElement?.closest?.("tv-menu-item");
288
+ const focusedMenuIndex = focusedMenuItem ? [...main.querySelectorAll("tv-menu-item")].indexOf(focusedMenuItem) : -1;
289
+ const tableControlFocused = document.activeElement instanceof Element
290
+ && Boolean(document.activeElement.closest(".table-grid, .table-reference-strip, tv-menu"));
291
+ renderedAxes = nextAxes;
292
+ const scroll = main.querySelector(".table-scroll");
293
+ const scrollPosition = scroll ? { left: scroll.scrollLeft, top: scroll.scrollTop } : null;
294
+ const previousEditor = main.querySelector(".table-input");
295
+ const editorState = previousEditor instanceof HTMLTextAreaElement ? {
296
+ focused: document.activeElement === previousEditor,
297
+ start: previousEditor.selectionStart,
298
+ end: previousEditor.selectionEnd,
299
+ direction: previousEditor.selectionDirection,
300
+ } : null;
301
+ if (unavailable || received && model === null) {
302
+ main.dataset.editable = "false";
303
+ replaceContents(`<section class="table-unreadable" role="alert">
304
+ <span class="table-unreadable-icon"><tv-icon name="warning" size="xl"></tv-icon></span>
305
+ <h1 class="table-unreadable-title">This table can't be shown</h1>
306
+ <p class="table-unreadable-text">Television can't read the saved table data. Ask your agent to check the data and access.</p>
307
+ </section>`);
308
+ renderStatus();
309
+ return;
310
+ }
311
+ if (!received) {
312
+ main.dataset.editable = "false";
313
+ replaceContents(`<div class="table-loading" role="status" aria-label="Loading table"><tv-icon name="spinner" size="md" spinning></tv-icon></div>`);
314
+ renderStatus();
315
+ return;
316
+ }
317
+
318
+ const displayed = nextAxes;
319
+ const editable = canWrite();
320
+ main.dataset.editable = String(editable);
321
+ main.dataset.headerRow = String(model.headerRow);
322
+ const columnWidths = displayed.columns.map((_, index) => displayedSize("columns", index));
323
+ const gridWidth = columnWidths.reduce((sum, width) => sum + width, 0);
324
+ const rowNumberDigits = String(displayed.rows.length).length;
325
+ const body = displayed.rows.map((row, rowIndex) => `<tr aria-rowindex="${rowIndex + 1}" style="--table-current-row-height: ${displayedSize("rows", rowIndex)}px">
326
+ ${displayed.columns.map((column, columnIndex) => bodyCell(row, column, rowIndex, columnIndex)).join("")}</tr>`).join("");
327
+ replaceContents(`<div class="table-frame">
328
+ <div class="table-scroll"><div class="table-sheet" style="--table-grid-width: ${gridWidth}px; --table-row-reference-digits: ${rowNumberDigits}">
329
+ <div class="table-reference-corner" aria-hidden="true"></div>
330
+ <div class="table-column-strip table-reference-strip" role="group" aria-label="Column references">
331
+ ${displayed.columns.map((_, index) => referenceButton("columns", index)).join("")}
332
+ ${editable ? `<div class="table-column-add-item"><button type="button" class="table-reference-item table-add-item" data-action="add-column" aria-label="Add column at end" title="Add column at end" tabindex="-1">+</button></div>` : ""}
333
+ </div>
334
+ <div class="table-row-strip table-reference-strip" role="group" aria-label="Row references">
335
+ ${displayed.rows.map((_, index) => referenceButton("rows", index)).join("")}
336
+ ${editable ? `<div class="table-row-add-item"><button type="button" class="table-reference-item table-add-item" data-action="add-row" aria-label="Add row at end" title="Add row at end" tabindex="-1">+</button></div>` : ""}
337
+ </div>
338
+ <table class="table-grid" role="grid" aria-label="Table" aria-rowcount="${displayed.rows.length}"
339
+ aria-colcount="${displayed.columns.length}" tabindex="${selection ? -1 : 0}">
340
+ <colgroup>${columnWidths.map(width => `<col style="width: ${width}px">`).join("")}</colgroup><tbody>${body}</tbody>
341
+ </table>
342
+ </div></div>
343
+ </div>${contextMenu()}`);
344
+ renderStatus();
345
+
346
+ const nextScroll = main.querySelector(".table-scroll");
347
+ if (nextScroll && scrollPosition) nextScroll.scrollTo(scrollPosition.left, scrollPosition.top);
348
+ const nextEditor = main.querySelector(".table-input");
349
+ if (nextEditor instanceof HTMLTextAreaElement && editing) nextEditor.value = editing.text;
350
+ if (focus === "leave" || focus === "none" && !tableControlFocused) return;
351
+ queueMicrotask(() => {
352
+ if (!document.hasFocus()) return;
353
+ const preservingEditor = focus === "none" && editorState?.focused;
354
+ const preservingSelection = focus === "none" && selectionFocused;
355
+ const preservingMenu = focus === "none" && focusedMenuIndex >= 0;
356
+ const preservingGrid = focus === "none" && gridFocused;
357
+ const intendedTarget = preservingEditor || focus === "editor" ? main.querySelector(".table-input")
358
+ : focus === "grid" ? main.querySelector(".table-grid")
359
+ : focus === "menu" ? main.querySelector("tv-menu-item")
360
+ : preservingMenu ? main.querySelectorAll("tv-menu-item")[focusedMenuIndex]
361
+ : preservingGrid ? main.querySelector(".table-grid")
362
+ : preservingSelection || focus === "selection" ? selectionTarget() : null;
363
+ const target = intendedTarget ?? selectionTarget() ?? main.querySelector(".table-grid");
364
+ suppressGridEntry = target === main.querySelector(".table-grid");
365
+ target?.focus({ preventScroll: true });
366
+ suppressGridEntry = false;
367
+ if (target instanceof HTMLTextAreaElement) {
368
+ if (preservingEditor && editorState) {
369
+ target.setSelectionRange(editorState.start, editorState.end, editorState.direction);
370
+ } else {
371
+ target.setSelectionRange(target.value.length, target.value.length);
372
+ }
373
+ }
374
+ if ((preservingEditor || preservingSelection || focus === "editor" || focus === "selection") && target) {
375
+ target.scrollIntoView({ block: "nearest", inline: "nearest" });
376
+ keepClearOfFrozenAreas(target);
377
+ }
378
+ });
379
+ }
380
+
381
+ function reserveKeys(axis, count = 5) {
382
+ // Four keys can materialize the minimum drawn axis; one more is the entry
383
+ // added beyond it.
384
+ const parent = ref(store, axis);
385
+ return Array.from({ length: count }, () => push(parent).key);
386
+ }
387
+
388
+ function applyOperations(operations) {
389
+ if (operations.length === 0) return;
390
+ if (operations.length === 1) {
391
+ const operation = operations[0];
392
+ const target = ref(store, operation.path.join("/"));
393
+ return operation.kind === "set" ? set(target, operation.value) : remove(target);
394
+ }
395
+ const entries = Object.fromEntries(operations.map(operation => [
396
+ operation.path.join("/"), operation.kind === "set" ? operation.value : deleteValue(),
397
+ ]));
398
+ return update(root, entries);
399
+ }
400
+
401
+ function showFailure() {
402
+ failure = true;
403
+ clearTimeout(failureTimer);
404
+ // Six seconds keeps the short status visible long enough to notice and for
405
+ // the conformance capture to settle, without making it persistent.
406
+ failureTimer = setTimeout(() => { failure = false; renderStatus(); }, 6000);
407
+ renderStatus();
408
+ }
409
+
410
+ function reportUnsentFollowUp() {
411
+ if (connection === "disconnected") failureAfterReconnect = true;
412
+ else showFailure();
413
+ }
414
+
415
+ function renderStatus() {
416
+ const message = connection === "disconnected" ? "Reconnecting…" : failure ? "Couldn't save that change." : "";
417
+ if (statusRegion.textContent !== message) statusRegion.textContent = message;
418
+ }
419
+
420
+ function announceResize(axis, index, size) {
421
+ if (!(resizeAnnouncement instanceof HTMLElement)) return;
422
+ const label = axis === "rows" ? `Row ${index + 1}` : `Column ${columnLetter(index)}`;
423
+ const dimension = axis === "rows" ? "tall" : "wide";
424
+ resizeAnnouncement.textContent = `${label}, ${size} pixels ${dimension}`;
425
+ }
426
+
427
+ function startWithActionEcho(start, actionEcho) {
428
+ pageActionSelection = actionEcho;
429
+ try {
430
+ return start();
431
+ } finally {
432
+ pageActionSelection = null;
433
+ }
434
+ }
435
+
436
+ async function applyPlan(plan, echoSelection = null, focusEcho = true, onLocalApply = null) {
437
+ if (!canWrite()) return false;
438
+ let followUpStarted = false;
439
+ const actionVersion = interactionVersion;
440
+ const currentPageActionSelection = echoSelection
441
+ ? nextAxes => {
442
+ const selected = interactionVersion === actionVersion ? echoSelection(nextAxes) : null;
443
+ return selected ? { selection: selected, focus: focusEcho } : null;
444
+ }
445
+ : null;
446
+ if (plan.kind === "no-write") {
447
+ if (plan.reason === "multiple-renumbering-required") showFailure();
448
+ const accepted = !rejectedNoWriteReasons.has(plan.reason);
449
+ if (accepted) onLocalApply?.();
450
+ return accepted;
451
+ }
452
+ try {
453
+ if (plan.kind === "renumber") {
454
+ // A whole-store subscription gives runTransaction a held view, so its
455
+ // first optimistic value is delivered synchronously inside this call.
456
+ const pending = startWithActionEcho(
457
+ () => runTransaction(ref(store, plan.axis), createAxisRenumberUpdate(plan.request)),
458
+ currentPageActionSelection,
459
+ );
460
+ onLocalApply?.();
461
+ const outcome = await pending;
462
+ if (!outcome.committed) { showFailure(); return false; }
463
+ if (plan.operations.length > 0) {
464
+ if (!canWrite()) {
465
+ reportUnsentFollowUp();
466
+ return false;
467
+ }
468
+ // Let access, connection and value notifications queued with the
469
+ // transaction acknowledgement reach the write guard first.
470
+ await new Promise(resolve => setTimeout(resolve, 0));
471
+ if (!canWrite()) {
472
+ reportUnsentFollowUp();
473
+ return false;
474
+ }
475
+ }
476
+ }
477
+ if (plan.operations.length > 0) {
478
+ followUpStarted = plan.kind === "renumber";
479
+ const pending = startWithActionEcho(() => applyOperations(plan.operations), currentPageActionSelection);
480
+ if (plan.kind !== "renumber") onLocalApply?.();
481
+ await pending;
482
+ }
483
+ return true;
484
+ } catch (error) {
485
+ if (error?.code === "disconnected") {
486
+ if (plan.kind === "renumber" && plan.operations.length > 0 && !followUpStarted) {
487
+ reportUnsentFollowUp();
488
+ }
489
+ } else showFailure();
490
+ return false;
491
+ }
492
+ }
493
+
494
+ function beginResize(axis, index, pointerPosition, pointerId) {
495
+ if (!canWrite()) return;
496
+ const item = axes()[axis][index];
497
+ if (!item) return;
498
+ const openedSize = displayedSize(axis, index);
499
+ resizing = {
500
+ axis, targetId: item.id, openedSize, previewSize: openedSize,
501
+ pointerPosition, pointerId,
502
+ };
503
+ }
504
+
505
+ function reconcileResizing(displayed) {
506
+ if (!resizing) return;
507
+ const index = indexOf(displayed[resizing.axis], resizing.targetId);
508
+ if (index < 0) resizing = null;
509
+ }
510
+
511
+ async function finishResize() {
512
+ if (!resizing) return;
513
+ const active = resizing;
514
+ resizing = null;
515
+ const currentIndex = indexOf(axes()[active.axis], active.targetId);
516
+ if (!canWrite() || currentIndex < 0) { render(); return; }
517
+ const beforeSave = axes();
518
+ const selected = selection;
519
+ const plan = planResize(value, active.axis, currentIndex, active.openedSize, active.previewSize, reserveKeys(active.axis));
520
+ const saved = await applyPlan(plan, nextAxes => selectionAtSamePosition(selected, beforeSave, nextAxes));
521
+ render();
522
+ if (!saved) return;
523
+ const currentSize = displayedSize(active.axis, Math.min(currentIndex, axes()[active.axis].length - 1));
524
+ announceResize(active.axis, currentIndex, currentSize);
525
+ }
526
+
527
+ async function resizeSelection(direction) {
528
+ if (!canWrite() || (selection?.kind !== "rows" && selection?.kind !== "columns") || selection.ids.length !== 1) return;
529
+ const index = indexOf(axes()[selection.kind], selection.anchorId);
530
+ if (index < 0) return;
531
+ const openedSize = displayedSize(selection.kind, index);
532
+ const selected = selection;
533
+ const beforeSave = axes();
534
+ const plan = planResize(
535
+ value,
536
+ selection.kind,
537
+ index,
538
+ openedSize,
539
+ openedSize + direction * KEYBOARD_RESIZE_STEP,
540
+ reserveKeys(selection.kind),
541
+ );
542
+ const saved = await applyPlan(plan, nextAxes => selectionAtSamePosition(selected, beforeSave, nextAxes));
543
+ if (!saved) return;
544
+ announceResize(selected.kind, index, displayedSize(selected.kind, index));
545
+ }
546
+
547
+ function beginEditing(rowIndex, columnIndex, replacement) {
548
+ if (!canWrite()) return;
549
+ interactionVersion += 1;
550
+ const displayed = axes();
551
+ const selected = cellSelectionAt(displayed, rowIndex, columnIndex);
552
+ if (!selected) return;
553
+ selection = selected;
554
+ const row = displayed.rows[rowIndex];
555
+ const column = displayed.columns[columnIndex];
556
+ const openedText = row.kind === "stored" && column.kind === "stored"
557
+ ? bodyCellText(rowIndex, column.key) : "";
558
+ editing = { kind: "cell", rowId: row.id, columnId: column.id, rowIndex, columnIndex, openedText, text: replacement ?? openedText };
559
+ menu = null;
560
+ render("editor");
561
+ }
562
+
563
+ function reconcileEditing(active, displayed) {
564
+ if (!active) return null;
565
+ const columnIndex = indexOf(displayed.columns, active.columnId);
566
+ if (columnIndex < 0) return null;
567
+ const rowIndex = indexOf(displayed.rows, active.rowId);
568
+ return rowIndex < 0 ? null : { ...active, rowIndex, columnIndex };
569
+ }
570
+
571
+ async function commitEditing(command = null, restoreFocus = true, onLocalApply = null, options = {}) {
572
+ if (!editing) return false;
573
+ if (!canWrite()) {
574
+ render(options.refocusWhenDisconnected === false ? "leave" : "editor");
575
+ return false;
576
+ }
577
+ const active = editing;
578
+ const completionVersion = interactionVersion;
579
+ const plan = planCellCommit(value, { rowIndex: active.rowIndex, columnIndex: active.columnIndex }, active.openedText, active.text, {
580
+ columns: reserveKeys("columns"), rows: reserveKeys("rows"),
581
+ });
582
+ editing = null;
583
+ const beforeSave = axes();
584
+ selection = cellSelectionAt(beforeSave, Math.min(active.rowIndex, beforeSave.rows.length - 1), Math.min(active.columnIndex, beforeSave.columns.length - 1));
585
+ const provisionalMove = command
586
+ ? moveSelection(selection, command, beforeSave) : null;
587
+ if (provisionalMove) selection = provisionalMove.selection;
588
+ const targetSelection = selection;
589
+ const echoSelection = nextAxes => selectionAtSamePosition(targetSelection, beforeSave, nextAxes);
590
+ const focusTarget = !provisionalMove?.exit && restoreFocus;
591
+ render(focusTarget ? "selection" : "leave");
592
+ const saved = await applyPlan(plan, echoSelection, focusTarget, onLocalApply);
593
+ if (!saved) {
594
+ if (interactionVersion === completionVersion) render(focusTarget ? "selection" : "leave");
595
+ return false;
596
+ }
597
+ return true;
598
+ }
599
+
600
+ function clearSelection(focus = "grid") {
601
+ interactionVersion += 1;
602
+ selection = null;
603
+ menu = null;
604
+ render(focus);
605
+ }
606
+
607
+ async function clearContents() {
608
+ if (!selection || !canWrite()) return;
609
+ let logical;
610
+ if (selection.kind === "cell") logical = { kind: "cell", ...selectedCellPosition() };
611
+ else logical = { kind: selection.kind, ...axisRange(selection.kind) };
612
+ await applyPlan(planClear(value, logical), nextAxes => reconcileSelection(selection, nextAxes));
613
+ }
614
+
615
+ async function addAtEnd(axis) {
616
+ if (!canWrite()) return;
617
+ const previous = selection;
618
+ const count = Math.max(0, MINIMUM_AXIS_SIZE - model[axis].length) + 1;
619
+ const keys = reserveKeys(axis);
620
+ const newKey = keys[count - 1];
621
+ await applyPlan(planAdd(value, axis, keys), nextAxes => selectionAfterAdd(previous, axis, newKey, nextAxes));
622
+ }
623
+
624
+ async function performMenuAction(action) {
625
+ if (!menu || (selection?.kind !== "rows" && selection?.kind !== "columns") || !canWrite()) return;
626
+ const axis = selection.kind;
627
+ const range = axisRange(axis);
628
+ if (!range) return;
629
+ menu = null;
630
+ if (action === "toggle-header") {
631
+ await applyPlan(planSetHeader(!model.headerRow), nextAxes => reconcileSelection(selection, nextAxes));
632
+ return;
633
+ }
634
+ if (action === "delete") {
635
+ const formerIndex = range.start;
636
+ await applyPlan(planDelete(value, axis, range), nextAxes => selectionAfterDelete(axis, formerIndex, nextAxes));
637
+ return;
638
+ }
639
+ const side = action === "insert-before" ? "before" : "after";
640
+ const insertionIndex = side === "before" ? range.start : range.end + 1;
641
+ const drawnBefore = Math.max(0, insertionIndex - model[axis].length);
642
+ const keys = reserveKeys(axis);
643
+ const newKey = keys[drawnBefore];
644
+ await applyPlan(planInsert(value, axis, range, side, keys), nextAxes => selectionAfterInsert(axis, newKey, nextAxes));
645
+ }
646
+
647
+ function openMenu(kind, index, extend = false) {
648
+ if (!canWrite()) return;
649
+ const displayed = axes();
650
+ if (!(selection?.kind === kind && selection.ids.includes(displayed[kind][index]?.id))) {
651
+ selection = selectAxis(selection, kind, index, extend, displayed);
652
+ }
653
+ menu = { kind, index, triggerId: displayed[kind][index].id };
654
+ render("selection");
655
+ }
656
+
657
+ function openSelectionMenu() {
658
+ if (!selection || !canWrite()) return;
659
+ selection = selectionForMenu(selection, axes());
660
+ if (selection?.kind !== "rows" && selection?.kind !== "columns") return;
661
+ const index = indexOf(axes()[selection.kind], selection.anchorId);
662
+ menu = { kind: selection.kind, index, triggerId: axes()[selection.kind][index].id };
663
+ render("menu");
664
+ }
665
+
666
+ main.addEventListener("input", event => {
667
+ if (!(event.target instanceof HTMLTextAreaElement) || !editing) return;
668
+ editing.text = event.target.value;
669
+ });
670
+
671
+ main.addEventListener("click", event => { void handleClick(event); });
672
+
673
+ main.addEventListener("pointerdown", event => {
674
+ if (!(event.target instanceof Element) || event.button !== 0) return;
675
+ const columnHandle = event.target.closest(".table-column-resize-handle");
676
+ const rowHandle = event.target.closest(".table-row-resize-handle");
677
+ const handle = columnHandle ?? rowHandle;
678
+ if (!handle) return;
679
+ event.preventDefault();
680
+ const axis = columnHandle ? "columns" : "rows";
681
+ const item = handle.parentElement;
682
+ const index = item ? [...item.parentElement.children].indexOf(item) : -1;
683
+ if (index < 0) return;
684
+ const pointerPosition = axis === "columns" ? event.clientX : event.clientY;
685
+ const start = () => beginResize(axis, index, pointerPosition, event.pointerId);
686
+ if (editing) void commitEditing(null, false, start);
687
+ else start();
688
+ });
689
+
690
+ async function handleClick(event) {
691
+ if (!(event.target instanceof Element) || event.target instanceof HTMLTextAreaElement) return;
692
+ if (event.target.matches(".table-reference-corner, .table-reference-strip")) return;
693
+ interactionVersion += 1;
694
+ let actionApplied = false;
695
+ const applyClick = () => {
696
+ if (actionApplied) return;
697
+ actionApplied = true;
698
+ applyClickTarget(event.target, event.detail, event.shiftKey);
699
+ };
700
+ if (editing) {
701
+ if (!await commitEditing(null, false, applyClick) || actionApplied) return;
702
+ }
703
+ applyClick();
704
+ }
705
+
706
+ function applyClickTarget(target, detail, extend) {
707
+ const menuAction = target.closest("[data-menu-action]");
708
+ if (menuAction) { void performMenuAction(menuAction.dataset.menuAction); return; }
709
+ const action = target.closest("[data-action]");
710
+ if (action) { void addAtEnd(action.dataset.action === "add-row" ? "rows" : "columns"); return; }
711
+
712
+ const rowButton = target.closest("[data-row-select]");
713
+ if (rowButton) {
714
+ menu = null;
715
+ selection = selectAxis(selection, "rows", Number(rowButton.dataset.rowIndex), extend, axes());
716
+ render("selection");
717
+ return;
718
+ }
719
+ const columnButton = target.closest("[data-column-select]");
720
+ if (columnButton) {
721
+ menu = null;
722
+ selection = selectAxis(selection, "columns", Number(columnButton.dataset.columnIndex), extend, axes());
723
+ render("selection");
724
+ return;
725
+ }
726
+ const cell = target.closest("[data-cell]");
727
+ if (cell) {
728
+ const rowIndex = Number(cell.dataset.rowIndex);
729
+ const columnIndex = Number(cell.dataset.columnIndex);
730
+ if (detail > 1) beginEditing(rowIndex, columnIndex);
731
+ else { selection = cellSelectionAt(axes(), rowIndex, columnIndex); menu = null; render("selection"); }
732
+ }
733
+ }
734
+
735
+ main.addEventListener("contextmenu", event => {
736
+ if (!(event.target instanceof Element) || event.target.closest(".table-input")) return;
737
+ interactionVersion += 1;
738
+ const rowButton = event.target.closest("[data-row-select]");
739
+ const columnButton = event.target.closest("[data-column-select]");
740
+ if (!rowButton && !columnButton) return;
741
+ event.preventDefault();
742
+ if (editing) {
743
+ void commitEditing(null, false, () => {
744
+ openMenu(rowButton ? "rows" : "columns", Number((rowButton ?? columnButton).dataset[rowButton ? "rowIndex" : "columnIndex"]));
745
+ });
746
+ return;
747
+ }
748
+ openMenu(rowButton ? "rows" : "columns", Number((rowButton ?? columnButton).dataset[rowButton ? "rowIndex" : "columnIndex"]));
749
+ });
750
+
751
+ // Record the scroll position before an in-frame Tab can make Chromium scroll
752
+ // the grid natively; focusin restores it before choosing the entry cell.
753
+ document.addEventListener("keydown", event => {
754
+ const grid = main.querySelector(".table-grid");
755
+ if (event.defaultPrevented || event.key !== "Tab" || selection !== null || document.activeElement === grid) return;
756
+ const scroll = main.querySelector(".table-scroll");
757
+ if (scroll instanceof HTMLElement) {
758
+ gridEntryScrollPosition = { left: scroll.scrollLeft, top: scroll.scrollTop };
759
+ }
760
+ }, { capture: true });
761
+
762
+ main.addEventListener("scroll", event => {
763
+ if (!(event.target instanceof HTMLElement) || !event.target.matches(".table-scroll")) return;
764
+ gridEntryScrollPosition = { left: event.target.scrollLeft, top: event.target.scrollTop };
765
+ }, { capture: true });
766
+
767
+ main.addEventListener("focusin", event => {
768
+ if (!suppressGridEntry && event.target === main.querySelector(".table-grid") && selection === null) {
769
+ const entryScrollPosition = gridEntryScrollPosition;
770
+ main.querySelector(".table-scroll")?.scrollTo(entryScrollPosition.left, entryScrollPosition.top);
771
+ selection = enterTable(selection, axes());
772
+ render("selection");
773
+ }
774
+ });
775
+
776
+ main.addEventListener("focusout", event => {
777
+ if (rendering || !(event.target instanceof HTMLTextAreaElement) || !editing) return;
778
+ queueMicrotask(() => {
779
+ if (!rendering && !pointerMovedFocus && editing && document.activeElement !== event.target) {
780
+ void commitEditing(null, false, null, { refocusWhenDisconnected: false });
781
+ }
782
+ });
783
+ });
784
+
785
+ main.addEventListener("keydown", event => {
786
+ if (event.defaultPrevented) return;
787
+ interactionVersion += 1;
788
+ if (event.target instanceof HTMLTextAreaElement) {
789
+ if (event.isComposing) return;
790
+ if (event.key === "Escape") {
791
+ event.preventDefault();
792
+ editing = null;
793
+ render("selection");
794
+ } else if (event.key === "Enter" || event.key === "Tab") {
795
+ if (!canWrite()) {
796
+ event.preventDefault();
797
+ return;
798
+ }
799
+ const command = event.key === "Tab" ? event.shiftKey ? "tab-backward" : "tab-forward"
800
+ : event.shiftKey ? "up" : "down";
801
+ const exits = event.key === "Tab" && moveSelection(selection, command, axes()).exit;
802
+ if (exits) {
803
+ // Native Tab moves beyond the artifact; the resulting focusout commits
804
+ // without replacing the editor before the browser chooses its target.
805
+ return;
806
+ }
807
+ event.preventDefault();
808
+ void commitEditing(command);
809
+ }
810
+ return;
811
+ }
812
+ if (editing) {
813
+ event.preventDefault();
814
+ main.querySelector(".table-input")?.focus();
815
+ return;
816
+ }
817
+ if (!selection) {
818
+ if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) {
819
+ event.preventDefault();
820
+ const command = event.key.replace("Arrow", "").toLowerCase();
821
+ selection = moveSelection(null, command, axes()).selection;
822
+ render("selection");
823
+ }
824
+ return;
825
+ }
826
+
827
+ if (event.key === "Delete" || event.key === "Backspace") {
828
+ event.preventDefault();
829
+ if (menu) return;
830
+ void clearContents();
831
+ return;
832
+ }
833
+ if ((event.key === "ContextMenu" || event.key === "F10" && event.shiftKey) && !editing) {
834
+ event.preventDefault();
835
+ openSelectionMenu();
836
+ return;
837
+ }
838
+ if (event.key === " " && event.shiftKey && event.ctrlKey && selection.kind === "cell") {
839
+ event.preventDefault();
840
+ const columnIndex = selectedCellPosition().columnIndex;
841
+ selection = selectAxis(null, "columns", columnIndex, false, axes());
842
+ render("selection");
843
+ return;
844
+ }
845
+ if (event.key === " " && event.shiftKey && selection.kind === "cell") {
846
+ event.preventDefault();
847
+ const position = selectedCellPosition();
848
+ selection = selectAxis(null, "rows", position.rowIndex, false, axes());
849
+ render("selection");
850
+ return;
851
+ }
852
+ if (selection.kind === "rows" || selection.kind === "columns") {
853
+ const commandModified = event.ctrlKey || event.metaKey || event.altKey;
854
+ if ((event.key === "+" || event.key === "Add" || event.key === "-" || event.key === "Subtract")
855
+ && selection.ids.length === 1 && !menu && !commandModified) {
856
+ event.preventDefault();
857
+ void resizeSelection(event.key === "+" || event.key === "Add" ? 1 : -1);
858
+ return;
859
+ }
860
+ const selectionControlKey = ["Enter", "F2", " "].includes(event.key);
861
+ const unmodifiedPrintableKey = event.key.length === 1 && !commandModified;
862
+ if (selectionControlKey || unmodifiedPrintableKey) {
863
+ event.preventDefault();
864
+ }
865
+ } else if (event.key === "Process" || event.isComposing) {
866
+ const position = selectedCellPosition();
867
+ beginEditing(position.rowIndex, position.columnIndex, "");
868
+ // Give the browser's still-pending composition a text input target.
869
+ main.querySelector(".table-input")?.focus();
870
+ return;
871
+ } else if (event.key === "Enter" || event.key === "F2") {
872
+ event.preventDefault();
873
+ const position = selectedCellPosition();
874
+ beginEditing(position.rowIndex, position.columnIndex);
875
+ return;
876
+ } else if (event.key.length === 1 && !event.metaKey && (!event.ctrlKey || event.altKey)) {
877
+ event.preventDefault();
878
+ const position = selectedCellPosition();
879
+ beginEditing(position.rowIndex, position.columnIndex, event.key);
880
+ return;
881
+ }
882
+
883
+ const command = ({ ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" })[event.key]
884
+ ?? (event.key === "Tab" ? event.shiftKey ? "tab-backward" : "tab-forward" : null);
885
+ if (!command) return;
886
+ const moved = moveSelection(selection, command, axes(), { extend: event.shiftKey });
887
+ if (moved.exit) return;
888
+ event.preventDefault();
889
+ if (menu && moved.selection !== selection) menu = null;
890
+ selection = moved.selection;
891
+ render("selection");
892
+ });
893
+
894
+ document.addEventListener("keydown", event => {
895
+ if (event.key !== "Escape") return;
896
+ if (editing) return;
897
+ if (menu) {
898
+ event.preventDefault();
899
+ event.stopImmediatePropagation();
900
+ menu = null;
901
+ render("selection");
902
+ } else if (selection) {
903
+ event.preventDefault();
904
+ event.stopImmediatePropagation();
905
+ clearSelection();
906
+ }
907
+ }, { capture: true });
908
+
909
+ document.addEventListener("pointerdown", event => {
910
+ if (event.target instanceof Element
911
+ && event.target.matches(".table-reference-corner, .table-reference-strip")) {
912
+ event.preventDefault();
913
+ pointerMovedFocus = false;
914
+ return;
915
+ }
916
+ if (editing && event.button === 2 && event.target instanceof Element
917
+ && event.target.closest("[data-cell]")
918
+ && !event.target.closest(".table-input")) {
919
+ event.preventDefault();
920
+ pointerMovedFocus = false;
921
+ return;
922
+ }
923
+ pointerMovedFocus = editing !== null && event.target instanceof Element && !event.target.closest(".table-input");
924
+ }, { capture: true });
925
+
926
+ document.addEventListener("pointermove", event => {
927
+ if (!resizing || event.pointerId !== resizing.pointerId) return;
928
+ const rules = AXIS_SIZES[resizing.axis];
929
+ const position = resizing.axis === "columns" ? event.clientX : event.clientY;
930
+ resizing.previewSize = Math.max(rules.minimum, Math.min(rules.maximum,
931
+ resizing.openedSize + position - resizing.pointerPosition));
932
+ // Pointer previews rerender the grid. This favors one consistent rendering
933
+ // path; very large tables may therefore resize less smoothly.
934
+ render();
935
+ }, { capture: true });
936
+ document.addEventListener("pointerup", event => {
937
+ pointerMovedFocus = false;
938
+ if (resizing && event.pointerId === resizing.pointerId) void finishResize();
939
+ }, { capture: true });
940
+ document.addEventListener("pointercancel", event => {
941
+ pointerMovedFocus = false;
942
+ if (resizing && event.pointerId === resizing.pointerId) {
943
+ resizing = null;
944
+ render();
945
+ }
946
+ }, { capture: true });
947
+
948
+ document.addEventListener("click", event => {
949
+ if (!(event.target instanceof Element)
950
+ || event.target.closest(".table-grid, .table-reference-strip, .table-reference-corner, tv-menu")) return;
951
+ if (editing) void commitEditing(null, false, () => clearSelection("none"));
952
+ else if (selection) clearSelection("none");
953
+ });
954
+
955
+ function commitWhenDocumentLosesFocus() {
956
+ if (editing && canWrite()) void commitEditing(null, false);
957
+ }
958
+
959
+ window.addEventListener("blur", commitWhenDocumentLosesFocus);
960
+ document.addEventListener("visibilitychange", () => {
961
+ if (document.visibilityState === "hidden") commitWhenDocumentLosesFocus();
962
+ });
963
+
964
+ function acceptValue(next) {
965
+ value = next;
966
+ received = true;
967
+ unavailable = false;
968
+ model = readTable(value);
969
+ const nextAxes = buildAxes();
970
+ reconcileResizing(nextAxes);
971
+ let focus = "none";
972
+ if (model !== null) {
973
+ editing = reconcileEditing(editing, nextAxes);
974
+ const actionEcho = pageActionSelection?.(nextAxes);
975
+ if (actionEcho) {
976
+ selection = actionEcho.selection;
977
+ focus = editing ? "none" : actionEcho.focus ? "selection" : "leave";
978
+ } else {
979
+ const reconciled = reconcileSelection(selection, nextAxes);
980
+ if (selection && !reconciled) { selection = null; editing = null; menu = null; }
981
+ else {
982
+ selection = reconciled;
983
+ if (menu && selection?.kind === menu.kind) {
984
+ const index = indexOf(nextAxes[menu.kind], menu.triggerId);
985
+ if (index < 0) menu = null;
986
+ else menu = { ...menu, index };
987
+ }
988
+ }
989
+ }
990
+ } else {
991
+ selection = null;
992
+ editing = null;
993
+ menu = null;
994
+ resizing = null;
995
+ }
996
+ render(focus, nextAxes);
997
+ }
998
+
999
+ function subscribe() {
1000
+ if (unsubscribe) return;
1001
+ unsubscribe = onValue(root, snapshot => acceptValue(snapshot.val()), error => {
1002
+ unsubscribe = null;
1003
+ if (error.code === "unavailable") unavailable = true;
1004
+ selection = null;
1005
+ editing = null;
1006
+ menu = null;
1007
+ resizing = null;
1008
+ render();
1009
+ });
1010
+ }
1011
+
1012
+ function updateAccess(level) {
1013
+ accessKnown = true;
1014
+ access = level;
1015
+ if (level === null && !received) unavailable = true;
1016
+ if (level !== "read-write") {
1017
+ editing = null;
1018
+ menu = null;
1019
+ resizing = null;
1020
+ }
1021
+ if (level !== null && connection === "connected") subscribe();
1022
+ render();
1023
+ }
1024
+
1025
+ onAccessChanged(updateAccess);
1026
+ getAccess().then(updateAccess, () => {});
1027
+ onConnectionStatusChanged(status => {
1028
+ connection = status;
1029
+ if (status !== "connected") {
1030
+ access = null;
1031
+ menu = null;
1032
+ resizing = null;
1033
+ } else {
1034
+ if (failureAfterReconnect) {
1035
+ failureAfterReconnect = false;
1036
+ showFailure();
1037
+ }
1038
+ if (accessKnown) getAccess().then(updateAccess, () => {});
1039
+ subscribe();
1040
+ }
1041
+ render();
1042
+ });
1043
+
1044
+ subscribe();
1045
+ render();