Cotton code
285 lines · 14.0 KB · SwiftRaw
// COTTON CINEMAS' STREAMING ROOT (assets/design/cinemas/CONTRACT-2.md "The places", MOTION.md): always dark; three// places on a bottom bar, Home, Search and You, each its own stack; the TV bar above the bar while a film plays on the// TV; a poster grows into its title's page and back (the system's zoom, which follows the finger and can be caught// mid-way). The owner sent it straight to the Cinemas app itself (26 Nov 2026), Dev and TestFlight alike; nothing here// touches his library, his kept films or where he stopped: they are the core's, read as they stand.#if os(iOS)import CottonKitimport SwiftUIstruct CinemasRoot: View {    /// Whether this app is Cotton Cinemas (and Cinemas Dev): the streaming screens replace the fan there.    static var applies: Bool { FlavourManifest.current?.flavour == "cinemas" }    @State private var model: CinemasModel    @State private var tv = CinemasTV()    @Environment(\.dynamicTypeSize) private var typeSize    @Namespace private var grow    @Environment(\.cottonSync) private var sync    @Environment(\.scenePhase) private var phase    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var shown = false    init(core: any CottonCalling, shares: ShareIntake?) {        CinemasFonts.register()        var source: any CinemasSource = CinemasCoreSource(core: core)        #if COTTON_DEV        if CinemasInvented.asked { source = CinemasInvented() }        #endif        _model = State(initialValue: CinemasModel(source: source, core: core, shares: shares))    }    /// For tests and previews: any source.    init(model: CinemasModel) {        _model = State(initialValue: model)    }    var body: some View {        ZStack(alignment: .bottom) {            CinemasInk.ground.ignoresSafeArea()                .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { seen in                    if let seen = seen.drawable, seen > 0 { model.width = seen }                }            ZStack {                ForEach(CinemasTab.allCases, id: \.self) { tab in                    stack(tab)                        .opacity(model.tab == tab ? 1 : 0)                        .allowsHitTesting(model.tab == tab)                        .accessibilityHidden(model.tab != tab)                }            }            .animation(CinemasMotion.or(CinemasMotion.tabChange, reduced: reduceMotion), value: model.tab)            VStack(spacing: 0) {                if tv.playing != nil {                    CinemasTVBar(tv: tv, grow: grow)                        .transition(.move(edge: .bottom).combined(with: .opacity))                }                CinemasTabs(model: model)            }            .animation(CinemasMotion.or(CinemasMotion.tvBar, reduced: reduceMotion), value: tv.playing != nil)            CinemasToastView(model: model)        }        .background(alignment: .topLeading) { CinemasHiddenPicker(tv: tv).frame(width: 1, height: 1) }        .opacity(shown ? 1 : 0)        .preferredColorScheme(.dark)        .environment(\.cinemasPictures, model.pictures)        .environment(tv)        // The remote grows out of the TV bar (MOTION: a shared element on a spring of 0.45 / 0.88; the system's zoom).        .fullScreenCover(isPresented: $tv.remoteOpen) {            CinemasRemote(tv: tv, model: model)                .navigationTransition(.zoom(sourceID: "cinemas-tv", in: grow))        }        .sheet(item: $model.sheet) { sheet in            CinemasSheetPage(model: model, sheet: sheet)                // At the accessibility sizes a sheet opens whole, so nothing it says stands below its edge.                .presentationDetents(typeSize.isAccessibilitySize ? [.large] : sheet.detents)                .presentationDragIndicator(.visible)                .presentationBackground(CinemasInk.sheet)                .presentationCornerRadius(22)                .preferredColorScheme(.dark)        }        .task {            tv.source = model.source            FilmNetwork.watch()            FilmPlayback.hiddenOpen = { [model] in model.hidden.open }            FilmPlayback.released = { [model] in model.prepareAgain() }            // The player's words in Cinemas' own toast, never the shell's.            FilmPlayback.speak { [model] said in model.say(said) }            // The player's Subtitles button opens Cinemas' own sheet (NEXT-PLAYER.md), dark, half then whole.            FilmPlayback.subtitlesSheet = { [model] film in                let item = CinemasItem(table: film.table, id: film.id, title: film.title, kind: film.table == "film_episode" ? .episode : .film)                let sheet = UIHostingController(rootView: CinemasSubtitlesSheet(model: model, item: item)                    .background(CinemasInk.ground.ignoresSafeArea()).preferredColorScheme(.dark))                sheet.overrideUserInterfaceStyle = .dark                if let parts = sheet.sheetPresentationController {                    parts.detents = [.medium(), .large()]                    parts.prefersGrabberVisible = true                    parts.preferredCornerRadius = 22                }                return sheet            }            FanLaunch.firstContent()            withAnimation(CinemasMotion.or(CinemasMotion.appOpens, reduced: reduceMotion)) { shown = true }            #if COTTON_DEV            await CinemasDevOpen.run(model, tv: tv)            #endif        }        // Another device, the Mac or an assistant wrote: read again.        .onChange(of: sync?.foreignRevision) { _, _ in model.changed() }        .onChange(of: phase) { _, now in            if now == .active {                model.changed()                model.prepareAgain()            }            // Hidden locks again as soon as the app leaves the screen; prepared films are let go, unless one plays on            // (picture in picture, the TV).            if now == .background {                model.lockHidden()                if !FilmPlayback.isPlaying { FilmPlayback.release() }            }        }        .onChange(of: model.inHiddenPlace) { _, now in model.hiddenShown(now) }        // No identifier on the root: on a container it would stand in for every element's own (the tabs', the toast's).    }    private func stack(_ tab: CinemasTab) -> some View {        NavigationStack(path: model.binding(tab)) {            root(tab)                .navigationDestination(for: CinemasRoute.self) { route in                    destination(route)                }        }        // Room for the bar (and the TV bar) under every place's scroll.        .safeAreaInset(edge: .bottom, spacing: 0) {            Color.clear.frame(height: tv.playing == nil ? CinemasTabs.height : CinemasTabs.height + CinemasTVBar.height)        }    }    @ViewBuilder private func root(_ tab: CinemasTab) -> some View {        switch tab {        case .home: CinemasHomeScreen(model: model, grow: grow)        case .search: CinemasSearchScreen(model: model, grow: grow)        case .you: CinemasYouScreen(model: model)        }    }    @ViewBuilder private func destination(_ route: CinemasRoute) -> some View {        switch route {        case .title(let item, let source):            CinemasTitleScreen(model: model, item: item, grow: grow)                // The system's zoom follows the finger back and can be caught mid-way; under Reduce Motion it is the                // system's own cross-fade.                .navigationTransition(.zoom(sourceID: source, in: grow))        case .row(let id, let title): CinemasRowScreen(model: model, id: id, title: title, grow: grow)        case .groups: CinemasGroupsScreen(model: model)        case .onPhone: CinemasOnPhoneScreen(model: model)        case .bin: CinemasBinScreen(model: model)        case .hiddenBin: CinemasBinScreen(model: model, hidden: true)        case .add: CinemasAddScreen(model: model)        case .hidden: CinemasHiddenScreen(model: model, grow: grow)        }    }}/// The bottom bar: three places, each an icon over its word; the one standing with its icon in amber and its word in/// ink, the icon springing in (0.9 → 1). A tap on the place standing goes back to its first screen.struct CinemasTabs: View {    static let height: CGFloat = 54    let model: CinemasModel    @Environment(\.accessibilityReduceMotion) private var reduceMotion    var body: some View {        HStack(spacing: 0) {            ForEach(CinemasTab.allCases, id: \.self) { tab in                let on = model.tab == tab                Button {                    if on { withAnimation { model.paths[tab] = [] } } else { model.tab = tab }                } label: {                    VStack(spacing: 4) {                        Image(systemName: on ? tab.iconOn : tab.icon)                            .font(.system(size: 21, weight: on ? .semibold : .regular))                            .foregroundStyle(on ? CinemasInk.accent : CinemasInk.faint)                            // MOTION: only the chosen icon springs, 0.9 → 1 (response 0.3, damping 0.7); the rest stand at 1.                            .keyframeAnimator(initialValue: CGFloat(1), trigger: on) { icon, scale in                                icon.scaleEffect(scale)                            } keyframes: { _ in                                KeyframeTrack {                                    if on && !reduceMotion {                                        LinearKeyframe(0.9, duration: 0.001)                                        SpringKeyframe(1, duration: 0.5, spring: Spring(response: 0.3, dampingRatio: 0.7))                                    } else {                                        LinearKeyframe(1, duration: 0.001)                                    }                                }                            }                        Text(CinemasWords.line("stream.\(tab.rawValue)"))                            .font(CinemasFonts.sans(11, 600, relativeTo: .caption2))                            .foregroundStyle(on ? CinemasInk.ink : CinemasInk.faint)                            .lineLimit(1)                    }                    .frame(maxWidth: .infinity, minHeight: Self.height)                    .padding(.top, 6)                    .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityLabel(Text(CinemasWords.line("stream.\(tab.rawValue)")))                .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)                // A long press shows the tab large, as the system's own bar does; each tab stays its own element.                .accessibilityShowsLargeContentViewer {                    Label(CinemasWords.line("stream.\(tab.rawValue)"), systemImage: on ? tab.iconOn : tab.icon)                }                .accessibilityIdentifier("cinemas-tab-\(tab.rawValue)")            }        }        // The bar stops growing at the largest ordinary size, as the system's own does; a long press shows it large.        .dynamicTypeSize(...DynamicTypeSize.xxLarge)        .background {            Rectangle().fill(.ultraThinMaterial)                .overlay(LinearGradient(colors: [CinemasInk.ground.opacity(0.98), CinemasInk.ground.opacity(0.85)], startPoint: .bottom, endPoint: .top))                .overlay(alignment: .top) { Rectangle().fill(Color.white.opacity(0.06)).frame(height: 0.5) }                .ignoresSafeArea(edges: .bottom)        }    }}/// The toast at the foot: rises 16 pt in 220 ms, holds 4 s (10 s with Undo), falls away in 180 ms.struct CinemasToastView: View {    let model: CinemasModel    @Environment(CinemasTV.self) private var tv    @Environment(\.accessibilityReduceMotion) private var reduceMotion    var body: some View {        ZStack {            if let toast = model.toast {                HStack(spacing: 12) {                    Text(toast.line).font(CinemasType.list).foregroundStyle(CinemasInk.ink).lineLimit(3)                    Spacer(minLength: 4)                    if let undo = toast.undo {                        Button(CinemasWords.line("stream.undo")) {                            model.toast = nil                            Task { await undo() }                        }                        .font(CinemasType.button)                        .foregroundStyle(CinemasInk.accent)                        .accessibilityIdentifier("cinemas-toast-undo")                    }                }                .padding(.horizontal, 16)                .padding(.vertical, 12)                .frame(minHeight: 52)                .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(CinemasInk.raisedHigh).shadow(color: .black.opacity(0.4), radius: 16, y: 6))                .padding(.horizontal, CinemasInk.side)                // Above the bottom bar, and above the TV bar while a film plays on the TV.                .padding(.bottom, CinemasTabs.height + (tv.playing == nil ? 0 : CinemasTVBar.height) + 10)                .transition(reduceMotion ? .opacity : .asymmetric(                    insertion: .offset(y: 16).combined(with: .opacity).animation(CinemasMotion.toastIn),                    removal: .offset(y: 16).combined(with: .opacity).animation(CinemasMotion.toastOut)))                .task(id: toast.id) {                    try? await Task.sleep(for: .seconds(toast.undo == nil ? 4 : 10))                    if model.toast?.id == toast.id { model.toast = nil }                }                .accessibilityElement(children: .contain)                .accessibilityIdentifier("cinemas-toast")            }        }        .animation(CinemasMotion.or(CinemasMotion.toastIn, reduced: reduceMotion), value: model.toast)        .onChange(of: model.toast) { _, now in            if let now { UIAccessibility.post(notification: .announcement, argument: now.line) }        }    }}extension CinemasSheet {    var detents: Set<PresentationDetent> {        switch self {        case .item: [.fraction(0.72), .large]        case .newGroup: [.height(240)]        case .rename: [.height(300)]        case .subtitles, .send: [.medium, .large]        case .hide: [.medium, .large]        case .share: [.large]        }    }}#endif