Cotton code
66 lines · 2.0 KB · SwiftRaw
// Where the reader is presented from: the root, once (`hostsReader`). A book// card's tap and the `reader.open` act ask the presenter in their// environment; neither presents a reader of its own.import SwiftUI/// The reader's state at the root: the book open, if one is.@MainActor @Observablefinal class ReaderPresenter {    var current: ReaderOpening?    /// A place asked of the book already open (`reader.open { at }`).    var jump: ReaderOpening?    func open(_ opening: ReaderOpening) {        if current?.id == opening.id {            if opening.at != nil { jump = opening }        } else {            current = opening        }    }    func close() {        current = nil        jump = nil    }}extension EnvironmentValues {    /// The reader books open in; nil in a preview or a test.    @Entry var readerPresenter: ReaderPresenter? = nil}#if os(iOS)/// Holds the presenter and presents the reader over everything under it.private struct ReaderHost: ViewModifier {    @State private var presenter = ReaderPresenter()    func body(content: Content) -> some View {        content            .environment(\.readerPresenter, presenter)            .fullScreenCover(item: $presenter.current) { opening in                BookReaderScreen(opening: opening) { presenter.close() }                .environment(\.readerPresenter, presenter)            }    }}extension View {    /// The root of a window: a book opened anywhere under it opens here.    func hostsReader() -> some View { modifier(ReaderHost()) }}#endif/// The phone's own act that opens a book (`reader.open { id, at? }`).enum ReaderMethod {    static let open = "reader.open"}extension TableDefinition {    /// A table whose read act is the reader's on the record itself: its    /// card's tap opens the book (`DeckCardTap.reader`). A highlight's    /// Open in book names its book by a column, so its tap stays its own.    var opensReader: Bool {        (commands ?? []).contains { $0.method == ReaderMethod.open && $0.bindings?["id"] == "$id" }    }}