Cotton code
470 lines · 22.4 KB · SwiftRaw
// A TITLE'S PAGE (CONTRACT-2 "A title", cinemas-3.html screens 3 to 5): a big backdrop that moves at half the scroll// and fades and blurs as the page rises (stretching when pulled past the top), the title in the display face over its// foot, the facts, Play saying what it will do and Play on TV naming the TV, the acts, the synopsis, the subtitle line,// In your groups with Add, and a series' seasons with their episodes. The page's words fade in after the poster has// grown into it (240 ms at +180 ms); once the big title has scrolled off, it stands in the bar over 85% black (200 ms).#if os(iOS)import CottonKitimport SwiftUIstruct CinemasTitleScreen: View {    let model: CinemasModel    let item: CinemasItem    let grow: Namespace.ID    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var title: CinemasRead<CinemasTitle>?    @State private var scrolled: CGFloat = 0    private var width: CGFloat { model.width }    @State private var landed = false    @State private var asked = 0    /// 300 high on a 390 screen; a video's picture is its own 16:9 card instead.    /// A web video's picture is 16:9 whole, below the status bar the page reaches under.    private var videoPicture: CGFloat { (width * 9 / 16).rounded() }    private var statusBar: CGFloat {        (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.keyWindow?.safeAreaInsets.top ?? 0    }    private var backdropHeight: CGFloat { shown.kind == .clip ? videoPicture + statusBar : (width * 0.77).rounded() }    /// Where the big title has scrolled off under the bar.    private var titleBottom: CGFloat { backdropHeight - 10 }    private var shown: CinemasItem { title?.answer?.item ?? item }    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                backdrop                VStack(alignment: .leading, spacing: 16) {                    Text(shown.title.uppercased())                        .font(shown.kind == .clip ? CinemasType.title(30, black: false) : CinemasType.page)                        .foregroundStyle(CinemasInk.ink)                        .lineLimit(4)                        .minimumScaleFactor(0.6)                        .shadow(color: .black.opacity(0.4), radius: 10)                        .accessibilityAddTraits(.isHeader)                        .accessibilityIdentifier("cinemas-title-name")                    switch title {                    case .read(let title)?: CinemasTitleBody(model: model, title: title, grow: grow)                    case .refused(let line)?: CinemasRefused(line: line) { asked += 1 }                    case nil: skeleton                    }                }                .padding(.horizontal, CinemasInk.side)                .padding(.top, -34)                .padding(.bottom, 32)                .opacity(landed ? 1 : 0)                .animation(reduceMotion ? CinemasMotion.reduced : CinemasMotion.standard(0.24).delay(0.18), value: landed)            }        }        .scrollIndicators(.hidden)        .ignoresSafeArea(edges: .top)        .onScrollGeometryChange(for: CGFloat.self, of: { $0.contentOffset.y + $0.contentInsets.top }) { _, now in scrolled = now }        .background(CinemasInk.ground.ignoresSafeArea())        .toolbarBackgroundVisibility(scrolled > titleBottom ? .visible : .hidden, for: .navigationBar)        .toolbarBackground(Color.black.opacity(0.85), for: .navigationBar)        .toolbar {            ToolbarItem(placement: .principal) {                Text(shown.title)                    .font(CinemasFonts.sans(17, 600, relativeTo: .headline))                    .foregroundStyle(CinemasInk.ink)                    .lineLimit(1)                    .opacity(scrolled > titleBottom ? 1 : 0)                    .animation(CinemasMotion.or(CinemasMotion.headerBar, reduced: reduceMotion), value: scrolled > titleBottom)                    .accessibilityHidden(scrolled <= titleBottom)            }            ToolbarItem(placement: .topBarTrailing) {                CinemasRouteButton().frame(width: 32, height: 32)            }        }        .navigationBarTitleDisplayMode(.inline)        .task(id: "\(model.generation)/\(asked)") {            let read = await model.source.title(table: item.table, id: item.id, hidden: model.hiddenReads)            // A read that fails after one stood keeps what is on screen, and says why.            if case .refused(let line) = read, title?.answer != nil {                model.say(line)                return            }            withAnimation(title == nil ? nil : CinemasMotion.standard(0.2)) { title = read }        }        .onAppear {            landed = true            // Its play prepared while the page is read (shell.player prepare); let go as the page goes.            model.prepare(item)        }        .onDisappear { model.unprepare(item) }        .accessibilityIdentifier("cinemas-title")    }    /// The backdrop: half the scroll speed, fading to nothing and blurring to 12 pt over its own height; pulled past the    /// top, it stretches from its foot. Still under Reduce Motion. A preparing title's picture is drained and dimmed.    private var backdrop: some View {        let key = shown.backdrop ?? shown.poster        let rise = max(0, scrolled)        let pull = max(0, -scrolled)        let fraction = min(rise / backdropHeight, 1)        return CinemasPicture(key: key, title: nil, seed: shown.id, art: shown.art)            .frame(width: width, height: shown.kind == .clip ? videoPicture + pull : backdropHeight + pull)            .padding(.top, shown.kind == .clip ? statusBar : 0)            .saturation(shown.preparing ? 0.35 : 1)            .brightness(shown.preparing ? -0.25 : 0)            .overlay {                LinearGradient(stops: [.init(color: .black.opacity(0.5), location: 0), .init(color: .clear, location: 0.3),                                       .init(color: .clear, location: 0.55), .init(color: CinemasInk.ground, location: 1)],                               startPoint: .top, endPoint: .bottom)            }            .blur(radius: reduceMotion ? 0 : CinemasMotion.backdropBlur * fraction)            .opacity(reduceMotion ? 1 : 1 - fraction)            .offset(y: reduceMotion ? 0 : (pull > 0 ? -pull : rise * CinemasMotion.parallax))            .frame(width: width, height: backdropHeight, alignment: .bottom)            .accessibilityHidden(true)    }    private var skeleton: some View {        VStack(alignment: .leading, spacing: 12) {            CinemasBlock(corner: 3).frame(width: 200, height: 13)            CinemasBlock(corner: CinemasInk.buttonCorner).frame(height: CinemasInk.buttonHeight)            CinemasBlock(corner: CinemasInk.buttonCorner).frame(height: CinemasInk.buttonHeight)            HStack(spacing: 12) { ForEach(0..<4, id: \.self) { _ in CinemasBlock(corner: 12).frame(width: 60, height: 50) } }            ForEach(0..<3, id: \.self) { _ in CinemasBlock(corner: 3).frame(height: 11) }        }        .accessibilityHidden(true)    }}/// Everything under the title, once the core has answered.struct CinemasTitleBody: View {    @Environment(\.dynamicTypeSize) private var typeSize    let model: CinemasModel    let title: CinemasTitle    let grow: Namespace.ID    @Environment(CinemasTV.self) private var tv    @State private var synopsisOpen = false    /// The acts this phone runs: all the core offers.    private static let drawn: Set<String> = ["keep", "remove_download", "open_page", "group", "kind", "mark_watched", "mark_unwatched", "subtitles", "send", "bin"]    var body: some View {        let item = title.item        VStack(alignment: .leading, spacing: 16) {            if !title.facts.isEmpty {                Text(title.facts.joined(separator: "  ·  "))                    .font(CinemasType.meta)                    .foregroundStyle(CinemasInk.quiet)                    .accessibilityIdentifier("cinemas-title-facts")            }            if let progress = item.progress {                ZStack(alignment: .leading) {                    GeometryReader { box in                        Capsule().fill(Color.white.opacity(0.2))                        Capsule().fill(CinemasInk.accent).frame(width: (box.size.width * progress).drawableOrZero)                    }                }                .frame(height: 3)                .accessibilityHidden(true)            }            if let watched = title.watchedLine {                Text(watched).font(CinemasType.small).foregroundStyle(CinemasInk.quiet)                    .accessibilityIdentifier("cinemas-title-watched")            }            if item.preparing || title.preparing != nil {                CinemasPreparingCard(model: model, item: item, fallback: title.preparing?.line)            }            buttons(item)            CinemasActs(model: model, title: title, drawn: Self.drawn)            if let synopsis = title.synopsis {                Text(synopsis)                    .font(CinemasType.body)                    .lineSpacing(5)                    .foregroundStyle(CinemasInk.body)                    .lineLimit(synopsisOpen ? nil : 4)                    .onTapGesture { withAnimation(CinemasMotion.standard(0.25)) { synopsisOpen.toggle() } }                    .accessibilityIdentifier("cinemas-title-synopsis")            }            // A series' episodes come straight after what it is about, not after its groups (frame 4).            if let seasons = title.seasons, !seasons.isEmpty {                CinemasSeasons(model: model, seasons: seasons, grow: grow)            } else if title.item.kind == .series {                // A series the importer made with no episodes yet says so rather than showing nothing.                CinemasLine(line: CinemasWords.line("stream.season_empty"))            }            if let line = title.subtitles?.line {                Label(line, systemImage: "captions.bubble")                    .font(CinemasType.small)                    .foregroundStyle(CinemasInk.faint)                    .accessibilityIdentifier("cinemas-title-subtitles")            }            VStack(alignment: .leading, spacing: 10) {                CinemasLabel(text: CinemasWords.line("stream.in_groups"))                FlowRow(spacing: 8) {                    ForEach(title.groups.filter(\.in)) { group in                        CinemasChip(label: group.name) { model.push(.row(id: "group:\(group.id)", title: group.name)) }                    }                    CinemasChip(label: CinemasWords.line("stream.add"), icon: "plus", style: .accent) { model.sheet = .item(item) }                        .accessibilityIdentifier("cinemas-title-add")                }            }            .accessibilityElement(children: .contain)            if let source = title.source, let url = URL(string: source.url) {                Link(destination: url) {                    Label(source.by ?? url.host() ?? source.url, systemImage: "safari")                        .font(CinemasType.meta)                        .foregroundStyle(CinemasInk.quiet)                }                .accessibilityIdentifier("cinemas-title-source")            }        }    }    /// Play (amber) saying what it will do, Play on TV naming the TV once one is chosen, side by side for a series or a    /// video and stacked for a film; Play from the start under them.    @ViewBuilder private func buttons(_ item: CinemasItem) -> some View {        if title.preparing == nil {            // The core's words; naming the TV waits for the core to remember it (PUNCH Both 11).            let tvLabel = title.tv            let layout = item.kind == .film || typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10))            layout {                CinemasButton(label: title.play.label, icon: "play.fill") { model.play(item) }                    .accessibilityIdentifier("cinemas-title-play")                CinemasButton(label: tvLabel, icon: "tv", style: .outline) { tv.playOnTV(item, model: model) }                    .accessibilityIdentifier("cinemas-title-tv")            }            if let fromStart = title.play.fromStart {                Button { model.playFromStart(item) } label: {                    Label(fromStart, systemImage: "backward.end.fill")                        .font(CinemasFonts.sans(13, 600))                        .foregroundStyle(CinemasInk.quiet)                        .frame(maxWidth: .infinity, minHeight: 44)                        .contentShape(Rectangle())                }                .buttonStyle(CinemasPress())                .accessibilityIdentifier("cinemas-title-from-start")            }        } else {            CinemasButton(label: title.play.label, disabled: true) {}                .accessibilityIdentifier("cinemas-title-play")        }    }}/// The acts under Play: each a 72-wide column, an icon over its word; Add to a group in amber. At the largest text/// sizes they stand as a list.struct CinemasActs: View {    let model: CinemasModel    let title: CinemasTitle    let drawn: Set<String>    @Environment(\.dynamicTypeSize) private var typeSize    var body: some View {        let acts = title.acts.filter { drawn.contains($0.id) }        let row = Array(acts.filter { $0.place != "more" }.prefix(4))        let more = acts.filter { $0.place == "more" }        if typeSize.isAccessibilitySize {            VStack(alignment: .leading, spacing: 0) {                ForEach(row + more) { act in                    Button { model.take(act, on: title) } label: {                        Label(act.label, systemImage: Self.icon(act.id))                            .font(CinemasType.list)                            .foregroundStyle(act.id == "group" ? CinemasInk.accent : CinemasInk.ink)                            .frame(maxWidth: .infinity, minHeight: 52, alignment: .leading)                    }                    .buttonStyle(CinemasPress())                    .accessibilityIdentifier("cinemas-act-\(act.id)")                }            }        } else {            HStack(alignment: .top, spacing: 0) {                ForEach(row) { act in                    Button { model.take(act, on: title) } label: {                        column(icon: Self.icon(act.id), word: act.short ?? act.label, second: act.second, amber: act.id == "group")                    }                    .buttonStyle(CinemasPress())                    .frame(maxWidth: .infinity)                    .accessibilityLabel(Text(act.label))                    .accessibilityIdentifier("cinemas-act-\(act.id)")                }                if !more.isEmpty {                    Menu {                        ForEach(more) { act in                            Button { model.take(act, on: title) } label: { Label(act.label, systemImage: Self.icon(act.id)) }                                .accessibilityIdentifier("cinemas-act-\(act.id)")                        }                    } label: {                        column(icon: "ellipsis.circle", word: CinemasWords.line("home.act_more"), second: nil, amber: false)                    }                    .frame(maxWidth: .infinity)                    .accessibilityIdentifier("cinemas-act-more")                }            }        }    }    /// One column of the row (cinemas-3.html 3, `.acts`): a 24 pt icon in ink, the word in the softer ink, and the    /// second line in the faintest; Add to group's icon is amber.    private func column(icon: String, word: String, second: String?, amber: Bool) -> some View {        VStack(spacing: 5) {            Image(systemName: icon)                .font(.system(size: 22, weight: .regular))                .foregroundStyle(amber ? CinemasInk.accent : CinemasInk.ink)                .frame(height: 26)            Text(word).font(CinemasFonts.sans(11, 500, relativeTo: .caption2)).foregroundStyle(CinemasInk.quiet)                .multilineTextAlignment(.center).lineLimit(2)            if let second { Text(second).font(CinemasFonts.sans(10, 500, relativeTo: .caption2)).foregroundStyle(CinemasInk.faint).lineLimit(1) }        }        .frame(width: 72)        .padding(.vertical, 6)        .contentShape(Rectangle())    }    static func icon(_ act: String) -> String {        switch act {        case "keep": "arrow.down.circle"        case "remove_download": "checkmark.circle"        case "open_page": "safari"        case "group": "plus.rectangle.on.rectangle"        case "send": "paperplane"        case "subtitles": "captions.bubble"        case "kind": "film.stack"        case "mark_watched": "eye"        case "mark_unwatched": "eye.slash"        case "bin": "trash"        default: "ellipsis.circle"        }    }}/// A simple wrapping row.struct FlowRow: Layout {    var spacing: CGFloat = 6    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {        let width = proposal.width ?? .infinity        var x: CGFloat = 0, y: CGFloat = 0, line: CGFloat = 0, widest: CGFloat = 0        for view in subviews {            let size = view.sizeThatFits(.unspecified)            if x > 0, x + size.width > width {                y += line + spacing                x = 0                line = 0            }            x += size.width + spacing            line = max(line, size.height)            widest = max(widest, x - spacing)        }        return CGSize(width: min(widest, width), height: y + line)    }    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {        var x = bounds.minX, y = bounds.minY, line: CGFloat = 0        for view in subviews {            let size = view.sizeThatFits(.unspecified)            if x > bounds.minX, x + size.width > bounds.maxX {                y += line + spacing                x = bounds.minX                line = 0            }            view.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))            x += size.width + spacing            line = max(line, size.height)        }    }}extension CinemasModel {    /// One of a title's acts.    func take(_ act: CinemasTitle.Act, on title: CinemasTitle) {        let item = title.item        switch act.id {        case "group", "kind":            sheet = .item(item)        case "keep":            Task { if await FilmKeeper.shared.keep(table: item.table, id: item.id) { changed() } }        case "remove_download":            Task { if await FilmKeeper.shared.remove(table: item.table, id: item.id) { changed() } }        case "mark_watched", "mark_unwatched":            Task {                let watched = act.id == "mark_watched"                switch await source.mark(item, watched: watched) {                case .read(let said):                    changed()                    say(said ?? ShellLines.line("cinemas", watched ? "watch.marked" : "watch.unmarked", ["name": item.title]))                case .refused(let line):                    UINotificationFeedbackGenerator().notificationOccurred(.warning)                    say(line)                }            }        case "subtitles":            sheet = .subtitles(item)        case "send":            sheet = .send(item)        case "bin":            Task { await bin(item) }        case "open_page":            if let page = title.source.flatMap({ URL(string: $0.url) }) { UIApplication.shared.open(page) }        default:            break        }    }}/// Still being prepared (frame 11, `cinemas.preparing`): what the Mac at home is doing, each step done, now or next,/// what is ahead of it and the note. No minutes: nothing records them, so none are drawn. The main button stays,/// disabled, above it.struct CinemasPreparingCard: View {    let model: CinemasModel    let item: CinemasItem    let fallback: String?    @State private var page: CinemasPreparing?    @Environment(\.accessibilityReduceMotion) private var reduceMotion    var body: some View {        VStack(alignment: .leading, spacing: 12) {            HStack(alignment: .top, spacing: 10) {                Image(systemName: "desktopcomputer").foregroundStyle(CinemasInk.accent).accessibilityHidden(true)                VStack(alignment: .leading, spacing: 2) {                    Text(page?.head ?? fallback ?? CinemasWords.line("stream.poster_preparing"))                        .font(CinemasFonts.sans(15, 700)).foregroundStyle(CinemasInk.ink)                    if let queue = page?.queue { Text(queue).font(CinemasType.small).foregroundStyle(CinemasInk.quiet) }                }            }            .accessibilityElement(children: .combine)            if let steps = page?.steps, !steps.isEmpty {                VStack(alignment: .leading, spacing: 10) {                    ForEach(Array(steps.enumerated()), id: \.offset) { _, step in                        HStack(spacing: 10) {                            mark(step.state).frame(width: 20, height: 20)                            Text(step.label)                                .font(CinemasFonts.sans(14, step.state == "now" ? 700 : 400))                                .foregroundStyle(step.state == "next" ? CinemasInk.faint : CinemasInk.ink)                        }                        .accessibilityElement(children: .combine)                        .accessibilityValue(Text(CinemasWords.line("stream.step_\(step.state)")))                    }                }                .padding(.leading, 2)            }            if let note = page?.note {                Text(note).font(CinemasType.small).foregroundStyle(CinemasInk.quiet)            }        }        .padding(14)        .frame(maxWidth: .infinity, alignment: .leading)        .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(CinemasInk.accent.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [5, 4])))        .task(id: model.generation) {            if case .read(let answer) = await model.source.preparing(item) { page = answer }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("cinemas-title-preparing")    }    @ViewBuilder private func mark(_ state: String) -> some View {        switch state {        case "done": Image(systemName: "checkmark.circle.fill").foregroundStyle(CinemasInk.ok)        case "now":            Image(systemName: "circle.dotted").foregroundStyle(CinemasInk.accent)                .symbolEffect(.rotate, options: .repeat(.continuous), isActive: !reduceMotion)        default: Image(systemName: "circle").foregroundStyle(CinemasInk.faint)        }    }}#endif