// The input box on the database page (Spec 7, Cotton note 708fe4fa): the SAME // box a list and a record's page draw (`ComposerCard`), standing on the page's // foot. Here its words are kept as a thought in the database the window // shows, with whatever the "+" attached, and the chip in its row says which // database that is — a tap on it opens the Databases screen, the one way to // another database. // // The brain is the capture dock's (`DockModel`): the draft, dictation spliced // onto typed words, pictures and files on the draft, and the send through the // thought kind's own service. Nothing here writes; the receipt's Undo goes // through `ThoughtFiling`. import CottonKit import SwiftUI #if os(iOS) import UIKit #endif /// The box's sentences on the database page. enum HomeInputWords { static var placeholder: String { ShellLines.line("input", "home.placeholder") } static func kept(in name: String) -> String { ShellLines.line("input", "home.kept", ["name": "\(name)"]) } static var undone: String { ShellLines.line("input", "home.undone") } static var couldNotUndo: String { ShellLines.line("input", "home.could_not_undo") } static var cancel: String { ShellLines.line("input", "home.cancel") } } /// What a Home box's dock is mounted for (`HomeInput.dockMount`). struct DockMount: Hashable { /// The database shown (nil: not yet resolved). let shown: String? /// The capture service the dock writes through; nil while there is none. let capture: ObjectIdentifier? } struct HomeInput: View { let model: CaptureSurfaceModel /// The shown database's whole name on the chip, including the personal one. let databaseName: String? /// A thought was kept, or one was taken back: the page reads again. let onChanged: () -> Void /// The top-row microphone speaks on tap and raises this box on hold. /// FanRecord keeps the voice motor mounted without a control at the foot. var voice = false var typing: Binding? /// The fan's tiles, for a spoken "show …" (`SpokenHome`); empty on a grid. var fan: [(key: String, name: String)] = [] /// The tile a spoken "show …" turns the fan to. var show: Binding? /// The row of database caps stands over the record button /// (`DatabaseCapRow`): the thought field carries no cap of its own. var caps = false @Environment(\.cottonCapture) private var capture @Environment(\.theme) private var theme @Environment(\.cottonHaptics) private var haptics @Environment(ToastCenter.self) private var toasts @Environment(DatabasesModel.self) private var databases: DatabasesModel? @Environment(DatabaseScene.self) private var scene: DatabaseScene? @Environment(Navigator.self) private var navigator: Navigator? @Environment(\.tableDefinitions) private var definitions @Environment(\.cottonCore) private var core @Environment(\.dictationSource) private var dictation @State private var mounted: MountedDock? /// The dictation the dock listens with, kept across a change of database. @State private var listener: DictationModel? @Environment(\.scenePhase) private var scenePhase /// What the dock was mounted for: the database shown and the capture /// service it writes through (`DockMount`). @State private var mountedFor: DockMount? @State private var scoped: CaptureContext? @State private var sources = AttachmentSourceState() @State private var choosingSource = false @State private var kept: ThoughtFiled? @State private var undone = false @State private var busy = false /// The keyboard is up under the raised thought field: its control row /// goes with the fan and comes back with it. @State private var keyboardUp = false private var shown: (name: String, colour: CapColour) { DatabaseCap.shown(scene: scene, in: databases, name: databaseName, theme: theme) } var body: some View { if voice, typing?.wrappedValue == true { // Cancel is in the field's own row; nothing of the box draws // over the page. The keyboard comes up with the box. box .onAppear { mounted?.dock.focusComposer() } #if os(iOS) .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in keyboardUp = true } .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in keyboardUp = false } #endif } else if voice { VStack(spacing: 0) { if let dock = mounted?.dock { FanRecord( dock: dock, words: VoiceWords.reading(definitions), kept: kept, undone: undone, undo: undone || busy || kept == nil ? nil : { if let kept { Task { await takeBack(kept) } } }, onDismiss: { kept = nil }) } } .frame(height: 0) .frame(maxWidth: .infinity) .task(id: dockMount) { await mount() } // An empty list's add act raises the box to type: the dial is // the one input on the phone, and there is no other to focus. .onReceive(NotificationCenter.default.publisher(for: .cottonFocusInput)) { _ in typing?.wrappedValue = true } .onDisappear { mounted?.engine.release() } // Back in the foreground: the model is warmed again, so the first // tap after a while away is as quick as the rest. .onChange(of: scenePhase) { _, phase in guard phase == .active, let dock = mounted?.dock else { return } Task { await dock.prepareDictation() } } } else { box } } /// The box as Home's record button, when Home is a fan. func voiced( _ on: Bool, typing: Binding, fan: [(key: String, name: String)], show: Binding, caps: Bool ) -> HomeInput { var input = self input.voice = on input.typing = typing input.fan = on ? fan : [] input.show = show input.caps = on && caps return input } /// A spoken line's route, over what this box is drawn with now: built at /// every draw and handed to the send, never kept from the mount. private var homeVoice: HomeVoice { HomeVoice( definitions: definitions, fan: fan, choosable: caps ? DatabaseCapRow.caps(databases).compactMap(\.database).map { ($0.databaseId, $0.name) } : [], core: core, navigator: navigator, show: show, scene: scene, databases: databases) } /// The box raised from the record button to type. private var raised: Bool { voice && typing?.wrappedValue == true } /// The input box: the composer on the page's foot. private var box: some View { VStack(spacing: 8) { if choosingSource { // The "+" asks where from: the same menu every box offers. BoxAttachMenu(onChoose: choose) } if let dock = mounted?.dock { CaptureComposer( model: dock, placeholder: HomeInputWords.placeholder, identifier: "cap", onAdd: { choosingSource.toggle() }, addLabel: BoxAttach.label, chip: caps ? nil : ComposerChip( name: shown.name, colour: shown.colour, identifier: "bar-database", action: { scene?.openDatabases() }), share: ComposerGrowth.boxShare, sendsWhileSpeaking: true, runsSpokenCommand: homeVoice.run ) .cancelling({ typing?.wrappedValue = false }, rowHidden: raised && keyboardUp, when: raised) .keyboardStaysOnTap() } } .padding(.horizontal, ChromeKnobs.chromeSettingsMargin) .padding(.bottom, 8) .frame(maxWidth: .infinity) // The kept thought's receipt is handed up to the board, which hangs // it at the toast edge (the top), never above the box at the foot. .preference(key: HomeReceiptKey.self, value: keptReceipt) .attachmentSources( $sources, photosOnly: false, several: true, onPicked: { source in Task { await attach(source) } }, onRefused: { toasts.show($0, tone: .error) }) // One dock per database shown: a thought typed for one database is // never sent into the next. .task(id: dockMount) { await mount() } .onDisappear { mounted?.engine.release() } } /// What the dock is mounted for, and what its task is keyed on: the /// database shown AND the capture service. Keyed on the database alone, /// a capture service that arrived after Home was drawn (boot ready /// before the workspace id; the owner's id landing a read later) never /// mounted the dock, and the record button stayed away until a database /// switch and back (owner's phone, build 288). private var dockMount: DockMount { DockMount(shown: scene?.shownId, capture: capture.map(ObjectIdentifier.init)) } /// Where the box's thoughts go: the database the window shows — the one /// whose cap was chosen last — and nil for the personal one. static func destination(_ shownId: String?, in databases: DatabasesModel?) -> ShownDatabase { ShownDatabase(databases?.database(shownId).flatMap { $0.isPersonal ? nil : $0.id }) } /// The dock, writing into the database this window shows. private func mount() async { // The same database again (the page came back from a list or a // record): the dock stays, and with it the words not yet sent. let wanted = dockMount if let dock = mounted?.dock, mountedFor == wanted { await dock.prepareDictation() return } mounted?.engine.release() mounted = nil // No capture service yet (boot is ready before the workspace is // known): no dock — and the task runs again the moment it arrives, // because it is part of `dockMount`. guard let capture else { return } mountedFor = wanted let held = databases?.database(scene?.shownId) let destination = Self.destination(scene?.shownId, in: databases) let scoped = capture.scoped(to: destination) self.scoped = scoped let model = model let built = CaptureMount.mount( capture: scoped, vocabulary: model.vocabulary, hints: { await model.loadHints() }, haptics: haptics, toasts: toasts, dictation: dictation, engine: listener, onCaptured: { _ in } ) // ONE recogniser for this box's life, whichever database it writes // to: the raised field's mic stays warm. listener = built.engine let dock = built.dock dock.onCaptured = { created in // Sent: a fan Home puts the box down and the fan back. typing?.wrappedValue = false undone = false kept = ThoughtFiled( id: created["id"]?.string ?? "", text: dock.lastSent?.text ?? "", projectIds: dock.lastSent?.projectIds ?? [], database: held) onChanged() } mounted = built await dock.prepareDictation() await model.load() } private func choose(_ choice: AttachmentChoice) { choosingSource = false sources = BoxAttach.open(choice) } /// What the "+" picked, onto the draft; the staged copy goes once the /// store holds it. private func attach(_ source: AttachmentSource) async { defer { try? FileManager.default.removeItem(at: source.url) } guard let dock = mounted?.dock else { return } await dock.attach(file: source.url, mime: source.mime, kind: source.kind, filename: source.filename) } private func takeBack(_ thought: ThoughtFiled) async { guard let filing = (scoped ?? capture)?.filing else { return } busy = true defer { busy = false } do { try await filing.takeBack(thoughtId: thought.id) undone = true onChanged() } catch { toasts.show(HomeInputWords.couldNotUndo, tone: .error) } } } extension HomeInput { /// The kept thought's receipt while it stands: its sentence, its words, /// Undo (nil once undone or while busy) and Done. fileprivate var keptReceipt: HomeReceipt? { guard let kept else { return nil } return HomeReceipt( sentence: undone ? HomeInputWords.undone : HomeInputWords.kept(in: shown.name), words: kept.text, undo: undone || busy ? nil : { Task { await takeBack(kept) } }, onDismiss: { self.kept = nil }) } } /// A typed thought's receipt, handed up from the box to the board, which /// draws it at the toast edge (`receiptAtToastEdge`). struct HomeReceipt: Equatable, @unchecked Sendable { let sentence: String let words: String let undo: (() -> Void)? let onDismiss: () -> Void static func == (lhs: HomeReceipt, rhs: HomeReceipt) -> Bool { lhs.sentence == rhs.sentence && lhs.words == rhs.words && (lhs.undo == nil) == (rhs.undo == nil) } } struct HomeReceiptKey: PreferenceKey { static let defaultValue: HomeReceipt? = nil static func reduce(value: inout HomeReceipt?, nextValue: () -> HomeReceipt?) { value = value ?? nextValue() } } /// The receipt of a thought kept from the database page: the sentence of what /// happened at its head (never the kinds), the words under it, Undo and Done. struct HomeThoughtReceipt: View { let sentence: String let words: String /// Nil once undone, or while the undo is on its way. let undo: (() -> Void)? let onDismiss: () -> Void var body: some View { ReceiptFace(label: sentence, seed: "home-thought-\(words)", labelIdentifier: "thought-receipt-head") { VStack(alignment: .leading, spacing: 6) { ReceiptBody(title: words, explanation: nil) .accessibilityElement(children: .combine) .accessibilityIdentifier("thought-receipt-words") HStack(spacing: 16) { Spacer(minLength: 8) if let undo { PaperTypedButton(ThoughtWords.undo, size: 14, action: undo) .accessibilityIdentifier("thought-receipt-undo") } PaperTypedButton(ThoughtWords.done, size: 14, action: onDismiss) .accessibilityIdentifier("thought-receipt-dismiss") } } } .accessibilityElement(children: .contain) .accessibilityIdentifier("thought-receipt") } }