Sheets native: optimistic cell edits, and the first keystroke types
Paul, 2026-11-26: typing on a selected cell lost its first character, and committing a cell greyed it for a round trip. Root cause, both: a value write was synchronous. The cell's field was disabled while it waited (the grey), the disabled field dropped keyboard focus to the window, and keys typed in that gap reached no responder. Separately the grid read keys as characters, so a dead key (no characters yet) or an input method never got the first keystroke. - SheetWrites: edits are recorded as pending and painted at once; one send per document in flight, edits made meanwhile coalesce into the next. The display rule: a queued or sending local value wins over a peer update of the same cell; once acknowledged the server's newest value shows; a failed edit keeps its value, marked, with Retry and Revert, and blocks nothing. Undo and other commands wait for edits on their way. - SheetTypeAhead (Mac): a local key monitor holds the raw event that starts typing, opens the cell's field, and replays held events into its field editor once focused, so dead keys and input methods compose from the first key. Return/F2/double-click keep the contents; typing replaces. Commit releases the keyboard at once so the next key starts the next cell. - Return to committed look: 172 ms median at 150 ms latency, grey throughout (main 26d271a) -> 17 ms with the server not answering. - New strings in all 12 languages.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
35 files changed,
+1,113
−176
native/README.md+14 −6native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/Resources/zh-Hans.lproj/Mac.strings+4 −0native/apple/Sources/SheetsKit/SheetAutoSize.swift+1 −1native/apple/Sources/SheetsKit/SheetCell.swift+40 −13native/apple/Sources/SheetsKit/SheetCellEditor.swift+15 −4native/apple/Sources/SheetsKit/SheetClipboard.swift+9 −9native/apple/Sources/SheetsKit/SheetCloseGuard.swift+24 −1native/apple/Sources/SheetsKit/SheetEditingControls.swift+21 −4native/apple/Sources/SheetsKit/SheetFiles.swift+2 −1native/apple/Sources/SheetsKit/SheetFormatMenu.swift+1 −1native/apple/Sources/SheetsKit/SheetGrid.swift+74 −28native/apple/Sources/SheetsKit/SheetModel.swift+44 −25native/apple/Sources/SheetsKit/SheetTable.swift+2 −2native/apple/Sources/SheetsKit/SheetTypeAhead.swift+112 −0native/apple/Sources/SheetsKit/SheetWire.swift+1 −1native/apple/Sources/SheetsKit/SheetWrites.swift+139 −38native/apple/Sources/SheetsKit/SheetsDocumentMenu.swift+1 −1native/apple/Sources/SheetsKit/SheetsEditorCommands.swift+2 −2native/apple/Sources/SheetsKit/SheetsWorkspace.swift+7 −15native/apple/Tests/SheetsKitTests/EditingTests.swift+0 −17native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift+214 −0native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift+207 −0native/apple/Tests/SheetsKitTests/SheetNativeInteractionTests.swift+15 −7native/apple/Tests/SheetsKitTests/SheetServerFixture.swift+120 −0
diff --git a/native/README.md b/native/README.md| index f7308fe..ce37b06 100644 |
| --- a/native/README.md |
| +++ b/native/README.md |
| @@ -61,18 +61,26 @@ 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. 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..21637c1 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ar.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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." = "لم تُحفظ بعض تعديلات الخلايا."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings| index ca17400..b2cb2b0 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/bn.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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." = "কিছু ঘরের সম্পাদনা সংরক্ষিত হয়নি।"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings| index d59b41c..a867788 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/en.lproj/Mac.strings |
| @@ -75,3 +75,7 @@ |
| "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."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings| index 2e6bfe4..ff7095d 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/es.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings| index fe98308..69ed293 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ga.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings| index 515afae..35d95cf 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/hi.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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." = "कुछ सेल के बदलाव सहेजे नहीं गए।"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings| index b4493eb..ebff5b3 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ja.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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." = "一部のセルの変更が保存されませんでした。"; |
diff --git a/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings| index 6faffe4..c4e9a52 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/pt.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings| index a32025d..8ab7b5f 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/ru.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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." = "Некоторые изменения ячеек не сохранены."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings| index 5dffed0..4cc5dd7 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/vi.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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."; |
diff --git a/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings b/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings| index 2b63666..e1b1112 100644 |
| --- a/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings |
| +++ b/native/apple/Sources/SheetsKit/Resources/yue.lproj/Mac.strings |
| @@ -74,3 +74,7 @@ |
| "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." = "有啲儲存格嘅修改未儲存到。"; |
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..a8ab488 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,7 @@ |
| "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." = "部分单元格修改未保存。"; |
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..a3d04ce 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetCell.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetCell.swift |
| @@ -9,11 +9,14 @@ struct SheetCell: View { |
| var endEditing: () -> Void |
| var columnWidth: Double? = nil |
| var rowHeight: Double? = nil |
| + #if os(macOS) |
| + var typeAhead: SheetTypeAhead? = nil |
| + #endif |
| @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" |
| @@ -21,11 +24,13 @@ struct SheetCell: View { |
| return Group { |
| #if os(macOS) |
| if editing == point { |
| - SheetCellEditor(text: $model.draft, enabled: model.mayWrite && !model.busy, |
| + // 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(right: $0) }, cancel: { |
| - guard !model.busy else { return } |
| - model.discardAll(); endEditing() |
| + model.discard(); endEditing() |
| }) |
| .padding(.horizontal, 5) |
| .frame(width: width(point.c), height: height(point.r)) |
| @@ -38,15 +43,16 @@ struct SheetCell: View { |
| #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() } |
| - } |
| + private func commit(right: Bool) -> Bool { |
| + guard model.selection.start == point else { return false } |
| + model.commit(moveRight: right) |
| + guard !model.dirty else { return false } |
| + endEditing() |
| + return true |
| } |
| 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,10 +63,18 @@ 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() } }) |
| + .contextMenu { |
| + if failed { |
| + Button(sheetsMacString("Retry")) { model.retryWrites([point]) } |
| + Button(sheetsMacString("Revert"), role: .destructive) { model.revertWrites([point]) } |
| + } |
| + } |
| + .help(failed ? sheetsMacString("Not saved") : "") |
| .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 : []) |
| } |
| private func fill(_ style: CellStyle?) -> Color { |
| @@ -74,3 +88,16 @@ struct SheetCell: View { |
| return .primary |
| } |
| } |
| + |
| +/// 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) |
| + } |
| +} |
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..3b67351 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetCloseGuard.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetCloseGuard.swift |
| @@ -38,6 +38,14 @@ |
| guard model.hasUnconfirmedChanges else { |
| return previousDelegate?.windowShouldClose?(sender) ?? true |
| } |
| + if !model.dirty && !model.hasFailedEdits { |
| + // Only edits on their way: let them land, then close. |
| + Task { @MainActor in |
| + await model.settle() |
| + if !model.hasUnconfirmedChanges { 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." |
| @@ -51,6 +59,8 @@ |
| if !model.hasUnconfirmedChanges { sender.performClose(nil) } |
| } else if response == .alertSecondButtonReturn { |
| model.discardAll() |
| + await model.settle() |
| + model.revertWrites() |
| sender.performClose(nil) |
| } |
| } |
| @@ -67,6 +77,15 @@ |
| 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. One that fails stays |
| + // marked in its window, and the app stays open to say so. |
| + Task { @MainActor in |
| + for model in pending { await model.settle() } |
| + sender.reply(toApplicationShouldTerminate: !pending.contains { $0.hasUnconfirmedChanges }) |
| + } |
| + return .terminateLater |
| + } |
| let alert = NSAlert() |
| alert.messageText = "Save your spreadsheet edits before quitting?" |
| alert.addButton(withTitle: "Save") |
| @@ -81,7 +100,11 @@ |
| return .terminateLater |
| case .alertSecondButtonReturn: |
| pending.forEach { $0.discardAll() } |
| - return .terminateNow |
| + Task { @MainActor in |
| + for model in pending { await model.settle() } |
| + 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..6e8da77 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 { |
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..9a0b34f 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetGrid.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetGrid.swift |
| @@ -7,6 +7,9 @@ struct SheetGrid: View { |
| @State private var savingResize = false |
| @GestureState private var draggingResize = false |
| @FocusState private var focused: Bool |
| + #if os(macOS) |
| + @State private var typeAhead = SheetTypeAhead() |
| + #endif |
| var beginEditing: () -> Void = {} |
| var body: some View { |
| ScrollView([.horizontal, .vertical]) { |
| @@ -27,12 +30,7 @@ struct SheetGrid: View { |
| #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)) |
| + cell(row: row, col: col) |
| } |
| } |
| } |
| @@ -86,25 +84,78 @@ struct SheetGrid: View { |
| edit(model.selection.start) |
| return .handled |
| } |
| + #if os(macOS) |
| + .background { SheetKeyMonitor(handle: handleKey) } |
| + #else |
| .onKeyPress(characters: .alphanumerics.union(.punctuationCharacters).union(.symbols).union(.whitespaces)) { |
| press in |
| - guard model.mayWrite, !model.busy, !press.characters.contains(where: { $0 == "\t" || $0.isNewline }), |
| + guard model.mayWrite, !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. |
| + if model.dirty { |
| model.draft += press.characters |
| } else { |
| - guard !model.hasUnconfirmedChanges else { return .ignored } |
| model.draft = press.characters |
| edit(model.selection.start) |
| } |
| return .handled |
| } |
| + #endif |
| + } |
| + private func cell(row: Int, col: Int) -> some View { |
| + let point = Coordinate(r: row, c: col) |
| + #if os(macOS) |
| + return SheetCell( |
| + model: model, point: point, editing: $editing, |
| + select: { select(point) }, |
| + beginEditing: { edit(point) }, |
| + endEditing: { editing = nil; typeAhead.cancel(); focused = true }, |
| + columnWidth: width(col), rowHeight: height(row), typeAhead: typeAhead) |
| + #else |
| + return SheetCell( |
| + model: model, point: point, editing: $editing, |
| + select: { select(point) }, |
| + beginEditing: { edit(point) }, |
| + endEditing: { editing = nil; focused = true }, |
| + columnWidth: width(col), rowHeight: height(row)) |
| + #endif |
| } |
| + #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 || editing == nil { |
| + typeAhead.cancel() |
| + } 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 editing == nil, model.mayWrite, !model.dirty, 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. |
| + model.draft = "" |
| + typeAhead.begin(with: event) |
| + edit(model.selection.start) |
| + if editing == nil { typeAhead.cancel(); model.discard(); return false } |
| + return true |
| + } |
| + #endif |
| private func edit(_ point: Coordinate) { |
| - guard model.mayWrite, !model.busy, model.failedWrites.isEmpty else { return } |
| + guard model.mayWrite else { return } |
| #if os(macOS) |
| editing = point |
| #else |
| @@ -112,28 +163,23 @@ struct SheetGrid: View { |
| #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 editing != point { editing = nil } |
| + model.select(point) |
| + focused = true |
| } |
| private func selectRow(_ row: Int) { |
| - guard !model.hasUnconfirmedChanges, !model.busy else { return } |
| + guard !model.dirty else { return } |
| editing = nil |
| model.rangeText = "A\(row + 1):" + Coordinate(r: row, c: model.cols - 1).ref |
| model.selectRange() |
| focused = true |
| } |
| private func selectColumn(_ col: Int) { |
| - guard !model.hasUnconfirmedChanges, !model.busy else { return } |
| + guard !model.dirty else { return } |
| editing = nil |
| model.rangeText = Coordinate(r: 0, c: col).ref + ":" + Coordinate(r: model.rows - 1, c: col).ref |
| model.selectRange() |
| @@ -157,7 +203,7 @@ struct SheetGrid: View { |
| #if os(macOS) |
| private func resizeHandle(axis: String, index: Int) -> some View { |
| SheetResizeHandle(vertical: axis == "row", |
| - canBegin: { model.mayWrite && !model.busy && !model.hasUnconfirmedChanges && !savingResize }, |
| + canBegin: { model.mayWrite && !model.busy && !model.dirty && !savingResize }, |
| change: { translation in |
| if resizing == nil { |
| resizing = SheetResizePreview(axis: axis, index: index, |
| @@ -183,7 +229,7 @@ struct SheetGrid: View { |
| DragGesture(minimumDistance: 2, coordinateSpace: .global) |
| .updating($draggingResize) { _, active, _ in active = true } |
| .onChanged { value in |
| - guard model.mayWrite, !model.busy, !model.hasUnconfirmedChanges else { return } |
| + guard model.mayWrite, !model.busy, !model.dirty else { return } |
| if resizing == nil { |
| resizing = SheetResizePreview(axis: axis, index: index, |
| original: axis == "col" ? width(index) : height(index)) |
diff --git a/native/apple/Sources/SheetsKit/SheetModel.swift b/native/apple/Sources/SheetsKit/SheetModel.swift| index db3587e..ad0624e 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetModel.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetModel.swift |
| @@ -18,8 +18,12 @@ 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>? |
| + /// 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,6 +66,7 @@ import RastrilloApple |
| } |
| } |
| func open(_ sheet: SheetSummary) async { |
| + await settle() |
| guard !hasUnconfirmedChanges && !busy else { |
| error = "Save or discard your cell edit before changing sheets." |
| return |
| @@ -146,59 +151,69 @@ import RastrilloApple |
| if let sizes = response.sizes { self.sizes = sizes } |
| 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() |
| } |
| + /// Close, Quit and switching sheets: commit the edit being typed, retry the |
| + /// failed ones, and wait for the answers. |
| func saveAll() async { |
| - if !failedWrites.isEmpty { await retryWrites() } |
| - if failedWrites.isEmpty && dirty { await commit() } |
| + if dirty { commit(moveRight: nil) } |
| + retryWrites() |
| + await settle() |
| } |
| 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 +228,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 +264,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 +286,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 +334,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..02ae0d1 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) { |
diff --git a/native/apple/Sources/SheetsKit/SheetTypeAhead.swift b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift| new file mode 100644 |
| index 0000000..2b95878 |
| --- /dev/null |
| +++ b/native/apple/Sources/SheetsKit/SheetTypeAhead.swift |
| @@ -0,0 +1,112 @@ |
| +#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 |
| + |
| + /// 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 |
| + else { return false } |
| + // A dead key has no characters yet; what it will compose is still text. |
| + let text = (event.characters ?? "").isEmpty ? event.charactersIgnoringModifiers ?? "" : event.characters ?? "" |
| + guard let scalar = text.unicodeScalars.first else { return false } |
| + return !CharacterSet.controlCharacters.contains(scalar) |
| + } |
| + |
| + func begin(with event: NSEvent) { |
| + held = [event] |
| + awaitingField = true |
| + deadline = ProcessInfo.processInfo.systemUptime + 1 |
| + } |
| + func hold(_ event: NSEvent) { held.append(event) } |
| + /// A field that never came (the edit was refused) 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 |
| + 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..290574a 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetWrites.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetWrites.swift |
| @@ -1,54 +1,155 @@ |
| import Foundation |
| import RastrilloApple |
| +/// 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 } |
| 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 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) { |
| + 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. Edits still being |
| + /// sent are not touched: they may already have landed. |
| + func revertWrites(_ points: [Coordinate]? = nil) { |
| + pending = pending.filter { point, edit in |
| + edit.state != .failed || !(points?.contains(point) ?? true) |
| + } |
| + if !hasFailedEdits { error = "" } |
| + if !dirty { discard() } |
| + } |
| + |
| + /// Waits until nothing is queued or in flight. Failed edits stay failed. |
| + func settle() async { |
| + while let sender { await sender.value } |
| + } |
| + |
| + func startSending() { |
| + guard sender == nil, pending.values.contains(where: { $0.state == .queued }) else { return } |
| + sender = Task { [weak self] in |
| + await self?.sendQueued() |
| + 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 { |
| + 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) |
| + guard (200..<300).contains(status) else { |
| + throw NativeClientError.message(sheetsMacString("Not saved")) |
| + } |
| + let response = try await wire.decode(bytes) |
| + guard grid == source else { return } |
| + await accept(response) |
| + resolve(batch[offset..<(offset + chunk.count)], failed: false) |
| + offset += chunk.count |
| } |
| - let response = try await wire.decode(bytes) |
| - await accept(response) |
| - offset += count |
| + error = "" |
| + notice = "Saved" |
| + if showTable { await loadTable() } |
| + } catch { |
| + guard grid == source else { return } |
| + // 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 |
| + |
| + /// 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/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..83e2bc7 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/FirstKeystrokeTests.swift |
| @@ -0,0 +1,214 @@ |
| +#if os(macOS) |
| +import AppKit |
| +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) |
| + } |
| + |
| + @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/OptimisticEditTests.swift b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift| new file mode 100644 |
| index 0000000..5c44b24 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/OptimisticEditTests.swift |
| @@ -0,0 +1,207 @@ |
| +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)") |
| +} |
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..99719b5 |
| --- /dev/null |
| +++ b/native/apple/Tests/SheetsKitTests/SheetServerFixture.swift |
| @@ -0,0 +1,120 @@ |
| +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 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 } } |
| + |
| + 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.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) } |
| + let mustWait = lock.withLock { () -> Bool in |
| + sent.append(batch) |
| + return holding |
| + } |
| + if mustWait { |
| + await withCheckedContinuation { continuation in lock.withLock { waiting.append(continuation) } } |
| + } |
| + return lock.withLock { |
| + if refusals > 0 { |
| + refusals -= 1 |
| + return NativeResponse(data: Data(), status: 503) |
| + } |
| + stamp += UInt64(batch.count) |
| + for cell in batch { cells[Coordinate(r: cell.r, c: cell.c)] = cell.raw } |
| + let changed = batch.map { |
| + #"{"r":\#($0.r),"c":\#($0.c),"raw":"\#($0.raw)","display":"\#(Self.display($0.raw))"}"# |
| + }.joined(separator: ",") |
| + return NativeResponse( |
| + data: Data(#"{"version":\#(stamp),"stamps":\#(batch.count),"cells":[\#(changed)]}"#.utf8), status: 200) |
| + } |
| + } |
| + 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 |
| +} |