Cotton code
861 lines · 38.0 KB · SwiftRaw
// RECORDINGS IN COMMS (assets/design/chat/DECISIONS.md "Recordings", CONTRACT.md "Recordings"): a conversation that// happened aloud (a meeting in a room, a voice memo, a file brought in, the notes taken on a call), listed in Calls with// the calls by day and opened on its own page. The page is the core's `chat.recording` drawn as it comes: the title (his// to change), when and how long, where the words are being made, who (each speaker tied to one of his people), the// audio with a scrubber whose place lights the line being said, the summary, the actions (each a to-do), the language,// Save as note and Share. Every word is the answer's.#if os(iOS)import AVFoundationimport CottonKitimport SwiftUIimport UIKitenum ChatRecordingMethod {    static let page = "chat.recording"    static let act = "chat.recording.act"    static let live = "chat.recording.live"    static let importFile = "meetings.import"}/// `chat.recording { id }`, as the core answers it.struct ChatRecordingPage: Codable, Equatable, Sendable {    struct Where: Codable, Equatable, Sendable {        /// `phone`, `mac`, `waiting` or `none`.        var on: String        var line: String?    }    struct Speaker: Codable, Equatable, Sendable, Identifiable {        var speaker: String        var label: String        var name: String?        var person: String?        var picture: ChatAvatar?        /// The words that tie this voice to one of his people ("Who is this?").        var choose: String?        var id: String { speaker }    }    struct Audio: Codable, Equatable, Sendable {        var key: String?        var path: String?    }    struct Line: Codable, Equatable, Sendable, Identifiable {        var line: String        var speaker: String        var name: String        var start_ms: Int        var end_ms: Int        var text: String        var language: String?        var edited: Bool?        var id: String { line }    }    struct Summary: Codable, Equatable, Sendable {        var points: [String]?        var note: String?    }    struct Action: Codable, Equatable, Sendable, Identifiable {        struct Act: Codable, Equatable, Sendable {            var label: String            var method: String?        }        var id: String        var words: String        var who: String?        var due: String?        var added: Bool        var act: Act?        /// Said once it is a to-do ("Added to to-dos").        var said: String?    }    struct Language: Codable, Equatable, Sendable {        struct Choice: Codable, Equatable, Sendable, Identifiable {            var code: String            var label: String            var on: Bool            var id: String { code }        }        var line: String?        var chosen: [String]?        var choices: [Choice]    }    struct Button: Codable, Equatable, Sendable {        var label: String        var saved: Bool?        /// Again's `mac`: sent back with the act.        var on: String?        /// Delete's ask.        var ask: String?    }    /// The ±15 s skip beside play: each moves the playhead by `ms`, its label read aloud.    struct Skip: Codable, Equatable, Sendable {        struct Step: Codable, Equatable, Sendable {            var label: String            var ms: Int        }        var back: Step        var ahead: Step    }    /// Export: the transcript as text or subtitles, or the audio, to the share sheet.    struct Export: Codable, Equatable, Sendable {        struct Choice: Codable, Equatable, Sendable, Identifiable {            var format: String            var label: String            var id: String { format }        }        var label: String        var choices: [Choice]    }    struct Buttons: Codable, Equatable, Sendable {        var note: Button        var share: Button        var again: Button?        var summary: Button?        var delete: Button?        var skip: Skip?        var export: Export?        var date: DateButton?    }    /// Its date, his to change (Comms 28 fixes 2): the picker's title, Save and Cancel, `at` the moment it began.    struct DateButton: Codable, Equatable, Sendable {        var label: String        var title: String        var save: String        var cancel: String        var at: String    }    /// Search inside the transcript (`query` asked with the page): each line holding the words, cut into parts, the    /// hits lit; `line` how many ("2 lines", "Not said in this recording"). The phone counts no characters.    struct Search: Codable, Equatable, Sendable {        struct Part: Codable, Equatable, Sendable {            var text: String            var hit: Bool        }        struct Hit: Codable, Equatable, Sendable, Identifiable {            var line: String            var start_ms: Int            var parts: [Part]            var id: String { line }        }        var hint: String        var query: String?        var hits: [Hit]        var line: String?    }    var id: String    var title: String    var named: Bool?    var when: String    var length: String    var duration_ms: Int?    var source: String?    var status: String    var status_line: String    var `where`: Where    var speakers: [Speaker]    var audio: Audio?    var lines: [Line]    var marks: [Int]?    var silenced: [[Int]]?    var summary: Summary    var actions: [Action]    var language: Language?    var search: Search?    var buttons: Buttons    var words: [String: String]    func word(_ key: String) -> String { words[key] ?? "" }    /// The line being said at `ms`: the last that started at or before it, so a gap keeps the one just said.    func lit(at ms: Int) -> Line? {        guard ms > 0 else { return nil }        return lines.last { $0.start_ms <= ms }    }}/// An act's answer: the page again (none after Delete) and one short line to show; `flush` after Share.struct ChatRecordingActAnswer: Codable, Equatable, Sendable {    /// Export's file, for the share sheet.    struct File: Codable, Equatable, Sendable {        var path: String        var name: String        var type: String?    }    var page: ChatRecordingPage?    var file: File?    var said: String?    var flush: Bool?    var deleted: Bool?}/// A recording's row in Calls: its mark on a round, its title, its length and state, when.struct ChatRecordingRowView: View {    let row: ChatCallRow    let open: () -> Void    @Environment(\.chatLook) private var look    private var symbol: String {        switch row.mark {        case "memo": "mic"        case "import": "square.and.arrow.down"        default: "waveform"        }    }    var body: some View {        Button(action: open) {            HStack(spacing: 13) {                Image(systemName: symbol)                    .font(.system(size: 20 * min(look.scale, 1.3), weight: .medium))                    .foregroundStyle(look.colours.accent)                    .frame(width: Warm.rowPicture * min(look.scale, 1.3), height: Warm.rowPicture * min(look.scale, 1.3))                    .background(Circle().fill(look.colours.bar))                VStack(alignment: .leading, spacing: 2) {                    Text(verbatim: row.name)                        .font(look.font(17, .semibold))                        .foregroundStyle(look.colours.text)                        .lineLimit(1)                    Text(verbatim: row.line).font(look.font(15)).foregroundStyle(look.colours.dim).lineLimit(2)                }                Spacer(minLength: 8)                Text(verbatim: row.when).font(look.font(13)).foregroundStyle(look.colours.faint).lineLimit(1)            }            .padding(.horizontal, Warm.side)            .padding(.vertical, 10)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityElement(children: .ignore)        .accessibilityLabel(Text(verbatim: [row.name, row.line, row.when].filter { !$0.isEmpty }.joined(separator: ", ")))        .accessibilityAddTraits(.isButton)        .accessibilityIdentifier("chat-recording-row-\(row.recording ?? "")")    }}/// The heading of a day in Calls.struct ChatCallsDay: View {    let day: String    @Environment(\.chatLook) private var look    var body: some View {        Text(verbatim: day)            .font(look.font(13, .semibold))            .foregroundStyle(look.colours.dim)            .padding(.horizontal, Warm.side)            .padding(.top, 14)            .padding(.bottom, 2)            .accessibilityAddTraits(.isHeader)            .accessibilityIdentifier("chat-calls-day")    }}/// A recording's page, as the core answers it.struct ChatRecordingPageView: View {    let recording: String    let back: () -> Void    @Environment(\.chatLook) private var look    @Environment(\.chatBook) private var book    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var page: ChatRecordingPage?    @State private var player = MeetingPlayer()    @State private var naming: ChatRecordingPage.Speaker?    @State private var titling = false    /// The date picker open (`buttons.date`), and the moment chosen in it.    @State private var dating = false    @State private var dated = Date()    @State private var title = ""    @State private var sharing = false    @State private var deleting = false    @State private var exporting = false    @State private var followed = true    /// The words searched for in the transcript, asked with the page.    @State private var query = ""    @FocusState private var editing: Bool    private struct Ask: Encodable, Sendable { let id: String; let charging: Bool; var query: String? }    /// Comms' own words the page's answer does not carry (Back, Save; the voice player's Pause and Position).    private func shell(_ key: String) -> String { ShellLines.line("words", key) }    private func chat(_ key: String) -> String { ShellLines.line("chat", key) }    var body: some View {        ScrollViewReader { scroller in            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    HStack {                        WarmRound(symbol: "chevron.left", label: shell("back"), id: "recording-back", tap: leave)                        Spacer()                        if let delete = page?.buttons.delete {                            WarmRound(symbol: "trash", label: delete.label, id: "recording-delete") { deleting = true }                        }                    }                    .padding(.leading, -6)                    if let page { content(page) }                }                .frame(maxWidth: .infinity, alignment: .leading)                .padding(.horizontal, Warm.side)                .padding(.top, 8)                .padding(.bottom, 32)            }            .scrollIndicators(.hidden)            .simultaneousGesture(DragGesture().onChanged { _ in followed = false })            .onChange(of: player.positionMs) { _, ms in                guard followed, player.playing, let lit = page?.lit(at: ms) else { return }                withAnimation(.easeOut(duration: 0.2)) { scroller.scrollTo(lit.line, anchor: .center) }            }        }        .background(look.colours.ground.ignoresSafeArea())        .accessibilityElement(children: .contain)        .accessibilityIdentifier("recording-page")        .task { await read() }        // The phone's own step ended (words made, or why not): the page as the core now answers it.        .onChange(of: ChatRecorder.shared.heard) { _, _ in Task { await read() } }        .onDisappear { player.stop() }        .lookPanel(item: $naming, style: look.panel, tall: true) { speaker in            ChatPeoplePicker(title: speaker.choose ?? "", go: shell("save"), leaving: []) { chosen in                naming = nil                if let person = chosen.first?.person {                    Task { await act(["act": .string("name"), "speaker": .string(speaker.speaker), "person": .string(person)]) }                }            }        }        .lookPanel(isPresented: $sharing, style: LookPanelStyle(scrim: Color.black.opacity(0.32), ground: look.colours.ground, corner: 26), tall: true) {            if let book {                ChatForwardSheet(book: book, from: "", look: look) { threads in                    sharing = false                    Task { for thread in threads { await act(["act": .string("share"), "thread": .string(thread)]) } }                }            }        }        .lookAsk(isPresented: $exporting, style: look.panel, font: look.font(17, .semibold), messageColour: look.colours.text,                 choices: (page?.buttons.export?.choices ?? []).map { choice in                     LookChoice(id: "recording-export-\(choice.format)", label: choice.label, colour: look.colours.accent) {                         Task { await act(["act": .string("export"), "format": .string(choice.format)]) }                     }                 },                 name: page?.buttons.export?.label)        // A word typed asks the page again, about 300 ms after the last key (CONTRACT "Search, the ±15 s skip").        .task(id: query) {            guard page != nil else { return }            try? await Task.sleep(for: .milliseconds(300))            guard !Task.isCancelled else { return }            await read()        }        .lookPanel(isPresented: $dating, style: look.panel, tall: true) {            if let date = page?.buttons.date {                ScrollView {                    VStack(spacing: 0) {                        Text(verbatim: date.title).font(look.font(19, .semibold)).foregroundStyle(look.colours.text)                            .multilineTextAlignment(.center)                            .fixedSize(horizontal: false, vertical: true)                            .padding(.horizontal, 24).padding(.top, 20).padding(.bottom, 8)                        DatePicker(selection: $dated, in: ...Date(), displayedComponents: [.date, .hourAndMinute]) { EmptyView() }                            .datePickerStyle(.graphical)                            .labelsHidden()                            .tint(look.colours.accent)                            .padding(.horizontal, 16)                            .accessibilityIdentifier("recording-date-picker")                        ChatPanelChoice(choice: LookChoice(id: "recording-date-save", label: date.save, colour: look.colours.accent) {                            dating = false                            Task { await act(["act": .string("date"), "at": .string(ChatRecordingDate.string(dated))]) }                        }, font: look.font(17, .semibold))                        ChatPanelChoice(choice: LookChoice(id: "recording-date-cancel", label: date.cancel, colour: look.colours.dim) {                            dating = false                        }, font: look.font(17, .semibold))                    }                    .padding(.bottom, 12)                }            }        }        .lookAsk(isPresented: $deleting, style: look.panel, font: look.font(17, .semibold), message: page?.buttons.delete?.ask,                 messageColour: look.colours.text,                 choices: [LookChoice(id: "recording-delete", label: page?.buttons.delete?.label ?? "", colour: look.colours.danger) {                     Task { await act(["act": .string("delete")]) }                 }])    }    // MARK: the page    @ViewBuilder    private func content(_ page: ChatRecordingPage) -> some View {        heading(page)        if page.audio != nil {            playerRow(page)                .padding(.top, 16)        }        if !page.speakers.isEmpty {            section(page.word("who"))            ForEach(page.speakers) { speaker in speakerRow(speaker) }        }        section(page.word("summary"))        if let points = page.summary.points, !points.isEmpty {            VStack(alignment: .leading, spacing: 8) {                ForEach(Array(points.enumerated()), id: \.offset) { _, point in                    HStack(alignment: .firstTextBaseline, spacing: 10) {                        Circle().fill(look.colours.accent).frame(width: 5, height: 5).accessibilityHidden(true)                        Text(verbatim: point).font(look.font(16)).foregroundStyle(look.colours.text)                            .fixedSize(horizontal: false, vertical: true)                    }                }            }            .accessibilityElement(children: .combine)            .accessibilityIdentifier("recording-summary")        } else if let note = page.summary.note {            Text(verbatim: note).font(look.font(15)).foregroundStyle(look.colours.dim)                .fixedSize(horizontal: false, vertical: true)                .accessibilityIdentifier("recording-summary")        }        if let ask = page.buttons.summary {            WarmPill(words: ask.label, id: "recording-summary-again") { Task { await act(["act": .string("summary")]) } }                .padding(.top, 10)        }        if !page.actions.isEmpty {            section(page.word("actions"))            ForEach(page.actions) { action in actionRow(action) }        }        buttons(page)            .padding(.top, 22)        // Drawn once the core has words for it (`line`: after the words are made) or he has chosen one: before that the        // core answers no line and nothing on, and the row would be a chevron with no words (seen on dev, 23 Nov 2026).        if let language = page.language, !language.choices.isEmpty,           !(language.line ?? "").isEmpty || language.choices.contains(where: \.on) {            section(page.word("language"))            languageRow(language)        }        if !page.lines.isEmpty {            section(page.word("transcript"))            if let search = page.search { searchField(search) }            if let search = page.search, !query.trimmingCharacters(in: .whitespaces).isEmpty, search.query != nil {                if let line = search.line {                    Text(verbatim: line).font(look.font(14)).foregroundStyle(look.colours.dim)                        .padding(.vertical, 6)                        .accessibilityIdentifier("recording-search-line")                }                VStack(alignment: .leading, spacing: 4) {                    ForEach(search.hits) { hit in hitRow(hit, lit: page.lit(at: player.positionMs)?.line == hit.line) }                }            } else {                VStack(alignment: .leading, spacing: 4) {                    ForEach(page.lines) { line in lineRow(line, lit: page.lit(at: player.positionMs)?.line == line.line) }                }            }        } else if let nothing = page.words["nothing"] {            section(page.word("transcript"))            Text(verbatim: nothing).font(look.font(15)).foregroundStyle(look.colours.dim)        }    }    private func heading(_ page: ChatRecordingPage) -> some View {        VStack(alignment: .leading, spacing: 6) {            if titling {                TextField(page.word("title_hint"), text: $title)                    .font(look.font(26, .bold))                    .foregroundStyle(look.colours.text)                    .focused($editing)                    .submitLabel(.done)                    .onSubmit(saveTitle)                    .onChange(of: editing) { _, now in if !now { saveTitle() } }                    .accessibilityIdentifier("recording-title-field")            } else {                Button {                    title = page.named == false ? "" : page.title                    titling = true                    editing = true                } label: {                    Text(verbatim: page.title)                        .font(look.font(30, .bold))                        .kerning(-0.6)                        .foregroundStyle(look.colours.text)                        .multilineTextAlignment(.leading)                        .fixedSize(horizontal: false, vertical: true)                }                .buttonStyle(.plain)                .accessibilityAddTraits(.isHeader)                .accessibilityHint(Text(verbatim: page.word("title_hint")))                .accessibilityIdentifier("recording-title")            }            let when = [page.when, page.length].filter { !$0.isEmpty }.joined(separator: " · ")            if let date = page.buttons.date {                // The date line opens the date picker (Comms 28 fixes 2).                Button {                    dated = ChatRecordingDate.parse(date.at) ?? Date()                    dating = true                } label: {                    HStack(spacing: 6) {                        Text(verbatim: when).font(look.font(15)).foregroundStyle(look.colours.dim)                            .fixedSize(horizontal: false, vertical: true)                        Image(systemName: "pencil").font(.system(size: 12, weight: .semibold)).foregroundStyle(look.colours.accent)                            .accessibilityHidden(true)                    }                }                .buttonStyle(.plain)                .accessibilityHint(Text(verbatim: date.label))                .accessibilityIdentifier("recording-date")            } else {                Text(verbatim: when).font(look.font(15)).foregroundStyle(look.colours.dim)            }            if let line = page.where.line, !line.isEmpty {                HStack(spacing: 6) {                    Image(systemName: whereSymbol(page.where.on)).font(.system(size: 13, weight: .semibold)).accessibilityHidden(true)                    Text(verbatim: line).font(look.font(14, .medium)).fixedSize(horizontal: false, vertical: true)                }                .foregroundStyle(page.where.on == "none" ? look.colours.dim : look.colours.accent)                .accessibilityElement(children: .combine)                .accessibilityIdentifier("recording-where")            }            if !page.status_line.isEmpty, page.status_line != page.where.line {                Text(verbatim: page.status_line).font(look.font(14))                    .foregroundStyle(page.status == "failed" ? look.colours.danger : look.colours.dim)                    .accessibilityIdentifier("recording-status")            }        }        .padding(.top, 12)    }    private func whereSymbol(_ on: String) -> String {        switch on {        case "phone": "iphone"        case "mac": "laptopcomputer"        case "waiting": "clock"        default: "minus.circle"        }    }    private func section(_ name: String) -> some View {        Text(verbatim: name)            .font(look.font(13, .semibold))            .foregroundStyle(look.colours.dim)            .padding(.top, 24)            .padding(.bottom, 8)            .accessibilityAddTraits(.isHeader)    }    // MARK: the audio    private func playerRow(_ page: ChatRecordingPage) -> some View {        let duration = max(player.durationMs, page.duration_ms ?? 0, 1)        return HStack(spacing: 12) {            WarmRound(symbol: player.playing ? "pause.fill" : "play.fill",                      label: player.playing ? chat("app.voice.pause") : page.title, id: "recording-play", accent: true) {                Task { await playOrPause(page) }            }            if let skip = page.buttons.skip {                WarmRound(symbol: "gobackward.15", label: skip.back.label, id: "recording-skip-back") {                    Task { await self.skip(page, by: skip.back.ms) }                }                WarmRound(symbol: "goforward.15", label: skip.ahead.label, id: "recording-skip-ahead") {                    Task { await self.skip(page, by: skip.ahead.ms) }                }            }            VStack(spacing: 4) {                ChatRecordingScrubber(fraction: Double(player.positionMs) / Double(duration), marks: (page.marks ?? []).map { Double($0) / Double(duration) },                                      label: chat("app.voice.position"), value: clock(player.positionMs)) { fraction in                    Task { await seek(page, Int(fraction * Double(duration))) }                }                HStack {                    Text(verbatim: clock(player.positionMs))                    Spacer()                    Text(verbatim: clock(duration))                }                .font(look.font(12).monospacedDigit())                .foregroundStyle(look.colours.faint)                .accessibilityHidden(true)            }        }        .padding(12)        .background(RoundedRectangle(cornerRadius: 22, style: .continuous).fill(look.colours.bar))    }    private func clock(_ ms: Int) -> String {        let seconds = max(0, ms / 1000)        return seconds >= 3600            ? String(format: "%d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60)            : String(format: "%d:%02d", seconds / 60, seconds % 60)    }    private func ready(_ page: ChatRecordingPage) async -> Bool {        if player.loaded { return true }        var path = page.audio?.path        if path == nil, let key = page.audio?.key, let core {            struct Key: Encodable, Sendable { let key: String }            struct Path: Decodable, Sendable { let path: String }            path = try? await core.call(CottonMethod.mediaEnsure, Key(key: key), as: Path.self).path        }        guard let path else { return false }        player.load(URL(fileURLWithPath: path))        return true    }    private func playOrPause(_ page: ChatRecordingPage) async {        if player.playing { player.toggle(); return }        guard await ready(page) else { return }        followed = true        player.play(fromMs: player.positionMs)    }    /// The playhead moved by `ms`, kept within the audio (its own length once loaded, else the page's); it plays on.    private func skip(_ page: ChatRecordingPage, by ms: Int) async {        guard await ready(page) else { return }        let end = player.durationMs > 0 ? player.durationMs : (page.duration_ms ?? 0)        await seek(page, min(max(0, player.positionMs + ms), max(0, end - 500)))    }    private func seek(_ page: ChatRecordingPage, _ ms: Int) async {        guard await ready(page) else { return }        followed = true        player.play(fromMs: ms)    }    // MARK: who, actions, language, lines    private func speakerRow(_ speaker: ChatRecordingPage.Speaker) -> some View {        HStack(spacing: 12) {            ChatAvatarView(avatar: speaker.picture ?? ChatAvatar(photo: nil, initials: speaker.label, tint: 0), side: 40 * min(look.scale, 1.3))            Text(verbatim: speaker.name ?? speaker.label).font(look.font(16, .semibold)).foregroundStyle(look.colours.text)            Spacer(minLength: 8)            if let choose = speaker.choose {                WarmPill(words: choose, id: "recording-choose-\(speaker.speaker)") { naming = speaker }            }        }        .padding(.vertical, 6)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("recording-speaker-\(speaker.speaker)")    }    private func actionRow(_ action: ChatRecordingPage.Action) -> some View {        HStack(alignment: .top, spacing: 12) {            VStack(alignment: .leading, spacing: 2) {                Text(verbatim: action.words).font(look.font(16)).foregroundStyle(look.colours.text)                    .fixedSize(horizontal: false, vertical: true)                let detail = [action.who, action.due].compactMap { $0 }.joined(separator: " · ")                if !detail.isEmpty { Text(verbatim: detail).font(look.font(13)).foregroundStyle(look.colours.dim) }            }            Spacer(minLength: 8)            if let act = action.act, !action.added {                WarmPill(words: act.label, id: "recording-todo-\(action.id)", accent: true) {                    Task { await self.act(["act": .string("todo"), "action": .string(action.id)]) }                }            } else if let said = action.said {                Text(verbatim: said).font(look.font(13, .medium)).foregroundStyle(look.colours.dim)                    .accessibilityIdentifier("recording-todo-\(action.id)")            }        }        .padding(.vertical, 6)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("recording-action-\(action.id)")    }    private func buttons(_ page: ChatRecordingPage) -> some View {        SearchWrapLayout(spacing: 8, lineSpacing: 8) {            WarmPill(words: page.buttons.note.label, id: "recording-note", accent: true) {                Task { await act(["act": .string("note")]) }            }            WarmPill(words: page.buttons.share.label, id: "recording-share") { sharing = true }            if let export = page.buttons.export {                WarmPill(words: export.label, id: "recording-export") { exporting = true }            }            if let again = page.buttons.again {                WarmPill(words: again.label, id: "recording-again") {                    var ask: [String: JSONValue] = ["act": .string("again")]                    if let on = again.on { ask["on"] = .string(on) }                    Task { await act(ask) }                }            }        }    }    /// The language he says it is in: each choice turned on or off, the recording heard again in those (two or more:    /// on his Mac, line by line).    private func languageRow(_ language: ChatRecordingPage.Language) -> some View {        Menu {            ForEach(language.choices) { choice in                Button {                    var chosen = language.choices.filter(\.on).map(\.code)                    if let at = chosen.firstIndex(of: choice.code) { chosen.remove(at: at) } else { chosen.append(choice.code) }                    guard !chosen.isEmpty else { return }                    Task { await act(["act": .string("language"), "languages": .array(chosen.map { .string($0) })]) }                } label: {                    if choice.on { Label(choice.label, systemImage: "checkmark") } else { Text(verbatim: choice.label) }                }            }        } label: {            HStack(spacing: 8) {                Text(verbatim: language.line ?? language.choices.filter(\.on).map(\.label).joined(separator: ", ")).font(look.font(16)).foregroundStyle(look.colours.text)                Spacer()                Image(systemName: "chevron.up.chevron.down").font(.system(size: 13, weight: .semibold)).foregroundStyle(look.colours.dim)            }            .padding(.vertical, 8)            .contentShape(Rectangle())        }        .accessibilityLabel(Text(verbatim: [page?.word("language"), language.line].compactMap { $0 }.joined(separator: ", ")))        .accessibilityIdentifier("recording-language")    }    private func searchField(_ search: ChatRecordingPage.Search) -> some View {        HStack(spacing: 8) {            Image(systemName: "magnifyingglass").font(.system(size: 14, weight: .semibold)).foregroundStyle(look.colours.dim)                .accessibilityHidden(true)            TextField(search.hint, text: $query)                .font(look.font(16))                .foregroundStyle(look.colours.text)                .textInputAutocapitalization(.never)                .autocorrectionDisabled()                .submitLabel(.search)                .accessibilityIdentifier("recording-search")        }        .padding(.horizontal, 12).padding(.vertical, 10)        .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(look.colours.bar))        .padding(.bottom, 8)    }    /// A line the search found, its parts in a row and the hits lit; a tap plays from it, as a line's does.    private func hitRow(_ hit: ChatRecordingPage.Search.Hit, lit: Bool) -> some View {        let said = page?.lines.first { $0.line == hit.line }        let words = hit.parts.reduce(Text(verbatim: "")) { sum, part in            sum + (part.hit ? Text(verbatim: part.text).bold().foregroundColor(look.colours.accent) : Text(verbatim: part.text).foregroundColor(look.colours.text))        }        return Button {            Task { if let page { await seek(page, hit.start_ms) } }        } label: {            VStack(alignment: .leading, spacing: 2) {                HStack(spacing: 8) {                    if let said { Text(verbatim: said.name).font(look.font(13, .semibold)).foregroundStyle(look.colours.accent) }                    Text(verbatim: clock(hit.start_ms)).font(look.font(12).monospacedDigit()).foregroundStyle(look.colours.faint)                }                words.font(look.font(16))                    .multilineTextAlignment(.leading)                    .fixedSize(horizontal: false, vertical: true)            }            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.horizontal, 10).padding(.vertical, 8)            .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(lit ? look.colours.bubbleOut : Color.clear))            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .padding(.horizontal, -10)        .accessibilityAddTraits(lit ? .isSelected : [])        .accessibilityIdentifier("recording-hit-\(hit.line)")    }    private func lineRow(_ line: ChatRecordingPage.Line, lit: Bool) -> some View {        Button {            Task { if let page { await seek(page, line.start_ms) } }        } label: {            VStack(alignment: .leading, spacing: 2) {                HStack(spacing: 8) {                    Text(verbatim: line.name).font(look.font(13, .semibold)).foregroundStyle(look.colours.accent)                    Text(verbatim: clock(line.start_ms)).font(look.font(12).monospacedDigit()).foregroundStyle(look.colours.faint)                }                Text(verbatim: line.text).font(look.font(16)).foregroundStyle(look.colours.text)                    .multilineTextAlignment(.leading)                    .fixedSize(horizontal: false, vertical: true)            }            .frame(maxWidth: .infinity, alignment: .leading)            .padding(.horizontal, 10).padding(.vertical, 8)            .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(lit ? look.colours.bubbleOut : Color.clear))            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .padding(.horizontal, -10)        .id(line.line)        .accessibilityAddTraits(lit ? .isSelected : [])        .accessibilityIdentifier("recording-line-\(line.line)")    }    // MARK: asking the core    private func leave() {        player.stop()        back()    }    private func read() async {        guard let core else { return }        let words = query.trimmingCharacters(in: .whitespacesAndNewlines)        page = try? await core.call(ChatRecordingMethod.page, Ask(id: recording, charging: MeetingsPower.charging, query: words.isEmpty ? nil : words),                                    as: ChatRecordingPage.self)    }    /// `chat.recording.act`: the page again and its line; Share's message flushed; Delete leaves the page.    private func act(_ fields: [String: JSONValue]) async {        guard let core else { return }        var ask = fields        ask["id"] = .string(recording)        ask["charging"] = .bool(MeetingsPower.charging)        do {            let answer = try await core.call(ChatRecordingMethod.act, JSONValue.object(ask), as: ChatRecordingActAnswer.self)            if let fresh = answer.page { page = fresh }            // Export: the file the core wrote, to the share sheet.            if let file = answer.file { ShareSheet.present(URL(fileURLWithPath: file.path)) }            if let said = answer.said, !said.isEmpty { toasts?.show(said) }            if answer.flush == true { await book?.flush() }            if answer.deleted == true { leave() }        } catch {            toasts?.show(ActionRefused.words(for: error), tone: .error)        }    }    private func saveTitle() {        guard titling else { return }        let wanted = title.trimmingCharacters(in: .whitespacesAndNewlines)        titling = false        editing = false        guard !wanted.isEmpty, wanted != page?.title else { return }        Task { await act(["act": .string("title"), "title": .string(wanted)]) }    }}/// A recording's moment as the core writes it (RFC 3339, UTC, milliseconds) and reads it.enum ChatRecordingDate {    static func parse(_ text: String) -> Date? {        let fractional = ISO8601DateFormatter()        fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]        return fractional.date(from: text) ?? ISO8601DateFormatter().date(from: text)    }    static func string(_ date: Date) -> String {        let format = ISO8601DateFormatter()        format.formatOptions = [.withInternetDateTime, .withFractionalSeconds]        format.timeZone = TimeZone(identifier: "UTC")        return format.string(from: date)    }}/// The audio's place: a track with his marks, the knob where it plays; a tap or a drag along it plays from there.struct ChatRecordingScrubber: View {    let fraction: Double    let marks: [Double]    let label: String    let value: String    let seek: (Double) -> Void    @Environment(\.chatLook) private var look    var body: some View {        GeometryReader { geo in            let width = max(geo.size.width, 1)            let at = min(max(fraction, 0), 1)            ZStack(alignment: .leading) {                Capsule().fill(look.colours.rule).frame(height: 4)                Capsule().fill(look.colours.accent).frame(width: width * at, height: 4)                ForEach(Array(marks.enumerated()), id: \.offset) { _, mark in                    Rectangle().fill(look.colours.dim).frame(width: 2, height: 10).offset(x: width * min(max(mark, 0), 1) - 1)                }                Circle().fill(look.colours.accent).frame(width: 14, height: 14).offset(x: width * at - 7)            }            .frame(maxHeight: .infinity)            .contentShape(Rectangle())            .gesture(DragGesture(minimumDistance: 0).onEnded { drag in seek(min(max(drag.location.x / width, 0), 1)) })        }        .frame(height: 28)        .accessibilityElement()        .accessibilityLabel(Text(verbatim: label))        .accessibilityValue(Text(verbatim: value))        .accessibilityAdjustableAction { direction in            seek(min(max(fraction + (direction == .increment ? 0.05 : -0.05), 0), 1))        }        .accessibilityIdentifier("recording-scrubber")    }}#endif