| index ed15841..a460842 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetGrid.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetGrid.swift |
| @@ -1,11 +1,18 @@ |
| import SwiftUI |
| |
| +/// The grid: state and behaviour here, layout in `SheetGridContent`. |
| +/// |
| +/// The split is for speed. Anything this view owns that changes (keyboard |
| +/// focus above all, which moves every time a cell's editor opens or closes) |
| +/// re-runs this body; if that rebuilt the rows, opening an editor on a |
| +/// 200-column sheet cost most of a second before the first key reached it. |
| +/// The content is Equatable on what it actually draws from, so a focus change |
| +/// re-renders nothing but this thin shell. |
| struct SheetGrid: View { |
| @Bindable var model: SheetModel |
| - @State private var editing: Coordinate? |
| + @State private var editState = SheetEditingState() |
| @State private var resizing: SheetResizePreview? |
| @State private var savingResize = false |
| - @GestureState private var draggingResize = false |
| @FocusState private var focused: Bool |
| @State private var scroller = SheetGridScroller() |
| #if os(macOS) |
| @@ -16,83 +23,25 @@ struct SheetGrid: View { |
| #endif |
| var beginEditing: () -> Void = {} |
| var body: some View { |
| - ScrollViewReader { proxy in |
| - ScrollView([.horizontal, .vertical]) { |
| - LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) { |
| - Section { |
| - ForEach(0..<model.rows, id: \.self) { row in |
| - HStack(spacing: 0) { |
| - ZStack(alignment: .bottom) { |
| - Button { selectRow(row) } label: { |
| - Text(String(row + 1)).frame(width: 48, height: height(row)).background(.quaternary) |
| - }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1)) |
| - #if os(macOS) |
| - resizeHandle(axis: "row", index: row).frame(width: 48, height: 8) |
| - #else |
| - Color.clear.frame(width: 48, height: 8) |
| - .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row)) |
| - .accessibilityHidden(true) |
| - #endif |
| - } |
| - ForEach(0..<model.cols, id: \.self) { col in |
| - cell(row: row, col: col).id(Coordinate(r: row, c: col)) |
| - } |
| - } |
| - .onAppear { scroller.rows.insert(row) } |
| - .onDisappear { scroller.rows.remove(row) } |
| - } |
| - } header: { |
| - HStack(spacing: 0) { |
| - Text("").frame(width: 48, height: 32) |
| - ForEach(0..<model.cols, id: \.self) { col in |
| - ZStack(alignment: .trailing) { |
| - Button { selectColumn(col) } label: { |
| - Text(Coordinate(r: 0, c: col).ref.dropLast()) |
| - .frame(width: width(col), height: 32) |
| - .contentShape(.rect) |
| - }.buttonStyle(.plain) |
| - .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast()))) |
| - #if os(macOS) |
| - resizeHandle(axis: "col", index: col).frame(width: 8, height: 32) |
| - .help(sheetsMacString("Double-click to fit column to contents")) |
| - #else |
| - Color.clear.frame(width: 8, height: 32) |
| - #endif |
| - } |
| - #if os(macOS) |
| - .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } } |
| - #endif |
| - } |
| - }.background(.regularMaterial) |
| - } |
| - } |
| - #if os(iOS) |
| - .overlay(alignment: .topLeading) { keySink } |
| - #endif |
| - }.defaultScrollAnchor(.topLeading) |
| - .onAppear { scroller.proxy = proxy } |
| - } |
| + content.equatable() |
| .accessibilityLabel("Spreadsheet grid") |
| .focusable() |
| .focusEffectDisabled() |
| .focused($focused) |
| - .background { SheetSelectionObserver(model: model, editing: $editing) } |
| + .background { SheetSelectionObserver(model: model, state: editState) } |
| .onChange(of: focused) { _, value in model.gridFocused = value } |
| .onDisappear { model.gridFocused = false; if !savingResize { resizing = nil } } |
| - .onChange(of: draggingResize) { _, active in |
| - if !active, !savingResize { resizing = nil } |
| - } |
| .onKeyPress(.leftArrow) { move(0, -1) } |
| .onKeyPress(.rightArrow) { move(0, 1) } |
| .onKeyPress(.upArrow) { move(-1, 0) } |
| .onKeyPress(.downArrow) { move(1, 0) } |
| .onKeyPress(.delete) { |
| - guard editing == nil, model.mayWrite else { return .ignored } |
| + guard editState.cell == nil, model.mayWrite else { return .ignored } |
| Task { await model.clear() } |
| return .handled |
| } |
| .onKeyPress(.return) { |
| - guard editing == nil, model.mayWrite else { return .ignored } |
| + guard editState.cell == nil, model.mayWrite else { return .ignored } |
| edit(model.selection.start) |
| return .handled |
| } |
| @@ -102,46 +51,38 @@ struct SheetGrid: View { |
| .onAppear { keyboardRequest += 1 } |
| #endif |
| } |
| - #if os(iOS) |
| - /// The keyboard's place on the selected cell (SheetKeySink). |
| - private var keySink: some View { |
| - let point = model.selection.start |
| - let x = 48 + (0..<point.c).reduce(0) { $0 + width($1) } |
| - let y = 32 + (0..<point.r).reduce(0) { $0 + height($1) } |
| - return SheetKeySink(model: model, focusRequest: keyboardRequest, move: { r, c in _ = move(r, c) }) |
| - .frame(width: width(point.c), height: height(point.r)) |
| - .offset(x: x, y: y) |
| - .allowsHitTesting(false) |
| - } |
| - #endif |
| - private func cell(row: Int, col: Int) -> some View { |
| - let point = Coordinate(r: row, c: col) |
| + private var content: SheetGridContent { |
| + var actions = SheetGridActions( |
| + select: select, edit: edit, selectRow: selectRow, selectColumn: selectColumn, |
| + endEditing: endEditing, move: { r, c in _ = move(r, c) }, |
| + canResize: { [model] in model.mayWrite && !model.busy && !model.dirty && !savingResize }, |
| + resizeChange: resizeChange, resizeFinish: finishResize, |
| + resizeCancel: { if !savingResize { resizing = nil } }) |
| + actions.beginEditing = beginEditing |
| #if os(macOS) |
| - return 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) |
| + return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing, |
| + typeAhead: typeAhead, actions: actions) |
| #else |
| - return SheetCell( |
| - model: model, point: point, editing: $editing, |
| - select: { select(point) }, |
| - beginEditing: { edit(point) }, |
| - endEditing: { editing = nil; takeKeyboard() }, |
| - columnWidth: width(col), rowHeight: height(row)) |
| + return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing, |
| + keyboardRequest: keyboardRequest, actions: actions) |
| #endif |
| } |
| + private var metrics: SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: resizing) } |
| + private func endEditing() { |
| + editState.cell = nil |
| + #if os(macOS) |
| + typeAhead.cancel() |
| + #endif |
| + takeKeyboard() |
| + } |
| #if os(macOS) |
| /// Every key event in this window, before SwiftUI sees it (SheetKeyMonitor). |
| /// Typing on a selected cell opens its field and hands the keystroke to it |
| /// whole, so a dead key or an input method composes from the first key. |
| private func handleKey(_ event: NSEvent) -> Bool { |
| if typeAhead.awaitingField { |
| - if typeAhead.expired || editing == nil { |
| - // The field never came: nothing was changed, and nothing stays open. |
| - typeAhead.cancel() |
| - editing = nil |
| + if typeAhead.expired || editState.cell == nil { |
| + fieldNeverCame() |
| } else if event.modifierFlags.intersection([.command, .control]).isEmpty { |
| typeAhead.hold(event) |
| return true |
| @@ -151,7 +92,7 @@ struct SheetGrid: View { |
| } |
| // 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, |
| + guard editState.cell == nil, model.mayWrite, !model.dirty, let window = event.window, |
| model.gridFocused || window.firstResponder === window, |
| !(window.firstResponder is NSText) |
| else { return false } |
| @@ -161,20 +102,29 @@ struct SheetGrid: View { |
| } |
| guard SheetTypeAhead.startsTyping(event) else { return false } |
| // Typing replaces the cell; Return, F2 and double-click keep it. The |
| - // cell may be scrolled out of view, where the lazy grid has no field to |
| - // open: bring it into view first. |
| + // cell may be scrolled out of view: bring it into view too. |
| let point = model.selection.start |
| - scroller.reveal(point) |
| - typeAhead.begin(with: event) { [model] in model.draft = "" } |
| + scroller.reveal(point, at: metrics.frame(point)) |
| + typeAhead.begin(with: event, replace: { [model] in model.draft = "" }, expired: fieldNeverCame) |
| edit(point) |
| - if editing == nil { typeAhead.cancel(); return false } |
| + if editState.cell == nil { typeAhead.cancel(); return false } |
| return true |
| } |
| + /// The cell's field did not come up in time. Nothing typed is dropped: the |
| + /// held text goes to the formula bar, where the edit carries on. |
| + private func fieldNeverCame() { |
| + let text = typeAhead.heldText |
| + typeAhead.cancel() |
| + editState.cell = nil |
| + guard !text.isEmpty else { return } |
| + model.draft = text |
| + beginEditing() |
| + } |
| #endif |
| private func edit(_ point: Coordinate) { |
| guard model.mayWrite else { return } |
| #if os(macOS) |
| - editing = point |
| + editState.cell = point |
| #else |
| beginEditing() |
| #endif |
| @@ -184,7 +134,7 @@ struct SheetGrid: View { |
| // 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 } |
| + if editState.cell != point { editState.cell = nil } |
| model.select(point) |
| takeKeyboard() |
| } |
| @@ -197,50 +147,34 @@ struct SheetGrid: View { |
| } |
| private func selectRow(_ row: Int) { |
| guard !model.dirty else { return } |
| - editing = nil |
| + editState.cell = nil |
| model.rangeText = "A\(row + 1):" + Coordinate(r: row, c: model.cols - 1).ref |
| model.selectRange() |
| takeKeyboard() |
| } |
| private func selectColumn(_ col: Int) { |
| guard !model.dirty else { return } |
| - editing = nil |
| + editState.cell = nil |
| model.rangeText = Coordinate(r: 0, c: col).ref + ":" + Coordinate(r: model.rows - 1, c: col).ref |
| model.selectRange() |
| takeKeyboard() |
| } |
| private func move(_ r: Int, _ c: Int) -> KeyPress.Result { |
| - guard editing == nil else { return .ignored } |
| + guard editState.cell == nil else { return .ignored } |
| let p = model.selection.start |
| let next = Coordinate(r: max(0, min(model.rows - 1, p.r + r)), c: max(0, min(model.cols - 1, p.c + c))) |
| model.select(next) |
| - scroller.reveal(next) |
| + scroller.reveal(next, at: metrics.frame(next)) |
| return .handled |
| } |
| - private func width(_ col: Int) -> Double { |
| - if let resizing, resizing.axis == "col", resizing.index == col { return resizing.size } |
| - return model.sizes.cols?[String(col)] ?? 110 |
| - } |
| - private func height(_ row: Int) -> Double { |
| - if let resizing, resizing.axis == "row", resizing.index == row { return resizing.size } |
| - return model.sizes.rows?[String(row)] ?? 32 |
| - } |
| - #if os(macOS) |
| - private func resizeHandle(axis: String, index: Int) -> some View { |
| - SheetResizeHandle(vertical: axis == "row", |
| - canBegin: { model.mayWrite && !model.busy && !model.dirty && !savingResize }, |
| - change: { translation in |
| - if resizing == nil { |
| - resizing = SheetResizePreview(axis: axis, index: index, |
| - original: axis == "col" ? width(index) : height(index)) |
| - } |
| - resizing?.update(translation: translation) |
| - }, finish: { finishResize(axis: axis, index: index) }, |
| - cancel: { if !savingResize { resizing = nil } }, |
| - fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil) |
| - |
| + private func resizeChange(axis: String, index: Int, translation: Double) { |
| + if resizing == nil { |
| + resizing = SheetResizePreview(axis: axis, index: index, |
| + original: axis == "col" ? metrics.width(index) : metrics.height(index)) |
| + } |
| + guard resizing?.axis == axis, resizing?.index == index else { return } |
| + resizing?.update(translation: translation) |
| } |
| - #endif |
| private func finishResize(axis: String, index: Int) { |
| guard let preview = resizing, preview.axis == axis, preview.index == index else { return } |
| savingResize = true |
| @@ -250,19 +184,179 @@ struct SheetGrid: View { |
| savingResize = false |
| } |
| } |
| +} |
| + |
| +/// What the grid's layout may ask of the grid. |
| +struct SheetGridActions { |
| + var select: (Coordinate) -> Void |
| + var edit: (Coordinate) -> Void |
| + var selectRow: (Int) -> Void |
| + var selectColumn: (Int) -> Void |
| + var endEditing: () -> Void |
| + var move: (Int, Int) -> Void |
| + var canResize: () -> Bool |
| + var resizeChange: (_ axis: String, _ index: Int, _ translation: Double) -> Void |
| + var resizeFinish: (_ axis: String, _ index: Int) -> Void |
| + var resizeCancel: () -> Void |
| + var beginEditing: () -> Void = {} |
| +} |
| + |
| +/// Column widths and row heights, with a resize in progress applied. |
| +struct SheetGridMetrics { |
| + let sizes: Sizes |
| + let resizing: SheetResizePreview? |
| + func width(_ col: Int) -> Double { |
| + if let resizing, resizing.axis == "col", resizing.index == col { return resizing.size } |
| + return sizes.cols?[String(col)] ?? 110 |
| + } |
| + func height(_ row: Int) -> Double { |
| + if let resizing, resizing.axis == "row", resizing.index == row { return resizing.size } |
| + return sizes.rows?[String(row)] ?? 32 |
| + } |
| + /// Where a cell sits in the grid's content: after the row header and the |
| + /// pinned column header. |
| + func frame(_ point: Coordinate) -> CGRect { |
| + CGRect( |
| + x: 48 + (0..<point.c).reduce(0) { $0 + width($1) }, |
| + y: 32 + (0..<point.r).reduce(0) { $0 + height($1) }, |
| + width: width(point.c), height: height(point.r)) |
| + } |
| +} |
| + |
| +/// The grid's rows, headers and floating editor. Equatable on what it draws |
| +/// from (the model's observed properties are tracked by SwiftUI as usual), so |
| +/// the grid's own focus and key state never rebuild it (see SheetGrid). |
| +struct SheetGridContent: View, Equatable { |
| + @Bindable var model: SheetModel |
| + let editState: SheetEditingState |
| + let scroller: SheetGridScroller |
| + let resizing: SheetResizePreview? |
| + #if os(macOS) |
| + let typeAhead: SheetTypeAhead |
| + #else |
| + let keyboardRequest: Int |
| + #endif |
| + let actions: SheetGridActions |
| + @GestureState private var draggingResize = false |
| + |
| + nonisolated static func == (a: Self, b: Self) -> Bool { |
| + MainActor.assumeIsolated { |
| + #if os(macOS) |
| + let same = a.typeAhead === b.typeAhead |
| + #else |
| + let same = a.keyboardRequest == b.keyboardRequest |
| + #endif |
| + return same && a.model === b.model && a.editState === b.editState && a.scroller === b.scroller |
| + && a.resizing == b.resizing |
| + } |
| + } |
| + private var metrics: SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: resizing) } |
| + private func width(_ col: Int) -> Double { metrics.width(col) } |
| + private func height(_ row: Int) -> Double { metrics.height(row) } |
| + |
| + var body: some View { |
| + ScrollViewReader { proxy in |
| + ScrollView([.horizontal, .vertical]) { |
| + LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) { |
| + Section { |
| + ForEach(0..<model.rows, id: \.self) { row in |
| + LazyHStack(spacing: 0) { |
| + ZStack(alignment: .bottom) { |
| + Button { actions.selectRow(row) } label: { |
| + Text(String(row + 1)).frame(width: 48, height: height(row)).background(.quaternary) |
| + }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1)) |
| + #if os(macOS) |
| + resizeHandle(axis: "row", index: row).frame(width: 48, height: 8) |
| + #else |
| + Color.clear.frame(width: 48, height: 8) |
| + .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row)) |
| + .accessibilityHidden(true) |
| + #endif |
| + } |
| + ForEach(0..<model.cols, id: \.self) { col in |
| + cell(row: row, col: col).id(Coordinate(r: row, c: col)) |
| + } |
| + } |
| + .onAppear { scroller.rows.insert(row) } |
| + .onDisappear { scroller.rows.remove(row) } |
| + } |
| + } header: { |
| + LazyHStack(spacing: 0) { |
| + Text("").frame(width: 48, height: 32) |
| + ForEach(0..<model.cols, id: \.self) { col in |
| + ZStack(alignment: .trailing) { |
| + Button { actions.selectColumn(col) } label: { |
| + Text(Coordinate(r: 0, c: col).ref.dropLast()) |
| + .frame(width: width(col), height: 32) |
| + .contentShape(.rect) |
| + }.buttonStyle(.plain) |
| + .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast()))) |
| + #if os(macOS) |
| + resizeHandle(axis: "col", index: col).frame(width: 8, height: 32) |
| + .help(sheetsMacString("Double-click to fit column to contents")) |
| + #else |
| + Color.clear.frame(width: 8, height: 32) |
| + #endif |
| + } |
| + #if os(macOS) |
| + .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } } |
| + #endif |
| + } |
| + }.background(.regularMaterial) |
| + } |
| + } |
| + #if os(iOS) |
| + .overlay(alignment: .topLeading) { keySink } |
| + #else |
| + .overlay(alignment: .topLeading) { |
| + SheetEditorOverlay(model: model, state: editState, typeAhead: typeAhead, |
| + frame: metrics.frame, end: actions.endEditing) |
| + } |
| + #endif |
| + }.defaultScrollAnchor(.topLeading) |
| + .onAppear { scroller.proxy = proxy } |
| + .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in scroller.visible = rect } |
| + } |
| + .onChange(of: draggingResize) { _, active in |
| + if !active { actions.resizeCancel() } |
| + } |
| + } |
| + #if os(iOS) |
| + /// The keyboard's place on the selected cell (SheetKeySink). |
| + private var keySink: some View { |
| + let box = metrics.frame(model.selection.start) |
| + return SheetKeySink(model: model, focusRequest: keyboardRequest, move: actions.move) |
| + .frame(width: box.width, height: box.height) |
| + .offset(x: box.minX, y: box.minY) |
| + .allowsHitTesting(false) |
| + } |
| + #endif |
| + private func cell(row: Int, col: Int) -> some View { |
| + let point = Coordinate(r: row, c: col) |
| + return SheetCell( |
| + model: model, point: point, |
| + select: { actions.select(point) }, |
| + beginEditing: { actions.edit(point) }, |
| + columnWidth: width(col), rowHeight: height(row)) |
| + } |
| + #if os(macOS) |
| + private func resizeHandle(axis: String, index: Int) -> some View { |
| + SheetResizeHandle(vertical: axis == "row", |
| + canBegin: actions.canResize, |
| + change: { translation in actions.resizeChange(axis, index, translation) }, |
| + finish: { actions.resizeFinish(axis, index) }, |
| + cancel: actions.resizeCancel, |
| + fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil) |
| + } |
| + #endif |
| private func resizeGesture(axis: String, index: Int) -> some Gesture { |
| DragGesture(minimumDistance: 2, coordinateSpace: .global) |
| .updating($draggingResize) { _, active, _ in active = true } |
| .onChanged { value in |
| - guard model.mayWrite, !model.busy, !model.dirty else { return } |
| - if resizing == nil { |
| - resizing = SheetResizePreview(axis: axis, index: index, |
| - original: axis == "col" ? width(index) : height(index)) |
| - } |
| - guard resizing?.axis == axis, resizing?.index == index else { return } |
| - resizing?.update(translation: axis == "col" ? value.translation.width : value.translation.height) |
| + guard actions.canResize() else { return } |
| + actions.resizeChange(axis, index, axis == "col" ? value.translation.width : value.translation.height) |
| } |
| - .onEnded { _ in finishResize(axis: axis, index: index) } |
| + .onEnded { _ in actions.resizeFinish(axis, index) } |
| } |
| } |
| |
| @@ -270,16 +364,16 @@ struct SheetGrid: View { |
| /// LazyVStack and every row's view construction. |
| private struct SheetSelectionObserver: View { |
| let model: SheetModel |
| - @Binding var editing: Coordinate? |
| + let state: SheetEditingState |
| var body: some View { |
| Color.clear.frame(width: 0, height: 0) |
| .onChange(of: model.selection.start) { _, point in |
| - if editing != point { editing = nil } |
| + if state.cell != point { state.cell = nil } |
| } |
| } |
| } |
| |
| -struct SheetResizePreview { |
| +struct SheetResizePreview: Equatable { |
| let axis: String |
| let index: Int |
| let original: Double |
| @@ -292,13 +386,24 @@ struct SheetResizePreview { |
| } |
| } |
| |
| -/// Keeps the selected cell on screen. The grid is lazy: a row scrolled out of |
| -/// view has no views, so there is no cell to edit until it is scrolled back. |
| -/// Not observed: rows coming and going must not re-render the grid. |
| +/// Keeps the selected cell on screen. Not observed: scrolling and rows coming |
| +/// and going must not re-render the grid. |
| @MainActor final class SheetGridScroller { |
| var proxy: ScrollViewProxy? |
| var rows = Set<Int>() |
| - func reveal(_ point: Coordinate) { |
| + /// The scroll view's visible rect, in the content's coordinates. |
| + var visible: CGRect? |
| + /// Scrolls only when the cell is not already in view (under the pinned |
| + /// column header counts as out of view), and never inside the keystroke: |
| + /// a scroll lays the grid out, and the first key must not wait for that. |
| + func reveal(_ point: Coordinate, at frame: CGRect) { |
| + if let visible { |
| + let clear = CGRect(x: visible.minX, y: visible.minY + 32, width: visible.width, height: visible.height - 32) |
| + if clear.contains(frame) { return } |
| + } |
| + DispatchQueue.main.async { [weak self] in self?.scroll(to: point) } |
| + } |
| + private func scroll(to point: Coordinate) { |
| guard let proxy else { return } |
| if rows.contains(point.r) { |
| proxy.scrollTo(point) |