Cotton code
328 lines · 16.0 KB · SwiftRaw
// HOME (CONTRACT-2 "Home: a featured title, then rows"; cinemas-3.html screen 1): one large featured title (what he// was watching, else the newest) under Cinemas' name, the TV button and the chips (Films, Series, Videos, Groups), with// its state in amber, Play and Play on TV; then sideways rows of posters in the core's order: Carry on, Recently added,// Films, Series, Videos, the automatic rows that have anything, then his own groups in his order, each marked "yours".// It settles in by MOTION.md: the picture from 1.06 and clear, the title and the buttons rising 16 pt after it, the// rows one after another.#if os(iOS)import CottonKitimport SwiftUIstruct CinemasHomeScreen: View {    let model: CinemasModel    let grow: Namespace.ID    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var home: CinemasRead<CinemasHome>?    private var width: CGFloat { model.width }    @State private var scrolled: CGFloat = 0    /// The rows have risen in once; a later read (an act, a sync) changes them in place.    @State private var risen = false    @State private var asked = 0    private var sizes: CinemasSizes { CinemasSizes(width: width) }    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 22) {                switch home {                case .read(let home)?:                    if let empty = home.empty {                        CinemasEmptyHome(model: model, empty: empty)                    } else {                        if let featured = home.featured {                            CinemasFeatured(model: model, featured: featured, size: sizes.featured, scrolled: scrolled, grow: grow)                                .id(featured.item.key)                                .transition(.opacity.animation(CinemasMotion.or(CinemasMotion.featuredChanges, reduced: reduceMotion)))                        } else {                            Color.clear.frame(height: 150)                        }                        LazyVStack(alignment: .leading, spacing: 22) {                            ForEach(Array(home.rows.enumerated()), id: \.element.id) { index, row in                                CinemasPosterRow(model: model, row: row, sizes: sizes, grow: grow)                                    .opacity(risen ? 1 : 0)                                    .offset(y: risen || reduceMotion ? 0 : CinemasMotion.rowRise)                                    .animation(reduceMotion ? CinemasMotion.reduced : CinemasMotion.rowAppears(index), value: risen)                            }                        }                        .padding(.bottom, 24)                    }                case .refused(let line)?:                    Color.clear.frame(height: 150)                    CinemasRefused(line: line) { asked += 1 }                case nil:                    CinemasHomeSkeleton(sizes: sizes)                }            }        }        .scrollIndicators(.hidden)        .ignoresSafeArea(edges: .top)        .onScrollGeometryChange(for: CGFloat.self, of: { $0.contentOffset.y + $0.contentInsets.top }) { _, now in scrolled = now }        .overlay(alignment: .top) { CinemasHomeBar(model: model, rows: home?.answer?.rows ?? [], scrolled: scrolled) }        .background(CinemasInk.ground.ignoresSafeArea())        .toolbar(.hidden, for: .navigationBar)        .task(id: "\(model.generation)/\(asked)") {            let read = await model.source.home()            // A read that fails after Home stood keeps what is on screen, and says why.            if case .refused(let line) = read, home?.answer != nil {                model.say(line)                return            }            withAnimation(home == nil ? nil : CinemasMotion.or(CinemasMotion.featuredChanges, reduced: reduceMotion)) { home = read }            if !risen { risen = true }        }        .refreshable { model.changed() }        .accessibilityIdentifier("cinemas-home")    }}/// Over Home: Cinemas' name and the TV button, then the chips: Films, Series and Videos (each the core's own row, by/// its own title, opened whole) and Groups. They stand on the picture at the top and on a blurred dark ground once the/// page has scrolled (200 ms).struct CinemasHomeBar: View {    let model: CinemasModel    let rows: [CinemasHome.Row]    let scrolled: CGFloat    @Environment(\.accessibilityReduceMotion) private var reduceMotion    /// The app's name as its icon says it, without "Cotton".    private var name: String {        let whole = FlavourManifest.current?.name ?? "Cinemas"        return (whole.hasPrefix("Cotton ") ? String(whole.dropFirst(7)) : whole).uppercased()    }    var body: some View {        let solid = scrolled > 40        VStack(alignment: .leading, spacing: 8) {            HStack(spacing: 8) {                CinemasPopcornBox().frame(width: 18, height: 22).accessibilityHidden(true)                Text(name)                    .font(CinemasType.title(26))                    .tracking(0.8)                    .foregroundStyle(CinemasInk.ink)                    .accessibilityAddTraits(.isHeader)                Spacer(minLength: 8)                ZStack {                    Circle().fill(.ultraThinMaterial).overlay(Circle().fill(Color.black.opacity(0.55))).frame(width: 38, height: 38)                    CinemasRouteButton().frame(width: 30, height: 30)                }                .frame(width: 44, height: 44)            }            ScrollView(.horizontal) {                HStack(spacing: 8) {                    ForEach(rows.filter { ["films", "series", "videos"].contains($0.id) }) { row in                        CinemasChip(label: row.title) { model.push(.row(id: row.id, title: row.title)) }                            .accessibilityIdentifier("cinemas-chip-\(row.id)")                    }                    CinemasChip(label: CinemasWords.line("stream.groups_short")) { model.push(.groups) }                        .accessibilityIdentifier("cinemas-chip-groups")                }            }            .scrollIndicators(.hidden)            .contentMargins(.horizontal, CinemasInk.side, for: .scrollContent)            .padding(.horizontal, -CinemasInk.side)        }        .padding(.horizontal, CinemasInk.side)        .padding(.bottom, 8)        .background {            ZStack {                Rectangle().fill(.ultraThinMaterial).opacity(solid ? 1 : 0)                CinemasInk.ground.opacity(solid ? 0.7 : 0)            }            .ignoresSafeArea(edges: .top)            .animation(CinemasMotion.or(CinemasMotion.headerBar, reduced: reduceMotion), value: solid)        }        .dynamicTypeSize(...DynamicTypeSize.xxxLarge)    }}/// The featured title: its picture full width, shaded to the ground; its state in amber, the title tall and narrow, the/// part watched, Play and Play on TV side by side.struct CinemasFeatured: View {    let model: CinemasModel    let featured: CinemasHome.Featured    let size: CGSize    let scrolled: CGFloat    let grow: Namespace.ID    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @Environment(\.dynamicTypeSize) private var typeSize    @Environment(CinemasTV.self) private var tv    @State private var settled = false    /// The year and the length of the featured title.    private var meta: [String] {        let item = featured.item        var parts: [String] = []        if let year = item.year { parts.append(year) }        if let minutes = item.minutes, item.kind != .series, minutes > 0 {            parts.append(cinemasLength(minutes))        }        return parts    }    var body: some View {        let item = featured.item        ZStack(alignment: .bottomLeading) {            CinemasPicture(key: item.backdrop ?? item.poster, title: nil, seed: item.id, art: item.art)                .frame(width: size.width, height: size.height)                .saturation(item.preparing ? 0.35 : 1)                .scaleEffect(settled || reduceMotion ? 1 : CinemasMotion.featuredScale)                .opacity(settled ? 1 : 0)                .animation(reduceMotion ? CinemasMotion.reduced : CinemasMotion.featuredBackdrop, value: settled)                // A slow drift as the page scrolls, so the picture sits behind the rows (off with Reduce Motion).                .offset(y: reduceMotion ? 0 : max(0, scrolled) * 0.25)                .clipped()            LinearGradient(stops: [.init(color: CinemasInk.ground.opacity(0.55), location: 0), .init(color: .clear, location: 0.22),                                   .init(color: .clear, location: 0.45), .init(color: CinemasInk.ground.opacity(0.85), location: 0.78),                                   .init(color: CinemasInk.ground, location: 1)],                           startPoint: .top, endPoint: .bottom)            VStack(alignment: .leading, spacing: 0) {                VStack(alignment: .leading, spacing: 6) {                    if let line = featured.line {                        Text(line.uppercased())                            .font(CinemasType.label)                            .tracking(1.2)                            .foregroundStyle(CinemasInk.accent)                            .accessibilityIdentifier("cinemas-featured-line")                    }                    Text(item.title.uppercased())                        .font(CinemasType.featured)                        .foregroundStyle(CinemasInk.ink)                        .lineLimit(3)                        .minimumScaleFactor(0.5)                        .shadow(color: .black.opacity(0.45), radius: 12)                        .accessibilityAddTraits(.isHeader)                    // The meta line (iPhone 4): the year and the length, each in the core's or the line set's words.                    // CC, language and 4K wait for the core's featured facts.                    if !meta.isEmpty {                        Text(meta.joined(separator: " · "))                            .font(CinemasFonts.sans(13, 500)).foregroundStyle(CinemasInk.body)                            .accessibilityIdentifier("cinemas-featured-meta")                    }                    if let progress = item.progress {                        GeometryReader { box in                            ZStack(alignment: .leading) {                                Capsule().fill(Color.white.opacity(0.2))                                Capsule().fill(CinemasInk.accent).frame(width: (box.size.width * progress).drawableOrZero)                            }                        }                        .frame(height: 3)                        .padding(.top, 6)                        .padding(.bottom, 8)                        .accessibilityHidden(true)                    }                }                .opacity(settled ? 1 : 0)                .offset(y: settled || reduceMotion ? 0 : CinemasMotion.featuredRise)                .animation(reduceMotion ? CinemasMotion.reduced : CinemasMotion.featuredTitle, value: settled)                .contentShape(Rectangle())                .onTapGesture { model.open(item, from: "featured") }                .accessibilityElement(children: .combine)                .accessibilityAddTraits(.isButton)                .accessibilityAction { model.open(item, from: "featured") }                .accessibilityIdentifier("cinemas-featured-title")                // The title is already poster-sized; past the largest ordinary size it would climb into the chips.                .dynamicTypeSize(...DynamicTypeSize.xxLarge)                // Side by side, stacked once the text is too large for two across.                (typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10))) {                    if item.preparing {                        CinemasButton(label: CinemasWords.line("stream.more"), style: .outline) { model.open(item, from: "featured") }                    } else {                        CinemasButton(label: featured.play, icon: "play.fill") { model.play(item) }                            .accessibilityIdentifier("cinemas-featured-play")                        CinemasButton(label: featured.tv, icon: "tv", style: .outline) { tv.playOnTV(item, model: model) }                            .accessibilityIdentifier("cinemas-featured-tv")                    }                }                .padding(.top, 8)                .opacity(settled ? 1 : 0)                // Featured's Play is ready before the tap, as a title's page is.                .onAppear { model.prepare(item) }                .onChange(of: item.id) { model.prepare(item) }                .offset(y: settled || reduceMotion ? 0 : CinemasMotion.featuredRise)                .animation(reduceMotion ? CinemasMotion.reduced : CinemasMotion.featuredButtons, value: settled)            }            .padding(.horizontal, CinemasInk.side)        }        .frame(width: size.width, height: size.height)        .matchedTransitionSource(id: "featured/\(item.key)", in: grow)        .onAppear { settled = true }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("cinemas-featured")    }}/// Home before its first answer: the featured block and three rows as shapes in their final sizes, shimmering.struct CinemasHomeSkeleton: View {    let sizes: CinemasSizes    var body: some View {        VStack(alignment: .leading, spacing: 22) {            ZStack(alignment: .bottomLeading) {                Rectangle().fill(CinemasInk.raised).frame(width: sizes.featured.width, height: sizes.featured.height)                VStack(alignment: .leading, spacing: 10) {                    CinemasBlock(corner: 3).frame(width: 140, height: 12)                    CinemasBlock(corner: 4).frame(width: 240, height: 52)                    HStack(spacing: 10) {                        CinemasBlock(corner: CinemasInk.buttonCorner).frame(width: sizes.halfButton, height: CinemasInk.buttonHeight)                        CinemasBlock(corner: CinemasInk.buttonCorner).frame(width: sizes.halfButton, height: CinemasInk.buttonHeight)                    }                    .padding(.top, 8)                }                .padding(.horizontal, CinemasInk.side)            }            CinemasSkeletonRow(sizes: sizes)            CinemasSkeletonRow(sizes: sizes)            CinemasSkeletonRow(sizes: sizes)        }        .accessibilityElement()        .accessibilityLabel(Text(CinemasWords.line("stream.loading")))        .accessibilityIdentifier("cinemas-home-skeleton")    }}/// No titles at all: the core's words and Add films.struct CinemasEmptyHome: View {    let model: CinemasModel    let empty: CinemasHome.Empty    var body: some View {        VStack(alignment: .leading, spacing: 14) {            Spacer(minLength: 200)            Text(empty.title.uppercased()).font(CinemasType.title(34)).foregroundStyle(CinemasInk.ink)            Text(empty.line).font(CinemasType.body).foregroundStyle(CinemasInk.quiet)            CinemasAddFilms(model: model, label: empty.add)                .frame(maxWidth: 260)                .padding(.top, 8)        }        .padding(.horizontal, CinemasInk.side)        .frame(maxWidth: .infinity, alignment: .leading)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("cinemas-empty")    }}/// The wordmark's striped popcorn box (`.wm i`): red and cream stripes 4 pt wide, narrowing to 70% at its foot.struct CinemasPopcornBox: View {    var body: some View {        Canvas { context, size in            let w = size.width, h = size.height            var box = Path()            box.move(to: .zero)            box.addLine(to: CGPoint(x: w, y: 0))            box.addLine(to: CGPoint(x: w * 0.85, y: h))            box.addLine(to: CGPoint(x: w * 0.15, y: h))            box.closeSubpath()            context.clip(to: box)            context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(Color(cinemasHex: "#f6efe6")))            var x: CGFloat = 0            while x < w {                context.fill(Path(CGRect(x: x, y: 0, width: 4, height: h)), with: .color(Color(cinemasHex: "#e33a2c")))                x += 8            }        }    }}#endif