Cotton code
168 lines · 8.0 KB · SwiftRaw
// Recording, import and recovery are device flows around the shared table list.//// The list is the meeting table's own (`TableListRoute`), and a meeting opens as// the meeting table's page. What this adds is only what a device does: the// unsaved-recording slips above the list, the file picker (`?import=1`), and the// recorder as a SHEET over the list (`/meetings/record`, the list's "Record a// meeting" act) — a flow, never a record screen of its own.import CottonKitimport SwiftUIstruct MeetingListFlow: View {    let writer: ScreenWriter    let opensImporter: Bool    /// The recorder, when the list was opened to record: drawn as a sheet over    /// the list for as long as this entry stands (`Navigator.listArrival`    /// never replaces it), and spent — the plain list put in its place — when    /// the sheet closes or lands on the meeting it filed.    var recorder: MeetingRecorderModel? = nil    @Environment(Navigator.self) private var navigator    /// Raised once the list has appeared, the way the picker is: a sheet bound    /// up before its presenter is on screen is a sheet SwiftUI may drop.    @State private var recorderAsked = false    /// The sheet is coming down; where to go once it is down.    @State private var recorderLeaving: RecorderLeaving?    @Environment(ToastCenter.self) private var toasts    @State private var picking = false    @State private var offers: [MeetingRecoveryOffer] = []    @State private var keepingId: String?    @State private var keepStage: MeetingKeepStage = .finishing    @State private var keepProgress: Double = 0    private var recovery: MeetingRecoveryStore { MeetingRecoveryStore() }    private var files: any MeetingAudioStore { AppGroupMeetingAudioStore() }    private var exporter: any MeetingAudioExporting { SystemMeetingAudioExport() }    var body: some View {        TableListRoute(table: "meeting", leading: {            ForEach(offers, id: \.marker.id) { offer in                MeetingRecoveryNote(offer: offer, busy: keepingId == offer.marker.id ? keepStage : nil,                    progress: keepProgress, keep: { Task { await keepRecovered(offer) } },                    discard: { discardRecovered(offer) })            }        }) { navigator.push(.meetingsMeeting(id: $0.id)) }        // Leaving goes through the recorder's own Close, which asks Keep or        // Discard while the microphone is open — never a tap beside the card.        .cottonCard(isPresented: recorderUp, detents: [.tall], holds: true, onDismiss: recorderDown) {            if let recorder {                MeetingRecorderSheet(model: recorder, close: { recorderLeaving = .toTheList })            }        }        // Stop filed it: the card comes down onto the meeting's page.        .onChange(of: recorderLanding) { _, route in            guard let route else { return }            recorderLeaving = .toTheMeeting(route)        }        .task {            offers = MeetingRecovery.offers(markers: recovery.markers(), onDisk: files.captures(),                // A file with no bytes is a take that never started: nothing                // was captured, so nothing is offered as unsaved.                exists: { ((try? FileManager.default.attributesOfItem(atPath: $0)[.size]) as? NSNumber)?.intValue ?? 0 > 0 },                probe: { MeetingAudioLength.milliseconds(atPath: $0) })            if opensImporter { picking = true }            if recorder != nil { recorderAsked = true }        }        .fileImporter(isPresented: $picking, allowedContentTypes: MeetingImport.pickerTypes) { result in            Task {                do {                    let created = try await MeetingImport.bring(try result.get(), through: writer)                    navigator.stack = MeetingImport.landed(created.landing, over: navigator.stack)                } catch { toasts.show(CottonStrings.writeFailure(error), tone: .error) }            }        }    }    private func keepRecovered(_ found: MeetingRecoveryOffer) async {        guard keepingId == nil else { return }        let marker = found.marker        keepingId = marker.id        keepStage = .finishing        keepProgress = 0        defer { keepingId = nil }        // The same encode Stop would have done: the marker names the CAPTURE        // file, which is linear PCM, and what is filed is the `.m4a` made from        // it (`MeetingAudioDelivery`). A capture the OS tore off may refuse to        // export, and then it is filed as it is — the crate accepts `.caf`, and        // a recording nobody can file is the worse failure.        let delivered = await MeetingAudioDelivery.prepare(            marker.path,            exporting: exporter,            watching: { fraction in                Task { @MainActor in keepProgress = fraction }            }        )        keepStage = .filing        do {            let created = try await writer.call(                CottonMethod.meetingsCreate,                MeetingCreateRequest(                    path: delivered.path,                    source: .record,                    title: marker.title,                    startedAt: marker.startedAt,                    // The length the SLIP said, which is the file's own where                    // the file could be read — so the row carries what the                    // person was shown rather than the marker's stale second.                    durationMs: found.durationMs,                    mime: delivered.mime                ),                as: MeetingCreated.self            )            recovery.clear(id: marker.id)            files.discard(act: marker.id)            offers.removeAll { $0.marker.id == marker.id }            // The same landing rule as an import's, and for the same reason:            // this slip can be kept while standing on the `?import=1` entry.            navigator.stack = MeetingImport.landed(created.landing, over: navigator.stack)        } catch let error as CottonCallError {            toasts.show(error.message, tone: .error)        } catch {            toasts.show(CottonStrings.writeFailure(error), tone: .error)        }    }    /// Where the recorder sheet goes once it is down.    enum RecorderLeaving: Equatable {        case toTheList        case toTheMeeting(Route)    }    /// Where the meeting the recorder filed is, once there is one.    private var recorderLanding: Route? {        guard let recorder, case .saved(let route) = recorder.state.stage else { return nil }        return route    }    /// Up from the moment the list stands to record until it is told to leave.    private var recorderUp: Binding<Bool> {        Binding(get: { recorderAsked && recorder != nil && recorderLeaving == nil }, set: { up in            if !up, recorderLeaving == nil { recorderLeaving = .toTheList }        })    }    /// The sheet is down: spend the `/meetings/record` entry, so the list is    /// the plain one and a later "Record a meeting" raises a fresh recorder.    private func recorderDown() {        guard let leaving = recorderLeaving else { return }        navigator.stack = Self.leavingRecorder(leaving, over: navigator.stack)    }    /// The path once the recorder sheet is down — pure, and one assignment, so    /// the list and the meeting land in a single transaction. Closing leaves    /// the plain list; a filed recording lands on its page with the plain list    /// under it (`MeetingImport.landed`).    static func leavingRecorder(_ leaving: RecorderLeaving, over path: [Route]) -> [Route] {        switch leaving {        case .toTheList: return MeetingImport.spent(path)        case .toTheMeeting(let landing): return MeetingImport.landed(landing, over: path)        }    }    /// Discard it: the bytes go, because the person said so. The only path in    /// this app that deletes a recording.    private func discardRecovered(_ found: MeetingRecoveryOffer) {        files.discard(act: found.marker.id)        recovery.clear(id: found.marker.id)        offers.removeAll { $0.marker.id == found.marker.id }    }}