Cotton code
164 lines · 6.6 KB · SwiftRaw
// Where the one viewer is presented from: the root, once.//// An opener asks the presenter in its environment; it never presents a// full-screen view of its own (`OneViewerTests`). On the phone the viewer// grows out of the tile it was opened from and, swiped down, follows the// finger back to the tile of whatever it is showing then — the system's// zoom transition, which crossfades under Reduce Motion.import SwiftUI/// The viewer's state at the root: what is open, and which item it is on.@MainActor @Observablefinal class ViewerPresenter {    /// The set on screen; nil when the viewer is closed. Closed, however it    /// closes (a swipe down sets it nil through the cover), the read still    /// growing its set stops.    var current: ViewerSet? {        didSet { if current == nil { growing?.cancel(); growing = nil } }    }    /// The item the viewer stands on — the tile a dismissal returns to.    var showing: String?    /// The read growing the set on screen to the whole it is a window of.    @ObservationIgnored private var growing: Task<Void, Never>?    // Where `set` is a window of more (a deck's dealt cards), `rest` reads    // the whole, and the viewer takes it standing where it is — unless it has    // closed or opened another set meanwhile.    /// What plays a film's or an episode's record (`FilmPlayer.cinema`) or a    /// podcast episode (`FilmPlayer.audio`): Apple's player, or the app's one    /// audio player, set by the host; nil in a preview.    @ObservationIgnored var streams: (@MainActor (ViewerItem) -> Void)?    /// Opens `set` at once. A film opens in Apple's player alone, never in    /// the viewer (`FilmPlayer`); the viewer walks the rest.    func open(_ set: ViewerSet, rest: (@MainActor () async -> [ViewerItem])? = nil) {        growing?.cancel()        growing = nil        guard !set.items.isEmpty else { return }        let opened = set.items[set.start]        if FilmPlayer.of(opened) != .viewer {            streams?(opened)            return        }        let set = Self.viewed(set)        guard !set.items.isEmpty else { return }        showing = set.items[set.start].id        current = set        guard let rest else { return }        growing = Task { [weak self] in            let all = await rest().filter { FilmPlayer.of($0) == .viewer }            guard !Task.isCancelled, let self, let open = self.current, open.id == set.id, all.count > open.items.count else { return }            let at = all.firstIndex { $0.id == self.showing } ?? open.start            self.current = ViewerSet(id: open.id, items: all, start: at, pins: open.pins)        }    }    /// `set` as the viewer walks it: the films left out, opened on the same    /// item.    static func viewed(_ set: ViewerSet) -> ViewerSet {        let opened = set.items[set.start].id        let items = set.items.filter { FilmPlayer.of($0) == .viewer }        return ViewerSet(id: set.id, items: items, start: items.firstIndex { $0.id == opened } ?? 0, pins: set.pins)    }    func close() { current = nil }}private struct ViewerPresenterKey: EnvironmentKey {    static let defaultValue: ViewerPresenter? = nil}private struct ViewerNamespaceKey: EnvironmentKey {    static let defaultValue: Namespace.ID? = nil}extension EnvironmentValues {    /// The viewer this screen opens media in; nil in a preview or a test.    var viewerPresenter: ViewerPresenter? {        get { self[ViewerPresenterKey.self] }        set { self[ViewerPresenterKey.self] = newValue }    }    /// The namespace a tile and the viewer match their transition in.    var viewerNamespace: Namespace.ID? {        get { self[ViewerNamespaceKey.self] }        set { self[ViewerNamespaceKey.self] = newValue }    }}/// Holds the presenter and presents the viewer over everything under it.private struct ViewerHost: ViewModifier {    @State private var presenter = ViewerPresenter()    @Namespace private var namespace    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    func body(content: Content) -> some View {        content            .onAppear { presenter.streams = streams }            .environment(\.viewerPresenter, presenter)            .environment(\.viewerNamespace, namespace)            .fullScreenCover(item: $presenter.current) { set in                MediaViewer(media: set, showing: $presenter.showing) { presenter.close() }                    .environment(\.viewerPresenter, presenter)                    // The cover is its own window: the cards opened over the                    // picture stand in it.                    .cardLayers()                    #if os(iOS)                    // The page under the viewer leaves the accessibility tree                    // while it is up: the zoom keeps the presenter in the                    // window, and its list stayed readable behind the picture                    // (walker 604bcce6). A sheet's anchor, the same rule.                    .background { SheetModalAnchor() }                    .navigationTransition(.zoom(sourceID: presenter.showing ?? set.id, in: namespace))                    #endif            }    }}extension ViewerHost {    /// A film's or an episode's record, dealt by the core's one player    /// (`shell.player`) and played in Apple's player over everything    /// (`FilmPlayback`); a podcast episode, in the app's one audio player    /// (`PodcastPlayback`).    private var streams: @MainActor (ViewerItem) -> Void {        { [core, toasts] item in            #if os(iOS)            guard let core else { return }            let say: (String) -> Void = { said in toasts?.show(said, tone: .error) }            if FilmPlayer.of(item) == .audio {                PodcastPlayback.shared.play(item, core: core, say: say)            } else if let record = item.record {                Task { await FilmPlayback.ask(table: record.table, id: record.id) }            }            #endif        }    }}extension View {    /// The root of a window: media opened anywhere under it opens here.    func hostsViewer() -> some View { modifier(ViewerHost()) }    /// A tile the viewer can grow out of and close back into, by the id of    /// the item it shows.    func viewerSource(_ id: String) -> some View { modifier(ViewerSource(id: id)) }}private struct ViewerSource: ViewModifier {    let id: String    @Environment(\.viewerNamespace) private var namespace    func body(content: Content) -> some View {        #if os(iOS)        if let namespace {            content.matchedTransitionSource(id: id, in: namespace)        } else {            content        }        #else        content        #endif    }}