| 1 | import SwiftUI |
| 2 | |
| 3 | /// The grid: state and behaviour here, layout in `SheetGridContent`. |
| 4 | /// |
| 5 | /// The split is for speed. Anything this view owns that changes (keyboard |
| 6 | /// focus above all, which moves every time a cell's editor opens or closes) |
| 7 | /// re-runs this body; if that rebuilt the rows, opening an editor on a |
| 8 | /// 200-column sheet cost most of a second before the first key reached it. |
| 9 | /// The content is Equatable on what it actually draws from, so a focus change |
| 10 | /// re-renders nothing but this thin shell. |
| 11 | struct SheetGrid: View { |
| 12 | @Bindable var model: SheetModel |
| 13 | @State private var editState = SheetEditingState() |
| 14 | @State private var resizing: SheetResizePreview? |
| 15 | @State private var savingResize = false |
| 16 | @FocusState private var focused: Bool |
| 17 | @State private var scroller = SheetGridScroller() |
| 18 | @State private var gridWindow = SheetGridWindow() |
| 19 | #if os(macOS) |
| 20 | @State private var typeAhead = SheetTypeAhead() |
| 21 | #else |
| 22 | /// Bumped to give the keyboard to the cell (SheetKeySink). |
| 23 | @State private var keyboardRequest = 0 |
| 24 | #endif |
| 25 | var beginEditing: () -> Void = {} |
| 26 | /// How long typed keys wait for the cell's field before going to the |
| 27 | /// formula bar instead. Tests shorten it. |
| 28 | var typeAheadTimeout: TimeInterval = 1 |
| 29 | var body: some View { |
| 30 | content.equatable() |
| 31 | .accessibilityLabel("Spreadsheet grid") |
| 32 | .focusable() |
| 33 | .focusEffectDisabled() |
| 34 | .focused($focused) |
| 35 | .background { SheetSelectionObserver(model: model, state: editState) } |
| 36 | .onChange(of: focused) { _, value in model.gridFocused = value } |
| 37 | .onDisappear { model.gridFocused = false; if !savingResize { resizing = nil } } |
| 38 | .onKeyPress(.leftArrow) { move(0, -1) } |
| 39 | .onKeyPress(.rightArrow) { move(0, 1) } |
| 40 | .onKeyPress(.upArrow) { move(-1, 0) } |
| 41 | .onKeyPress(.downArrow) { move(1, 0) } |
| 42 | .onKeyPress(.delete) { |
| 43 | guard editState.cell == nil, model.mayWrite else { return .ignored } |
| 44 | Task { await model.clear() } |
| 45 | return .handled |
| 46 | } |
| 47 | .onKeyPress(.return) { |
| 48 | guard editState.cell == nil, model.mayWrite else { return .ignored } |
| 49 | edit(model.selection.start) |
| 50 | return .handled |
| 51 | } |
| 52 | #if os(macOS) |
| 53 | .background { SheetKeyMonitor(handle: handleKey) } |
| 54 | #else |
| 55 | .onAppear { keyboardRequest += 1 } |
| 56 | #endif |
| 57 | } |
| 58 | private var content: SheetGridContent { |
| 59 | var actions = SheetGridActions( |
| 60 | select: select, edit: edit, selectRow: selectRow, selectColumn: selectColumn, |
| 61 | endEditing: endEditing, move: { r, c in _ = move(r, c) }, |
| 62 | canResize: { [model] in model.mayWrite && !model.busy && !model.dirty && !savingResize }, |
| 63 | resizeChange: resizeChange, resizeFinish: finishResize, |
| 64 | resizeCancel: { if !savingResize { resizing = nil } }) |
| 65 | actions.beginEditing = beginEditing |
| 66 | #if os(macOS) |
| 67 | return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing, |
| 68 | typeAhead: typeAhead, actions: actions) |
| 69 | #else |
| 70 | return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing, |
| 71 | keyboardRequest: keyboardRequest, actions: actions) |
| 72 | #endif |
| 73 | } |
| 74 | private var metrics: SheetGridMetrics { |
| 75 | SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols) |
| 76 | } |
| 77 | private func endEditing() { |
| 78 | editState.cell = nil |
| 79 | #if os(macOS) |
| 80 | typeAhead.cancel() |
| 81 | #endif |
| 82 | takeKeyboard() |
| 83 | } |
| 84 | #if os(macOS) |
| 85 | /// Every key event in this window, before SwiftUI sees it (SheetKeyMonitor). |
| 86 | /// Typing on a selected cell opens its field and hands the keystroke to it |
| 87 | /// whole, so a dead key or an input method composes from the first key. |
| 88 | private func handleKey(_ event: NSEvent) -> Bool { |
| 89 | if typeAhead.awaitingField { |
| 90 | if typeAhead.expired || editState.cell == nil { |
| 91 | // This key arrived after the field should have: it goes on to the |
| 92 | // formula bar with the rest, not into the void. |
| 93 | if SheetTypeAhead.startsTyping(event) { typeAhead.hold(event) } |
| 94 | fieldNeverCame() |
| 95 | return SheetTypeAhead.startsTyping(event) |
| 96 | } else if event.modifierFlags.intersection([.command, .control]).isEmpty { |
| 97 | typeAhead.hold(event) |
| 98 | return true |
| 99 | } else { |
| 100 | return false |
| 101 | } |
| 102 | } |
| 103 | // The grid has the keyboard, or nothing does: a cell's field has just let |
| 104 | // go of it (SheetCellEditor) and SwiftUI has not handed it back yet. |
| 105 | guard editState.cell == nil, model.mayWrite, !model.dirty, !model.opening, let window = event.window, |
| 106 | model.gridFocused || window.firstResponder === window, |
| 107 | !(window.firstResponder is NSText) |
| 108 | else { return false } |
| 109 | if event.specialKey == .f2 { |
| 110 | edit(model.selection.start) |
| 111 | return true |
| 112 | } |
| 113 | guard SheetTypeAhead.startsTyping(event) else { return false } |
| 114 | // Typing replaces the cell; Return, F2 and double-click keep it. The |
| 115 | // cell may be scrolled out of view: bring it into view too. |
| 116 | let point = model.selection.start |
| 117 | scroller.reveal(point, at: metrics.frame(point)) |
| 118 | typeAhead.begin(with: event, timeout: typeAheadTimeout, expired: fieldNeverCame) |
| 119 | edit(point) |
| 120 | if editState.cell == nil { typeAhead.cancel(); return false } |
| 121 | return true |
| 122 | } |
| 123 | /// The cell's field did not come up in time. Nothing typed is dropped: the |
| 124 | /// held text goes to the formula bar, where the edit carries on. |
| 125 | private func fieldNeverCame() { |
| 126 | let text = typeAhead.heldText |
| 127 | typeAhead.cancel() |
| 128 | editState.cell = nil |
| 129 | guard !text.isEmpty else { return } |
| 130 | model.draft = text |
| 131 | beginEditing() |
| 132 | } |
| 133 | #endif |
| 134 | private func edit(_ point: Coordinate) { |
| 135 | // Mid-switch the edit could only be committed to the sheet being left. |
| 136 | guard model.mayWrite, !model.opening else { return } |
| 137 | #if os(macOS) |
| 138 | editState.cell = point |
| 139 | #else |
| 140 | beginEditing() |
| 141 | #endif |
| 142 | } |
| 143 | private func select(_ point: Coordinate) { |
| 144 | // Clicking another cell commits the one being typed in, as every |
| 145 | // spreadsheet does; the save itself no longer holds anything up. |
| 146 | if model.dirty, point != model.selection.start { model.commit(moveRight: nil) } |
| 147 | guard !model.dirty else { return } |
| 148 | if editState.cell != point { editState.cell = nil } |
| 149 | model.select(point) |
| 150 | takeKeyboard() |
| 151 | } |
| 152 | private func takeKeyboard() { |
| 153 | #if os(macOS) |
| 154 | focused = true |
| 155 | #else |
| 156 | keyboardRequest += 1 |
| 157 | #endif |
| 158 | } |
| 159 | private func selectRow(_ row: Int) { |
| 160 | guard !model.dirty else { return } |
| 161 | editState.cell = nil |
| 162 | model.rangeText = "A\(row + 1):" + Coordinate(r: row, c: model.cols - 1).ref |
| 163 | model.selectRange() |
| 164 | takeKeyboard() |
| 165 | } |
| 166 | private func selectColumn(_ col: Int) { |
| 167 | guard !model.dirty else { return } |
| 168 | editState.cell = nil |
| 169 | model.rangeText = Coordinate(r: 0, c: col).ref + ":" + Coordinate(r: model.rows - 1, c: col).ref |
| 170 | model.selectRange() |
| 171 | takeKeyboard() |
| 172 | } |
| 173 | private func move(_ r: Int, _ c: Int) -> KeyPress.Result { |
| 174 | guard editState.cell == nil else { return .ignored } |
| 175 | let p = model.selection.start |
| 176 | let next = Coordinate(r: max(0, min(model.rows - 1, p.r + r)), c: max(0, min(model.cols - 1, p.c + c))) |
| 177 | model.select(next) |
| 178 | scroller.reveal(next, at: metrics.frame(next)) |
| 179 | return .handled |
| 180 | } |
| 181 | private func resizeChange(axis: String, index: Int, translation: Double) { |
| 182 | if resizing == nil { |
| 183 | resizing = SheetResizePreview(axis: axis, index: index, |
| 184 | original: axis == "col" ? metrics.width(index) : metrics.height(index)) |
| 185 | } |
| 186 | guard resizing?.axis == axis, resizing?.index == index else { return } |
| 187 | resizing?.update(translation: translation) |
| 188 | } |
| 189 | private func finishResize(axis: String, index: Int) { |
| 190 | guard let preview = resizing, preview.axis == axis, preview.index == index else { return } |
| 191 | savingResize = true |
| 192 | Task { |
| 193 | await model.resize(axis: axis, size: Int(preview.size), index: index) |
| 194 | resizing = nil |
| 195 | savingResize = false |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// What the grid's layout may ask of the grid. |
| 201 | struct SheetGridActions { |
| 202 | var select: (Coordinate) -> Void |
| 203 | var edit: (Coordinate) -> Void |
| 204 | var selectRow: (Int) -> Void |
| 205 | var selectColumn: (Int) -> Void |
| 206 | var endEditing: () -> Void |
| 207 | var move: (Int, Int) -> Void |
| 208 | var canResize: () -> Bool |
| 209 | var resizeChange: (_ axis: String, _ index: Int, _ translation: Double) -> Void |
| 210 | var resizeFinish: (_ axis: String, _ index: Int) -> Void |
| 211 | var resizeCancel: () -> Void |
| 212 | var beginEditing: () -> Void = {} |
| 213 | } |
| 214 | |
| 215 | /// Column widths and row heights, with a resize in progress applied: the one |
| 216 | /// geometry the grid is laid out from, and that the editor, the keyboard field, |
| 217 | /// scrolling and the windowing below all read. Nothing is estimated. |
| 218 | struct SheetGridMetrics { |
| 219 | let sizes: Sizes |
| 220 | let resizing: SheetResizePreview? |
| 221 | let rows: Int |
| 222 | let cols: Int |
| 223 | /// Leading edge of each column (and the total width last), from 0. |
| 224 | let colStarts: [Double] |
| 225 | let rowStarts: [Double] |
| 226 | init(sizes: Sizes, resizing: SheetResizePreview?, rows: Int, cols: Int) { |
| 227 | self.sizes = sizes; self.resizing = resizing; self.rows = rows; self.cols = cols |
| 228 | func width(_ c: Int) -> Double { |
| 229 | if let resizing, resizing.axis == "col", resizing.index == c { return resizing.size } |
| 230 | return sizes.cols?[String(c)] ?? 110 |
| 231 | } |
| 232 | func height(_ r: Int) -> Double { |
| 233 | if let resizing, resizing.axis == "row", resizing.index == r { return resizing.size } |
| 234 | return sizes.rows?[String(r)] ?? 32 |
| 235 | } |
| 236 | var x: [Double] = [0]; x.reserveCapacity(cols + 1) |
| 237 | for c in 0..<cols { x.append(x[c] + width(c)) } |
| 238 | var y: [Double] = [0]; y.reserveCapacity(rows + 1) |
| 239 | for r in 0..<rows { y.append(y[r] + height(r)) } |
| 240 | colStarts = x; rowStarts = y |
| 241 | } |
| 242 | static let rowHeader = 48.0 |
| 243 | static let colHeader = 32.0 |
| 244 | func width(_ col: Int) -> Double { col < cols ? colStarts[col + 1] - colStarts[col] : 110 } |
| 245 | func height(_ row: Int) -> Double { row < rows ? rowStarts[row + 1] - rowStarts[row] : 32 } |
| 246 | var cellsWidth: Double { colStarts[cols] } |
| 247 | var cellsHeight: Double { rowStarts[rows] } |
| 248 | /// Where a cell sits in the grid's content: after the row header and the |
| 249 | /// pinned column header. |
| 250 | func frame(_ point: Coordinate) -> CGRect { |
| 251 | let c = min(point.c, cols), r = min(point.r, rows) |
| 252 | return CGRect(x: Self.rowHeader + colStarts[c], y: Self.colHeader + rowStarts[r], |
| 253 | width: width(point.c), height: height(point.r)) |
| 254 | } |
| 255 | /// The columns and rows a visible rect (content coordinates) touches, |
| 256 | /// widened to whole blocks (2 columns, 4 rows), so scrolling re-renders the |
| 257 | /// grid only every few columns or rows, never every pixel. Blocks are kept |
| 258 | /// small: each crossing builds a block of new cells in one frame, and |
| 259 | /// every cell built is one that opening an editor has to lay out. |
| 260 | func window(for visible: CGRect) -> (cols: Range<Int>, rows: Range<Int>) { |
| 261 | func span(_ starts: [Double], _ count: Int, _ lo: Double, _ hi: Double, block: Int) -> Range<Int> { |
| 262 | guard count > 0 else { return 0..<0 } |
| 263 | // First index whose far edge is past lo; last whose near edge is before hi. |
| 264 | var first = 0, low = 0, high = count |
| 265 | while low < high { let mid = (low + high) / 2; if starts[mid + 1] <= lo { low = mid + 1 } else { high = mid } } |
| 266 | first = low |
| 267 | low = first; high = count |
| 268 | while low < high { let mid = (low + high) / 2; if starts[mid] < hi { low = mid + 1 } else { high = mid } } |
| 269 | let last = max(first, low - 1) |
| 270 | let start = first / block * block |
| 271 | let end = min(count, (last / block + 1) * block) |
| 272 | return start..<max(start, end) |
| 273 | } |
| 274 | return ( |
| 275 | span(colStarts, cols, visible.minX - Self.rowHeader, visible.maxX - Self.rowHeader, block: 2), |
| 276 | span(rowStarts, rows, visible.minY - Self.colHeader, visible.maxY - Self.colHeader, block: 4)) |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /// Which columns and rows exist as views. Only the grid's layout reads the |
| 281 | /// ranges, and they change only when scrolling crosses a block. |
| 282 | @MainActor @Observable final class SheetGridWindow { |
| 283 | var cols: Range<Int> = 0..<8 |
| 284 | var rows: Range<Int> = 0..<24 |
| 285 | /// The top of the area below the pinned column header, in content |
| 286 | /// coordinates: the editor is clipped to it. Read only while editing. |
| 287 | var clipTop: Double = SheetGridMetrics.colHeader |
| 288 | @ObservationIgnored var visible = CGRect(x: 0, y: 0, width: 800, height: 700) |
| 289 | func update(_ visible: CGRect, _ metrics: SheetGridMetrics) { |
| 290 | self.visible = visible |
| 291 | let next = metrics.window(for: visible) |
| 292 | if next.cols != cols { cols = next.cols } |
| 293 | if next.rows != rows { rows = next.rows } |
| 294 | let top = visible.minY + SheetGridMetrics.colHeader |
| 295 | if top != clipTop { clipTop = top } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | /// The grid's rows, headers and floating editor. Equatable on what it draws |
| 300 | /// from (the model's observed properties are tracked by SwiftUI as usual), so |
| 301 | /// the grid's own focus and key state never rebuild it (see SheetGrid). |
| 302 | struct SheetGridContent: View, Equatable { |
| 303 | @Bindable var model: SheetModel |
| 304 | let editState: SheetEditingState |
| 305 | let scroller: SheetGridScroller |
| 306 | let window: SheetGridWindow |
| 307 | let resizing: SheetResizePreview? |
| 308 | #if os(macOS) |
| 309 | let typeAhead: SheetTypeAhead |
| 310 | #else |
| 311 | let keyboardRequest: Int |
| 312 | #endif |
| 313 | let actions: SheetGridActions |
| 314 | @GestureState private var draggingResize = false |
| 315 | |
| 316 | /// SwiftUI compares views on the main thread, where they are built: `==` |
| 317 | /// is nonisolated only because Equatable requires it, and the stored |
| 318 | /// references (main-actor objects) are compared by identity, nothing more. |
| 319 | nonisolated static func == (a: Self, b: Self) -> Bool { |
| 320 | MainActor.assumeIsolated { |
| 321 | #if os(macOS) |
| 322 | let same = a.typeAhead === b.typeAhead |
| 323 | #else |
| 324 | let same = a.keyboardRequest == b.keyboardRequest |
| 325 | #endif |
| 326 | return same && a.model === b.model && a.editState === b.editState && a.scroller === b.scroller |
| 327 | && a.window === b.window && a.resizing == b.resizing |
| 328 | } |
| 329 | } |
| 330 | private var metrics: SheetGridMetrics { |
| 331 | SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols) |
| 332 | } |
| 333 | @State private var position = ScrollPosition() |
| 334 | |
| 335 | // Columns and rows are windowed by hand from the exact metrics: a leading |
| 336 | // and a trailing spacer stand in for what is off screen. (A LazyHStack |
| 337 | // estimated the widths of columns it had not built, so its layout and the |
| 338 | // exact geometry the editor and clicks use disagreed by whole columns.) |
| 339 | var body: some View { |
| 340 | let m = metrics |
| 341 | let cols = Array(window.cols.clamped(to: 0..<m.cols)) |
| 342 | let rows = Array(window.rows.clamped(to: 0..<m.rows)) |
| 343 | let lead = m.colStarts[cols.first ?? 0] |
| 344 | let trail = m.cellsWidth - m.colStarts[cols.last.map { $0 + 1 } ?? 0] |
| 345 | ScrollView([.horizontal, .vertical]) { |
| 346 | LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) { |
| 347 | Section { |
| 348 | VStack(alignment: .leading, spacing: 0) { |
| 349 | Color.clear.frame(width: 1, height: m.rowStarts[rows.first ?? 0]) |
| 350 | ForEach(rows, id: \.self) { row in |
| 351 | HStack(spacing: 0) { |
| 352 | rowHeader(row, m) |
| 353 | Color.clear.frame(width: lead, height: m.height(row)) |
| 354 | ForEach(cols, id: \.self) { col in cell(row: row, col: col, m) } |
| 355 | Color.clear.frame(width: trail, height: m.height(row)) |
| 356 | } |
| 357 | } |
| 358 | Color.clear.frame(width: 1, height: m.cellsHeight - m.rowStarts[rows.last.map { $0 + 1 } ?? 0]) |
| 359 | } |
| 360 | } header: { |
| 361 | HStack(spacing: 0) { |
| 362 | Text("").frame(width: SheetGridMetrics.rowHeader, height: SheetGridMetrics.colHeader) |
| 363 | Color.clear.frame(width: lead, height: SheetGridMetrics.colHeader) |
| 364 | ForEach(cols, id: \.self) { col in columnHeader(col, m) } |
| 365 | Color.clear.frame(width: trail, height: SheetGridMetrics.colHeader) |
| 366 | }.background(.regularMaterial) |
| 367 | } |
| 368 | } |
| 369 | #if os(iOS) |
| 370 | .overlay(alignment: .topLeading) { keySink } |
| 371 | #else |
| 372 | .overlay(alignment: .topLeading) { |
| 373 | SheetEditorOverlay(model: model, state: editState, window: window, typeAhead: typeAhead, |
| 374 | frame: m.frame, end: actions.endEditing) |
| 375 | } |
| 376 | #endif |
| 377 | // Always-shown scroll bars sit over the content's last strip; without |
| 378 | // room for them the last row and column could never be scrolled clear. |
| 379 | .padding(.trailing, SheetGridScroller.legacyBar) |
| 380 | .padding(.bottom, SheetGridScroller.legacyBar) |
| 381 | } |
| 382 | .defaultScrollAnchor(.topLeading) |
| 383 | .scrollPosition($position) |
| 384 | .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in |
| 385 | scroller.visible = SheetGridScroller.usable(rect) |
| 386 | window.update(rect, metrics) |
| 387 | } |
| 388 | // New sizes or a resize in progress move every edge after them. |
| 389 | .onChange(of: m.colStarts + m.rowStarts) { window.update(window.visible, metrics) } |
| 390 | .onAppear { |
| 391 | scroller.scrollTo = { point in position.scrollTo(point: point) } |
| 392 | window.update(window.visible, m) |
| 393 | } |
| 394 | .onChange(of: draggingResize) { _, active in |
| 395 | if !active { actions.resizeCancel() } |
| 396 | } |
| 397 | } |
| 398 | private func rowHeader(_ row: Int, _ m: SheetGridMetrics) -> some View { |
| 399 | ZStack(alignment: .bottom) { |
| 400 | Button { actions.selectRow(row) } label: { |
| 401 | Text(String(row + 1)).frame(width: SheetGridMetrics.rowHeader, height: m.height(row)).background(.quaternary) |
| 402 | }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1)) |
| 403 | #if os(macOS) |
| 404 | resizeHandle(axis: "row", index: row).frame(width: SheetGridMetrics.rowHeader, height: 8) |
| 405 | #else |
| 406 | Color.clear.frame(width: SheetGridMetrics.rowHeader, height: 8) |
| 407 | .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row)) |
| 408 | .accessibilityHidden(true) |
| 409 | #endif |
| 410 | } |
| 411 | } |
| 412 | private func columnHeader(_ col: Int, _ m: SheetGridMetrics) -> some View { |
| 413 | ZStack(alignment: .trailing) { |
| 414 | Button { actions.selectColumn(col) } label: { |
| 415 | Text(Coordinate(r: 0, c: col).ref.dropLast()) |
| 416 | .frame(width: m.width(col), height: SheetGridMetrics.colHeader) |
| 417 | .contentShape(.rect) |
| 418 | }.buttonStyle(.plain) |
| 419 | .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast()))) |
| 420 | #if os(macOS) |
| 421 | resizeHandle(axis: "col", index: col).frame(width: 8, height: SheetGridMetrics.colHeader) |
| 422 | .help(sheetsMacString("Double-click to fit column to contents")) |
| 423 | #else |
| 424 | Color.clear.frame(width: 8, height: SheetGridMetrics.colHeader) |
| 425 | #endif |
| 426 | } |
| 427 | #if os(macOS) |
| 428 | .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } } |
| 429 | #endif |
| 430 | } |
| 431 | #if os(iOS) |
| 432 | /// The keyboard's place on the selected cell (SheetKeySink). |
| 433 | private var keySink: some View { |
| 434 | let box = metrics.frame(model.selection.start) |
| 435 | return SheetKeySink(model: model, focusRequest: keyboardRequest, move: actions.move) |
| 436 | .frame(width: box.width, height: box.height) |
| 437 | .modifier(SheetHeaderClip(window: window, top: box.minY)) |
| 438 | .offset(x: box.minX, y: box.minY) |
| 439 | .allowsHitTesting(false) |
| 440 | } |
| 441 | #endif |
| 442 | private func cell(row: Int, col: Int, _ m: SheetGridMetrics) -> some View { |
| 443 | let point = Coordinate(r: row, c: col) |
| 444 | return SheetCell( |
| 445 | model: model, point: point, |
| 446 | select: { actions.select(point) }, |
| 447 | beginEditing: { actions.edit(point) }, |
| 448 | columnWidth: m.width(col), rowHeight: m.height(row), editState: editState).equatable() |
| 449 | } |
| 450 | #if os(macOS) |
| 451 | private func resizeHandle(axis: String, index: Int) -> some View { |
| 452 | SheetResizeHandle(vertical: axis == "row", |
| 453 | canBegin: actions.canResize, |
| 454 | change: { translation in actions.resizeChange(axis, index, translation) }, |
| 455 | finish: { actions.resizeFinish(axis, index) }, |
| 456 | cancel: actions.resizeCancel, |
| 457 | fit: axis == "col" ? { Task { await model.fitColumn(index) } } : nil) |
| 458 | } |
| 459 | #endif |
| 460 | private func resizeGesture(axis: String, index: Int) -> some Gesture { |
| 461 | DragGesture(minimumDistance: 2, coordinateSpace: .global) |
| 462 | .updating($draggingResize) { _, active, _ in active = true } |
| 463 | .onChanged { value in |
| 464 | guard actions.canResize() else { return } |
| 465 | actions.resizeChange(axis, index, axis == "col" ? value.translation.width : value.translation.height) |
| 466 | } |
| 467 | .onEnded { _ in actions.resizeFinish(axis, index) } |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | /// Observe selection in a leaf, so moving between cells does not invalidate the |
| 472 | /// LazyVStack and every row's view construction. |
| 473 | private struct SheetSelectionObserver: View { |
| 474 | let model: SheetModel |
| 475 | let state: SheetEditingState |
| 476 | var body: some View { |
| 477 | Color.clear.frame(width: 0, height: 0) |
| 478 | .onChange(of: model.selection.start) { _, point in |
| 479 | if state.cell != point { state.cell = nil } |
| 480 | } |
| 481 | // A new sheet: no editor of the old one stays open over it. |
| 482 | .onChange(of: model.page?.Sheet.ID) { state.cell = nil } |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | struct SheetResizePreview: Equatable { |
| 487 | let axis: String |
| 488 | let index: Int |
| 489 | let original: Double |
| 490 | var size: Double |
| 491 | init(axis: String, index: Int, original: Double) { |
| 492 | self.axis = axis; self.index = index; self.original = original; self.size = original |
| 493 | } |
| 494 | mutating func update(translation: Double) { |
| 495 | size = min(2000, max(16, (original + translation).rounded())) |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | /// Keeps the selected cell on screen. Not observed: scrolling must not |
| 500 | /// re-render the grid. |
| 501 | @MainActor final class SheetGridScroller { |
| 502 | var scrollTo: ((CGPoint) -> Void)? |
| 503 | /// The scroll view's visible rect, in the content's coordinates. |
| 504 | var visible: CGRect? |
| 505 | /// Scrolls only when the cell is not already in view (under the pinned |
| 506 | /// column header counts as out of view), and never inside the keystroke: |
| 507 | /// a scroll lays the grid out, and the first key must not wait for that. |
| 508 | /// It scrolls just far enough, to the cell's exact place. |
| 509 | func reveal(_ point: Coordinate, at frame: CGRect) { |
| 510 | guard let visible, let target = Self.offset(showing: frame, in: visible) else { return } |
| 511 | DispatchQueue.main.async { [weak self] in self?.scrollTo?(target) } |
| 512 | } |
| 513 | /// The part of the visible rect not under scroll bars. The scroll geometry |
| 514 | /// counts the area under them; with legacy (always shown) scroll bars on |
| 515 | /// the Mac, a cell revealed into that strip would be hidden by them. |
| 516 | static func usable(_ rect: CGRect) -> CGRect { |
| 517 | let bar = legacyBar |
| 518 | return CGRect(x: rect.minX, y: rect.minY, width: rect.width - bar, height: rect.height - bar) |
| 519 | } |
| 520 | /// The width of an always-shown scroll bar, or 0 with overlay scroll bars. |
| 521 | static var legacyBar: Double { |
| 522 | #if os(macOS) |
| 523 | NSScroller.preferredScrollerStyle == .legacy ? NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) : 0 |
| 524 | #else |
| 525 | 0 |
| 526 | #endif |
| 527 | } |
| 528 | /// The content offset that brings `frame` into view with the least scroll, |
| 529 | /// or nil when it is in view already. |
| 530 | static func offset(showing frame: CGRect, in visible: CGRect) -> CGPoint? { |
| 531 | let top = SheetGridMetrics.colHeader |
| 532 | var x = visible.minX, y = visible.minY |
| 533 | if frame.minX < visible.minX { x = frame.minX } else if frame.maxX > visible.maxX { x = frame.maxX - visible.width } |
| 534 | if frame.minY < visible.minY + top { y = frame.minY - top } else if frame.maxY > visible.maxY { y = frame.maxY - visible.height } |
| 535 | let target = CGPoint(x: max(0, x), y: max(0, y)) |
| 536 | return target == visible.origin ? nil : target |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | /// Keeps a floating field (the cell editor, the iOS key field) below the |
| 541 | /// pinned column header when its cell has scrolled under it. |
| 542 | struct SheetHeaderClip: ViewModifier { |
| 543 | let window: SheetGridWindow |
| 544 | /// The field's top, in the grid's content coordinates. |
| 545 | let top: Double |
| 546 | func body(content: Content) -> some View { |
| 547 | content.mask(alignment: .topLeading) { |
| 548 | Rectangle().padding(.top, max(0, window.clipTop - top)) |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | |