oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1import SwiftUI
2
3/// Equatable on what it draws from besides the model's observed state (which
4/// SwiftUI tracks on its own): the grid rebuilds its rows whenever scrolling
5/// crosses a window block, and without this every visible cell's body ran
6/// again each time. Its closures act on the grid and are equal in effect.
7struct SheetCell: View, Equatable {
8 nonisolated static func == (a: Self, b: Self) -> Bool {
9 // SwiftUI compares views on the main thread, where it builds them.
10 MainActor.assumeIsolated {
11 a.model === b.model && a.point == b.point && a.columnWidth == b.columnWidth
12 && a.rowHeight == b.rowHeight && a.editState === b.editState
13 }
14 }
15 @Bindable var model: SheetModel
16 let point: Coordinate
17 var select: () -> Void
18 var beginEditing: () -> Void = {}
19 var columnWidth: Double? = nil
20 var rowHeight: Double? = nil
21 /// While this cell's editor is open, the editor is the one element here.
22 var editState: SheetEditingState? = nil
23 @Environment(\.colorScheme) private var scheme
24 private func width(_ col: Int) -> Double { columnWidth ?? model.sizes.cols?[String(col)] ?? 110 }
25 private func height(_ row: Int) -> Double { rowHeight ?? model.sizes.rows?[String(row)] ?? 32 }
26 var body: some View {
27 let cell = model.displayCell(point)
28 let style = model.styles[cell?.f ?? ""]
29 let alignment: Alignment =
30 style?.a == "center"
31 ? .center : style?.a == "right" || (style?.a == nil && cell?.n == true) ? .trailing : .leading
32 // The editor is not drawn here: it floats over the grid
33 // (SheetEditorOverlay), so opening one re-renders no cell.
34 return display(cell, style: style, alignment: alignment)
35 }
36 private func display(_ cell: Cell?, style: CellStyle?, alignment: Alignment) -> some View {
37 let failed = model.editState(point) == .failed
38 return Button(action: select) {
39 Text(cell?.display ?? "").font(.system(size: 13, weight: style?.b == true ? .bold : .regular))
40 .italic(style?.i == true).lineLimit(1).padding(.horizontal, 5)
41 .frame(width: width(point.c), height: height(point.r), alignment: alignment)
42 .foregroundStyle(ink(style)).background(fill(style))
43 .contentShape(.rect)
44 .overlay {
45 Rectangle().strokeBorder(
46 model.selection.contains(point) ? Color.accentColor : Color.secondary.opacity(0.2),
47 lineWidth: model.selection.contains(point) ? 2 : 0.5)
48 }
49 .overlay(alignment: .topTrailing) { if failed { SheetNotSavedMark() } }
50 }.buttonStyle(.plain)
51 .simultaneousGesture(TapGesture(count: 2).onEnded { if model.mayWrite, !model.dirty { model.select(point); beginEditing() } })
52 .modifier(NotSavedActions(model: model, point: point, failed: failed))
53 .accessibilityLabel("\(point.ref), \(cell?.display ?? "Empty")")
54 .accessibilityValue(failed ? sheetsMacString("Not saved") : style?.lc == true ? "Imported colours have low contrast" : "")
55 .accessibilityAddTraits(model.selection.contains(point) ? .isSelected : [])
56 .modifier(HiddenWhileEditing(state: editState, point: point))
57 }
58 private func fill(_ style: CellStyle?) -> Color { cellFill(style, scheme: scheme) }
59 private func ink(_ style: CellStyle?) -> Color {
60 if let hex = style?.k { return Color(hex: hex) }
61 if let h = style?.kh, let c = style?.kc { return .oklch(scheme == .dark ? 0.80 : 0.42, c, h) }
62 return .primary
63 }
64}
65
66/// Hides a cell from accessibility while its editor floats over it, so
67/// VoiceOver finds one element there, not two. A modifier, so that opening an
68/// editor re-runs this small body for each cell and never the cell's own.
69private struct HiddenWhileEditing: ViewModifier {
70 let state: SheetEditingState?
71 let point: Coordinate
72 func body(content: Content) -> some View {
73 content.accessibilityHidden(state?.cell == point)
74 }
75}
76
77/// Retry and Revert on a cell whose edit was not saved. Only such a cell
78/// carries a context menu and a tooltip, so the rest of the grid stays light.
79private struct NotSavedActions: ViewModifier {
80 let model: SheetModel
81 let point: Coordinate
82 let failed: Bool
83 func body(content: Content) -> some View {
84 if failed {
85 content
86 .contextMenu {
87 Button(sheetsMacString("Retry")) { model.retryWrites([point]) }
88 Button(sheetsMacString("Revert"), role: .destructive) { model.revertWrites([point]) }
89 }
90 .help(sheetsMacString("Not saved"))
91 } else {
92 content
93 }
94 }
95}
96
97/// A refused or unanswered edit: a small corner flag, like a comment marker,
98/// so the value stays readable and the rest of the sheet stays calm.
99struct SheetNotSavedMark: View {
100 var body: some View {
101 Path { path in
102 path.move(to: CGPoint(x: 0, y: 0))
103 path.addLine(to: CGPoint(x: 8, y: 0))
104 path.addLine(to: CGPoint(x: 8, y: 8))
105 path.closeSubpath()
106 }.fill(Color.red).frame(width: 8, height: 8).accessibilityHidden(true)
107 }
108}
109
110func cellFill(_ style: CellStyle?, scheme: ColorScheme) -> Color {
111 if let hex = style?.fx { return Color(hex: hex) }
112 if let h = style?.fh, let c = style?.fc { return .oklch(scheme == .dark ? 0.30 : 0.92, c, h) }
113 return Color.clear
114}
115
116/// Which cell has an open editor. Observed only by the editor overlay and the
117/// selection observer, never by the grid or its cells: opening an editor
118/// re-rendered every cell when this lived in the grid, which on a 200-column
119/// sheet kept the first keystroke from its field for most of a second.
120@MainActor @Observable final class SheetEditingState {
121 var cell: Coordinate?
122}
123
124#if os(macOS)
125/// The cell editor, floating over the grid at the edited cell.
126struct SheetEditorOverlay: View {
127 @Bindable var model: SheetModel
128 let state: SheetEditingState
129 let window: SheetGridWindow
130 let typeAhead: SheetTypeAhead
131 let frame: (Coordinate) -> CGRect
132 let end: () -> Void
133 @Environment(\.colorScheme) private var scheme
134 var body: some View {
135 if let point = state.cell {
136 let box = frame(point)
137 let style = model.styles[model.displayCell(point)?.f ?? ""]
138 // Never disabled by a save: saves are optimistic (SheetWrites.swift),
139 // so the field neither greys nor drops focus while one is in flight.
140 SheetCellEditor(text: $model.draft, enabled: model.mayWrite,
141 label: String(format: sheetsMacString("Edit %@"), point.ref),
142 typeAhead: typeAhead,
143 commit: { commit(point, right: $0) }, cancel: { model.discard(); end() })
144 .padding(.horizontal, 5)
145 .frame(width: box.width, height: box.height)
146 .background(cellFill(style, scheme: scheme))
147 .background(.background)
148 .overlay { Rectangle().strokeBorder(Color.accentColor, lineWidth: 2) }
149 .accessibilityLabel(String(format: sheetsMacString("Edit %@"), point.ref))
150 .modifier(SheetHeaderClip(window: window, top: box.minY))
151 .offset(x: box.minX, y: box.minY)
152 .id(point)
153 }
154 }
155 private func commit(_ point: Coordinate, right: Bool) -> Bool {
156 guard model.selection.start == point else { return false }
157 model.commit(moveRight: right)
158 guard !model.dirty else { return false }
159 end()
160 return true
161 }
162}
163#endif
164