Cotton code
600 lines · 26.7 KB · SwiftRaw
// What the board draws above its tiles: everything the old Home showed that is// not a tool, so nothing the owner saw there is lost when the board replaces// it (rebuild note 7b95efa4, "Surfaces"; audit ws-m5b18, 1 Oct).//// Four board parts are drawn from here (design note 26203e21): the `head`// (`BoardHeadPart`), the `notices` (`BoardNotices`), and the `asked` and// `done` lists (`BoardAskedList`, `BoardDoneList`) — which are also what the// head's two tags open as sheets. `BoardSurface` draws each once, in the// board's order.//// WHAT each part draws is the board's, not this file's (pagestyles ruling 2,// 13 Oct 2026): `notices.shows` names the notices and their order// (`BoardNoticeKind`: the update, a copy arriving, an unreadable database, the// backup, what an assistant is working on, a refused read, a Mac that cannot// be reached, the project's page — and a device asking to join, which the// crate still names and this phone, with no relay to hear one, never draws); `asked.shows` and// `done.shows` name the rows and receipts the crate reads that they show, and// `place` whether each is a band on the page or the list its head tag opens.// Home's declaration is `boards/home.json`.//// The step-shaped notices wear the shared receipt face (`Faces/ReceiptFace.swift`,// carried verbatim from #1307); what each says, in its ink, is `NoticeBody`.//// Everything here DRAWS and decides nothing: the words, which notices speak,// the rows and the counts are the core's (`shell.today`'s `parts`, held by// `HomeModel`). Every item is absent when it has nothing to say — the board is// not a status page.import CottonKitimport CottonValuesimport SwiftUI/// The update slip's two sides and their words, pure so a test reads them.enum UpdateNotice {    /// Which side is behind.    public enum Kind: Equatable, Sendable {        /// This build is older than the file: update the phone.        case phone        /// The Mac's build is older than this one: update the Mac.        case mac    }    /// TestFlight's own scheme — it opens the app's page there, which is where    /// every Cotton build lives until the store listing exists.    public static let testFlightURL = "itms-beta://"    static func label(_ kind: Kind) -> String {        switch kind {        case .phone: return ShellLines.line("board", "update.label.phone")        case .mac: return ShellLines.line("board", "update.label.mac")        }    }    static func title(_ kind: Kind) -> String {        switch kind {        case .phone: return ShellLines.line("board", "update.title.phone")        case .mac: return ShellLines.line("board", "update.title.mac")        }    }    static func sentence(_ kind: Kind) -> String {        switch kind {        case .phone:            return ShellLines.line("board", "update.sentence.phone")        case .mac:            return ShellLines.line("board", "update.sentence.mac")        }    }}/// The words the board's notices add to what the old Home already said.enum BoardNoticeWords {    static var devicesLabel: String { ShellLines.line("board", "notice.devices_label") }    static var doneHeading: String { ShellLines.line("board", "notice.done_heading") }    static var projects: String { ShellLines.line("board", "notice.projects") }    static var arrange: String { ShellLines.line("board", "notice.arrange") }    static var settings: String { ShellLines.line("board", "notice.settings") }    static var openSettings: String { ShellLines.line("board", "notice.open_settings") }    static var change: String { ShellLines.line("board", "notice.change") }    /// A Done for you receipt's label: what Cotton did, and when.    static func doneLabel(_ item: DoneItem, now: Date) -> String {        let age = item.when        return age.isEmpty ? item.label : ShellLines.line("board", "notice.done_label", ["label": item.label, "age": age])    }}/// What the board's head, notices, asked and done parts draw from: Home's one/// read, the device rows, and the switcher's project — handed to/// `BoardSurface` by `HomeBoard`, so every board draws them off the same read.struct BoardHome {    let model: HomeModel    let databaseName: String?    /// The chosen project's name and slug, when the switcher names one this    /// read knows; nil for All.    let project: (name: String, slug: String)?    let now: Date    /// The project was archived from its page: the board lets go of it.    var onLeaveProject: () -> Void = {}}/// The `head` part: the database's name and the tags the part lists, each/// opening its list (`BoardAskedList`, `BoardDoneList`) as a sheet. The/// database's cap is the frame's caps arc, never the head's: no board turns/// it on.struct BoardHeadPart: View {    let context: BoardHome    let tags: [String]    /// The rows the asked tag counts and opens, and their figure.    var asked: [AskedItem] = []    var askedTotal = 0    /// The receipts the done tag counts and opens.    var done: [DoneItem] = []    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    @Environment(\.cottonCore) private var core    @Environment(\.tableDefinitions) private var definitions    @Environment(ToastCenter.self) private var toasts: ToastCenter?    /// The shown database's whole name, as on its cap.    @Environment(\.shownDatabaseName) private var shownName    @Environment(DatabasesModel.self) private var databases: DatabasesModel?    @Environment(\.theme) private var theme    @Environment(BootModel.self) private var boot: BootModel?    /// The list a head slip opened: what is asked, or what was done.    @State private var listed: Listed?    /// tray › Leave this database asked, waiting on its answer.    @State private var leaving = false    private enum Listed: String, Identifiable {        case asked, done        var id: String { rawValue }    }    private var home: HomeModel { context.model }    private var project: (name: String, slug: String)? { context.project }    private var databaseName: String? { context.databaseName }    /// Whether Home's answer is the shown database's own.    private var ownAnswer: Bool { home.answersShown(scene: scene, in: databases) }    /// The database this window shows, once the held list is read.    private var shown: HeldDatabase? {        databases.flatMap { scene?.shown(in: $0) }    }    /// Where the shown database's sync stands (`DatabaseSyncLine`); current    /// until the shown database is resolved.    private var sync: DatabaseSyncLine {        shown.flatMap { databases?.sync($0.databaseId) } ?? .current    }    var body: some View {        let name = project?.name ?? shownName ?? shown?.name ?? databaseName ?? BoardHeadWords.fallbackName        return BoardHead(                name: name,                // Nothing of a database is said until the shown one is                // resolved and Home's answer is its own (walk6 05:55Z:                // 'only you' and Personal's figures under Allotment).                who: shown?.peopleLine ?? "",                asked: !ownAnswer || asked.isEmpty ? 0 : max(askedTotal, 1),                done: ownAnswer ? done.count : 0,                // The household's Mac serves every database held at its                // address, so its name stands for each of them; a database                // joined at another person's Mac says "their Mac".                syncLine: sync.pageLine(                    mac: shown.flatMap { $0.theirs ? nil : boot?.serverName }, theirs: shown?.theirs ?? false),                syncFraction: sync.fraction,                syncRefuses: sync.refuses,                onSync: { navigator?.open(.device) },                onChange: scene.map { scene in { scene.openDatabases() } },                onAsked: { listed = .asked },                onDone: { listed = .done },                onWho: { onOpen(.members) },                menu: BoardMenu.items(                    personal: shown?.isPersonal ?? true,                    onNameAndPicture: {                        if let id = shown?.databaseId, let databases = definitions.playing(.database) {                            onOpen(.tableRecord(table: databases.id, id: id))                        }                    },                    onLeave: { leaving = true }),                showsCap: false,                tags: tags            )        .confirmDecision(            isPresented: $leaving,            title: ShellLines.line("board", "menu.leave_title", ["name": shown?.name ?? ShellLines.line("board", "menu.this_database")]),            message: BoardMenu.leaveMessage,            confirmLabel: ShellLines.line("board", "menu.leave_confirm"),            identifier: "board-leave-confirm"        ) {            Task {                _ = await DatabaseLeaving.leaveShown(                    databases: databases, scene: scene, boot: boot, navigator: navigator, toasts: toasts)            }        }        .cottonCard(            isPresented: Binding(get: { listed != nil }, set: { if !$0 { listed = nil } }),            detents: [.half, .tall]        ) {            ScrollView {                VStack(alignment: .leading, spacing: BoardNoticesKnobs.boardNoticeStackGap) {                    switch listed {                    case .asked: BoardAskedList(home: home, items: asked) { listed = nil }                    case .done: BoardDoneList(home: home, now: context.now, items: done) { listed = nil }                    case nil: EmptyView()                    }                }                .frame(maxWidth: .infinity, alignment: .leading)                .padding(ChromeKnobs.chromeSettingsMargin)            }        }        // The asked list closes with its last card: an Admit held on it        // answers the last ask and nothing is left to hold the sheet open        // (coordinator, 16 Oct 2026: it stood open and empty for seconds).        .onChange(of: listed == .asked && asked.isEmpty) { _, answeredAll in            if answeredAll { listed = nil }        }    }    /// A tap opens through the navigator's one door: the phone's host pushes,    /// the Mac's opens the window the route names.    private func onOpen(_ route: Route) {        listed = nil        navigator?.open(route)    }}/// stack button on a database's Home (owner, 11 Oct 2026): exactly "Name and picture"/// and "Leave this database" — the personal database, which is the person and/// cannot be left, has only the first. "This database", "You" and "This phone"/// left it: the person is the Me card, the device is reached from Devices, its/// sync line and Me's Devices, and members and the tools' arrangement are/// cards of their own.enum BoardMenu {    static var nameAndPicture: String { ShellLines.line("board", "menu.name_and_picture") }    static var leave: String { ShellLines.line("board", "menu.leave") }    static var leaveMessage: String { ShellLines.line("board", "menu.leave_message", ["host": HostNoun.titleCase]) }    static func items(personal: Bool, onNameAndPicture: @escaping () -> Void, onLeave: @escaping () -> Void) -> [PopoverMenuItem] {        var items = [PopoverMenuItem(id: "board-name-and-picture", label: nameAndPicture, action: onNameAndPicture)]        if !personal {            items.append(PopoverMenuItem(id: "board-leave", label: leave, destructive: true, action: onLeave))        }        return items    }}/// The `notices` part: what the old Home said above its tiles that is not the/// head — the update, what the assistant is working on, a failed read of what/// is asked, a Mac that cannot be reached, and the/// chosen project's own page. Absent, every one, when it has nothing to say.struct BoardNotices: View {    @Environment(\.theme) private var theme    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    let context: BoardHome    @Environment(\.cottonSync) private var sync    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(\.tableDefinitions) private var definitions    private var home: HomeModel { context.model }    private var now: Date { context.now }    /// The board's `notices` part, as the core answered it.    let entry: BoardEntry    /// The notices the part names, in its order.    private var shows: [BoardNoticeKind] { entry.settings.strings("shows").compactMap(BoardNoticeKind.init(rawValue:)) }    /// The backup receipt's words, the part's own (`notices.backup_*`).    private var backupWords: BackupWords {        BackupWords(behind: entry.settings.text("backup_behind") ?? "", unset: entry.settings.text("backup_unset") ?? "", open: entry.settings.text("backup_open") ?? "")    }    private func said(_ id: String) -> TodayAnswer.Notice? { entry.notices.first { $0.id == id } }    /// Whether the part says something only this window holds: the serving    /// Mac's backup is the board's own round trip, and the project the    /// switcher's. The core answers every other notice (`entry.shown`).    @MainActor    static func saysOwn(_ context: BoardHome, in entry: BoardEntry) -> Bool {        entry.settings.strings("shows").contains { word in            switch BoardNoticeKind(rawValue: word) {            case .backup: return context.model.backupNotice != nil            case .project: return context.project != nil            default: return false            }        }    }    /// The shown database's sync page — every device's copy of it.    private func openSync() {        var filter: [String: RecordValue] = [:]        if let shown = scene?.shownId { filter["database"] = .text(shown) }        navigator?.open(FilteredListOpening(table: HomeSync.table, filter: filter, title: "").route)    }    var body: some View {        VStack(alignment: .leading, spacing: BoardNoticesKnobs.boardNoticeStackGap) {            ForEach(shows, id: \.self) { kind in notice(kind) }        }    }    /// One notice, drawn once; nothing when it has nothing to say.    @ViewBuilder private func notice(_ kind: BoardNoticeKind) -> some View {        switch kind {        case .update:            if let side = said("update")?.side { UpdateReceipt(kind: side == "mac" ? .mac : .phone) }        case .arriving:            // Its chevron opens the database's sync page: where its copy stands.            if let line = said("arriving")?.words {                PencilLine(text: line, identifier: "board-arriving") { openSync() }            }        case .unreadable:            ForEach(entry.notices.filter { $0.id.hasPrefix("unreadable/") }, id: \.id) { line in                QuietState(title: line.words, message: "")            }        case .backup:            if let notice = home.backupNotice {                BackupReceipt(notice: notice, words: backupWords) { navigator?.open(.devicesId(id: notice.deviceId)) }            }        case .joinRequests:            EmptyView()        case .workingOn:            if let line = said("workingOn")?.words {                PencilLine(text: line, identifier: "board-working-on") { navigator?.open(.activity) }            }        case .readRefusal:            if let line = said("readRefusal")?.words {                // The core's line, never the error's words; a read the core                // cut has no Try again — the core asks again by itself — and                // any other failure offers it.                if home.answer?.failed?.keeps_trying ?? true {                    QuietState(title: line, message: "")                } else {                    QuietState(title: line, message: "", actionLabel: CottonStrings.tryAgain, action: { Task { await home.load() } })                }            }        case .attention:            // A device that is not syncing is one pencilled line.            if let line = said("attention")?.words {                PencilLine(text: line, amber: true, identifier: "board-attention") {                    navigator?.open(.device)                }            }        case .project:            // The database page IS the project's page: its description, its            // conversation and its sections, under the head.            if let project = context.project {                ProjectOnBoard(slug: project.slug, onLeave: context.onLeaveProject)                    // Two section columns wide at most: in a wide window the                    // description keeps its stack button beside it and the project's                    // slips are not stretched across the tool sections' columns.                    .frame(maxWidth: BoardNoticesKnobs.boardProjectMeasure, alignment: .leading)            }        }    }}/// Asked of you: the `asked` part, and the list the head's asked tag opens —/// one view in both places.struct BoardAskedList: View {    let home: HomeModel    /// The rows the board's `asked` part shows.    var items: [AskedItem] = []    /// Something was opened from the list: the head's sheet lets go.    var onOpened: () -> Void = {}    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(DatabasesModel.self) private var databases: DatabasesModel?    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(\.tableDefinitions) private var definitions    var body: some View {        AskedBand(            items: items,            onOpen: open,            onAnswered: { Task { await home.refresh() } }        )    }    /// Every path a notice hands out came from the crate's read; an    /// unparseable one is a no-op, as it always was on Home. A tap opens    /// through the navigator's one door.    private func open(_ path: String) {        guard let route = Route.parse(path) else { return }        onOpened()        navigator?.open(route)    }}/// Done for you: the `done` part, and the list the head's done tag opens —/// one view in both places. A receipt per act, newest first, each with its/// one verb. The receipt's words open what it is about, and Undo (or Change)/// sits BESIDE them, never inside: a button in a button is a tap nobody can/// aim, as the old Done band had it.struct BoardDoneList: View {    @Environment(\.theme) private var theme    let home: HomeModel    let now: Date    /// The receipts the board's `done` part shows.    var items: [DoneItem] = []    /// Something was opened from the list: the head's sheet lets go.    var onOpened: () -> Void = {}    @Environment(Navigator.self) private var navigator: Navigator?    var body: some View {        VStack(alignment: .leading, spacing: BoardNoticesKnobs.boardNoticeSmallGap) {            PaperSection(title: BoardNoticeWords.doneHeading)            ForEach(items) { item in                ReceiptFace(                    label: BoardNoticeWords.doneLabel(item, now: now).uppercased(),                    seed: "receipt-done-\(item.id)"                ) {                    HStack(alignment: .center, spacing: BoardNoticesKnobs.boardNoticeRowGap) {                        Button { open(item.path) } label: {                            NoticeBody(title: item.text) { EmptyView() }                                .contentShape(Rectangle())                        }                        .buttonStyle(.plain)                        .accessibilityLabel("\(item.label): \(item.text)")                        .accessibilityIdentifier("board-done-\(item.id)")                        switch item.action {                        case .undo:                            PaperTypedButton(CottonStrings.undo, size: BoardNoticesKnobs.boardNoticeButtonSize) { Task { await home.undo(item) } }                                .disabled(home.undoing.contains(item.id))                                .accessibilityIdentifier("board-done-undo-\(item.id)")                        case .change:                            PaperTypedButton(BoardNoticeWords.change, size: BoardNoticesKnobs.boardNoticeButtonSize) { open(item.path) }                                .accessibilityIdentifier("board-done-change-\(item.id)")                        case .open:                            // The receipt's own words open it; there is no verb beside them.                            EmptyView()                        }                    }                }                // A container, never a named element: an identifier on a view                // that is not itself one is handed down and beats its children's.                .accessibilityElement(children: .contain)                .modifier(UnreadUnderTheFan())            }        }    }    /// Every path a notice hands out came from the crate's read; an    /// unparseable one is a no-op, as it always was on Home. A tap opens    /// through the navigator's one door.    private func open(_ path: String) {        guard let route = Route.parse(path) else { return }        onOpened()        navigator?.open(route)    }}/// One pencilled line with a chevron: the working-on and the sync lines.struct PencilLine: View {    @Environment(\.theme) private var theme    let text: String    var amber = false    let identifier: String    let action: () -> Void    var body: some View {        Button(action: action) {            HStack(spacing: BoardNoticesKnobs.boardNoticeIconTextGap) {                Text(text)                    .paperHand(theme.scale.handSize + 3)                    .foregroundStyle(amber ? CottonColors.statusWarning : theme.print(.pencil))                    .lineLimit(BoardNoticesKnobs.boardNoticePencilMaxLines)                Image(systemName: "chevron.right")                    .font(CottonFonts.symbol(BoardNoticesKnobs.boardNoticeLabelSize, weight: .medium))                    .foregroundStyle(theme.print(.pencil))                Spacer(minLength: 0)            }            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityIdentifier(identifier)    }}/// The update slip as a receipt. The phone can open its own update; the Mac's/// is on the Mac.private struct UpdateReceipt: View {    @Environment(\.theme) private var theme    let kind: UpdateNotice.Kind    @Environment(\.openURL) private var openURL    var body: some View {        ReceiptFace(label: UpdateNotice.label(kind).uppercased(), seed: "receipt-update-required") {            NoticeBody(title: UpdateNotice.title(kind), explanation: UpdateNotice.sentence(kind), ink: .red) {            if kind == .phone {                PaperTypedButton(ShellLines.line("board", "update.open_testflight"), size: BoardNoticesKnobs.boardNoticeButtonSize) {                    guard let url = URL(string: UpdateNotice.testFlightURL) else { return }                    openURL(url)                }                .padding(.top, BoardNoticesKnobs.boardNoticeTopPadding)                .accessibilityIdentifier("update-required-open")            }            }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("update-required-banner")    }}/// The serving Mac's backup that is not getting through, as a receipt in red/// ink: how far behind it is in the person's words, and the Mac's page (where/// the Mac's own reason and Back up now are) one tap away. One per Mac/// (`BackupNotice`).private struct BackupReceipt: View {    @Environment(\.theme) private var theme    let notice: BackupNotice    let words: BackupWords    let onOpen: () -> Void    var body: some View {        ReceiptFace(label: BackupNoticeWords.label.uppercased(), seed: "receipt-backup-\(notice.deviceId)") {            NoticeBody(explanation: notice.line, ink: .red) {                PaperTypedButton(words.open, size: BoardNoticesKnobs.boardNoticeButtonSize, action: onOpen)                    .padding(.top, BoardNoticesKnobs.boardNoticeSecondaryTopPadding)                    .accessibilityIdentifier("board-backup-open")            }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("board-backup")    }}/// The ink a notice's explanation is written in. Ink is STATE, never a tint:/// red for a stop (the update slip was always red ink), amber for attention/// that is not an error (a Mac asleep on a desk), pencil otherwise. It goes in/// what the board puts inside the shared `ReceiptFace`, never into the face.enum NoticeInk {    case pencil, amber, red}/// What the board puts inside a receipt: the handwritten title, the plain/// explanation in its ink, and the step's own verbs under them.private struct NoticeBody<Actions: View>: View {    @Environment(\.theme) private var theme    private let title: String?    private let explanation: String?    private let ink: NoticeInk    private let actions: Actions    init(title: String? = nil, explanation: String? = nil, ink: NoticeInk = .pencil, @ViewBuilder actions: () -> Actions) {        self.title = title        self.explanation = explanation        self.ink = ink        self.actions = actions()    }    var body: some View {        VStack(alignment: .leading, spacing: BoardNoticesKnobs.boardNoticeBodyGap) {            if let title, !title.isEmpty {                Text(title)                    .paperHand(theme.scale.handSize + 4, ink: .ink)                    .fixedSize(horizontal: false, vertical: true)            }            if let explanation, !explanation.isEmpty {                Group {                    switch ink {                    case .red: Text(explanation).paperRed(theme.scale.handSize - 1)                    case .amber:                        Text(explanation).paperBody(theme.scale.bodySize - 1)                            .foregroundStyle(CottonColors.statusWarning)                    case .pencil: Text(explanation).paperBody(theme.scale.bodySize - 1, ink: .pencil)                    }                }                .lineSpacing(BoardNoticesKnobs.boardNoticeLineSpacing)                .fixedSize(horizontal: false, vertical: true)            }            actions        }        .frame(maxWidth: .infinity, alignment: .leading)        .accessibilityElement(children: .contain)    }}/// The sizes, counts and timings BoardNotices draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum BoardNoticesKnobs {    static let boardNoticeBodyGap: CGFloat = 12    static let boardNoticeButtonSize: CGFloat = 15    static let boardNoticeIconTextGap: CGFloat = 6    static let boardNoticeLabelSize: CGFloat = 11    static let boardNoticeLineSpacing: CGFloat = 3    static let boardNoticePencilMaxLines = 2    static let boardNoticeRowGap: CGFloat = 14    static let boardNoticeSecondaryTopPadding: CGFloat = 4    static let boardNoticeSmallGap: CGFloat = 10    static let boardNoticeStackGap: CGFloat = 16    static let boardNoticeTertiaryTopPadding: CGFloat = 6    static let boardNoticeTopPadding: CGFloat = 10    static let boardProjectMeasure: CGFloat = 668}