| index c694df9..75ca358 100644 |
| --- a/native/apple/Sources/SheetsKit/SheetGrid.swift |
| +++ b/native/apple/Sources/SheetsKit/SheetGrid.swift |
| @@ -15,6 +15,7 @@ struct SheetGrid: View { |
| @State private var savingResize = false |
| @FocusState private var focused: Bool |
| @State private var scroller = SheetGridScroller() |
| + @State private var gridWindow = SheetGridWindow() |
| #if os(macOS) |
| @State private var typeAhead = SheetTypeAhead() |
| #else |
| @@ -60,14 +61,16 @@ struct SheetGrid: View { |
| resizeCancel: { if !savingResize { resizing = nil } }) |
| actions.beginEditing = beginEditing |
| #if os(macOS) |
| - return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing, |
| + return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing, |
| typeAhead: typeAhead, actions: actions) |
| #else |
| - return SheetGridContent(model: model, editState: editState, scroller: scroller, resizing: resizing, |
| + return SheetGridContent(model: model, editState: editState, scroller: scroller, window: gridWindow, resizing: resizing, |
| keyboardRequest: keyboardRequest, actions: actions) |
| #endif |
| } |
| - private var metrics: SheetGridMetrics { SheetGridMetrics(sizes: model.sizes, resizing: resizing) } |
| + private var metrics: SheetGridMetrics { |
| + SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols) |
| + } |
| private func endEditing() { |
| editState.cell = nil |
| #if os(macOS) |
| @@ -202,26 +205,87 @@ struct SheetGridActions { |
| var beginEditing: () -> Void = {} |
| } |
| |
| -/// Column widths and row heights, with a resize in progress applied. |
| +/// Column widths and row heights, with a resize in progress applied: the one |
| +/// geometry the grid is laid out from, and that the editor, the keyboard field, |
| +/// scrolling and the windowing below all read. Nothing is estimated. |
| struct SheetGridMetrics { |
| let sizes: Sizes |
| let resizing: SheetResizePreview? |
| - 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 |
| + let rows: Int |
| + let cols: Int |
| + /// Leading edge of each column (and the total width last), from 0. |
| + let colStarts: [Double] |
| + let rowStarts: [Double] |
| + init(sizes: Sizes, resizing: SheetResizePreview?, rows: Int, cols: Int) { |
| + self.sizes = sizes; self.resizing = resizing; self.rows = rows; self.cols = cols |
| + func width(_ c: Int) -> Double { |
| + if let resizing, resizing.axis == "col", resizing.index == c { return resizing.size } |
| + return sizes.cols?[String(c)] ?? 110 |
| + } |
| + func height(_ r: Int) -> Double { |
| + if let resizing, resizing.axis == "row", resizing.index == r { return resizing.size } |
| + return sizes.rows?[String(r)] ?? 32 |
| + } |
| + var x: [Double] = [0]; x.reserveCapacity(cols + 1) |
| + for c in 0..<cols { x.append(x[c] + width(c)) } |
| + var y: [Double] = [0]; y.reserveCapacity(rows + 1) |
| + for r in 0..<rows { y.append(y[r] + height(r)) } |
| + colStarts = x; rowStarts = y |
| } |
| + static let rowHeader = 48.0 |
| + static let colHeader = 32.0 |
| + func width(_ col: Int) -> Double { col < cols ? colStarts[col + 1] - colStarts[col] : 110 } |
| + func height(_ row: Int) -> Double { row < rows ? rowStarts[row + 1] - rowStarts[row] : 32 } |
| + var cellsWidth: Double { colStarts[cols] } |
| + var cellsHeight: Double { rowStarts[rows] } |
| /// Where a cell sits in the grid's content: after the row header and the |
| /// pinned column header. |
| func frame(_ point: Coordinate) -> CGRect { |
| - CGRect( |
| - x: 48 + (0..<point.c).reduce(0) { $0 + width($1) }, |
| - y: 32 + (0..<point.r).reduce(0) { $0 + height($1) }, |
| + let c = min(point.c, cols), r = min(point.r, rows) |
| + return CGRect(x: Self.rowHeader + colStarts[c], y: Self.colHeader + rowStarts[r], |
| width: width(point.c), height: height(point.r)) |
| } |
| + /// The columns and rows a visible rect (content coordinates) touches, |
| + /// widened to whole blocks (4 columns, 8 rows), so scrolling re-renders the |
| + /// grid only every few columns or rows, never every pixel. Blocks are kept |
| + /// small: every cell built is a cell opening an editor has to lay out. |
| + func window(for visible: CGRect) -> (cols: Range<Int>, rows: Range<Int>) { |
| + func span(_ starts: [Double], _ count: Int, _ lo: Double, _ hi: Double, block: Int) -> Range<Int> { |
| + guard count > 0 else { return 0..<0 } |
| + // First index whose far edge is past lo; last whose near edge is before hi. |
| + var first = 0, low = 0, high = count |
| + while low < high { let mid = (low + high) / 2; if starts[mid + 1] <= lo { low = mid + 1 } else { high = mid } } |
| + first = low |
| + low = first; high = count |
| + while low < high { let mid = (low + high) / 2; if starts[mid] < hi { low = mid + 1 } else { high = mid } } |
| + let last = max(first, low - 1) |
| + let start = first / block * block |
| + let end = min(count, (last / block + 1) * block) |
| + return start..<max(start, end) |
| + } |
| + return ( |
| + span(colStarts, cols, visible.minX - Self.rowHeader, visible.maxX - Self.rowHeader, block: 4), |
| + span(rowStarts, rows, visible.minY - Self.colHeader, visible.maxY - Self.colHeader, block: 8)) |
| + } |
| +} |
| + |
| +/// Which columns and rows exist as views. Only the grid's layout reads the |
| +/// ranges, and they change only when scrolling crosses a block. |
| +@MainActor @Observable final class SheetGridWindow { |
| + var cols: Range<Int> = 0..<8 |
| + var rows: Range<Int> = 0..<24 |
| + /// The top of the area below the pinned column header, in content |
| + /// coordinates: the editor is clipped to it. Read only while editing. |
| + var clipTop: Double = SheetGridMetrics.colHeader |
| + @ObservationIgnored var visible = CGRect(x: 0, y: 0, width: 800, height: 700) |
| + func update(_ visible: CGRect, _ metrics: SheetGridMetrics) { |
| + self.visible = visible |
| + let next = metrics.window(for: visible) |
| + if next.cols != cols { cols = next.cols } |
| + if next.rows != rows { rows = next.rows } |
| + let top = visible.minY + SheetGridMetrics.colHeader |
| + if top != clipTop { clipTop = top } |
| + } |
| } |
| |
| /// The grid's rows, headers and floating editor. Equatable on what it draws |
| @@ -231,6 +295,7 @@ struct SheetGridContent: View, Equatable { |
| @Bindable var model: SheetModel |
| let editState: SheetEditingState |
| let scroller: SheetGridScroller |
| + let window: SheetGridWindow |
| let resizing: SheetResizePreview? |
| #if os(macOS) |
| let typeAhead: SheetTypeAhead |
| @@ -248,61 +313,45 @@ struct SheetGridContent: View, Equatable { |
| 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 |
| + && a.window === b.window && 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) } |
| + private var metrics: SheetGridMetrics { |
| + SheetGridMetrics(sizes: model.sizes, resizing: resizing, rows: model.rows, cols: model.cols) |
| + } |
| + @State private var position = ScrollPosition() |
| |
| + // Columns and rows are windowed by hand from the exact metrics: a leading |
| + // and a trailing spacer stand in for what is off screen. (A LazyHStack |
| + // estimated the widths of columns it had not built, so its layout and the |
| + // exact geometry the editor and clicks use disagreed by whole columns.) |
| var body: some View { |
| - ScrollViewReader { proxy in |
| + let m = metrics |
| + let cols = Array(window.cols.clamped(to: 0..<m.cols)) |
| + let rows = Array(window.rows.clamped(to: 0..<m.rows)) |
| + let lead = m.colStarts[cols.first ?? 0] |
| + let trail = m.cellsWidth - m.colStarts[cols.last.map { $0 + 1 } ?? 0] |
| ScrollView([.horizontal, .vertical]) { |
| - LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) { |
| + LazyVStack(alignment: .leading, 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)) |
| + VStack(alignment: .leading, spacing: 0) { |
| + Color.clear.frame(width: 1, height: m.rowStarts[rows.first ?? 0]) |
| + ForEach(rows, id: \.self) { row in |
| + HStack(spacing: 0) { |
| + rowHeader(row, m) |
| + Color.clear.frame(width: lead, height: m.height(row)) |
| + ForEach(cols, id: \.self) { col in cell(row: row, col: col, m) } |
| + Color.clear.frame(width: trail, height: m.height(row)) |
| } |
| } |
| - .onAppear { scroller.rows.insert(row) } |
| - .onDisappear { scroller.rows.remove(row) } |
| + Color.clear.frame(width: 1, height: m.cellsHeight - m.rowStarts[rows.last.map { $0 + 1 } ?? 0]) |
| } |
| } 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 |
| - } |
| + HStack(spacing: 0) { |
| + Text("").frame(width: SheetGridMetrics.rowHeader, height: SheetGridMetrics.colHeader) |
| + Color.clear.frame(width: lead, height: SheetGridMetrics.colHeader) |
| + ForEach(cols, id: \.self) { col in columnHeader(col, m) } |
| + Color.clear.frame(width: trail, height: SheetGridMetrics.colHeader) |
| }.background(.regularMaterial) |
| } |
| } |
| @@ -310,18 +359,60 @@ struct SheetGridContent: View, Equatable { |
| .overlay(alignment: .topLeading) { keySink } |
| #else |
| .overlay(alignment: .topLeading) { |
| - SheetEditorOverlay(model: model, state: editState, typeAhead: typeAhead, |
| - frame: metrics.frame, end: actions.endEditing) |
| + SheetEditorOverlay(model: model, state: editState, window: window, typeAhead: typeAhead, |
| + frame: m.frame, end: actions.endEditing) |
| } |
| #endif |
| - }.defaultScrollAnchor(.topLeading) |
| - .onAppear { scroller.proxy = proxy } |
| - .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in scroller.visible = rect } |
| + } |
| + .defaultScrollAnchor(.topLeading) |
| + .scrollPosition($position) |
| + .onScrollGeometryChange(for: CGRect.self, of: \.visibleRect) { _, rect in |
| + scroller.visible = SheetGridScroller.usable(rect) |
| + window.update(rect, metrics) |
| + } |
| + // New sizes or a resize in progress move every edge after them. |
| + .onChange(of: m.colStarts + m.rowStarts) { window.update(window.visible, metrics) } |
| + .onAppear { |
| + scroller.scrollTo = { point in position.scrollTo(point: point) } |
| + window.update(window.visible, m) |
| } |
| .onChange(of: draggingResize) { _, active in |
| if !active { actions.resizeCancel() } |
| } |
| } |
| + private func rowHeader(_ row: Int, _ m: SheetGridMetrics) -> some View { |
| + ZStack(alignment: .bottom) { |
| + Button { actions.selectRow(row) } label: { |
| + Text(String(row + 1)).frame(width: SheetGridMetrics.rowHeader, height: m.height(row)).background(.quaternary) |
| + }.buttonStyle(.plain).accessibilityLabel(String(format: sheetsMacString("Select row %d"), row + 1)) |
| + #if os(macOS) |
| + resizeHandle(axis: "row", index: row).frame(width: SheetGridMetrics.rowHeader, height: 8) |
| + #else |
| + Color.clear.frame(width: SheetGridMetrics.rowHeader, height: 8) |
| + .contentShape(.rect).gesture(resizeGesture(axis: "row", index: row)) |
| + .accessibilityHidden(true) |
| + #endif |
| + } |
| + } |
| + private func columnHeader(_ col: Int, _ m: SheetGridMetrics) -> some View { |
| + ZStack(alignment: .trailing) { |
| + Button { actions.selectColumn(col) } label: { |
| + Text(Coordinate(r: 0, c: col).ref.dropLast()) |
| + .frame(width: m.width(col), height: SheetGridMetrics.colHeader) |
| + .contentShape(.rect) |
| + }.buttonStyle(.plain) |
| + .accessibilityLabel(String(format: sheetsMacString("Select column %@"), String(Coordinate(r: 0, c: col).ref.dropLast()))) |
| + #if os(macOS) |
| + resizeHandle(axis: "col", index: col).frame(width: 8, height: SheetGridMetrics.colHeader) |
| + .help(sheetsMacString("Double-click to fit column to contents")) |
| + #else |
| + Color.clear.frame(width: 8, height: SheetGridMetrics.colHeader) |
| + #endif |
| + } |
| + #if os(macOS) |
| + .contextMenu { Button(sheetsMacString("Fit column to contents")) { Task { await model.fitColumn(col) } } } |
| + #endif |
| + } |
| #if os(iOS) |
| /// The keyboard's place on the selected cell (SheetKeySink). |
| private var keySink: some View { |
| @@ -332,13 +423,13 @@ struct SheetGridContent: View, Equatable { |
| .allowsHitTesting(false) |
| } |
| #endif |
| - private func cell(row: Int, col: Int) -> some View { |
| + private func cell(row: Int, col: Int, _ m: SheetGridMetrics) -> some View { |
| let point = Coordinate(r: row, c: col) |
| return SheetCell( |
| model: model, point: point, |
| select: { actions.select(point) }, |
| beginEditing: { actions.edit(point) }, |
| - columnWidth: width(col), rowHeight: height(row)) |
| + columnWidth: m.width(col), rowHeight: m.height(row)) |
| } |
| #if os(macOS) |
| private func resizeHandle(axis: String, index: Int) -> some View { |
| @@ -389,31 +480,40 @@ struct SheetResizePreview: Equatable { |
| } |
| } |
| |
| -/// Keeps the selected cell on screen. Not observed: scrolling and rows coming |
| -/// and going must not re-render the grid. |
| +/// Keeps the selected cell on screen. Not observed: scrolling must not |
| +/// re-render the grid. |
| @MainActor final class SheetGridScroller { |
| - var proxy: ScrollViewProxy? |
| - var rows = Set<Int>() |
| + var scrollTo: ((CGPoint) -> Void)? |
| /// The scroll view's visible rect, in the content's coordinates. |
| var visible: CGRect? |
| /// Scrolls only when the cell is not already in view (under the pinned |
| /// column header counts as out of view), and never inside the keystroke: |
| /// a scroll lays the grid out, and the first key must not wait for that. |
| + /// It scrolls just far enough, to the cell's exact place. |
| func reveal(_ point: Coordinate, at frame: CGRect) { |
| - 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) |
| - } else { |
| - // Bring the row into being, then the cell into view. |
| - proxy.scrollTo(point.r) |
| - DispatchQueue.main.async { proxy.scrollTo(point) } |
| - } |
| + guard let visible, let target = Self.offset(showing: frame, in: visible) else { return } |
| + DispatchQueue.main.async { [weak self] in self?.scrollTo?(target) } |
| + } |
| + /// The part of the visible rect not under scroll bars. The scroll geometry |
| + /// counts the area under them; with legacy (always shown) scroll bars on |
| + /// the Mac, a cell revealed into that strip would be hidden by them. |
| + static func usable(_ rect: CGRect) -> CGRect { |
| + #if os(macOS) |
| + guard NSScroller.preferredScrollerStyle == .legacy else { return rect } |
| + let bar = NSScroller.scrollerWidth(for: .regular, scrollerStyle: .legacy) |
| + return CGRect(x: rect.minX, y: rect.minY, width: rect.width - bar, height: rect.height - bar) |
| + #else |
| + return rect |
| + #endif |
| + } |
| + /// The content offset that brings `frame` into view with the least scroll, |
| + /// or nil when it is in view already. |
| + static func offset(showing frame: CGRect, in visible: CGRect) -> CGPoint? { |
| + let top = SheetGridMetrics.colHeader |
| + var x = visible.minX, y = visible.minY |
| + if frame.minX < visible.minX { x = frame.minX } else if frame.maxX > visible.maxX { x = frame.maxX - visible.width } |
| + if frame.minY < visible.minY + top { y = frame.minY - top } else if frame.maxY > visible.maxY { y = frame.maxY - visible.height } |
| + let target = CGPoint(x: max(0, x), y: max(0, y)) |
| + return target == visible.origin ? nil : target |
| } |
| } |