Cotton code
215 lines · 9.1 KB · SwiftRaw
// Cotton Story's SCENE AS A CHAT (`scene.chat`, the owner's own idea; contract// 17 Nov 2026): the scene read as a conversation. Each speech is a bubble// under its speaker's name; in a two-hander the first speaker's bubbles sit// on the left and the other's on the right; with more voices every bubble// sits left under its name. Action is narration, centred between the// bubbles; an aside rides in its speech's bubble, quieter. Read-only: the// writer is the same writer whichever face the scene wears.//// Slots: `number`, `title` (the heading), `lines` (as the core read them)// or `body`. Every word is the core's.import CottonPaperimport CottonValuesimport SwiftUIenum StorySceneChatKnobs {    static let bubbleCorner: CGFloat = 18    static let bubblePad = EdgeInsets(top: 9, leading: 13, bottom: 9, trailing: 13)    static let bubbleWidth: CGFloat = 0.78    static let gap: CGFloat = 10}/// One beat of the conversation: a speech by a speaker, or narration.struct StoryChatBeat: Equatable {    enum Side { case left, right }    var speaker: String?    var aside: String?    var words: String    var side: Side    var narration: Bool    /// The scene's lines folded into beats: a name, its asides and speech    /// make one bubble; action and cuts make narration.    static func of(_ lines: [StoryLine]) -> [StoryChatBeat] {        let speakers = lines.filter { $0.kind == .character }.map { name(of: $0.text) }        let voices = speakers.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }        let twoHander = voices.count == 2        var beats: [StoryChatBeat] = []        var speaker: String?        var aside: String?        var speech: [String] = []        func close() {            if let who = speaker, !speech.isEmpty {                let side: Side = twoHander && who == voices[1] ? .right : .left                beats.append(StoryChatBeat(speaker: who, aside: aside, words: speech.joined(separator: "\n"), side: side, narration: false))            }            speaker = nil            aside = nil            speech = []        }        for line in lines {            switch line.kind {            case .character:                close()                speaker = name(of: line.text)            case .parenthetical:                if speaker != nil, speech.isEmpty { aside = line.text } else if speaker != nil { speech.append(line.text) }            case .dialogue:                if speaker != nil { speech.append(line.text) }            case .blank:                close()            case .action, .transition, .centered, .heading:                close()                if !line.text.isEmpty {                    if let last = beats.last, last.narration, beats.count > 0, line.kind == .action {                        beats[beats.count - 1].words += " " + line.text                    } else {                        beats.append(StoryChatBeat(speaker: nil, aside: nil, words: line.text, side: .left, narration: true))                    }                }            case .note:                continue            }        }        close()        return beats    }    /// A speaker's name without its extension: "MEERA (V.O.)" speaks as MEERA.    static func name(of cue: String) -> String {        let trimmed = cue.trimmingCharacters(in: .whitespaces)        if let open = trimmed.firstIndex(of: "(") {            return String(trimmed[..<open]).trimmingCharacters(in: .whitespaces)        }        return trimmed.replacingOccurrences(of: "^", with: "").trimmingCharacters(in: .whitespaces)    }}struct StorySceneChatFace: View {    let card: DeckCard    init(card: DeckCard) {        self.card = card    }    var body: some View {        VStack(alignment: .leading, spacing: StoryCardKnobs.gap) {            HStack(alignment: .firstTextBaseline, spacing: 8) {                if let number = card.text("number") {                    StoryQuietLine(text: number)                }                if let heading = card.text("title") {                    Text(verbatim: heading)                        .font(StoryType.script(14, relativeTo: .subheadline).bold())                        .foregroundStyle(StoryMaterial.ink.colour)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("deck-title")                        .facePart(.title)                }            }            Rectangle().fill(StoryMaterial.hairline.colour).frame(height: 1)            GeometryReader { box in                VStack(alignment: .leading, spacing: StorySceneChatKnobs.gap) {                    ForEach(Array(StoryChatBeat.of(StoryLine.of(card)).enumerated()), id: \.offset) { _, beat in                        if beat.narration {                            Text(verbatim: beat.words)                                .font(StoryType.sans(.footnote).italic())                                .foregroundStyle(StoryMaterial.quiet.colour)                                .multilineTextAlignment(.center)                                .fixedSize(horizontal: false, vertical: true)                                .frame(maxWidth: .infinity)                                .padding(.horizontal, 12)                        } else {                            StoryBubble(beat: beat, width: box.size.width * StorySceneChatKnobs.bubbleWidth)                                .frame(maxWidth: .infinity, alignment: beat.side == .left ? .leading : .trailing)                        }                    }                }                .frame(width: box.size.width, alignment: .topLeading)            }            .storyFadesOut()            .accessibilityIdentifier("scene-chat")            .facePart(.body)        }        .padding(StoryCardKnobs.inset)        .storySheet()        .accessibilityElement(children: .contain)    }}private struct StoryBubble: View {    let beat: StoryChatBeat    let width: CGFloat    var body: some View {        let other = beat.side == .right        VStack(alignment: other ? .trailing : .leading, spacing: 3) {            if let speaker = beat.speaker {                Text(verbatim: speaker)                    .font(StoryType.sans(.caption, weight: .semibold))                    .foregroundStyle(StoryMaterial.quiet.colour)                    .padding(.horizontal, 6)            }            VStack(alignment: .leading, spacing: 2) {                if let aside = beat.aside {                    Text(verbatim: aside)                        .font(StoryType.sans(.footnote).italic())                        .foregroundStyle(other ? StoryMaterial.bubbleOtherInk.colour.opacity(0.7) : StoryMaterial.quiet.colour)                }                Text(verbatim: beat.words)                    .font(StoryType.sans(.callout))                    .foregroundStyle(other ? StoryMaterial.bubbleOtherInk.colour : StoryMaterial.ink.colour)            }            .fixedSize(horizontal: false, vertical: true)            .padding(StorySceneChatKnobs.bubblePad)            .background(                RoundedRectangle(cornerRadius: StorySceneChatKnobs.bubbleCorner, style: .continuous)                    .fill(other ? StoryMaterial.bubbleOther.colour : StoryMaterial.bubble.colour)            )        }        .frame(maxWidth: width, alignment: other ? .trailing : .leading)    }}/// The chat face, and the cards it is reviewed in.public enum StorySceneChatFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .blank    public static let face = Face(id: "scene.chat", specimens: [        Specimen("two-hander", twoHander), Specimen("telugu", telugu), Specimen("crowd", crowd),    ]) { card, _, _ in        StorySceneChatFace(card: card)    }    public static let twoHander = DeckCard(face: "scene.chat", corner: nil, pressing: false, pace: nil, plate: nil, fields: [        "number": .text("3"),        "title": .text("INT. LIGHTHOUSE KITCHEN - NIGHT"),        "lines": StoryLine.fields(StorySpecimenLinesCatalogue.twoHander),    ])    public static let telugu = DeckCard(face: "scene.chat", corner: nil, pressing: false, pace: nil, plate: nil, fields: [        "number": .text("7"),        "title": .text("INT. వంటగది - రాత్రి"),        "lines": StoryLine.fields(StorySpecimenLinesCatalogue.telugu),    ])    /// Three voices: every bubble on the left, under its name.    public static let crowd = DeckCard(face: "scene.chat", corner: nil, pressing: false, pace: nil, plate: nil, fields: [        "number": .text("9"),        "title": .text("EXT. FERRY DECK - DAY"),        "lines": StoryLine.fields([            StoryLine(.action, "Gulls. The ferry horn. Three of them at the rail."),            StoryLine(.blank, ""),            StoryLine(.character, "ANU"),            StoryLine(.dialogue, "Is that the island?"),            StoryLine(.blank, ""),            StoryLine(.character, "OLD SAILOR"),            StoryLine(.dialogue, "That is fog, child."),            StoryLine(.blank, ""),            StoryLine(.character, "RAVI (O.S.)"),            StoryLine(.dialogue, "Anu! Away from the rail."),        ]),    ])}