Cotton code
364 lines · 17.6 KB · SwiftRaw
// COTTON POST'S ROOT (assets/design/mail/DECISIONS.md "Structure", mail.html; CONTRACT.md): four places as text tabs at// the foot, Mail, Senders, Files and You, the same for every account, each its own stack. The side page slides in from// the left over Mail and PUSHES the inbox right, never covering it, at four fifths of the width (380 points at most),// with Words' spring (NotesDrawer). The writer, Search, an attachment and a link rise over the whole app. Every screen// stands in the Stamp look (`PostLook.swift`); nothing from Comms' mail screens, the fan or the shared boards. The core// decides every word and act (`mail.*`, `look`, the `post` line set); this file only places them.#if os(iOS)import CottonKitimport SwiftUIstruct PostRoot: View {    /// Whether this app is Cotton Post (registry slug `mail`).    static var applies: Bool { FlavourManifest.current?.flavour == "mail" }    @State private var model: PostModel    @State private var look = LookModel.standing("mail")    @Environment(\.cottonSync) private var sync    @Environment(\.scenePhase) private var phase    @State private var keyboardUp = false    @Environment(\.accessibilityReduceMotion) private var reduceMotion    init(core: any CottonCalling) {        PostFonts.register()        _model = State(initialValue: PostModel(core: core))    }    var body: some View {        ZStack(alignment: .leading) {            PostInk.ground.ignoresSafeArea()            places                .accessibilityHidden(model.sideOpen || model.drawer.visible)                .overlay { if model.sideOpen || model.drawer.visible { PostSideEdge(model: model) } }                .offset(x: model.drawer.shown * model.drawer.width)            if model.sideOpen || model.drawer.visible {                PostSidePage(model: model)                    .frame(width: model.drawer.width)                    .frame(maxHeight: .infinity)                    .offset(x: (model.drawer.shown - 1) * model.drawer.width)            }        }        .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { model.drawer.width = NotesDrawer.width(across: $0) }        .onChange(of: reduceMotion, initial: true) { _, now in model.drawer.reduceMotion = now }        .fullScreenCover(item: $model.sheet) { sheet in            sheetPage(sheet)                .background(PostInk.ground.ignoresSafeArea())                .lookStanding(look)        }        .lookStanding(look)        .task {            await look.read(model.core)            FanLaunch.firstContent()            #if COTTON_DEV            await PostDevOpen.run(model)            #endif            await model.fetchHere()        }        // Another device, the Mac's reader or an assistant wrote: read again.        .onChange(of: sync?.foreignRevision) { _, _ in model.changed() }        // A Post notification tapped: its conversation, over Mail.        .onReceive(NotificationCenter.default.publisher(for: PostRings.opened)) { _ in openRung() }        .task { openRung() }        // The side page's rows held from launch, so the menu opens onto them at once.        .task { await model.readSide() }        // Another Cotton app handing over (`cottonmail://open?from=comms`, You's Mail row in Comms): Post opens on Mail's        // first screen, the side page closed (COMMS WITHOUT MAIL).        .onOpenURL { link in            guard URLComponents(url: link, resolvingAgainstBaseURL: false)?.host == "open" else { return }            model.sideOpen = false            model.paths[.mail] = []            model.tab = .mail        }        // The home's sync line was tapped: You.        .onReceive(NotificationCenter.default.publisher(for: SyncSeenOpens.notice)) { _ in model.tab = .you }        .onChange(of: phase) { _, now in            guard now == .active else { return }            model.changed()            Task { await model.fetchHere() }        }        .accessibilityIdentifier("post-root")    }    /// A tapped Post notification's conversation, opened over Mail (once).    private func openRung() {        guard let thread = PostRings.take() else { return }        model.sheet = nil        model.sideOpen = false        model.tab = .mail        model.paths[.mail] = [.thread(thread)]    }    /// The four places, each its own stack, and the tabs under them.    private var places: some View {        VStack(spacing: 0) {            ZStack {                ForEach(PostTab.allCases, id: \.self) { tab in                    stack(tab)                        .opacity(model.tab == tab ? 1 : 0)                        .allowsHitTesting(model.tab == tab)                        .accessibilityHidden(model.tab != tab)                }            }            // The tabs stop growing at a large ordinary size, as the system's own do; a long press shows them large.            // While the keyboard is up the tabs step aside, as the system's do, so they never ride over the keys            // (the walk, 26 Nov 2026: adding an account).            if !keyboardUp { PostTabs(model: model).dynamicTypeSize(...DynamicTypeSize.xxLarge) }        }        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in keyboardUp = true }        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in keyboardUp = false }        .background(PostInk.ground.ignoresSafeArea())        // The status bar stands on the paper, so a list scrolled up never runs under the clock.        .overlay(alignment: .top) { PostInk.ground.frame(height: 0).ignoresSafeArea(edges: .top) }    }    private func stack(_ tab: PostTab) -> some View {        ZStack {            root(tab).accessibilityHidden(!(model.paths[tab] ?? []).isEmpty)            ForEach(Array((model.paths[tab] ?? []).enumerated()), id: \.offset) { index, route in                destination(route)                    .background(PostInk.ground.ignoresSafeArea())                    .accessibilityHidden(index < (model.paths[tab]?.count ?? 0) - 1)                    .transition(.move(edge: .trailing))                    .gesture(DragGesture(minimumDistance: 24).onEnded { drag in                        if drag.startLocation.x < 28, drag.translation.width > 80 { model.pop() }                    })            }        }        .animation(.easeOut(duration: 0.25), value: model.paths[tab] ?? [])    }    @ViewBuilder private func root(_ tab: PostTab) -> some View {        switch tab {        case .mail: PostHomeScreen(model: model)        case .senders: PostSendersScreen(model: model)        case .files: PostFilesScreen(model: model)        case .you: PostYouScreen(model: model)        }    }    @ViewBuilder private func destination(_ route: PostRoute) -> some View {        switch route {        case .list(let place): PostListScreen(model: model, place: place)        case .thread(let thread): PostThreadScreen(model: model, thread: thread)        case .sender(let key): PostSenderScreen(model: model, key: key)        case .blocked: PostBlockedScreen(model: model)        case .look: PostLookPage(model: model)        case .accounts: PostAccountsScreen(model: model)        case .accountAdd(let kind): PostAccountAddScreen(model: model, kind: kind)        case .account(let id): PostAccountScreen(model: model, id: id)        case .domains: PostDomainsScreen(model: model)        case .domain(let domain): PostDomainScreen(model: model, domain: domain)        case .rules: PostRulesScreen(model: model)        case .privacy(let title): PostPrivacyScreen(model: model, title: title)        case .shared(let page, let title): PostSharedScreen(model: model, page: page, title: title)        }    }    @ViewBuilder private func sheetPage(_ sheet: PostSheet) -> some View {        switch sheet {        case .write(let mode, let thread, let email, let draft): PostWritePage(model: model, mode: mode, thread: thread, email: email, draft: draft)        case .search: PostSearchPage(model: model)        case .file(let path, let name, let back): PostFilePage(model: model, path: path, name: name, back: back)        case .reader(let url, let back): PostReaderPage(model: model, url: url, back: back)        }    }}/// `.tabs`: the four places in words at the foot, the one standing in bold ink with a short rule under it. A tap on/// the place standing goes back to its first screen.struct PostTabs: View {    let model: PostModel    /// The tabs' words grow with the phone's text only as far as the cap below, as the system's own tabs do.    @ScaledMetric(relativeTo: .subheadline) private var size: CGFloat = 15    var body: some View {        VStack(spacing: 0) {            PostRule()            HStack(spacing: 0) {                ForEach(PostTab.allCases, id: \.self) { tab in                    let on = model.tab == tab                    Button {                        if on { model.paths[tab] = [] } else { model.tab = tab }                    } label: {                        VStack(spacing: 3) {                            Text(PostWords.line("tab.\(tab.rawValue)"))                                .font(Font(PostFonts.ui(.sans, size * PostInk.look.scale, weight: on ? 700 : 400)))                                .foregroundStyle(on ? PostInk.ink : PostInk.quiet)                                .lineLimit(1)                                .minimumScaleFactor(0.6)                            Capsule().fill(on ? PostInk.ink : .clear).frame(width: 18, height: 2)                        }                        .padding(.horizontal, 8)                        .padding(.top, 12)                        .padding(.bottom, 4)                        .frame(maxWidth: .infinity, minHeight: 48)                        .contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityAddTraits(on ? [.isSelected, .isButton] : .isButton)                    .accessibilityIdentifier("post-tab-\(tab.rawValue)")                }            }        }        // The tabs stop growing at the largest ordinary size, as the system's own do; a long press shows them large.        .dynamicTypeSize(...DynamicTypeSize.xxLarge)        .accessibilityShowsLargeContentViewer()        .background(PostInk.ground.ignoresSafeArea(edges: .bottom))    }}/// The inbox's edge while the side page stands open: a tap closes the page, a drag moves it with the finger.struct PostSideEdge: View {    let model: PostModel    @State private var holding = false    var body: some View {        Color.black.opacity(0.06 * model.drawer.shown)            .contentShape(Rectangle())            .gesture(                DragGesture(minimumDistance: 0, coordinateSpace: .global)                    .onChanged { drag in                        if !holding {                            holding = true                            model.drawer.grab()                        }                        model.drawer.follow(drag.translation.width)                    }                    .onEnded { drag in                        holding = false                        let moved = hypot(drag.translation.width, drag.translation.height)                        model.letGoOfSide(moved < 10 ? nil : drag.velocity.width)                    }            )            .ignoresSafeArea()            .accessibilityElement()            .accessibilityLabel(Text(PostWords.line("side.close")))            .accessibilityAddTraits(.isButton)            .accessibilityAction { model.sideOpen = false }            .accessibilityIdentifier("post-side-edge")    }}/// THE SIDE PAGE: the stamp and Post's name; Inboxes (All inboxes, then each account); Places (Drafts, Sent, Archived,/// Bin); Gmail's labels. A tap narrows Mail or opens the place and closes the page; a swipe to the left closes it.struct PostSidePage: View {    let model: PostModel    @State private var holding = false    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                HStack(spacing: 10) {                    PostStampMark(size: 34)                    Text(PostWords.line("app_name")).font(PostType.sans(22, .bold, relativeTo: .title2)).foregroundStyle(PostInk.ink)                }                .padding(.top, 14)                .accessibilityElement(children: .combine)                switch model.side {                case .read(let side)?:                    band(side.inboxes) { row in                        let chosen = row.id == "all" ? model.account == nil : model.account == row.title.lowercased()                        return (chosen, { model.chooseSide(inbox: row.id, title: row.title) })                    }                    band(side.places, icons: true) { row in (false, { model.chooseSide(place: row.id) }) }                    if let labels = side.labels {                        band(labels, label: true) { row in (false, { model.chooseSide(place: row.id) }) }                    }                case .refused(let line)?: PostRefused(line: line)                case nil: EmptyView()                }            }            .padding(.horizontal, PostInk.side)            .padding(.bottom, 30)        }        .background(PostInk.ground.ignoresSafeArea())        .overlay(alignment: .trailing) { Rectangle().fill(PostInk.rule).frame(width: 1).ignoresSafeArea() }        .gesture(DragGesture(minimumDistance: 18, coordinateSpace: .global)            .onChanged { drag in                guard drag.translation.width < 0 else { return }                if !holding {                    holding = true                    model.drawer.grab()                }                model.drawer.follow(drag.translation.width)            }            .onEnded { drag in                guard holding else { return }                holding = false                model.letGoOfSide(drag.velocity.width)            })        // The rows stand from the model's last answer; this fills the counts in behind them.        .task(id: model.generation) { await model.readSide() }        .accessibilityIdentifier("post-side")    }    private func band(_ band: PostSide.Band, icons: Bool = false, label: Bool = false, act: @escaping (PostSide.Row) -> (Bool, () -> Void)) -> some View {        VStack(alignment: .leading, spacing: 0) {            PostSection(title: band.title)            ForEach(Array(band.rows.enumerated()), id: \.element.id) { index, row in                let (chosen, tap) = act(row)                Button(action: tap) {                    HStack(spacing: 12) {                        if icons || label {                            Image(systemName: label ? "tag" : Self.icon(row.id)).font(.system(size: 15, weight: .light)).foregroundStyle(PostInk.ink).frame(width: 22)                        }                        VStack(alignment: .leading, spacing: 1) {                            Text(row.title).font(PostType.sans(16.5, chosen ? .bold : .medium)).foregroundStyle(PostInk.ink).lineLimit(2)                            if let tag = row.tag { Text(tag).font(PostType.small).foregroundStyle(PostInk.quiet) }                        }                        Spacer(minLength: 6)                        if let count = row.count { Text(count.formatted()).font(PostType.end).foregroundStyle(PostInk.quiet) }                    }                    .padding(.vertical, 11)                    .contentShape(Rectangle())                    .overlay(alignment: .leading) { if chosen { Rectangle().fill(PostInk.ink).frame(width: 3).offset(x: -PostInk.side) } }                    .overlay(alignment: .bottom) { if index < band.rows.count - 1 { PostRule() } }                }                .buttonStyle(PostPressStyle())                .accessibilityAddTraits(chosen ? [.isButton, .isSelected] : .isButton)                .accessibilityIdentifier("post-side-\(row.id)")            }        }    }    private static func icon(_ place: String) -> String {        switch place {        case "drafts": "square.and.pencil"        case "sent": "paperplane"        case "archived": "archivebox"        case "bin": "trash"        default: "tray"        }    }}/// The Stamp: the icon's own mark (scripts/draw-app-icons.mjs `STAMP_EDGE`), a postage stamp 38 by 46 in a box of 64,/// six perforations across and seven down bitten out of its edge, its inner frame cut in the paper's colour; in the/// accent, so it follows the ink Look chose.struct PostStampMark: View {    var size: CGFloat = 26    var body: some View {        Canvas { context, box in            let k = box.width / 64            // The stamp with its perforations as holes (even-odd), kept inside its own edge: nothing is cleared, so            // nothing drawn beside it can be.            let edge = CGRect(x: 13 * k, y: 9 * k, width: 38 * k, height: 46 * k)            var stamp = Path(edge)            let r = 2.4 * k            for x in [17.2, 23.12, 29.04, 34.96, 40.88, 46.8] {                for y in [9.0, 55.0] { stamp.addEllipse(in: CGRect(x: x * k - r, y: y * k - r, width: 2 * r, height: 2 * r)) }            }            for y in [13.2, 19.47, 25.73, 32.0, 38.27, 44.53, 50.8] {                for x in [13.0, 51.0] { stamp.addEllipse(in: CGRect(x: x * k - r, y: y * k - r, width: 2 * r, height: 2 * r)) }            }            context.clip(to: Path(edge))            context.fill(stamp, with: .color(PostInk.accent), style: FillStyle(eoFill: true))            context.stroke(Path(roundedRect: CGRect(x: 18.5 * k, y: 14.5 * k, width: 27 * k, height: 35 * k), cornerRadius: k),                           with: .color(PostInk.ground), lineWidth: 1.8 * k)        }        .frame(width: size, height: size)        .accessibilityHidden(true)    }}#endif