Cotton code
490 lines · 19.8 KB · SwiftRaw
// New thought, the bar's dark pill, as the UI direction draws it (Cotton note// 0a22168c §4, the mock's "New thought: overlay"): a dark veil over the whole// screen in every state, and across its top "‹ [cap] goes into <Name> ›" — the// personal database first and by default, the ‹ › stepping through the// held databases; choosing a database wins over where the pill was pressed.//// A tap LISTENS at once: a pulsing red dot, the words as they are heard,// "Type instead" and Cancel; the dot finishes the take and sends it. A hold// TYPES: one plain multi-line field, "Add or ask…", then an underlined Send// and Cancel and nothing else — no chips, no hints, no picture controls. The// share path with a picture keeps `CaptureSurface`.//// The RECEIPT is drawn inside the overlay, not as a card on the page: "Saved// in <Name>." (and " Only you can see it." for the personal database) at// display size over a torn slip, with Undo on the slip and Done under it, and one tap// "Move it to <project>" when the thought went personal while the board's cap// was on a project. The verbs go through `ThoughtFiling` (CottonKit), the// thought kind's own tool; no `cottonCapture` in the environment (a test, a// preview) draws the words and no verbs.import CottonKitimport SwiftUI/// What landed when New thought kept a capture — the overlay's own send, or/// the capture surface's `onKept` on the picture path.struct ThoughtFiled: Equatable {    let id: String    let text: String    /// The projects the thought was aimed at; empty when it went to the    /// personal database alone.    let projectIds: [String]    var database: HeldDatabase? = nil}/// The overlay's sentences, decided apart from the drawing.enum ThoughtWords {    static var label: String { ShellLines.line("input", "thought.label") }    static var placeholder: String { ShellLines.line("input", "thought.placeholder") }    static var listening: String { ShellLines.line("input", "thought.listening") }    static var typeInstead: String { ShellLines.line("input", "thought.type_instead") }    static var send: String { ShellLines.line("input", "thought.send") }    static var cancel: String { ShellLines.line("input", "thought.cancel") }    static func goesInto(_ name: String) -> String { ShellLines.line("input", "thought.goes_into", ["name": "\(name)"]) }    static func saved(in name: String, onlyYou: Bool) -> String {        ShellLines.line("input", onlyYou ? "thought.saved_only_you" : "thought.saved", ["name": name])    }    static func moved(to name: String) -> String { ShellLines.line("input", "thought.moved", ["name": "\(name)"]) }    static func moveTo(_ name: String) -> String { ShellLines.line("input", "thought.move_to", ["name": "\(name)"]) }    static var takenBack: String { ShellLines.line("input", "thought.taken_back") }    static var undo: String { ShellLines.line("input", "thought.undo") }    static var done: String { ShellLines.line("input", "thought.done") }    static var couldNotUndo: String { ShellLines.line("input", "thought.could_not_undo") }    static func couldNotMove(_ name: String) -> String { ShellLines.line("input", "thought.could_not_move", ["name": "\(name)"]) }    /// The person's first name, for the personal database's cap and receipt.    static func firstName(_ ownerName: String?) -> String? {        ownerName?.split(separator: " ").first.map(String.init)    }}struct NewThoughtOverlay: View {    @Environment(\.theme) private var theme    let model: CaptureSurfaceModel    /// How the pill was pressed; nil draws a receipt alone (`kept`).    let start: CaptureStart?    /// A thought the capture surface kept, for its receipt.    let kept: ThoughtFiled?    /// What the personal database is called.    let personalName: String    /// The project the board's cap is on, when it is — the receipt's one tap.    let pageDatabaseId: String?    /// The screen under the overlay, which a thought said here carries.    let screen: CaptureScreen?    /// The overlay is done: closed with nothing more to show. A spoken    /// "open …" / "go to …" naming a tool ends here too, saving nothing, and    /// the tool opens through the app's `Navigator`.    let onDone: () -> Void    @Environment(\.cottonCapture) private var capture    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(\.cottonHaptics) private var haptics    @Environment(ToastCenter.self) private var toasts    @Environment(DatabasesModel.self) private var databases: DatabasesModel?    @Environment(\.cottonCore) private var core    enum Phase: Equatable { case listening, typing, receipt(ThoughtFiled) }    enum Receipt: Equatable { case saved, moved(String), takenBack }    @State private var phase: Phase    @State private var mounted: MountedDock?    @State private var started = false    @State private var closing = false    @State private var target = 0    @State private var destination = ShownDatabase()    @State private var destinations: [HeldDatabase] = []    @State private var scopedCapture: CaptureContext?    @State private var sending = false    @State private var pulsing = false    @State private var receipt: Receipt = .saved    @State private var busy = false    @State private var failure: String?    @FocusState private var fieldFocused: Bool    static let veil = CottonColors.ink.opacity(0.93)    static let cream = CottonColors.ground    static let dot = CottonColors.statusError    init(model: CaptureSurfaceModel, start: CaptureStart?, kept: ThoughtFiled?,         personalName: String, pageDatabaseId: String?, screen: CaptureScreen? = nil,         onDone: @escaping () -> Void) {        self.screen = screen        self.model = model        self.start = start        self.kept = kept        self.personalName = personalName        self.pageDatabaseId = pageDatabaseId        self.onDone = onDone        let opening: Phase = kept.map { .receipt($0) } ?? (start == .typing ? .typing : .listening)        _phase = State(initialValue: opening)    }    var body: some View {        ZStack {            Self.veil.ignoresSafeArea()            VStack(spacing: 0) {                targetRow                    .padding(.top, 12)                Spacer(minLength: 24)                switch phase {                case .listening: listening                case .typing: typing                case .receipt(let thought): receiptFace(thought)                }                Spacer(minLength: 24)            }            .padding(.horizontal, ChromeKnobs.chromeSettingsMargin)        }        .task { await mount() }        .onChange(of: mounted?.dock.ending) { _, ending in takeEnded(ending) }        .onDisappear { mounted?.engine.release() }    }    // MARK: ‹ cap goes into Name ›    private var selectedDatabase: HeldDatabase? {        guard destinations.indices.contains(target) else { return nil }        return destinations[target]    }    private var capDatabase: HeldDatabase? {        if case .moved = receipt {            return databases?.held.first(where: { $0.id == pageDatabaseId })        }        return selectedDatabase    }    private var targetName: String {        capDatabase.map { databases?.capName($0) ?? $0.name } ?? personalName    }    private var canStep: Bool {        if case .receipt = phase { return false }        return destinations.count > 1 && !sending    }    @ViewBuilder private var targetRow: some View {        HStack(spacing: 10) {            stepButton("‹", by: -1)            ProjectCap(                name: targetName,                colour: capDatabase.flatMap { databases?.colours[$0.id] } ?? .navy,                side: 30)            .accessibilityHidden(true)            Text(ThoughtWords.goesInto(targetName))                .font(CottonFonts.type(15))                .foregroundStyle(Self.cream)                .lineLimit(1)                .accessibilityIdentifier("new-thought-target")            stepButton("›", by: 1)        }        .frame(maxWidth: .infinity)    }    private func stepButton(_ glyph: String, by delta: Int) -> some View {        Button {            step(by: delta)        } label: {            Text(glyph)                .font(CottonFonts.serif(26))                .foregroundStyle(Self.cream)                .frame(width: 36, height: 36)                .contentShape(Rectangle())        }        .buttonStyle(.plain)        .opacity(canStep ? 1 : 0.25)        .disabled(!canStep)        .accessibilityLabel(ShellLines.line("input", delta < 0 ? "thought.previous_database" : "thought.next_database"))    }    private func step(by delta: Int) {        guard canStep else { return }        let count = destinations.count        target = ((target + delta) % count + count) % count        destination.id = selectedDatabase.flatMap { $0.isPersonal ? nil : $0.id }        haptics.select()    }    // MARK: Listening    @ViewBuilder private var listening: some View {        let heard = mounted?.dock.displayText ?? ""        VStack(spacing: 28) {            Button {                Task { await finishAndSend() }            } label: {                Circle()                    .fill(Self.dot)                    .frame(width: 22, height: 22)                    .scaleEffect(pulsing ? 1.25 : 0.9)                    .opacity(pulsing ? 1 : 0.7)                    .frame(width: 60, height: 60)                    .contentShape(Circle())            }            .buttonStyle(.plain)            .accessibilityLabel(ThoughtWords.send)            .accessibilityIdentifier("new-thought-finish")            .onAppear {                withAnimation(.easeInOut(duration: 0.9).repeatForever(autoreverses: true)) { pulsing = true }            }            Text(heard.isEmpty ? ThoughtWords.listening : heard)                .font(CottonFonts.serif(24))                .foregroundStyle(Self.cream.opacity(heard.isEmpty ? 0.6 : 1))                .multilineTextAlignment(.center)                .frame(maxWidth: .infinity)                .accessibilityIdentifier("new-thought-heard")            HStack(spacing: 28) {                link(ThoughtWords.typeInstead, id: "new-thought-type") { Task { await typeInstead() } }                link(ThoughtWords.cancel, id: "new-thought-cancel") { cancel() }            }        }    }    // MARK: Typing    private var words: Binding<String> {        Binding(            get: { mounted?.dock.displayText ?? "" },            set: { mounted?.dock.fieldEdited($0) })    }    @ViewBuilder private var typing: some View {        VStack(spacing: 28) {            // The prompt is drawn by hand: a TextField's own placeholder is the            // system's grey, which vanishes on the veil.            TextField(text: words, prompt: Text(ThoughtWords.placeholder).foregroundStyle(Self.cream.opacity(0.55)), axis: .vertical) {                Text(ThoughtWords.label)            }                .textFieldStyle(.plain)                .font(CottonFonts.serif(24))                .foregroundStyle(Self.cream)                .tint(Self.cream)                .lineLimit(2...10)                .focused($fieldFocused)                .submitLabel(.return)                .frame(maxWidth: .infinity)                .accessibilityIdentifier("new-thought-field")            VStack(spacing: 12) {                link(ThoughtWords.send, id: "new-thought-send") { Task { await send() } }                    .disabled(mounted?.dock.isReadyToSend != true)                    .opacity(mounted?.dock.isReadyToSend == true ? 1 : 0.4)                link(ThoughtWords.cancel, id: "new-thought-cancel") { cancel() }            }        }        .onAppear { fieldFocused = true }    }    // MARK: Receipt    private var aimedName: String? {        guard case .receipt(let thought) = phase,              let database = thought.database, !database.isPersonal else { return nil }        return databases?.capName(database) ?? database.name    }    private var pageDatabase: DatabaseRef? {        guard let database = databases?.held.first(where: { $0.id == pageDatabaseId }),              !database.isPersonal else { return nil }        return DatabaseRef(id: database.id, name: databases?.capName(database) ?? database.name)    }    private var sentence: String {        switch receipt {        case .saved:            if let aimedName { return ThoughtWords.saved(in: aimedName, onlyYou: false) }            return ThoughtWords.saved(in: personalName, onlyYou: true)        case .moved(let name): return ThoughtWords.moved(to: name)        case .takenBack: return ThoughtWords.takenBack        }    }    @ViewBuilder private func receiptFace(_ thought: ThoughtFiled) -> some View {        VStack(spacing: 24) {            if !thought.text.isEmpty {                Text(thought.text)                    .font(CottonFonts.hand(15))                    .foregroundStyle(Self.cream)                    .lineLimit(3)                    .accessibilityIdentifier("thought-receipt-words")            }            VStack(alignment: .leading, spacing: 12) {                // The slip is a `.contain` container, and the flat accessibility                // tree lists no line for a container: the walk finds the receipt                // by its head and reads the parts under it (`receipt_lines`).                HStack(alignment: .firstTextBaseline, spacing: 12) {                    Text(failure ?? sentence)                        .font(CottonFonts.display(28))                        .foregroundStyle(failure == nil ? CottonColors.ink : CottonColors.statusError)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("thought-receipt-head")                    if capture != nil, receipt != .takenBack {                        link(ThoughtWords.undo, id: "thought-receipt-undo", ink: CottonColors.ink) {                            Task { await takeBack(thought) }                        }                        .fixedSize()                        .disabled(busy)                    }                }            }            .frame(maxWidth: .infinity, alignment: .leading)            .padding(22)            .background(PaperSurface(dye: .cream, edge: .torn, seed: "thought-\(thought.id)"))            .accessibilityElement(children: .contain)            .accessibilityIdentifier("thought-receipt")            VStack(spacing: 12) {                if capture != nil, receipt != .takenBack {                    if let pageDatabase, receipt == .saved, aimedName == nil {                        link(ThoughtWords.moveTo(pageDatabase.name), id: "thought-receipt-move") {                            Task { await move(thought, to: pageDatabase) }                        }                        .disabled(busy)                    }                }                link(ThoughtWords.done, id: "thought-receipt-dismiss") { finish() }            }        }    }    // MARK: Verbs    private func link(_ title: String, id: String, ink: Color = Self.cream, action: @escaping () -> Void) -> some View {        Button(action: action) {            Text(title)                .font(CottonFonts.type(theme.scale.titleSize))                .underline()                .foregroundStyle(ink)                .padding(.vertical, 8)                .padding(.horizontal, 4)                .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityIdentifier(id)    }    /// Built in `.task`, never in an init: `CaptureMount.mount` makes the    /// speech recogniser, and a recogniser made per view init is a leak.    private func mount() async {        destinations = databases?.ordered ?? []        guard start != nil, mounted == nil, let capture else { return }        let scoped = capture.scoped(to: destination)        scopedCapture = scoped        let model = model        let built = CaptureMount.mount(            capture: scoped,            vocabulary: model.vocabulary,            hints: { model.hints },            haptics: haptics,            toasts: toasts,            onCaptured: { _ in }        )        let dock = built.dock        dock.screen = screen        dock.onCaptured = { created in            phase = .receipt(ThoughtFiled(                id: created["id"]?.string ?? "",                text: dock.lastSent?.text ?? "",                projectIds: dock.lastSent?.projectIds ?? [],                database: selectedDatabase))        }        mounted = built        await model.load()        await model.loadHints()        guard !started else { return }        started = true        if phase == .listening {            await dock.startDictation()            if !dock.isDictationLive, phase == .listening { phase = .typing }        }    }    /// A take ended while the overlay listened: what it heard goes, read by    /// the overlay as it is drawn now.    private func takeEnded(_ ending: DockModel.DictationEnding?) {        guard let ending, let dock = mounted?.dock, !closing, phase == .listening else { return }        if ending.outcome == .dictated, dock.canSend {            Task { await send() }        } else if ending.outcome != .dictationCancelled {            // A simulator has no recogniser; a take that heard nothing            // falls to typing rather than to a blank screen.            phase = .typing        }    }    private func finishAndSend() async {        guard let dock = mounted?.dock else { return }        await dock.finishDictation()        if dock.canSend {            await send()        } else if phase == .listening {            phase = .typing        }    }    private func typeInstead() async {        guard let dock = mounted?.dock else {            phase = .typing            return        }        await dock.switchToTyping()        phase = .typing    }    /// The voice split: a spoken "open …" runs now, anything else is saved    /// as a thought at once — over what the overlay is drawn with now.    private var spokenOpen: SpokenOpenVoice {        SpokenOpenVoice(core: core, navigator: navigator) {            closing = true            onDone()        }    }    private func send() async {        guard !sending, let dock = mounted?.dock, dock.isReadyToSend else { return }        sending = true        defer { sending = false }        fieldFocused = false        await dock.send(runsSpokenCommand: spokenOpen.run)    }    private func cancel() {        closing = true        mounted?.dock.cancelDictation()        onDone()    }    private func finish() {        closing = true        onDone()    }    private func takeBack(_ thought: ThoughtFiled) async {        guard let filing = (scopedCapture ?? capture)?.filing else { return }        busy = true        defer { busy = false }        do {            try await filing.takeBack(thoughtId: thought.id)            failure = nil            finish()        } catch {            failure = ThoughtWords.couldNotUndo        }    }    private func move(_ thought: ThoughtFiled, to database: DatabaseRef) async {        guard let filing = (scopedCapture ?? capture)?.filing else { return }        busy = true        defer { busy = false }        do {            try await filing.move(thoughtId: thought.id, to: database)            failure = nil            receipt = .moved(database.name)        } catch ThoughtFilingGap.sourceRetractionFailed(let name) {            failure = ShellLines.line("input", "thought.still_in_both", ["name": "\(name)", "personal": "\(personalName)"])        } catch ThoughtFilingGap.mediaNeedsTransfer {            failure = ShellLines.line("input", "thought.media_stays", ["personal": "\(personalName)"])        } catch ThoughtFilingGap.alreadyFiled {            failure = ShellLines.line("input", "thought.already_filed", ["personal": "\(personalName)"])        } catch {            failure = ThoughtWords.couldNotMove(database.name)        }    }}