Cotton code
637 lines · 23.5 KB · SwiftRaw
// Cotton Story's door to the core: the script home, a scene, its lines, the// pages. The core answers every screen whole and takes every change// (`crates/cotton-ffi/src/phone/story_desk.rs`): order, previews, minutes,// the cast and every word in an answer come from it, and the Ink screens// (`Story/Ink`) draw them. This file names those methods and decodes their// answers exactly as the core writes them.import CottonKitimport CottonValuesimport Foundationimport SwiftUI/// The writer's-tool methods, by name.enum StoryDeskMethod {    static let list = "story.list"    static let scenes = "story.scenes"    static let scene = "story.scene"    static let draft = "story.draft"    static let sceneAdd = "story.scene.add"    static let sceneLeave = "story.scene.leave"    static let choose = "story.choose"    static let scenePlace = "story.scene.place"    static let sequenceEdit = "story.sequence.edit"    static let lineAdd = "story.line.add"    static let lineEdit = "story.line.edit"    static let lineRemove = "story.line.remove"    static let characterAdd = "story.character.add"    static let sceneRemove = "story.scene.remove"    static let lineMove = "story.line.move"}/// A colour the core names, `#RRGGBB`.struct StoryHex: Decodable, Hashable {    let hex: String    init(_ hex: String) { self.hex = hex }    init(from decoder: any Decoder) throws {        hex = try decoder.singleValueContainer().decode(String.self)    }    var colour: Color {        let digits = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex        let value = UInt32(digits, radix: 16) ?? 0        return Color(red: Double((value >> 16) & 0xFF) / 255, green: Double((value >> 8) & 0xFF) / 255, blue: Double(value & 0xFF) / 255)    }}/// A character's tint: the ink their initial is ringed in and the paper/// their speech is written on.struct StoryTint: Decodable, Hashable {    let key: String    let ink: StoryHex    let paper: StoryHex}/// A character as the composer offers them.struct StoryChip: Decodable, Equatable, Identifiable {    let id: String    let name: String    let initial: String    let tint: StoryTint}// MARK: - The stories/// `story.list {}`: every story, the current one marked.struct StoryListAnswer: Decodable, Equatable {    struct Story: Decodable, Equatable, Identifiable {        let id: String        let title: String        let summary: String        let current: Bool    }    let stories: [Story]    let empty: String    /// A signed-in phone with no script yet whose scripts may still be coming    /// down: the home says `arrivingLine` and offers nothing until they land.    let arriving: Bool?    let arrivingLine: String?    enum CodingKeys: String, CodingKey {        case stories, empty, arriving        case arrivingLine = "arriving_line"    }}// MARK: - The scene list (picture 1)/// `story.scenes { story? }`: the whole scene list, in order and folded.struct StoryScenesAnswer: Decodable, Equatable {    struct Story: Decodable, Equatable {        let id: String        let title: String        /// `5 scenes · 7 min`.        let summary: String        /// About this script's facts.        let logline: String?        let writtenBy: String?        enum CodingKeys: String, CodingKey {            case id, title, summary, logline            case writtenBy = "written_by"        }    }    /// The pinned slip: the next question, or the words that stand once all are answered.    struct Slip: Decodable, Equatable {        let title: String        let key: String?        let question: String    }    struct Preview: Decodable, Equatable {        let kind: String        let text: String        let tint: StoryTint?    }    struct Row: Decodable, Equatable, Identifiable {        enum Kind: String, Decodable { case scene, sequence, interval }        let kind: Kind        private let rowID: String?        // A scene's.        /// Its number, printed from the order.        let number: Int?        let title: String?        let dot: StoryHex?        let minutesWord: String?        let preview: Preview?        let unwritten: Bool?        let question: String?        /// The one line that tells it apart: the summary, else its first line.        let line: String?        // A sequence's.        let folded: Bool?        let summary: String?        // The interval's.        let words: String?        /// The interval has no row of its own; it is the one interval.        var id: String { rowID ?? "interval" }        enum CodingKeys: String, CodingKey {            case kind, number, title, dot, preview, unwritten, question, folded, summary, words, line            case rowID = "id"            case minutesWord = "minutes_word"        }    }    /// One of the cast on the script home, ordered by lines spoken.    struct Person: Decodable, Equatable, Identifiable {        let id: String        let name: String        let initial: String        let lines: Int?        /// Their face's media key, when they have one.        let picture: String?    }    /// A fixed pill on the script home: `read`, `places`, `views`.    struct Door: Decodable, Equatable, Identifiable {        let key: String        let words: String        var id: String { key }    }    let story: Story    let slip: Slip    let rows: [Row]    let cast: [Person]?    let doors: [Door]?    /// The Plus's spoken name.    let add: String    var scenes: [Row] { rows.filter { $0.kind == .scene } }}// MARK: - The scene (pictures 3 and 4)/// `story.scene { id, after?, editing? }`: one scene's lines as the writer/// sets them down, the characters to write as, what the composer says, and/// the sheet that sets its place and time.struct StorySceneAnswer: Decodable, Equatable {    struct Line: Decodable, Equatable, Identifiable {        enum Kind: String, Decodable { case action, dialogue, note, enters }        let id: String        let kind: Kind        let text: String        /// A speech's cue, `RAVI`.        let who: String?        /// The speaker's character id.        let character: String?        let initial: String?        let tint: StoryTint?        /// A direction under the name, `not looking up` (drawn in brackets).        let aside: String?        /// How VoiceOver reads the line whole.        let label: String    }    struct Insert: Decodable, Equatable {        /// A line id, or `start`.        let after: String        let words: String    }    struct Picker: Decodable, Equatable {        struct Time: Decodable, Equatable, Identifiable {            let band: String            let word: String            let dot: StoryHex            var id: String { band }        }        struct Setting: Decodable, Equatable, Identifiable {            /// `INT.` or `EXT.`.            let setting: String            let word: String            var id: String { setting }        }        let title: String        let hint: String        let place: String        /// The places this script already uses, most used first.        let used: [String]?        /// "Places you have used".        let usedLabel: String?        /// `INT.`, `EXT.`, or none yet.        let setting: String?        let settings: [Setting]?        let band: String?        let times: [Time]        let summary: String?        let summaryHint: String?        let done: String        enum CodingKeys: String, CodingKey {            case title, hint, place, used, setting, settings, band, times, summary, done            case summaryHint = "summary_hint"            case usedLabel = "used_label"        }    }    struct Composer: Decodable, Equatable {        let action: String        let note: String        let hint: String        let draft: String        /// `Adding after Ravi's line`, `Changing Ravi's line`; nil when writing at the end.        let banner: String?        /// The words of the line being changed.        let text: String?        let close: String        /// VoiceOver's action on a line: write the next one after it.        let insert: String        let remove: String        let send: String    }    /// The composer's pick (`story.scene`'s `pick`): who or what the next    /// line is. The core orders every row and suggests the next; the phone    /// draws them as given.    struct Pick: Decodable, Equatable {        struct Next: Decodable, Equatable {            let kind: String            let character: String?        }        struct Row: Decodable, Equatable {            let kind: String            let character: String?            let name: String            let tint: StoryTint?            let suggested: Bool            /// The row's choice.            var choice: StoryChoice {                switch kind {                case "note": .note                case "character": character.map { .character($0) } ?? .action                default: .action                }            }        }        struct Section: Decodable, Equatable {            let key: String            let rows: [Row]        }        struct New: Decodable, Equatable {            let label: String            let hint: String        }        let next: Next        /// The characters, as the chooser lists them.        let sections: [Section]        /// The bar's two switches beside the speaker: Action and Note.        let switches: [Row]?        let new: New        /// The chip's spoken name.        let label: String        /// The choice the core suggests for the next line.        var suggested: StoryChoice {            switch next.kind {            case "note": .note            case "character": next.character.map { .character($0) } ?? .action            default: .action            }        }    }    let id: String    let story: String    /// `Kitchen · night`.    let title: String    let place: String    /// The time of day as written, `night`.    let time: String?    let dot: StoryHex?    /// `INT. KITCHEN - NIGHT`.    let slugline: String    let question: String?    let lines: [Line]    let chips: [StoryChip]    let insert: Insert?    let editing: String?    let picker: Picker    let composer: Composer    let pick: Pick    /// Whether the scene has its place yet (a new scene opens on the place sheet).    var placed: Bool { !place.trimmingCharacters(in: .whitespaces).isEmpty }}/// `story.line.add`'s answer: the new line and the scene again.struct StoryLineAdded: Decodable {    let line: String    let scene: StorySceneAnswer}/// `story.draft { story }`: the story laid out as screenplay pages (the page/// model `story.script` answers), with the words the draft's Share says.struct StoryDraftAnswer: Decodable {    let title: String    let script: StoryScript    let share: String    let pdf: String    let fountain: String    let fountainText: String    let fountainName: String    enum CodingKeys: String, CodingKey {        case title, paper, pages, scenes, share, pdf, fountain        case fountainText = "fountain_text"        case fountainName = "fountain_name"    }    init(from decoder: any Decoder) throws {        let container = try decoder.container(keyedBy: CodingKeys.self)        title = try container.decode(String.self, forKey: .title)        script = StoryScript(paper: try container.decode(StoryScript.Paper.self, forKey: .paper), titlePage: nil,                             pages: try container.decode([StoryScript.Page].self, forKey: .pages),                             scenes: try container.decode([StoryScript.SceneStart].self, forKey: .scenes))        share = try container.decode(String.self, forKey: .share)        pdf = try container.decode(String.self, forKey: .pdf)        fountain = try container.decode(String.self, forKey: .fountain)        fountainText = try container.decode(String.self, forKey: .fountainText)        fountainName = try container.decode(String.self, forKey: .fountainName)    }}// MARK: - The door/// Where the next line goes, or which line is being changed.enum StoryComposing: Equatable {    case end    /// After a line id, or `start`.    case after(String)    case editing(String)    static let start = "start"}/// What the next line is written as: a character's speech, action or a note.enum StoryChoice: Equatable {    case character(String)    case action    case note    var kind: StorySceneAnswer.Line.Kind {        switch self {        case .character: .dialogue        case .action: .action        case .note: .note        }    }    var character: String? {        if case .character(let id) = self { id } else { nil }    }}/// Everything the four screens ask, and every change they make.@MainActorprotocol StoryBook: AnyObject {    func list() async throws -> StoryListAnswer    /// A new story by its title; answers its id.    func start(title: String) async throws -> String    func scenes(story: String?) async throws -> StoryScenesAnswer    func addScene(story: String) async throws -> String    /// A new scene straight after `scene` (`story.scene.new { after }`).    func addScene(after scene: String) async throws -> String    /// A scene to a place in the order, from 1.    func moveScene(_ scene: String, to: Int) async throws    /// The writer closed a scene Plus made: the core drops it if it holds nothing.    func leaveScene(_ scene: String) async throws    /// The screenplay a fan tile opened is the one being written.    func choose(story: String) async throws    func placeScene(_ scene: String, after: String?, across: Bool) async throws -> StoryScenesAnswer    func fold(_ sequence: String, folded: Bool) async throws -> StoryScenesAnswer    func scene(_ scene: String, composing: StoryComposing) async throws -> StorySceneAnswer    func addLine(scene: String, after: String?, choice: StoryChoice, text: String) async throws -> StoryLineAdded    func editLine(scene: String, line: String, choice: StoryChoice, text: String) async throws -> StorySceneAnswer    func removeLine(scene: String, line: String) async throws -> StorySceneAnswer    func setPlace(scene: String, place: String, time: String) async throws -> StorySceneAnswer    /// A character by name in the story (the one already there by that name, or a new one); answers their id.    func addCharacter(story: String, name: String) async throws -> String    func draft(story: String) async throws -> StoryDraftAnswer    // The Ink screens' writes.    func moveScene(_ scene: String, by: Int) async throws    func duplicateScene(_ scene: String) async throws    func removeScene(_ scene: String) async throws    /// The scene's heading parts and one-line summary; `nil` leaves a part as it is.    func writeScene(_ scene: String, setting: String?, place: String?, time: String?, summary: String?) async throws    func setAside(scene: String, line: String, aside: String?) async throws -> StorySceneAnswer    func moveLine(scene: String, line: String, by: Int) async throws -> StorySceneAnswer    func near(_ scene: String) async throws -> StoryNear    func rename(story: String, title: String) async throws    func writeFacts(story: String, _ facts: StoryFacts) async throws    /// The script to Deleted (it can come back from there).    func deleteScript(_ story: String) async throws}/// About this script's facts, as the person writes them.struct StoryFacts: Equatable {    let title: String    let writtenBy: String    let logline: String}/// `story.scene.near`: the writer's previous and next scene, and "3 of 12".struct StoryNear: Decodable, Equatable {    let previous: String?    let next: String?    let number: Int    let of: Int}extension StoryDraftAnswer: Identifiable {    var id: String { fountainName }}/// The book, from the core.@MainActorfinal class CoreStoryBook: StoryBook {    private let core: any CottonCalling    init(core: any CottonCalling) {        self.core = core    }    private struct Story: Encodable { let story: String? }    private struct Start: Encodable { let title: String }    private struct Started: Decodable { let story: String }    private struct Added: Decodable { let scene: String }    private struct Place: Encodable { let id: String; let after: String?; let across: Bool }    private struct Fold: Encodable { let id: String; let folded: Bool }    private struct SceneAsk: Encodable { let id: String; let after: String?; let editing: String? }    private struct LineAdd: Encodable { let scene: String; let kind: String; let text: String; let character: String?; let after: String? }    private struct LineEdit: Encodable { let scene: String; let id: String; let kind: String; let text: String; let character: String? }    private struct LineRemove: Encodable { let scene: String; let id: String }    private struct SceneWrite: Encodable { let id: String; let place: String; let time: String }    private struct CharacterAdd: Encodable { let story: String; let name: String }    private struct CharacterAdded: Decodable { let character: StoryChip }    func list() async throws -> StoryListAnswer {        try await core.call(StoryDeskMethod.list, EmptyRequest(), as: StoryListAnswer.self)    }    @discardableResult    func start(title: String) async throws -> String {        try await core.call(StoryMethod.start, Start(title: title), as: Started.self).story    }    func scenes(story: String?) async throws -> StoryScenesAnswer {        try await core.call(StoryDeskMethod.scenes, Story(story: story), as: StoryScenesAnswer.self)    }    func addScene(story: String) async throws -> String {        try await core.call(StoryDeskMethod.sceneAdd, Story(story: story), as: Added.self).scene    }    private struct After: Encodable { let after: String }    private struct MoveTo: Encodable { let id: String; let to: Int }    func addScene(after scene: String) async throws -> String {        try await core.call(StoryMethod.sceneNew, After(after: scene), as: Added.self).scene    }    func moveScene(_ scene: String, to: Int) async throws {        _ = try await core.call(StoryMethod.sceneMove, MoveTo(id: scene, to: to), as: JSONValue.self)    }    func leaveScene(_ scene: String) async throws {        _ = try await core.call(StoryDeskMethod.sceneLeave, ["id": scene], as: JSONValue.self)    }    func choose(story: String) async throws {        _ = try await core.call(StoryDeskMethod.choose, ["story": story], as: JSONValue.self)    }    func placeScene(_ scene: String, after: String?, across: Bool) async throws -> StoryScenesAnswer {        try await core.call(StoryDeskMethod.scenePlace, Place(id: scene, after: after, across: across), as: StoryScenesAnswer.self)    }    func fold(_ sequence: String, folded: Bool) async throws -> StoryScenesAnswer {        try await core.call(StoryDeskMethod.sequenceEdit, Fold(id: sequence, folded: folded), as: StoryScenesAnswer.self)    }    func scene(_ scene: String, composing: StoryComposing) async throws -> StorySceneAnswer {        let ask: SceneAsk        switch composing {        case .end: ask = SceneAsk(id: scene, after: nil, editing: nil)        case .after(let line): ask = SceneAsk(id: scene, after: line, editing: nil)        case .editing(let line): ask = SceneAsk(id: scene, after: nil, editing: line)        }        return try await core.call(StoryDeskMethod.scene, ask, as: StorySceneAnswer.self)    }    func addLine(scene: String, after: String?, choice: StoryChoice, text: String) async throws -> StoryLineAdded {        let ask = LineAdd(scene: scene, kind: choice.kind.rawValue, text: text, character: choice.character, after: after)        return try await core.call(StoryDeskMethod.lineAdd, ask, as: StoryLineAdded.self)    }    func editLine(scene: String, line: String, choice: StoryChoice, text: String) async throws -> StorySceneAnswer {        let ask = LineEdit(scene: scene, id: line, kind: choice.kind.rawValue, text: text, character: choice.character)        return try await core.call(StoryDeskMethod.lineEdit, ask, as: StorySceneAnswer.self)    }    func removeLine(scene: String, line: String) async throws -> StorySceneAnswer {        try await core.call(StoryDeskMethod.lineRemove, LineRemove(scene: scene, id: line), as: StorySceneAnswer.self)    }    func setPlace(scene: String, place: String, time: String) async throws -> StorySceneAnswer {        _ = try await core.call(StoryMethod.sceneWrite, SceneWrite(id: scene, place: place, time: time), as: JSONValue.self)        return try await self.scene(scene, composing: .end)    }    func addCharacter(story: String, name: String) async throws -> String {        try await core.call(StoryDeskMethod.characterAdd, CharacterAdd(story: story, name: name), as: CharacterAdded.self).character.id    }    func draft(story: String) async throws -> StoryDraftAnswer {        try await core.call(StoryDeskMethod.draft, Story(story: story), as: StoryDraftAnswer.self)    }    private struct Move: Encodable { let id: String; let by: Int }    private struct Heading: Encodable { let id: String; let setting: String?; let place: String?; let time: String?; let summary: String? }    private struct Aside: Encodable { let scene: String; let id: String; let aside: String? }    func moveScene(_ scene: String, by: Int) async throws {        _ = try await core.call(StoryMethod.sceneMove, Move(id: scene, by: by), as: JSONValue.self)    }    func duplicateScene(_ scene: String) async throws {        _ = try await core.call(StoryMethod.sceneDuplicate, ["id": scene], as: JSONValue.self)    }    func removeScene(_ scene: String) async throws {        _ = try await core.call(StoryDeskMethod.sceneRemove, ["id": scene], as: JSONValue.self)    }    func writeScene(_ scene: String, setting: String?, place: String?, time: String?, summary: String?) async throws {        _ = try await core.call(StoryMethod.sceneWrite, Heading(id: scene, setting: setting, place: place, time: time, summary: summary), as: JSONValue.self)    }    func setAside(scene: String, line: String, aside: String?) async throws -> StorySceneAnswer {        try await core.call(StoryDeskMethod.lineEdit, Aside(scene: scene, id: line, aside: aside), as: StorySceneAnswer.self)    }    private struct LineMove: Encodable { let scene: String; let id: String; let by: Int }    func moveLine(scene: String, line: String, by: Int) async throws -> StorySceneAnswer {        try await core.call(StoryDeskMethod.lineMove, LineMove(scene: scene, id: line, by: by), as: StorySceneAnswer.self)    }    func near(_ scene: String) async throws -> StoryNear {        try await core.call(StoryMethod.sceneNear, ["id": scene], as: StoryNear.self)    }    func writeFacts(story: String, _ facts: StoryFacts) async throws {        _ = try await core.callJSON(StoryMethod.recordsUpdate, [            "table": RecordValue.text(StoryTable.story), "id": .text(story),            "patch": .object(["title": .text(facts.title), "written_by": .text(facts.writtenBy), "logline": .text(facts.logline)]),        ])    }    func deleteScript(_ story: String) async throws {        _ = try await core.callJSON(StoryMethod.recordsDelete, [            "table": RecordValue.text(StoryTable.story), "id": .text(story), "today": .text(Self.today()),        ])    }    private static func today() -> String {        let format = DateFormatter()        format.calendar = Calendar(identifier: .gregorian)        format.locale = Locale(identifier: "en_US_POSIX")        format.dateFormat = "yyyy-MM-dd"        return format.string(from: Date())    }    func rename(story: String, title: String) async throws {        _ = try await core.callJSON(StoryMethod.recordsUpdate, [            "table": RecordValue.text(StoryTable.story), "id": .text(story), "patch": .object(["title": .text(title)]),        ])    }}