Cotton code
318 lines · 16.1 KB · SwiftRaw
// The recorder — a SHEET over the meetings list, never a screen of its own.//// Recording is a flow, not a record: a thing that is a record is drawn by its// table's page, and the meeting this makes is the meeting table's page (its// name, its length, the recording as media, the transcript as the body, who// spoke as links to people). What is left here is what exists only while the// microphone is open, and it is reached as an ACT: the meetings list's "Record// a meeting" (`meeting.json` create) and the + fan both// name `/meetings/record`, which is the list with this sheet up// (`MeetingListFlow`).//// ONE cream `.cut` sheet, untilted, and everything on it is a fact about the// recording that is happening: the name the person may type, the elapsed stamp// in the display serif, the strip the microphone is drawing right now, and the// verbs. Nothing else — a recorder with settings on it is a recorder somebody// is reading instead of listening.//// **The strip is the only waveform in this app that is REAL.** Everywhere else// `MeetingWaveform.samples(id:)` derives a speech-shaped picture from the// meeting's id, because the file stores no loudness envelope and reading an// hour of m4a to draw a row would be the whole-body read the app refuses. Here// the bytes are going past this sheet as they are written, so the bars are the// microphone's own, newest at the right, folded to the width by the same// `MeetingWaveform.barCount` the list uses.//// **Close while the microphone is open asks: Keep or Discard.** The sheet// cannot be swiped away (`interactiveDismissDisabled`), so nothing is lost by a// stray drag; its close circle gives the verbs way to the question, and "Carry// on" puts them back. Keep is Stop: the recording is filed as a meeting.// Discard is also beside Stop, behind its own question, because it deletes for// good. Stop lands on the meeting's page, with the plain list under it// (`MeetingImport.landed`): going back to a finished recorder would be going// back to a microphone that is no longer open. While the recording is being// finished and filed there is no close.//// **A denied microphone is a STATE.** It is the capability layer's own rule// ported to a sheet: the sentence `CapabilityRefusal` writes, and a verb to// Settings only where Settings would actually help. Never a second prompt — iOS// grants one per install — and never a spinner.import CottonKitimport SwiftUI#if canImport(UIKit)    import UIKit#endifstruct MeetingRecorderSheet: View {    @Environment(\.theme) private var theme    @Bindable var model: MeetingRecorderModel    /// Leave the recorder for the list under it — before the microphone opens,    /// after a refusal, or once the recording was thrown away. A filed    /// recording is landed by the list that owns the sheet, which reads the    /// model's `.saved` stage itself (`MeetingListFlow`): the sheet is handed    /// no navigation.    let close: () -> Void    @Environment(\.openURL) private var openURL    /// Close was tapped on a live recording: the sheet asks Keep or Discard.    @State private var leaving = false    /// Discard was tapped: asked once more, because it deletes for good.    @State private var discarding = false    /// The name the sheet suggests. A PLACEHOLDER and never a value: the crate    /// writes no title for a recording it was not given one for, the summariser    /// writes a real one when the meeting goes ready, and a screen that sent    /// this string would name every meeting the same thing.    ///    /// It is `MeetingFacts.datedLabel`'s and not its own sentence, because it    /// is the SAME sentence the list and the open meeting draw over a row with    /// no title — which is what this recording is about to become.    private var suggestedName: String {        MeetingFacts.datedLabel(Date())    }    var body: some View {        PaperScreen(title: nil, showsBack: false, trailing: {            if canLeave || isLive {                NavCircle(symbol: "xmark", label: ShellLines.line("capture", "composer.close")) {                    if isLive { leaving = true } else { close() }                }                .accessibilityIdentifier("meeting-record-close")            }        }) {            Paper(dye: .cream, edge: .cut, seed: "meeting-record", tilt: false, inset: 22) {                VStack(alignment: .leading, spacing: 22) {                    PaperTextField(                        suggestedName,                        text: $model.title,                        size: 21,                        serif: true                    )                    .accessibilityIdentifier("meeting-record-title")                    .disabled(model.state.stage.isFinished)                    stamp                    strip                    if model.state.stage == .finishing { finishing }                    verbs                }                .frame(maxWidth: .infinity, alignment: .leading)            }            .fixedSize(horizontal: false, vertical: true)        }        .task { model.appeared() }        .onDisappear { model.disappeared() }        .onChange(of: isLive) { _, live in if !live { leaving = false } }        .confirmDecision(            isPresented: $discarding,            title: ShellLines.line("capture", "meeting.discard_question"),            message: ShellLines.line("capture", "meeting.discard_question_body"),            confirmLabel: ShellLines.line("capture", "meeting.discard"),            identifier: "meeting-record-discard-confirm",            onConfirm: discard        )    }    /// The microphone is open, or paused with a recording behind it.    private var isLive: Bool {        switch model.state.stage {        case .recording, .paused: return true        default: return false        }    }    /// Throws the recording away and leaves the recorder.    private func discard() {        model.discard()        close()    }    /// Close is offered only when nothing would be lost by taking it: before    /// the microphone opens, and after the meeting exists or the recorder    /// refused. (While it is open, Close asks first — `leaving`.)    private var canLeave: Bool {        switch model.state.stage {        case .idle, .asking, .blocked, .failed, .saved: return true        case .opening, .recording, .paused, .finishing, .saving: return false        }    }    // ── The stamp ─────────────────────────────────────────────────────────    /// The elapsed time, large, in the display serif with monospaced digits so    /// the sheet does not twitch every tenth of a second.    ///    /// `h:mm:ss` past the hour and `m:ss` under it — the same spelling    /// `MeetingFacts.clock` gives the player's scrubber, because the two are    /// the same number about the same recording.    private var stamp: some View {        VStack(alignment: .leading, spacing: 10) {            HStack(alignment: .firstTextBaseline, spacing: 12) {                Text(MeetingFacts.clock(model.elapsedMs))                    .font(CottonFonts.display(46))                    .foregroundStyle(theme.print(.ink))                    .monospacedDigit()                    .accessibilityIdentifier("meeting-record-elapsed")                if !stageIsASentence { stageLine }                Spacer(minLength: 0)            }            if stageIsASentence { stageLine }        }    }    /// What is happening. **A WORD is handwritten beside the stamp; a SENTENCE    /// is TYPED, across the sheet, and wraps.**    ///    /// A refusal is a sentence — "Cotton doesn't have access to your    /// microphone. You can turn it on in Settings." — and the walk of 15 Sep    /// 2026 read it twice: first cut off at "your microph…" beside a 46-point    /// clock, then, given the whole width, still cut off at "…turn it on in    /// Settin…". The width was never the whole answer. **The handwriting voice    /// does not wrap on this sheet** — every other thing it says is an    /// annotation a few words long, which is what it is for — so a sentence set    /// in it takes one line and loses its end, and the end is the half that    /// says what to do about the refusal.    ///    /// So the sentence is set in the typed body voice, which is what the    /// recovery slip says its own two sentences in, on the same paper, wrapping    /// (`MeetingRecoveryNote`). The ink does not change: a refusal is still    /// red. `fixedSize` stays on both, so neither is ever given one line by a    /// parent.    private var stageLine: some View {        Group {            if stageIsASentence {                Text(stage).paperBody(14, ink: stageInk)            } else {                Text(stage).paperHand(19, ink: stageInk)            }        }        .fixedSize(horizontal: false, vertical: true)        .frame(maxWidth: .infinity, alignment: .leading)        .accessibilityIdentifier("meeting-record-stage")    }    /// True while the stage is prose rather than a word. The two states that    /// carry a sentence are the two that are asking the person to do something:    /// a capability the app was refused, and a filing that did not land.    private var stageIsASentence: Bool {        switch model.state.stage {        case .blocked, .failed: return true        default: return false        }    }    /// What is happening, in a word or a sentence, handwritten beside the    /// stamp. A refusal is red; everything else is pencil.    private var stage: String {        switch model.state.stage {        case .idle, .asking: return ShellLines.line("capture", "meeting.stage.getting_ready")        case .blocked(let capability, let access):            return CapabilityRefusal.sentence(capability, access)                ?? ShellLines.line("capture", "meeting.stage.no_microphone")        case .opening: return ShellLines.line("capture", "meeting.stage.starting")        case .recording: return ShellLines.line("capture", "meeting.stage.recording")        case .paused(.person): return ShellLines.line("capture", "meeting.stage.paused")        case .paused(.interruption): return ShellLines.line("capture", "meeting.stage.interrupted")        case .finishing: return ShellLines.line("capture", "meeting.stage.finishing")        case .saving: return ShellLines.line("capture", "meeting.stage.filing")        case .failed(let why): return why        case .saved: return ShellLines.line("capture", "meeting.stage.saved")        }    }    private var stageInk: PaperInk {        switch model.state.stage {        case .blocked, .failed: return .red        default: return .pencil        }    }    // ── The strip ─────────────────────────────────────────────────────────    /// The microphone's own bars. Empty until the first tick, which is a strip    /// waiting rather than a strip claiming silence.    private var strip: some View {        GeometryReader { geo in            let bars = MeetingWaveform.barCount(width: geo.size.width, pitch: 3)            Waveform(samples: MeetingWaveform.bars(model.meter, count: bars), barFraction: 0.45, theme: theme)                .fill(theme.print(.pencil))        }        .frame(height: 64)        .opacity(model.state.stage.isCapturing ? 1 : 0.45)        .accessibilityHidden(true)    }    // ── Finishing ─────────────────────────────────────────────────────────    /// The pencil line the encode fills, under the strip.    ///    /// **A real fraction, not a spinner.** The capture is linear PCM and what    /// is filed is an AAC `.m4a` made from it, which on a long meeting is a    /// transcode a person waits through; `AVAssetExportSession` says how far it    /// has got and this draws exactly that (`MeetingRecorderModel.exportProgress`).    /// It is the same pencil line a goal's progress is drawn with, because it is    /// the same thing: how much of something is done.    private var finishing: some View {        ZStack {            ProgressLine(fraction: 1, seed: "meeting-record-track", theme: theme)                .stroke(theme.print(.pencil), lineWidth: 0.7)            ProgressLine(fraction: model.exportProgress, seed: "meeting-record-progress", theme: theme)                .stroke(                    theme.print(.ink).opacity(0.72),                    style: StrokeStyle(lineWidth: 2.4, lineCap: .round))        }        .blendMode(theme.printBlend)        .frame(height: 5)        .accessibilityIdentifier("meeting-record-progress")        .accessibilityLabel(ShellLines.line("capture", "meeting.finishing_recording"))    }    // ── The verbs ─────────────────────────────────────────────────────────    @ViewBuilder private var verbs: some View {        if leaving, isLive {            Text(ShellLines.line("capture", "meeting.keep_question"))                .paperBody(15)                .accessibilityIdentifier("meeting-record-leaving")        }        HStack(spacing: 26) {            switch model.state.stage {            case .recording where leaving, .paused where leaving:                DocketAction(label: ShellLines.line("capture", "meeting.keep"), identifier: "meeting-record-keep") { model.stop() }                DocketAction(label: ShellLines.line("capture", "meeting.discard"), identifier: "meeting-record-leave-discard", emphasis: .secondary, action: discard)                DocketAction(label: ShellLines.line("capture", "meeting.carry_on"), identifier: "meeting-record-carry-on", emphasis: .secondary) { leaving = false }            case .recording:                DocketAction(label: ShellLines.line("capture", "meeting.pause"), identifier: "meeting-record-pause") { model.pause() }                DocketAction(label: ShellLines.line("capture", "meeting.stop"), identifier: "meeting-record-stop") { model.stop() }                DocketAction(label: ShellLines.line("capture", "meeting.discard"), identifier: "meeting-record-discard", emphasis: .secondary) { discarding = true }            case .paused:                DocketAction(label: ShellLines.line("capture", "meeting.resume"), identifier: "meeting-record-resume") { model.resume() }                DocketAction(label: ShellLines.line("capture", "meeting.stop"), identifier: "meeting-record-stop") { model.stop() }                DocketAction(label: ShellLines.line("capture", "meeting.discard"), identifier: "meeting-record-discard", emphasis: .secondary) { discarding = true }            case .blocked(_, let access):                if CapabilityRefusal.offersSettings(access) {                    // `UIApplication.openSettingsURLString` — Cotton's OWN page                    // in Settings, which is the only URL iOS will open there.                    // **The simulator lands on the Settings root**, because a                    // simulated app has no page until it has been granted or                    // refused something on that device; a real phone opens                    // Cotton's own. Verified on the walk of 15 Sep 2026 and                    // recorded rather than worked around: there is no second                    // URL to try.                    DocketAction(label: ShellLines.line("capture", "meeting.open_settings"), identifier: "meeting-record-settings") {                        guard let url = CapabilityRefusal.settingsURL else { return }                        openURL(url)                    }                }            case .failed:                // The audio is still on disk and the marker still names it, so                // the retry is the same call again rather than a new recording.                DocketAction(label: ShellLines.line("capture", "meeting.try_again"), identifier: "meeting-record-retry") { model.retry() }            case .idle, .asking, .opening, .finishing, .saving, .saved:                EmptyView()            }            Spacer(minLength: 0)        }    }}