| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import RastrilloApple |
| 4 | import RastrilloNative |
| 5 | import SwiftUI |
| 6 | |
| 7 | /// The app-wide Format inspector state (spec D1): open by default, one value |
| 8 | /// for every window, remembered across launches. |
| 9 | enum DocsInspectorState { |
| 10 | static let key = "docs.inspector.open" |
| 11 | static let defaultOpen = true |
| 12 | } |
| 13 | |
| 14 | /// Docs' own title area at the toolbar's leading edge (spec §1, header |
| 15 | /// contract): the document's title in 15pt semibold, and under it the §6 |
| 16 | /// subtitle. The system title is hidden but still set, so the Window menu, |
| 17 | /// Mission Control, window tabs and VoiceOver's window name are the title. |
| 18 | /// |
| 19 | /// Its own view, reading the model's title, access and sync status itself, |
| 20 | /// so none of those re-evaluates the body that hosts the text view. |
| 21 | @MainActor struct DocsTitleArea: View { |
| 22 | let model: DocsModel |
| 23 | let team: String? |
| 24 | @Binding var renaming: Bool |
| 25 | let beginRename: () -> Void |
| 26 | /// Commits the rename; false when the model refused it. |
| 27 | let finishRename: () -> Bool |
| 28 | |
| 29 | var body: some View { |
| 30 | // spacing-allow: the subtitle sits on the title's descender, as a |
| 31 | // window title and subtitle do; a step of the scale would split them. |
| 32 | VStack(alignment: .leading, spacing: 1) { |
| 33 | title |
| 34 | DocsSubtitleView(model: model, team: team) |
| 35 | } |
| 36 | .frame(minWidth: 120, maxWidth: 520, alignment: .leading) |
| 37 | .fixedSize(horizontal: false, vertical: true) |
| 38 | .accessibilityElement(children: .contain) |
| 39 | .accessibilityIdentifier("docs.document.header") |
| 40 | } |
| 41 | |
| 42 | /// A reader never gets an editable field, whatever `renaming` says. |
| 43 | static func showsField(renaming: Bool, access: DocsAccess) -> Bool { renaming && access == .writable } |
| 44 | |
| 45 | /// Esc: the title as it was. |
| 46 | private func cancelRename() { model.renameInput = nil; renaming = false } |
| 47 | |
| 48 | @ViewBuilder private var title: some View { |
| 49 | if Self.showsField(renaming: renaming, access: model.documentAccess) { |
| 50 | // An AppKit field: SwiftUI's focus does not reach into a toolbar |
| 51 | // item's hosting view, so a TextField there appears without the |
| 52 | // keyboard and never sees Esc. This one takes focus as it |
| 53 | // appears, commits on Return or focus loss, and reverts on Esc. |
| 54 | DocsRenameField(text: model.renameInput ?? model.detail?.title ?? "", |
| 55 | placeholder: String(localized: "docs.list.create.placeholder", bundle: DocsResources.bundle), |
| 56 | changed: { model.renameInput = $0 }, commit: finishRename, cancel: cancelRename) |
| 57 | .frame(minWidth: 180, maxWidth: 480) |
| 58 | // Write access ending mid-rename puts the title back. |
| 59 | .onChange(of: model.documentAccess) { _, access in if access != .writable { cancelRename() } } |
| 60 | } else { |
| 61 | let canWrite = model.detail?.can_write == true |
| 62 | Text(verbatim: model.detail?.title ?? " ") |
| 63 | .font(.system(size: 15, weight: .semibold)) |
| 64 | .foregroundStyle(OficinaPalette.text) |
| 65 | .lineLimit(1).truncationMode(.tail) |
| 66 | .accessibilityAddTraits(.isHeader) |
| 67 | .accessibilityIdentifier("docs.document.title") |
| 68 | .onTapGesture(count: 2) { if canWrite { beginRename() } } |
| 69 | .contextMenu { |
| 70 | if canWrite { |
| 71 | Button { beginRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) } |
| 72 | .keyboardShortcut("r", modifiers: [.command, .shift]) |
| 73 | } |
| 74 | } |
| 75 | .accessibilityActions { |
| 76 | if canWrite { |
| 77 | Button { beginRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) } |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | /// The header's trailing controls, 8pt apart (spec §1): the undo/redo pill |
| 85 | /// and the Format toggle for writers, then Share… for owners and members. |
| 86 | /// A reader gets none of them. |
| 87 | @MainActor struct DocsHeaderControls: View { |
| 88 | enum Part { case history, format, share } |
| 89 | let model: DocsModel |
| 90 | @Binding var inspectorOpen: Bool |
| 91 | var part: Part |
| 92 | let share: () -> Void |
| 93 | /// The document's origin: Share… waits while it is offline. nil: online. |
| 94 | var origin: URL? = nil |
| 95 | /// Where Share…'s popover hangs from (the window's; nil in snapshots). |
| 96 | var sharePopover: DocsSharePopover? = nil |
| 97 | |
| 98 | var body: some View { |
| 99 | let canWrite = model.documentAccess == .writable |
| 100 | let canShare = model.detail?.can_share == true && !model.isDraft && model.documentAccess != .unavailable |
| 101 | switch part { |
| 102 | case .history: |
| 103 | if canWrite { DocsUndoRedoPill(model: model).fixedSize() } |
| 104 | case .format: |
| 105 | if canWrite { |
| 106 | Toggle(isOn: $inspectorOpen) { |
| 107 | Label { Text("docs.editor.inspector.toggle", bundle: DocsResources.bundle) } icon: { Image(systemName: "pencil") } |
| 108 | } |
| 109 | .toggleStyle(.button) |
| 110 | .buttonStyle(DocsPillStyle(kind: inspectorOpen ? .toggledOn : .quiet)) |
| 111 | .help(Text(inspectorOpen ? "native.format.hide" : "native.format.show", bundle: DocsResources.bundle)) |
| 112 | .accessibilityIdentifier("docs.format.toggle") |
| 113 | } |
| 114 | case .share: |
| 115 | if canShare { |
| 116 | let offline = origin.map { model.connectivity.isOffline($0) } ?? false |
| 117 | Button(action: share) { Text("docs.share.action", bundle: DocsResources.bundle) } |
| 118 | .buttonStyle(DocsPillStyle(kind: .filled)) |
| 119 | // Offline it waits, and says why (spec §1, "When it is available"). |
| 120 | .disabled(offline) |
| 121 | .help(offline ? Text("native.share.offline", bundle: DocsResources.bundle) : Text("docs.share.action", bundle: DocsResources.bundle)) |
| 122 | .background { if let sharePopover { DocsShareAnchor(popover: sharePopover, activate: share) } } |
| 123 | .accessibilityIdentifier("docs.share") |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Undo and redo in one pill, a hairline between them, each enabled from |
| 130 | /// the projection's `canUndo`/`canRedo` (spec §1, item 1). |
| 131 | @MainActor struct DocsUndoRedoPill: View { |
| 132 | let model: DocsModel |
| 133 | var body: some View { |
| 134 | // The observed history, never the projection (S1a unobserves it). |
| 135 | let history = model.history |
| 136 | HStack(spacing: 0) { |
| 137 | button("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: history.canUndo) |
| 138 | Rectangle().fill(OficinaPalette.line).frame(width: 1, height: DocsSpacing.sp3) |
| 139 | button("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: history.canRedo) |
| 140 | } |
| 141 | .background(Capsule().fill(OficinaPalette.sunk)) |
| 142 | .overlay(Capsule().stroke(OficinaPalette.line, lineWidth: 1)) |
| 143 | .accessibilityElement(children: .contain) |
| 144 | .accessibilityLabel(Text("docs.editor.toolbar.history", bundle: DocsResources.bundle)) |
| 145 | } |
| 146 | private func button(_ key: String, icon: String, op: String, enabled: Bool) -> some View { |
| 147 | Button { |
| 148 | // Undo needs no rendered content: only the model's own check. |
| 149 | DocumentCommands(model: model, content: NSAttributedString()).perform(op) |
| 150 | } label: { |
| 151 | Image(systemName: icon) |
| 152 | .font(.system(size: 13, weight: .semibold)) |
| 153 | .flipsForRightToLeftLayoutDirection(true) |
| 154 | .frame(width: 30, height: 28) |
| 155 | .contentShape(Rectangle()) |
| 156 | } |
| 157 | .buttonStyle(.plain) |
| 158 | .foregroundStyle(OficinaPalette.text) |
| 159 | .opacity(enabled ? 1 : 0.35) |
| 160 | .disabled(!enabled) |
| 161 | .help(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)) |
| 162 | .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)) |
| 163 | .accessibilityIdentifier("docs." + op) |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// The header's pills (the web's I2 header): quiet, toggled on (accent-soft |
| 168 | /// with accent text) and the one filled accent pill. 28pt tall; they grow |
| 169 | /// with their label rather than truncate it (spec §9, long languages). |
| 170 | struct DocsPillStyle: ButtonStyle { |
| 171 | enum Kind { case quiet, toggledOn, filled } |
| 172 | let kind: Kind |
| 173 | @Environment(\.isEnabled) private var isEnabled |
| 174 | func makeBody(configuration: Configuration) -> some View { |
| 175 | let accent = OficinaPalette.accent(.docs) |
| 176 | configuration.label |
| 177 | .labelStyle(.titleAndIcon) |
| 178 | .font(.system(size: 13, weight: .semibold)) |
| 179 | .lineLimit(1) |
| 180 | .fixedSize() |
| 181 | .padding(.horizontal, DocsSpacing.sp3) |
| 182 | .frame(height: 28) |
| 183 | .foregroundStyle(kind == .filled ? OficinaPalette.onAccent : kind == .toggledOn ? accent : OficinaPalette.text) |
| 184 | .background { |
| 185 | switch kind { |
| 186 | case .filled: Capsule().fill(accent) |
| 187 | case .toggledOn: Capsule().fill(OficinaPalette.accentSoft(.docs)).overlay(Capsule().stroke(accent.opacity(0.3), lineWidth: 1)) |
| 188 | case .quiet: Capsule().fill(OficinaPalette.sunk).overlay(Capsule().stroke(OficinaPalette.line, lineWidth: 1)) |
| 189 | } |
| 190 | } |
| 191 | .opacity(configuration.isPressed ? 0.8 : isEnabled ? 1 : 0.5) |
| 192 | .contentShape(Capsule()) |
| 193 | } |
| 194 | } |
| 195 | #endif |
| 196 | |
| 197 | #if os(macOS) |
| 198 | /// The window's callouts under the header (spec §6, banners): No longer |
| 199 | /// available (row 1) with Close and, with changes unsent, Discard changes; |
| 200 | /// and today's `errorKey` text with Try again and Discard changes. Their own |
| 201 | /// view, so the text view's host does not read either. |
| 202 | @MainActor struct DocsDocumentCallouts: View { |
| 203 | let model: DocsModel |
| 204 | @Environment(\.locale) private var locale |
| 205 | let discard: () -> Void |
| 206 | /// Close (row 1): through the window's own close, so `DocsCloseGuard` |
| 207 | /// still asks about unsent changes. nil uses the window this view is in. |
| 208 | var close: (() -> Void)? = nil |
| 209 | @State private var closer = DocsWindowCloser() |
| 210 | /// The floating inspector shows: the callouts keep clear of it, centred |
| 211 | /// in the desk beside it rather than under it. |
| 212 | var inspectorShown = false |
| 213 | /// The account flow, as Settings' Sign in… opens it (the home window). |
| 214 | var signIn: () -> Void = {} |
| 215 | var body: some View { |
| 216 | VStack(spacing: DocsSpacing.sp2) { |
| 217 | // §6 rows 5 and 6: the session ended. Typing still reaches the |
| 218 | // outbox; signing in sends it. |
| 219 | if model.documentAccess != .unavailable, case .needsSignIn(let pending) = model.syncStatus { |
| 220 | let sync = NativeSyncStrings.kit |
| 221 | callout(Text(verbatim: pending > 0 ? sync.needsSignIn(pending) : DocsStrings(locale: locale)("native.subtitle.signedOut")), negative: true) { |
| 222 | Button { signIn() } label: { Text(verbatim: sync.signIn) } |
| 223 | } |
| 224 | } |
| 225 | if model.documentAccess == .unavailable { |
| 226 | callout(Text("native.unavailable.body", bundle: DocsResources.bundle), negative: true) { |
| 227 | Button { if let close { close() } else { closer.close() } } label: { Text("native.close", bundle: DocsResources.bundle) } |
| 228 | if model.hasUnsavedChanges { |
| 229 | Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) } |
| 230 | } |
| 231 | } |
| 232 | } else if let key = model.errorKey { |
| 233 | callout(Text(LocalizedStringKey(key), bundle: DocsResources.bundle), negative: false) { |
| 234 | Button { Task { await model.retry() } } label: { Text("native.retry", bundle: DocsResources.bundle) } |
| 235 | if model.hasUnsavedChanges { |
| 236 | Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) } |
| 237 | } |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | .padding(.top, DocsSpacing.sp3) |
| 242 | .frame(maxWidth: 560) |
| 243 | .frame(maxWidth: .infinity) |
| 244 | .padding(.leading, DocsDeskLayout.padding) |
| 245 | .padding(.trailing, inspectorShown ? DocsDeskLayout.reserve : DocsDeskLayout.padding) |
| 246 | .background { DocsWindowReader(closer: closer).frame(width: 0, height: 0) } |
| 247 | } |
| 248 | private func callout<Actions: View>(_ text: Text, negative: Bool, @ViewBuilder actions: () -> Actions) -> some View { |
| 249 | HStack(spacing: DocsSpacing.sp3) { |
| 250 | text.font(.callout).foregroundStyle(negative ? OficinaPalette.negative : OficinaPalette.text) |
| 251 | .fixedSize(horizontal: false, vertical: true) |
| 252 | Spacer(minLength: 8) |
| 253 | actions().controlSize(.small) |
| 254 | } |
| 255 | .padding(.horizontal, DocsSpacing.sp3).padding(.vertical, DocsSpacing.sp2) |
| 256 | .background(RoundedRectangle(cornerRadius: 10).fill(negative ? OficinaPalette.negativeSoft : OficinaPalette.surface)) |
| 257 | .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(OficinaPalette.line, lineWidth: 1)) |
| 258 | .shadow(color: .black.opacity(0.08), radius: 8, y: 3) |
| 259 | .accessibilityElement(children: .contain) |
| 260 | .accessibilityIdentifier(negative ? "docs.callout.negative" : "docs.callout.error") |
| 261 | } |
| 262 | } |
| 263 | #endif |
| 264 | |
| 265 | #if os(macOS) |
| 266 | /// Closes the window a view is in the way the close button does |
| 267 | /// (`performClose`), so the window's delegate (`DocsCloseGuard`) decides: |
| 268 | /// unsent changes are asked about, never dropped. |
| 269 | @MainActor final class DocsWindowCloser { |
| 270 | weak var window: NSWindow? |
| 271 | /// A window with a sheet still attached refuses `performClose` (it beeps |
| 272 | /// and stays). Delete…'s confirmation is such a sheet, and a fast server |
| 273 | /// answers while it is still going away (Fable on #178, finding 2), so |
| 274 | /// the close waits for the sheet to go first, for at most two seconds. |
| 275 | func close() { |
| 276 | guard let window else { return } |
| 277 | guard window.attachedSheet != nil else { window.performClose(nil); return } |
| 278 | Task { @MainActor [weak window] in |
| 279 | for _ in 0..<100 { |
| 280 | guard let window, window.attachedSheet != nil else { break } |
| 281 | try? await Task.sleep(for: .milliseconds(20)) |
| 282 | } |
| 283 | window?.performClose(nil) |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | struct DocsWindowReader: NSViewRepresentable { |
| 289 | let closer: DocsWindowCloser |
| 290 | func makeNSView(context: Context) -> ReaderView { let view = ReaderView(); view.closer = closer; return view } |
| 291 | func updateNSView(_ view: ReaderView, context: Context) { view.closer = closer; closer.window = view.window } |
| 292 | final class ReaderView: NSView { |
| 293 | weak var closer: DocsWindowCloser? |
| 294 | override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); closer?.window = window } |
| 295 | } |
| 296 | } |
| 297 | #endif |
| 298 | |
| 299 | /// One rename's commit rules (Fable on #169, finding 2). It is finished |
| 300 | /// only by a commit the model accepts, or by putting the title back: |
| 301 | /// - Return: commit; refused, the field stays with the error shown, and a |
| 302 | /// later Return or focus loss tries again. |
| 303 | /// - Focus loss: commit; refused, the title goes back as it was (the error |
| 304 | /// stays shown), so no field is left open behind the person's back. |
| 305 | /// - Esc: the title as it was. |
| 306 | @MainActor final class DocsRenameSession { |
| 307 | enum Outcome: Equatable { case committed, keepEditing, reverted, finished } |
| 308 | private let commit: () -> Bool |
| 309 | private let cancel: () -> Void |
| 310 | private(set) var isFinished = false |
| 311 | init(commit: @escaping () -> Bool, cancel: @escaping () -> Void) { self.commit = commit; self.cancel = cancel } |
| 312 | func returnPressed() -> Outcome { |
| 313 | guard !isFinished else { return .finished } |
| 314 | if commit() { isFinished = true; return .committed } |
| 315 | return .keepEditing |
| 316 | } |
| 317 | func focusLost() -> Outcome { |
| 318 | guard !isFinished else { return .finished } |
| 319 | isFinished = true |
| 320 | if commit() { return .committed } |
| 321 | cancel() |
| 322 | return .reverted |
| 323 | } |
| 324 | func escape() { |
| 325 | guard !isFinished else { return } |
| 326 | isFinished = true |
| 327 | cancel() |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | #if os(macOS) |
| 332 | /// The title's rename field (spec §1, "Rename in place"): Return or focus |
| 333 | /// loss commits through `model.commitRename()`, Esc reverts. |
| 334 | struct DocsRenameField: NSViewRepresentable { |
| 335 | let text: String |
| 336 | let placeholder: String |
| 337 | let changed: (String) -> Void |
| 338 | let commit: () -> Bool |
| 339 | let cancel: () -> Void |
| 340 | func makeCoordinator() -> Coordinator { Coordinator(self) } |
| 341 | func makeNSView(context: Context) -> NSTextField { |
| 342 | let field = FocusingField(string: text) |
| 343 | field.placeholderString = placeholder |
| 344 | field.isBordered = false |
| 345 | field.drawsBackground = false |
| 346 | field.focusRingType = .none |
| 347 | field.font = .systemFont(ofSize: 15, weight: .semibold) |
| 348 | field.lineBreakMode = .byTruncatingTail |
| 349 | field.cell?.isScrollable = true |
| 350 | field.delegate = context.coordinator |
| 351 | field.setAccessibilityIdentifier("docs.document.title") |
| 352 | field.setAccessibilityLabel(String(localized: "docs.document.rename", bundle: DocsResources.bundle)) |
| 353 | return field |
| 354 | } |
| 355 | func updateNSView(_ field: NSTextField, context: Context) { context.coordinator.parent = self } |
| 356 | @MainActor final class Coordinator: NSObject, NSTextFieldDelegate { |
| 357 | var parent: DocsRenameField |
| 358 | private lazy var session = DocsRenameSession(commit: { [unowned self] in self.parent.commit() }, cancel: { [unowned self] in self.parent.cancel() }) |
| 359 | init(_ parent: DocsRenameField) { self.parent = parent } |
| 360 | func controlTextDidChange(_ note: Notification) { |
| 361 | if let field = note.object as? NSTextField { parent.changed(field.stringValue) } |
| 362 | } |
| 363 | func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { |
| 364 | if selector == #selector(NSResponder.cancelOperation(_:)) { session.escape(); return true } |
| 365 | if selector == #selector(NSResponder.insertNewline(_:)) { _ = session.returnPressed(); return true } |
| 366 | return false |
| 367 | } |
| 368 | func controlTextDidEndEditing(_ note: Notification) { _ = session.focusLost() } |
| 369 | } |
| 370 | /// Takes the keyboard as soon as it is in a window, with the title selected. |
| 371 | final class FocusingField: NSTextField { |
| 372 | override func viewDidMoveToWindow() { |
| 373 | super.viewDidMoveToWindow() |
| 374 | guard let window else { return } |
| 375 | DispatchQueue.main.async { [weak self] in |
| 376 | guard let self, self.window === window else { return } |
| 377 | window.makeFirstResponder(self) |
| 378 | self.currentEditor()?.selectAll(nil) |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | #endif |
| 384 | |