Cotton code
869 lines · 36.4 KB · SwiftRaw
// A scene while writing (ink.html "A scene, while writing"; wireframes 3):// the bar (back, the scene's number, place and time, ▤ for the page), the// standard heading small, action as plain paragraphs, speech under the// speaker's name with the face beside it, then the writing bar above the// keyboard, which never hides the line being written: who speaks next (the// core's guess), the Action and Note switches, dictation, send. A tap on a// line edits it in place; a press and hold moves it, changes its speaker,// adds a direction, writes after it or deletes it. A sideways swipe goes to the next or previous scene.#if os(iOS)import CottonKitimport CottonValuesimport CottonVoiceimport SwiftUIimport UIKit@MainActor @Observablefinal class InkSceneModel {    var scene: String    var answer: StorySceneAnswer?    var near: StoryNear?    /// The words in the writing bar.    var draft = ""    /// What the next line is written as; nil, the core's guess.    var chosen: StoryChoice?    /// The line new lines are written after (Write after this); nil, the end.    var after: String?    /// The line being changed in place, and its words.    var editing: String?    var editText = ""    /// The sheet over the scene.    var sheet: InkSceneSheet?    /// Which way the last scene change went, for the slide.    var forward = true    @ObservationIgnored let book: any StoryBook    @ObservationIgnored let story: InkStory    @ObservationIgnored let dictation: ComposerVoice    /// The scene Plus made for this visit, left again if nothing went in it.    @ObservationIgnored let fresh: String?    /// The scene the microphone writes into, as it changes with a swipe.    @ObservationIgnored private let dictating: InkSceneRef    init(story: InkStory, scene: String, fresh: Bool) {        self.story = story        self.book = story.book        self.scene = scene        self.fresh = fresh ? scene : nil        let dictating = InkSceneRef(scene)        self.dictating = dictating        dictation = ComposerVoice(core: story.core) {            VoicePlanRequest(surface: "story.writer", table: StoryTable.scene, column: "body", record: dictating.scene, mode: .dictate)        }    }    /// The next line's choice: the person's pick, else the core's guess.    var choice: StoryChoice { chosen ?? answer?.pick.suggested ?? .action }    func load() async {        await story.attempt {            answer = try await book.scene(scene, composing: .end)            near = try await book.near(scene)        }    }    func go(to other: String, forward: Bool) async {        commitEdit()        await story.attempt {            let next = try await book.scene(other, composing: .end)            let around = try await book.near(other)            withAnimation(.easeOut(duration: 0.25)) {                self.forward = forward                chosen = nil                draft = ""                after = nil                scene = other                dictating.scene = other                answer = next                near = around            }        }    }    func send() async {        let words = draft.trimmingCharacters(in: .whitespacesAndNewlines)        guard !words.isEmpty else { return }        draft = ""        let picked = choice        await story.attempt {            let added = try await book.addLine(scene: scene, after: after, choice: picked, text: words)            answer = added.scene            // Writing after a line goes on after the one just written.            if after != nil { after = added.line }            chosen = nil        }    }    /// Write after this: the next lines go in after `line`, until Write at the end.    func writeAfter(_ line: StorySceneAnswer.Line) async {        sheet = nil        after = line.id        chosen = nil        await story.attempt { answer = try await book.scene(scene, composing: .after(line.id)) }    }    /// Back to writing at the end of the scene.    func writeAtEnd() async {        after = nil        chosen = nil        await story.attempt { answer = try await book.scene(scene, composing: .end) }    }    /// "Writing after: Ravi looks up from the bus": the line written after, its first 40 characters.    var writingAfter: String? {        guard let after, let line = answer?.lines.first(where: { $0.id == after }) else { return nil }        return InkWords.line("scene.writing_after", ["line": String(line.text.prefix(40))])    }    func edit(_ line: StorySceneAnswer.Line) {        commitEdit()        editing = line.id        editText = line.text    }    func commitEdit() {        guard let line = editing, let shown = answer?.lines.first(where: { $0.id == line }) else {            editing = nil            return        }        editing = nil        let words = editText.trimmingCharacters(in: .whitespacesAndNewlines)        guard words != shown.text, !words.isEmpty else { return }        let keep = Self.choice(of: shown)        Task {            await story.attempt { answer = try await book.editLine(scene: scene, line: line, choice: keep, text: words) }        }    }    func speaker(_ line: StorySceneAnswer.Line, to choice: StoryChoice) async {        sheet = nil        await story.attempt { answer = try await book.editLine(scene: scene, line: line.id, choice: choice, text: line.text) }    }    func direct(_ line: StorySceneAnswer.Line, _ words: String) async {        sheet = nil        let aside = words.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: "()"))        await story.attempt { answer = try await book.setAside(scene: scene, line: line.id, aside: aside.isEmpty ? nil : aside) }    }    func move(_ line: StorySceneAnswer.Line, by: Int) async {        sheet = nil        await story.attempt { answer = try await book.moveLine(scene: scene, line: line.id, by: by) }    }    func remove(_ line: StorySceneAnswer.Line) async {        sheet = nil        if after == line.id { after = nil }        await story.attempt { answer = try await book.removeLine(scene: scene, line: line.id) }    }    /// A new character by name, then the next line is theirs.    func named(_ name: String) async {        sheet = nil        guard let story = answer?.story else { return }        await self.story.attempt {            let id = try await book.addCharacter(story: story, name: name)            chosen = .character(id)            answer = try await book.scene(scene, composing: .end)        }    }    /// `time` nil leaves the stored time as it is.    func setPlace(setting: String?, place: String, time: String?, summary: String) async {        sheet = nil        await story.attempt {            try await book.writeScene(scene, setting: setting, place: place, time: time, summary: summary)            answer = try await book.scene(scene, composing: .end)        }    }    /// Leaving the scene: changes kept, an empty scene Plus made dropped.    func leave() async {        commitEdit()        if let fresh { await story.left(fresh) } else { await story.reloadHome() }    }    static func choice(of line: StorySceneAnswer.Line) -> StoryChoice {        switch line.kind {        case .dialogue, .enters: line.character.map { .character($0) } ?? .action        case .note: .note        case .action: .action        }    }}/// Which scene the writer is on, read by the microphone's plan at each start.@MainActor final class InkSceneRef {    var scene: String    init(_ scene: String) { self.scene = scene }}enum InkSceneSheet: Identifiable, Equatable {    case whereWhen    case acts(StorySceneAnswer.Line)    case speaker(StorySceneAnswer.Line?)    case direction(StorySceneAnswer.Line)    case naming    var id: String {        switch self {        case .whereWhen: "where"        case .acts(let line): "acts-\(line.id)"        case .speaker(let line): "speaker-\(line?.id ?? "next")"        case .direction(let line): "direction-\(line.id)"        case .naming: "naming"        }    }}struct InkSceneScreen: View {    @State private var model: InkSceneModel    @Environment(\.dismiss) private var dismiss    @FocusState private var focus: InkFocus?    private let opensOnPlace: Bool    private let route: InkRoute    enum InkFocus: Hashable { case writing, line }    init(story: InkStory, scene: String, fresh: Bool) {        _model = State(initialValue: InkSceneModel(story: story, scene: scene, fresh: fresh))        opensOnPlace = fresh        route = .scene(scene, fresh: fresh)    }    var body: some View {        VStack(spacing: 0) {            bar            if let answer = model.answer {                lines(answer)                    .id(model.scene)                    .transition(.asymmetric(insertion: .move(edge: model.forward ? .trailing : .leading).combined(with: .opacity),                                            removal: .opacity))            } else {                Spacer()            }        }        .safeAreaInset(edge: .bottom, spacing: 0) {            if model.answer != nil, model.editing == nil {                InkWritingBar(model: model, focus: $focus)                    .padding(.horizontal, 16)                    .padding(.top, 8)                    .padding(.bottom, 10)                    .background(Ink.ground)            }        }        .inkGround()        .toolbar(.hidden, for: .navigationBar)        .simultaneousGesture(swipe)        .lookPanel(item: $model.sheet, style: Ink.panel, tall: model.sheet == .whereWhen) { sheet in            InkSceneSheetContent(model: model, sheet: sheet)        }        // Dictation's reason before the phone is asked, or Open Settings after it refused; Not now beside either        // (voice control.*, store pass, 24 Nov 2026).        .lookPanel(isPresented: Binding(get: { model.dictation.ask != nil }, set: { if !$0 { model.dictation.notNow() } }), style: Ink.panel) {            if let ask = model.dictation.ask {                let words = model.dictation.askWords(ask)                InkActsSheet(title: words.line, acts: [                    InkAct(words: words.go, tag: "voice-ask-go") { Task { await model.dictation.goOn(ask) } },                    InkAct(words: words.notNow, quiet: true, tag: "voice-ask-not-now") { model.dictation.notNow() },                ])            }        }        .task {            await model.load()            if opensOnPlace, !(model.answer?.placed ?? true) { model.sheet = .whereWhen }            #if COTTON_DEV            if InkStory.lookAtWhere { InkStory.lookAtWhere = false; model.sheet = .whereWhen }            if InkStory.lookAtSpeaker { InkStory.lookAtSpeaker = false; model.sheet = .speaker(nil) }            #endif        }        // A new scene's Where and when closed: the keyboard comes up on the bar for its first line (the iPhone walk,        // 24 Nov 2026: "Write the first line below." stood with no keyboard until the bar was tapped).        .onChange(of: model.sheet) { was, now in            if was == .whereWhen, now == nil, model.answer?.lines.isEmpty == true { focus = .writing }        }        // Gone from the stack (back), not covered by the page pushed over it.        .onDisappear {            guard !model.story.path.contains(route) else { return }            Task { await model.leave() }        }    }    // MARK: The bar    private var bar: some View {        HStack(spacing: 10) {            InkGlyph(symbol: "chevron.left", label: InkWords.line("writer.back")) { dismiss() }            Button { model.sheet = .whereWhen } label: {                Text(title)                    .font(InkType.barTitle)                    .foregroundStyle(Ink.ink)                    .multilineTextAlignment(.center)                    .frame(maxWidth: .infinity)            }            .buttonStyle(InkPress())            .accessibilityHint(InkWords.line("picker.title"))            .accessibilityAction(named: InkWords.line("ink.previous_scene")) { step(forward: false) }            .accessibilityAction(named: InkWords.line("ink.next_scene")) { step(forward: true) }            InkGlyph(symbol: "doc.plaintext", label: InkWords.line("scene.read")) {                guard let story = model.answer?.story else { return }                model.commitEdit()                model.story.path.append(.read(story: story, at: model.scene))            }        }        .padding(.horizontal, 8)        .padding(.top, 6)    }    /// The next or previous scene, as a sideways swipe or VoiceOver's actions ask.    private func step(forward: Bool) {        guard let other = forward ? model.near?.next : model.near?.previous else { return }        focus = nil        Task { await model.go(to: other, forward: forward) }    }    private var title: String {        guard let answer = model.answer else { return "" }        guard let number = model.near?.number else { return answer.title }        return "\(number) · \(answer.title)"    }    // MARK: The lines    private func lines(_ answer: StorySceneAnswer) -> some View {        ScrollViewReader { reader in            ScrollView {                VStack(alignment: .leading, spacing: 18) {                    Text(answer.slugline)                        .font(InkType.slug)                        .tracking(0.72)                        .foregroundStyle(Ink.quiet)                        .accessibilityLabel(answer.slugline)                    if answer.lines.isEmpty {                        Text(InkWords.line("scene.empty"))                            .font(InkType.line)                            .foregroundStyle(Ink.rule)                    }                    ForEach(answer.lines) { line in                        lineView(line)                            .id(line.id)                    }                    Color.clear.frame(height: 1).id("end")                }                .padding(.horizontal, Ink.gutter)                .padding(.top, 12)                .padding(.bottom, 12)                .frame(maxWidth: .infinity, alignment: .leading)            }            .scrollIndicators(.hidden)            // A long scene opens at its last line; a short one stands from the top.            .defaultScrollAnchor(.bottom, for: .initialOffset)            .defaultScrollAnchor(.top, for: .alignment)            .onChange(of: answer.lines.count) { _, _ in                // Writing after a line keeps that place in view; else the end.                withAnimation(.easeOut(duration: 0.2)) {                    if let after = model.after { reader.scrollTo(after, anchor: .center) } else { reader.scrollTo("end", anchor: .bottom) }                }            }            .onChange(of: focus) { _, now in                guard now == .writing else { return }                withAnimation {                    if let after = model.after { reader.scrollTo(after, anchor: .center) } else { reader.scrollTo("end", anchor: .bottom) }                }            }        }    }    @ViewBuilder private func lineView(_ line: StorySceneAnswer.Line) -> some View {        let editing = model.editing == line.id        Group {            switch line.kind {            case .dialogue:                HStack(alignment: .top, spacing: 10) {                    InkPictureFace(initial: line.initial ?? "", picture: picture(of: line.character), size: 38)                    VStack(alignment: .leading, spacing: 2) {                        Text(line.who ?? "")                            .font(InkType.speaker)                            .tracking(0.92)                            .foregroundStyle(Ink.blue)                        if let aside = line.aside {                            Text("(\(aside))")                                .font(InkType.direction)                                .foregroundStyle(Ink.quiet)                        }                        words(line, editing: editing, lineSpacing: 7.25 * 0.6)                    }                    .frame(maxWidth: .infinity, alignment: .leading)                }            case .action:                words(line, editing: editing, lineSpacing: 5)            case .note:                words(line, editing: editing, lineSpacing: 4, font: InkType.direction, ink: Ink.quiet)            case .enters:                Text(line.text)                    .font(InkType.direction)                    .foregroundStyle(Ink.quiet)            }        }        .contentShape(Rectangle())        .onTapGesture {            guard !editing, line.kind != .enters else { return }            model.edit(line)            // The writing bar, which held the keyboard, leaves as the line            // opens: the line takes the focus once its field stands, so the            // bar's going (or the app's tap rule putting its keyboard away)            // never closes the line again.            Task { @MainActor in                try? await Task.sleep(for: .milliseconds(60))                if model.editing == line.id { focus = .line }            }        }        .onLongPressGesture(minimumDuration: 0.45) {            model.commitEdit()            focus = nil            model.sheet = .acts(line)        }        .accessibilityElement(children: editing ? .contain : .ignore)        .accessibilityLabel(line.label)        .accessibilityIdentifier("ink-line")        .accessibilityHint(InkWords.line("scene.tap_to_change"))        .accessibilityAction { model.edit(line); focus = .line }        .accessibilityAction(named: InkWords.line("home.more")) { model.sheet = .acts(line) }        .accessibilityAction(named: InkWords.line("ink.previous_scene")) { step(forward: false) }        .accessibilityAction(named: InkWords.line("ink.next_scene")) { step(forward: true) }    }    @ViewBuilder private func words(_ line: StorySceneAnswer.Line, editing: Bool, lineSpacing: CGFloat, font: Font = InkType.line, ink: Color = Ink.ink) -> some View {        if editing {            TextField("", text: $model.editText, axis: .vertical)                .font(font)                .foregroundStyle(ink)                .lineSpacing(lineSpacing)                .focused($focus, equals: .line)                // The line being changed is named by who says it, or by its kind.                .accessibilityLabel(line.who ?? InkWords.line(line.kind == .note ? "kind.note" : "kind.action"))                .submitLabel(.done)                .onChange(of: model.editText) { _, now in                    if now.contains("\n") {                        model.editText = now.replacingOccurrences(of: "\n", with: "")                        model.commitEdit()                        focus = nil                    }                }                .onChange(of: focus) { was, now in                    // Only the line letting go of the keyboard ends the change.                    if was == .line, now != .line, model.editing == line.id { model.commitEdit() }                }                .padding(.bottom, 2)                .overlay(alignment: .bottom) { InkRule() }        } else {            Text(line.text)                .font(font)                .foregroundStyle(ink)                .lineSpacing(lineSpacing)                .fixedSize(horizontal: false, vertical: true)        }    }    private func picture(of character: String?) -> String? {        guard let character else { return nil }        return model.story.home?.cast?.first { $0.id == character }?.picture    }    // MARK: Sideways to the next or previous scene    private var swipe: some Gesture {        DragGesture(minimumDistance: 30)            .onEnded { drag in                let dx = drag.translation.width, dy = drag.translation.height                guard abs(dx) > 80, abs(dx) > abs(dy) * 2, drag.startLocation.x > 30 else { return }                step(forward: dx < 0)            }    }}/// The writing bar (`.compose`): the line being written, then who it is/// (the guess), the Action switch, the microphone and send.struct InkWritingBar: View {    @Bindable var model: InkSceneModel    var focus: FocusState<InkSceneScreen.InkFocus?>.Binding    var body: some View {        VStack(alignment: .leading, spacing: 12) {            if let writingAfter = model.writingAfter {                HStack(alignment: .firstTextBaseline, spacing: 10) {                    Text(writingAfter)                        .font(InkType.sceneLength)                        .foregroundStyle(Ink.quiet)                        .lineLimit(2)                        .frame(maxWidth: .infinity, alignment: .leading)                    Button { Task { await model.writeAtEnd() } } label: {                        Text(InkWords.line("scene.back_to_end"))                            .font(InkType.sceneLength)                            .foregroundStyle(Ink.quiet)                            .underline()                            .frame(minHeight: 32)                            .contentShape(Rectangle())                    }                    .buttonStyle(InkPress())                }            }            TextField("", text: shownDraft, prompt: Text(hint).foregroundColor(Ink.rule), axis: .vertical)                .font(InkType.line)                .foregroundStyle(Ink.ink)                .lineLimit(1...5)                .focused(focus, equals: .writing)                .submitLabel(.send)                .onChange(of: model.draft) { _, now in                    // Return sends the line; the next one is ready at once.                    if now.hasSuffix("\n") {                        model.draft = String(now.dropLast())                        Task { await model.send() }                    }                }                .accessibilityLabel(hint)            HStack(spacing: 8) {                // The chips side by side, onto a second row when they do not                // fit beside the mic and Send, each whole (as Android's                // BarChips): at the largest text they were squeezed into                // columns of single letters.                InkFlow(spacing: 8) {                    speakerChip                    ForEach(switches, id: \.kind) { one in                        let on = model.choice == one.choice                        InkChip(on: on) { Text(one.name) }                            // On again is off: the speaker the core would put next is current.                            .onTapGesture { model.chosen = on ? model.answer?.pick.suggestedSpeaker : one.choice }                            .accessibilityAddTraits(.isButton)                            .accessibilityAddTraits(on ? .isSelected : [])                    }                }                .frame(maxWidth: .infinity, alignment: .leading)                mic                Button { Task { await model.send() } } label: {                    Image(systemName: "arrow.up")                        .font(.system(size: 15, weight: .semibold))                        .foregroundStyle(.white)                        .frame(width: 34, height: 34)                        .background(Circle().fill(Ink.blue))                        .frame(width: 44, height: 44)                        .contentShape(Circle())                }                .buttonStyle(InkPress())                .accessibilityLabel(model.answer?.composer.send ?? InkWords.line("composer.send"))                .disabled(model.draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)            }        }        .padding(.vertical, 12)        .padding(.horizontal, 14)        .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(Ink.ground))        .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(Ink.ink, lineWidth: Ink.stroke))        // A tap on a chip, the mic or Send keeps the keyboard up.        .keyboardStaysOnTap()    }    /// While the microphone listens, its live words stand in the field.    private var shownDraft: Binding<String> {        Binding(get: { listening ? (model.dictation.shown ?? model.draft) : model.draft },                set: { model.draft = $0; if listening { model.dictation.fieldChanged($0) } })    }    private var hint: String { model.answer?.composer.hint ?? "" }    /// Action and Note, the two switches beside the speaker (the core's    /// `pick.switches`; Action alone from a core that has none).    private var switches: [StorySceneAnswer.Pick.Row] {        if let given = model.answer?.pick.switches, !given.isEmpty { return given }        return [StorySceneAnswer.Pick.Row(kind: "action", character: nil, name: InkWords.line("composer.action"), tint: nil, suggested: false)]    }    private var listening: Bool {        switch model.dictation.phase {        case .listening, .preparing, .settling: true        default: false        }    }    /// `Ravi ▾`: who speaks next; a tap offers everyone else.    private var speakerChip: some View {        let name = speakerName        let speaking: Bool = if case .character = model.choice { true } else { false }        return InkChip(on: speaking) {            HStack(spacing: 4) {                Text(name)                Text("▾").accessibilityHidden(true)            }        }        .onTapGesture { model.sheet = .speaker(nil) }        .accessibilityAddTraits(.isButton)        .accessibilityLabel(model.answer?.pick.label ?? name)        .accessibilityValue(name)    }    private var speakerName: String {        guard let answer = model.answer else { return "" }        let rows = answer.pick.sections.flatMap(\.rows)        switch model.choice {        case .character(let id): return rows.first { $0.character == id }?.name ?? InkWords.line("kind.character")        case .action, .note:            // The chip still names the speaker the core would guess next.            if let id = answer.pick.suggestedSpeaker?.character, let row = rows.first(where: { $0.character == id }) { return row.name }            return rows.first { $0.kind == "character" }?.name ?? InkWords.line("kind.character")        }    }    private var mic: some View {        Button {            Task {                if listening {                    model.draft = await model.dictation.stop()                } else {                    // Before the phone is asked, and after it refused, a card says why first (below).                    await model.dictation.start(text: model.draft, selection: nil)                    if model.dictation.ask == nil, let refusal = model.dictation.refusal { model.story.notice = refusal }                }            }        } label: {            Image(systemName: listening ? "mic.fill" : "mic")                .font(.system(size: 18))                .foregroundStyle(listening ? Ink.blue : Ink.ink)                .frame(width: 44, height: 44)                .contentShape(Rectangle())        }        .buttonStyle(InkPress())        .accessibilityLabel(InkWords.line("scene.dictate"))    }}extension StorySceneAnswer.Pick {    /// The speaker the core would put next, whatever the next line's kind.    var suggestedSpeaker: StoryChoice? {        if case .character = suggested { return suggested }        return sections.first { $0.key == "characters" }?.rows.first { $0.suggested }?.choice            ?? sections.first { $0.key == "characters" }?.rows.first?.choice    }}/// The scene's sheets.private struct InkSceneSheetContent: View {    let model: InkSceneModel    let sheet: InkSceneSheet    var body: some View {        switch sheet {        case .whereWhen:            if let answer = model.answer {                InkWhereWhen(model: model, answer: answer)            }        case .acts(let line):            InkActsSheet(title: line.who ?? InkWords.line(line.kind == .note ? "kind.note" : "kind.action"), acts: acts(line))        case .speaker(let line):            InkSpeakerSheet(model: model, line: line)        case .direction(let line):            InkDirectionSheet(line: line) { words in Task { await model.direct(line, words) } }        case .naming:            InkNewCharacterSheet(model: model)        }    }    private func acts(_ line: StorySceneAnswer.Line) -> [InkAct] {        let lines = model.answer?.lines ?? []        let at = lines.firstIndex { $0.id == line.id } ?? 0        // Write after this first, as Android has it.        var acts = [InkAct(words: InkWords.line("scene.write_after")) { Task { await model.writeAfter(line) } }]        if at > 0 { acts.append(InkAct(words: InkWords.line("acts.move_earlier")) { Task { await model.move(line, by: -1) } }) }        if at < lines.count - 1 { acts.append(InkAct(words: InkWords.line("acts.move_later")) { Task { await model.move(line, by: 1) } }) }        if line.kind == .dialogue || line.kind == .action {            acts.append(InkAct(words: InkWords.line("scene.change_speaker")) { model.sheet = .speaker(line) })        }        if line.kind == .dialogue {            acts.append(InkAct(words: InkWords.line(line.aside == nil ? "scene.add_direction" : "scene.change_direction")) { model.sheet = .direction(line) })        }        acts.append(InkAct(words: InkWords.line("scene.delete"), quiet: true) { Task { await model.remove(line) } })        return acts    }}/// Who speaks (the next line, or a line being changed), as a panel in Ink/// that stands inside the safe area: its title and a close mark, a field to/// find someone once there are more than eight, then the characters in the/// core's order (the one suggested, those already in this scene, then the/// rest by lines spoken), Action first for a line being changed and New/// character… last. The rows scroll; a tap above the panel, a pull down on/// its top or the close mark closes it (owner on a phone, 20 Nov 2026).struct InkSpeakerSheet: View {    let model: InkSceneModel    let line: StorySceneAnswer.Line?    @State private var find = ""    @State private var rowsHeight: CGFloat = 0    @FocusState private var finding: Bool    @Environment(\.closeCard) private var closeCard    /// More than this many characters and the find field stands at the top.    static let findAbove = 8    var body: some View {        if let pick = model.answer?.pick {            let people = Self.people(pick, changing: line != nil)            VStack(alignment: .leading, spacing: 0) {                top(pick)                if people.count > Self.findAbove {                    InkField(hint: InkWords.line("pick.find"), text: $find, focused: $finding) {}                        .padding(.horizontal, Ink.gutter)                        .padding(.bottom, 4)                        .accessibilityIdentifier("ink-speaker-find")                }                ScrollView {                    rows(pick, people: Self.found(people, find))                        .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { rowsHeight = $0 }                }                .scrollIndicators(.automatic)                .frame(height: min(max(rowsHeight, 1), Self.limit))                .accessibilityIdentifier("ink-speaker-rows")            }            .padding(.bottom, 8)        }    }    /// The rows' greatest height: well under the screen, so the panel never    /// reaches the status bar and the scrim above it stays to tap.    static var limit: CGFloat {        let screen = (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.screen.bounds.height ?? 700        return max(240, screen * 0.55)    }    /// The title, with the close mark; a pull down here closes the panel.    private func top(_ pick: StorySceneAnswer.Pick) -> some View {        HStack(alignment: .firstTextBaseline) {            Text(pick.label)                .font(InkType.sceneTitle)                .foregroundStyle(Ink.quiet)                .accessibilityAddTraits(.isHeader)            Spacer(minLength: 12)            InkGlyph(symbol: "xmark", label: InkWords.line("home.close")) { closeCard?() }                .accessibilityIdentifier("ink-speaker-close")        }        .padding(.leading, Ink.gutter)        .padding(.trailing, Ink.gutter - 10)        .padding(.top, 14)        .contentShape(Rectangle())    }    private func rows(_ pick: StorySceneAnswer.Pick, people: [StorySceneAnswer.Pick.Row]) -> some View {        VStack(alignment: .leading, spacing: 0) {            if line != nil, find.isEmpty, let action = pick.switches?.first(where: { $0.kind == "action" }) {                row(action.name) { choose(action.choice) }                InkRule()            }            ForEach(Array(people.enumerated()), id: \.offset) { _, person in                row(person.name) { choose(person.choice) }                InkRule()            }            row(pick.new.label, quiet: true) { model.sheet = .naming }        }        .padding(.horizontal, Ink.gutter)    }    private func row(_ words: String, quiet: Bool = false, run: @escaping () -> Void) -> some View {        Button(action: run) {            Text(words)                .font(InkType.mono(16, relativeTo: .body))                .foregroundStyle(quiet ? Ink.quiet : Ink.ink)                .fixedSize(horizontal: false, vertical: true)                .frame(maxWidth: .infinity, alignment: .leading)                .padding(.vertical, 14)                .contentShape(Rectangle())        }        .buttonStyle(InkPress())    }    /// The characters as the core ordered them; a line being changed takes a    /// speaker or Action, never a note.    static func people(_ pick: StorySceneAnswer.Pick, changing: Bool) -> [StorySceneAnswer.Pick.Row] {        pick.sections.flatMap(\.rows).filter { !(changing && $0.kind == "note") }    }    /// Those whose name holds what is typed, in the same order, ignoring case and accents.    static func found(_ people: [StorySceneAnswer.Pick.Row], _ typed: String) -> [StorySceneAnswer.Pick.Row] {        let words = typed.trimmingCharacters(in: .whitespacesAndNewlines)        guard !words.isEmpty else { return people }        return people.filter { $0.name.range(of: words, options: [.caseInsensitive, .diacriticInsensitive]) != nil }    }    private func choose(_ choice: StoryChoice) {        if let line {            Task { await model.speaker(line, to: choice) }        } else {            model.chosen = choice            model.sheet = nil        }    }}/// A direction under the speaker's name, `(not looking up)`.struct InkDirectionSheet: View {    let line: StorySceneAnswer.Line    let done: (String) -> Void    @State private var words: String    @FocusState private var focused: Bool    @Environment(\.closeCard) private var closeCard    /// Closes the panel this stands in.    private func dismiss() { closeCard?() }    init(line: StorySceneAnswer.Line, done: @escaping (String) -> Void) {        self.line = line        self.done = done        _words = State(initialValue: line.aside ?? "")    }    var body: some View {        VStack(alignment: .leading, spacing: 18) {            InkSheetTop(title: InkWords.line("scene.direction_title"), close: InkWords.line("home.close")) { dismiss() }            Text(line.text)                .font(InkType.line)                .foregroundStyle(Ink.quiet)                .lineLimit(2)            InkField(hint: InkWords.line("scene.direction_hint"), text: $words, focused: $focused, font: InkType.direction) { done(words) }            HStack {                Spacer()                InkButton(words: InkWords.line("picker.done")) { done(words) }            }            Spacer(minLength: 0)        }        .padding(.horizontal, Ink.gutter)        .padding(.top, 22)        .onAppear { focused = true }    }}/// New character…: their name, then the next line is theirs.struct InkNewCharacterSheet: View {    let model: InkSceneModel    @State private var name = ""    @FocusState private var focused: Bool    @Environment(\.closeCard) private var closeCard    /// Closes the panel this stands in.    private func dismiss() { closeCard?() }    var body: some View {        VStack(alignment: .leading, spacing: 18) {            InkSheetTop(title: model.answer?.pick.new.label ?? "", close: InkWords.line("home.close")) { dismiss() }            InkField(hint: model.answer?.pick.new.hint ?? "", text: $name, focused: $focused, font: InkType.title(22, relativeTo: .title2)) { add() }            HStack {                Spacer()                InkButton(words: InkWords.line("picker.done")) { add() }            }            Spacer(minLength: 0)        }        .padding(.horizontal, Ink.gutter)        .padding(.top, 22)        .onAppear { focused = true }    }    private func add() {        let named = name.trimmingCharacters(in: .whitespacesAndNewlines)        guard !named.isEmpty else { return }        Task { await model.named(named) }    }}#endif