Cotton code
314 lines · 14.5 KB · SwiftRaw
// HIDDEN (CONTRACT-2 HIDDEN, the owner 26 Nov): his categories he keeps out of sight, and every title in any of them.// Outside, the core leaves them out of every answer; the phone never filters. You › Hidden, the last row of You, asks// the phone's own lock (DeviceLock, as Sites asks it) each time it opens, then the core's unlock (`cinemas.unlock`);// inside it is a small home (Carry on, each hidden category, a search over hidden titles alone) whose reads say// `hidden: true`. Leaving Hidden or the app shuts it at once (`cinemas.lock`). With no screen lock it opens and says// so honestly, with Set a screen lock (Sites' scheme, Cinemas' words).//// HIDE FROM SCREEN (the owner, 27 Nov): hidden is from the SCREEN, not from assistants: a hidden category and its titles// do not show in Cinemas until he opens You › Hidden behind the phone's lock. Reachable in every build. A hidden title// playing never names itself or shows its poster on the lock screen, Control Centre or a TV (FilmPlayback.nowPlaying).//// A category is hidden from its menu on Home or in You › Your categories ("Hide this category", then the Hide sheet's// honest line once); inside Hidden its menu says Stop hiding. Both come back with Undo.#if os(iOS)import CottonKitimport SwiftUIextension CinemasModel {    /// Whether Hidden can be reached: in every build (HIDE FROM SCREEN, the owner 27 Nov: what he wanted all along is    /// hide from the screen, and he thought it was built). Kept as one switch so a walk can still ask where it stands.    var hiddenReachable: Bool { true }    /// Hidden's own place is showing: You, with Hidden first on its stack.    var inHiddenPlace: Bool { tab == .you && paths[.you]?.first == .hidden }    /// Whether a read here says `hidden: true`: only inside Hidden, once it is open.    var hiddenReads: Bool { hidden.open && inHiddenPlace }    /// You › Hidden: the phone's own lock first, every time it opens (or, with none, said so), then the core's unlock    /// (`cinemas.unlock`), which the core gives only on that word and shuts on `cinemas.lock`.    func openHidden() async {        var isSet = DeviceLock.isSet        var passed: Bool?        #if COTTON_DEV        // A walk on a simulator (never the real build): `-cinemas-skip-lock` stands for a lock that passed,        // `-cinemas-no-lock` for a phone with none.        let arguments = ProcessInfo.processInfo.arguments        if arguments.contains("-cinemas-skip-lock") { isSet = true; passed = true }        if arguments.contains("-cinemas-no-lock") { isSet = false }        #endif        if isSet {            if passed == nil { passed = await DeviceLock.ask(CinemasWords.line("stream.hidden_unlock")) }            guard passed == true else { return }        }        switch await source.unlock(noLock: !isSet) {        case .read(true):            hidden.open = true            hidden.noLock = !isSet            FilmPlayback.hiddenChanged()            tab = .you            paths[.you] = [.hidden]        case .read(false):            say(CinemasWords.line("stream.hidden_locked"))        case .refused(let line):            say(line)        }    }    /// Hidden's place shown or left: left, it shuts at once (`cinemas.lock`), and opens again only behind the lock.    func hiddenShown(_ shown: Bool) {        if !shown { lockHidden() }    }    /// Shut: the app left the screen, or he left Hidden. The core's unlock is shut, what was read inside is let go,    /// and the screens stacked over Hidden close with it.    func lockHidden() {        let was = hidden.open        hidden.open = false        if paths[.you]?.first == .hidden {            paths[.you] = []            if tab == .you { sheet = nil }        }        guard was else { return }        // A hidden title playing on: the lock screen no longer names it.        FilmPlayback.hiddenChanged()        let source = self.source        Task { _ = await source.lock() }        changed()    }    /// Hide a category, or stop hiding it; the core's words, with the Undo it handed back, run exactly as handed (a    /// Hide's carries a one-use token, so its Undo works on Home with Hidden shut).    func hide(_ group: String, hidden: Bool) async {        switch await source.hide(group, hidden: hidden) {        case .read(let done):            changed()            guard done.unchanged != true else { return }            let source = self.source            let undo: (@Sendable () async -> Void)? = done.undo.map { handed in                { @Sendable [weak self] in                    switch await source.undo(handed) {                    case .read(let undone):                        await self?.changed()                        if let line = undone.line { await self?.say(line) }                    case .refused(let line):                        await self?.say(line)                    }                }            }            say(done.line ?? CinemasWords.line("stream.done"), undo: undo)        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)        }    }}extension CinemasModel {    /// A hidden category the Bin holds, restored from inside Hidden (`cinemas.restore`): the core's words, then read again.    func restoreNamed(_ act: CinemasNamedAct) async {        switch await source.named(act, id: nil) {        case .read(let said):            changed()            say(said ?? CinemasWords.line("stream.done"))        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)        }    }}/// Hidden's state on the model.struct CinemasHiddenState {    /// The phone's lock passed (or the phone has none) and the core unlocked: Hidden shows.    var open = false    /// The phone has no screen lock: Hidden opens, and says so.    var noLock = false}// MARK: - The Hide sheet/// "Hide Rainy Sundays?": the honest line, once, then Hide or Cancel.struct CinemasHideSheet: View {    let model: CinemasModel    let group: String    let name: String    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 16) {                Text(CinemasWords.line("stream.hide_title", ["group": name]))                    .font(CinemasType.title(28))                    .foregroundStyle(CinemasInk.ink)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityAddTraits(.isHeader)                Text(CinemasWords.line("stream.hide_line"))                    .font(CinemasType.body)                    .foregroundStyle(CinemasInk.quiet)                    .fixedSize(horizontal: false, vertical: true)                CinemasButton(label: CinemasWords.line("stream.hide_act"), icon: "eye.slash") {                    model.sheet = nil                    Task { await model.hide(group, hidden: true) }                }                .accessibilityIdentifier("cinemas-hide-confirm")                CinemasButton(label: CinemasWords.line("stream.group_cancel"), style: .outline) { model.sheet = nil }                    .accessibilityIdentifier("cinemas-hide-cancel")            }            .padding(.horizontal, CinemasInk.side)            .padding(.top, 28)            .padding(.bottom, 20)        }        .scrollBounceBehavior(.basedOnSize)        .accessibilityIdentifier("cinemas-hide-sheet")    }}// MARK: - You › Hidden/// Hidden's own small home: the honest line when the phone has no lock, a search over hidden titles alone, then the/// core's rows (Carry on, each hidden category), each with Stop hiding in its menu.struct CinemasHiddenScreen: View {    let model: CinemasModel    let grow: Namespace.ID    @State private var place: CinemasRead<CinemasHiddenPlace>?    @State private var q = ""    @State private var found: CinemasFound?    @Environment(\.scenePhase) private var phase    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 18) {                CinemasPageTitle(text: CinemasWords.line("stream.hidden_place"))                    .padding(.horizontal, CinemasInk.side)                switch place {                case .read(let place)? where place.locked:                    // The core's unlock ran out: its words, and the lock asked again.                    CinemasButton(label: place.unlock ?? CinemasWords.line("stream.hidden_unlock"), icon: "lock") {                        Task { await model.openHidden() }                    }                    .padding(.horizontal, CinemasInk.side)                    .accessibilityIdentifier("cinemas-hidden-unlock")                case .read(let place)?:                    if let noLock = place.noLock { noLockCard(noLock, set: place.setLock) }                    search(place.searchHint ?? CinemasWords.line("stream.hidden_search_hint"))                    if !q.trimmingCharacters(in: .whitespaces).isEmpty {                        results                    } else if place.rows.isEmpty {                        Text(place.empty ?? CinemasWords.line("stream.hidden_empty"))                            .font(CinemasType.body)                            .foregroundStyle(CinemasInk.quiet)                            .fixedSize(horizontal: false, vertical: true)                            .padding(.horizontal, CinemasInk.side)                            .accessibilityIdentifier("cinemas-hidden-empty")                    } else {                        ForEach(place.rows) { row in                            if row.act?.method == CottonMethod.cinemasBin {                                CinemasPlaceRow(title: row.title, count: row.count) { model.push(.hiddenBin) }                                    .accessibilityIdentifier("cinemas-hidden-bin")                            } else {                                CinemasPosterRow(model: model, row: row, sizes: CinemasSizes(width: model.width), grow: grow)                            }                        }                    }                case .refused(let line)?:                    CinemasRefused(line: line) { Task { await read() } }                case nil:                    ProgressView().tint(CinemasInk.accent).frame(maxWidth: .infinity)                }            }            .padding(.bottom, 24)        }        .background(CinemasInk.ground.ignoresSafeArea())        // Nothing of Hidden in the app switcher's picture: covered as soon as the app is not in front.        .overlay { if phase != .active { CinemasInk.ground.ignoresSafeArea() } }        .task(id: model.generation) { await read() }        .task(id: "\(model.generation)/\(q)") { await look() }        .accessibilityIdentifier("cinemas-hidden")    }    private func read() async {        guard model.hidden.open else { return }        place = await model.source.hiddenPlace()    }    private func look() async {        let words = q.trimmingCharacters(in: .whitespaces)        guard !words.isEmpty, model.hidden.open else { found = nil; return }        try? await Task.sleep(for: .milliseconds(180))        guard !Task.isCancelled else { return }        found = await model.source.search(words, hidden: true).answer    }    private func noLockCard(_ line: String, set: String?) -> some View {        VStack(alignment: .leading, spacing: 12) {            Label {                Text(line).font(CinemasType.body).foregroundStyle(CinemasInk.ink).fixedSize(horizontal: false, vertical: true)            } icon: {                Image(systemName: "lock.open").foregroundStyle(CinemasInk.accent)            }            if let set {                CinemasButton(label: set, style: .outline, height: 44) { DeviceLock.openSettings() }                    .accessibilityIdentifier("cinemas-hidden-set-lock")            }        }        .padding(16)        .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(CinemasInk.raised))        .padding(.horizontal, CinemasInk.side)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("cinemas-hidden-no-lock")    }    private func search(_ hint: String) -> some View {        HStack(spacing: 10) {            Image(systemName: "magnifyingglass").foregroundStyle(CinemasInk.quiet).accessibilityHidden(true)            TextField(text: $q, prompt: Text(hint).foregroundStyle(CinemasInk.faint)) { Text(hint) }                .font(CinemasType.list)                .foregroundStyle(CinemasInk.ink)                .tint(CinemasInk.accent)                .submitLabel(.search)                .autocorrectionDisabled()                .accessibilityIdentifier("cinemas-hidden-search")        }        .padding(.horizontal, 14)        .frame(minHeight: 48)        .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(CinemasInk.raised))        .padding(.horizontal, CinemasInk.side)    }    @ViewBuilder private var results: some View {        if let found {            VStack(alignment: .leading, spacing: 0) {                ForEach(found.items) { item in                    Button { model.open(item, from: "hidden-search") } label: {                        HStack(spacing: 12) {                            CinemasPicture(key: item.poster, title: item.title, seed: item.id, art: item.art)                                .frame(width: 44, height: 66)                                .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous))                            Text(item.title).font(CinemasType.list).foregroundStyle(CinemasInk.ink).multilineTextAlignment(.leading)                            Spacer(minLength: 0)                        }                        .padding(.vertical, 8)                        .contentShape(Rectangle())                    }                    .buttonStyle(CinemasPress())                    .accessibilityIdentifier("cinemas-hidden-found-\(item.id)")                }                ForEach(found.groups) { group in                    Button { model.push(.row(id: "group:\(group.id)", title: group.name)) } label: {                        Label(group.name, systemImage: "square.stack")                            .font(CinemasType.list).foregroundStyle(CinemasInk.ink)                            .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)                            .contentShape(Rectangle())                    }                    .buttonStyle(CinemasPress())                }            }            .padding(.horizontal, CinemasInk.side)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("cinemas-hidden-results")        }    }}#endif