// 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)importCottonKitimportCottonValuesimportSwiftUIimportUniformTypeIdentifiers/// Where the stack has gone from the script home.enumInkRoute: 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.enumInkSheet: Identifiable, Equatable {case scriptscase namingcase viewscase sceneActs(StoryScenesAnswer.Row)case morevar id: String {switchself {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.enumInkWords {staticfunc 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).staticfunc 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 @ObservablefinalclassInkStory {/// 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 = coreself.book = CoreStoryBook(core: core) }var story: String? { home?.story.id }func load() async {await attempt {let list = tryawait book.list() scripts = listguard !list.stories.isEmpty else { arriving = (list.arriving ?? false) ? (list.arrivingLine ?? InkWords.line("home.arriving")) : nil none = arriving == nil home = nilreturn } arriving = nil none = false home = tryawait book.scenes(story: nil) } }/// The scene list again, after a write.func reloadHome() async {await attempt { home = tryawait book.scenes(story: story) } }func choose(_ script: String) async { sheet = nil path = []await attempt { tryawait 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 { _ = tryawait book.start(title: title) }await load() }/// Plus: a new scene at the end, opened on Where and when.func newScene() async {guardlet story else { return }await attempt {let made = tryawait 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 { tryawait book.leaveScene(scene) }await reloadHome() }func move(_ scene: String, by: Int) async { sheet = nilawait attempt { tryawait 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 { tryawait 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 = nilawait attempt {let made = tryawait book.addScene(after: scene) path.append(.scene(made, fresh: true))await reloadHome() } }func duplicate(_ scene: String) async { sheet = nilawait attempt { tryawait book.duplicateScene(scene) }await reloadHome() }func remove(_ scene: String) async { sheet = nilawait attempt { tryawait 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 { tryawait book.deleteScript(script) } path = []await load() }func bring(_ url: URL) async {let came = awaitStoryFountainOpen.bring(url, core: core) { [weakself] words, _ inself?.notice = words } path = [] sheet = nilawait load()iflet came { brought(came.check) } }/// A script came in (here or by Open in): its check stands on its home.func brought(_ check: String?) {guardlet 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.staticvar lookAtWhere = false/// The look asked for opens the first scene's speaker chooser.staticvar 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() {guardletopen = UserDefaults.standard.string(forKey: "story-ink-open") else { return }ifopen == "naming" { sheet = .naming; return }ifopen == "new" { Task { await start(InkWords.line("fan.untitled")) }; return }guardlet home else { return }let first = home.scenes.firstswitchopen {case"scene": iflet first { path = [.scene(first.id, fresh: false)] }case"where": iflet first { InkStory.lookAtWhere = true; path = [.scene(first.id, fresh: false)] }case"speaker": iflet first { InkStory.lookAtSpeaker = true; path = [.scene(first.id, fresh: false)] }case"read": path = [.read(story: home.story.id, at: nil)]case"scripts": sheet = .scriptscase"views": sheet = .viewscase"more": sheet = .morecase"about": path = [.about(home.story.id)]case"settings": path = [.settings]case"character": iflet person = home.cast?.first { path = [.character(person.id)] }case"places": path = [.places(story: home.story.id, title: InkWords.line("home.places"))]case"place": Task { iflet 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": iflet first { sheet = .sceneActs(first) }default: break } } #endiffunc attempt(_ work: () asyncthrows -> Void) async {do { tryawait work() } catch { notice = ActionRefused.words(for: error) } }}/// The app: the script home (or the first screen), its stack and its sheets.structInkStoryRoot: View {/// Cotton Story's own build.staticvar applies: Bool { FlavourManifest.current?.flavour == "story" } @State privatevar model: InkStory @Environment(\.cottonSync) privatevar sync @Environment(\.scenePhase) privatevar phaseinit(core: any CottonCalling) { _model = State(initialValue: InkStory(core: core)) }var body: someView {NavigationStack(path: $model.path) {Group {iflet line = model.arriving {// The core says the scripts may still be coming (story.list's arriving).InkArriving(words: line) } elseif model.none {InkNoScripts(model: model) } elseiflet home = model.home {InkHome(model: model, home: home) } else {Ink.ground } } .navigationDestination(for: InkRoute.self) { route inswitch 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 { awaitLookModel.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 inInkSheetContent(model: model, sheet: sheet) } .fileImporter(isPresented: $model.bringing, allowedContentTypes: StoryScriptTypes.all) { result inifcase .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_DEVawait model.attempt { tryawaitInkSeed.seed(model.core, book: model.book) } #endifawait 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 { awaitSettingsHome.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) { _, _ inTask { if model.home == nil { await model.load() } else { await model.reloadHome() } } } .onChange(of: sync?.revision) { _, _ inguard model.arriving != nilelse { 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? awaitTask.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 inTask { model.path = []await model.load() model.brought(note.object as? String) } } .onChange(of: phase) { _, now inif now == .active { Task { await model.reloadHome() } } } }}/// The sheet's own ground under the status bar, as tall as the bar itself.structInkStatusGround: View {var body: someView {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.structInkArriving: View {let words: String @State privatevar dim = false @Environment(\.accessibilityReduceMotion) privatevar still @Environment(BootModel.self) privatevar boot: BootModel?var body: someView {// The core's progress while the first pull runs ("Loading your data… 42%" and its thin bar); the dot until it counts.iflet 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 } }privatevar dot: someView { 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.privatestructInkSheetContent: View {let model: InkStorylet sheet: InkSheetvar body: someView {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) } } }privatefunc sceneActs(_ row: StoryScenesAnswer.Row) -> [InkAct] {let id = row.idlet scenes = model.home?.scenes ?? []let at = scenes.firstIndex { $0.id == id } ?? 0var 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 }privatevar moreActs: [InkAct] {guardlet 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`).enumStoryScriptTypes {staticvar 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.structInkNotice: View { @Binding var words: String?var body: someView {iflet 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? awaitTask.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.structInkToast: View {let toast: CottonToastlet onUndo: () -> Voidlet onDismiss: () -> Voidvar body: someView { 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 hiddenextensionView {/// 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() -> someView { background(InkSwipeBack()) }}privatestructInkSwipeBack: UIViewControllerRepresentable {func makeUIViewController(context: Context) -> Finder { Finder() }func updateUIViewController(_ controller: Finder, context: Context) {}finalclassFinder: UIViewController, UIGestureRecognizerDelegate {overridefunc viewDidAppear(_ animated: Bool) {super.viewDidAppear(animated)guardlet navigation = findNavigation() else { return } navigation.interactivePopGestureRecognizer?.delegate = self }privatefunc findNavigation() -> UINavigationController? {var next: UIViewController? = parentwhilelet one = next {iflet navigation = one as? UINavigationController { return navigation }iflet found = one.children.lazy.compactMap({ $0 as? UINavigationController }).first { return found } next = one.parent }return view.window?.rootViewController.flatMap { Self.first(in: $0) } }privatestaticfunc first(in controller: UIViewController) -> UINavigationController? {iflet navigation = controller as? UINavigationController { return navigation }for child in controller.children {iflet found = first(in: child) { return found } }returnnil }func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool { (findNavigation()?.viewControllers.count ?? 0) > 1 } }}#endif