// 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`.importCottonKitimportSwiftUI#if os(iOS)import UIKit#endif/// The box's sentences on the database page.enumHomeInputWords {staticvar placeholder: String { ShellLines.line("input", "home.placeholder") }staticfunc kept(in name: String) -> String { ShellLines.line("input", "home.kept", ["name": "\(name)"]) }staticvar undone: String { ShellLines.line("input", "home.undone") }staticvar couldNotUndo: String { ShellLines.line("input", "home.could_not_undo") }staticvar cancel: String { ShellLines.line("input", "home.cancel") }}/// What a Home box's dock is mounted for (`HomeInput.dockMount`).structDockMount: 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?}structHomeInput: 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 = falsevar typing: Binding<Bool>?/// 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<String?>?/// 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) privatevar capture @Environment(\.theme) privatevar theme @Environment(\.cottonHaptics) privatevar haptics @Environment(ToastCenter.self) privatevar toasts @Environment(DatabasesModel.self) privatevar databases: DatabasesModel? @Environment(DatabaseScene.self) privatevar scene: DatabaseScene? @Environment(Navigator.self) privatevar navigator: Navigator? @Environment(\.tableDefinitions) privatevar definitions @Environment(\.cottonCore) privatevar core @Environment(\.dictationSource) privatevar dictation @State privatevar mounted: MountedDock?/// The dictation the dock listens with, kept across a change of database. @State privatevar listener: DictationModel? @Environment(\.scenePhase) privatevar scenePhase/// What the dock was mounted for: the database shown and the capture/// service it writes through (`DockMount`). @State privatevar mountedFor: DockMount? @State privatevar scoped: CaptureContext? @State privatevar sources = AttachmentSourceState() @State privatevar choosingSource = false @State privatevar kept: ThoughtFiled? @State privatevar undone = false @State privatevar busy = false/// The keyboard is up under the raised thought field: its control row/// goes with the fan and comes back with it. @State privatevar keyboardUp = falseprivatevar shown: (name: String, colour: CapColour) {DatabaseCap.shown(scene: scene, in: databases, name: databaseName, theme: theme) }var body: someView {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 } elseif voice { VStack(spacing: 0) {iflet dock = mounted?.dock {FanRecord( dock: dock, words: VoiceWords.reading(definitions), kept: kept, undone: undone, undo: undone || busy || kept == nil ? nil : { iflet 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 inguard 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<Bool>, fan: [(key: String, name: String)], show: Binding<String?>, caps: Bool ) -> HomeInput {var input = self input.voice = on input.typing = typing input.fan = on ? fan : [] input.show = show input.caps = on && capsreturn 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.privatevar 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.privatevar raised: Bool { voice && typing?.wrappedValue == true }/// The input box: the composer on the page's foot.privatevar box: someView { VStack(spacing: 8) {if choosingSource {// The "+" asks where from: the same menu every box offers.BoxAttachMenu(onChoose: choose) }iflet 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 inTask { 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).privatevar 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.staticfunc 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.privatefunc 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 = dockMountiflet 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`.guardlet capture else { return } mountedFor = wantedlet held = databases?.database(scene?.shownId)let destination = Self.destination(scene?.shownId, in: databases)let scoped = capture.scoped(to: destination)self.scoped = scopedlet model = modellet 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.enginelet 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 = builtawait dock.prepareDictation()await model.load() }privatefunc choose(_ choice: AttachmentChoice) { choosingSource = false sources = BoxAttach.open(choice) }/// What the "+" picked, onto the draft; the staged copy goes once the/// store holds it.privatefunc attach(_ source: AttachmentSource) async {defer { try? FileManager.default.removeItem(at: source.url) }guardlet dock = mounted?.dock else { return }await dock.attach(file: source.url, mime: source.mime, kind: source.kind, filename: source.filename) }privatefunc takeBack(_ thought: ThoughtFiled) async {guardlet filing = (scoped ?? capture)?.filing else { return } busy = truedefer { busy = false }do {tryawait filing.takeBack(thoughtId: thought.id) undone = true onChanged() } catch { toasts.show(HomeInputWords.couldNotUndo, tone: .error) } }}extensionHomeInput {/// The kept thought's receipt while it stands: its sentence, its words,/// Undo (nil once undone or while busy) and Done.fileprivatevar keptReceipt: HomeReceipt? {guardlet kept else { returnnil }returnHomeReceipt( 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`).structHomeReceipt: Equatable, @unchecked Sendable {let sentence: Stringlet words: Stringlet undo: (() -> Void)?let onDismiss: () -> Voidstaticfunc == (lhs: HomeReceipt, rhs: HomeReceipt) -> Bool { lhs.sentence == rhs.sentence && lhs.words == rhs.words && (lhs.undo == nil) == (rhs.undo == nil) }}structHomeReceiptKey: PreferenceKey {staticlet defaultValue: HomeReceipt? = nilstaticfunc reduce(value: inoutHomeReceipt?, 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.structHomeThoughtReceipt: View {let sentence: Stringlet words: String/// Nil once undone, or while the undo is on its way.let undo: (() -> Void)?let onDismiss: () -> Voidvar body: someView {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)iflet 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") }}