Sheets: the first keystroke types, and cell edits save in the background
Paul (2026-11-26): typing on a selected cell only focused it, and the native app greyed the cell while it waited for the server. - Native: edits show at once and save in the background (one save in flight per document, later edits coalesced, last value per cell); a refused edit keeps its value with a red corner and Retry/Revert; a session renewing mid-save holds and resends; Close/Quit wait and ask; status says Saving…/Not saved. Return to committed: 172 ms (grey) → one frame. - First keystroke: Mac holds the raw key for the field (dead keys and input methods compose); iPad/iPhone hardware keyboards via a key field; the grid windows exact visible rows and columns and floats one editor, so the first key reaches the cell in ~25–30 ms at any width, and held keys are never dropped. - Web: typestart.js keeps the keyboard on the selected cell (dead keys, IME), the editor is not refilled with old contents, the library's selection and active sheet are restored after toolbar/menu/formula-bar clicks, and a value landing under an open editor shows when it closes. Durable offline edits are deferred (last-write-wins needs edit ids and base versions server-side; design in the spec). Discussion oficina/sheets #72. Reviewed by Claude Fable 5.2 across four passes (3dd17f7, 9eec18c APPROVE, 186d734 CHANGES NEEDED, 58b4cb0 APPROVE AFTER FIXES; fixes as prescribed, checked in Chromium and WebKit). Web checked on the google-import canary build. Hub CI passed at b4312c7.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
50 files changed,
+3,496
−354
Makefile+9 −2docs/superpowers/specs/2026-08-30-sheets-design.md+24 −1internal/sheets/static/clipboard.js+3 −2internal/sheets/static/commands.js+5 −2internal/sheets/static/grid.js+31 −31internal/sheets/static/sheets.css+18 −0internal/sheets/static/typestart.js+172 −0internal/sheets/templates/sheet.html+1 −0internal/sheets/typestart_browser_test.go+183 −0internal/sheets/typestart_leave_browser_test.go+270 −0native/README.md+18 −6native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings+5 −0native/apple/Sources/SheetsKit/SheetAutoSize.swift+1 −1native/apple/Sources/SheetsKit/SheetCell.swift+125 −38native/apple/Sources/SheetsKit/SheetCellEditor.swift+15 −4native/apple/Sources/SheetsKit/SheetClipboard.swift+9 −9native/apple/Sources/SheetsKit/SheetCloseGuard.swift+29 −3native/apple/Sources/SheetsKit/SheetEditingControls.swift+22 −5native/apple/Sources/SheetsKit/SheetFiles.swift+2 −1native/apple/Sources/SheetsKit/SheetFormatMenu.swift+1 −1native/apple/Sources/SheetsKit/SheetGrid.swift+462 −133native/apple/Sources/SheetsKit/SheetKeySink.swift+230 −0native/apple/Sources/SheetsKit/SheetModel.swift+69 −27native/apple/Sources/SheetsKit/SheetTable.swift+3 −3native/apple/Sources/SheetsKit/SheetTypeAhead.swift+138 −0native/apple/Sources/SheetsKit/SheetWire.swift+1 −1native/apple/Sources/SheetsKit/SheetWrites.swift+240 −38native/apple/Sources/SheetsKit/SheetsDocumentMenu.swift+1 −1native/apple/Sources/SheetsKit/SheetsEditorCommands.swift+2 −2native/apple/Sources/SheetsKit/SheetsWorkspace.swift+7 −15native/apple/Sources/SheetsReview/Review.swift+6 −0native/apple/Tests/SheetsKitTests/EditingTests.swift+0 −17native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift+411 −0native/apple/Tests/SheetsKitTests/GridGeometryTests.swift+216 −0native/apple/Tests/SheetsKitTests/KeySinkTests.swift+150 −0native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift+379 −0native/apple/Tests/SheetsKitTests/SheetNativeInteractionTests.swift+15 −7native/apple/Tests/SheetsKitTests/SheetServerFixture.swift+161 −0native/ios/UITests/NativeUITests.swift+7 −4
CI passed — run details
CI log
amadan: .amadan/timeout: this job's budget is 15m0s (this runner allows up to 30m0s) === vet === CGO_ENABLED=0 go vet ./... CGO_ENABLED=0 go vet -tags browser ./internal/sheets/ === spacing === go tool fiesta spacing -skip 'vendor/*.css' -skip 'tokens.css' internal/sheets/static === fmt === === build === CGO_ENABLED=0 go build ./... === migrations === go tool rastrillo migration check rastrillo migration check: models and migrations agree === go-test === CGO_ENABLED=0 go test -count=1 ./... ? amadan.net/oficina/sheets/cmd/sheets [no test files] ? amadan.net/oficina/sheets/cmd/sheets-contract [no test files] ok amadan.net/oficina/sheets/internal/guardstest 0.177s ok amadan.net/oficina/sheets/internal/sheets 16.852s ok amadan.net/oficina/sheets/internal/sheets/calc 0.013s ok amadan.net/oficina/sheets/internal/sheets/format 0.003s ? amadan.net/oficina/sheets/internal/sheets/keymailtest [no test files] ok amadan.net/oficina/sheets/internal/sheets/live 0.056s ok amadan.net/oficina/sheets/internal/sheets/seal 0.006s ok amadan.net/oficina/sheets/internal/sheets/sealtest 0.003s ok amadan.net/oficina/sheets/internal/sheets/store 6.556s ok amadan.net/oficina/sheets/internal/sheets/teamstate 0.145s ok amadan.net/oficina/sheets/internal/sheets/xlsx 4.817s ? amadan.net/oficina/sheets/tools/gencorpus [no test files] === race === go test -race -count=1 ./internal/sheets/store/... ./internal/sheets/live/... ok amadan.net/oficina/sheets/internal/sheets/store 73.809s ok amadan.net/oficina/sheets/internal/sheets/live 1.064s
diff --git a/Makefile b/Makefile| index bfb122e..d670a04 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -141,7 +141,7 @@ test-race: |
| # only; on a Mac set RASTRILLO_CHROME to Playwright's or Chrome's binary). |
| # Deliberately NOT part of `test`: the gate CI runs on every push must |
| # not need a browser. Run it before shipping a change to the CSS or to |
| -# rastrillo's pin. The filter runs five tests: OnTap matches both |
| +# rastrillo's pin. The filter runs eight tests: OnTap matches both |
| # TestNoZoomOnTap (the iOS zoom-on-tap check) and TestFormatMenuFitsOnTap; |
| # TestDocumentStylesSurviveTheProductionCSP and TestSmartDoorInABrowser |
| # are served through rastrillo's production stack, so they see the real |
| @@ -149,5 +149,12 @@ test-race: |
| # measure whichever scheme the browser starts in. |
| # TestEveryScreenKeepsTheRhythm is Fiesta's rhythm audit over every |
| # screen but the grid's own surface, at 1280 and 390px. |
| +# TestFirstKeystrokeTypesInABrowser types into the grid as the OS |
| +# delivers keys: a plain key, a dead key and an input method's |
| +# composition each start a cell edit from the first key; |
| +# TestFirstKeystrokeAfterLeavingTheGrid checks that Enter saves and Escape |
| +# cancels such an edit after Bold, a menu item and the formula bar; |
| +# TestFirstKeystrokeKeepsWhatLandsUnderAnOpenEditor that a value arriving |
| +# under an open editor is shown when it closes. |
| test-browser: |
| - CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|DocumentStyles|SmartDoorInABrowser|KeepsTheRhythm' ./internal/sheets/ |
| + CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|DocumentStyles|SmartDoorInABrowser|KeepsTheRhythm|FirstKeystroke' ./internal/sheets/ |
diff --git a/docs/superpowers/specs/2026-08-30-sheets-design.md b/docs/superpowers/specs/2026-08-30-sheets-design.md| index b974d6f..3895c50 100644 |
| --- a/docs/superpowers/specs/2026-08-30-sheets-design.md |
| +++ b/docs/superpowers/specs/2026-08-30-sheets-design.md |
| @@ -356,6 +356,29 @@ out-of-order paints by version rather than by arrival. Without this, |
| optimistic painting plus LWW produces visibly wrong grids under two |
| concurrent editors — the exact bug the optimism is meant to hide. |
| +**The native apps paint a committed cell at once and send in the |
| +background** (Paul, 2026-11-26: the cell going grey for a round trip was |
| +"unnecessary"). One send per document is in flight; edits made meanwhile |
| +wait and go together in the next. On screen, a queued or in-flight local |
| +value wins over the server's for that cell, so a peer update landing |
| +first does not flicker it back and then forward; once the server |
| +acknowledges, the cell shows the server's newest value by version (ours, |
| +or a peer's that came after it). A refused or unanswered edit keeps its |
| +value on screen, marked as not saved, with Retry and Revert, and blocks |
| +nothing else; one the server turns out to hold is cleared, and Revert |
| +reads the server back. While anything is on its way the status reads |
| +Saving…, never Saved. An ended session is not a refusal: the queue waits |
| +for the session to be renewed and sends again. No edit outlives the sheet |
| +it was made on. |
| + |
| +**The native grid builds only the cells in view.** Columns and rows are |
| +windowed from exact widths and heights (a spacer stands in for the rest), |
| +so a cell scrolled out of view, and its row and column headers, are not in |
| +the accessibility tree until they are scrolled back; VoiceOver reads what |
| +is on screen and the formula bar and name box reach any cell. While a |
| +cell's editor is open, the editor is the only element over that cell. These edits live in memory: they do not survive a quit or |
| +crash while unsent (§14). |
| + |
| **The SSE transport check is a streamed 200**, not a 101. SSE is |
| `text/event-stream` over a normal response; 101 is the WebSocket upgrade. |
| The test verifies an unbuffered stream through the real edge — a check |
| @@ -1148,7 +1171,7 @@ it is a fallback rather than a scramble. |
| | ~~Sharing a sheet whose sole owner left the team~~ | **Ruled and built 2026-10-28** (Paul, oficina/sheets #52). Team mode made it routine: a removed creator's own grant stops counting, so the team could edit the sheet and nobody could share it. A roster owner now holds `owner` on any sheet with no live owner grant (§8.2, `team_owner.go`). Still not built: an explicit, auditable "Take ownership" verb that writes a grant — trigger: **a team asks who rescued a sheet**, or the rule needs to outlive a roster owner's own removal. | |
| | Pivot tables | Asked for twice | |
| | Rich presence beyond who's-here | Teams above ~5 concurrent editors | |
| -| Offline editing | — | |
| +| **Durable native cell edits (offline editing)** | Native edits are optimistic but in memory (§7): a quit, crash or long offline spell loses what was not yet acknowledged, and Quit waits or asks rather than pretend. Durability needs more than the shared kit's outbox (`OutboxDrainer`/`NativeSealedStore`, as Docs uses): Docs replays CRDT updates, which are idempotent and merge, while a Sheets edit is last-write-wins (ruling 3), so replaying one after a crash — when the server may already have it — or after hours offline would silently overwrite newer edits by others. It needs a client edit id the server dedupes on (an additive table, every write route in `TestTeamEveryWriteRouteRefusesALapseBeforeCommit`) and a base version per cell so a stale replay is held as a conflict, not applied. Design in oficina/sheets discussion for branch `fix/cell-editing-optimistic`. Trigger: **Paul asks for offline editing, or an edit is reported lost to a quit or crash.** | |
| | Mobile-native apps | — | |
| | `client` shape for anything but the grid | A surface genuinely needs client-held keys | |
| | Print / PDF export | Asked for. docs-e6 keeps its layout engine's page model generic over content boxes so this stays open: paginated grid, repeating header rows, scale-to-width, explicit page breaks, charts as vector | |
diff --git a/internal/sheets/static/clipboard.js b/internal/sheets/static/clipboard.js| index c680b10..e670006 100644 |
| --- a/internal/sheets/static/clipboard.js |
| +++ b/internal/sheets/static/clipboard.js |
| @@ -121,9 +121,10 @@ |
| }).then(function () { if (move) move.busy = false; }); |
| } |
| + // typestart.js's holder is the grid's keyboard, not a text field. |
| function inTextField(el) { |
| - return !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || |
| - el.isContentEditable); |
| + return !!el && !el.hasAttribute('data-type-holder') && |
| + (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable); |
| } |
| function own(e) { |
diff --git a/internal/sheets/static/commands.js b/internal/sheets/static/commands.js| index 1177c5b..efae613 100644 |
| --- a/internal/sheets/static/commands.js |
| +++ b/internal/sheets/static/commands.js |
| @@ -174,7 +174,10 @@ |
| e.preventDefault(); |
| run(el.dataset.cmd, el.dataset.value !== undefined ? el.dataset.value : el.dataset.fn); |
| var panel = el.closest('[data-tool-menu]'); |
| - if (!panel) return; |
| + /* A toolbar button clicked with the pointer keeps focus, so typing |
| + * after Bold went nowhere; the keyboard goes back to the cell. A |
| + * button reached with the keyboard keeps it, to reach the next. */ |
| + if (!panel) { if (e.detail > 0) g.focus(); return; } |
| /* Closing the panel leaves focus on a button inside a closed |
| * <details>, which drops it to <body> — so the keyboard ends up |
| * at the top of the document after picking a colour. Hand it back |
| @@ -215,7 +218,7 @@ |
| document.addEventListener('keydown', function (e) { |
| var t = e.target; |
| - if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return; |
| + if (t && !t.hasAttribute('data-type-holder') && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return; |
| /* Delete is deliberately NOT handled here. The vendored grid |
| * already clears the selection through its own setValue, which |
diff --git a/internal/sheets/static/grid.js b/internal/sheets/static/grid.js| index fda8e51..88db0fe 100644 |
| --- a/internal/sheets/static/grid.js |
| +++ b/internal/sheets/static/grid.js |
| @@ -2,15 +2,12 @@ |
| * |
| * It paints strings the server computed and never evaluates a formula |
| * itself. parseFormulas is off below, deliberately: our engine and |
| - * Jspreadsheet's would disagree on the first SUM(1,2,"3") — the |
| - * divergence the formula corpus already documents — and the |
| - * disagreement would be invisible, because both would look like a |
| - * number in a cell. |
| + * Jspreadsheet's would disagree on the first SUM(1,2,"3"), and invisibly: |
| + * both would look like a number in a cell. |
| * |
| - * Cell data holds DISPLAY strings; the raw input lives in a side map. |
| - * That way the grid shows 42 and the formula bar shows =6*7, which is |
| - * what a spreadsheet does. The alternative — raw in the data — shows |
| - * you =6*7 in every cell and is not a spreadsheet. |
| + * Cell data holds DISPLAY strings; the raw input lives in a side map, |
| + * so the grid shows 42 and the formula bar =6*7, as a spreadsheet does; |
| + * raw in the data would show =6*7 in every cell. |
| * |
| * The chrome above and below the grid is not wired here. This module |
| * publishes window.SheetsGrid and menubar.js and commands.js build on |
| @@ -49,6 +46,7 @@ |
| * one that forgets is invisible until a format outlives its cell. */ |
| var meta = Object.create(null); |
| var styles = Object.create(null); /* format key -> the style */ |
| + var held = Object.create(null); /* "r,c" -> a display that landed under an open editor */ |
| var version = 0; /* the newest version painted */ |
| var ws = null; |
| var sel = null; /* {r,c,r2,c2}; r,c is the anchor */ |
| @@ -91,8 +89,7 @@ |
| }); |
| } |
| - /* Layout arrives with the batch it belongs to, so a column widened |
| - * in another tab widens here in the same frame the edit lands. */ |
| + /* Layout arrives with its batch: a column widened elsewhere widens here. */ |
| if (window.SheetsSizes) window.SheetsSizes.apply(ws, payload.sizes); |
| applying = true; |
| @@ -100,7 +97,11 @@ |
| payload.cells.forEach(function (cell) { |
| if (cell.r >= rows || cell.c >= cols) return; |
| meta[key(cell.r, cell.c)] = { raw: cell.raw || '', f: cell.f, n: cell.n }; |
| - ws.setValueFromCoords(cell.c, cell.r, cell.display, true); |
| + /* Never set the td under an open editor (that wiped the edit, and |
| + * closing it saved an empty cell): hold the display until it closes. */ |
| + var ed = ws.edition; |
| + if (ed && +ed[2] === cell.c && +ed[3] === cell.r) held[key(cell.r, cell.c)] = cell.display; |
| + else ws.setValueFromCoords(cell.c, cell.r, cell.display, true); |
| paint.repaint(cell.r, cell.c); |
| }); |
| } finally { |
| @@ -127,21 +128,12 @@ |
| .catch(function () { /* the stream's own reconnect will try again */ }); |
| } |
| - /* post sends one change and paints what comes back. |
| - * |
| - * One function for all three — a cell, a format patch, a size — |
| - * because all three are the same exchange: send a change, receive the |
| - * batch it produced, paint that. Three copies of it is three places |
| - * for the version check or the failure path to drift. |
| - * |
| - * The response is applied even though the grid may already show the |
| - * typed text, because the server owns the displayed string: it is |
| - * what turns "=6*7" into "42", and what corrects a value the engine |
| - * read differently from how it looked. |
| - * |
| - * Every failure refetches. The write may or may not have landed, and |
| - * refetching is the only honest answer — the alternative is leaving |
| - * the grid showing something the server never accepted. */ |
| + /* post sends one change (a cell, a format patch, a size: one exchange, |
| + * so the version check and failure path cannot drift between three) and |
| + * paints the batch it produced, even over typed text: the server owns |
| + * the displayed string ("=6*7" is "42"). Every failure refetches: the |
| + * write may or may not have landed, and the grid must not keep showing |
| + * something the server never accepted. */ |
| function post(path, body) { |
| body.client = clientId; |
| return fetch(base + path, { |
| @@ -186,6 +178,7 @@ |
| * browser tabs found it. */ |
| onchange: function (instance, cell, c, r, value) { |
| if (applying) return; |
| + delete held[key(r, c)]; /* this edit's own response will paint it */ |
| write(parseInt(r, 10), parseInt(c, 10), value === null ? '' : String(value)); |
| }, |
| onselection: function (instance, x1, y1, x2, y2) { |
| @@ -193,13 +186,20 @@ |
| r2: parseInt(y2, 10), c2: parseInt(x2, 10) }; |
| announce(); |
| }, |
| - /* The in-cell editor should show the formula, not its result. |
| - * The input does not exist yet when this fires, so it is filled |
| - * on the next frame — best effort, because the formula bar is |
| - * the reliable path and this is the convenience. */ |
| + /* F2 or double-click shows the formula, filled a frame later (no input |
| + * yet); typing replaces the cell (typestart.js), so is never filled. */ |
| + /* An edit closed without writing (Escape, or Enter on unchanged |
| + * text): show what landed under it meanwhile, not the stale text. */ |
| + oneditionend: function (instance, td, c, r) { |
| + var k = key(parseInt(r, 10), parseInt(c, 10)), d = held[k]; |
| + if (d === undefined) return; |
| + delete held[k]; |
| + applying = true; |
| + try { ws.setValueFromCoords(parseInt(c, 10), parseInt(r, 10), d, true); } finally { applying = false; } |
| + }, |
| oneditionstart: function (instance, td, c, r) { |
| var text = at(parseInt(r, 10), parseInt(c, 10)).raw; |
| - if (!text) return; |
| + if (!text || (window.SheetsTypeStart && window.SheetsTypeStart.replacing)) return; |
| requestAnimationFrame(function () { |
| var input = td.querySelector('input, textarea'); |
| if (input) { input.value = text; input.select(); } |
diff --git a/internal/sheets/static/sheets.css b/internal/sheets/static/sheets.css| index 85704b1..e1bb01a 100644 |
| --- a/internal/sheets/static/sheets.css |
| +++ b/internal/sheets/static/sheets.css |
| @@ -1340,3 +1340,21 @@ |
| [estilo-google-import] p { |
| margin: 0; |
| } |
| + |
| +/* typestart.js: the keyboard's place on the selected cell, so a dead key |
| + * or an input method composes from the first key. Never seen: the key |
| + * that starts typing opens the cell's own editor, which shows the text. |
| + * 16px type so a touch screen never zooms for it. */ |
| +[data-type-holder] { |
| + position: fixed; |
| + inline-size: 1px; |
| + block-size: 1px; |
| + padding: 0; |
| + border: 0; |
| + margin: 0; |
| + opacity: 0; |
| + resize: none; |
| + overflow: hidden; |
| + pointer-events: none; |
| + font-size: 16px; |
| +} |
diff --git a/internal/sheets/static/typestart.js b/internal/sheets/static/typestart.js| new file mode 100644 |
| index 0000000..0d7d50a |
| --- /dev/null |
| +++ b/internal/sheets/static/typestart.js |
| @@ -0,0 +1,172 @@ |
| +/* Typing on a selected cell replaces it, from the first key. |
| + * |
| + * Paul, 2026-11-26: "the first character typed focusses the cell and |
| + * doesn't actually type into it." Two causes, both fixed here: |
| + * |
| + * - grid.js filled the in-cell editor with the cell's formula a frame |
| + * after it opened. Opened by typing, that overwrote the typed key |
| + * with the old contents and selected them, so the next key replaced |
| + * everything. The fill now happens only for an edit that keeps the |
| + * contents (Enter, F2, double-click): `replacing` says which. |
| + * |
| + * - A browser composes text (´ then e makes é; an input method's かな) |
| + * only inside a focused text control, and the grid is not one. The |
| + * library ignores a dead key ("Dead"), and with nothing editable |
| + * focused an input method never engages, so the first key arrives as a |
| + * bare letter and "ka" becomes "kあ". So while a cell is selected a |
| + * text field with no on-screen keyboard (inputmode=none) holds focus on |
| + * it; the key that starts typing opens the cell's editor in the same |
| + * keydown, before the browser places the text or composition, and the |
| + * editor receives it. If a browser composes into the holder anyway, |
| + * what it composed moves into the editor when the composition ends. |
| + */ |
| +(function () { |
| + 'use strict'; |
| + |
| + var surface = document.querySelector('[data-sheet-surface]'); |
| + if (!surface || surface.dataset.mayWrite !== '1') return; |
| + |
| + var state = { replacing: false }; |
| + window.SheetsTypeStart = state; |
| + |
| + var holder = document.createElement('textarea'); |
| + holder.setAttribute('data-type-holder', ''); |
| + holder.setAttribute('inputmode', 'none'); |
| + holder.setAttribute('autocomplete', 'off'); |
| + holder.setAttribute('autocapitalize', 'off'); |
| + holder.setAttribute('spellcheck', 'false'); |
| + holder.setAttribute('aria-label', 'Selected cell'); |
| + holder.tabIndex = -1; |
| + |
| + function grid() { return window.SheetsGrid; } |
| + function idle() { |
| + var g = grid(); |
| + var ws = g && g.worksheet(); |
| + return !!(ws && !ws.edition && g.selection()); |
| + } |
| + function cellAt(sel) { |
| + var ws = grid().worksheet(); |
| + var row = ws && ws.records && ws.records[sel.r]; |
| + return row && row[sel.c] ? row[sel.c].element : null; |
| + } |
| + |
| + /* Where the keyboard is when nobody else has it: the page itself, the |
| + * grid, or the holder. Never the formula bar, a menu or a dialog. */ |
| + function unclaimed(el) { |
| + return !el || el === document.body || el === holder || |
| + (el.closest && el.closest('[data-sheet-grid]') && !el.closest('td.editor')); |
| + } |
| + |
| + /* A key that is text, or the start of some: a printable key (Option and |
| + * AltGr characters included), a dead key, or an input method's key. */ |
| + function startsText(e) { |
| + if (e.isComposing) return false; |
| + if (e.key === 'Dead' || e.key === 'Process' || e.keyCode === 229) return true; |
| + if (!e.key || e.key.length !== 1) return false; |
| + if (e.metaKey) return false; |
| + return !e.ctrlKey || e.altKey; /* Ctrl+Alt is AltGr on Windows */ |
| + } |
| + |
| + /* The library drives an open editor (Enter, Escape, the arrows) only for |
| + * its "current" sheet, and a click anywhere outside the table (Bold, a |
| + * menu, the formula bar) sets that to none. Whenever the holder has the |
| + * keyboard, the grid is current again; without this an editor opened by |
| + * typing ignored Enter and Escape and was saved by the next click. The |
| + * same click clears the library's own selection while ours stands, and |
| + * then Enter saved without moving on (the next value overwrote the cell) |
| + * and the arrows and Delete did nothing: put that back too. */ |
| + function own() { |
| + var ws = grid() && grid().worksheet(); |
| + var s = grid() && grid().selection(); |
| + if (!ws || !window.jspreadsheet) return; |
| + window.jspreadsheet.current = ws; |
| + if (!ws.selectedCell && s && ws.updateSelectionFromCoords) ws.updateSelectionFromCoords(s.c, s.r, s.c2, s.r2); |
| + } |
| + |
| + function open(sel) { |
| + var td = cellAt(sel); |
| + var ws = grid().worksheet(); |
| + if (!td || !ws.openEditor) return null; |
| + own(); |
| + state.replacing = true; |
| + try { ws.openEditor(td, true); } finally { state.replacing = false; } |
| + return td.querySelector('input, textarea'); |
| + } |
| + |
| + /* Capture phase: ahead of the library's own document handler, which |
| + * then finds an edit already open and leaves the key to the editor. */ |
| + document.addEventListener('keydown', function (e) { |
| + var g = grid(); |
| + var ws = g && g.worksheet(); |
| + /* Enter, Tab or Escape closing an edit: WebKit sends no focusout when |
| + * the library removes the editor, so take the keyboard back here too. */ |
| + if (ws && ws.edition && (e.key === 'Enter' || e.key === 'Tab' || e.key === 'Escape')) claim(); |
| + if (!g || !idle() || !unclaimed(document.activeElement)) return; |
| + if (document.activeElement === holder) own(); |
| + if (startsText(e)) open(g.selection()); |
| + }, true); |
| + |
| + /* A composition that landed in the holder after all moves to the cell. */ |
| + function rescue() { |
| + var text = holder.value; |
| + holder.value = ''; |
| + if (!text || !idle()) return; |
| + var input = open(grid().selection()); |
| + if (!input) return; |
| + input.value = text; |
| + input.setSelectionRange(text.length, text.length); |
| + } |
| + holder.addEventListener('input', function (e) { if (!e.isComposing) rescue(); }); |
| + holder.addEventListener('compositionend', function () { setTimeout(rescue, 0); }); |
| + |
| + function colName(c) { |
| + var s = ''; |
| + for (c += 1; c > 0; c = Math.floor((c - 1) / 26)) s = String.fromCharCode(65 + (c - 1) % 26) + s; |
| + return s; |
| + } |
| + |
| + /* Over the cell, so an input method's candidates appear beside it, and |
| + * named like it, so a screen reader still hears which cell this is. */ |
| + function place(sel) { |
| + var td = sel && cellAt(sel); |
| + if (!td) return; |
| + var box = td.getBoundingClientRect(); |
| + holder.style.left = Math.round(box.left) + 'px'; |
| + holder.style.top = Math.round(box.top) + 'px'; |
| + var ref = colName(sel.c) + (sel.r + 1); |
| + holder.setAttribute('aria-label', td.textContent ? ref + ', ' + td.textContent : ref); |
| + } |
| + |
| + /* After the browser's own focus move for the click that selected. */ |
| + function claim() { |
| + setTimeout(function () { |
| + if (!idle() || !unclaimed(document.activeElement)) return; |
| + place(grid().selection()); |
| + holder.focus({ preventScroll: true }); |
| + }, 0); |
| + } |
| + |
| + function ready() { |
| + var g = grid(); |
| + if (!g || !g.mayWrite) return; |
| + surface.appendChild(holder); |
| + holder.addEventListener('focus', own); |
| + g.onSelection(claim); |
| + /* Every "back to the grid" (after a menu item, a paste, the formula |
| + * bar) lands on the holder, so the next key composes from the first. */ |
| + var focusHost = g.focus; |
| + g.focus = function () { |
| + if (!idle()) return focusHost(); |
| + place(g.selection()); |
| + holder.focus({ preventScroll: true }); |
| + }; |
| + /* An edit closed (Enter, Tab, Escape, a click away): the page has the |
| + * keyboard again, so the holder takes it back. */ |
| + document.addEventListener('focusout', function (e) { |
| + if (e.target && e.target.closest && e.target.closest('td.editor')) claim(); |
| + }); |
| + } |
| + |
| + if (window.SheetsGrid) ready(); |
| + else document.addEventListener('sheets:ready', ready, { once: true }); |
| +}()); |
diff --git a/internal/sheets/templates/sheet.html b/internal/sheets/templates/sheet.html| index fed9d8d..a84a4a2 100644 |
| --- a/internal/sheets/templates/sheet.html |
| +++ b/internal/sheets/templates/sheet.html |
| @@ -14,6 +14,7 @@ |
| <script defer src="{{asset "static/sizes.js"}}"></script> |
| <script defer src="{{asset "static/autofit.js"}}"></script> |
| <script defer src="{{asset "static/grid.js"}}"></script> |
| +<script defer src="{{asset "static/typestart.js"}}"></script> |
| <script defer src="{{asset "static/menubar.js"}}"></script> |
| <script defer src="{{asset "static/formulabar.js"}}"></script> |
| <script defer src="{{asset "static/formulapick.js"}}"></script> |
diff --git a/internal/sheets/typestart_browser_test.go b/internal/sheets/typestart_browser_test.go| new file mode 100644 |
| index 0000000..02d52b4 |
| --- /dev/null |
| +++ b/internal/sheets/typestart_browser_test.go |
| @@ -0,0 +1,183 @@ |
| +//go:build browser |
| + |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/cdproto/input" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +// TestFirstKeystrokeTypesInABrowser: Paul, 2026-11-26, "the first |
| +// character typed focusses the cell and doesn't actually type into it." |
| +// Typing on a selected cell replaces it from the first key (typestart.js), |
| +// including a dead key (´ then e) and an input method's composition, and |
| +// F2 or a double-click edits the cell keeping what it holds. Served through the |
| +// production stack, so the page runs under the real CSP. |
| +// |
| +// Keys go in as the browser receives them from the operating system: |
| +// Input.dispatchKeyEvent for the key, then Input.imeSetComposition and |
| +// Input.insertText for what the keyboard layout or input method makes of |
| +// it, in that order, to whatever has focus by then. |
| +func TestFirstKeystrokeTypesInABrowser(t *testing.T) { |
| + app, cookies := signIn(t) |
| + sheet, cells := newSheet(t, app, cookies, "Typing") |
| + for r, raw := range []string{"old A1", "old A2", "old A3", "old A4", "old A5"} { |
| + postCell(t, app, cookies, cells, fmt.Sprintf(`{"r":%d,"c":0,"raw":%q}`, r, raw)) |
| + } |
| + rig := harness.New(t, func(string) http.Handler { return productionHandler(t, app) }) |
| + var set []chromedp.Action[chromedp.Void] |
| + for _, c := range cookies { |
| + set = append(set, setCookie(rig.Origin, c)) |
| + } |
| + rig.Run(set...) |
| + |
| + cell := func(r int) string { return fmt.Sprintf(`td[data-x="0"][data-y="%d"]`, r) } |
| + editor := func(r int) string { return cell(r) + ` input, ` + cell(r) + ` textarea` } |
| + key := func(kind input.DispatchKeyEventType, key, code string, vk int64, text string, mods int64) chromedp.Action[chromedp.Void] { |
| + return command(input.DispatchKeyEvent, input.DispatchKeyEventParams{ |
| + Type: kind, Key: key, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk, |
| + Text: text, UnmodifiedText: text, Modifiers: mods, |
| + }) |
| + } |
| + press := func(k, code string, vk int64, text string) []chromedp.Action[chromedp.Void] { |
| + kind := input.DispatchKeyEventTypeKeyDown |
| + if text == "" { |
| + kind = input.DispatchKeyEventTypeRawKeyDown |
| + } |
| + return []chromedp.Action[chromedp.Void]{key(kind, k, code, vk, text, 0), key(input.DispatchKeyEventTypeKeyUp, k, code, vk, "", 0)} |
| + } |
| + compose := func(text string) chromedp.Action[chromedp.Void] { |
| + n := int64(len([]rune(text))) |
| + return command(input.ImeSetComposition, input.ImeSetCompositionParams{Text: text, SelectionStart: n, SelectionEnd: n}) |
| + } |
| + commit := func(text string) chromedp.Action[chromedp.Void] { |
| + return command(input.InsertText, input.InsertTextParams{Text: text}) |
| + } |
| + // Two frames: grid.js's fill of the editor ran on the next one. |
| + settle := chromedp.Sleep(80 * time.Millisecond) |
| + run := func(what string, actions ...chromedp.Action[chromedp.Void]) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| + defer cancel() |
| + if err := chromedp.Do(ctx, actions...); err != nil { |
| + t.Fatalf("%s: %v", what, err) |
| + } |
| + } |
| + value := func(r int) string { |
| + t.Helper() |
| + var v string |
| + run("read the editor", evalInto(&v, fmt.Sprintf(`(document.querySelector(%q) || {}).value || ''`, editor(r)))) |
| + return v |
| + } |
| + saved := func(r int, want string) { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for { |
| + read := decodeGrid(t, do(t, app, as(httptest.NewRequest(http.MethodGet, cells+"?rows=6&cols=2", nil), cookies))) |
| + for _, c := range read.Cells { |
| + if c.R == r && c.C == 0 && c.Raw == want { |
| + return |
| + } |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("row %d never saved %q: %+v", r+1, want, read.Cells) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + } |
| + selectCell := func(r int) { |
| + t.Helper() |
| + var holder bool |
| + run(fmt.Sprintf("select row %d", r+1), |
| + chromedp.Click(chromedp.CSS(cell(r))), |
| + chromedp.Sleep(50*time.Millisecond), |
| + evalInto(&holder, `document.activeElement && document.activeElement.hasAttribute('data-type-holder')`), |
| + ) |
| + if !holder { |
| + t.Fatalf("row %d: a selected cell must hold the keyboard in a text field, or an input method never engages", r+1) |
| + } |
| + } |
| + |
| + run("open the sheet", |
| + chromedp.Navigate(fmt.Sprintf("%s/sheets/%d", rig.Origin, sheet.ID)), |
| + chromedp.WaitVisible(chromedp.CSS(cell(4))), |
| + chromedp.Sleep(200*time.Millisecond), |
| + ) |
| + |
| + // A plain key replaces the cell, and stays typed. |
| + selectCell(0) |
| + run("type x", append(press("x", "KeyX", 88, "x"), settle)...) |
| + if got := value(0); got != "x" { |
| + t.Fatalf("typing x on a selected cell: the editor holds %q, want %q", got, "x") |
| + } |
| + run("type y, Enter", append(append(press("y", "KeyY", 89, "y"), press("Enter", "Enter", 13, "\r")...), settle)...) |
| + saved(0, "xy") |
| + |
| + // A dead key: ´ (Option-E on a Mac) composes with the next key. |
| + selectCell(1) |
| + run("dead key", key(input.DispatchKeyEventTypeRawKeyDown, "Dead", "KeyE", 69, "", 1), compose("´"), |
| + key(input.DispatchKeyEventTypeKeyUp, "Dead", "KeyE", 69, "", 1), settle) |
| + run("e", key(input.DispatchKeyEventTypeRawKeyDown, "e", "KeyE", 69, "", 0), commit("é"), |
| + key(input.DispatchKeyEventTypeKeyUp, "e", "KeyE", 69, "", 0), settle) |
| + if got := value(1); got != "é" { |
| + t.Fatalf("´ then e on a selected cell: the editor holds %q, want é", got) |
| + } |
| + run("Enter", append(press("Enter", "Enter", 13, "\r"), settle)...) |
| + saved(1, "é") |
| + |
| + // An input method: its keys arrive as "Process", and it composes. |
| + selectCell(2) |
| + run("k", key(input.DispatchKeyEventTypeRawKeyDown, "Process", "KeyK", 229, "", 0), compose("k"), settle) |
| + run("a", key(input.DispatchKeyEventTypeRawKeyDown, "Process", "KeyA", 229, "", 0), compose("か"), settle) |
| + if got := value(2); got != "か" { |
| + t.Fatalf("an input method's composition: the editor holds %q, want か", got) |
| + } |
| + run("confirm, Enter", commit("か"), settle) |
| + run("Enter", append(press("Enter", "Enter", 13, "\r"), settle)...) |
| + saved(2, "か") |
| + |
| + // Review #72, 11: after a toolbar button (Bold) the keyboard is back |
| + // on the cell's holder, so a dead key composes from the first key. |
| + selectCell(0) |
| + var holder bool |
| + run("Bold with the pointer", |
| + chromedp.Click(chromedp.CSS(`button[data-tool][data-cmd="bold"]`)), |
| + chromedp.Sleep(100*time.Millisecond), |
| + evalInto(&holder, `document.activeElement && document.activeElement.hasAttribute('data-type-holder')`), |
| + ) |
| + if !holder { |
| + t.Fatal("after Bold the keyboard is on the button: typing goes nowhere") |
| + } |
| + run("dead key after Bold", key(input.DispatchKeyEventTypeRawKeyDown, "Dead", "KeyE", 69, "", 1), compose("´"), |
| + key(input.DispatchKeyEventTypeKeyUp, "Dead", "KeyE", 69, "", 1), commit("é"), settle) |
| + if got := value(0); got != "é" { |
| + t.Fatalf("´ then e after Bold: the editor holds %q, want é", got) |
| + } |
| + run("Escape", append(press("Escape", "Escape", 27, ""), settle)...) |
| + var label string |
| + run("the holder names its cell", chromedp.Sleep(50*time.Millisecond), evalInto(&label, `document.querySelector('[data-type-holder]').getAttribute('aria-label')`)) |
| + if label != "A1, xy" { |
| + t.Errorf("the holder reads %q to a screen reader, want the cell's reference and value", label) |
| + } |
| + |
| + // Double-click and F2 keep the cell. (Enter on a selected cell moves |
| + // down, as in Excel; that is unchanged.) |
| + run("double-click", chromedp.DoubleClick(chromedp.CSS(cell(3))), settle) |
| + if got := value(3); got != "old A4" { |
| + t.Fatalf("double-click on a cell: the editor holds %q, want its contents", got) |
| + } |
| + run("Escape", append(press("Escape", "Escape", 27, ""), settle)...) |
| + selectCell(4) |
| + run("F2", append(press("F2", "F2", 113, ""), settle)...) |
| + if got := value(4); got != "old A5" { |
| + t.Fatalf("F2 on a selected cell: the editor holds %q, want its contents", got) |
| + } |
| +} |
diff --git a/internal/sheets/typestart_leave_browser_test.go b/internal/sheets/typestart_leave_browser_test.go| new file mode 100644 |
| index 0000000..b1209a6 |
| --- /dev/null |
| +++ b/internal/sheets/typestart_leave_browser_test.go |
| @@ -0,0 +1,270 @@ |
| +//go:build browser |
| + |
| +package sheets |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/cdproto/input" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +// TestFirstKeystrokeAfterLeavingTheGrid: #72's web canary. A pointer click |
| +// outside the table (Bold, a menu item, the formula bar) makes Jspreadsheet |
| +// drop the sheet as "current", and an editor opened by typing after it |
| +// ignored Enter and Escape: Enter saved nothing, Escape cancelled nothing |
| +// (the next click saved the discarded text), and Bold-then-type at once |
| +// saved an empty cell when the format's repaint wiped the open editor. For |
| +// each way of leaving the grid, type and press Enter (the value is saved), |
| +// and type and press Escape (the cell keeps its old value, and the keyboard |
| +// is back on the cell's text holder). |
| +func TestFirstKeystrokeAfterLeavingTheGrid(t *testing.T) { |
| + app, cookies := signIn(t) |
| + sheet, cells := newSheet(t, app, cookies, "Leaving") |
| + for r := 0; r < 14; r++ { |
| + postCell(t, app, cookies, cells, fmt.Sprintf(`{"r":%d,"c":0,"raw":"old%d"}`, r, r)) |
| + postCell(t, app, cookies, cells, fmt.Sprintf(`{"r":%d,"c":2,"raw":"c%d"}`, r, r)) |
| + } |
| + rig := harness.New(t, func(string) http.Handler { return productionHandler(t, app) }) |
| + var set []chromedp.Action[chromedp.Void] |
| + for _, c := range cookies { |
| + set = append(set, setCookie(rig.Origin, c)) |
| + } |
| + rig.Run(set...) |
| + |
| + cell := func(r, c int) string { return fmt.Sprintf(`td[data-x="%d"][data-y="%d"]`, c, r) } |
| + press := func(k, code string, vk int64, text string) []chromedp.Action[chromedp.Void] { |
| + kind := input.DispatchKeyEventTypeKeyDown |
| + if text == "" { |
| + kind = input.DispatchKeyEventTypeRawKeyDown |
| + } |
| + return []chromedp.Action[chromedp.Void]{ |
| + command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: kind, Key: k, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk, Text: text, UnmodifiedText: text}), |
| + command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeKeyUp, Key: k, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk}), |
| + } |
| + } |
| + run := func(what string, actions ...chromedp.Action[chromedp.Void]) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| + defer cancel() |
| + if err := chromedp.Do(ctx, actions...); err != nil { |
| + t.Fatalf("%s: %v", what, err) |
| + } |
| + } |
| + rawAt := func(r, col int) string { |
| + read := decodeGrid(t, do(t, app, as(httptest.NewRequest(http.MethodGet, cells+"?rows=16&cols=3", nil), cookies))) |
| + for _, c := range read.Cells { |
| + if c.R == r && c.C == col { |
| + return c.Raw |
| + } |
| + } |
| + return "" |
| + } |
| + raw := func(r int) string { return rawAt(r, 0) } |
| + selection := func() [4]int { |
| + var s [4]int |
| + run("read the selection", evalInto(&s, `(() => { const s = SheetsGrid.selection(); return [s.r, s.c, s.r2, s.c2]; })()`)) |
| + return s |
| + } |
| + saved := func(what string, r int, want string) { |
| + t.Helper() |
| + deadline := time.Now().Add(4 * time.Second) |
| + for raw(r) != want { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("%s: row %d holds %q, want %q", what, r+1, raw(r), want) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| + } |
| + state := func() (editorOpen bool, holder bool) { |
| + var got struct{ Editor, Holder bool } |
| + run("read state", evalInto(&got, `({Editor: !!document.querySelector('td.editor'), Holder: !!(document.activeElement && document.activeElement.hasAttribute('data-type-holder'))})`)) |
| + return got.Editor, got.Holder |
| + } |
| + menu := func(cmd string) chromedp.Action[chromedp.Void] { |
| + return evalInto((*any)(nil), fmt.Sprintf(`(() => { |
| + const s = document.querySelector('details[estilo-menubar-menu]:has(button[estilo-menu-item][data-cmd=%q]) > summary'); |
| + s.click(); |
| + return null; |
| + })()`, cmd)) |
| + } |
| + pointerClick := func(sel string) chromedp.Action[chromedp.Void] { return chromedp.Click(chromedp.CSS(sel)) } |
| + |
| + ways := []struct { |
| + name string |
| + leave []chromedp.Action[chromedp.Void] |
| + pause time.Duration |
| + }{ |
| + {"Bold on the toolbar", []chromedp.Action[chromedp.Void]{pointerClick(`button[data-tool][data-cmd="bold"]`)}, 250 * time.Millisecond}, |
| + // Typing at once, inside the format's round trip: its repaint must |
| + // not wipe the editor the key opened. |
| + {"Bold on the toolbar, then typing at once", []chromedp.Action[chromedp.Void]{pointerClick(`button[data-tool][data-cmd="italic"]`)}, 0}, |
| + {"Format › Bold", []chromedp.Action[chromedp.Void]{menu("bold"), chromedp.Sleep(150 * time.Millisecond), |
| + pointerClick(`details[estilo-menubar-menu][open] button[estilo-menu-item][data-cmd="bold"]`)}, 250 * time.Millisecond}, |
| + {"leaving the formula bar with Escape", append([]chromedp.Action[chromedp.Void]{pointerClick(`[data-formula-input]`)}, |
| + press("Escape", "Escape", 27, "")...), 250 * time.Millisecond}, |
| + } |
| + run("open the sheet", chromedp.Navigate(fmt.Sprintf("%s/sheets/%d", rig.Origin, sheet.ID)), |
| + chromedp.WaitVisible(chromedp.CSS(cell(13, 0))), chromedp.Sleep(200*time.Millisecond)) |
| + for i, way := range ways { |
| + enter, escape := 3*i, 3*i+2 |
| + // Enter saves what was typed. |
| + run(way.name+": select", pointerClick(cell(enter, 0)), chromedp.Sleep(150*time.Millisecond)) |
| + run(way.name+": leave", append(way.leave, chromedp.Sleep(way.pause))...) |
| + run(way.name+": type, Enter", append(append(press("q", "KeyQ", 81, "q"), chromedp.Sleep(100*time.Millisecond)), |
| + append(press("Enter", "Enter", 13, "\r"), chromedp.Sleep(300*time.Millisecond))...)...) |
| + if open, _ := state(); open { |
| + t.Errorf("%s: Enter left the editor open", way.name) |
| + } |
| + saved(way.name+", Enter", enter, "q") |
| + // Enter moved on, so the next value lands one row down, not over this one. |
| + run(way.name+": type the next value", append(append(press("r", "KeyR", 82, "r"), chromedp.Sleep(100*time.Millisecond)), |
| + append(press("Enter", "Enter", 13, "\r"), chromedp.Sleep(300*time.Millisecond))...)...) |
| + saved(way.name+", the next value", enter+1, "r") |
| + if got := raw(enter); got != "q" { |
| + t.Errorf("%s: the second value overwrote the first: row %d holds %q", way.name, enter+1, got) |
| + } |
| + |
| + // Escape cancels, and a click away saves nothing. |
| + run(way.name+": select", pointerClick(cell(escape, 0)), chromedp.Sleep(150*time.Millisecond)) |
| + run(way.name+": leave", append(way.leave, chromedp.Sleep(way.pause))...) |
| + run(way.name+": type, Escape", append(append(press("q", "KeyQ", 81, "q"), chromedp.Sleep(100*time.Millisecond)), |
| + append(press("Escape", "Escape", 27, ""), chromedp.Sleep(200*time.Millisecond))...)...) |
| + open, holder := state() |
| + if open { |
| + t.Errorf("%s: Escape left the editor open", way.name) |
| + } |
| + if !holder { |
| + t.Errorf("%s: after Escape the keyboard is not back on the cell's holder", way.name) |
| + } |
| + run(way.name+": click away", pointerClick(cell(15, 1)), chromedp.Sleep(300*time.Millisecond)) |
| + if got := raw(escape); got != fmt.Sprintf("old%d", escape) { |
| + t.Errorf("%s: Escape then a click away saved %q over old%d", way.name, got, escape) |
| + } |
| + |
| + // The grid's own keys still work after leaving it: an arrow, an |
| + // extending Shift+arrow, and Delete on what that selected. |
| + top := 3 * i |
| + run(way.name+": select in column C", pointerClick(cell(top, 2)), chromedp.Sleep(150*time.Millisecond)) |
| + run(way.name+": leave", append(way.leave, chromedp.Sleep(250*time.Millisecond))...) |
| + run(way.name+": ArrowDown", append(press("ArrowDown", "ArrowDown", 40, ""), chromedp.Sleep(150*time.Millisecond))...) |
| + if s := selection(); s[0] != top+1 || s[1] != 2 { |
| + t.Errorf("%s: ArrowDown left the selection at %v, want row %d", way.name, s, top+2) |
| + } |
| + run(way.name+": leave", append(way.leave, chromedp.Sleep(250*time.Millisecond))...) |
| + run(way.name+": Shift+ArrowDown", command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeRawKeyDown, Key: "ArrowDown", Code: "ArrowDown", WindowsVirtualKeyCode: 40, Modifiers: 8}), |
| + command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeKeyUp, Key: "ArrowDown", Code: "ArrowDown", WindowsVirtualKeyCode: 40, Modifiers: 8}), |
| + chromedp.Sleep(150*time.Millisecond)) |
| + if s := selection(); s[0] != top+1 || s[2] != top+2 { |
| + t.Errorf("%s: Shift+ArrowDown selected %v, want rows %d to %d", way.name, s, top+2, top+3) |
| + } |
| + run(way.name+": leave", append(way.leave, chromedp.Sleep(250*time.Millisecond))...) |
| + run(way.name+": Delete", append(press("Delete", "Delete", 46, ""), chromedp.Sleep(400*time.Millisecond))...) |
| + if got := rawAt(top+1, 2); got != "" { |
| + t.Errorf("%s: Delete left row %d of column C holding %q", way.name, top+2, got) |
| + } |
| + } |
| +} |
| + |
| +// TestFirstKeystrokeKeepsWhatLandsUnderAnOpenEditor: a batch for a cell |
| +// whose editor is open must not wipe the editor (41ebeea), and must not be |
| +// lost either. Fable's review of 58b4cb0: the skipped repaint was never |
| +// applied, so C1 (=B1*2) kept showing 10 after B1 became 7 and its editor |
| +// was closed, and a cell kept its old text while the server held a new one. |
| +// The values arrive through the tab's own write path, so the order is fixed. |
| +func TestFirstKeystrokeKeepsWhatLandsUnderAnOpenEditor(t *testing.T) { |
| + app, cookies := signIn(t) |
| + sheet, cells := newSheet(t, app, cookies, "Under an editor") |
| + for _, body := range []string{`{"r":0,"c":0,"raw":"old0"}`, `{"r":1,"c":0,"raw":"old1"}`, `{"r":0,"c":1,"raw":"5"}`, `{"r":0,"c":2,"raw":"=B1*2"}`} { |
| + postCell(t, app, cookies, cells, body) |
| + } |
| + rig := harness.New(t, func(string) http.Handler { return productionHandler(t, app) }) |
| + var set []chromedp.Action[chromedp.Void] |
| + for _, c := range cookies { |
| + set = append(set, setCookie(rig.Origin, c)) |
| + } |
| + rig.Run(set...) |
| + cell := func(r, c int) string { return fmt.Sprintf(`td[data-x="%d"][data-y="%d"]`, c, r) } |
| + press := func(k, code string, vk int64, text string) []chromedp.Action[chromedp.Void] { |
| + kind := input.DispatchKeyEventTypeKeyDown |
| + if text == "" { |
| + kind = input.DispatchKeyEventTypeRawKeyDown |
| + } |
| + return []chromedp.Action[chromedp.Void]{ |
| + command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: kind, Key: k, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk, Text: text, UnmodifiedText: text}), |
| + command(input.DispatchKeyEvent, input.DispatchKeyEventParams{Type: input.DispatchKeyEventTypeKeyUp, Key: k, Code: code, WindowsVirtualKeyCode: vk, NativeVirtualKeyCode: vk}), |
| + } |
| + } |
| + run := func(what string, actions ...chromedp.Action[chromedp.Void]) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| + defer cancel() |
| + if err := chromedp.Do(ctx, actions...); err != nil { |
| + t.Fatalf("%s: %v", what, err) |
| + } |
| + } |
| + shows := func(r, c int) string { |
| + var text string |
| + run("read a cell", evalInto(&text, fmt.Sprintf(`document.querySelector(%q).textContent`, cell(r, c)))) |
| + return text |
| + } |
| + editorOpen := func() bool { |
| + var open bool |
| + run("editor?", evalInto(&open, `!!document.querySelector('td.editor')`)) |
| + return open |
| + } |
| + edit := func(r, c int) { |
| + t.Helper() |
| + run("F2", append([]chromedp.Action[chromedp.Void]{chromedp.Click(chromedp.CSS(cell(r, c))), chromedp.Sleep(150 * time.Millisecond)}, |
| + append(press("F2", "F2", 113, ""), chromedp.Sleep(150*time.Millisecond))...)...) |
| + if !editorOpen() { |
| + t.Fatalf("F2 opened no editor on row %d column %d", r+1, c+1) |
| + } |
| + } |
| + write := func(r, c int, raw string) { |
| + run("a write lands", evalInto((*any)(nil), fmt.Sprintf(`SheetsGrid.write(%d, %d, %q), null`, r, c, raw)), chromedp.Sleep(600*time.Millisecond)) |
| + } |
| + |
| + run("open the sheet", chromedp.Navigate(fmt.Sprintf("%s/sheets/%d", rig.Origin, sheet.ID)), |
| + chromedp.WaitVisible(chromedp.CSS(cell(1, 0))), chromedp.Sleep(200*time.Millisecond)) |
| + if got := shows(0, 2); got != "10" { |
| + t.Fatalf("C1 shows %q before anything, want 10", got) |
| + } |
| + |
| + // A dependent recomputed under C1's editor, then Escape. |
| + edit(0, 2) |
| + write(0, 1, "7") |
| + run("Escape", append(press("Escape", "Escape", 27, ""), chromedp.Sleep(200*time.Millisecond))...) |
| + if got := shows(0, 2); got != "14" { |
| + t.Errorf("C1 shows %q after B1 became 7 under its editor, want 14", got) |
| + } |
| + |
| + // The cell's own new value under its editor, then Escape. |
| + edit(0, 0) |
| + write(0, 0, "fresh") |
| + run("Escape", append(press("Escape", "Escape", 27, ""), chromedp.Sleep(200*time.Millisecond))...) |
| + if got := shows(0, 0); got != "fresh" { |
| + t.Errorf("A1 shows %q after a new value landed under its editor, want fresh", got) |
| + } |
| + |
| + // Enter on text nobody changed writes nothing, so it shows the new value |
| + // and does not put the old one back on the server. |
| + edit(1, 0) |
| + write(1, 0, "fresh2") |
| + run("Enter", append(press("Enter", "Enter", 13, "\r"), chromedp.Sleep(500*time.Millisecond))...) |
| + if got := shows(1, 0); got != "fresh2" { |
| + t.Errorf("A2 shows %q after Enter on unchanged text, want fresh2", got) |
| + } |
| + read := decodeGrid(t, do(t, app, as(httptest.NewRequest(http.MethodGet, cells+"?rows=4&cols=3", nil), cookies))) |
| + for _, c := range read.Cells { |
| + if c.R == 1 && c.C == 0 && c.Raw != "fresh2" { |
| + t.Errorf("Enter on unchanged text wrote %q over fresh2", c.Raw) |
| + } |
| + } |
| +} |
diff --git a/native/README.md b/native/README.md| index f7308fe..16044cc 100644 |
| --- a/native/README.md |
| +++ b/native/README.md |
| @@ -61,18 +61,30 @@ The Sparkle build updates quietly, as Calls does: `"install": "automatic"` in |
| checks from opening a window. A downloaded update installs on quit; the app menu |
| offers "Update Ready — Restart Sheets" and the Home window shows a one-line notice. |
| -Select a cell, then edit its formula bar, double-click, or type while the |
| -Mac grid has keyboard focus. Enter saves and moves down; Tab saves and |
| -moves right; Escape discards the focused cell edit. The range field accepts |
| +Select a cell, then edit its formula bar, double-click, press Return or F2 |
| +(these keep the cell's contents), or just type (this replaces them, as in |
| +Numbers or Excel). The keystroke that starts typing goes to the cell's own |
| +text field, so a dead key (´ then e) or an input method composes from the |
| +first key. On iPad and iPhone a hardware keyboard works the same way: while |
| +a cell is selected an invisible text field sits on it holding the keyboard |
| +(without raising the on-screen one), so arrows, Return, Tab and Delete move |
| +and clear, and the first typed or composed text starts the edit in place. |
| +Touch editing stays in the formula bar (double-tap a cell). Enter saves and moves down; Tab saves and moves right; Escape |
| +discards the focused cell edit. The range field accepts |
| addresses such as `A1:C10`. Menus provide copy/paste, clear, fill, formatting, |
| size controls, functions, history, comments, sharing and workbook transfer. |
| Sort/filter opens a native table preserving each cell's original reference. |
| Network content uses ephemeral transport. Requested exports stream to a private |
| temporary workbook and are handed to the system file-save picker; the temporary |
| -file is removed on completion, cancellation or failure. Failed value batches |
| -remain available for retry/discard; window close and Quit protect pending |
| -edits. The app does not claim offline editing or sealed local document caches. |
| +file is removed on completion, cancellation or failure. Value edits are |
| +optimistic: a committed cell shows its value at once and the send happens in |
| +the background, one at a time per document, with edits made meanwhile sent |
| +together next. A refused or unanswered edit keeps its value on screen with a |
| +small red corner mark and offers Retry and Revert (on the cell's context menu |
| +and above the grid); editing carries on around it. Window close and Quit wait |
| +for edits on their way and ask about failed ones. Edits live in memory until |
| +the server has them: they do not survive a crash or quit while offline. The app does not claim offline editing or sealed local document caches. |
| Current web limits remain visible: a single worksheet, a 500-row/200-column |
| grid window, 500-cell paste limit, first-worksheet XLSX/XLSM import up to |
diff --git a/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings| index 58fee11..13bbfe3 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "الفرق"; |
| "Done" = "تم"; |
| "Sign in with Oficina ID" = "تسجيل الدخول باستخدام Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "استعادة"; |
| +"Not saved" = "لم يُحفظ"; |
| +"Some cell edits weren’t saved." = "لم تُحفظ بعض تعديلات الخلايا."; |
| +"Saving…" = "جارٍ الحفظ…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings| index ca17400..edcf304 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "টিম"; |
| "Done" = "সম্পন্ন"; |
| "Sign in with Oficina ID" = "Oficina ID দিয়ে সাইন ইন করুন"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "আগের অবস্থায় ফেরান"; |
| +"Not saved" = "সংরক্ষিত হয়নি"; |
| +"Some cell edits weren’t saved." = "কিছু ঘরের সম্পাদনা সংরক্ষিত হয়নি।"; |
| +"Saving…" = "সংরক্ষণ করা হচ্ছে…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings| index d59b41c..22a9fc2 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings |
| @@ -75,3 +75,8 @@ |
| "Teams" = "Teams"; |
| "Done" = "Done"; |
| "Sign in with Oficina ID" = "Sign in with Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "Revert"; |
| +"Not saved" = "Not saved"; |
| +"Some cell edits weren’t saved." = "Some cell edits weren’t saved."; |
| +"Saving…" = "Saving…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings| index 2e6bfe4..26c2511 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "Equipos"; |
| "Done" = "Listo"; |
| "Sign in with Oficina ID" = "Iniciar sesión con Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "Revertir"; |
| +"Not saved" = "No guardado"; |
| +"Some cell edits weren’t saved." = "Algunos cambios en celdas no se guardaron."; |
| +"Saving…" = "Guardando…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings| index fe98308..261c9f8 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "Foirne"; |
| "Done" = "Déanta"; |
| "Sign in with Oficina ID" = "Sínigh isteach le Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "Fill ar ais"; |
| +"Not saved" = "Níor sábháladh"; |
| +"Some cell edits weren’t saved." = "Níor sábháladh roinnt athruithe ar chealla."; |
| +"Saving…" = "Á shábháil…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings| index 515afae..3c27a55 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "टीमें"; |
| "Done" = "हो गया"; |
| "Sign in with Oficina ID" = "Oficina ID से साइन इन करें"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "पहले जैसा करें"; |
| +"Not saved" = "सहेजा नहीं गया"; |
| +"Some cell edits weren’t saved." = "कुछ सेल के बदलाव सहेजे नहीं गए।"; |
| +"Saving…" = "सहेजा जा रहा है…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings| index b4493eb..df75272 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "チーム"; |
| "Done" = "完了"; |
| "Sign in with Oficina ID" = "Oficina ID でサインイン"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "元に戻す"; |
| +"Not saved" = "保存されていません"; |
| +"Some cell edits weren’t saved." = "一部のセルの変更が保存されませんでした。"; |
| +"Saving…" = "保存中…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings| index 6faffe4..e2ec7eb 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "Equipas"; |
| "Done" = "Concluído"; |
| "Sign in with Oficina ID" = "Iniciar sessão com o Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "Reverter"; |
| +"Not saved" = "Não guardado"; |
| +"Some cell edits weren’t saved." = "Algumas alterações em células não foram guardadas."; |
| +"Saving…" = "A guardar…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings| index a32025d..5f19d46 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "Команды"; |
| "Done" = "Готово"; |
| "Sign in with Oficina ID" = "Войти с Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "Вернуть"; |
| +"Not saved" = "Не сохранено"; |
| +"Some cell edits weren’t saved." = "Некоторые изменения ячеек не сохранены."; |
| +"Saving…" = "Сохранение…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings| index 5dffed0..d08d48a 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "Nhóm"; |
| "Done" = "Xong"; |
| "Sign in with Oficina ID" = "Đăng nhập bằng Oficina ID"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "Hoàn nguyên"; |
| +"Not saved" = "Chưa lưu"; |
| +"Some cell edits weren’t saved." = "Một số chỉnh sửa ô chưa được lưu."; |
| +"Saving…" = "Đang lưu…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings| index 2b63666..438fdb8 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "團隊"; |
| "Done" = "完成"; |
| "Sign in with Oficina ID" = "用 Oficina ID 登入"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "還原"; |
| +"Not saved" = "未儲存"; |
| +"Some cell edits weren’t saved." = "有啲儲存格嘅修改未儲存到。"; |
| +"Saving…" = "儲存緊…"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings| index 9d1bd66..a40219c 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings |
| @@ -74,3 +74,8 @@ |
| "Teams" = "团队"; |
| "Done" = "完成"; |
| "Sign in with Oficina ID" = "使用 Oficina ID 登录"; |
| +/* Optimistic cell edits (2026-11-26): a refused or unanswered edit is marked on its cell. */ |
| +"Revert" = "还原"; |
| +"Not saved" = "未保存"; |
| +"Some cell edits weren’t saved." = "部分单元格修改未保存。"; |
| +"Saving…" = "正在保存…"; |
diff --git a/native/apple/Sources/SheetsKit/SheetAutoSize.swift b/native/apple/Sources/SheetsKit/SheetAutoSize.swift| index fd9d26f..3123e33 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetAutoSize.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetAutoSize.swift |
| @@ -4,7 +4,7 @@ import AppKit |
| extension SheetModel { |
| /// Fits the loaded grid (the same visible rows used by the editor). |
| func fitColumn(_ column: Int) async { |
| - guard (0..<cols).contains(column), mayWrite, !busy, !hasUnconfirmedChanges else { return } |
| + guard (0..<cols).contains(column), mayWrite, !busy, !dirty else { return } |
| var width: CGFloat = 40 |
| for (point, cell) in cells where point.c == column { |
| let style = styles[cell.f ?? ""] |
diff --git a/native/apple/Sources/SheetsKit/SheetCell.swift b/native/apple/Sources/SheetsKit/SheetCell.swift| index 205f77e..0c85835 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetCell.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetCell.swift |
| @@ -1,52 +1,41 @@ |
| import SwiftUI |
| -struct SheetCell: View { |
| +/// Equatable on what it draws from besides the model's observed state (which |
| +/// SwiftUI tracks on its own): the grid rebuilds its rows whenever scrolling |
| +/// crosses a window block, and without this every visible cell's body ran |
| +/// again each time. Its closures act on the grid and are equal in effect. |
| +struct SheetCell: View, Equatable { |
| + nonisolated static func == (a: Self, b: Self) -> Bool { |
| + // SwiftUI compares views on the main thread, where it builds them. |
| + MainActor.assumeIsolated { |
| + a.model === b.model && a.point == b.point && a.columnWidth == b.columnWidth |
| + && a.rowHeight == b.rowHeight && a.editState === b.editState |
| + } |
| + } |
| @Bindable var model: SheetModel |
| let point: Coordinate |
| - @Binding var editing: Coordinate? |
| var select: () -> Void |
| var beginEditing: () -> Void = {} |
| - var endEditing: () -> Void |
| var columnWidth: Double? = nil |
| var rowHeight: Double? = nil |
| + /// While this cell's editor is open, the editor is the one element here. |
| + var editState: SheetEditingState? = nil |
| @Environment(\.colorScheme) private var scheme |
| private func width(_ col: Int) -> Double { columnWidth ?? model.sizes.cols?[String(col)] ?? 110 } |
| private func height(_ row: Int) -> Double { rowHeight ?? model.sizes.rows?[String(row)] ?? 32 } |
| var body: some View { |
| - let cell = model.cells[point] |
| + let cell = model.displayCell(point) |
| let style = model.styles[cell?.f ?? ""] |
| let alignment: Alignment = |
| style?.a == "center" |
| ? .center : style?.a == "right" || (style?.a == nil && cell?.n == true) ? .trailing : .leading |
| - return Group { |
| - #if os(macOS) |
| - if editing == point { |
| - SheetCellEditor(text: $model.draft, enabled: model.mayWrite && !model.busy, |
| - label: String(format: sheetsMacString("Edit %@"), point.ref), |
| - commit: { commit(right: $0) }, cancel: { |
| - guard !model.busy else { return } |
| - model.discardAll(); endEditing() |
| - }) |
| - .padding(.horizontal, 5) |
| - .frame(width: width(point.c), height: height(point.r)) |
| - .background(fill(style)) |
| - .overlay { Rectangle().strokeBorder(Color.accentColor, lineWidth: 2) } |
| - .accessibilityLabel(String(format: sheetsMacString("Edit %@"), point.ref)) |
| - } else { display(cell, style: style, alignment: alignment) } |
| - #else |
| - display(cell, style: style, alignment: alignment) |
| - #endif |
| - } |
| - } |
| - private func commit(right: Bool) { |
| - guard !model.busy, model.selection.start == point else { return } |
| - Task { |
| - await model.commit(moveRight: right) |
| - if !model.hasUnconfirmedChanges { endEditing() } |
| - } |
| + // The editor is not drawn here: it floats over the grid |
| + // (SheetEditorOverlay), so opening one re-renders no cell. |
| + return display(cell, style: style, alignment: alignment) |
| } |
| private func display(_ cell: Cell?, style: CellStyle?, alignment: Alignment) -> some View { |
| - Button(action: select) { |
| + let failed = model.editState(point) == .failed |
| + return Button(action: select) { |
| Text(cell?.display ?? "").font(.system(size: 13, weight: style?.b == true ? .bold : .regular)) |
| .italic(style?.i == true).lineLimit(1).padding(.horizontal, 5) |
| .frame(width: width(point.c), height: height(point.r), alignment: alignment) |
| @@ -57,20 +46,118 @@ struct SheetCell: View { |
| model.selection.contains(point) ? Color.accentColor : Color.secondary.opacity(0.2), |
| lineWidth: model.selection.contains(point) ? 2 : 0.5) |
| } |
| + .overlay(alignment: .topTrailing) { if failed { SheetNotSavedMark() } } |
| }.buttonStyle(.plain) |
| - .simultaneousGesture(TapGesture(count: 2).onEnded { if model.mayWrite, !model.busy, !model.hasUnconfirmedChanges { model.select(point); beginEditing() } }) |
| + .simultaneousGesture(TapGesture(count: 2).onEnded { if model.mayWrite, !model.dirty { model.select(point); beginEditing() } }) |
| + .modifier(NotSavedActions(model: model, point: point, failed: failed)) |
| .accessibilityLabel("\(point.ref), \(cell?.display ?? "Empty")") |
| - .accessibilityValue(style?.lc == true ? "Imported colours have low contrast" : "") |
| + .accessibilityValue(failed ? sheetsMacString("Not saved") : style?.lc == true ? "Imported colours have low contrast" : "") |
| .accessibilityAddTraits(model.selection.contains(point) ? .isSelected : []) |
| + .modifier(HiddenWhileEditing(state: editState, point: point)) |
| } |
| - private func fill(_ style: CellStyle?) -> Color { |
| - if let hex = style?.fx { return Color(hex: hex) } |
| - if let h = style?.fh, let c = style?.fc { return .oklch(scheme == .dark ? 0.30 : 0.92, c, h) } |
| - return Color.clear |
| - } |
| + private func fill(_ style: CellStyle?) -> Color { cellFill(style, scheme: scheme) } |
| private func ink(_ style: CellStyle?) -> Color { |
| if let hex = style?.k { return Color(hex: hex) } |
| if let h = style?.kh, let c = style?.kc { return .oklch(scheme == .dark ? 0.80 : 0.42, c, h) } |
| return .primary |
| } |
| } |
| + |
| +/// Hides a cell from accessibility while its editor floats over it, so |
| +/// VoiceOver finds one element there, not two. A modifier, so that opening an |
| +/// editor re-runs this small body for each cell and never the cell's own. |
| +private struct HiddenWhileEditing: ViewModifier { |
| + let state: SheetEditingState? |
| + let point: Coordinate |
| + func body(content: Content) -> some View { |
| + content.accessibilityHidden(state?.cell == point) |
| + } |
| +} |
| + |
| +/// Retry and Revert on a cell whose edit was not saved. Only such a cell |
| +/// carries a context menu and a tooltip, so the rest of the grid stays light. |
| +private struct NotSavedActions: ViewModifier { |
| + let model: SheetModel |
| + let point: Coordinate |
| + let failed: Bool |
| + func body(content: Content) -> some View { |
| + if failed { |
| + content |
| + .contextMenu { |
| + Button(sheetsMacString("Retry")) { model.retryWrites([point]) } |
| + Button(sheetsMacString("Revert"), role: .destructive) { model.revertWrites([point]) } |
| + } |
| + .help(sheetsMacString("Not saved")) |
| + } else { |
| + content |
| + } |
| + } |
| +} |
| + |
| +/// A refused or unanswered edit: a small corner flag, like a comment marker, |
| +/// so the value stays readable and the rest of the sheet stays calm. |
| +struct SheetNotSavedMark: View { |
| + var body: some View { |
| + Path { path in |
| + path.move(to: CGPoint(x: 0, y: 0)) |
| + path.addLine(to: CGPoint(x: 8, y: 0)) |
| + path.addLine(to: CGPoint(x: 8, y: 8)) |
| + path.closeSubpath() |
| + }.fill(Color.red).frame(width: 8, height: 8).accessibilityHidden(true) |
| + } |
| +} |
| + |
| +func cellFill(_ style: CellStyle?, scheme: ColorScheme) -> Color { |
| + if let hex = style?.fx { return Color(hex: hex) } |
| + if let h = style?.fh, let c = style?.fc { return .oklch(scheme == .dark ? 0.30 : 0.92, c, h) } |
| + return Color.clear |
| +} |
| + |
| +/// Which cell has an open editor. Observed only by the editor overlay and the |
| +/// selection observer, never by the grid or its cells: opening an editor |
| +/// re-rendered every cell when this lived in the grid, which on a 200-column |
| +/// sheet kept the first keystroke from its field for most of a second. |
| +@MainActor @Observable final class SheetEditingState { |
| + var cell: Coordinate? |
| +} |
| + |
| +#if os(macOS) |
| +/// The cell editor, floating over the grid at the edited cell. |
| +struct SheetEditorOverlay: View { |
| + @Bindable var model: SheetModel |
| + let state: SheetEditingState |
| + let window: SheetGridWindow |
| + let typeAhead: SheetTypeAhead |
| + let frame: (Coordinate) -> CGRect |
| + let end: () -> Void |
| + @Environment(\.colorScheme) private var scheme |
| + var body: some View { |
| + if let point = state.cell { |
| + let box = frame(point) |
| + let style = model.styles[model.displayCell(point)?.f ?? ""] |
| + // Never disabled by a save: saves are optimistic (SheetWrites.swift), |
| + // so the field neither greys nor drops focus while one is in flight. |
| + SheetCellEditor(text: $model.draft, enabled: model.mayWrite, |
| + label: String(format: sheetsMacString("Edit %@"), point.ref), |
| + typeAhead: typeAhead, |
| + commit: { commit(point, right: $0) }, cancel: { model.discard(); end() }) |
| + .padding(.horizontal, 5) |
| + .frame(width: box.width, height: box.height) |
| + .background(cellFill(style, scheme: scheme)) |
| + .background(.background) |
| + .overlay { Rectangle().strokeBorder(Color.accentColor, lineWidth: 2) } |
| + .accessibilityLabel(String(format: sheetsMacString("Edit %@"), point.ref)) |
| + .modifier(SheetHeaderClip(window: window, top: box.minY)) |
| + .offset(x: box.minX, y: box.minY) |
| + .id(point) |
| + } |
| + } |
| + private func commit(_ point: Coordinate, right: Bool) -> Bool { |
| + guard model.selection.start == point else { return false } |
| + model.commit(moveRight: right) |
| + guard !model.dirty else { return false } |
| + end() |
| + return true |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/SheetsKit/SheetCellEditor.swift b/native/apple/Sources/SheetsKit/SheetCellEditor.swift| index 162aef2..ca84b0e 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetCellEditor.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetCellEditor.swift |
| @@ -8,7 +8,9 @@ struct SheetCellEditor: NSViewRepresentable { |
| @Binding var text: String |
| let enabled: Bool |
| let label: String |
| - let commit: (Bool) -> Void |
| + var typeAhead: SheetTypeAhead? = nil |
| + /// Returns true when the edit ended (it may not, if the value was refused). |
| + let commit: (Bool) -> Bool |
| let cancel: () -> Void |
| func makeCoordinator() -> Coordinator { Coordinator(self) } |
| func makeNSView(context: Context) -> CellTextField { |
| @@ -20,6 +22,7 @@ struct SheetCellEditor: NSViewRepresentable { |
| field.delegate = context.coordinator |
| field.stringValue = text |
| field.setAccessibilityLabel(label) |
| + field.typeAhead = typeAhead |
| return field |
| } |
| func updateNSView(_ field: CellTextField, context: Context) { |
| @@ -35,6 +38,8 @@ struct SheetCellEditor: NSViewRepresentable { |
| if regainedEditing { field.window?.makeFirstResponder(field) } |
| } |
| final class CellTextField: NSTextField { |
| + /// Holds the keystroke that opened this field (SheetTypeAhead). |
| + weak var typeAhead: SheetTypeAhead? |
| override func viewDidMoveToWindow() { |
| super.viewDidMoveToWindow() |
| guard let window else { return } |
| @@ -49,6 +54,7 @@ struct SheetCellEditor: NSViewRepresentable { |
| if accepted, let editor = currentEditor() as? NSTextView { |
| editor.setSelectedRange(NSRange(location: editor.string.utf16.count, length: 0)) |
| } |
| + if accepted { typeAhead?.fieldFocused(self) } |
| return accepted |
| } |
| } |
| @@ -60,12 +66,17 @@ struct SheetCellEditor: NSViewRepresentable { |
| parent.text = field.stringValue |
| } |
| func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { |
| + let ended: Bool |
| switch selector { |
| - case #selector(NSResponder.insertNewline(_:)): parent.commit(false) |
| - case #selector(NSResponder.insertTab(_:)): parent.commit(true) |
| - case #selector(NSResponder.cancelOperation(_:)): parent.cancel() |
| + case #selector(NSResponder.insertNewline(_:)): ended = parent.commit(false) |
| + case #selector(NSResponder.insertTab(_:)): ended = parent.commit(true) |
| + case #selector(NSResponder.cancelOperation(_:)): parent.cancel(); ended = true |
| default: return false |
| } |
| + // Let go of the keyboard now, not when SwiftUI next removes this |
| + // field: a key typed in between belongs to the next cell, and the |
| + // grid's type-ahead takes it from here. |
| + if ended { control.window?.makeFirstResponder(nil) } |
| return true |
| } |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetClipboard.swift b/native/apple/Sources/SheetsKit/SheetClipboard.swift| index 5413ddb..7f705c8 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetClipboard.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetClipboard.swift |
| @@ -14,7 +14,7 @@ import Foundation |
| let range = selection |
| let rows = (range.start.r...range.end.r).map { r in |
| (range.start.c...range.end.c).map { c in |
| - CellWrite(r: r, c: c, raw: cells[Coordinate(r: r, c: c)]?.raw ?? "") |
| + CellWrite(r: r, c: c, raw: rawAt(Coordinate(r: r, c: c))) |
| } |
| } |
| copied = rows |
| @@ -27,7 +27,7 @@ import Foundation |
| #endif |
| } |
| func paste() async { |
| - guard !dirty && !busy else { |
| + guard !dirty else { |
| error = "Save or discard your cell edit first." |
| return |
| } |
| @@ -59,24 +59,24 @@ import Foundation |
| writes.append(CellWrite(r: dest.r, c: dest.c, raw: raw, fromR: source?.r, fromC: source?.c)) |
| } |
| } |
| - _ = await write(writes) |
| + write(writes) |
| } |
| func clear() async { |
| - guard !dirty && !busy else { |
| + guard !dirty else { |
| error = "Save or discard your cell edit first." |
| return |
| } |
| - _ = await write( |
| - selection.coordinates.filter { !(cells[$0]?.raw ?? "").isEmpty }.map { |
| + write( |
| + selection.coordinates.filter { !rawAt($0).isEmpty }.map { |
| CellWrite(r: $0.r, c: $0.c, raw: "") |
| }) |
| } |
| func fill(down: Bool) async { |
| - guard !dirty && !busy else { |
| + guard !dirty else { |
| error = "Save or discard your cell edit first." |
| return |
| } |
| - _ = await write(fillWrites(down: down)) |
| + write(fillWrites(down: down)) |
| } |
| func fillWrites(down: Bool) -> [CellWrite] { |
| let source = selection.start |
| @@ -90,7 +90,7 @@ import Foundation |
| return destinations.compactMap { point -> CellWrite? in |
| if source == point { return nil } |
| return CellWrite( |
| - r: point.r, c: point.c, raw: cells[source]?.raw ?? "", fromR: source.r, fromC: source.c) |
| + r: point.r, c: point.c, raw: rawAt(source), fromR: source.r, fromC: source.c) |
| } |
| } |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetCloseGuard.swift b/native/apple/Sources/SheetsKit/SheetCloseGuard.swift| index f4fca79..b9ae677 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetCloseGuard.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetCloseGuard.swift |
| @@ -38,6 +38,15 @@ |
| guard model.hasUnconfirmedChanges else { |
| return previousDelegate?.windowShouldClose?(sender) ?? true |
| } |
| + if !model.dirty && !model.hasFailedEdits { |
| + // Only edits on their way: let them land, then close; any that did |
| + // not (an ended session is not waited out) are asked about now. |
| + Task { @MainActor in |
| + await model.settle(hurry: true) |
| + if !model.hasUnconfirmedChanges || model.hasFailedEdits { sender.performClose(nil) } |
| + } |
| + return false |
| + } |
| let alert = NSAlert() |
| alert.messageText = "Keep your cell edit?" |
| alert.informativeText = "This cell has changes that have not been saved." |
| @@ -47,10 +56,12 @@ |
| alert.beginSheetModal(for: sender) { response in |
| Task { @MainActor in |
| if response == .alertFirstButtonReturn { |
| - await model.saveAll() |
| + await model.saveAll(hurry: true) |
| if !model.hasUnconfirmedChanges { sender.performClose(nil) } |
| } else if response == .alertSecondButtonReturn { |
| model.discardAll() |
| + await model.settle(hurry: true) |
| + model.revertWrites() |
| sender.performClose(nil) |
| } |
| } |
| @@ -67,6 +78,17 @@ |
| if models.contains(where: { $0.busy }) { return .terminateCancel } |
| let pending = models.filter { $0.hasUnconfirmedChanges } |
| if pending.isEmpty { return .terminateNow } |
| + if pending.allSatisfy({ !$0.dirty && !$0.hasFailedEdits }) { |
| + // Only edits on their way: quit once they land. Any that did not (an |
| + // ended session is not waited out) are asked about at once. |
| + Task { @MainActor in |
| + for model in pending { await model.settle(hurry: true) } |
| + let clean = !pending.contains { $0.hasUnconfirmedChanges } |
| + sender.reply(toApplicationShouldTerminate: clean) |
| + if !clean { DispatchQueue.main.async { NSApp.terminate(nil) } } |
| + } |
| + return .terminateLater |
| + } |
| let alert = NSAlert() |
| alert.messageText = "Save your spreadsheet edits before quitting?" |
| alert.addButton(withTitle: "Save") |
| @@ -75,13 +97,17 @@ |
| switch alert.runModal() { |
| case .alertFirstButtonReturn: |
| Task { @MainActor in |
| - for model in pending { await model.saveAll() } |
| + for model in pending { await model.saveAll(hurry: true) } |
| sender.reply(toApplicationShouldTerminate: !pending.contains { $0.hasUnconfirmedChanges }) |
| } |
| return .terminateLater |
| case .alertSecondButtonReturn: |
| pending.forEach { $0.discardAll() } |
| - return .terminateNow |
| + Task { @MainActor in |
| + for model in pending { await model.settle(hurry: true) } |
| + sender.reply(toApplicationShouldTerminate: true) |
| + } |
| + return .terminateLater |
| default: return .terminateCancel |
| } |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetEditingControls.swift b/native/apple/Sources/SheetsKit/SheetEditingControls.swift| index 03a50d0..2cabdfd 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetEditingControls.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetEditingControls.swift |
| @@ -11,29 +11,46 @@ struct SheetFormulaBar: View { |
| }.accessibilityLabel("Cell or range, for example A1:B5") |
| Text("fx").foregroundStyle(.secondary) |
| TextField("Cell contents or formula", text: $model.draft).focused(formulaFocused).disabled( |
| - !model.mayWrite || model.busy || !model.failedWrites.isEmpty |
| + !model.mayWrite || model.busy |
| ) |
| .autocorrectionDisabled() |
| #if os(iOS) |
| .textInputAutocapitalization(.never) |
| #endif |
| - .onSubmit { Task { await model.commit() } } |
| + .onSubmit { model.commit() } |
| .onKeyPress(.escape) { |
| model.discard() |
| return .handled |
| } |
| .onKeyPress(.tab) { |
| - Task { await model.commit(moveRight: true) } |
| + model.commit(moveRight: true) |
| return .handled |
| } |
| if model.dirty { |
| - Button(sheetsMacString("Save")) { Task { await model.commit() } }.disabled(model.busy) |
| + Button(sheetsMacString("Save")) { model.commit() }.disabled(model.busy) |
| Button("Discard") { model.discard() }.disabled(model.busy) |
| } |
| }.textFieldStyle(.roundedBorder).padding(8) |
| } |
| } |
| +/// Edits the server refused or never answered. Editing goes on around them; |
| +/// each marked cell also offers Retry and Revert from its context menu. |
| +struct SheetFailedEditsBar: View { |
| + var model: SheetModel |
| + var body: some View { |
| + if model.hasFailedEdits { |
| + HStack { |
| + Image(systemName: "exclamationmark.circle").foregroundStyle(.red).accessibilityHidden(true) |
| + Text(sheetsMacString("Some cell edits weren’t saved.")) |
| + Spacer() |
| + Button(sheetsMacString("Retry")) { model.retryWrites() } |
| + Button(sheetsMacString("Revert"), role: .destructive) { model.revertWrites() } |
| + }.font(.callout).padding(.horizontal, 8).padding(.vertical, 4) |
| + } |
| + } |
| +} |
| + |
| struct SheetStatusBar: View { |
| var model: SheetModel |
| var body: some View { |
| @@ -41,7 +58,7 @@ struct SheetStatusBar: View { |
| Text(model.page?.Sheet.TabName ?? "Sheet") |
| Spacer() |
| if model.busy { ProgressView().controlSize(.small) } |
| - Text(model.dirty ? "Unsaved cell edit" : model.notice) |
| + Text(model.saveStatus) |
| Text(model.live).foregroundStyle(.secondary) |
| }.font(.caption).padding(8) |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetFiles.swift b/native/apple/Sources/SheetsKit/SheetFiles.swift| index c8245bc..7fdedb4 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetFiles.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetFiles.swift |
| @@ -48,7 +48,7 @@ struct SheetFiles: View { |
| Button("Choose workbook") { picker = true }.disabled(working) |
| } else { |
| Button("Save workbook…") { Task { await export() } }.disabled( |
| - working || model.hasUnconfirmedChanges || model.busy) |
| + working || model.dirty || model.hasFailedEdits || model.busy) |
| } |
| if working { ProgressView() } |
| if !progress.isEmpty { Text(progress) } |
| @@ -83,6 +83,7 @@ struct SheetFiles: View { |
| workbook = nil |
| } |
| private func export() async { |
| + await model.settle() |
| guard !model.hasUnconfirmedChanges && !model.busy else { |
| progress = "Save your cell edit first." |
| return |
diff --git a/native/apple/Sources/SheetsKit/SheetFormatMenu.swift b/native/apple/Sources/SheetsKit/SheetFormatMenu.swift| index e9555ca..e4b8ba8 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetFormatMenu.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetFormatMenu.swift |
| @@ -55,6 +55,6 @@ struct SheetFormatMenu: View { |
| ]) |
| } |
| } |
| - }.disabled(!model.mayWrite || model.hasUnconfirmedChanges || model.busy) |
| + }.disabled(!model.mayWrite || model.dirty || model.busy) |
| } |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetGrid.swift b/native/apple/Sources/SheetsKit/SheetGrid.swift| index d01be06..2d0b6a3 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetGrid.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetGrid.swift |
| @@ -1,175 +1,191 @@ |
| import SwiftUI |
| +/// The grid: state and behaviour here, layout in `SheetGridContent`. |
| +/// |
| +/// The split is for speed. Anything this view owns that changes (keyboard |
| +/// focus above all, which moves every time a cell's editor opens or closes) |
| +/// re-runs this body; if that rebuilt the rows, opening an editor on a |
| +/// 200-column sheet cost most of a second before the first key reached it. |
| +/// The content is Equatable on what it actually draws from, so a focus change |
| +/// re-renders nothing but this thin shell. |
| struct SheetGrid: View { |
| @Bindable var model: SheetModel |
| - @State private var editing: Coordinate? |
| + @State private var editState = SheetEditingState() |
| @State private var resizing: SheetResizePreview? |
| @State private var savingResize = false |
| - @GestureState private var draggingResize = false |
| @FocusState private var focused: Bool |
| + @State private var scroller = SheetGridScroller() |
| + @State private var gridWindow = SheetGridWindow() |
| + #if os(macOS) |
| + @State private var typeAhead = SheetTypeAhead() |
| + #else |
| + /// Bumped to give the keyboard to the cell (SheetKeySink). |
| + @State private var keyboardRequest = 0 |
| + #endif |
| var beginEditing: () -> Void = {} |
| + /// How long typed keys wait for the cell's field before going to the |
| + /// formula bar instead. Tests shorten it. |
| + var typeAheadTimeout: TimeInterval = 1 |
| var body: some View { |
| - ScrollView([.horizontal, .vertical]) { |
| - LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) { |
| - Section { |
| - ForEach(0..<model.rows, id: \.self) { row in |
| - HStack(spacing: 0) { |
| - ZStack(alignment: .bottom) { |
| - Button { selectRow(row) } label: { |
| - Text(String(row + 1)).frame(width: 48, height: height(row)).background(.quaternary) |
| - }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1)) |
| - #if os(macOS) |
| - resizeHandle(axis: "row", index: row).frame(width: 48, height: 8) |
| - #else |
| - Color.clear.frame(width: 48, height: 8) |
| - .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row)) |
| - .accessibilityHidden(true) |
| - #endif |
| - } |
| - ForEach(0..<model.cols, id: \.self) { col in |
| - SheetCell( |
| - model: model, point: Coordinate(r: row, c: col), editing: $editing, |
| - select: { select(Coordinate(r: row, c: col)) }, |
| - beginEditing: { edit(Coordinate(r: row, c: col)) }, |
| - endEditing: { editing = nil; focused = true }, |
| - columnWidth: width(col), rowHeight: height(row)) |
| - } |
| - } |
| - } |
| - } header: { |
| - HStack(spacing: 0) { |
| - Text("").frame(width: 48, height: 32) |
| - ForEach(0..<model.cols, id: \.self) { col in |
| - ZStack(alignment: .trailing) { |
| - Button { selectColumn(col) } label: { |
| - Text(Coordinate(r: 0, c: col).ref.dropLast()) |
| - .frame(width: width(col), height: 32) |
| - .contentShape(.rect) |
| - }.buttonStyle(.plain) |
| - .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast()))) |
| - #if os(macOS) |
| - resizeHandle(axis: "col", index: col).frame(width: 8, height: 32) |
| - .help(sheetsMacString("Double-click to fit column to contents")) |
| - #else |
| - Color.clear.frame(width: 8, height: 32) |
| - #endif |
| - } |
| - #if os(macOS) |
| - .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } } |
| - #endif |
| - } |
| - }.background(.regularMaterial) |
| - } |
| - } |
| - }.defaultScrollAnchor(.topLeading) |
| + content.equatable() |
| .accessibilityLabel("Spreadsheet grid") |
| .focusable() |
| .focusEffectDisabled() |
| .focused($focused) |
| - .background { SheetSelectionObserver(model: model, editing: $editing) } |
| + .background { SheetSelectionObserver(model: model, state: editState) } |
| .onChange(of: focused) { _, value in model.gridFocused = value } |
| .onDisappear { model.gridFocused = false; if !savingResize { resizing = nil } } |
| - .onChange(of: draggingResize) { _, active in |
| - if !active, !savingResize { resizing = nil } |
| - } |
| .onKeyPress(.leftArrow) { move(0, -1) } |
| .onKeyPress(.rightArrow) { move(0, 1) } |
| .onKeyPress(.upArrow) { move(-1, 0) } |
| .onKeyPress(.downArrow) { move(1, 0) } |
| .onKeyPress(.delete) { |
| - guard editing == nil, model.mayWrite else { return .ignored } |
| + guard editState.cell == nil, model.mayWrite else { return .ignored } |
| Task { await model.clear() } |
| return .handled |
| } |
| .onKeyPress(.return) { |
| - guard editing == nil, model.mayWrite else { return .ignored } |
| + guard editState.cell == nil, model.mayWrite else { return .ignored } |
| edit(model.selection.start) |
| return .handled |
| } |
| - .onKeyPress(characters: .alphanumerics.union(.punctuationCharacters).union(.symbols).union(.whitespaces)) { |
| - press in |
| - guard model.mayWrite, !model.busy, !press.characters.contains(where: { $0 == "\t" || $0.isNewline }), |
| - press.modifiers.intersection([.command, .control, .option]).isEmpty |
| - else { return .ignored } |
| - if editing != nil { |
| - // Events arriving before the cell's native field gains focus still |
| - // belong to this edit. Once focused, NSTextField handles them itself. |
| - model.draft += press.characters |
| - } else { |
| - guard !model.hasUnconfirmedChanges else { return .ignored } |
| - model.draft = press.characters |
| - edit(model.selection.start) |
| - } |
| - return .handled |
| + #if os(macOS) |
| + .background { SheetKeyMonitor(handle: handleKey) } |
| + #else |
| + .onAppear { keyboardRequest += 1 } |
| + #endif |
| + } |
| + private var content: SheetGridContent { |
| + var actions = SheetGridActions( |
| + select: select, edit: edit, selectRow: selectRow, selectColumn: selectColumn, |
| + endEditing: endEditing, move: { r, c in _ = move(r, c) }, |
| + canResize: { [model] in model.mayWrite && !model.busy && !model.dirty && !savingResize }, |
| + resizeChange: resizeChange, resizeFinish: finishResize, |
| + resizeCancel: { if !savingResize { resizing = nil } }) |
| + actions.beginEditing = beginEditing |
| + #if os(macOS) |
| + return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing, |
| + typeAhead: typeAhead, actions: actions) |
| + #else |
| + return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing, |
| + keyboardRequest: keyboardRequest, actions: actions) |
| + #endif |
| + } |
| + private var metrics: SheetGridMetrics { |
| + SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols) |
| + } |
| + private func endEditing() { |
| + editState.cell = nil |
| + #if os(macOS) |
| + typeAhead.cancel() |
| + #endif |
| + takeKeyboard() |
| + } |
| + #if os(macOS) |
| + /// Every key event in this window, before SwiftUI sees it (SheetKeyMonitor). |
| + /// Typing on a selected cell opens its field and hands the keystroke to it |
| + /// whole, so a dead key or an input method composes from the first key. |
| + private func handleKey(_ event: NSEvent) -> Bool { |
| + if typeAhead.awaitingField { |
| + if typeAhead.expired || editState.cell == nil { |
| + // This key arrived after the field should have: it goes on to the |
| + // formula bar with the rest, not into the void. |
| + if SheetTypeAhead.startsTyping(event) { typeAhead.hold(event) } |
| + fieldNeverCame() |
| + return SheetTypeAhead.startsTyping(event) |
| + } else if event.modifierFlags.intersection([.command, .control]).isEmpty { |
| + typeAhead.hold(event) |
| + return true |
| + } else { |
| + return false |
| } |
| + } |
| + // The grid has the keyboard, or nothing does: a cell's field has just let |
| + // go of it (SheetCellEditor) and SwiftUI has not handed it back yet. |
| + guard editState.cell == nil, model.mayWrite, !model.dirty, !model.opening, let window = event.window, |
| + model.gridFocused || window.firstResponder === window, |
| + !(window.firstResponder is NSText) |
| + else { return false } |
| + if event.specialKey == .f2 { |
| + edit(model.selection.start) |
| + return true |
| + } |
| + guard SheetTypeAhead.startsTyping(event) else { return false } |
| + // Typing replaces the cell; Return, F2 and double-click keep it. The |
| + // cell may be scrolled out of view: bring it into view too. |
| + let point = model.selection.start |
| + scroller.reveal(point, at: metrics.frame(point)) |
| + typeAhead.begin(with: event, timeout: typeAheadTimeout, expired: fieldNeverCame) |
| + edit(point) |
| + if editState.cell == nil { typeAhead.cancel(); return false } |
| + return true |
| } |
| + /// The cell's field did not come up in time. Nothing typed is dropped: the |
| + /// held text goes to the formula bar, where the edit carries on. |
| + private func fieldNeverCame() { |
| + let text = typeAhead.heldText |
| + typeAhead.cancel() |
| + editState.cell = nil |
| + guard !text.isEmpty else { return } |
| + model.draft = text |
| + beginEditing() |
| + } |
| + #endif |
| private func edit(_ point: Coordinate) { |
| - guard model.mayWrite, !model.busy, model.failedWrites.isEmpty else { return } |
| + // Mid-switch the edit could only be committed to the sheet being left. |
| + guard model.mayWrite, !model.opening else { return } |
| #if os(macOS) |
| - editing = point |
| + editState.cell = point |
| #else |
| beginEditing() |
| #endif |
| } |
| private func select(_ point: Coordinate) { |
| - guard !model.busy else { return } |
| - if model.hasUnconfirmedChanges { |
| - Task { |
| - await model.saveAll() |
| - guard !model.hasUnconfirmedChanges, !model.busy else { return } |
| - editing = nil; model.select(point); focused = true |
| - } |
| - } else { |
| - if editing != point { editing = nil } |
| - model.select(point) |
| - focused = true |
| - } |
| + // Clicking another cell commits the one being typed in, as every |
| + // spreadsheet does; the save itself no longer holds anything up. |
| + if model.dirty, point != model.selection.start { model.commit(moveRight: nil) } |
| + guard !model.dirty else { return } |
| + if editState.cell != point { editState.cell = nil } |
| + model.select(point) |
| + takeKeyboard() |
| + } |
| + private func takeKeyboard() { |
| + #if os(macOS) |
| + focused = true |
| + #else |
| + keyboardRequest += 1 |
| + #endif |
| } |
| private func selectRow(_ row: Int) { |
| - guard !model.hasUnconfirmedChanges, !model.busy else { return } |
| - editing = nil |
| + guard !model.dirty else { return } |
| + editState.cell = nil |
| model.rangeText = "A\(row + 1):" + Coordinate(r: row, c: model.cols - 1).ref |
| model.selectRange() |
| - focused = true |
| + takeKeyboard() |
| } |
| private func selectColumn(_ col: Int) { |
| - guard !model.hasUnconfirmedChanges, !model.busy else { return } |
| - editing = nil |
| + guard !model.dirty else { return } |
| + editState.cell = nil |
| model.rangeText = Coordinate(r: 0, c: col).ref + ":" + Coordinate(r: model.rows - 1, c: col).ref |
| model.selectRange() |
| - focused = true |
| + takeKeyboard() |
| } |
| private func move(_ r: Int, _ c: Int) -> KeyPress.Result { |
| - guard editing == nil else { return .ignored } |
| + guard editState.cell == nil else { return .ignored } |
| let p = model.selection.start |
| - model.select( |
| - Coordinate(r: max(0, min(model.rows - 1, p.r + r)), c: max(0, min(model.cols - 1, p.c + c)))) |
| + let next = Coordinate(r: max(0, min(model.rows - 1, p.r + r)), c: max(0, min(model.cols - 1, p.c + c))) |
| + model.select(next) |
| + scroller.reveal(next, at: metrics.frame(next)) |
| return .handled |
| } |
| - private func width(_ col: Int) -> Double { |
| - if let resizing, resizing.axis == "col", resizing.index == col { return resizing.size } |
| - return model.sizes.cols?[String(col)] ?? 110 |
| - } |
| - private func height(_ row: Int) -> Double { |
| - if let resizing, resizing.axis == "row", resizing.index == row { return resizing.size } |
| - return model.sizes.rows?[String(row)] ?? 32 |
| - } |
| - #if os(macOS) |
| - private func resizeHandle(axis: String, index: Int) -> some View { |
| - SheetResizeHandle(vertical: axis == "row", |
| - canBegin: { model.mayWrite && !model.busy && !model.hasUnconfirmedChanges && !savingResize }, |
| - change: { translation in |
| - if resizing == nil { |
| - resizing = SheetResizePreview(axis: axis, index: index, |
| - original: axis == "col" ? width(index) : height(index)) |
| - } |
| - resizing?.update(translation: translation) |
| - }, finish: { finishResize(axis: axis, index: index) }, |
| - cancel: { if !savingResize { resizing = nil } }, |
| - fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil) |
| - |
| + private func resizeChange(axis: String, index: Int, translation: Double) { |
| + if resizing == nil { |
| + resizing = SheetResizePreview(axis: axis, index: index, |
| + original: axis == "col" ? metrics.width(index) : metrics.height(index)) |
| + } |
| + guard resizing?.axis == axis, resizing?.index == index else { return } |
| + resizing?.update(translation: translation) |
| } |
| - #endif |
| private func finishResize(axis: String, index: Int) { |
| guard let preview = resizing, preview.axis == axis, preview.index == index else { return } |
| savingResize = true |
| @@ -179,19 +195,276 @@ struct SheetGrid: View { |
| savingResize = false |
| } |
| } |
| +} |
| + |
| +/// What the grid's layout may ask of the grid. |
| +struct SheetGridActions { |
| + var select: (Coordinate) -> Void |
| + var edit: (Coordinate) -> Void |
| + var selectRow: (Int) -> Void |
| + var selectColumn: (Int) -> Void |
| + var endEditing: () -> Void |
| + var move: (Int, Int) -> Void |
| + var canResize: () -> Bool |
| + var resizeChange: (_ axis: String, _ index: Int, _ translation: Double) -> Void |
| + var resizeFinish: (_ axis: String, _ index: Int) -> Void |
| + var resizeCancel: () -> Void |
| + var beginEditing: () -> Void = {} |
| +} |
| + |
| +/// Column widths and row heights, with a resize in progress applied: the one |
| +/// geometry the grid is laid out from, and that the editor, the keyboard field, |
| +/// scrolling and the windowing below all read. Nothing is estimated. |
| +struct SheetGridMetrics { |
| + let sizes: Sizes |
| + let resizing: SheetResizePreview? |
| + let rows: Int |
| + let cols: Int |
| + /// Leading edge of each column (and the total width last), from 0. |
| + let colStarts: [Double] |
| + let rowStarts: [Double] |
| + init(sizes: Sizes, resizing: SheetResizePreview?, rows: Int, cols: Int) { |
| + self.sizes = sizes; self.resizing = resizing; self.rows = rows; self.cols = cols |
| + func width(_ c: Int) -> Double { |
| + if let resizing, resizing.axis == "col", resizing.index == c { return resizing.size } |
| + return sizes.cols?[String(c)] ?? 110 |
| + } |
| + func height(_ r: Int) -> Double { |
| + if let resizing, resizing.axis == "row", resizing.index == r { return resizing.size } |
| + return sizes.rows?[String(r)] ?? 32 |
| + } |
| + var x: [Double] = [0]; x.reserveCapacity(cols + 1) |
| + for c in 0..<cols { x.append(x[c] + width(c)) } |
| + var y: [Double] = [0]; y.reserveCapacity(rows + 1) |
| + for r in 0..<rows { y.append(y[r] + height(r)) } |
| + colStarts = x; rowStarts = y |
| + } |
| + static let rowHeader = 48.0 |
| + static let colHeader = 32.0 |
| + func width(_ col: Int) -> Double { col < cols ? colStarts[col + 1] - colStarts[col] : 110 } |
| + func height(_ row: Int) -> Double { row < rows ? rowStarts[row + 1] - rowStarts[row] : 32 } |
| + var cellsWidth: Double { colStarts[cols] } |
| + var cellsHeight: Double { rowStarts[rows] } |
| + /// Where a cell sits in the grid's content: after the row header and the |
| + /// pinned column header. |
| + func frame(_ point: Coordinate) -> CGRect { |
| + let c = min(point.c, cols), r = min(point.r, rows) |
| + return CGRect(x: Self.rowHeader + colStarts[c], y: Self.colHeader + rowStarts[r], |
| + width: width(point.c), height: height(point.r)) |
| + } |
| + /// The columns and rows a visible rect (content coordinates) touches, |
| + /// widened to whole blocks (2 columns, 4 rows), so scrolling re-renders the |
| + /// grid only every few columns or rows, never every pixel. Blocks are kept |
| + /// small: each crossing builds a block of new cells in one frame, and |
| + /// every cell built is one that opening an editor has to lay out. |
| + func window(for visible: CGRect) -> (cols: Range<Int>, rows: Range<Int>) { |
| + func span(_ starts: [Double], _ count: Int, _ lo: Double, _ hi: Double, block: Int) -> Range<Int> { |
| + guard count > 0 else { return 0..<0 } |
| + // First index whose far edge is past lo; last whose near edge is before hi. |
| + var first = 0, low = 0, high = count |
| + while low < high { let mid = (low + high) / 2; if starts[mid + 1] <= lo { low = mid + 1 } else { high = mid } } |
| + first = low |
| + low = first; high = count |
| + while low < high { let mid = (low + high) / 2; if starts[mid] < hi { low = mid + 1 } else { high = mid } } |
| + let last = max(first, low - 1) |
| + let start = first / block * block |
| + let end = min(count, (last / block + 1) * block) |
| + return start..<max(start, end) |
| + } |
| + return ( |
| + span(colStarts, cols, visible.minX - Self.rowHeader, visible.maxX - Self.rowHeader, block: 2), |
| + span(rowStarts, rows, visible.minY - Self.colHeader, visible.maxY - Self.colHeader, block: 4)) |
| + } |
| +} |
| + |
| +/// Which columns and rows exist as views. Only the grid's layout reads the |
| +/// ranges, and they change only when scrolling crosses a block. |
| +@MainActor @Observable final class SheetGridWindow { |
| + var cols: Range<Int> = 0..<8 |
| + var rows: Range<Int> = 0..<24 |
| + /// The top of the area below the pinned column header, in content |
| + /// coordinates: the editor is clipped to it. Read only while editing. |
| + var clipTop: Double = SheetGridMetrics.colHeader |
| + @ObservationIgnored var visible = CGRect(x: 0, y: 0, width: 800, height: 700) |
| + func update(_ visible: CGRect, _ metrics: SheetGridMetrics) { |
| + self.visible = visible |
| + let next = metrics.window(for: visible) |
| + if next.cols != cols { cols = next.cols } |
| + if next.rows != rows { rows = next.rows } |
| + let top = visible.minY + SheetGridMetrics.colHeader |
| + if top != clipTop { clipTop = top } |
| + } |
| +} |
| + |
| +/// The grid's rows, headers and floating editor. Equatable on what it draws |
| +/// from (the model's observed properties are tracked by SwiftUI as usual), so |
| +/// the grid's own focus and key state never rebuild it (see SheetGrid). |
| +struct SheetGridContent: View, Equatable { |
| + @Bindable var model: SheetModel |
| + let editState: SheetEditingState |
| + let scroller: SheetGridScroller |
| + let window: SheetGridWindow |
| + let resizing: SheetResizePreview? |
| + #if os(macOS) |
| + let typeAhead: SheetTypeAhead |
| + #else |
| + let keyboardRequest: Int |
| + #endif |
| + let actions: SheetGridActions |
| + @GestureState private var draggingResize = false |
| + |
| + /// SwiftUI compares views on the main thread, where they are built: `==` |
| + /// is nonisolated only because Equatable requires it, and the stored |
| + /// references (main-actor objects) are compared by identity, nothing more. |
| + nonisolated static func == (a: Self, b: Self) -> Bool { |
| + MainActor.assumeIsolated { |
| + #if os(macOS) |
| + let same = a.typeAhead === b.typeAhead |
| + #else |
| + let same = a.keyboardRequest == b.keyboardRequest |
| + #endif |
| + return same && a.model === b.model && a.editState === b.editState && a.scroller === b.scroller |
| + && a.window === b.window && a.resizing == b.resizing |
| + } |
| + } |
| + private var metrics: SheetGridMetrics { |
| + SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols) |
| + } |
| + @State private var position = ScrollPosition() |
| + |
| + // Columns and rows are windowed by hand from the exact metrics: a leading |
| + // and a trailing spacer stand in for what is off screen. (A LazyHStack |
| + // estimated the widths of columns it had not built, so its layout and the |
| + // exact geometry the editor and clicks use disagreed by whole columns.) |
| + var body: some View { |
| + let m = metrics |
| + let cols = Array(window.cols.clamped(to: 0..<m.cols)) |
| + let rows = Array(window.rows.clamped(to: 0..<m.rows)) |
| + let lead = m.colStarts[cols.first ?? 0] |
| + let trail = m.cellsWidth - m.colStarts[cols.last.map { $0 + 1 } ?? 0] |
| + ScrollView([.horizontal, .vertical]) { |
| + LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) { |
| + Section { |
| + VStack(alignment: .leading, spacing: 0) { |
| + Color.clear.frame(width: 1, height: m.rowStarts[rows.first ?? 0]) |
| + ForEach(rows, id: \.self) { row in |
| + HStack(spacing: 0) { |
| + rowHeader(row, m) |
| + Color.clear.frame(width: lead, height: m.height(row)) |
| + ForEach(cols, id: \.self) { col in cell(row: row, col: col, m) } |
| + Color.clear.frame(width: trail, height: m.height(row)) |
| + } |
| + } |
| + Color.clear.frame(width: 1, height: m.cellsHeight - m.rowStarts[rows.last.map { $0 + 1 } ?? 0]) |
| + } |
| + } header: { |
| + HStack(spacing: 0) { |
| + Text("").frame(width: SheetGridMetrics.rowHeader, height: SheetGridMetrics.colHeader) |
| + Color.clear.frame(width: lead, height: SheetGridMetrics.colHeader) |
| + ForEach(cols, id: \.self) { col in columnHeader(col, m) } |
| + Color.clear.frame(width: trail, height: SheetGridMetrics.colHeader) |
| + }.background(.regularMaterial) |
| + } |
| + } |
| + #if os(iOS) |
| + .overlay(alignment: .topLeading) { keySink } |
| + #else |
| + .overlay(alignment: .topLeading) { |
| + SheetEditorOverlay(model: model, state: editState, window: window, typeAhead: typeAhead, |
| + frame: m.frame, end: actions.endEditing) |
| + } |
| + #endif |
| + // Always-shown scroll bars sit over the content's last strip; without |
| + // room for them the last row and column could never be scrolled clear. |
| + .padding(.trailing, SheetGridScroller.legacyBar) |
| + .padding(.bottom, SheetGridScroller.legacyBar) |
| + } |
| + .defaultScrollAnchor(.topLeading) |
| + .scrollPosition($position) |
| + .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in |
| + scroller.visible = SheetGridScroller.usable(rect) |
| + window.update(rect, metrics) |
| + } |
| + // New sizes or a resize in progress move every edge after them. |
| + .onChange(of: m.colStarts + m.rowStarts) { window.update(window.visible, metrics) } |
| + .onAppear { |
| + scroller.scrollTo = { point in position.scrollTo(point: point) } |
| + window.update(window.visible, m) |
| + } |
| + .onChange(of: draggingResize) { _, active in |
| + if !active { actions.resizeCancel() } |
| + } |
| + } |
| + private func rowHeader(_ row: Int, _ m: SheetGridMetrics) -> some View { |
| + ZStack(alignment: .bottom) { |
| + Button { actions.selectRow(row) } label: { |
| + Text(String(row + 1)).frame(width: SheetGridMetrics.rowHeader, height: m.height(row)).background(.quaternary) |
| + }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1)) |
| + #if os(macOS) |
| + resizeHandle(axis: "row", index: row).frame(width: SheetGridMetrics.rowHeader, height: 8) |
| + #else |
| + Color.clear.frame(width: SheetGridMetrics.rowHeader, height: 8) |
| + .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row)) |
| + .accessibilityHidden(true) |
| + #endif |
| + } |
| + } |
| + private func columnHeader(_ col: Int, _ m: SheetGridMetrics) -> some View { |
| + ZStack(alignment: .trailing) { |
| + Button { actions.selectColumn(col) } label: { |
| + Text(Coordinate(r: 0, c: col).ref.dropLast()) |
| + .frame(width: m.width(col), height: SheetGridMetrics.colHeader) |
| + .contentShape(.rect) |
| + }.buttonStyle(.plain) |
| + .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast()))) |
| + #if os(macOS) |
| + resizeHandle(axis: "col", index: col).frame(width: 8, height: SheetGridMetrics.colHeader) |
| + .help(sheetsMacString("Double-click to fit column to contents")) |
| + #else |
| + Color.clear.frame(width: 8, height: SheetGridMetrics.colHeader) |
| + #endif |
| + } |
| + #if os(macOS) |
| + .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } } |
| + #endif |
| + } |
| + #if os(iOS) |
| + /// The keyboard's place on the selected cell (SheetKeySink). |
| + private var keySink: some View { |
| + let box = metrics.frame(model.selection.start) |
| + return SheetKeySink(model: model, focusRequest: keyboardRequest, move: actions.move) |
| + .frame(width: box.width, height: box.height) |
| + .modifier(SheetHeaderClip(window: window, top: box.minY)) |
| + .offset(x: box.minX, y: box.minY) |
| + .allowsHitTesting(false) |
| + } |
| + #endif |
| + private func cell(row: Int, col: Int, _ m: SheetGridMetrics) -> some View { |
| + let point = Coordinate(r: row, c: col) |
| + return SheetCell( |
| + model: model, point: point, |
| + select: { actions.select(point) }, |
| + beginEditing: { actions.edit(point) }, |
| + columnWidth: m.width(col), rowHeight: m.height(row), editState: editState).equatable() |
| + } |
| + #if os(macOS) |
| + private func resizeHandle(axis: String, index: Int) -> some View { |
| + SheetResizeHandle(vertical: axis == "row", |
| + canBegin: actions.canResize, |
| + change: { translation in actions.resizeChange(axis, index, translation) }, |
| + finish: { actions.resizeFinish(axis, index) }, |
| + cancel: actions.resizeCancel, |
| + fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil) |
| + } |
| + #endif |
| private func resizeGesture(axis: String, index: Int) -> some Gesture { |
| DragGesture(minimumDistance: 2, coordinateSpace: .global) |
| .updating($draggingResize) { _, active, _ in active = true } |
| .onChanged { value in |
| - guard model.mayWrite, !model.busy, !model.hasUnconfirmedChanges else { return } |
| - if resizing == nil { |
| - resizing = SheetResizePreview(axis: axis, index: index, |
| - original: axis == "col" ? width(index) : height(index)) |
| - } |
| - guard resizing?.axis == axis, resizing?.index == index else { return } |
| - resizing?.update(translation: axis == "col" ? value.translation.width : value.translation.height) |
| + guard actions.canResize() else { return } |
| + actions.resizeChange(axis, index, axis == "col" ? value.translation.width : value.translation.height) |
| } |
| - .onEnded { _ in finishResize(axis: axis, index: index) } |
| + .onEnded { _ in actions.resizeFinish(axis, index) } |
| } |
| } |
| @@ -199,16 +472,18 @@ struct SheetGrid: View { |
| /// LazyVStack and every row's view construction. |
| private struct SheetSelectionObserver: View { |
| let model: SheetModel |
| - @Binding var editing: Coordinate? |
| + let state: SheetEditingState |
| var body: some View { |
| Color.clear.frame(width: 0, height: 0) |
| .onChange(of: model.selection.start) { _, point in |
| - if editing != point { editing = nil } |
| + if state.cell != point { state.cell = nil } |
| } |
| + // A new sheet: no editor of the old one stays open over it. |
| + .onChange(of: model.page?.Sheet.ID) { state.cell = nil } |
| } |
| } |
| -struct SheetResizePreview { |
| +struct SheetResizePreview: Equatable { |
| let axis: String |
| let index: Int |
| let original: Double |
| @@ -220,3 +495,57 @@ struct SheetResizePreview { |
| size = min(2000, max(16, (original + translation).rounded())) |
| } |
| } |
| + |
| +/// Keeps the selected cell on screen. Not observed: scrolling must not |
| +/// re-render the grid. |
| +@MainActor final class SheetGridScroller { |
| + var scrollTo: ((CGPoint) -> Void)? |
| + /// The scroll view's visible rect, in the content's coordinates. |
| + var visible: CGRect? |
| + /// Scrolls only when the cell is not already in view (under the pinned |
| + /// column header counts as out of view), and never inside the keystroke: |
| + /// a scroll lays the grid out, and the first key must not wait for that. |
| + /// It scrolls just far enough, to the cell's exact place. |
| + func reveal(_ point: Coordinate, at frame: CGRect) { |
| + guard let visible, let target = Self.offset(showing: frame, in: visible) else { return } |
| + DispatchQueue.main.async { [weak self] in self?.scrollTo?(target) } |
| + } |
| + /// The part of the visible rect not under scroll bars. The scroll geometry |
| + /// counts the area under them; with legacy (always shown) scroll bars on |
| + /// the Mac, a cell revealed into that strip would be hidden by them. |
| + static func usable(_ rect: CGRect) -> CGRect { |
| + let bar = legacyBar |
| + return CGRect(x: rect.minX, y: rect.minY, width: rect.width - bar, height: rect.height - bar) |
| + } |
| + /// The width of an always-shown scroll bar, or 0 with overlay scroll bars. |
| + static var legacyBar: Double { |
| + #if os(macOS) |
| + NSScroller.preferredScrollerStyle == .legacy ? NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) : 0 |
| + #else |
| + 0 |
| + #endif |
| + } |
| + /// The content offset that brings `frame` into view with the least scroll, |
| + /// or nil when it is in view already. |
| + static func offset(showing frame: CGRect, in visible: CGRect) -> CGPoint? { |
| + let top = SheetGridMetrics.colHeader |
| + var x = visible.minX, y = visible.minY |
| + if frame.minX < visible.minX { x = frame.minX } else if frame.maxX > visible.maxX { x = frame.maxX - visible.width } |
| + if frame.minY < visible.minY + top { y = frame.minY - top } else if frame.maxY > visible.maxY { y = frame.maxY - visible.height } |
| + let target = CGPoint(x: max(0, x), y: max(0, y)) |
| + return target == visible.origin ? nil : target |
| + } |
| +} |
| + |
| +/// Keeps a floating field (the cell editor, the iOS key field) below the |
| +/// pinned column header when its cell has scrolled under it. |
| +struct SheetHeaderClip: ViewModifier { |
| + let window: SheetGridWindow |
| + /// The field's top, in the grid's content coordinates. |
| + let top: Double |
| + func body(content: Content) -> some View { |
| + content.mask(alignment: .topLeading) { |
| + Rectangle().padding(.top, max(0, window.clipTop - top)) |
| + } |
| + } |
| +} |
diff --git a/native/apple/Sources/SheetsKit/SheetKeySink.swift b/native/apple/Sources/SheetsKit/SheetKeySink.swift| new file mode 100644 |
| index 0000000..3bc56fe |
| --- /dev/null |
| +++ b/native/apple/Sources/SheetsKit/SheetKeySink.swift |
| @@ -0,0 +1,230 @@ |
| +#if os(iOS) |
| +import SwiftUI |
| +import UIKit |
| + |
| +/// The keyboard on iPad and iPhone, when a cell is selected. |
| +/// |
| +/// UIKit composes text (a dead key's ´ then e, an input method's かな) only |
| +/// inside a text input that is already first responder when the key goes |
| +/// down; a key press cannot be handed to one afterwards. So the grid keeps |
| +/// this field first responder while a cell is selected, sitting on that cell. |
| +/// Idle, it is invisible and turns arrows, Return, Tab and Delete into grid |
| +/// moves. The first text it receives, typed or composed, starts a cell edit |
| +/// that replaces the cell (Return and F2 keep it), and from then on it is the |
| +/// cell's editor. It brings up no on-screen keyboard: touch editing stays in |
| +/// the formula bar, reached by double-tapping a cell. |
| +struct SheetKeySink: UIViewRepresentable { |
| + let model: SheetModel |
| + /// Bumped to ask for the keyboard (a cell was tapped, the grid appeared). |
| + let focusRequest: Int |
| + let move: (Int, Int) -> Void |
| + func makeUIView(context: Context) -> SinkField { |
| + let field = SinkField() |
| + field.model = model |
| + field.move = move |
| + return field |
| + } |
| + func updateUIView(_ field: SinkField, context: Context) { |
| + field.model = model |
| + field.move = move |
| + field.pageChanged(to: model.page?.Sheet.ID) |
| + field.selectionChanged(to: model.selection.start) |
| + if focusRequest != field.focusRequest { |
| + field.focusRequest = focusRequest |
| + field.claimKeyboard() |
| + } |
| + } |
| + |
| + @MainActor final class SinkField: UITextField { |
| + weak var model: SheetModel? |
| + var move: (Int, Int) -> Void = { _, _ in } |
| + var focusRequest = 0 |
| + /// True once this field holds the cell's edit. |
| + private(set) var typing = false |
| + private var cell: Coordinate? |
| + private var quiet = false |
| + /// Presses handled here, so their ends are not sent on to UIKit either. |
| + private var handled: Set<UIKeyboardHIDUsage> = [] |
| + |
| + override init(frame: CGRect) { |
| + super.init(frame: frame) |
| + inputView = UIView() // no on-screen keyboard: touch edits in the formula bar |
| + inputAssistantItem.leadingBarButtonGroups = [] |
| + inputAssistantItem.trailingBarButtonGroups = [] |
| + autocorrectionType = .no |
| + autocapitalizationType = .none |
| + spellCheckingType = .no |
| + smartQuotesType = .no // a formula's quotes are ASCII |
| + smartDashesType = .no |
| + smartInsertDeleteType = .no |
| + inlinePredictionType = .no |
| + font = .systemFont(ofSize: 13) |
| + borderStyle = .none |
| + accessibilityLabel = sheetsMacString("Cell contents") |
| + addTarget(self, action: #selector(changed), for: .editingChanged) |
| + appearIdle() |
| + } |
| + required init?(coder: NSCoder) { nil } |
| + |
| + /// Idle, the field is invisible and cannot be typed into without a hardware |
| + /// keyboard, so VoiceOver must not land on it: the cell's own button is |
| + /// what it reads. Typing, it is the cell's editor and is announced as one. |
| + private func appearIdle() { |
| + isAccessibilityElement = false |
| + accessibilityElementsHidden = true |
| + textColor = .clear |
| + tintColor = .clear |
| + backgroundColor = .clear |
| + layer.borderWidth = 0 |
| + } |
| + private func appearTyping() { |
| + isAccessibilityElement = true |
| + accessibilityElementsHidden = false |
| + textColor = .label |
| + tintColor = nil |
| + backgroundColor = .systemBackground |
| + layer.borderColor = UIColor.tintColor.cgColor |
| + layer.borderWidth = 2 |
| + } |
| + |
| + func claimKeyboard() { |
| + guard window != nil, !isFirstResponder else { return } |
| + becomeFirstResponder() |
| + } |
| + override func didMoveToWindow() { |
| + super.didMoveToWindow() |
| + if window != nil && focusRequest > 0 { claimKeyboard() } |
| + } |
| + |
| + private var sheet: UInt64? |
| + /// Another sheet opened: no edit of the old one carries over. |
| + func pageChanged(to id: UInt64?) { |
| + guard id != sheet else { return } |
| + sheet = id |
| + if typing || !(text ?? "").isEmpty { reset() } |
| + } |
| + /// A commit, a cancel, or a tap moved the selection: this edit is over. |
| + func selectionChanged(to point: Coordinate) { |
| + guard point != cell else { return } |
| + cell = point |
| + if typing || !(text ?? "").isEmpty { reset() } |
| + } |
| + private func reset() { |
| + quiet = true |
| + if markedTextRange != nil { unmarkText() } |
| + text = "" |
| + quiet = false |
| + typing = false |
| + appearIdle() |
| + } |
| + |
| + /// Typed or composed text, the first of which starts the edit. |
| + @objc private func changed() { |
| + guard !quiet, let model else { return } |
| + let value = text ?? "" |
| + if !typing { |
| + guard model.mayWrite, !model.dirty, !model.opening, !value.isEmpty || markedTextRange != nil else { |
| + if !model.mayWrite { reset() } |
| + return |
| + } |
| + typing = true |
| + appearTyping() |
| + } |
| + model.draft = value |
| + } |
| + /// Every commit ends this edit, including one on the last row or column, |
| + /// where the selection cannot move and so would never reset the field. |
| + private func commit(moveRight: Bool) { |
| + guard let model else { return } |
| + model.commit(moveRight: moveRight) |
| + if !model.dirty { reset() } |
| + } |
| + /// Return or F2 on a selected cell: edit it here, keeping its contents. |
| + private func editInPlace() { |
| + guard let model, model.mayWrite, !model.dirty else { return } |
| + quiet = true |
| + text = model.rawAt(model.selection.start) |
| + quiet = false |
| + typing = true |
| + appearTyping() |
| + } |
| + |
| + // The text input calls a key press arrives as. Each reports the change |
| + // itself rather than relying on .editingChanged alone, which UIKit sends |
| + // for some of these and not others. |
| + override func insertText(_ text: String) { |
| + super.insertText(text) |
| + changed() |
| + } |
| + override func setMarkedText(_ markedText: String?, selectedRange: NSRange) { |
| + super.setMarkedText(markedText, selectedRange: selectedRange) |
| + changed() |
| + } |
| + override func unmarkText() { |
| + super.unmarkText() |
| + changed() |
| + } |
| + override func deleteBackward() { |
| + if typing { super.deleteBackward(); changed(); return } |
| + if let model, model.mayWrite { Task { await model.clear() } } |
| + } |
| + |
| + override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| + // An input method's own keys (Return confirms, Escape cancels, arrows |
| + // pick a candidate) are never ours while it is composing. |
| + guard markedTextRange == nil, let key = presses.first?.key, |
| + key.modifierFlags.intersection([.command, .control, .alternate]).isEmpty, |
| + handle(key.keyCode, shift: key.modifierFlags.contains(.shift)) |
| + else { return super.pressesBegan(presses, with: event) } |
| + handled.insert(key.keyCode) |
| + } |
| + /// The grid's keys. Returns false for anything that is text. |
| + func handle(_ code: UIKeyboardHIDUsage, shift: Bool = false) -> Bool { |
| + guard let model else { return false } |
| + switch code { |
| + case .keyboardReturnOrEnter, .keypadEnter: |
| + if typing { commit(moveRight: false) } else { editInPlace() } |
| + case .keyboardTab: |
| + if typing { commit(moveRight: true) } else { move(0, shift ? -1 : 1) } |
| + case .keyboardEscape: |
| + guard typing else { return false } |
| + model.discard(); reset() |
| + case .keyboardF2 where !typing: editInPlace() |
| + case .keyboardUpArrow where !typing: move(-1, 0) |
| + case .keyboardDownArrow where !typing: move(1, 0) |
| + case .keyboardLeftArrow where !typing: move(0, -1) |
| + case .keyboardRightArrow where !typing: move(0, 1) |
| + default: return false |
| + } |
| + return true |
| + } |
| + override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| + if let code = presses.first?.key?.keyCode, handled.remove(code) != nil { return } |
| + super.pressesEnded(presses, with: event) |
| + } |
| + override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) { |
| + if let code = presses.first?.key?.keyCode, handled.remove(code) != nil { return } |
| + super.pressesCancelled(presses, with: event) |
| + } |
| + |
| + /// Idle, Copy, Paste and Select All belong to the grid's commands. |
| + override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { |
| + typing ? super.canPerformAction(action, withSender: sender) : false |
| + } |
| + |
| + override func resignFirstResponder() -> Bool { |
| + let resigned = super.resignFirstResponder() |
| + // Focus went elsewhere (the formula bar, say): the edit, if any, carries |
| + // on there with the same draft. |
| + if resigned && typing { |
| + quiet = true |
| + text = "" |
| + quiet = false |
| + typing = false |
| + appearIdle() |
| + } |
| + return resigned |
| + } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/SheetsKit/SheetModel.swift b/native/apple/Sources/SheetsKit/SheetModel.swift| index db3587e..20f5ef6 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetModel.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetModel.swift |
| @@ -18,8 +18,28 @@ import RastrilloApple |
| var draft = "" |
| var originalDraft = "" |
| var dirty: Bool { draft != originalDraft } |
| - var failedWrites: [CellWrite] = [] |
| - var hasUnconfirmedChanges: Bool { dirty || !failedWrites.isEmpty } |
| + /// Value edits the server has not acknowledged (SheetWrites.swift). |
| + var pending: [Coordinate: PendingEdit] = [:] |
| + @ObservationIgnored var editGeneration: UInt64 = 0 |
| + @ObservationIgnored var sender: Task<Void, Never>? |
| + /// Held for as long as edits are on their way, so the system lets them land: |
| + /// on iOS a background task (a swipe away or a switch to another app does |
| + /// not cut the send off), on the Mac no sudden termination. Returns the end. |
| + @ObservationIgnored var keepAliveWhileSending: @MainActor () -> (@MainActor () -> Void) = SheetModel.keepAlive |
| + /// How long to wait, attempt by attempt, for an ended session to be renewed |
| + /// before an edit is marked as not saved (about a minute in all; Oficina ID |
| + /// re-mints at most once a minute per team). |
| + @ObservationIgnored var sessionRetryDelays: [Duration] = [ |
| + .milliseconds(500), .seconds(1), .seconds(2), .seconds(4), .seconds(8), .seconds(15), .seconds(30), |
| + ] |
| + /// Close or Quit is waiting: a session hold gives up at once, so the window |
| + /// can ask about the edits instead of waiting out the renewal. |
| + @ObservationIgnored var hurried = false |
| + @ObservationIgnored var sessionWait: Task<Void, Never>? |
| + /// True while `open` replaces the sheet: no edit may start against either. |
| + @ObservationIgnored var opening = false |
| + /// An edit being typed, or one not yet acknowledged by the server. |
| + var hasUnconfirmedChanges: Bool { dirty || !pending.isEmpty } |
| var busy = false |
| var error = "" |
| var notice = "" |
| @@ -62,15 +82,21 @@ import RastrilloApple |
| } |
| } |
| func open(_ sheet: SheetSummary) async { |
| + await settle() |
| guard !hasUnconfirmedChanges && !busy else { |
| error = "Save or discard your cell edit before changing sheets." |
| return |
| } |
| busy = true |
| - defer { busy = false } |
| + opening = true |
| + defer { busy = false; opening = false } |
| do { |
| let value: SheetPage = try await client.request("/sheets/\(sheet.ID)") |
| clearCopyProvenance() |
| + // Pending edits belong to the sheet they were made on; none survive it. |
| + pending = [:] |
| + originalDraft = "" |
| + draft = "" |
| page = value |
| version = 0 |
| cells = [:] |
| @@ -115,6 +141,7 @@ import RastrilloApple |
| cells = updated |
| styles = formats |
| sizes = fetchedSizes |
| + reconcileFailedEdits() |
| refreshDraftIfClean() |
| } |
| } catch is CancellationError { return } catch { self.error = error.localizedDescription } |
| @@ -144,61 +171,72 @@ import RastrilloApple |
| } |
| version = response.version |
| if let sizes = response.sizes { self.sizes = sizes } |
| + reconcileFailedEdits() |
| refreshDraftIfClean() |
| } |
| - private func refreshDraftIfClean() { |
| + func refreshDraftIfClean() { |
| guard !dirty else { return } |
| - originalDraft = cells[selection.start]?.raw ?? "" |
| + originalDraft = rawAt(selection.start) |
| draft = originalDraft |
| } |
| + /// Only an edit being typed holds the selection; edits on their way to the |
| + /// server never do. |
| func select(_ point: Coordinate) { |
| - guard !hasUnconfirmedChanges && !busy else { |
| + guard !dirty else { |
| error = "Save or discard this edit before selecting another cell." |
| return |
| } |
| selection = CellRange(point, point) |
| rangeText = point.ref |
| - originalDraft = cells[point]?.raw ?? "" |
| + originalDraft = rawAt(point) |
| draft = originalDraft |
| } |
| func selectRange() { |
| - guard !hasUnconfirmedChanges && !busy, let range = CellRange.parse(rangeText), |
| + guard !dirty, let range = CellRange.parse(rangeText), |
| range.end.r < rows, range.end.c < cols |
| else { |
| error = "Choose a range inside the visible sheet, after saving your edit." |
| return |
| } |
| selection = range |
| - originalDraft = cells[range.start]?.raw ?? "" |
| + originalDraft = rawAt(range.start) |
| draft = originalDraft |
| } |
| + /// Close, Quit and switching sheets: drop the edit being typed and every |
| + /// failed one. Edits already on their way are left to land. |
| func discardAll() { |
| - failedWrites = [] |
| + revertWrites() |
| discard() |
| } |
| - func saveAll() async { |
| - if !failedWrites.isEmpty { await retryWrites() } |
| - if failedWrites.isEmpty && dirty { await commit() } |
| + /// Close, Quit and switching sheets: commit the edit being typed, retry the |
| + /// failed ones, and wait for the answers. |
| + func saveAll(hurry: Bool = false) async { |
| + if dirty { commit(moveRight: nil) } |
| + retryWrites() |
| + await settle(hurry: hurry) |
| } |
| func discard() { |
| - originalDraft = cells[selection.start]?.raw ?? "" |
| + originalDraft = rawAt(selection.start) |
| draft = originalDraft |
| - error = "" |
| + if !hasFailedEdits { error = "" } |
| } |
| - func commit(moveRight: Bool = false) async { |
| + /// Commits the cell being edited and moves on at once; the server's answer |
| + /// arrives later (SheetWrites.swift). `moveRight: nil` stays put. |
| + func commit(moveRight: Bool? = false) { |
| let point = selection.start |
| - let saved = dirty ? await write([CellWrite(r: point.r, c: point.c, raw: draft)]) : true |
| - if saved { |
| + if dirty { |
| + guard write([CellWrite(r: point.r, c: point.c, raw: draft)]) else { return } |
| originalDraft = draft |
| - select( |
| - Coordinate( |
| - r: moveRight ? point.r : min(rows - 1, point.r + 1), |
| - c: moveRight ? min(cols - 1, point.c + 1) : point.c)) |
| } |
| + guard let moveRight else { return } |
| + select( |
| + Coordinate( |
| + r: moveRight ? point.r : min(rows - 1, point.r + 1), |
| + c: moveRight ? min(cols - 1, point.c + 1) : point.c)) |
| } |
| func format(_ values: [String: Any]) async { |
| - guard mayWrite && !busy && !hasUnconfirmedChanges else { return } |
| + guard mayWrite && !busy && !dirty else { return } |
| var values = values |
| values["r1"] = selection.start.r |
| values["c1"] = selection.start.c |
| @@ -213,7 +251,7 @@ import RastrilloApple |
| } catch { self.error = error.localizedDescription } |
| } |
| func resize(axis: String, size: Int, index: Int? = nil) async { |
| - guard mayWrite && !busy && !hasUnconfirmedChanges else { return } |
| + guard mayWrite && !busy && !dirty else { return } |
| busy = true |
| defer { busy = false } |
| do { |
| @@ -249,12 +287,15 @@ import RastrilloApple |
| } |
| @discardableResult func command(_ suffix: String, _ fields: [String: String] = [:]) async -> Bool |
| { |
| - guard !busy && !hasUnconfirmedChanges else { |
| + guard !busy && !dirty else { |
| error = "Save or discard the current edit first." |
| return false |
| } |
| lastNotice = "" |
| busy = true |
| + // Undo, restore and the rest act on what the server has: let the edits |
| + // already on their way land first. |
| + await settle() |
| defer { busy = false } |
| do { |
| let value: Notice = try await form(base + suffix, fields) |
| @@ -268,6 +309,7 @@ import RastrilloApple |
| } |
| } |
| @discardableResult func create(openCreated: Bool = true) async -> SheetSummary? { |
| + await settle() |
| guard !hasUnconfirmedChanges && !busy else { |
| error = "Save or discard the current edit first." |
| return nil |
| @@ -315,9 +357,9 @@ import RastrilloApple |
| func insertFunction(_ name: String) async { |
| let p = selection.start |
| var top = p.r |
| - while top > 0 && !(cells[Coordinate(r: top - 1, c: p.c)]?.raw ?? "").isEmpty { top -= 1 } |
| + while top > 0 && !rawAt(Coordinate(r: top - 1, c: p.c)).isEmpty { top -= 1 } |
| let arg = |
| top < p.r ? Coordinate(r: top, c: p.c).ref + ":" + Coordinate(r: p.r - 1, c: p.c).ref : "" |
| - _ = await write([CellWrite(r: p.r, c: p.c, raw: "=\(name)(\(arg))")]) |
| + write([CellWrite(r: p.r, c: p.c, raw: "=\(name)(\(arg))")]) |
| } |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetTable.swift b/native/apple/Sources/SheetsKit/SheetTable.swift| index 0af8392..e1f759c 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetTable.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetTable.swift |
| @@ -9,12 +9,12 @@ struct SheetTable: View { |
| Button("Previous page") { |
| model.tablePage -= 1 |
| Task { await model.loadTable() } |
| - }.disabled(model.table?.HasPrev != true || model.hasUnconfirmedChanges || model.busy) |
| + }.disabled(model.table?.HasPrev != true || model.dirty || model.busy) |
| Text("Page \(model.tablePage)") |
| Button("Next page") { |
| model.tablePage += 1 |
| Task { await model.loadTable() } |
| - }.disabled(model.table?.HasNext != true || model.hasUnconfirmedChanges || model.busy) |
| + }.disabled(model.table?.HasNext != true || model.dirty || model.busy) |
| } |
| ScrollView([.horizontal, .vertical]) { |
| LazyVStack(spacing: 0) { |
| @@ -22,7 +22,7 @@ struct SheetTable: View { |
| HStack(spacing: 0) { |
| Text(String(row.Number)).frame(width: 48) |
| ForEach(row.Cells, id: \.C) { cell in |
| - SheetCell(model: model, point: Coordinate(r: cell.R, c: cell.C), editing: .constant(nil), select: { model.select(Coordinate(r: cell.R, c: cell.C)) }, endEditing: {}) |
| + SheetCell(model: model, point: Coordinate(r: cell.R, c: cell.C), select: { model.select(Coordinate(r: cell.R, c: cell.C)) }) |
| } |
| } |
| } |
diff --git a/native/apple/Sources/SheetsKit/SheetTypeAhead.swift b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift| new file mode 100644 |
| index 0000000..cad13bd |
| --- /dev/null |
| +++ b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift |
| @@ -0,0 +1,138 @@ |
| +#if os(macOS) |
| +import AppKit |
| +import SwiftUI |
| + |
| +/// The keystroke that starts a cell edit, delivered to the cell's own text |
| +/// field rather than interpreted by the grid. |
| +/// |
| +/// Typing on a selected cell replaces it (Numbers, Excel, Google Sheets). The |
| +/// grid is not a text view, so it cannot read a keystroke as text: a dead key |
| +/// (´ then e makes é) arrives with no characters at all, and an input method |
| +/// (Japanese, Chinese) composes only inside a text input client. So the grid |
| +/// does not try. It holds the raw key events, opens the cell's field, and once |
| +/// that field has keyboard focus replays them into its field editor, where the |
| +/// system's text input machinery treats them as if they had been typed there. |
| +/// Events that arrive while the field is still coming up are held in order. |
| +@MainActor final class SheetTypeAhead { |
| + private(set) var held: [NSEvent] = [] |
| + /// True from the keystroke that opened the field until it has them all. |
| + private(set) var awaitingField = false |
| + private var deadline: TimeInterval = 0 |
| + /// Keys that change the input mode, not the text (JIS 英数 and かな): they |
| + /// arrive as key-downs with no characters, like a dead key, and are not one. |
| + static let modeKeys: Set<UInt16> = [102, 104] |
| + |
| + /// Whether a key, pressed on a selected cell, should start replacing it. |
| + /// Anything that is not text (arrows, Return, Tab, Escape, Delete, function |
| + /// keys) or that is a shortcut (Command, Control) is left to the grid. |
| + static func startsTyping(_ event: NSEvent) -> Bool { |
| + guard event.type == .keyDown, event.modifierFlags.intersection([.command, .control]).isEmpty, |
| + event.specialKey == nil, !modeKeys.contains(event.keyCode) |
| + else { return false } |
| + // A dead key has no characters yet; what it will compose is still text. |
| + // With Option (US ´ is Option-E) the unmodified key still names a |
| + // character; a layout's own dead key (Spanish ´, German ^, French ^) may |
| + // name none at all, and that empty key-down is a dead key too: modifier |
| + // keys arrive as flagsChanged, and every other non-text key is special. |
| + let text = (event.characters ?? "").isEmpty ? event.charactersIgnoringModifiers ?? "" : event.characters ?? "" |
| + guard let scalar = text.unicodeScalars.first else { return true } |
| + return !CharacterSet.controlCharacters.contains(scalar) |
| + } |
| + |
| + private var generation = 0 |
| + /// `expired` runs if the field has not come a second later; the grid then |
| + /// hands what was typed to the formula bar rather than drop it. |
| + func begin(with event: NSEvent, timeout: TimeInterval = 1, expired: @escaping () -> Void) { |
| + held = [event] |
| + awaitingField = true |
| + deadline = ProcessInfo.processInfo.systemUptime + timeout |
| + generation += 1 |
| + let current = generation |
| + DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self] in |
| + guard let self, self.awaitingField, self.generation == current else { return } |
| + expired() |
| + } |
| + } |
| + /// The text the held keys carry, for the formula bar if the field never |
| + /// comes. A dead key's composition is lost there; its base letter is not. |
| + var heldText: String { |
| + held.compactMap(\.characters).joined().filter { !$0.unicodeScalars.contains { CharacterSet.controlCharacters.contains($0) } } |
| + } |
| + func hold(_ event: NSEvent) { held.append(event) } |
| + /// A field that never came must not swallow keys. |
| + var expired: Bool { awaitingField && ProcessInfo.processInfo.systemUptime > deadline } |
| + func cancel() { |
| + held = [] |
| + awaitingField = false |
| + } |
| + |
| + /// Called once the cell's field is first responder. The replay waits one |
| + /// turn of the run loop so the window has switched its text input context to |
| + /// the new field editor; anything typed meanwhile is still held, in order. |
| + func fieldFocused(_ field: NSTextField) { |
| + guard awaitingField else { return } |
| + DispatchQueue.main.async { [weak self, weak field] in |
| + guard let self, let field else { return } |
| + self.replay(into: field) |
| + } |
| + } |
| + func replay(into field: NSTextField) { |
| + let events = held |
| + held = [] |
| + awaitingField = false |
| + // Typing replaces the cell, but only once text (or an input method's |
| + // marked text) actually arrives: the keys go in over the whole contents, |
| + // selected, and a key that turns out to type nothing leaves the cell as |
| + // it was, so a click away commits nothing. |
| + field.currentEditor()?.selectAll(nil) |
| + for (index, event) in events.enumerated() { |
| + guard let editor = field.currentEditor() else { |
| + // Return or Tab ended this edit; what followed starts the next one. |
| + for later in events[index...].reversed() { NSApp.postEvent(later, atStart: true) } |
| + return |
| + } |
| + editor.keyDown(with: event) |
| + } |
| + } |
| +} |
| + |
| +/// Watches the window's key events for the grid, ahead of SwiftUI, so the |
| +/// first keystroke reaches `SheetTypeAhead` whole (with its key code and |
| +/// modifiers) instead of as characters a dead key does not have yet. |
| +struct SheetKeyMonitor: NSViewRepresentable { |
| + /// Returns true when the event was taken. |
| + let handle: @MainActor (NSEvent) -> Bool |
| + func makeNSView(context: Context) -> MonitorView { |
| + let view = MonitorView() |
| + view.handle = handle |
| + return view |
| + } |
| + func updateNSView(_ view: MonitorView, context: Context) { view.handle = handle } |
| + static func dismantleNSView(_ view: MonitorView, coordinator: ()) { view.stop() } |
| + |
| + @MainActor final class MonitorView: NSView { |
| + var handle: (@MainActor (NSEvent) -> Bool)? |
| + private var monitor: Any? |
| + override func viewDidMoveToWindow() { |
| + super.viewDidMoveToWindow() |
| + stop() |
| + guard window != nil else { return } |
| + monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] incoming in |
| + // Local monitors run on the main thread, inside sendEvent. |
| + nonisolated(unsafe) let event = incoming |
| + let taken = MainActor.assumeIsolated { () -> Bool in |
| + guard let self, let window = self.window, event.window === window, |
| + let handle = self.handle |
| + else { return false } |
| + return handle(event) |
| + } |
| + return taken ? nil : event |
| + } |
| + } |
| + func stop() { |
| + if let monitor { NSEvent.removeMonitor(monitor) } |
| + monitor = nil |
| + } |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Sources/SheetsKit/SheetWire.swift b/native/apple/Sources/SheetsKit/SheetWire.swift| index ec455b4..17d9aa2 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetWire.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetWire.swift |
| @@ -71,7 +71,7 @@ struct GridResponse: Decodable, Sendable { |
| /// (server grid.go gridResponse.Stamps). See SheetModel.accept. |
| var stamps: Int? |
| } |
| -struct CellWrite: Encodable, Sendable { |
| +struct CellWrite: Encodable, Sendable, Equatable { |
| let r: Int |
| let c: Int |
| let raw: String |
diff --git a/native/apple/Sources/SheetsKit/SheetWrites.swift b/native/apple/Sources/SheetsKit/SheetWrites.swift| index 375e005..10bea76 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetWrites.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetWrites.swift |
| @@ -1,54 +1,256 @@ |
| import Foundation |
| import RastrilloApple |
| +#if os(iOS) |
| +import UIKit |
| +#endif |
| + |
| +/// A value edit the server has not acknowledged yet. |
| +/// |
| +/// Edits are optimistic (Paul, 2026-11-26: "the cell goes grey for a second |
| +/// to wait for the server … unnecessary"). Committing a cell records it here |
| +/// and returns at once; the cell paints this value normally while one send |
| +/// per document carries it, and any edits made meanwhile wait behind that send |
| +/// and go together in the next one. |
| +/// |
| +/// The display rule, which `SheetModel.displayCell` implements: |
| +/// - queued or sending: the local value wins. A peer update for the same cell |
| +/// lands underneath in `cells` and does not flicker the local value back |
| +/// and forth. |
| +/// - acknowledged: the entry is removed and the cell shows the server's value, |
| +/// which is the newest by version (ours, or a peer's that came after it). |
| +/// - failed: the local value stays on screen, marked as not saved, until |
| +/// Retry sends it again or Revert drops it and shows the server's value. |
| +/// An unsaved value nobody can see is one nobody can decide to keep. |
| +struct PendingEdit: Sendable, Equatable { |
| + enum State: Sendable, Equatable { case queued, sending, failed } |
| + var write: CellWrite |
| + var state: State |
| + /// Each new edit to a cell gets a higher generation, so an answer for an |
| + /// older send never resolves a newer edit made while it was in flight. |
| + var generation: UInt64 |
| +} |
| @MainActor extension SheetModel { |
| - @discardableResult func write(_ writes: [CellWrite], retrying: Bool = false) async -> Bool { |
| - guard failedWrites.isEmpty || retrying else { |
| - error = "Retry or discard the pending edits before making another change." |
| - return false |
| - } |
| - guard mayWrite && !busy else { return false } |
| + /// Records value edits and starts sending them. Returns false only when the |
| + /// edit cannot be accepted at all (no write access, or over the size limit); |
| + /// the answer from the server arrives later and never blocks editing. |
| + @discardableResult func write(_ writes: [CellWrite]) -> Bool { |
| + guard mayWrite else { return false } |
| + hurried = false |
| + // Mid-switch, an edit could only be sent to the sheet being left. |
| + guard !opening else { return false } |
| guard writes.allSatisfy({ $0.raw.utf8.count <= 8192 }) else { |
| error = "A cell exceeds the input size limit. Nothing was changed." |
| return false |
| } |
| if writes.isEmpty { return true } |
| - busy = true |
| - defer { busy = false } |
| - var offset = 0 |
| - do { |
| - while offset < writes.count { |
| - let batch = try await wire.encode(writes, startingAt: offset) |
| - let count = batch.count |
| - let data = batch.data |
| - let (bytes, status) = try await client.response( |
| - grid + "/cells/batch", method: "POST", body: data, maxBytes: 64 << 20) |
| - guard (200..<300).contains(status) else { |
| - throw NativeClientError.message("The server did not confirm the edit.") |
| + var next = pending |
| + for write in writes { |
| + editGeneration += 1 |
| + next[Coordinate(r: write.r, c: write.c)] = PendingEdit( |
| + write: write, state: .queued, generation: editGeneration) |
| + } |
| + pending = next |
| + startSending() |
| + return true |
| + } |
| + |
| + var hasFailedEdits: Bool { pending.values.contains { $0.state == .failed } } |
| + var isSending: Bool { pending.values.contains { $0.state != .failed } } |
| + /// The status bar's words: an edit being typed, edits on their way, edits |
| + /// not saved, or the last outcome. "Saved" only once nothing is left to |
| + /// send and nothing failed. |
| + var saveStatus: String { |
| + if dirty { return "Unsaved cell edit" } |
| + if isSending { return sheetsMacString("Saving…") } |
| + if hasFailedEdits { return sheetsMacString("Not saved") } |
| + return notice |
| + } |
| + |
| + static func keepAlive() -> (@MainActor () -> Void) { |
| + #if os(iOS) |
| + final class Holder { var id = UIBackgroundTaskIdentifier.invalid } |
| + let app = UIApplication.shared |
| + let task = Holder() |
| + task.id = app.beginBackgroundTask(withName: "Saving cell edits") { |
| + MainActor.assumeIsolated { |
| + app.endBackgroundTask(task.id) |
| + task.id = .invalid |
| + } |
| + } |
| + return { |
| + if task.id != .invalid { app.endBackgroundTask(task.id); task.id = .invalid } |
| + } |
| + #else |
| + ProcessInfo.processInfo.disableSuddenTermination() |
| + return { ProcessInfo.processInfo.enableSuddenTermination() } |
| + #endif |
| + } |
| + |
| + /// The cell as it should look: a pending local value wins over the server's. |
| + func displayCell(_ point: Coordinate) -> Cell? { |
| + guard let edit = pending[point] else { return cells[point] } |
| + let raw = edit.write.raw |
| + var cell = cells[point] ?? Cell(r: point.r, c: point.c, raw: "", display: "") |
| + cell.raw = raw |
| + cell.display = raw |
| + cell.n = Double(raw.trimmingCharacters(in: .whitespaces)) != nil |
| + return cell |
| + } |
| + /// The input a cell holds, including an edit that is still on its way. |
| + func rawAt(_ point: Coordinate) -> String { pending[point]?.write.raw ?? cells[point]?.raw ?? "" } |
| + func editState(_ point: Coordinate) -> PendingEdit.State? { pending[point]?.state } |
| + |
| + func retryWrites(_ points: [Coordinate]? = nil) { |
| + hurried = false |
| + var next = pending |
| + for (point, edit) in pending where edit.state == .failed && (points?.contains(point) ?? true) { |
| + next[point]?.state = .queued |
| + } |
| + pending = next |
| + error = "" |
| + startSending() |
| + } |
| + /// Drops failed edits and shows the server's value again. An edit whose |
| + /// answer was lost may have landed after all, so the cells are read back |
| + /// from the server rather than trusted from before the edit. Edits still |
| + /// being sent are not touched: they may land yet. |
| + func revertWrites(_ points: [Coordinate]? = nil) { |
| + pending = pending.filter { point, edit in |
| + edit.state != .failed || !(points?.contains(point) ?? true) |
| + } |
| + if !hasFailedEdits { error = "" } |
| + if !dirty { discard() } |
| + Task { await refresh() } |
| + } |
| + |
| + /// A failed edit the server turns out to hold (its answer was lost, then |
| + /// the live stream or a refetch brought the cell back) is saved after all. |
| + func reconcileFailedEdits() { |
| + // A cleared cell is absent from the server's cells, not an empty one. |
| + let landed = pending.filter { point, edit in |
| + edit.state == .failed && (cells[point]?.raw ?? "") == edit.write.raw |
| + } |
| + guard !landed.isEmpty else { return } |
| + pending = pending.filter { landed[$0.key] == nil } |
| + } |
| + |
| + /// Waits until nothing is queued or in flight. Failed edits stay failed. |
| + /// `hurry`: Close or Quit is waiting, so an ended session's edits are |
| + /// marked as not saved now rather than after the renewal hold (about a |
| + /// minute), and the window can ask about them straight away. |
| + func settle(hurry: Bool = false) async { |
| + if hurry { |
| + hurried = true |
| + sessionWait?.cancel() |
| + } |
| + while let sender { await sender.value } |
| + } |
| + |
| + func startSending() { |
| + guard sender == nil, pending.values.contains(where: { $0.state == .queued }) else { return } |
| + let release = keepAliveWhileSending() |
| + sender = Task { [weak self] in |
| + await self?.sendQueued() |
| + release() |
| + self?.sender = nil |
| + // An edit queued while the last answer was being applied. |
| + self?.startSending() |
| + } |
| + } |
| + |
| + /// One send per document at a time. Everything queued when a send starts |
| + /// goes in it; edits made meanwhile wait and go together in the next. |
| + private func sendQueued() async { |
| + var sessionWaits = 0 |
| + while !Task.isCancelled { |
| + let batch = pending.values.filter { $0.state == .queued }.sorted { $0.generation < $1.generation } |
| + guard !batch.isEmpty else { return } |
| + var next = pending |
| + for edit in batch { next[edit.write.coordinate]?.state = .sending } |
| + pending = next |
| + let source = grid |
| + let writes = batch.map(\.write) |
| + var offset = 0 |
| + do { |
| + while offset < writes.count { |
| + let chunk = try await wire.encode(writes, startingAt: offset) |
| + let (bytes, status) = try await client.response( |
| + source + "/cells/batch", method: "POST", body: chunk.data, maxBytes: 64 << 20) |
| + // 401, or the 303 to sign-in (the Oficina ID transport also reports |
| + // the guards' "Sign in first." 403 as 401): the session ended and is |
| + // being renewed. That refuses nothing about the edit. |
| + if status == 401 || status == 303 { throw NativeClientError.unauthorized } |
| + guard (200..<300).contains(status) else { |
| + throw NativeClientError.message(sheetsMacString("Not saved")) |
| + } |
| + let response = try await wire.decode(bytes) |
| + guard grid == source else { return abandon(batch) } |
| + await accept(response) |
| + resolve(batch[offset..<(offset + chunk.count)], failed: false) |
| + offset += chunk.count |
| + } |
| + sessionWaits = 0 |
| + error = "" |
| + if !isSending { notice = "Saved" } |
| + if showTable { await loadTable() } |
| + } catch NativeClientError.unauthorized where sessionWaits < sessionRetryDelays.count && !hurried { |
| + guard grid == source else { return abandon(batch) } |
| + // Hold the queue while the session is renewed, then send again: the |
| + // edits stay pending (Saving…), and edits made meanwhile join them. |
| + requeue(batch[offset...]) |
| + let delay = sessionRetryDelays[sessionWaits] |
| + sessionWaits += 1 |
| + let wait = Task { _ = try? await Task.sleep(for: delay) } |
| + sessionWait = wait |
| + await wait.value |
| + sessionWait = nil |
| + if hurried { |
| + // Close or Quit cut the hold short: what is queued is not saved. |
| + var next = pending |
| + for (point, edit) in pending where edit.state == .queued { next[point]?.state = .failed } |
| + pending = next |
| + return |
| } |
| - let response = try await wire.decode(bytes) |
| - await accept(response) |
| - offset += count |
| + } catch { |
| + guard grid == source else { return abandon(batch) } |
| + // The cells say so themselves, with Retry and Revert; editing goes on. |
| + resolve(batch[offset...], failed: true) |
| } |
| - failedWrites = [] |
| - error = "" |
| - notice = "Saved" |
| - if showTable { await loadTable() } |
| - return true |
| - } catch { |
| - failedWrites = Array(writes.dropFirst(offset)) |
| - self.error = |
| - "\(offset) cells confirmed; \(failedWrites.count) still need saving. " |
| - + error.localizedDescription |
| - return false |
| } |
| } |
| - func retryWrites() async { |
| - let pending = failedWrites |
| - if await write(pending, retrying: true), pending.count == 1, let value = pending.first, |
| - value.r == selection.start.r, value.c == selection.start.c, value.raw == draft |
| - { |
| - originalDraft = draft |
| + |
| + private func requeue(_ sent: ArraySlice<PendingEdit>) { |
| + var next = pending |
| + for edit in sent where next[edit.write.coordinate]?.generation == edit.generation { |
| + next[edit.write.coordinate]?.state = .queued |
| + } |
| + pending = next |
| + } |
| + |
| + /// The sheet changed under a send: its edits were for the old sheet, and |
| + /// must neither paint on the new one nor stay "sending" for ever. |
| + private func abandon(_ batch: [PendingEdit]) { |
| + var next = pending |
| + for edit in batch where next[edit.write.coordinate]?.generation == edit.generation { |
| + next[edit.write.coordinate] = nil |
| + } |
| + pending = next |
| + } |
| + |
| + /// Settles the edits a send carried, unless the person edited the cell again |
| + /// while it was in flight: that newer edit is still queued and stays. |
| + private func resolve(_ sent: ArraySlice<PendingEdit>, failed: Bool) { |
| + var next = pending |
| + for edit in sent where next[edit.write.coordinate]?.generation == edit.generation { |
| + if failed { next[edit.write.coordinate]?.state = .failed } |
| + else { next[edit.write.coordinate] = nil } |
| } |
| + pending = next |
| + refreshDraftIfClean() |
| } |
| } |
| + |
| +extension CellWrite { |
| + var coordinate: Coordinate { Coordinate(r: r, c: c) } |
| +} |
diff --git a/native/apple/Sources/SheetsKit/SheetsDocumentMenu.swift b/native/apple/Sources/SheetsKit/SheetsDocumentMenu.swift| index 894ca7a..b04fe88 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetsDocumentMenu.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetsDocumentMenu.swift |
| @@ -7,7 +7,7 @@ public struct SheetsDocumentMenu: View { |
| private var available: Bool { editor?.model.page != nil } |
| private var writable: Bool { |
| guard let model = editor?.model else { return false } |
| - return model.mayWrite && !model.busy && !model.hasUnconfirmedChanges |
| + return model.mayWrite && !model.busy && !model.dirty |
| } |
| public var body: some View { |
| Group { |
diff --git a/native/apple/Sources/SheetsKit/SheetsEditorCommands.swift b/native/apple/Sources/SheetsKit/SheetsEditorCommands.swift| index 9151495..79f8e98 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetsEditorCommands.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetsEditorCommands.swift |
| @@ -8,7 +8,7 @@ public struct SheetsEditorCommands: Commands { |
| private var available: Bool { editor?.model.page != nil } |
| private var writable: Bool { |
| guard let model = editor?.model else { return false } |
| - return model.mayWrite && !model.busy && !model.hasUnconfirmedChanges |
| + return model.mayWrite && !model.busy && !model.dirty |
| } |
| private func route(_ selector: Selector, grid: (SheetModel) -> Void) { |
| if NSApp.keyWindow?.firstResponder is NSTextView { |
| @@ -24,7 +24,7 @@ public struct SheetsEditorCommands: Commands { |
| } |
| CommandGroup(replacing: .pasteboard) { |
| Button(sheetsMacString("Cut")) { route(#selector(NSText.cut(_:))) { model in |
| - guard model.mayWrite, !model.busy, !model.hasUnconfirmedChanges else { return } |
| + guard model.mayWrite, !model.dirty else { return } |
| model.copy(); Task { await model.clear() } |
| } }.keyboardShortcut("x") |
| Button(sheetsMacString("Copy")) { route(#selector(NSText.copy(_:))) { $0.copy() } }.keyboardShortcut("c") |
diff --git a/native/apple/Sources/SheetsKit/SheetsWorkspace.swift b/native/apple/Sources/SheetsKit/SheetsWorkspace.swift| index e8696e2..02e5a8c 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetsWorkspace.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetsWorkspace.swift |
| @@ -121,7 +121,7 @@ import SwiftUI |
| } |
| ForEach(filteredSheets) { sheet in |
| Button { |
| - if model.hasUnconfirmedChanges { |
| + if model.dirty || model.hasFailedEdits { |
| pendingSheet = sheet |
| askDiscard = true |
| } else { Task { await model.open(sheet) } } |
| @@ -193,7 +193,7 @@ import SwiftUI |
| } |
| private var newSheet: some View { |
| Button(sheetsMacString("New spreadsheet"), systemImage: "plus") { Task { await createSheet() } } |
| - .disabled(model.hasUnconfirmedChanges || model.busy) |
| + .disabled(model.dirty || model.busy) |
| } |
| private func show(_ name: String) { |
| panel = Panel(name: name) |
| @@ -225,17 +225,17 @@ import SwiftUI |
| model.rangeText = "A1:" + Coordinate(r: model.rows - 1, c: model.cols - 1).ref |
| model.selectRange() |
| }.keyboardShortcut("a") |
| - }.disabled(model.hasUnconfirmedChanges || model.busy) |
| + }.disabled(model.dirty || model.busy) |
| Menu("Insert function") { |
| ForEach(["SUM", "AVERAGE", "COUNT", "MIN", "MAX"], id: \.self) { name in |
| Button(name) { Task { await model.insertFunction(name) } } |
| } |
| - }.disabled(!model.mayWrite || model.hasUnconfirmedChanges || model.busy) |
| + }.disabled(!model.mayWrite || model.dirty || model.busy) |
| SheetFormatMenu(model: model) |
| Button("Sizes") { show("Sizes") }.disabled( |
| - !model.mayWrite || model.hasUnconfirmedChanges || model.busy) |
| + !model.mayWrite || model.dirty || model.busy) |
| Button("Sort and filter") { show("Data") }.disabled( |
| - model.hasUnconfirmedChanges || model.busy) |
| + model.dirty || model.busy) |
| Button("Comments") { show("Comments") } |
| Button(sheetsMacString("Refresh"), systemImage: "arrow.clockwise") { Task { await model.refresh() } } |
| } |
| @@ -249,15 +249,7 @@ import SwiftUI |
| }.padding(8) |
| #endif |
| SheetFormulaBar(model: model, formulaFocused: $formulaFocused) |
| - if !model.failedWrites.isEmpty { |
| - HStack { |
| - Button("Retry pending edits") { Task { await model.retryWrites() } }.disabled(model.busy) |
| - Button("Discard pending edits", role: .destructive) { |
| - model.failedWrites = [] |
| - model.discard() |
| - }.disabled(model.busy) |
| - }.padding(8) |
| - } |
| + SheetFailedEditsBar(model: model) |
| if !model.error.isEmpty { |
| Text(model.error).foregroundStyle(.red).padding(8).accessibilityAddTraits( |
| .updatesFrequently) |
diff --git a/native/apple/Sources/SheetsReview/Review.swift b/native/apple/Sources/SheetsReview/Review.swift| index d7b0044..fef122a 100644 |
| --- a/native/apple/Sources/SheetsReview/Review.swift |
| +++ b/native/apple/Sources/SheetsReview/Review.swift |
| @@ -1,4 +1,7 @@ |
| // Test-only executable; isolated credentials arrive through stdin, never argv. |
| +// Mac only. The iOS stub lets the package's tests build for a simulator |
| +// (xcodebuild test -scheme SheetsNative-Package), where KeySinkTests run. |
| +#if os(macOS) |
| import AppKit |
| import SwiftUI |
| import RastrilloApple |
| @@ -61,3 +64,6 @@ import SheetsKit |
| return false |
| } |
| } |
| +#else |
| +@main enum Review { static func main() {} } |
| +#endif |
diff --git a/native/apple/Tests/SheetsKitTests/EditingTests.swift b/native/apple/Tests/SheetsKitTests/EditingTests.swift| index 60116b6..398908d 100644 |
| --- a/native/apple/Tests/SheetsKitTests/EditingTests.swift |
| +++ b/native/apple/Tests/SheetsKitTests/EditingTests.swift |
| @@ -92,23 +92,6 @@ import Testing |
| #expect(model.dirty) |
| } |
| -@MainActor @Test func pendingBatchCannotBeReplacedByFormulaCommit() async { |
| - let model = SheetModel(client: NativeHTTP(origin: URL(string: "http://localhost")!)) |
| - model.failedWrites = [ |
| - CellWrite(r: 1, c: 0, raw: "first pending"), CellWrite(r: 2, c: 0, raw: "second pending"), |
| - ] |
| - model.draft = "a new edit" |
| - await model.commit() |
| - #expect(model.failedWrites.map(\.raw) == ["first pending", "second pending"]) |
| - #expect(model.dirty) |
| - #expect(model.error.contains("Retry or discard")) |
| - model.discard() |
| - model.rangeText = "B2:C3" |
| - model.selectRange() |
| - #expect(model.selection.start == Coordinate(r: 0, c: 0)) |
| - #expect(model.failedWrites.count == 2) |
| -} |
| - |
| @Test func workbookExportNamesUseSafeDocumentTitles() { |
| let url = URL(fileURLWithPath: "/tmp/private-staging.xlsx") |
| #expect(WorkbookExport(url: url, title: "Budget 2026").filename == "Budget 2026.xlsx") |
diff --git a/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift| new file mode 100644 |
| index 0000000..63782c6 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift |
| @@ -0,0 +1,411 @@ |
| +#if os(macOS) |
| +import AppKit |
| +import Carbon |
| +import SwiftUI |
| +import XCTest |
| +import RastrilloApple |
| +@testable import SheetsKit |
| + |
| +/// Paul, 2026-11-26: "the first character typed focusses the cell and doesn't |
| +/// actually type into it." Two causes: a save in flight disabled the field (so |
| +/// keys typed meanwhile reached no responder), and the grid read keys as |
| +/// characters, which a dead key or an input method does not produce. |
| +final class FirstKeystrokeTests: XCTestCase { |
| + /// Records what reaches the cell's field editor. In `inputMethod` mode it |
| + /// stands in for an input method: it takes the key without inserting it, |
| + /// and the test then composes exactly as the system would. |
| + final class RecordingFieldEditor: NSTextView { |
| + var keys: [NSEvent] = [] |
| + var inputMethod = false |
| + override func keyDown(with event: NSEvent) { |
| + keys.append(event) |
| + if !inputMethod { super.keyDown(with: event) } |
| + } |
| + } |
| + @MainActor final class FieldEditorDelegate: NSObject, NSWindowDelegate { |
| + let editor: RecordingFieldEditor = { |
| + let editor = RecordingFieldEditor() |
| + editor.isFieldEditor = true |
| + return editor |
| + }() |
| + func windowWillReturnFieldEditor(_ sender: NSWindow, to client: Any?) -> Any? { |
| + client is SheetCellEditor.CellTextField ? editor : nil |
| + } |
| + } |
| + |
| + @MainActor private func host(_ model: SheetModel, delegate: NSWindowDelegate? = nil) async throws -> (NSWindow, NSView) { |
| + let host = NSHostingView(rootView: SheetGrid(model: model)) |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.delegate = delegate |
| + window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| + try await Task.sleep(for: .milliseconds(200)) |
| + // A2: below the header row and A1. |
| + click(NSPoint(x: 100, y: 400 - 32 - 32 - 16), window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + return (window, host) |
| + } |
| + @MainActor private func click(_ point: NSPoint, window: NSWindow, count: Int = 1) { |
| + for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { |
| + window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: count, pressure: 1)!) |
| + } |
| + } |
| + @MainActor private func key(_ text: String, ignoring: String? = nil, code: UInt16, modifiers: NSEvent.ModifierFlags = [], window: NSWindow) { |
| + NSApp.sendEvent(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: modifiers, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: ignoring ?? text, isARepeat: false, keyCode: code)!) |
| + } |
| + @MainActor private func editors(_ view: NSView) -> [NSTextField] { |
| + ((view as? SheetCellEditor.CellTextField).map { [$0] } ?? []) + view.subviews.flatMap(editors) |
| + } |
| + |
| + @MainActor func testTypingReplacesAndReturnKeeps() async throws { |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server) |
| + let a2 = Coordinate(r: 1, c: 0) |
| + model.cells[a2] = Cell(r: 1, c: 0, raw: "old", display: "old") |
| + let (window, _) = try await host(model) |
| + defer { window.orderOut(nil) } |
| + XCTAssertEqual(model.selection.start, a2) |
| + key("n", code: 45, window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertEqual(model.draft, "n", "typing on a selected cell replaces it") |
| + key("\u{1b}", code: 53, window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + XCTAssertEqual(model.draft, "old") |
| + // Return edits without replacing; so does F2. |
| + key("\r", code: 36, window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertTrue(window.firstResponder is NSTextView) |
| + key("!", code: 18, modifiers: [.shift], window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + XCTAssertEqual(model.draft, "old!") |
| + key("\u{1b}", code: 53, window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + let f2 = String(UnicodeScalar(UInt16(NSF2FunctionKey))!) |
| + key(f2, code: 120, modifiers: [.function], window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertTrue(window.firstResponder is NSTextView) |
| + XCTAssertEqual(model.draft, "old") |
| + } |
| + |
| + /// A dead key has no characters; the grid used to drop it, so ´ then e |
| + /// gave "e". Now the raw events reach the field editor in order, where the |
| + /// system composes them; the composition then lands in the draft. |
| + @MainActor func testDeadKeyReachesTheFieldAndComposes() async throws { |
| + let delegate = FieldEditorDelegate() |
| + let model = fixtureModel(SheetServerFixture()) |
| + let (window, _) = try await host(model, delegate: delegate) |
| + defer { window.orderOut(nil) } |
| + delegate.editor.inputMethod = true |
| + // Option-E is ´ on a US layout: no characters until the next key. |
| + key("", ignoring: "e", code: 14, modifiers: [.option], window: window) |
| + key("e", code: 14, window: window) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + XCTAssertTrue(window.firstResponder === delegate.editor, "the cell's field must have focus") |
| + XCTAssertEqual(delegate.editor.keys.map(\.keyCode), [14, 14], "both keys, in order, reach the text input") |
| + XCTAssertEqual(delegate.editor.keys.first?.modifierFlags.contains(.option), true) |
| + XCTAssertEqual(delegate.editor.keys.first?.characters, "", "the dead key arrives as a dead key") |
| + // What the keyboard layout does with that pair: |
| + delegate.editor.setMarkedText("´", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) |
| + delegate.editor.insertText("é", replacementRange: NSRange(location: NSNotFound, length: 0)) |
| + try await Task.sleep(for: .milliseconds(50)) |
| + XCTAssertEqual(model.draft, "é") |
| + } |
| + |
| + /// An input method (Japanese) must see the first key too, or "ka" becomes |
| + /// "kあ" instead of "か". |
| + @MainActor func testInputMethodSeesTheFirstKey() async throws { |
| + let delegate = FieldEditorDelegate() |
| + let model = fixtureModel(SheetServerFixture()) |
| + let (window, _) = try await host(model, delegate: delegate) |
| + defer { window.orderOut(nil) } |
| + delegate.editor.inputMethod = true |
| + key("k", code: 40, window: window) |
| + key("a", code: 0, window: window) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + XCTAssertEqual(delegate.editor.keys.compactMap(\.characters), ["k", "a"]) |
| + XCTAssertEqual(model.draft, "", "nothing is inserted behind the input method's back") |
| + let none = NSRange(location: NSNotFound, length: 0) |
| + delegate.editor.setMarkedText("k", selectedRange: NSRange(location: 1, length: 0), replacementRange: none) |
| + delegate.editor.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: none) |
| + delegate.editor.insertText("か", replacementRange: none) |
| + try await Task.sleep(for: .milliseconds(50)) |
| + XCTAssertEqual(model.draft, "か") |
| + delegate.editor.inputMethod = false |
| + key("\r", code: 36, window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "か") |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 2, c: 0)) |
| + } |
| + |
| + /// Typing straight on after Return, while the server has not answered. |
| + /// The field used to be disabled for the save: grey, and the next key went |
| + /// nowhere. |
| + @MainActor func testTypingDuringASaveIsNotLost() async throws { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + let (window, host) = try await host(model) |
| + defer { window.orderOut(nil) } |
| + key("h", code: 4, window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + key("\r", code: 36, window: window) |
| + key("x", code: 7, window: window) |
| + key("y", code: 16, window: window) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + XCTAssertEqual(server.heldCount, 1, "the first save is still waiting for the server") |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 2, c: 0)) |
| + XCTAssertEqual(model.draft, "xy") |
| + XCTAssertTrue(editors(host).allSatisfy(\.isEnabled), "no field greys while a save is in flight") |
| + XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "h") |
| + server.release(stopHolding: true) |
| + key("\r", code: 36, window: window) |
| + await model.settle() |
| + XCTAssertEqual(server.value(1, 0), "h") |
| + XCTAssertEqual(server.value(2, 0), "xy") |
| + } |
| + |
| + /// Return to the cell looking committed (editor gone, value painted). |
| + /// Before this change it was the server's round trip plus ~20 ms, grey |
| + /// throughout (measured on main 26d271a: 172 ms median at 150 ms latency). |
| + @MainActor func testReturnLooksCommittedWithinAFrame() async throws { |
| + var samples: [Double] = [] |
| + for _ in 0..<5 { |
| + let server = SheetServerFixture() |
| + server.hold() // the server never answers during the measurement |
| + let model = fixtureModel(server) |
| + let (window, host) = try await host(model) |
| + key("h", code: 4, window: window) |
| + try await Task.sleep(for: .milliseconds(120)) |
| + let start = ProcessInfo.processInfo.systemUptime |
| + key("\r", code: 36, window: window) |
| + while ProcessInfo.processInfo.systemUptime - start < 2 { |
| + host.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| + if editors(host).isEmpty, model.displayCell(Coordinate(r: 1, c: 0))?.display == "h" { break } |
| + try await Task.sleep(for: .milliseconds(1)) |
| + } |
| + samples.append((ProcessInfo.processInfo.systemUptime - start) * 1000) |
| + server.release(stopHolding: true) |
| + window.orderOut(nil) |
| + } |
| + let median = samples.sorted()[samples.count / 2] |
| + print("MEASURE return->committed with the server not answering: median \(String(format: "%.1f", median)) ms, all \(samples.map { String(format: "%.1f", $0) })") |
| + XCTAssertLessThan(median, 50) |
| + } |
| + |
| + /// Review #72, finding 2: a selected cell scrolled out of the lazy grid |
| + /// has no field. Typing must bring it into view and type into it, and |
| + /// must never empty the draft for a field that does not exist (the next |
| + /// click would commit that empty draft over the cell). |
| + @MainActor func testTypingOnACellScrolledOutOfViewBringsItBack() async throws { |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server, rows: 120, cols: 4) |
| + let far = Coordinate(r: 100, c: 0) |
| + model.cells[far] = Cell(r: 100, c: 0, raw: "keep me", display: "keep me") |
| + let (window, host) = try await host(model) |
| + defer { window.orderOut(nil) } |
| + model.select(far) |
| + key("x", code: 7, window: window) |
| + XCTAssertEqual(model.draft, "keep me", "the draft changes only once the cell's field has the keys") |
| + try await Task.sleep(for: .milliseconds(400)) |
| + XCTAssertFalse(editors(host).isEmpty, "the cell was scrolled into view and opened") |
| + XCTAssertEqual(model.draft, "x") |
| + key("\r", code: 36, window: window) |
| + await model.settle() |
| + XCTAssertEqual(server.value(100, 0), "x") |
| + } |
| + |
| + /// Review #72, finding 4: a layout's own dead key (Spanish ´, German ^) |
| + /// needs no Option and its key-down may carry no characters at all. The |
| + /// layouts are read with UCKeyTranslate, not selected, so the machine's |
| + /// keyboard is left alone: find each layout's unmodified dead keys, check |
| + /// they compose, and check such a key-down starts typing whatever AppKit |
| + /// puts in its character fields. |
| + @MainActor func testLayoutDeadKeysWithoutOptionStartTyping() throws { |
| + for id in ["com.apple.keylayout.Spanish-ISO", "com.apple.keylayout.German"] { |
| + let filter = [kTISPropertyInputSourceID as String: id] as CFDictionary |
| + guard let list = TISCreateInputSourceList(filter, true)?.takeRetainedValue() as? [TISInputSource], |
| + let source = list.first, |
| + let raw = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else { |
| + XCTFail("\(id) is not installed"); continue |
| + } |
| + let data = Unmanaged<CFData>.fromOpaque(raw).takeUnretainedValue() as Data |
| + var deadKeys: [(UInt16, String)] = [] |
| + data.withUnsafeBytes { buffer in |
| + let layout = buffer.bindMemory(to: UCKeyboardLayout.self).baseAddress! |
| + func translate(_ code: UInt16, _ state: inout UInt32) -> String { |
| + var chars = [UniChar](repeating: 0, count: 4); var length = 0 |
| + UCKeyTranslate(layout, code, UInt16(kUCKeyActionDown), 0, UInt32(LMGetKbdType()), 0, &state, 4, &length, &chars) |
| + return String(utf16CodeUnits: chars, count: length) |
| + } |
| + for code in UInt16(0)..<UInt16(51) { |
| + var state: UInt32 = 0 |
| + guard translate(code, &state).isEmpty, state != 0 else { continue } |
| + deadKeys.append((code, translate(14, &state))) // then e |
| + } |
| + } |
| + XCTAssertFalse(deadKeys.isEmpty, "\(id) has an unmodified dead key") |
| + XCTAssertTrue(deadKeys.contains { ["é", "ê", "è"].contains($0.1) }, "\(id): a dead key then e composes (\(deadKeys))") |
| + for (code, _) in deadKeys { |
| + for ignoring in ["", "´", "^"] { |
| + let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: ignoring, isARepeat: false, keyCode: code)! |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event), "\(id) dead key \(code) with ignoring \"\(ignoring)\"") |
| + } |
| + } |
| + } |
| + } |
| + |
| + /// Review #72 delta, finding 6: on a wide sheet the first key took up to |
| + /// 900 ms to reach the cell's field. First key to glyph (the key's text in |
| + /// the cell's draft) must not grow with the sheet's width. |
| + @MainActor func testFirstKeyReachesTheFieldWithinFramesOnWideSheets() async throws { |
| + var report: [String] = [] |
| + for cols in [10, 60, 200] { |
| + var samples: [Double] = [] |
| + // Six tries, the first a warm-up: a busy machine stalls one now and then. |
| + for attempt in 0..<6 { |
| + let model = fixtureModel(SheetServerFixture(), rows: 120, cols: cols) |
| + let (window, _) = try await host(model) |
| + let point = Coordinate(r: 1 + attempt, c: 1) |
| + model.select(point) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + let start = ProcessInfo.processInfo.systemUptime |
| + key("x", code: 7, window: window) |
| + while model.draft != "x", ProcessInfo.processInfo.systemUptime - start < 3 { |
| + try await Task.sleep(for: .milliseconds(1)) |
| + } |
| + samples.append((ProcessInfo.processInfo.systemUptime - start) * 1000) |
| + XCTAssertEqual(model.draft, "x", "\(cols) columns: the key never arrived") |
| + window.orderOut(nil) |
| + } |
| + samples.removeFirst() |
| + let median = samples.sorted()[samples.count / 2] |
| + report.append("\(cols) cols: median \(String(format: "%.1f", median)) ms \(samples.map { String(format: "%.0f", $0) })") |
| + XCTAssertLessThan(median, 50, "\(cols) columns: one or two frames, whatever the width") |
| + } |
| + print("MEASURE first key to glyph: " + report.joined(separator: "; ")) |
| + } |
| + |
| + /// Review #72 delta, finding 1: no editor of the old sheet survives, or |
| + /// opens during, a switch to another. |
| + @MainActor func testNoEditorSurvivesASheetSwitch() async throws { |
| + let server = SheetServerFixture() |
| + server.holdPages() |
| + let model = fixtureModel(server) |
| + let (window, host) = try await host(model) |
| + defer { window.orderOut(nil) } |
| + key("x", code: 7, window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertFalse(editors(host).isEmpty) |
| + model.discard() |
| + let opening = Task { await model.open(SheetSummary(ID: 2, Title: "", TabID: 0, TabName: "")) } |
| + let loading = await eventually { server.requests.contains("GET /sheets/2") } |
| + XCTAssertTrue(loading) |
| + key("\u{1b}", code: 53, window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + key("y", code: 16, window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertTrue(editors(host).isEmpty, "no editor opens while the sheet is being replaced") |
| + server.releasePages() |
| + await opening.value |
| + try await Task.sleep(for: .milliseconds(100)) |
| + XCTAssertEqual(model.page?.Sheet.ID, 2) |
| + XCTAssertTrue(editors(host).isEmpty) |
| + XCTAssertEqual(model.draft, "") |
| + } |
| + |
| + @MainActor func testAnOpenEditorClosesWhenTheSheetChanges() async throws { |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server) |
| + let (window, host) = try await host(model) |
| + defer { window.orderOut(nil) } |
| + // A1, where the new sheet's selection starts too: only the page changes. |
| + model.select(Coordinate(r: 0, c: 0)) |
| + key("x", code: 7, window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertFalse(editors(host).isEmpty) |
| + model.discard() |
| + await model.open(SheetSummary(ID: 2, Title: "", TabID: 0, TabName: "")) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + XCTAssertTrue(editors(host).isEmpty, "a stray editor of the old sheet stayed open") |
| + } |
| + |
| + /// Review #72 delta, finding 5: an empty key-down that types nothing (or |
| + /// an input-mode key) must not clear the cell. |
| + @MainActor func testAKeyThatTypesNothingLeavesTheCellAlone() async throws { |
| + let delegate = FieldEditorDelegate() |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server) |
| + model.cells[Coordinate(r: 1, c: 0)] = Cell(r: 1, c: 0, raw: "keep", display: "keep") |
| + let (window, host) = try await host(model, delegate: delegate) |
| + defer { window.orderOut(nil) } |
| + XCTAssertEqual(model.draft, "keep") |
| + // JIS かな: an input-mode key, not text. |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: 104)!)) |
| + // An empty key-down the system then makes nothing of. |
| + delegate.editor.inputMethod = true |
| + key("", code: 10, window: window) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + XCTAssertFalse(editors(host).isEmpty, "a dead key opens the cell") |
| + XCTAssertEqual(model.draft, "keep", "nothing typed, nothing replaced") |
| + click(NSPoint(x: 260, y: 320), window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + await model.settle() |
| + XCTAssertTrue(server.batches.isEmpty, "a click away wrote the cell") |
| + XCTAssertEqual(model.displayCell(Coordinate(r: 1, c: 0))?.display, "keep") |
| + } |
| + |
| + /// Held keys are never dropped: if the field does not come, what was typed |
| + /// is handed on (to the formula bar) rather than discarded. |
| + @MainActor func testHeldKeysAreHandedOnIfTheFieldNeverComes() async throws { |
| + func event(_ text: String, _ code: UInt16) -> NSEvent { |
| + NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: 0, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)! |
| + } |
| + let typeAhead = SheetTypeAhead() |
| + var handedOn: String? |
| + typeAhead.begin(with: event("x", 7), expired: { handedOn = typeAhead.heldText }) |
| + typeAhead.hold(event("y", 16)) |
| + typeAhead.hold(event("\r", 36)) |
| + try await Task.sleep(for: .milliseconds(1300)) |
| + XCTAssertEqual(handedOn, "xy", "the typed text, without the Return") |
| + } |
| + |
| + /// Review #72 delta 2, finding 2: when the next key (not the timer) finds |
| + /// the field late, that key goes to the formula bar too. |
| + @MainActor func testAKeyThatFindsTheFieldLateIsHandedOnToo() async throws { |
| + let model = fixtureModel(SheetServerFixture()) |
| + var formulaBar = 0 |
| + let host = NSHostingView(rootView: SheetGrid(model: model, beginEditing: { formulaBar += 1 }, typeAheadTimeout: 0)) |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| + defer { window.orderOut(nil) } |
| + try await Task.sleep(for: .milliseconds(200)) |
| + click(NSPoint(x: 100, y: 400 - 32 - 32 - 16), window: window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + // Both in one turn of the run loop: the second finds the deadline passed. |
| + key("x", code: 7, window: window) |
| + key("y", code: 16, window: window) |
| + XCTAssertEqual(model.draft, "xy", "the late key was lost") |
| + XCTAssertEqual(formulaBar, 1, "the edit carries on in the formula bar") |
| + } |
| + |
| + @MainActor func testWhichKeysStartTyping() { |
| + func event(_ chars: String, _ ignoring: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent { |
| + NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil, characters: chars, charactersIgnoringModifiers: ignoring, isARepeat: false, keyCode: code)! |
| + } |
| + func fn(_ key: Int) -> String { String(UnicodeScalar(UInt16(key))!) } |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event("a", "a", 0))) |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event("=", "=", 24))) |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event(" ", " ", 49))) |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event("å", "a", 0, [.option])), "Option characters are text") |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event("", "e", 14, [.option])), "a dead key starts a composition") |
| + XCTAssertTrue(SheetTypeAhead.startsTyping(event("ü", "ü", 33))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event("c", "c", 8, [.command]))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{3}", "c", 8, [.control]))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event("\r", "\r", 36))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event("\t", "\t", 48))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{1b}", "\u{1b}", 53))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event("\u{7f}", "\u{7f}", 51))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event(fn(NSUpArrowFunctionKey), fn(NSUpArrowFunctionKey), 126, [.function, .numericPad]))) |
| + XCTAssertFalse(SheetTypeAhead.startsTyping(event(fn(NSF2FunctionKey), fn(NSF2FunctionKey), 120, [.function]))) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Tests/SheetsKitTests/GridGeometryTests.swift b/native/apple/Tests/SheetsKitTests/GridGeometryTests.swift| new file mode 100644 |
| index 0000000..b9bf8a5 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/GridGeometryTests.swift |
| @@ -0,0 +1,216 @@ |
| +#if os(macOS) |
| +import AppKit |
| +import SwiftUI |
| +import XCTest |
| +import RastrilloApple |
| +@testable import SheetsKit |
| + |
| +/// Review #72, the column windowing: the grid is laid out from exact column |
| +/// widths and row heights (SheetGridMetrics), and the editor, clicks and |
| +/// scrolling all use the same numbers. A LazyHStack estimated the widths of |
| +/// columns it had not built, so after scrolling right a click selected a cell |
| +/// columns away from the one under the pointer, and the editor opened off |
| +/// screen. These scroll, click where the geometry says a cell is, and type. |
| +final class GridGeometryTests: XCTestCase { |
| + /// 60 columns of 40, 300 and 110 points, and rows of 60 and 32. |
| + @MainActor private func mixedModel() -> SheetModel { |
| + let model = fixtureModel(SheetServerFixture(), rows: 120, cols: 60) |
| + var cols: [String: Double] = [:], rows: [String: Double] = [:] |
| + for c in 0..<60 where c % 3 != 2 { cols[String(c)] = c % 3 == 0 ? 40 : 300 } |
| + for r in stride(from: 0, to: 120, by: 4) { rows[String(r)] = 60 } |
| + model.sizes = Sizes(cols: cols, rows: rows) |
| + return model |
| + } |
| + @MainActor private func metrics(_ model: SheetModel) -> SheetGridMetrics { |
| + SheetGridMetrics(sizes: model.sizes, resizing: nil, rows: model.rows, cols: model.cols) |
| + } |
| + @MainActor private func open(_ model: SheetModel) async throws -> (NSWindow, NSView, NSScrollView) { |
| + let host = NSHostingView(rootView: SheetGrid(model: model)) |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 640, height: 400), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| + try await Task.sleep(for: .milliseconds(300)) |
| + func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) } |
| + let scroll = try XCTUnwrap(scrolls(host).first) |
| + return (window, host, scroll) |
| + } |
| + @MainActor private func wheel(_ window: NSWindow, dx: Int32, dy: Int32 = 0) { |
| + let event = CGEvent(scrollWheelEvent2Source: nil, units: .pixel, wheelCount: 2, wheel1: dy, wheel2: dx, wheel3: 0)! |
| + let screen = window.convertPoint(toScreen: NSPoint(x: 320, y: 200)) |
| + event.location = CGPoint(x: screen.x, y: (NSScreen.screens.first?.frame.height ?? 0) - screen.y) |
| + window.sendEvent(NSEvent(cgEvent: event)!) |
| + } |
| + /// A content rect (the grid's coordinates) in window coordinates, now. |
| + @MainActor private func onScreen(_ frame: CGRect, _ scroll: NSScrollView, _ window: NSWindow) -> CGRect { |
| + let visible = scroll.contentView.bounds |
| + let height = window.contentView!.bounds.height |
| + return CGRect(x: frame.minX - visible.minX, y: height - (frame.maxY - visible.minY), width: frame.width, height: frame.height) |
| + } |
| + @MainActor private func click(_ point: CGPoint, _ window: NSWindow) { |
| + for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] { |
| + window.sendEvent(NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, eventNumber: 1, clickCount: 1, pressure: 1)!) |
| + } |
| + } |
| + @MainActor private func key(_ text: String, _ code: UInt16, _ window: NSWindow) { |
| + NSApp.sendEvent(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!) |
| + } |
| + @MainActor private func editorRect(_ host: NSView) -> CGRect? { |
| + func find(_ v: NSView) -> NSView? { v is SheetCellEditor.CellTextField ? v : v.subviews.lazy.compactMap(find).first } |
| + return find(host).map { $0.convert($0.bounds, to: nil) } |
| + } |
| + /// The editor's field sits inside its cell (inset by its padding) and on screen. |
| + @MainActor private func assertEditor(at cell: CGRect, _ host: NSView, _ scroll: NSScrollView, file: StaticString = #filePath, line: UInt = #line) { |
| + guard let field = editorRect(host) else { return XCTFail("no editor", file: file, line: line) } |
| + XCTAssertTrue(cell.insetBy(dx: -1, dy: -1).contains(field), "editor \(field) is not in its cell \(cell)", file: file, line: line) |
| + XCTAssertTrue(scroll.frame.contains(field), "editor \(field) is off screen", file: file, line: line) |
| + } |
| + |
| + @MainActor func testTheContentIsExactlyAsWideAndTallAsTheCells() async throws { |
| + let model = mixedModel() |
| + let (window, _, scroll) = try await open(model) |
| + defer { window.orderOut(nil) } |
| + let m = metrics(model) |
| + let document = try XCTUnwrap(scroll.documentView).frame.size |
| + // Plus room for always-shown scroll bars, when they are. |
| + let bar = SheetGridScroller.legacyBar |
| + XCTAssertEqual(document.width, SheetGridMetrics.rowHeader + m.cellsWidth + bar, accuracy: 0.5) |
| + XCTAssertEqual(document.height, SheetGridMetrics.colHeader + m.cellsHeight + bar, accuracy: 0.5) |
| + XCTAssertEqual(scroll.contentView.bounds.origin, .zero, "mixed widths opened pre-scrolled") |
| + } |
| + |
| + @MainActor func testClickAfterScrollingRightSelectsTheCellUnderThePointer() async throws { |
| + let model = mixedModel() |
| + let (window, host, scroll) = try await open(model) |
| + defer { window.orderOut(nil) } |
| + let m = metrics(model) |
| + for distance: Int32 in [-4000, -3000] { |
| + wheel(window, dx: distance) |
| + try await Task.sleep(for: .milliseconds(300)) |
| + let visible = scroll.contentView.bounds |
| + XCTAssertGreaterThan(visible.minX, 1000, "the grid scrolled right") |
| + // A cell fully in view, by the exact geometry. |
| + let row = 6 |
| + let col = try XCTUnwrap((0..<60).first { c in |
| + let f = m.frame(Coordinate(r: row, c: c)) |
| + return f.minX >= visible.minX + 10 && f.maxX <= visible.maxX - 10 |
| + }) |
| + let target = Coordinate(r: row, c: col) |
| + let cell = onScreen(m.frame(target), scroll, window) |
| + click(CGPoint(x: cell.midX, y: cell.midY), window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertEqual(model.selection.start, target, "the click selected a different cell from the one under it") |
| + key("q", 12, window) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + XCTAssertEqual(model.draft, "q") |
| + assertEditor(at: cell, host, scroll) |
| + key("\u{1b}", 53, window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + } |
| + } |
| + |
| + @MainActor func testTypingOnAFarCellScrollsExactlyToIt() async throws { |
| + let model = mixedModel() |
| + let (window, host, scroll) = try await open(model) |
| + defer { window.orderOut(nil) } |
| + let m = metrics(model) |
| + // Including the last cell, BH120: with always-shown scroll bars it |
| + // stopped one bar short, under both bars. |
| + for target in [Coordinate(r: 90, c: 50), Coordinate(r: 3, c: 1), Coordinate(r: 61, c: 33), Coordinate(r: 119, c: 59)] { |
| + model.select(target) |
| + key("z", 6, window) |
| + try await Task.sleep(for: .milliseconds(400)) |
| + let frame = m.frame(target) |
| + let visible = scroll.contentView.bounds |
| + let clear = CGRect(x: visible.minX, y: visible.minY + SheetGridMetrics.colHeader, |
| + width: visible.width, height: visible.height - SheetGridMetrics.colHeader) |
| + XCTAssertTrue(clear.insetBy(dx: -1, dy: -1).contains(frame), "\(target.ref) at \(frame) not in view \(visible)") |
| + XCTAssertEqual(model.draft, "z") |
| + assertEditor(at: onScreen(frame, scroll, window), host, scroll) |
| + key("\u{1b}", 53, window) |
| + try await Task.sleep(for: .milliseconds(100)) |
| + } |
| + } |
| + |
| + /// Review #72 delta 2, finding 3: an open editor scrolled up under the |
| + /// pinned column header is clipped by it, not drawn over it. |
| + @MainActor func testTheEditorStaysBelowThePinnedHeader() async throws { |
| + let model = fixtureModel(SheetServerFixture(), rows: 60, cols: 10) |
| + let (window, host, scroll) = try await open(model) |
| + defer { window.orderOut(nil) } |
| + model.select(Coordinate(r: 1, c: 1)) |
| + key("w", 13, window) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + XCTAssertNotNil(editorRect(host)) |
| + wheel(window, dx: 0, dy: -50) |
| + try await Task.sleep(for: .milliseconds(300)) |
| + XCTAssertGreaterThan(scroll.contentView.bounds.minY, 20) |
| + let bitmap = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) |
| + host.cacheDisplay(in: host.bounds, to: bitmap) |
| + let scale = Double(bitmap.pixelsWide) / host.bounds.width |
| + func colour(_ x: Double, _ yFromTop: Double) -> NSColor? { |
| + bitmap.colorAt(x: Int(x * scale), y: Int(yFromTop * scale))?.usingColorSpace(.sRGB) |
| + } |
| + let visible = scroll.contentView.bounds |
| + // Column B's header strip, above where the editor would draw, against |
| + // column D's, which has no editor anywhere near it. |
| + let m = metrics(model) |
| + let b = m.frame(Coordinate(r: 1, c: 1)), d = m.frame(Coordinate(r: 1, c: 3)) |
| + let underB = try XCTUnwrap(colour(b.midX - visible.minX, 20)) |
| + let underD = try XCTUnwrap(colour(d.midX - visible.minX, 20)) |
| + XCTAssertEqual(underB.redComponent, underD.redComponent, accuracy: 0.03, "the editor drew over the pinned header") |
| + XCTAssertEqual(underB.blueComponent, underD.blueComponent, accuracy: 0.03, "the editor drew over the pinned header") |
| + } |
| + |
| + @MainActor func testTheLeastScrollThatShowsACell() { |
| + let visible = CGRect(x: 1000, y: 500, width: 600, height: 400) |
| + XCTAssertNil(SheetGridScroller.offset(showing: CGRect(x: 1100, y: 600, width: 100, height: 30), in: visible)) |
| + XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 3000, y: 600, width: 100, height: 30), in: visible), |
| + CGPoint(x: 2500, y: 500), "far right: its right edge at the view's, not the grid's last column") |
| + XCTAssertEqual(SheetGridScroller.offset(showing: CGRect(x: 200, y: 510, width: 100, height: 30), in: visible), |
| + CGPoint(x: 200, y: 478), "up and left: clear of the pinned column header") |
| + } |
| +} |
| +#endif |
| + |
| +#if os(macOS) |
| +/// Review #72 (58b4cb0), finding 4: scrolling crosses a window block every |
| +/// few rows or columns, and each crossing rebuilt every visible cell's body. |
| +final class GridScrollTests: XCTestCase { |
| + @MainActor func testScrollStepsStayCheap() async throws { |
| + let model = fixtureModel(SheetServerFixture(), rows: 1000, cols: 200) |
| + for r in 0..<60 { for c in 0..<20 { model.cells[Coordinate(r: r, c: c)] = Cell(r: r, c: c, raw: "\(r)·\(c)", display: "\(r)·\(c)") } } |
| + let host = NSHostingView(rootView: SheetGrid(model: model)) |
| + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1200, height: 800), styleMask: [.titled], backing: .buffered, defer: false) |
| + window.contentView = host; NSApp.setActivationPolicy(.regular); window.makeKeyAndOrderFront(nil); NSApp.activate() |
| + defer { window.orderOut(nil) } |
| + try await Task.sleep(for: .milliseconds(300)) |
| + func scrolls(_ v: NSView) -> [NSScrollView] { ((v as? NSScrollView).map { [$0] } ?? []) + v.subviews.flatMap(scrolls) } |
| + let scroll = try XCTUnwrap(scrolls(host).first) |
| + var report: [String] = [] |
| + for (name, dx, dy) in [("vertical", 0.0, 32.0), ("horizontal", 55.0, 0.0), ("diagonal", 55.0, 32.0)] { |
| + scroll.contentView.scroll(to: .zero); scroll.reflectScrolledClipView(scroll.contentView) |
| + try await Task.sleep(for: .milliseconds(200)) |
| + var steps: [Double] = [] |
| + for step in 1...120 { |
| + let start = ProcessInfo.processInfo.systemUptime |
| + scroll.contentView.scroll(to: NSPoint(x: dx * Double(step), y: dy * Double(step))) |
| + scroll.reflectScrolledClipView(scroll.contentView) |
| + host.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| + var spent = ProcessInfo.processInfo.systemUptime - start |
| + // The window update the scroll set off renders on the next turn. |
| + await Task.yield(); await Task.yield() |
| + let again = ProcessInfo.processInfo.systemUptime |
| + host.layoutSubtreeIfNeeded(); window.displayIfNeeded() |
| + spent += ProcessInfo.processInfo.systemUptime - again |
| + steps.append(spent * 1000) |
| + } |
| + let mean = steps.reduce(0, +) / Double(steps.count) |
| + let worst = steps.max() ?? 0 |
| + report.append("\(name) mean \(String(format: "%.1f", mean)) worst \(String(format: "%.0f", worst)) ms") |
| + // Was 113 / 117 / 154 ms worst at 58b4cb0 on this host; a busy |
| + // machine adds a little, so the bound is loose. |
| + XCTAssertLessThan(worst, 130, "\(name): a scroll step took \(worst) ms") |
| + } |
| + print("MEASURE scroll steps, 1000x200, 1200x800: " + report.joined(separator: "; ")) |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Tests/SheetsKitTests/KeySinkTests.swift b/native/apple/Tests/SheetsKitTests/KeySinkTests.swift| new file mode 100644 |
| index 0000000..6b21e9a |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/KeySinkTests.swift |
| @@ -0,0 +1,150 @@ |
| +#if os(iOS) |
| +import UIKit |
| +import XCTest |
| +@testable import SheetsKit |
| + |
| +/// iPad and iPhone with a hardware keyboard (SheetKeySink). The text input |
| +/// calls below are the ones UIKit makes for a key press: insertText for a |
| +/// plain key, setMarkedText for a dead key or an input method's composition. |
| +final class KeySinkTests: XCTestCase { |
| + @MainActor private func sink(_ raw: String = "") -> (SheetModel, SheetKeySink.SinkField, UIWindow) { |
| + let model = fixtureModel(SheetServerFixture()) |
| + if !raw.isEmpty { model.cells[Coordinate(r: 0, c: 0)] = Cell(r: 0, c: 0, raw: raw, display: raw) } |
| + model.select(Coordinate(r: 0, c: 0)) |
| + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 300)) |
| + let field = SheetKeySink.SinkField() |
| + field.model = model |
| + field.move = { r, c in |
| + let p = model.selection.start |
| + model.select(Coordinate(r: max(0, p.r + r), c: max(0, p.c + c))) |
| + } |
| + field.frame = CGRect(x: 48, y: 32, width: 110, height: 32) |
| + window.addSubview(field) |
| + window.makeKeyAndVisible() |
| + field.selectionChanged(to: model.selection.start) |
| + field.focusRequest = 1 |
| + field.claimKeyboard() |
| + return (model, field, window) |
| + } |
| + private let none = NSRange(location: NSNotFound, length: 0) |
| + |
| + @MainActor func testTheFieldHoldsTheKeyboardWithoutAnOnScreenOne() { |
| + let (_, field, window) = sink() |
| + defer { window.isHidden = true } |
| + XCTAssertTrue(field.isFirstResponder) |
| + XCTAssertNotNil(field.inputView, "no on-screen keyboard over the grid") |
| + XCTAssertEqual(field.smartQuotesType, .no) |
| + XCTAssertFalse(field.typing) |
| + } |
| + |
| + @MainActor func testFirstKeyReplacesTheCell() { |
| + let (model, field, window) = sink("old") |
| + defer { window.isHidden = true } |
| + field.insertText("n") |
| + XCTAssertTrue(field.typing) |
| + XCTAssertEqual(model.draft, "n") |
| + field.insertText("ew") |
| + XCTAssertEqual(model.draft, "new") |
| + XCTAssertTrue(field.handle(.keyboardReturnOrEnter)) |
| + XCTAssertEqual(model.displayCell(Coordinate(r: 0, c: 0))?.display, "new") |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 0)) |
| + field.selectionChanged(to: model.selection.start) |
| + XCTAssertFalse(field.typing) |
| + XCTAssertEqual(field.text, "") |
| + } |
| + |
| + @MainActor func testDeadKeyComposesFromTheFirstKey() { |
| + let (model, field, window) = sink("old") |
| + defer { window.isHidden = true } |
| + field.setMarkedText("´", selectedRange: NSRange(location: 1, length: 0)) |
| + XCTAssertTrue(field.typing, "a dead key alone starts the edit") |
| + field.insertText("é") |
| + XCTAssertEqual(field.text, "é") |
| + XCTAssertEqual(model.draft, "é") |
| + } |
| + |
| + @MainActor func testInputMethodComposesFromTheFirstKey() { |
| + let (model, field, window) = sink() |
| + defer { window.isHidden = true } |
| + field.setMarkedText("k", selectedRange: NSRange(location: 1, length: 0)) |
| + field.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0)) |
| + // Return belongs to the input method while it composes. |
| + XCTAssertNotNil(field.markedTextRange) |
| + field.unmarkText() |
| + XCTAssertEqual(model.draft, "か") |
| + XCTAssertTrue(field.handle(.keyboardReturnOrEnter)) |
| + XCTAssertEqual(model.displayCell(Coordinate(r: 0, c: 0))?.display, "か") |
| + } |
| + |
| + @MainActor func testReturnAndF2KeepTheCellEscapeCancels() { |
| + let (model, field, window) = sink("old") |
| + defer { window.isHidden = true } |
| + XCTAssertTrue(field.handle(.keyboardReturnOrEnter)) |
| + XCTAssertTrue(field.typing) |
| + XCTAssertEqual(field.text, "old") |
| + field.insertText("!") |
| + XCTAssertEqual(model.draft, "old!") |
| + XCTAssertTrue(field.handle(.keyboardEscape)) |
| + XCTAssertFalse(field.typing) |
| + XCTAssertEqual(model.draft, "old") |
| + XCTAssertFalse(model.dirty) |
| + XCTAssertTrue(field.handle(.keyboardF2)) |
| + XCTAssertEqual(field.text, "old") |
| + } |
| + |
| + @MainActor func testIdleKeysMoveTheSelection() { |
| + let (model, field, window) = sink() |
| + defer { window.isHidden = true } |
| + XCTAssertTrue(field.handle(.keyboardDownArrow)) |
| + XCTAssertTrue(field.handle(.keyboardRightArrow)) |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 1)) |
| + XCTAssertTrue(field.handle(.keyboardTab, shift: true)) |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 1, c: 0)) |
| + XCTAssertFalse(field.handle(.keyboardA), "letters are text, not commands") |
| + } |
| + |
| + /// Review #72, finding 6: VoiceOver must not land on the invisible field. |
| + @MainActor func testIdleFieldIsHiddenFromAccessibility() { |
| + let (_, field, window) = sink("old") |
| + defer { window.isHidden = true } |
| + XCTAssertFalse(field.isAccessibilityElement) |
| + XCTAssertTrue(field.accessibilityElementsHidden) |
| + field.insertText("n") |
| + XCTAssertTrue(field.isAccessibilityElement, "while typing it is the cell's editor") |
| + XCTAssertFalse(field.accessibilityElementsHidden) |
| + XCTAssertTrue(field.handle(.keyboardEscape)) |
| + XCTAssertFalse(field.isAccessibilityElement) |
| + } |
| + |
| + /// Review #72, finding 7: on the last row Return commits but the selection |
| + /// cannot move; the field must still reset rather than keep the old text. |
| + @MainActor func testCommitOnTheLastRowAndColumnResetsTheField() { |
| + let (model, field, window) = sink() |
| + defer { window.isHidden = true } |
| + let corner = Coordinate(r: 5, c: 3) |
| + model.select(corner) |
| + field.selectionChanged(to: corner) |
| + field.insertText("last") |
| + XCTAssertTrue(field.handle(.keyboardReturnOrEnter)) |
| + XCTAssertEqual(model.selection.start, corner, "nowhere further down to go") |
| + XCTAssertEqual(model.displayCell(corner)?.display, "last") |
| + XCTAssertFalse(field.typing) |
| + XCTAssertEqual(field.text, "") |
| + field.insertText("again") |
| + XCTAssertEqual(model.draft, "again", "a new edit, not appended to the old one") |
| + XCTAssertTrue(field.handle(.keyboardTab)) |
| + XCTAssertFalse(field.typing) |
| + XCTAssertEqual(model.displayCell(corner)?.display, "again") |
| + } |
| + |
| + @MainActor func testReadOnlySheetsDoNotStartAnEdit() { |
| + let (model, field, window) = sink("old") |
| + defer { window.isHidden = true } |
| + model.page = SheetPage(Sheet: model.page!.Sheet, Rows: 6, Cols: 4, Truncated: false, MayWrite: false, |
| + MayComment: false, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil) |
| + field.insertText("x") |
| + XCTAssertFalse(field.typing) |
| + XCTAssertEqual(model.draft, "old") |
| + } |
| +} |
| +#endif |
diff --git a/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift| new file mode 100644 |
| index 0000000..06cc004 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift |
| @@ -0,0 +1,379 @@ |
| +import Foundation |
| +import RastrilloApple |
| +import Testing |
| + |
| +@testable import SheetsKit |
| + |
| +// Paul, 2026-11-26: "the cell goes grey for a second to wait for the server … |
| +// The change should probably be saved locally and then synced." Edits are |
| +// optimistic; these pin the rules in SheetWrites.swift. |
| + |
| +private let a1 = Coordinate(r: 0, c: 0) |
| +private let a2 = Coordinate(r: 1, c: 0) |
| +private let a3 = Coordinate(r: 2, c: 0) |
| +private let b1 = Coordinate(r: 0, c: 1) |
| + |
| +@MainActor private func type(_ model: SheetModel, _ point: Coordinate, _ raw: String, moveRight: Bool? = false) { |
| + model.select(point) |
| + model.draft = raw |
| + model.commit(moveRight: moveRight) |
| +} |
| + |
| +@MainActor @Test func committedValueShowsAtOnceWithoutBusy() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "hello") |
| + // Synchronously, before any network answer: moved on, value painted. |
| + #expect(model.selection.start == a2) |
| + #expect(model.displayCell(a1)?.display == "hello") |
| + #expect(!model.busy) |
| + #expect(!model.dirty) |
| + #expect(await eventually { server.heldCount == 1 }) |
| + #expect(model.editState(a1) == .sending) |
| + #expect(model.displayCell(a1)?.display == "hello") |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(model.pending.isEmpty) |
| + #expect(model.cells[a1]?.raw == "hello") |
| + #expect(model.displayCell(a1)?.display == "hello") |
| + #expect(model.error.isEmpty) |
| +} |
| + |
| +@MainActor @Test func oneSendInFlightAndLaterEditsCoalesce() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "1") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + // While the first is in flight: three edits, two to the same cell. |
| + type(model, a2, "2") |
| + type(model, a3, "3") |
| + type(model, a2, "two") |
| + try? await Task.sleep(for: .milliseconds(50)) |
| + #expect(server.batches.count == 1, "a second send started while one was in flight") |
| + #expect(model.displayCell(a2)?.raw == "two") |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(server.batches.count == 2) |
| + #expect(server.batches[0] == [.init(r: 0, c: 0, raw: "1")]) |
| + #expect(server.batches[1] == [.init(r: 2, c: 0, raw: "3"), .init(r: 1, c: 0, raw: "two")]) |
| + #expect(model.pending.isEmpty) |
| + #expect(model.cells[a2]?.raw == "two") |
| + #expect(model.error.isEmpty, "the version moved by exactly the stamps; no refetch was needed") |
| +} |
| + |
| +@MainActor @Test func refusedEditIsMarkedAndEditingCarriesOn() async { |
| + let server = SheetServerFixture() |
| + server.refuseNext() |
| + let model = fixtureModel(server) |
| + type(model, a1, "refused") |
| + await model.settle() |
| + #expect(model.editState(a1) == .failed) |
| + #expect(model.hasFailedEdits) |
| + // The value stays visible, marked; nothing else is blocked. |
| + #expect(model.displayCell(a1)?.display == "refused") |
| + #expect(!model.busy) |
| + type(model, b1, "later") |
| + #expect(model.selection.start == Coordinate(r: 1, c: 1)) |
| + await model.settle() |
| + #expect(model.cells[b1]?.raw == "later") |
| + #expect(model.editState(a1) == .failed, "a later send must not resolve an earlier failure") |
| + model.retryWrites([a1]) |
| + await model.settle() |
| + #expect(model.pending.isEmpty) |
| + #expect(server.value(0, 0) == "refused") |
| + #expect(model.cells[a1]?.raw == "refused") |
| + #expect(server.batches.map(\.first?.raw) == ["refused", "later", "refused"]) |
| +} |
| + |
| +@MainActor @Test func revertShowsTheServerValueAgain() async { |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server) |
| + type(model, a1, "kept") |
| + await model.settle() |
| + server.refuseNext() |
| + type(model, a1, "refused") |
| + await model.settle() |
| + #expect(model.displayCell(a1)?.raw == "refused") |
| + model.select(a1) |
| + #expect(model.draft == "refused", "the formula bar reads what the cell shows") |
| + model.revertWrites([a1]) |
| + #expect(model.pending.isEmpty) |
| + #expect(model.displayCell(a1)?.raw == "kept") |
| + #expect(model.draft == "kept") |
| + #expect(!model.hasFailedEdits) |
| +} |
| + |
| +@MainActor @Test func failedEditsSurviveCloseOnlyByChoice() async { |
| + let server = SheetServerFixture() |
| + server.refuseNext() |
| + let model = fixtureModel(server) |
| + type(model, a1, "x") |
| + await model.settle() |
| + #expect(model.hasUnconfirmedChanges, "close and quit must ask about a failed edit") |
| + await model.saveAll() |
| + #expect(!model.hasUnconfirmedChanges) |
| + #expect(server.value(0, 0) == "x") |
| +} |
| + |
| +/// The rule for a peer update to a cell with a local edit on its way: the |
| +/// local value wins on screen until the server acknowledges (or refuses) it, |
| +/// then the cell shows the server's newest value. Never back, then forward. |
| +@MainActor @Test func peerUpdateDoesNotFlickerAPendingLocalValue() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "mine") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + // A peer's edit of the same cell (and another) lands before our answer. |
| + await model.accept(server.peer(0, 0, "theirs")) |
| + await model.accept(server.peer(0, 1, "peer B1")) |
| + #expect(model.cells[a1]?.raw == "theirs", "the server's value is kept underneath") |
| + #expect(model.displayCell(a1)?.raw == "mine", "the pending local value wins on screen") |
| + #expect(model.displayCell(b1)?.raw == "peer B1", "peer edits to other cells apply at once") |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + // Ours landed after theirs on the server, so ours is the newest value. |
| + #expect(model.pending.isEmpty) |
| + #expect(model.displayCell(a1)?.raw == "mine") |
| + #expect(model.error.isEmpty) |
| +} |
| + |
| +@MainActor @Test func acknowledgedEditGivesWayToANewerPeerValue() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "mine") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + server.release(stopHolding: true) |
| + #expect(await eventually { server.value(0, 0) == "mine" }) |
| + // The peer's later edit can reach the stream before our answer is applied |
| + // (or after; a gap refetches). Either way, once ours is acknowledged the |
| + // cell shows the server's newest value. |
| + await model.accept(server.peer(0, 0, "theirs, later")) |
| + await model.settle() |
| + #expect(model.pending.isEmpty) |
| + #expect(model.displayCell(a1)?.raw == "theirs, later", "once acknowledged, the server's newest value shows") |
| +} |
| + |
| +@MainActor @Test func editAgainWhileInFlightKeepsTheNewestValue() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "first") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + type(model, a1, "second") |
| + server.release() |
| + // The first answer resolves only the first edit; "second" stays on screen. |
| + #expect(await eventually { server.heldCount == 1 }) |
| + #expect(model.displayCell(a1)?.raw == "second") |
| + #expect(model.editState(a1) == .sending) |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(model.cells[a1]?.raw == "second") |
| + #expect(model.pending.isEmpty) |
| +} |
| + |
| +@MainActor @Test func pastedAndFilledCellsAreOptimisticToo() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "=B1") |
| + model.select(a1) |
| + model.selection = CellRange(a1, a3) |
| + await model.fill(down: true) |
| + #expect(model.displayCell(a3)?.raw == "=B1") |
| + #expect(model.rawAt(a2) == "=B1") |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(model.pending.isEmpty) |
| +} |
| + |
| +@MainActor @Test func undoWaitsForEditsOnTheirWay() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "x") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + let undo = Task { await model.command("/undo") } |
| + try? await Task.sleep(for: .milliseconds(30)) |
| + #expect(!server.requests.contains { $0.hasSuffix("/undo") }, "undo went ahead of an edit still on its way") |
| + server.release(stopHolding: true) |
| + _ = await undo.value |
| + #expect(model.pending.isEmpty) |
| + let order = server.requests.filter { $0.hasSuffix("/undo") || $0.hasSuffix("/cells/batch") } |
| + #expect(order.last?.hasSuffix("/undo") == true, "\(order)") |
| +} |
| + |
| +// Review #72, finding 1: an edit must never be sent to, or painted on, a |
| +// sheet it was not made on, and a send must never be left "sending". |
| +@MainActor @Test func anEditDuringASheetSwitchIsNotSentToEitherSheet() async { |
| + let server = SheetServerFixture() |
| + server.holdPages() |
| + let model = fixtureModel(server) |
| + let opening = Task { await model.open(SheetSummary(ID: 2, Title: "", TabID: 0, TabName: "")) } |
| + #expect(await eventually { server.requests.contains("GET /sheets/2") }) |
| + model.select(a1) |
| + model.draft = "typed mid-switch" |
| + model.commit() |
| + #expect(model.pending.isEmpty, "an edit started while the sheet is being replaced") |
| + server.releasePages() |
| + await opening.value |
| + #expect(model.page?.Sheet.ID == 2) |
| + #expect(model.displayCell(a1) == nil, "no phantom value on the new sheet") |
| + #expect(!model.hasUnconfirmedChanges, "close, quit and open would refuse for ever") |
| + #expect(server.batches.isEmpty) |
| +} |
| + |
| +@MainActor @Test func aSendForASheetNoLongerShownIsDroppedNotStuck() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + type(model, a1, "old sheet") |
| + #expect(await eventually { server.heldCount == 1 }) |
| + // The page is replaced while the send is in flight. |
| + model.page = SheetPage( |
| + Sheet: SheetSummary(ID: 2, Title: "Other", TabID: 2, TabName: "Tab"), Rows: 6, Cols: 4, Truncated: false, |
| + MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], |
| + Warned: nil) |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(model.pending.isEmpty, "left .sending for ever") |
| + #expect(model.displayCell(a1) == nil) |
| + #expect(!model.hasUnconfirmedChanges) |
| +} |
| + |
| +// Review #72, finding 3: "Saved" only once nothing is left to send, and the |
| +// system is asked to let edits on their way land. |
| +@MainActor @Test func statusSaysSavingWhileEditsAreOnTheirWay() async { |
| + let server = SheetServerFixture() |
| + server.hold() |
| + let model = fixtureModel(server) |
| + var held = 0 |
| + var released = 0 |
| + model.keepAliveWhileSending = { |
| + held += 1 |
| + return { released += 1 } |
| + } |
| + model.notice = "Saved" |
| + type(model, a1, "1") |
| + #expect(model.saveStatus == "Saving…") |
| + #expect(held == 1 && released == 0) |
| + #expect(await eventually { server.heldCount == 1 }) |
| + type(model, a2, "2") |
| + server.release() |
| + #expect(await eventually { server.heldCount == 1 }) |
| + #expect(model.saveStatus == "Saving…", "the first answer is not the last") |
| + server.release(stopHolding: true) |
| + await model.settle() |
| + #expect(model.saveStatus == "Saved") |
| + #expect(held == released && held >= 1, "every hold on the system was let go") |
| +} |
| + |
| +// Review #72, finding 5: an ended session is renewed in the background; edits |
| +// wait for it and go again by themselves, and are not marked as refused. |
| +@MainActor @Test func anEndedSessionHoldsTheQueueAndResends() async { |
| + let server = SheetServerFixture() |
| + server.unauthorizeNext(2) |
| + let model = fixtureModel(server) |
| + model.sessionRetryDelays = [.milliseconds(20), .milliseconds(20), .milliseconds(20)] |
| + type(model, a1, "first") |
| + type(model, a2, "second") |
| + #expect(!model.hasFailedEdits) |
| + await model.settle() |
| + #expect(!model.hasFailedEdits, "a renewal is not a refusal") |
| + #expect(model.pending.isEmpty) |
| + #expect(server.value(0, 0) == "first") |
| + #expect(server.value(1, 0) == "second") |
| +} |
| + |
| +@MainActor @Test func aSessionThatNeverReturnsIsMarkedInTheEnd() async { |
| + let server = SheetServerFixture() |
| + server.unauthorizeNext(10) |
| + let model = fixtureModel(server) |
| + model.sessionRetryDelays = [.milliseconds(10), .milliseconds(10)] |
| + type(model, a1, "x") |
| + await model.settle() |
| + #expect(model.editState(a1) == .failed) |
| + #expect(server.batches.count == 3) |
| +} |
| + |
| +// Review #72, finding 8: an edit whose answer was lost may have landed. |
| +@MainActor @Test func aFailedEditTheServerHoldsIsSavedAfterAll() async { |
| + let server = SheetServerFixture() |
| + server.loseNextResponse() |
| + let model = fixtureModel(server) |
| + type(model, a1, "landed") |
| + await model.settle() |
| + #expect(model.editState(a1) == .failed) |
| + #expect(server.value(0, 0) == "landed", "the server applied it; only the answer was lost") |
| + // The live stream delivers the cell, as it does every edit. |
| + await model.accept(GridResponse(version: server.version, cells: [Cell(r: 0, c: 0, raw: "landed", display: "landed")], stamps: 1)) |
| + #expect(model.pending.isEmpty, "no longer marked as not saved") |
| + #expect(model.displayCell(a1)?.raw == "landed") |
| +} |
| + |
| +@MainActor @Test func revertReadsTheServerBackInCaseTheEditLanded() async { |
| + let server = SheetServerFixture() |
| + server.loseNextResponse() |
| + let model = fixtureModel(server) |
| + type(model, a1, "landed") |
| + await model.settle() |
| + #expect(model.editState(a1) == .failed) |
| + model.revertWrites([a1]) |
| + #expect(await eventually { model.cells[a1]?.raw == "landed" }, "the server's value, not the one from before the edit") |
| + #expect(model.displayCell(a1)?.raw == "landed") |
| +} |
| + |
| +// Review #72 delta, finding 3: never "Saved" beside an edit that was not. |
| +@MainActor @Test func statusNeverSaysSavedBesideAFailedEdit() async { |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server) |
| + type(model, a1, "ok") |
| + await model.settle() |
| + #expect(model.saveStatus == "Saved") |
| + server.refuseNext() |
| + type(model, a2, "refused") |
| + await model.settle() |
| + #expect(model.saveStatus == "Not saved") |
| + model.retryWrites() |
| + await model.settle() |
| + #expect(model.saveStatus == "Saved") |
| +} |
| + |
| +// Review #72 delta, finding 4: a clear whose answer was lost, and landed. |
| +@MainActor @Test func aLostClearThatLandedIsSavedAfterAll() async { |
| + let server = SheetServerFixture() |
| + let model = fixtureModel(server) |
| + type(model, a1, "x") |
| + await model.settle() |
| + server.loseNextResponse() |
| + model.select(a1) |
| + await model.clear() |
| + await model.settle() |
| + #expect(model.editState(a1) == .failed) |
| + #expect(server.value(0, 0) == nil, "the server cleared it; only the answer was lost") |
| + await model.refresh() |
| + #expect(model.pending.isEmpty, "the server no longer has the cell: the clear landed") |
| +} |
| + |
| +// Review #72 delta, finding 2: Close and Quit do not wait out a session hold. |
| +@MainActor @Test func closingCutsASessionHoldShort() async { |
| + let server = SheetServerFixture() |
| + server.unauthorizeNext(100) |
| + let model = fixtureModel(server) |
| + model.sessionRetryDelays = [.seconds(30), .seconds(30)] |
| + type(model, a1, "x") |
| + #expect(await eventually { server.batches.count == 1 }) |
| + let start = ProcessInfo.processInfo.systemUptime |
| + await model.settle(hurry: true) |
| + #expect(ProcessInfo.processInfo.systemUptime - start < 1, "Close waited out the renewal") |
| + #expect(model.editState(a1) == .failed, "so the window can ask about it") |
| + // A later edit holds for a renewal again. |
| + server.unauthorizeNext(1) |
| + model.sessionRetryDelays = [.milliseconds(10)] |
| + model.retryWrites() |
| + await model.settle() |
| + #expect(model.pending.isEmpty) |
| +} |
diff --git a/native/apple/Tests/SheetsKitTests/SheetNativeInteractionTests.swift b/native/apple/Tests/SheetsKitTests/SheetNativeInteractionTests.swift| index 8ff1ddd..759c994 100644 |
| --- a/native/apple/Tests/SheetsKitTests/SheetNativeInteractionTests.swift |
| +++ b/native/apple/Tests/SheetsKitTests/SheetNativeInteractionTests.swift |
| @@ -6,7 +6,7 @@ import RastrilloApple |
| @testable import SheetsKit |
| final class SheetNativeInteractionTests: XCTestCase { |
| - @MainActor func testTypingEntersCellAndFailedCommitKeepsDraft() async throws { |
| + @MainActor func testTypingEntersCellAndFailedCommitIsMarkedNotBlocking() async throws { |
| let model = SheetModel(client: NativeHTTP(origin: URL(string: "http://127.0.0.1:1")!)) |
| model.page = SheetPage(Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: 4, Cols: 3, Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], NumberFormats: [], Warned: nil) |
| let host = NSHostingView(rootView: SheetGrid(model: model).background(Color.white).preferredColorScheme(.light)) |
| @@ -36,17 +36,24 @@ final class SheetNativeInteractionTests: XCTestCase { |
| host.cacheDisplay(in: host.bounds, to: bitmap) |
| try bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: "/tmp/oficina-sheets-grid-fixture.png")) |
| } |
| + // The server is unreachable. Tab still commits at once and moves on; |
| + // the failure marks A1 and blocks nothing. |
| key("\t", code: 48, window: window) |
| try await Task.sleep(for: .milliseconds(500)) |
| - XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 0)) |
| - XCTAssertEqual(model.draft, "he") |
| - XCTAssertTrue(model.hasUnconfirmedChanges) |
| - XCTAssertFalse(model.failedWrites.isEmpty) |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 1)) |
| + XCTAssertEqual(model.displayCell(Coordinate(r: 0, c: 0))?.display, "he") |
| + XCTAssertEqual(model.editState(Coordinate(r: 0, c: 0)), .failed) |
| + XCTAssertFalse(model.dirty) |
| + key("x", code: 7, window: window) |
| + try await Task.sleep(for: .milliseconds(150)) |
| + XCTAssertEqual(model.draft, "x", "a failed edit elsewhere must not stop typing") |
| XCTAssertTrue(window.firstResponder is NSTextView) |
| key("\u{1b}", code: 53, window: window) |
| try await Task.sleep(for: .milliseconds(100)) |
| + XCTAssertFalse(model.dirty) |
| + XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 1)) |
| + model.revertWrites() |
| XCTAssertFalse(model.hasUnconfirmedChanges) |
| - XCTAssertEqual(model.selection.start, Coordinate(r: 0, c: 0)) |
| // Column B header then row 2 header select complete ranges. |
| click(NSPoint(x: 200, y: 375), window: window) |
| try await Task.sleep(for: .milliseconds(100)) |
| @@ -151,9 +158,10 @@ final class SheetNativeInteractionTests: XCTestCase { |
| window.sendEvent(event) |
| } |
| } |
| + /// Through NSApp, as the system delivers it, so local monitors see it. |
| @MainActor private func key(_ text: String, code: UInt16, window: NSWindow) { |
| let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text, charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)! |
| - window.sendEvent(event) |
| + NSApp.sendEvent(event) |
| } |
| } |
| #endif |
diff --git a/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift b/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift| new file mode 100644 |
| index 0000000..8476bef |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift |
| @@ -0,0 +1,161 @@ |
| +import Foundation |
| +import RastrilloApple |
| +@testable import SheetsKit |
| + |
| +/// An in-process Sheets server for value edits: it applies each batch, moves |
| +/// the version by one per cell (as the real server's stamps do), and can hold |
| +/// a send until the test releases it, or refuse the next few. |
| +final class SheetServerFixture: NativeTransport, @unchecked Sendable { |
| + struct Sent: Equatable, Sendable { |
| + let r: Int |
| + let c: Int |
| + let raw: String |
| + } |
| + let origin = URL(string: "https://sheets-fixture.invalid")! |
| + private let lock = NSLock() |
| + private var holding = false |
| + private var waiting: [CheckedContinuation<Void, Never>] = [] |
| + private var refusals = 0 |
| + private var unauthorized = 0 |
| + private var losses = 0 |
| + private var holdingPages = false |
| + private var waitingPages: [CheckedContinuation<Void, Never>] = [] |
| + private var stamp: UInt64 = 0 |
| + private var sent: [[Sent]] = [] |
| + private var requested: [String] = [] |
| + /// Every request's method and path, in order. |
| + var requests: [String] { lock.withLock { requested } } |
| + private var cells: [Coordinate: String] = [:] |
| + /// Every batch the server received, in order, refused ones included. |
| + var batches: [[Sent]] { lock.withLock { sent } } |
| + var heldCount: Int { lock.withLock { waiting.count } } |
| + var version: UInt64 { lock.withLock { stamp } } |
| + func value(_ r: Int, _ c: Int) -> String? { lock.withLock { cells[Coordinate(r: r, c: c)] } } |
| + |
| + /// From now on, each batch waits for `release()`. |
| + func hold() { lock.withLock { holding = true } } |
| + /// Lets the oldest waiting batch through; `stopHolding` lets every later one through too. |
| + func release(stopHolding: Bool = false) { |
| + let next: CheckedContinuation<Void, Never>? = lock.withLock { |
| + if stopHolding { holding = false } |
| + return waiting.isEmpty ? nil : waiting.removeFirst() |
| + } |
| + next?.resume() |
| + } |
| + func refuseNext(_ count: Int = 1) { lock.withLock { refusals = count } } |
| + /// The next batches meet an ended session: 401, applied nowhere. |
| + func unauthorizeNext(_ count: Int = 1) { lock.withLock { unauthorized = count } } |
| + /// The next batch is applied, then its answer is lost on the way back. |
| + func loseNextResponse() { lock.withLock { losses = 1 } } |
| + /// Opening a sheet (GET /sheets/<id>) waits for `releasePages`. |
| + func holdPages() { lock.withLock { holdingPages = true } } |
| + func releasePages() { |
| + let all: [CheckedContinuation<Void, Never>] = lock.withLock { |
| + holdingPages = false |
| + defer { waitingPages = [] } |
| + return waitingPages |
| + } |
| + all.forEach { $0.resume() } |
| + } |
| + |
| + static func display(_ raw: String) -> String { raw.hasPrefix("=") ? "computed" : raw } |
| + |
| + /// Another person's edit, as the live stream would deliver it. |
| + func peer(_ r: Int, _ c: Int, _ raw: String) -> GridResponse { |
| + lock.withLock { |
| + stamp += 1 |
| + cells[Coordinate(r: r, c: c)] = raw |
| + return GridResponse( |
| + version: stamp, cells: [Cell(r: r, c: c, raw: raw, display: Self.display(raw))], stamps: 1) |
| + } |
| + } |
| + |
| + func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws |
| + -> NativeResponse |
| + { |
| + lock.withLock { requested.append(method + " " + (path.split(separator: "?").first.map(String.init) ?? path)) } |
| + if method == "GET", path.hasPrefix("/sheets/"), let id = UInt64(path.dropFirst("/sheets/".count)) { |
| + await withCheckedContinuation { continuation in |
| + let wait = lock.withLock { () -> Bool in |
| + if holdingPages { waitingPages.append(continuation) } |
| + return holdingPages |
| + } |
| + if !wait { continuation.resume() } |
| + } |
| + let page = #"{"Sheet":{"ID":\#(id),"Title":"Sheet \#(id)","TabID":\#(id),"TabName":"Tab"},"Rows":6,"Cols":4,"Truncated":false,"MayWrite":true,"MayComment":true,"MayShare":false,"FillSwatches":[],"InkSwatches":[],"NumberFormats":[]}"# |
| + return NativeResponse(data: Data(page.utf8), status: 200) |
| + } |
| + if method == "GET", path.contains("/cells?") { |
| + // A snapshot, as a refetch after a version gap reads it. |
| + return lock.withLock { |
| + let all = cells.map { |
| + #"{"r":\#($0.key.r),"c":\#($0.key.c),"raw":"\#($0.value)","display":"\#(Self.display($0.value))"}"# |
| + }.joined(separator: ",") |
| + return NativeResponse(data: Data(#"{"version":\#(stamp + 1),"cells":[\#(all)]}"#.utf8), status: 200) |
| + } |
| + } |
| + guard method == "POST", path.hasSuffix("/cells/batch"), let body else { |
| + return NativeResponse(data: Data(), status: 404) |
| + } |
| + struct Batch: Decodable { let cells: [Wire] } |
| + struct Wire: Decodable { let r: Int; let c: Int; let raw: String } |
| + let batch = try JSONDecoder().decode(Batch.self, from: body).cells.map { Sent(r: $0.r, c: $0.c, raw: $0.raw) } |
| + await withCheckedContinuation { continuation in |
| + let wait = lock.withLock { () -> Bool in |
| + sent.append(batch) |
| + if holding { waiting.append(continuation) } |
| + return holding |
| + } |
| + if !wait { continuation.resume() } |
| + } |
| + let outcome = lock.withLock { () -> NativeResponse? in |
| + if unauthorized > 0 { |
| + unauthorized -= 1 |
| + return NativeResponse(data: Data(), status: 401) |
| + } |
| + if refusals > 0 { |
| + refusals -= 1 |
| + return NativeResponse(data: Data(), status: 503) |
| + } |
| + stamp += UInt64(batch.count) |
| + // A cleared cell is deleted, as the real server deletes it. |
| + for cell in batch { cells[Coordinate(r: cell.r, c: cell.c)] = cell.raw.isEmpty ? nil : cell.raw } |
| + let changed = batch.map { |
| + #"{"r":\#($0.r),"c":\#($0.c),"raw":"\#($0.raw)","display":"\#(Self.display($0.raw))"}"# |
| + }.joined(separator: ",") |
| + if losses > 0 { |
| + losses -= 1 |
| + return nil |
| + } |
| + return NativeResponse( |
| + data: Data(#"{"version":\#(stamp),"stamps":\#(batch.count),"cells":[\#(changed)]}"#.utf8), status: 200) |
| + } |
| + guard let outcome else { throw NativeClientError.offline(.networkConnectionLost) } |
| + return outcome |
| + } |
| + func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) |
| + async throws |
| + { |
| + try await Task.sleep(for: .seconds(3600)) |
| + } |
| + func download(_ path: String, to destination: URL) async throws {} |
| +} |
| + |
| +@MainActor func fixtureModel(_ server: SheetServerFixture, rows: Int = 6, cols: Int = 4) -> SheetModel { |
| + let model = SheetModel(client: server) |
| + model.page = SheetPage( |
| + Sheet: SheetSummary(ID: 1, Title: "Fixture", TabID: 1, TabName: "Sheet 1"), Rows: rows, Cols: cols, |
| + Truncated: false, MayWrite: true, MayComment: true, MayShare: false, FillSwatches: [], InkSwatches: [], |
| + NumberFormats: [], Warned: nil) |
| + return model |
| +} |
| + |
| +/// Polls the main actor until `condition` holds or `seconds` pass. |
| +@MainActor func eventually(_ seconds: Double = 2, _ condition: () -> Bool) async -> Bool { |
| + let deadline = ProcessInfo.processInfo.systemUptime + seconds |
| + while !condition() { |
| + if ProcessInfo.processInfo.systemUptime > deadline { return false } |
| + try? await Task.sleep(for: .milliseconds(2)) |
| + } |
| + return true |
| +} |
diff --git a/native/ios/UITests/NativeUITests.swift b/native/ios/UITests/NativeUITests.swift| index 9c1bfb6..b3acbbe 100644 |
| --- a/native/ios/UITests/NativeUITests.swift |
| +++ b/native/ios/UITests/NativeUITests.swift |
| @@ -73,6 +73,8 @@ import XCTest |
| field.typeText(reference + "\n") |
| } |
| + // Edits are optimistic (2026-11-26): a refused one keeps its value on |
| + // its cell, marked, offers Retry, and blocks nothing else. |
| func testFailedCellEditCanBeRetriedWithoutLosingDraft() { |
| continueAfterFailure = false |
| let app = XCUIApplication() |
| @@ -86,12 +88,13 @@ import XCTest |
| // Only this exact synthetic input triggers one refusal in the fixture. |
| formula.typeText("=6*7") |
| app.buttons["Save"].tap() |
| - let retry = app.buttons["Retry pending edits"] |
| + // "Retry" reads "Try again" in English (Mac.strings). |
| + let retry = app.buttons["Try again"] |
| XCTAssertTrue(retry.waitForExistence(timeout: 10)) |
| - XCTAssertEqual(formula.value as? String, "=6*7") |
| - XCTAssertFalse(formula.isEnabled) |
| + XCTAssertTrue(app.buttons["A1, =6*7"].exists, "the refused value stays on its cell") |
| + XCTAssertTrue(formula.isEnabled, "a refused edit must not lock the formula bar") |
| app.buttons["A2, Empty"].tap() |
| - XCTAssertEqual(app.textFields["Cell or range, for example A1:B5"].value as? String, "A1") |
| + XCTAssertEqual(app.textFields["Cell or range, for example A1:B5"].value as? String, "A2") |
| retry.tap() |
| XCTAssertTrue(app.buttons["A1, 42"].waitForExistence(timeout: 10)) |
| XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: retry)], timeout: 10), .completed) |