#if os(macOS) import AppKit import RastrilloApple import RastrilloNative import SwiftUI /// The app-wide Format inspector state (spec D1): open by default, one value /// for every window, remembered across launches. enum DocsInspectorState { static let key = "docs.inspector.open" static let defaultOpen = true } /// Docs' own title area at the toolbar's leading edge (spec §1, header /// contract): the document's title in 15pt semibold, and under it the §6 /// subtitle. The system title is hidden but still set, so the Window menu, /// Mission Control, window tabs and VoiceOver's window name are the title. /// /// Its own view, reading the model's title, access and sync status itself, /// so none of those re-evaluates the body that hosts the text view. @MainActor struct DocsTitleArea: View { let model: DocsModel let team: String? @Binding var renaming: Bool let beginRename: () -> Void /// Commits the rename; false when the model refused it. let finishRename: () -> Bool var body: some View { // spacing-allow: the subtitle sits on the title's descender, as a // window title and subtitle do; a step of the scale would split them. VStack(alignment: .leading, spacing: 1) { title DocsSubtitleView(model: model, team: team) } .frame(minWidth: 120, maxWidth: 520, alignment: .leading) .fixedSize(horizontal: false, vertical: true) .accessibilityElement(children: .contain) .accessibilityIdentifier("docs.document.header") } /// A reader never gets an editable field, whatever `renaming` says. static func showsField(renaming: Bool, access: DocsAccess) -> Bool { renaming && access == .writable } /// Esc: the title as it was. private func cancelRename() { model.renameInput = nil; renaming = false } @ViewBuilder private var title: some View { if Self.showsField(renaming: renaming, access: model.documentAccess) { // An AppKit field: SwiftUI's focus does not reach into a toolbar // item's hosting view, so a TextField there appears without the // keyboard and never sees Esc. This one takes focus as it // appears, commits on Return or focus loss, and reverts on Esc. DocsRenameField(text: model.renameInput ?? model.detail?.title ?? "", placeholder: String(localized: "docs.list.create.placeholder", bundle: DocsResources.bundle), changed: { model.renameInput = $0 }, commit: finishRename, cancel: cancelRename) .frame(minWidth: 180, maxWidth: 480) // Write access ending mid-rename puts the title back. .onChange(of: model.documentAccess) { _, access in if access != .writable { cancelRename() } } } else { let canWrite = model.detail?.can_write == true Text(verbatim: model.detail?.title ?? " ") .font(.system(size: 15, weight: .semibold)) .foregroundStyle(OficinaPalette.text) .lineLimit(1).truncationMode(.tail) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("docs.document.title") .onTapGesture(count: 2) { if canWrite { beginRename() } } .contextMenu { if canWrite { Button { beginRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) } .keyboardShortcut("r", modifiers: [.command, .shift]) } } .accessibilityActions { if canWrite { Button { beginRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) } } } } } } /// The header's trailing controls, 8pt apart (spec §1): the undo/redo pill /// and the Format toggle for writers, then Share… for owners and members. /// A reader gets none of them. @MainActor struct DocsHeaderControls: View { enum Part { case history, format, share } let model: DocsModel @Binding var inspectorOpen: Bool var part: Part let share: () -> Void /// The document's origin: Share… waits while it is offline. nil: online. var origin: URL? = nil /// Where Share…'s popover hangs from (the window's; nil in snapshots). var sharePopover: DocsSharePopover? = nil var body: some View { let canWrite = model.documentAccess == .writable let canShare = model.detail?.can_share == true && !model.isDraft && model.documentAccess != .unavailable switch part { case .history: if canWrite { DocsUndoRedoPill(model: model).fixedSize() } case .format: if canWrite { Toggle(isOn: $inspectorOpen) { Label { Text("docs.editor.inspector.toggle", bundle: DocsResources.bundle) } icon: { Image(systemName: "pencil") } } .toggleStyle(.button) .buttonStyle(DocsPillStyle(kind: inspectorOpen ? .toggledOn : .quiet)) .help(Text(inspectorOpen ? "native.format.hide" : "native.format.show", bundle: DocsResources.bundle)) .accessibilityIdentifier("docs.format.toggle") } case .share: if canShare { let offline = origin.map { model.connectivity.isOffline($0) } ?? false Button(action: share) { Text("docs.share.action", bundle: DocsResources.bundle) } .buttonStyle(DocsPillStyle(kind: .filled)) // Offline it waits, and says why (spec §1, "When it is available"). .disabled(offline) .help(offline ? Text("native.share.offline", bundle: DocsResources.bundle) : Text("docs.share.action", bundle: DocsResources.bundle)) .background { if let sharePopover { DocsShareAnchor(popover: sharePopover, activate: share) } } .accessibilityIdentifier("docs.share") } } } } /// Undo and redo in one pill, a hairline between them, each enabled from /// the projection's `canUndo`/`canRedo` (spec §1, item 1). @MainActor struct DocsUndoRedoPill: View { let model: DocsModel var body: some View { // The observed history, never the projection (S1a unobserves it). let history = model.history HStack(spacing: 0) { button("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: history.canUndo) Rectangle().fill(OficinaPalette.line).frame(width: 1, height: DocsSpacing.sp3) button("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: history.canRedo) } .background(Capsule().fill(OficinaPalette.sunk)) .overlay(Capsule().stroke(OficinaPalette.line, lineWidth: 1)) .accessibilityElement(children: .contain) .accessibilityLabel(Text("docs.editor.toolbar.history", bundle: DocsResources.bundle)) } private func button(_ key: String, icon: String, op: String, enabled: Bool) -> some View { Button { // Undo needs no rendered content: only the model's own check. DocumentCommands(model: model, content: NSAttributedString()).perform(op) } label: { Image(systemName: icon) .font(.system(size: 13, weight: .semibold)) .flipsForRightToLeftLayoutDirection(true) .frame(width: 30, height: 28) .contentShape(Rectangle()) } .buttonStyle(.plain) .foregroundStyle(OficinaPalette.text) .opacity(enabled ? 1 : 0.35) .disabled(!enabled) .help(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)) .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)) .accessibilityIdentifier("docs." + op) } } /// The header's pills (the web's I2 header): quiet, toggled on (accent-soft /// with accent text) and the one filled accent pill. 28pt tall; they grow /// with their label rather than truncate it (spec §9, long languages). struct DocsPillStyle: ButtonStyle { enum Kind { case quiet, toggledOn, filled } let kind: Kind @Environment(\.isEnabled) private var isEnabled func makeBody(configuration: Configuration) -> some View { let accent = OficinaPalette.accent(.docs) configuration.label .labelStyle(.titleAndIcon) .font(.system(size: 13, weight: .semibold)) .lineLimit(1) .fixedSize() .padding(.horizontal, DocsSpacing.sp3) .frame(height: 28) .foregroundStyle(kind == .filled ? OficinaPalette.onAccent : kind == .toggledOn ? accent : OficinaPalette.text) .background { switch kind { case .filled: Capsule().fill(accent) case .toggledOn: Capsule().fill(OficinaPalette.accentSoft(.docs)).overlay(Capsule().stroke(accent.opacity(0.3), lineWidth: 1)) case .quiet: Capsule().fill(OficinaPalette.sunk).overlay(Capsule().stroke(OficinaPalette.line, lineWidth: 1)) } } .opacity(configuration.isPressed ? 0.8 : isEnabled ? 1 : 0.5) .contentShape(Capsule()) } } #endif #if os(macOS) /// The window's callouts under the header (spec §6, banners): No longer /// available (row 1) with Close and, with changes unsent, Discard changes; /// and today's `errorKey` text with Try again and Discard changes. Their own /// view, so the text view's host does not read either. @MainActor struct DocsDocumentCallouts: View { let model: DocsModel @Environment(\.locale) private var locale let discard: () -> Void /// Close (row 1): through the window's own close, so `DocsCloseGuard` /// still asks about unsent changes. nil uses the window this view is in. var close: (() -> Void)? = nil @State private var closer = DocsWindowCloser() /// The floating inspector shows: the callouts keep clear of it, centred /// in the desk beside it rather than under it. var inspectorShown = false /// The account flow, as Settings' Sign in… opens it (the home window). var signIn: () -> Void = {} var body: some View { VStack(spacing: DocsSpacing.sp2) { // §6 rows 5 and 6: the session ended. Typing still reaches the // outbox; signing in sends it. if model.documentAccess != .unavailable, case .needsSignIn(let pending) = model.syncStatus { let sync = NativeSyncStrings.kit callout(Text(verbatim: pending > 0 ? sync.needsSignIn(pending) : DocsStrings(locale: locale)("native.subtitle.signedOut")), negative: true) { Button { signIn() } label: { Text(verbatim: sync.signIn) } } } if model.documentAccess == .unavailable { callout(Text("native.unavailable.body", bundle: DocsResources.bundle), negative: true) { Button { if let close { close() } else { closer.close() } } label: { Text("native.close", bundle: DocsResources.bundle) } if model.hasUnsavedChanges { Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) } } } } else if let key = model.errorKey { callout(Text(LocalizedStringKey(key), bundle: DocsResources.bundle), negative: false) { Button { Task { await model.retry() } } label: { Text("native.retry", bundle: DocsResources.bundle) } if model.hasUnsavedChanges { Button(role: .destructive) { discard() } label: { Text("native.discard.action", bundle: DocsResources.bundle) } } } } } .padding(.top, DocsSpacing.sp3) .frame(maxWidth: 560) .frame(maxWidth: .infinity) .padding(.leading, DocsDeskLayout.padding) .padding(.trailing, inspectorShown ? DocsDeskLayout.reserve : DocsDeskLayout.padding) .background { DocsWindowReader(closer: closer).frame(width: 0, height: 0) } } private func callout(_ text: Text, negative: Bool, @ViewBuilder actions: () -> Actions) -> some View { HStack(spacing: DocsSpacing.sp3) { text.font(.callout).foregroundStyle(negative ? OficinaPalette.negative : OficinaPalette.text) .fixedSize(horizontal: false, vertical: true) Spacer(minLength: 8) actions().controlSize(.small) } .padding(.horizontal, DocsSpacing.sp3).padding(.vertical, DocsSpacing.sp2) .background(RoundedRectangle(cornerRadius: 10).fill(negative ? OficinaPalette.negativeSoft : OficinaPalette.surface)) .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(OficinaPalette.line, lineWidth: 1)) .shadow(color: .black.opacity(0.08), radius: 8, y: 3) .accessibilityElement(children: .contain) .accessibilityIdentifier(negative ? "docs.callout.negative" : "docs.callout.error") } } #endif #if os(macOS) /// Closes the window a view is in the way the close button does /// (`performClose`), so the window's delegate (`DocsCloseGuard`) decides: /// unsent changes are asked about, never dropped. @MainActor final class DocsWindowCloser { weak var window: NSWindow? /// A window with a sheet still attached refuses `performClose` (it beeps /// and stays). Delete…'s confirmation is such a sheet, and a fast server /// answers while it is still going away (Fable on #178, finding 2), so /// the close waits for the sheet to go first, for at most two seconds. func close() { guard let window else { return } guard window.attachedSheet != nil else { window.performClose(nil); return } Task { @MainActor [weak window] in for _ in 0..<100 { guard let window, window.attachedSheet != nil else { break } try? await Task.sleep(for: .milliseconds(20)) } window?.performClose(nil) } } } struct DocsWindowReader: NSViewRepresentable { let closer: DocsWindowCloser func makeNSView(context: Context) -> ReaderView { let view = ReaderView(); view.closer = closer; return view } func updateNSView(_ view: ReaderView, context: Context) { view.closer = closer; closer.window = view.window } final class ReaderView: NSView { weak var closer: DocsWindowCloser? override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); closer?.window = window } } } #endif /// One rename's commit rules (Fable on #169, finding 2). It is finished /// only by a commit the model accepts, or by putting the title back: /// - Return: commit; refused, the field stays with the error shown, and a /// later Return or focus loss tries again. /// - Focus loss: commit; refused, the title goes back as it was (the error /// stays shown), so no field is left open behind the person's back. /// - Esc: the title as it was. @MainActor final class DocsRenameSession { enum Outcome: Equatable { case committed, keepEditing, reverted, finished } private let commit: () -> Bool private let cancel: () -> Void private(set) var isFinished = false init(commit: @escaping () -> Bool, cancel: @escaping () -> Void) { self.commit = commit; self.cancel = cancel } func returnPressed() -> Outcome { guard !isFinished else { return .finished } if commit() { isFinished = true; return .committed } return .keepEditing } func focusLost() -> Outcome { guard !isFinished else { return .finished } isFinished = true if commit() { return .committed } cancel() return .reverted } func escape() { guard !isFinished else { return } isFinished = true cancel() } } #if os(macOS) /// The title's rename field (spec §1, "Rename in place"): Return or focus /// loss commits through `model.commitRename()`, Esc reverts. struct DocsRenameField: NSViewRepresentable { let text: String let placeholder: String let changed: (String) -> Void let commit: () -> Bool let cancel: () -> Void func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSTextField { let field = FocusingField(string: text) field.placeholderString = placeholder field.isBordered = false field.drawsBackground = false field.focusRingType = .none field.font = .systemFont(ofSize: 15, weight: .semibold) field.lineBreakMode = .byTruncatingTail field.cell?.isScrollable = true field.delegate = context.coordinator field.setAccessibilityIdentifier("docs.document.title") field.setAccessibilityLabel(String(localized: "docs.document.rename", bundle: DocsResources.bundle)) return field } func updateNSView(_ field: NSTextField, context: Context) { context.coordinator.parent = self } @MainActor final class Coordinator: NSObject, NSTextFieldDelegate { var parent: DocsRenameField private lazy var session = DocsRenameSession(commit: { [unowned self] in self.parent.commit() }, cancel: { [unowned self] in self.parent.cancel() }) init(_ parent: DocsRenameField) { self.parent = parent } func controlTextDidChange(_ note: Notification) { if let field = note.object as? NSTextField { parent.changed(field.stringValue) } } func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { if selector == #selector(NSResponder.cancelOperation(_:)) { session.escape(); return true } if selector == #selector(NSResponder.insertNewline(_:)) { _ = session.returnPressed(); return true } return false } func controlTextDidEndEditing(_ note: Notification) { _ = session.focusLost() } } /// Takes the keyboard as soon as it is in a window, with the title selected. final class FocusingField: NSTextField { override func viewDidMoveToWindow() { super.viewDidMoveToWindow() guard let window else { return } DispatchQueue.main.async { [weak self] in guard let self, self.window === window else { return } window.makeFirstResponder(self) self.currentEditor()?.selectAll(nil) } } } } #endif