Cotton code
340 lines · 16.1 KB · SwiftRaw
// The Databases screen, from the centre cap — and the two screens its "+"// opens (UI direction 3 Oct 2026, Cotton note 0a22168c §5–6, and its mock).//// A grid of caps, each with who is in it underneath, and one bare "+" cap,// "new or join". Nothing else on it: no links, no sentence. Tapping a cap// shows that database in THIS window and closes the screen.//// "+" opens "What is it for?": the eight toolkit cards. A card opens ONE// screen to name the database, and Create makes it, shows it and closes// everything. Never a longer wizard.//// One screen for both platforms: the Mac raises the same sheet from its cap.import CottonKitimport SwiftUIstruct DatabasesScreen: View {    let model: DatabasesModel    let scene: DatabaseScene    @State private var path: [Step] = []    @Environment(\.cottonCapabilities) private var capabilities    @Environment(\.openURL) private var openURL    @Environment(\.tableDefinitions) private var definitions    /// Local Network is off for Cotton — the one line that sends the person    /// to the switch (`findYourMac`).    @State private var macOnThisNetworkIsOff = false    enum Step: Hashable {        case toolkits        case name(DatabaseToolkit)    }    init(model: DatabasesModel, scene: DatabaseScene) {        self.model = model        self.scene = scene    }    var body: some View {        NavigationStack(path: $path) {            grid                .cottonScreenFrame()                // Which build this is and which Mac it last heard from.                .safeAreaInset(edge: .bottom, spacing: 0) {                    BuildLineView(databasesListed: "\(model.held.count) / \(model.held.count + model.elsewhere.count)")                }                .navigationDestination(for: Step.self) { step in                    // A step pushed on the card steps back, never closes it.                    Group {                        switch step {                        case .toolkits:                            ToolkitsScreen(model: model, go: { path.append($0) }, cancel: { scene.choosing = false })                                .cottonScreenFrame()                        case .name(let toolkit):                            NameDatabaseScreen(model: model, scene: scene, toolkit: toolkit)                                .cottonScreenFrame()                        }                    }                    .environment(\.closeCard, nil)                }        }        // The root's back circle closes the card: nothing is under it.        .environment(\.cottonAtColumnRoot, false)        .task(id: path.isEmpty) {            guard path.isEmpty else { return }            await model.refresh()            await model.refreshPeople()            await model.refreshClaims()        }        // DECLINED, as far as anyone remembers: read where it stands NOW — a        // decided permission is never prompted again, and the person may have        // switched it on since. Never raised from here: this sheet asks for        // nothing the person did not start.        .task {            guard await capabilities.status(.localNetwork) == .denied else { return }            macOnThisNetworkIsOff = await capabilities.ask(.localNetwork) == .denied        }    }    /// Local Network was declined, so everything this phone sends goes the    /// long way through the relay. One line, and it opens the switch.    private var findYourMac: some View {        PaperTypedButton(ShellLines.line("databases", "find_your_mac_on")) {            if let settings = CapabilityRefusal.settingsURL { openURL(settings) }        }        .accessibilityIdentifier("databases-find-your-mac")    }    private var grid: some View {        PaperScreen(title: ShellLines.line("databases", "databases"), showsBack: false) {            VStack(alignment: .leading, spacing: 24) {                if let refusal = model.readRefusal {                    Text(refusal).paperBody(ink: .red).accessibilityIdentifier("databases-read-error")                    PaperTypedButton(CottonStrings.tryAgain) { Task { await model.refresh() } }                }                if macOnThisNetworkIsOff { findYourMac }                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 3), spacing: 18) {                    ForEach(model.ordered) { database in                        Button {                            Task { await scene.pick(database.databaseId, in: model) }                        } label: {                            // THE CAP ITSELF SAYS WHERE ITS COPY STANDS: it                            // turns while rows or bytes move, and the ONE line                            // under it says how far ("9 of 11 MB", "syncing ·                            // 62%") or, with nothing to say, who is in it.                            capCell(model.capLine(database), ink: model.capRefuses(database) ? .red : .pencil) {                                DatabaseCap(                                    name: model.capName(database),                                    colour: model.colours[database.databaseId] ?? .cream,                                    side: Self.capSide,                                    turning: model.turns(database)                                )                            }                        }                        .buttonStyle(OpacityButtonStyle(pressed: 0.7))                        .accessibilityLabel("\(model.capName(database)), \(database.peopleLine)")                        .accessibilityIdentifier("database-\(database.databaseId)")                        // A long press opens the database's own page (Spec 10.2).                        .contextMenu {                            Button(ShellLines.line("databases", "open_its_page")) {                                scene.pageAsked = .database                                Task { await scene.pick(database.databaseId, in: model) }                            }                            // Every device's copy of it, how far behind each is.                            if let copies = definitions.playing(.copies) { Button(ShellLines.line("databases", "open_sync")) {                                scene.pageAsked = FilteredListOpening(                                    table: copies.id, filter: ["database": .text(database.databaseId)], title: "").route                                Task { await scene.pick(database.databaseId, in: model) }                            } }                        }                        .accessibilityAddTraits(database.databaseId == scene.shownId ? .isSelected : [])                    }                    // What the person joined on another device and this one                    // does not hold: one cap each, fetched here on a tap.                    ForEach(model.elsewhere) { place in                        Button {                            Task {                                guard let fetched = await model.present(place) else { return }                                await scene.pick(fetched.databaseId, in: model)                            }                        } label: {                            capCell(model.presenting == place.databaseId ? ShellLines.line("databases", "getting_it") : ElsewhereDatabase.capLine, lines: 4) {                                ProjectCap(name: place.name, colour: .cream, side: Self.capSide)                                    .opacity(0.6)                            }                        }                        .buttonStyle(OpacityButtonStyle(pressed: 0.7))                        .disabled(model.presenting != nil)                        .accessibilityLabel([place.name, model.presenting == place.databaseId ? ShellLines.line("databases", "getting_it") : ElsewhereDatabase.capLine].joined(separator: ", "))                        .accessibilityIdentifier("elsewhere-\(place.databaseId)")                    }                    Button {                        path.append(.toolkits)                    } label: {                        capCell(ShellLines.line("databases", "new_or_join")) { EmptyCap(side: Self.capSide) }                    }                    .buttonStyle(OpacityButtonStyle(pressed: 0.7))                    .accessibilityLabel(ShellLines.line("databases", "new_or_join_a"))                }                ForEach(model.claims) { claim in                    ClaimCard(claim: claim, database: model.database(claim.databaseId)?.name) { admit in                        Task { await model.decide(claim, admit: admit) }                    }                }                if let refusal = model.membersRefusal {                    Text(refusal).paperBody(ink: .red).accessibilityIdentifier("databases-read-error")                }                PaperTypedButton("Close") { scene.choosing = false }                    .frame(maxWidth: .infinity)            }        }        .refreshable {            await model.refresh()            await model.refreshPeople()            await model.refreshClaims()        }    }    /// A cap and its line. The line sits close under the cap, like a    /// caption, and is ONE line high whatever it says — the people line, a    /// percent, "offline" — so nothing on the sheet moves when it changes    /// (sync programme, lane A). Only a cap this device does not hold yet    /// asks for more lines, and its words never change.    private func capCell(        _ caption: String, lines: Int = 1, ink: PaperInk = .pencil, @ViewBuilder cap: () -> some View    ) -> some View {        VStack(spacing: Self.captionGap) {            CapBoard.shadow(cap())            Text(caption)                .paperHand(16, ink: ink)                .multilineTextAlignment(.center)                .lineLimit(lines)        }        .frame(maxWidth: .infinity)        .contentShape(Rectangle())    }    static let capSide: CGFloat = 92    /// Between a cap and the line under it.    static let captionGap: CGFloat = 2}/// "What is it for?": the toolkit cards.private struct ToolkitsScreen: View {    let model: DatabasesModel    let go: (DatabasesScreen.Step) -> Void    let cancel: () -> Void    var body: some View {        PaperScreen(title: ShellLines.line("databases", "what_is_it_for")) {            VStack(alignment: .leading, spacing: 24) {                Text(ShellLines.line("databases", "choose_the_tools_it")).paperHand(15)                if let refusal = model.toolkitsRefusal {                    Text(refusal).paperBody(ink: .red)                    PaperTypedButton(ShellLines.line("databases", "try_again")) { Task { await model.loadToolkits() } }                }                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 12), count: 4), spacing: 14) {                    ForEach(model.toolkits) { toolkit in                        Button {                            go(.name(toolkit))                        } label: {                            ToolCard(key: Self.stock[toolkit.id] ?? "notes", name: toolkit.name, asset: "toolkit-\(toolkit.id)")                        }                        .buttonStyle(OpacityButtonStyle(pressed: 0.7))                    }                }                Text(ShellLines.line("databases", "you_can_add_hide")).paperHand(15)                PaperTypedButton("Cancel", action: cancel)                    .frame(maxWidth: .infinity)            }        }        .task { await model.loadToolkits() }    }    /// Which paper each toolkit's card is printed on, named by the tool whose    /// stock it shares (`ToolCardTint.byTool`) — the people's rose for the    /// ones made for people, the sage of time for classes and lessons.    private static let stock: [String: String] = [        "family": "people",        "partner": "people",        "friends": "people",        "tech-team": "code",        "yoga-studio": "calendar",        "yoga-trainer": "calendar",        "teaching": "documents",        "blank": "notes",    ]}/// The one screen after a card: the name, and Create.private struct NameDatabaseScreen: View {    let model: DatabasesModel    let scene: DatabaseScene    let toolkit: DatabaseToolkit    @State private var name: String    @FocusState private var focused: Bool    init(model: DatabasesModel, scene: DatabaseScene, toolkit: DatabaseToolkit) {        self.model = model        self.scene = scene        self.toolkit = toolkit        // The field starts blank with the card's own name as its placeholder        // and as the name Create falls back to: pre-filling it put the cursor        // after "Friends" and a typed name came out "FriendsGarden Club"        // (4 Oct 2026).        _name = State(initialValue: "")    }    /// The card's name stands in for an untyped one; a blank card has none.    private var placeholder: String { toolkit.id == "blank" ? "Name" : toolkit.name }    private var chosenName: String {        let typed = name.trimmingCharacters(in: .whitespacesAndNewlines)        return typed.isEmpty && toolkit.id != "blank" ? toolkit.name : typed    }    var body: some View {        PaperScreen(title: ShellLines.line("databases", "name_it")) {            VStack(alignment: .leading, spacing: 18) {                PaperTextField(placeholder, text: $name, size: 28, serif: true, focus: $focused)                    .onSubmit(create)                if let refusal = model.refusal {                    Text(refusal).paperBody(ink: .red)                }                VStack(alignment: .leading, spacing: 6) {                    Text(ShellLines.line("databases", "starts_with")).paperHand(15)                    Text(toolkit.startingTools.isEmpty ? ShellLines.line("databases", "an_empty_board_add") : toolkit.startingTools.joined(separator: " · "))                        .paperBody()                        .accessibilityIdentifier("database-starting-tools")                }                Text(ShellLines.line("databases", "only_you_are_in")).paperHand(15)                PaperTypedButton(model.creating ? ShellLines.line("databases", "creating") : "Create", action: create)                    .disabled(chosenName.isEmpty || model.creating)                    .frame(maxWidth: .infinity)                PaperTypedButton("Cancel") { scene.choosing = false }                    .frame(maxWidth: .infinity)            }        }        .onAppear {            model.clearRefusal()            focused = true        }        .onChange(of: name) { _, _ in model.clearRefusal() }    }    private func create() {        Task {            guard let made = await model.create(name: chosenName, toolkit: toolkit) else { return }            await scene.show(made.databaseId, in: model)        }    }}/// One joiner waiting: who, the two fingerprints to compare, Admit and Refuse.struct ClaimCard: View {    let claim: DatabaseClaim    let database: String?    let decide: (Bool) -> Void    var body: some View {        VStack(alignment: .leading, spacing: 8) {            Text(database.map { ShellLines.line("databases", "asks_to_join", ["person": "\(claim.personName)", "database": "\($0)"]) } ?? ShellLines.line("databases", "asks_to_join_here", ["person": "\(claim.personName)"]))                .paperBody()            if let device = claim.deviceName {                Text(device).paperHand(15)            }            if let digits = claim.digits {                // The six digits the joiner's own screen shows.                Text(ShellLines.line("databases", "their_phone_shows", ["digits": "\(pairingDigitsGrouped(digits))"])).paperBody()                    .accessibilityIdentifier("claim-card-digits")            }            Text(ShellLines.line("databases", "device_fingerprint", ["fingerprint": "\(claim.deviceFingerprint)"])).paperBody()                .accessibilityIdentifier("claim-device-fingerprint")            Text(ShellLines.line("databases", "person_fingerprint", ["fingerprint": "\(claim.personFingerprint)"])).paperHand(15)            HStack(spacing: 24) {                PaperTypedButton("Admit") { decide(true) }                PaperTypedButton("Refuse", destructive: true) { decide(false) }            }        }        .frame(maxWidth: .infinity, alignment: .leading)    }}