Cotton code
478 lines · 21.2 KB · SwiftRaw
// CAPTURE MODE — the dock, mounted on a surface of its own.//// Design 2026-09-13 §4.3 (D5, D6): capture happens on Home, in place. A tap on// the New thought pill clears Home's body and draws THIS — a close circle// top-right, the words growing from the foot, and the one control row the// composer card already has. Done keeps the thought and returns to Home; ✕// discards it. One thought, one tap in, one tap out. Nothing from a previous// thought is drawn here; the Done for you row on Home is the receipt.//// **This is the dock's mounting logic, lifted out of `/thoughts`.** The chat// used to be the dock's one host: it built the recogniser and the engine on// arrival, built a `DockModel` over the app's `CaptureContext`, supplied the// `#`/`@` vocabulary off its own read and the voice dictionary as bias terms,// re-read when a capture landed, focused the pill on `?compose=1` and released// the microphone with the screen. Every one of those is here now, and the chat// mounts its dock through the same `CaptureMount.mount` so the two cannot// drift while both exist (lane D turns the chat into a list and drops its dock).//// **Filing goes through the SAME path the chat's dock uses** — `DockModel.send`// over `CaptureContext.service`, the plan-bandless dock, the same fan. Nothing// about what a capture IS changed; only where the card is drawn.//// ## Two hosts, one start//// `start` says how the surface opens: `.listening` starts the engine the moment// the dock is mounted (the pill's tap — "you are being listened to"); `.typing`// raises the keyboard instead (the long-press menu's "Type instead", the Mac's// ⌘N). The keyboard disc on the recording row lands the words heard so far and// switches to typing without leaving the surface (`DockModel.switchToTyping`).//// ## What the surface owes its host//// `onKept` fires when a capture LANDED (`DockModel.onCaptured`) — the host// takes the surface down. `onDiscarded` fires from the close circle, and from// the `+` fan: a row chosen there pushes a creation screen, and a capture// surface left open under it would be a second thing to close on the way back.// The engine is released in `onDisappear` whoever took the surface down, so// the microphone always goes back with it.//// ## Pictures//// Two of the fan's rows do NOT leave: Picture and Camera put a picture on the// thought being written, so this surface raises the photo library or the// camera over itself and hands what comes back to `DockModel.attach(file:…)`.// The pickers are the note editor's own (`MediaStaging`, `CameraPicker`,// `Camera.refusal`) — one way to pick a picture in this app, whichever// record it lands on.//// A picture can also ARRIVE: the share sheet files a shared photo and lands// here carrying it (`ShareIntake.swift` branch 2). The navigator holds it// (`Navigator.waitingPicture`) until a mounted dock takes it — on arrival, or// the moment it lands if the surface is already up — for both hosts, since// the Mac's page column mounts this same surface.import CottonKitimport PhotosUIimport SwiftUI// `CaptureStart` — how capture mode opens — is the navigator's// (`Boot/Navigator.swift`): `navigator.open(route, start:)` sets// `navigator.capture`, the host draws this surface while it is non-nil, and// the start is honoured ONCE, on the surface's arrival.// MARK: - The model/// What the surface needs to know that the environment does not carry: the/// `#`/`@` vocabulary, the voice dictionary, and today's key for the fan.////// The vocabulary comes off `read.thoughts` — the same read the chat supplied/// it from, because it is the one read that answers the active projects AND the/// people together. It is asked ONCE per surface, on arrival, through a/// `ScreenRead` rather than the core itself: this model is built on the/// scaffold's one read shape and holds no core of its own/// (`ScaffoldSweepTests`' ledger of hand-built models only ever shrinks). The/// dictionary arrives the same way — as the ONE call it is, handed in.@MainActor@Observablefinal class CaptureSurfaceModel {    /// The `#` / `@` lists the dock completes against, shaped by    /// `DockVocabulary`'s own rules (active projects only, people whole).    let vocabulary = DockVocabulary()    /// The voice dictionary, as the recogniser's bias list. Read once on    /// arrival; the dock reads it at the mic tap through a closure.    private(set) var hints = DictationHints()    /// The fan's Event row anchors on this day. Read on arrival, not on every    /// redraw — a surface is a minute long and never straddles a midnight    /// anybody would notice.    private(set) var now: Date    private let read: ScreenRead    private let dictionary: @MainActor () async -> DictationHints    private let calendar: Calendar    /// - Parameters:    ///   - read: `read.thoughts`, as a `ScreenRead` — the host builds it over    ///     the core it has (`ScreenRead(core:read:families:)`).    ///   - dictionary: the voice dictionary's terms — `VoiceBias.hints(core:)`    ///     at the host, `{ [] }` in a test.    init(        read: ScreenRead,        dictionary: @escaping @MainActor () async -> DictationHints,        calendar: Calendar = .current,        now: Date = Date()    ) {        self.read = read        self.dictionary = dictionary        self.calendar = calendar        self.now = now    }    /// The name of the read the host builds for this model.    static let readName = "thoughts"    /// The day key (`YYYY-MM-DD`) the fan's Event row anchors on.    var todayKey: String { JournalStreak.dayKey(now, calendar: calendar) }    /// The vocabulary, off the one read that carries both halves. A failed    /// read leaves the lists empty: the dock then offers no completions and    /// files the words exactly as typed, which is a capture with no chips    /// rather than no capture.    func load() async {        await read.load()        if let answer = read.value {            vocabulary.supply(thoughtsRead: answer)        }    }    /// Refresh at the microphone tap, before the recogniser opens.    @discardableResult    func loadHints() async -> DictationHints {        hints = await dictionary()        return hints    }}extension DockVocabulary {    /// The `#`/`@` lists off `read.thoughts`' answer — `projects` with their    /// status (archived ones are dropped by `supply`) and `people` whole. The    /// ONE reading of that shape, shared by the chat and the capture surface.    func supply(thoughtsRead answer: JSONValue) {        supply(            projects: answer.list("projects").map {                VocabularyProject(                    id: $0.text("id") ?? "",                    name: $0.text("name") ?? "",                    status: $0.text("status") ?? "",                    slug: $0.text("slug")                )            },            people: answer.list("people").map {                VocabularyPerson(id: $0.text("id") ?? "", name: $0.text("fullName") ?? "")            }        )    }}// MARK: - Mounting the dock/// A dock and the engine under it, built together — the pair every host holds.struct MountedDock {    let dock: DockModel    let engine: DictationModel}/// What a box's dock listens with, when it is not the system's recogniser/// (`DictationModel.live`): the Home preview hands a scripted one, because a/// simulator has no speech model and a recording must still show a spoken/// line going where it goes.struct DictationSource: Sendable {    let make: @MainActor @Sendable () -> DictationModel}private struct DictationSourceKey: EnvironmentKey {    static let defaultValue: DictationSource? = nil}extension EnvironmentValues {    var dictationSource: DictationSource? {        get { self[DictationSourceKey.self] }        set { self[DictationSourceKey.self] = newValue }    }}enum CaptureMount {    /// Build the dock the way the chat always has: a fresh recogniser (which    /// opens the audio stack, so this runs in `.task`, never in an `init` —    /// `CapabilityGateSweepTests` holds the line), the engine over it, and a    /// `DockModel` writing through the app's capture service with the host's    /// vocabulary, dictionary and receipt.    ///    /// `onCaptured` is the host's receipt: the chat re-reads its transcript,    /// the capture surface goes away.    @MainActor    static func mount(        capture: CaptureContext,        vocabulary: DockVocabulary,        hints: @escaping @MainActor () async -> DictationHints,        haptics: any Haptics,        toasts: ToastCenter,        dictation: DictationSource? = nil,        engine kept: DictationModel? = nil,        onCaptured: @escaping (JSONValue) -> Void    ) -> MountedDock {        let engine = kept ?? dictation?.make() ?? DictationModel.live()        let dock = DockModel(            place: .page,            captures: capture.service,            media: capture.media,            dictation: engine,            vocabulary: vocabulary,            haptics: haptics,            toasts: toasts,            hints: hints        )        dock.onCaptured = onCaptured        return MountedDock(dock: dock, engine: engine)    }}// MARK: - The surfacestruct CaptureSurface: View {    @Environment(\.theme) private var theme    static var typeInstead: String { ShellLines.line("capture", "composer.type_instead") }    private let model: CaptureSurfaceModel    private let start: CaptureStart    /// A capture LANDED: what it was and where it went, for the receipt.    private let onKept: (ThoughtFiled) -> Void    private let onDiscarded: () -> Void    /// The dock's brain and its engine, built on ARRIVAL for the note editor's    /// reason: the real recogniser opens an audio engine the moment it exists,    /// and a view's `init` runs wherever a `View` value is described. `nil`    /// below the gate (no `CaptureContext`), and then no card is drawn.    @State private var mounted: MountedDock?    /// The start is honoured ONCE. `.task` can run again on a re-created    /// view, and a second start would open a second dictation.    @State private var started = false    /// The photo library is up — the fan's Picture row.    @State private var pickingPhoto = false    @State private var photoPick: PhotosPickerItem?    /// The camera is up — the fan's Camera row.    @State private var takingPhoto = false    @Environment(\.cottonCapture) private var capture    @Environment(\.cottonCapabilities) private var capabilities    @Environment(\.cottonHaptics) private var haptics    @Environment(ToastCenter.self) private var toasts    @Environment(Navigator.self) private var navigator    init(        model: CaptureSurfaceModel,        start: CaptureStart,        onKept: @escaping (ThoughtFiled) -> Void,        onDiscarded: @escaping () -> Void    ) {        self.model = model        self.start = start        self.onKept = onKept        self.onDiscarded = onDiscarded    }    var body: some View {        ZStack(alignment: .top) {            // The page ground the paper kit stands on — the input sheet is            // cream paper now, and reads as paper against it. While the            // microphone is open the screen dims and the words appear            // (0a22168c §4: "you are being listened to").            PageGroundFill().ignoresSafeArea()            Color.black                .opacity(mounted?.dock.isDictationLive == true ? 0.35 : 0)                .ignoresSafeArea()                .allowsHitTesting(false)                .animation(.easeInOut(duration: 0.25), value: mounted?.dock.isDictationLive == true)            VStack(spacing: 0) {                HStack {                    Spacer(minLength: 0)                    // The sheet's own close — the same circle wearing an X,                    // top-right (`Chrome/NavCircle.swift`).                    NavCircle(                        symbol: Glyph.symbol("x") ?? "xmark",                        label: ShellLines.line("capture", "composer.close"),                        action: onDiscarded                    )                    .accessibilityIdentifier("capture-close")                }                .padding(.horizontal, ChromeKnobs.chromeSettingsMargin)                .frame(height: CaptureSurfaceKnobs.chromeScreenBarHeight)                // The words grow from the FOOT: everything above the card is                // air, and the card takes the space upward as the thought                // lengthens (`ComposerGrowth`).                Spacer(minLength: 0)                if let mounted {                    // Listening: a visible "Type instead" above the words                    // (0a22168c §4), beside the keyboard disc on the row.                    if mounted.dock.isDictationLive {                        PaperTypedButton(CaptureSurface.typeInstead, size: 15) {                            Task { await mounted.dock.switchToTyping() }                        }                        .padding(.bottom, 14)                        .accessibilityIdentifier("capture-type-instead")                    }                    // The kind hints, over the sheet: what the words look                    // like so far, the guess underlined (`CaptureKindGuess`).                    CaptureKindHints(text: mounted.dock.displayText)                        .padding(.horizontal, ChromeKnobs.chromeSettingsMargin + 6)                        .padding(.bottom, 8)                    // The dock, as a plain view at the foot of a column that                    // already ends at the keyboard — NOT `.dockShell`, which                    // would inset it a second time (`DockShell.swift`'s header).                    DockShell {                        CaptureDock(                            model: mounted.dock,                            today: model.todayKey,                            identifier: "capture-dock",                            offersTypingSwitch: true,                            offersPictures: true,                            onChoose: choose                        )                    }                    // Its IDEAL height, never a share of the column's — the                    // chat's reason, kept: a bounded card in a column with a                    // spacer is offered the spare column.                    .fixedSize(horizontal: false, vertical: true)                }            }            // THIS column is the column the card grows into — the screen minus            // the keyboard, measured rather than assumed.            .composerColumn()        }        .task {            // Once, on arrival. `@State` survives every redraw, so a second            // recogniser is never built for the same surface.            if mounted == nil, let capture {                let model = model                let built = CaptureMount.mount(                    capture: capture,                    vocabulary: model.vocabulary,                    hints: { await model.loadHints() },                    haptics: haptics,                    toasts: toasts,                    onCaptured: { _ in }                )                // A capture LANDED: the surface's whole job is done, and the                // host's receipt says what it was and where it went — the                // words and the projects the chip aimed it at (`lastSent`).                let dock = built.dock                dock.onCaptured = { created in                    onKept(ThoughtFiled(                        id: created["id"]?.string ?? "",                        text: dock.lastSent?.text ?? "",                        projectIds: dock.lastSent?.projectIds ?? []))                }                mounted = built            }            // A shared picture waiting for this surface goes on the draft            // BEFORE the reads below, so it is on screen with the card.            takeWaitingPicture()            await model.load()            // NOT aimed at the open project: a thought always goes into the            // personal database first, whatever page it was spoken on, so a            // mistake is never visible to anyone else (0a22168c §4); the            // receipt offers the move. Choosing a project with the chip wins.            guard !started, let mounted else { return }            started = true            switch start {            case .listening: await mounted.dock.startDictation()            case .typing: mounted.dock.focusComposer()            }        }        // A picture shared in while the surface is already up.        .onChange(of: navigator.waitingPicture) { _, _ in takeWaitingPicture() }        .photosPicker(isPresented: $pickingPhoto, selection: $photoPick, matching: .images)        .onChange(of: photoPick) { _, chosen in            // Cleared FIRST so the same photograph picked twice in a row still            // fires — `onChange` sees a value, not an event (the note editor's            // reason, kept).            photoPick = nil            guard let chosen else { return }            Task { await attachPicked(chosen) }        }        .fullScreenCover(isPresented: $takingPhoto) {            CameraPicker(                onTaken: { url in                    takingPhoto = false                    Task { await attachTaken(url) }                },                onCancelled: { takingPhoto = false }            )        }        // The microphone goes back with the surface — whoever took it down.        .onDisappear { mounted?.engine.release() }        // **The surface says which ground it stands on.** `PageGroundFill`        // reads `\.cottonPageGround`, whose default is `.ground` — `#FFFFFF`,        // the token no paper screen has stood on since phase 20. On the phone        // that never showed: capture is drawn inside HOME, and Home declares        // `.groundMuted` above it. The Mac draws the surface in the page        // column, over the boot environment, where nothing had declared one —        // so the whole column behind the capture bar was white (the walk's        // re-shoot, walk-13-v2). A surface that carries its own ground reads        // as paper wherever it is mounted, which is the only thing either        // host should have to know about it.        .cottonPageGround(.groundMuted)        // NO identifier on the surface itself: one here is handed down to        // every element under it and beats `capture-close` and the dock's own        // ids (Cotton note "The phone and Mac app — how a screen is built" states        // the rule; a `ScrollView`        // is the one barrier and there is none here).    }    /// A fan row chosen. Every row is a push onto a creation surface that    /// already exists; the one sheet kind (a project's memory sentence) is    /// never offered here, because only the project page can write it. The    /// surface goes first, so back from the creation screen lands on Home and    /// not on a capture nobody is making.    ///    /// Picture and Camera are the two rows that STAY: they put a picture on    /// this thought, so the surface raises the picker over itself.    private func choose(_ destination: AddFanDestination) {        switch destination {        case .push(let route):            onDiscarded()            navigator.push(route)        case .hosted(.photoLibrary):            pickingPhoto = true        case .hosted(.camera):            Task { await openCamera() }        case .hosted(.memory):            break        }    }    /// The picture the share sheet left with the navigator, onto the draft.    /// Only once a dock is mounted: taken earlier, it would have nowhere to go.    private func takeWaitingPicture() {        guard let mounted, let picture = navigator.takeWaitingPicture() else { return }        mounted.dock.attach(picture: picture)    }    /// The camera, or the sentence saying why not.    private func openCamera() async {        if let refusal = await Camera.refusal(capabilities) {            toasts.show(refusal, tone: .error)            return        }        takingPhoto = true    }    /// One out of the photo library, written to a file first — `capture.media`    /// takes a PATH. The staged copy is this surface's, so it goes once the    /// crate has copied it into the store.    private func attachPicked(_ item: PhotosPickerItem) async {        guard let mounted else { return }        guard let staged = await MediaStaging.stage(item) else {            toasts.show(DockModel.pictureRefused, tone: .error)            return        }        defer { try? FileManager.default.removeItem(at: staged.url) }        await mounted.dock.attach(            file: staged.url, mime: staged.mime, kind: .photo,            filename: staged.url.lastPathComponent)    }    /// One out of the camera. The staged JPEG goes once it is in the store.    private func attachTaken(_ url: URL) async {        defer { try? FileManager.default.removeItem(at: url) }        guard let mounted else { return }        await mounted.dock.attach(            file: url, mime: "image/jpeg", kind: .photo, filename: url.lastPathComponent)    }}/// The sizes, counts and timings CaptureSurface draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum CaptureSurfaceKnobs {    static let chromeScreenBarHeight: CGFloat = 44}