Cotton code
594 lines · 23.3 KB · SwiftRaw
// Cotton Story in the Ink look (assets/design/story/DECISIONS.md, ink.html,// wireframes.html): the whole app, mounted by the root in place of the fan and// the board (`RootView.hosts`), as Cotton Vault and Cotton Health are. It// opens on the script last worked on, which is home and has no back button;// the other scripts are in a sheet behind the title. Every answer is the// core's (`StoryBook`); the screens draw them in `InkLook`.#if os(iOS)import CottonKitimport CottonValuesimport SwiftUIimport UniformTypeIdentifiers/// Where the stack has gone from the script home.enum InkRoute: Hashable {    /// A scene being written; `fresh` when Plus just made it (it opens on Where and when).    case scene(String, fresh: Bool)    /// The script as pages, from the start or at a scene.    case read(story: String, at: String?)    /// About this script.    case about(String)    case settings    /// A character's page, from a face on the home.    case character(String)    /// Every place in the script, under the door's words.    case places(story: String, title: String)    case place(String)    /// The script's drafts, from About.    case drafts(String)    /// A marked draft's pages.    case readDraft(story: String, draft: String, name: String)    /// Everything one character says, in order.    case lines(String)    /// What changed since a draft.    case changes(draft: String, name: String)}/// A sheet over the screen.enum InkSheet: Identifiable, Equatable {    case scripts    case naming    case views    case sceneActs(StoryScenesAnswer.Row)    case more    var id: String {        switch self {        case .scripts: "scripts"        case .naming: "naming"        case .views: "views"        case .sceneActs(let row): "acts-\(row.id)"        case .more: "more"        }    }}/// Story's words that are not in an answer, from the `story` line set.enum InkWords {    static func line(_ path: String, _ fills: [String: String] = [:]) -> String {        ShellLines.line("story", path, fills)    }    /// A counted line: `path.one` for one, else `path.other` with `{n}`    /// (and `path.zero` for none, where the set has one).    static func counted(_ path: String, _ n: Int, _ fills: [String: String] = [:]) -> String {        var all = fills        all["n"] = String(n)        if n == 0, let zero = ShellLines.shipped("story", path + ".zero", all) { return zero }        return line(path + (n == 1 ? ".one" : ".other"), all)    }}@MainActor @Observablefinal class InkStory {    /// The script home, as `story.scenes` answers it.    var home: StoryScenesAnswer?    /// Every script, for the sheet behind the title.    var scripts: StoryListAnswer?    /// No script yet: the first screen.    var none = false    /// No script here yet but they may still be coming down: the one quiet    /// line said instead of the first screen, until they land or stop coming.    var arriving: String?    var path: [InkRoute] = []    var sheet: InkSheet?    /// A refusal, said once at the foot of the screen.    var notice: String?    /// A file to bring in is being chosen.    var bringing = false    /// A printed script just brought in: the line asking to read it through,    /// shown quietly on its home until it is tapped away or another script is home.    var check: (story: String, words: String)?    @ObservationIgnored let book: any StoryBook    @ObservationIgnored let core: any CottonCalling    /// People, places and drafts.    var shelf: StoryShelf { StoryShelf(core: core) }    /// Listen, kept by the app so it goes on with the screen off and over a scene opened from Read; leaving Read stops it.    let listen = InkListen()    init(core: any CottonCalling) {        self.core = core        self.book = CoreStoryBook(core: core)    }    var story: String? { home?.story.id }    func load() async {        await attempt {            let list = try await book.list()            scripts = list            guard !list.stories.isEmpty else {                arriving = (list.arriving ?? false) ? (list.arrivingLine ?? InkWords.line("home.arriving")) : nil                none = arriving == nil                home = nil                return            }            arriving = nil            none = false            home = try await book.scenes(story: nil)        }    }    /// The scene list again, after a write.    func reloadHome() async {        await attempt { home = try await book.scenes(story: story) }    }    func choose(_ script: String) async {        sheet = nil        path = []        await attempt { try await book.choose(story: script) }        await load()    }    /// A new script by its title: it becomes home, then its first scene is offered.    func start(_ title: String) async {        sheet = nil        path = []        await attempt { _ = try await book.start(title: title) }        await load()    }    /// Plus: a new scene at the end, opened on Where and when.    func newScene() async {        guard let story else { return }        await attempt {            let made = try await book.addScene(story: story)            path.append(.scene(made, fresh: true))            await reloadHome()        }    }    /// Back from a scene Plus made: one that holds nothing goes.    func left(_ scene: String) async {        await attempt { try await book.leaveScene(scene) }        await reloadHome()    }    func move(_ scene: String, by: Int) async {        sheet = nil        await attempt { try await book.moveScene(scene, by: by) }        await reloadHome()    }    /// A scene dropped at a place in the order, from 1.    func move(_ scene: String, to: Int) async {        await attempt { try await book.moveScene(scene, to: to) }        await reloadHome()    }    /// New scene after this: made straight after it, opened on Where and when.    func newScene(after scene: String) async {        sheet = nil        await attempt {            let made = try await book.addScene(after: scene)            path.append(.scene(made, fresh: true))            await reloadHome()        }    }    func duplicate(_ scene: String) async {        sheet = nil        await attempt { try await book.duplicateScene(scene) }        await reloadHome()    }    func remove(_ scene: String) async {        sheet = nil        await attempt { try await book.removeScene(scene) }        await reloadHome()    }    /// Delete this script: it goes to Deleted, and the next one is home.    func deleteScript(_ script: String) async {        await attempt { try await book.deleteScript(script) }        path = []        await load()    }    func bring(_ url: URL) async {        let came = await StoryFountainOpen.bring(url, core: core) { [weak self] words, _ in self?.notice = words }        path = []        sheet = nil        await load()        if let came { brought(came.check) }    }    /// A script came in (here or by Open in): its check stands on its home.    func brought(_ check: String?) {        guard let check, !check.isEmpty, let story else { return }        self.check = (story, check)    }    #if COTTON_DEV    /// The look asked for opens the first scene's Where and when.    static var lookAtWhere = false    /// The look asked for opens the first scene's speaker chooser.    static var lookAtSpeaker = false    /// A look on a simulator opens a screen by name: `-story-ink-open    /// scene|where|speaker|read|scripts|views|more|acts`.    func openForALook() {        guard let open = UserDefaults.standard.string(forKey: "story-ink-open") else { return }        if open == "naming" { sheet = .naming; return }        if open == "new" { Task { await start(InkWords.line("fan.untitled")) }; return }        guard let home else { return }        let first = home.scenes.first        switch open {        case "scene": if let first { path = [.scene(first.id, fresh: false)] }        case "where": if let first { InkStory.lookAtWhere = true; path = [.scene(first.id, fresh: false)] }        case "speaker": if let first { InkStory.lookAtSpeaker = true; path = [.scene(first.id, fresh: false)] }        case "read": path = [.read(story: home.story.id, at: nil)]        case "scripts": sheet = .scripts        case "views": sheet = .views        case "more": sheet = .more        case "about": path = [.about(home.story.id)]        case "settings": path = [.settings]        case "character": if let person = home.cast?.first { path = [.character(person.id)] }        case "places": path = [.places(story: home.story.id, title: InkWords.line("home.places"))]        case "place": Task { if let place = try? await shelf.places(story: home.story.id).first { path = [.places(story: home.story.id, title: InkWords.line("home.places")), .place(place.id)] } }        case "drafts": path = [.about(home.story.id), .drafts(home.story.id)]        case "acts": if let first { sheet = .sceneActs(first) }        default: break        }    }    #endif    func attempt(_ work: () async throws -> Void) async {        do { try await work() } catch { notice = ActionRefused.words(for: error) }    }}/// The app: the script home (or the first screen), its stack and its sheets.struct InkStoryRoot: View {    /// Cotton Story's own build.    static var applies: Bool { FlavourManifest.current?.flavour == "story" }    @State private var model: InkStory    @Environment(\.cottonSync) private var sync    @Environment(\.scenePhase) private var phase    init(core: any CottonCalling) {        _model = State(initialValue: InkStory(core: core))    }    var body: some View {        NavigationStack(path: $model.path) {            Group {                if let line = model.arriving {                    // The core says the scripts may still be coming (story.list's arriving).                    InkArriving(words: line)                } else if model.none {                    InkNoScripts(model: model)                } else if let home = model.home {                    InkHome(model: model, home: home)                } else {                    Ink.ground                }            }            .navigationDestination(for: InkRoute.self) { route in                switch route {                case .scene(let scene, let fresh):                    InkSceneScreen(story: model, scene: scene, fresh: fresh)                case .read(let story, let at):                    InkReadScreen(story: model, script: story, at: at)                case .about(let story):                    InkAboutScreen(story: model, script: story)                case .settings:                    InkSettingsScreen(story: model)                case .character(let id):                    InkCharacterScreen(story: model, id: id)                case .places(let story, let title):                    InkPlacesScreen(story: model, script: story, title: title)                case .place(let id):                    InkPlaceScreen(story: model, id: id)                case .drafts(let story):                    InkDraftsScreen(story: model, script: story)                case .readDraft(let story, let draft, let name):                    InkReadScreen(story: model, script: story, at: nil, draft: InkReadScreen.Draft(id: draft, name: name))                case .lines(let id):                    InkLinesScreen(story: model, id: id)                case .changes(let draft, let name):                    InkChangesScreen(story: model, draft: draft, name: name)                }            }            .toolbar(.hidden, for: .navigationBar)            .inkSwipeBack()        }        .inkGround()        // Look (shared/DECISIONS.md "Look"): every screen in the paper, ink, face and size chosen.        .lookStanding(LookModel.standing("story"))        .task { await LookModel.standing("story").read(model.core) }        // Nothing draws under the clock. Every Ink screen hides the navigation        // bar, so nothing stood under the status bar, and a scroll view runs on        // under it: scrolled rows, and the home laid out again while a sheet's        // keyboard was up, drew beneath the time. The ground stands there as a        // bar would, under the panels' scrim.        .overlay(alignment: .top) { InkStatusGround() }        .lookPanel(item: $model.sheet, style: Ink.panel, tall: model.sheet == .scripts || model.sheet == .views) { sheet in            InkSheetContent(model: model, sheet: sheet)        }        .fileImporter(isPresented: $model.bringing, allowedContentTypes: StoryScriptTypes.all) { result in            if case .success(let url) = result { Task { await model.bring(url) } }        }        .overlay(alignment: .bottom) { InkNotice(words: $model.notice) }        // The app's one keyboard rule (Chrome/KeyboardDismissal.swift): a        // drag down or a tap outside a field puts the keyboard away, on every        // Story screen and panel. Story wore none, so a drag down on a scene        // with the keyboard up left it there (StoryKeyboardTests).        .cottonScreenFrame()        .task {            InkFonts.register()            #if COTTON_DEV            await model.attempt { try await InkSeed.seed(model.core, book: model.book) }            #endif            await model.load()            // The first content is read: the splash goes now, never at the            // launch's ceiling (launch-fast, 20 Nov 2026).            FanLaunch.firstContent()            // Settings draws whole on its first frame from the list last read; a phone with none yet reads it now.            Task { await SettingsHome.warm(model.core) }            #if COTTON_DEV            model.openForALook()            #endif        }        // Another device or Claude wrote: read again (the whole list while there is no script yet).        .onChange(of: sync?.foreignRevision) { _, _ in            Task { if model.home == nil { await model.load() } else { await model.reloadHome() } }        }        .onChange(of: sync?.revision) { _, _ in            guard model.arriving != nil else { return }            Task { await model.load() }        }        // While scripts are still coming, ask again every few seconds until they land or stop coming.        .task(id: model.arriving != nil) {            while model.arriving != nil {                try? await Task.sleep(for: .seconds(3))                guard !Task.isCancelled else { return }                await model.load()            }        }        // A Fountain file opened in Story from Files, Mail or AirDrop came in.        .onReceive(NotificationCenter.default.publisher(for: StoryFountainOpen.broughtIn)) { note in            Task {                model.path = []                await model.load()                model.brought(note.object as? String)            }        }        .onChange(of: phase) { _, now in            if now == .active { Task { await model.reloadHome() } }        }    }}/// The sheet's own ground under the status bar, as tall as the bar itself.struct InkStatusGround: View {    var body: some View {        Color.clear            .frame(height: 0)            .background(Ink.ground.ignoresSafeArea(edges: .top))            .allowsHitTesting(false)            .accessibilityHidden(true)    }}/// Scripts still coming down: one quiet line after the pen's blue dot, which/// pulses gently (still, with Reduce Motion), and nothing to press.struct InkArriving: View {    let words: String    @State private var dim = false    @Environment(\.accessibilityReduceMotion) private var still    @Environment(BootModel.self) private var boot: BootModel?    var body: some View {        // The core's progress while the first pull runs ("Loading your data… 42%" and its thin bar); the dot until it counts.        if let bringing = boot?.home?.bringing {            LoadingLine(bringing: bringing, ink: Ink.quiet, font: InkType.count)                .padding(.horizontal, Ink.gutter)                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)                .inkGround()                .accessibilityIdentifier("story-arriving")        } else {            dot        }    }    private var dot: some View {        HStack(alignment: .firstTextBaseline, spacing: 10) {            Circle()                .fill(Ink.blue)                .frame(width: 8, height: 8)                .opacity(dim ? 0.25 : 1)                .accessibilityHidden(true)            Text(words)                .font(InkType.count)                .foregroundStyle(Ink.quiet)                .fixedSize(horizontal: false, vertical: true)        }        .padding(.horizontal, Ink.gutter)        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)        .inkGround()        .accessibilityElement(children: .combine)        .accessibilityAddTraits(.updatesFrequently)        .onAppear {            guard !still else { return }            withAnimation(.easeInOut(duration: 1.1).repeatForever(autoreverses: true)) { dim = true }        }    }}/// The sheets, each drawn in Ink.private struct InkSheetContent: View {    let model: InkStory    let sheet: InkSheet    var body: some View {        Group {            switch sheet {            case .scripts:                InkScriptsSheet(model: model)            case .naming:                InkNamingSheet(model: model)            case .views:                InkViewsSheet(model: model)            case .sceneActs(let row):                InkActsSheet(title: row.title ?? "", acts: sceneActs(row))            case .more:                InkActsSheet(title: model.home?.story.title ?? "", acts: moreActs)            }        }    }    private func sceneActs(_ row: StoryScenesAnswer.Row) -> [InkAct] {        let id = row.id        let scenes = model.home?.scenes ?? []        let at = scenes.firstIndex { $0.id == id } ?? 0        var acts: [InkAct] = []        if at > 0 { acts.append(InkAct(words: InkWords.line("ink.picture_earlier")) { Task { await model.move(id, by: -1) } }) }        if at < scenes.count - 1 { acts.append(InkAct(words: InkWords.line("ink.picture_later")) { Task { await model.move(id, by: 1) } }) }        acts.append(InkAct(words: InkWords.line("scene.new_after")) { Task { await model.newScene(after: id) } })        acts.append(InkAct(words: InkWords.line("acts.duplicate")) { Task { await model.duplicate(id) } })        acts.append(InkAct(words: InkWords.line("scene.delete"), quiet: true) { Task { await model.remove(id) } })        return acts    }    private var moreActs: [InkAct] {        guard let story = model.story else { return [] }        return [            InkAct(words: InkWords.line("about.title")) {                model.sheet = nil                model.path.append(.about(story))            },            InkAct(words: InkWords.line("settings.title")) {                model.sheet = nil                model.path.append(.settings)            },        ]    }}/// The file kinds Bring in a script offers: Fountain, Final Draft, PDF and/// plain text (the core reads each by what it is, `story.bring_in`).enum StoryScriptTypes {    static var all: [UTType] {        [UTType(filenameExtension: "fountain", conformingTo: .plainText) ?? .plainText,         UTType(filenameExtension: "fdx", conformingTo: .xml) ?? .xml,         .pdf, .plainText]    }}/// A refusal at the foot of the screen, in ink on the ground, gone by itself.struct InkNotice: View {    @Binding var words: String?    var body: some View {        if let words {            Text(words)                .font(InkType.count)                .foregroundStyle(Ink.ink)                .padding(.vertical, 10)                .padding(.horizontal, 16)                .background(Capsule().fill(Ink.under))                .overlay(Capsule().strokeBorder(Ink.rule, lineWidth: 1))                .padding(.horizontal, 16)                .padding(.bottom, 12)                .transition(.opacity)                .accessibilityAddTraits(.updatesFrequently)                .task(id: words) {                    try? await Task.sleep(for: .seconds(4))                    self.words = nil                }                .onTapGesture { self.words = nil }        }    }}/// The shell's passing line (an approval, a sync failure, a sealed key) in Story's own toast (`AppToast`): the/// notice's face, in ink on the ground with its rule, at the top as Android's Story says its lines (at the foot it/// stood under the "+"), with Undo in blue when the line carries one.struct InkToast: View {    let toast: CottonToast    let onUndo: () -> Void    let onDismiss: () -> Void    var body: some View {        HStack(spacing: 10) {            Text(toast.message)                .font(InkType.count)                .foregroundStyle(Ink.ink)                .lineLimit(AppToastView.lineLimit(toast.tone))                .fixedSize(horizontal: false, vertical: true)            if toast.undo != nil {                Button(action: onUndo) {                    Text(CottonStrings.undo).font(InkType.count).foregroundStyle(Ink.blue)                        .frame(minWidth: 44, minHeight: 44).contentShape(Rectangle())                }                .buttonStyle(.plain)            }        }        .padding(.vertical, toast.undo == nil ? 10 : 0)        .padding(.horizontal, 16)        .background(RoundedRectangle(cornerRadius: 20, style: .continuous).fill(Ink.under))        .overlay(RoundedRectangle(cornerRadius: 20, style: .continuous).strokeBorder(Ink.rule, lineWidth: 1))        .padding(.horizontal, 16)        .padding(.top, 8)        .onTapGesture(perform: onDismiss)        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)    }}// MARK: - The system's back gesture with the bar hiddenextension View {    /// The edge swipe steps back though the navigation bar is hidden (the    /// platform's back gesture is the one thing of the system's Story keeps).    func inkSwipeBack() -> some View { background(InkSwipeBack()) }}private struct InkSwipeBack: UIViewControllerRepresentable {    func makeUIViewController(context: Context) -> Finder { Finder() }    func updateUIViewController(_ controller: Finder, context: Context) {}    final class Finder: UIViewController, UIGestureRecognizerDelegate {        override func viewDidAppear(_ animated: Bool) {            super.viewDidAppear(animated)            guard let navigation = findNavigation() else { return }            navigation.interactivePopGestureRecognizer?.delegate = self        }        private func findNavigation() -> UINavigationController? {            var next: UIViewController? = parent            while let one = next {                if let navigation = one as? UINavigationController { return navigation }                if let found = one.children.lazy.compactMap({ $0 as? UINavigationController }).first { return found }                next = one.parent            }            return view.window?.rootViewController.flatMap { Self.first(in: $0) }        }        private static func first(in controller: UIViewController) -> UINavigationController? {            if let navigation = controller as? UINavigationController { return navigation }            for child in controller.children {                if let found = first(in: child) { return found }            }            return nil        }        func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {            (findNavigation()?.viewControllers.count ?? 0) > 1        }    }}#endif