Cotton code
260 lines · 11.3 KB · SwiftRaw
// COTTON ALBUMS' ROOT (assets/design/albums/DECISIONS.md "The structure"): the whole app, mounted by the root in place// of the fan and the board (`RootView.hosts`), as Data and Sites are. The core says which screen opens (`albums.start`):// first run, no permission, or the four places at the foot (Albums, Tidy, People, You), opening on Albums, always.// Screens stand over a place and go back with a swipe from the edge. Whenever Albums leaves the screen it lays down its// ground and mark, never a photo.#if os(iOS)import CottonKitimport SwiftUIstruct AlbumsRoot: View {    /// Cotton Albums' own build.    static var applies: Bool { FlavourManifest.current?.flavour == "albums" }    @State private var model: AlbumsModel    @Environment(\.scenePhase) private var phase    @Environment(\.accessibilityReduceMotion) private var still    @State private var launching = true    init(core: any CottonCalling) {        _model = State(initialValue: AlbumsModel(core: core))    }    init(model: AlbumsModel) {        _model = State(initialValue: model)    }    var body: some View {        ZStack {            Olive.ground.ignoresSafeArea()            switch model.opening?.screen {            case "home"?:                AlbumsPlaces(model: model).accessibilityHidden(model.sheet != nil)            case "no_permission"?:                if let none = model.opening?.noPermission { AlbumsNoPermission(model: model, words: none) }            case "first_run"?:                if let first = model.opening?.firstRun { AlbumsFirstRun(model: model, words: first) }            default:                EmptyView()            }            sheetOverlay            if let toast = model.toast {                VStack {                    Spacer()                    AlbumsToast(words: toast.words, undo: toast.undo?.label) {                        if let undo = toast.undo { Task { await model.undo(undo) } }                    }                    .padding(.bottom, model.home ? 64 : 24)                    .padding(.horizontal, Olive.side)                }                .transition(.move(edge: .bottom).combined(with: .opacity))            }            if launching {                AlbumsLaunchMark().transition(.opacity).allowsHitTesting(false)            }            // The app switcher's picture: the ground and the mark, never a photo.            if phase != .active {                AlbumsLaunchMark().accessibilityHidden(true)            }        }        .lookStanding(Olive.look)        .task {            FanLaunch.firstContent()            Task { await SettingsHome.warm(model.core) }            // The library is read behind the first screen (a whole first read of a large library takes a while):            // the mark never waits for it.            Task { await model.launched() }            try? await Task.sleep(for: .milliseconds(still ? 0 : 300))            withAnimation(still ? nil : .easeOut(duration: 0.45)) { launching = false }        }        .task(id: model.pass.revision) { await model.readLines() }        .onChange(of: phase) { _, now in            switch now {            case .active: model.cameBack()            case .background: model.wentAway()            default: break            }        }        .animation(still ? nil : .easeOut(duration: 0.22), value: model.sheet)        .animation(still ? nil : .easeOut(duration: 0.22), value: model.toast)    }    @ViewBuilder private var sheetOverlay: some View {        if let sheet = model.sheet {            let close = { withAnimation(still ? nil : .easeOut(duration: 0.2)) { model.sheet = nil } }            AlbumsSheet(close: close) {                switch sheet {                case .ask(let ask): AlbumsAskView(ask: ask, close: close)                case .makeAlbum: AlbumsTitleSheet(title: AlbumsWords.line("album.make_title"), yes: AlbumsWords.line("album.make"), start: "", tag: "make", close: close) {                    await model.makeAlbum($0)                }                case .rename(let id, let title): AlbumsTitleSheet(title: AlbumsWords.line("album.rename"), yes: AlbumsWords.line("album.save"), start: title, tag: "rename", close: close) {                    await model.rename(id, to: $0)                }                case .name(let group): AlbumsTitleSheet(title: AlbumsWords.line("people.name_title"), yes: AlbumsWords.line("people.save"), start: "",                                                        hint: AlbumsWords.line("people.name_hint"), tag: "name", close: close) {                    await model.name(group, $0)                }                case .keep(let id, let title): AlbumsKeepSheet(id: id, title: title, close: close)                }            }            .transition(still ? .opacity : .move(edge: .bottom).combined(with: .opacity))        }    }}/// The launch's mark alone on the ground, where the launch screen lays it (`LaunchObject`).struct AlbumsLaunchMark: View {    var body: some View {        ZStack {            Olive.ground            if let object = SplashKnobs.object { object.frame(maxWidth: .infinity, maxHeight: .infinity) }        }        .ignoresSafeArea()        .accessibilityHidden(true)    }}/// A sheet over the places: a veil, the sheet at the foot, a swipe down or a tap on the veil closes it.struct AlbumsSheet<Content: View>: View {    let close: () -> Void    @ViewBuilder var content: () -> Content    @State private var drag: CGFloat = 0    var body: some View {        ZStack(alignment: .bottom) {            Olive.veil.ignoresSafeArea().onTapGesture(perform: close).accessibilityHidden(true)            VStack(alignment: .leading, spacing: 0) {                Capsule().fill(Olive.rule).frame(width: 36, height: 5).frame(maxWidth: .infinity).padding(.top, 8).padding(.bottom, 16)                // Taller than the screen (the largest text): the sheet scrolls, its buttons reached at the foot.                ViewThatFits(in: .vertical) {                    content()                    ScrollView { content() }.scrollBounceBehavior(.basedOnSize)                }            }            .padding(.horizontal, Olive.side)            .padding(.bottom, 20)            .frame(maxWidth: .infinity)            .background(UnevenRoundedRectangle(topLeadingRadius: 22, topTrailingRadius: 22).fill(Olive.ground).ignoresSafeArea())            .offset(y: max(0, drag))            .gesture(DragGesture().onChanged { drag = $0.translation.height }.onEnded { end in                if end.translation.height > 100 { close() }                drag = 0            })            .accessibilityAction(.escape, close)        }    }}/// The places and the screens stood on them, with the four tabs at the foot.struct AlbumsPlaces: View {    @Bindable var model: AlbumsModel    @Environment(\.accessibilityReduceMotion) private var still    @State private var typing = false    var body: some View {        VStack(spacing: 0) {            ZStack {                ForEach(AlbumsTab.allCases) { tab in                    if model.visited.contains(tab) {                        let shown = model.tab == tab && model.stack.isEmpty                        root(tab)                            .opacity(model.tab == tab ? 1 : 0)                            .allowsHitTesting(shown)                            .accessibilityHidden(!shown)                    }                }                ForEach(Array(model.stack.enumerated()), id: \.element.id) { at, screen in                    let top = at == model.stack.count - 1                    AlbumsScreenView(model: model, screen: screen)                        .background(Olive.ground)                        .allowsHitTesting(top)                        .accessibilityHidden(!top)                        .transition(still ? .opacity : .move(edge: .trailing))                        .gesture(top ? edgeBack : nil)                        .accessibilityAction(.escape) { model.back() }                }            }            .frame(maxWidth: .infinity, maxHeight: .infinity)            .animation(still ? nil : .easeOut(duration: 0.24), value: model.stack)            if !typing { AlbumsTabs(model: model) }        }        .background(Olive.ground)        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in typing = true }        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in typing = false }    }    private var edgeBack: some Gesture {        DragGesture(minimumDistance: 20, coordinateSpace: .global).onEnded { end in            if end.startLocation.x < 28, end.translation.width > 80, abs(end.translation.height) < end.translation.width { model.back() }        }    }    @ViewBuilder private func root(_ tab: AlbumsTab) -> some View {        switch tab {        case .albums: AlbumsListScreen(model: model)        case .tidy: AlbumsTidyScreen(model: model)        case .people: AlbumsPeopleScreen(model: model)        case .you: AlbumsYouScreen(model: model)        }    }}/// The four places at the foot: text only, the one stood on in ink and bold with a short line under it.struct AlbumsTabs: View {    let model: AlbumsModel    var body: some View {        VStack(spacing: 0) {            AlbumsRule()            HStack(spacing: 0) {                ForEach(AlbumsTab.allCases) { tab in                    let on = model.tab == tab                    Button { model.place(tab) } label: {                        VStack(spacing: 4) {                            Text(verbatim: tab.words)                                .font(AlbumsType.sans(15, on ? .bold : .regular, .subheadline, upTo: 17))                                .foregroundStyle(on ? Olive.ink : Olive.quiet)                                .lineLimit(1).minimumScaleFactor(0.8)                            Capsule().fill(on ? Olive.ink : .clear).frame(width: 18, height: 2)                        }                        .padding(.horizontal, 4)                        .frame(maxWidth: .infinity, minHeight: 48)                        .contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)                    .accessibilityIdentifier("albums-tab-\(tab.rawValue)")                    .accessibilityShowsLargeContentViewer { Text(verbatim: tab.words) }                }            }            .padding(.top, 4)        }        .background(Olive.ground)        // The four words stay readable side by side; past this a long press shows the word large.        .dynamicTypeSize(...DynamicTypeSize.large)    }}/// A page on a place: scrolls, the side margin, the tag a walk finds it by; pulling reads it again.struct AlbumsPage<Content: View>: View {    let tag: String    var pull: (() async -> Void)?    @ViewBuilder var content: () -> Content    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) { content() }                .padding(.horizontal, Olive.side)                .padding(.bottom, 32)                .frame(maxWidth: .infinity, alignment: .leading)        }        .scrollIndicators(.hidden)        .refreshable { await pull?() }        // Rows end at the status bar rather than sliding under the clock (the page has no bar of its own to blur).        .clipped()        .accessibilityIdentifier(tag)    }}#endif