Cotton code
246 lines · 10.7 KB · SwiftRaw
// Drafts (wireframes 11, reached from About this script): today's script// marked as a named draft, the working copy (and how much changed since the// newest draft), and each draft marked, newest first. A draft can be read,// compared with now, sent as a PDF, or gone back to after asking (the script// becomes that draft again; scenes written since go to Deleted). The changes// page lists every scene that is new, taken out, moved or changed since a// draft (`story.drafts.changes`). Same words and order as Android's.#if os(iOS)import CottonKitimport SwiftUIstruct InkDraftsScreen: View {    let story: InkStory    let script: String    @State private var drafts: [StoryDraftMark]?    /// What changed since the newest draft.    @State private var since: StoryChanges.Since?    @State private var marking = false    @State private var chosen: StoryDraftMark?    @State private var restoring: StoryDraftMark?    var body: some View {        InkPageFrame(title: InkWords.line("ink.drafts")) {            InkButton(words: InkWords.line("ink.mark_draft")) { marking = true }            VStack(spacing: 0) {                InkLinkRow(title: InkWords.line("ink.working"), line: working,                           last: (drafts ?? []).isEmpty) { story.path = [] }                ForEach(Array((drafts ?? []).enumerated()), id: \.element.id) { at, draft in                    InkLinkRow(title: draft.name, line: Self.line(draft), last: at == (drafts ?? []).count - 1) { chosen = draft }                }            }            if let drafts, drafts.isEmpty {                Text(InkWords.line("ink.drafts_none"))                    .font(InkType.count)                    .foregroundStyle(Ink.quiet)                    .fixedSize(horizontal: false, vertical: true)            }            if let newest = drafts?.first {                Button { story.path.append(.changes(draft: newest.id, name: newest.name)) } label: {                    Text(InkWords.line("ink.see_all"))                        .font(InkType.count)                        .foregroundStyle(Ink.quiet)                        .underline()                        .fixedSize(horizontal: false, vertical: true)                        .frame(maxWidth: .infinity, alignment: .leading)                        .contentShape(Rectangle())                }                .buttonStyle(InkPress())            }        }        .lookPanel(isPresented: $marking, style: Ink.panel) {            InkNameSheet(title: InkWords.line("ink.draft_name"), hint: InkWords.line("ink.draft_hint")) { name in                Task {                    await story.attempt { try await story.shelf.markDraft(story: script, name: name) }                    await load()                }            }        }        .lookPanel(item: $chosen, style: Ink.panel) { draft in            InkActsSheet(title: draft.name, acts: acts(draft))        }        .lookPanel(item: $restoring, style: Ink.panel) { draft in            InkActsSheet(title: InkWords.line("ink.restore_ask", ["draft": draft.name]), acts: [                InkAct(words: InkWords.line("ink.restore"), detail: InkWords.line("ink.restore_line")) {                    restoring = nil                    Task {                        await story.attempt { try await story.shelf.restoreDraft(draft.id) }                        await story.reloadHome()                        await load()                    }                },            ])        }        .task(id: story.home) { await load() }    }    /// "now · 3 scenes changed since Second draft", or nothing changed, or the script's size.    private var working: String {        let now = InkWords.line("ink.working_line")        guard let newest = drafts?.first, let since else {            return [now, story.home?.story.summary].compactMap { $0 }.joined(separator: " · ")        }        return now + " · " + Self.since(since, draft: newest.name)    }    static func since(_ since: StoryChanges.Since, draft: String) -> String {        since.scenes == 0            ? InkWords.line("ink.nothing_changed", ["draft": draft])            : InkWords.counted("ink.changed_since", since.scenes, ["draft": draft])    }    private func load() async {        await story.attempt {            let all = try await story.shelf.drafts(story: script)            drafts = all            if let newest = all.first {                since = try await story.shelf.changes(newest.id).since            } else {                since = nil            }        }    }    private func acts(_ draft: StoryDraftMark) -> [InkAct] {        [            InkAct(words: InkWords.line("ink.read_draft")) {                chosen = nil                story.path.append(.readDraft(story: script, draft: draft.id, name: draft.name))            },            InkAct(words: InkWords.line("ink.changes")) {                chosen = nil                story.path.append(.changes(draft: draft.id, name: draft.name))            },            InkAct(words: InkWords.line("ink.send_pdf")) {                chosen = nil                Task { await story.attempt { try await InkSending.pdf(story: story, script: script, draft: InkReadScreen.Draft(id: draft.id, name: draft.name)) } }            },            InkAct(words: InkWords.line("ink.restore")) {                chosen = nil                restoring = draft            },        ]    }    /// "12 Nov 2026 · 14 scenes · 18 pages".    static func line(_ draft: StoryDraftMark) -> String {        let whole = max(1, Int(draft.pages.rounded()))        let pages = InkWords.counted("length.pages", whole)        let counts = InkWords.line("ink.draft_row", ["scenes": InkCounting.scenes(draft.scenes), "pages": pages])        guard let made = madeAt(draft.madeAt) else { return counts }        return made.formatted(date: .abbreviated, time: .omitted) + " · " + counts    }    /// The newest draft beside About's Drafts row: "Second draft · 12 Nov 2026".    static func latest(_ draft: StoryDraftMark) -> String {        guard let made = madeAt(draft.madeAt) else { return draft.name }        return draft.name + " · " + made.formatted(date: .abbreviated, time: .omitted)    }    private static func madeAt(_ iso: String) -> Date? {        let whole = ISO8601DateFormatter()        if let date = whole.date(from: iso) { return date }        let fractional = ISO8601DateFormatter()        fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]        if let date = fractional.date(from: iso) { return date }        let day = ISO8601DateFormatter()        day.formatOptions = [.withFullDate]        return day.date(from: iso)    }}/// What changed since a draft: one line for the whole, then each scene that/// is new, taken out, moved or changed, in today's order.struct InkChangesScreen: View {    let story: InkStory    let draft: String    let name: String    @State private var changes: StoryChanges?    var body: some View {        InkPageFrame(title: InkWords.line("ink.changes_title", ["draft": name])) {            if let changes {                let rows = changes.scenes.filter { $0.change != "same" }                if rows.isEmpty {                    Text(InkWords.line("ink.nothing_changed", ["draft": name]))                        .font(InkType.count)                        .foregroundStyle(Ink.quiet)                        .fixedSize(horizontal: false, vertical: true)                } else {                    Text(InkWords.line("ink.change_since_line", [                        "scenes": InkDraftsScreen.since(changes.since, draft: name),                        "lines": InkWords.line("ink.change_lines", [                            "added": String(changes.since.linesAdded),                            "changed": String(changes.since.linesChanged),                            "removed": String(changes.since.linesRemoved),                        ]),                    ]))                    .font(InkType.count)                    .foregroundStyle(Ink.quiet)                    .fixedSize(horizontal: false, vertical: true)                    VStack(spacing: 0) {                        ForEach(Array(rows.enumerated()), id: \.element.id) { at, row in                            InkChangeRow(row: row, last: at == rows.count - 1) {                                story.path.append(.scene(row.scene, fresh: false))                            }                        }                    }                }            }        }        .task { await story.attempt { changes = try await story.shelf.changes(draft) } }    }}/// A changed scene: its number and heading, then what happened to it.struct InkChangeRow: View {    let row: StoryChanges.Scene    let last: Bool    let open: () -> Void    private var gone: Bool { row.change == "removed" }    private var word: String {        let lines = InkWords.line("ink.change_lines", [            "added": String(row.lines.added), "changed": String(row.lines.changed), "removed": String(row.lines.removed),        ])        switch row.change {        case "added": return InkWords.line("ink.change_added")        case "removed": return InkWords.line("ink.change_removed")        case "moved": return InkWords.line("ink.change_moved", ["n": row.numberThen.map(String.init) ?? ""])        default: return InkWords.line("ink.change_changed") + " · " + lines        }    }    var body: some View {        VStack(spacing: 0) {            Button(action: open) {                HStack(alignment: .firstTextBaseline, spacing: 8) {                    Text((gone ? row.numberThen : row.numberNow ?? row.numberThen).map(String.init) ?? "")                        .font(InkType.sceneNumber)                        .foregroundStyle(gone ? Ink.quiet : Ink.blue)                        .frame(minWidth: 28, alignment: .leading)                    VStack(alignment: .leading, spacing: 3) {                        Text((gone ? row.headingThen : row.headingNow ?? row.headingThen) ?? "")                            .font(InkType.sceneTitle)                            .foregroundStyle(gone ? Ink.quiet : Ink.ink)                            .fixedSize(horizontal: false, vertical: true)                        Text(word)                            .font(InkType.count)                            .foregroundStyle(Ink.quiet)                            .fixedSize(horizontal: false, vertical: true)                    }                    .frame(maxWidth: .infinity, alignment: .leading)                }                .padding(.vertical, 13)                .contentShape(Rectangle())            }            .buttonStyle(InkPress())            .disabled(gone)            .accessibilityElement(children: .combine)            if !last { InkRule() }        }    }}#endif