Cotton code
210 lines · 8.7 KB · SwiftRaw
// Read (wireframes 6): the script the way the industry prints it, start to// end, with no writing tools in the way. The pages are the core's// (`story.draft`, laid out as `story.script`: Courier 12 pt, the standard// indents, MORE and CONT'D, scene numbers both sides); the phone draws each// one at its real proportions on a plain sheet, the one place Story shows// paper because a screenplay page is paper. A tap on a line opens its scene;// ↗ sends the script as a PDF, a Final Draft or a Fountain file. Listen// reads it aloud from the page in view, on with the screen off, and stops// when Read is left, when Stop is tapped, or at the end.#if os(iOS)import CottonKitimport CottonPaperimport SwiftUIstruct InkReadScreen: View {    let story: InkStory    let script: String    /// The scene to open the pages at.    let at: String?    /// A marked draft to read instead of the script as it stands.    var draft: Draft? = nil    @State private var answer: Shown?    @State private var sending = false    /// The page in view, which Listen starts from.    @State private var inView: Int?    @Environment(\.dismiss) private var dismiss    struct Draft: Hashable {        let id: String        let name: String    }    /// What Read draws and sends: the working script, or a draft laid on its paper.    struct Shown {        let title: String        let script: StoryScript    }    /// This screen's place in the stack, so a scene opened over it is not leaving it.    private var route: InkRoute {        if let draft { return .readDraft(story: script, draft: draft.id, name: draft.name) }        return .read(story: script, at: at)    }    var body: some View {        VStack(spacing: 0) {            HStack(spacing: 10) {                InkGlyph(symbol: "chevron.left", label: InkWords.line("writer.back")) { dismiss() }                Text(draft?.name ?? InkWords.line("home.read"))                    .font(InkType.barTitle)                    .foregroundStyle(Ink.ink)                    .multilineTextAlignment(.center)                    .frame(maxWidth: .infinity)                    .accessibilityAddTraits(.isHeader)                InkGlyph(symbol: "square.and.arrow.up", label: InkWords.line("ink.send")) { sending = true }                    .disabled(answer == nil)            }            .padding(.horizontal, 8)            .padding(.top, 6)            if let answer {                if answer.script.pages.isEmpty {                    Text(InkWords.line("script.empty"))                        .font(InkType.count)                        .foregroundStyle(Ink.quiet)                        .padding(Ink.gutter)                    Spacer()                } else {                    pages(answer)                }            } else {                Spacer()            }        }        .safeAreaInset(edge: .bottom, spacing: 0) {            if let answer, let last = answer.script.pages.last {                let page = inView ?? answer.script.pages.first?.number ?? 1                InkReadFoot(listen: story.listen, page: page, of: last.number) {                    story.listen.start(answer.script.pages, from: page, title: answer.title)                }            }        }        .inkGround()        .toolbar(.hidden, for: .navigationBar)        .lookPanel(isPresented: $sending, style: Ink.panel) {            InkSendSheet(story: story, script: script, title: answer?.title ?? "", draft: draft)        }        .task { await load() }        // Gone from the stack (back), not covered by a scene opened from a line: Listen stops.        .onDisappear {            guard !story.path.contains(route) else { return }            story.listen.stop()        }    }    private func load() async {        await story.attempt {            let working = try await story.book.draft(story: script)            guard let draft else {                answer = Shown(title: working.title, script: working.script)                return            }            let read = try await story.shelf.readDraft(draft.id)            answer = Shown(title: [working.title, draft.name].filter { !$0.isEmpty }.joined(separator: " - "),                           script: StoryScript(paper: working.script.paper, titlePage: nil, pages: read.pages, scenes: []))        }    }    private func pages(_ answer: Shown) -> some View {        ScrollViewReader { reader in            ScrollView {                LazyVStack(spacing: 18) {                    ForEach(answer.script.pages, id: \.number) { page in                        InkPage(page: page, paper: answer.script.paper, scenes: scenes(of: page, in: answer.script), opens: draft == nil) { scene in                            // A draft's scenes may be gone from the script: only the script's own open.                            if draft == nil { open(scene) }                        }                        .id(page.number)                    }                }                .scrollTargetLayout()                .padding(.horizontal, 16)                .padding(.vertical, 12)            }            .scrollPosition(id: $inView, anchor: .top)            .scrollIndicators(.hidden)            .onAppear {                guard let at, let start = answer.script.scenes.first(where: { $0.id == at }) else { return }                reader.scrollTo(start.page, anchor: .top)            }            .onChange(of: story.listen.page) { _, page in                guard let page, story.listen.playing, page != inView else { return }                withAnimation { reader.scrollTo(page, anchor: .top) }            }        }    }    /// Which scene each line of a page belongs to: the heading above it, on    /// this page or an earlier one.    private func scenes(of page: StoryScript.Page, in script: StoryScript) -> [String?] {        var current = script.scenes.last { $0.page < page.number }?.id        if let first = script.scenes.filter({ $0.page == page.number }).first, page.lines.first?.scene == nil, current == nil {            current = first.id        }        return page.lines.map { line in            if let scene = line.scene { current = scene.id }            return current        }    }    private func open(_ scene: String?) {        guard let scene else { return }        story.path.append(.scene(scene, fresh: false))    }}/// One page at its paper's proportions, Courier Prime sized so the page's/// widest line fits the phone.struct InkPage: View {    let page: StoryScript.Page    let paper: StoryScript.Paper    /// The scene each line belongs to.    let scenes: [String?]    /// Whether a tap on a line opens its scene (not in a draft).    var opens = true    let open: (String?) -> Void    var body: some View {        GeometryReader { geometry in            let scale = geometry.size.width / paper.width            let size = 12 * scale            let lineHeight = 12 * scale            let left = paper.margins.left * scale            ZStack(alignment: .topLeading) {                Rectangle().fill(InkPaper.sheet)                Text(String(page.number) + ".")                    .font(.custom(CottonFonts.typeFace, fixedSize: size))                    .foregroundStyle(Ink.ink)                    .frame(width: geometry.size.width - paper.margins.right * scale, alignment: .trailing)                    .offset(y: paper.margins.top * scale / 2)                    .accessibilityHidden(true)                ForEach(Array(page.lines.enumerated()), id: \.offset) { index, line in                    if line.kind != "blank" {                        Text(line.text)                            .font(.custom(CottonFonts.typeFace, fixedSize: size))                            .bold(line.kind == "heading")                            .foregroundStyle(Ink.ink)                            .lineLimit(1)                            .fixedSize()                            .offset(x: left + CGFloat(line.indent) * size * 0.6, y: paper.margins.top * scale + CGFloat(index) * lineHeight)                            .onTapGesture { open(scenes[index]) }                            // Every printed line is read on its own, a tap opening its scene.                            .accessibilityLabel(line.text)                            .accessibilityAddTraits(opens && scenes[index] != nil ? .isButton : .isStaticText)                            .accessibilityAddTraits(line.kind == "heading" ? .isHeader : [])                    }                }            }        }        .aspectRatio(paper.width / paper.height, contentMode: .fit)        .overlay(Rectangle().strokeBorder(Ink.rule, lineWidth: 1))        .accessibilityElement(children: .contain)    }}/// The page itself: white, as a printed screenplay is.enum InkPaper {    static let sheet = Color(ink: 0xFCFCFE)}#endif