Cotton code
1159 lines · 56.9 KB · SwiftRaw
// The board: the database's tiles in the Home order, a plain vertical scroll// with the database bar at the foot — Search, the current database's cap, New// thought (UI direction, Cotton note 0a22168c §3; `DatabaseBar.swift`). A// project is this board with the cap's choice set.//// A tile is a picture: its tool's photograph and name, and a tap opens the// view it points at. Home draws no records of its own (owner, 12 Oct 2026:// Home is tiles; the notices line is its only attention).//// New thought raises the capture surface over the board (`Navigator.capture`),// as a share arriving or a notification's tap does; the change// receipt above the bar shows what the last write did, with its byline and// Undo.//// ONE RENDERER, THE BOARD AS THE CORE ANSWERS IT (design note 26203e21;// `shell.today`'s `parts.board`). What the page draws, in what order, and// whether each part draws at all, are the answer's: the page walks the parts// in order and draws each shown one in THE PART SWITCH (`part(_:)`) — one case// per kind, each kind drawn there once, and no part draws another part. A kind// the answer calls `unknown` is passed over and said once in Feedback// (`BoardFeedback`), never a crash. `BoardSurfaceGuardTests` holds all three.//// Search is not a part: it is the head's companion, drawn under the head and// the notices that follow it, where Home always had it.//// EVERYTHING A BOARD OPENS IS A ROUTE, opened through the navigator: a list, a// data tool's own board (`/tools/board/[id]`), a record's screen or its// table's page (`/lists/[table]/[id]`), the database's facts. The board never// pushes a view of its own: the Tools screen and the database page are boards// PUSHED over Home, and SwiftUI honours the `navigationDestination(item:)` for// a type nearest the stack's root — a pushed board's own was ignored and the// tap opened nothing (build 228's walk). `BoardOpensThroughRoutesTests` keeps// the modifier out of this file.import CottonKitimport CottonValuesimport SwiftUIstruct BoardSurface<Results: View>: View {    @Environment(\.theme) private var theme    @Binding private var project: String?    /// The board this page is, for its id and picture.    private let board: BoardDefinition    /// The parts this page draws, in order, as the core answered them.    private let entries: [BoardEntry]    /// Home's read, for the head, notices, asked and done parts.    private let home: BoardHome    /// The page's title when the board has no head to name it (the Tools screen).    private let title: String?    /// The page is the root of its stack (Home): no Back, and the input box and    /// capture at its foot. A pushed board (Tools, the database page) has a    /// Back and leaves the box to Home beneath it.    private let root: Bool    /// The Tools screen: the tools part shows every tool of the database, a    /// tile on Home or not, and no Tools tile of its own.    private let everyTool: Bool    /// The page's tray; empty draws no circle (Home has none).    private let menu: [PopoverMenuItem]    /// Home's tiles (`HomeModel.homeTiles`) — the ONE copy: the board holds    /// none of its own, so a reorder in Tools or a tile taken off reaches the    /// board with Home's next read, every time. Nil until the shown    /// database's arrangement is answered: the board then draws no tile and    /// no tile — the arranged board or nothing.    private let arrangement: HomeTiles?    private let onOpenTable: (TableDefinition) -> Void    /// The projects the switcher falls back to when the records hold none.    private let projects: [TableRecord]    /// What takes the tiles' place while the host's global search has words.    private let results: Results?    /// The held database's whole name, for its cap, search and thought receipt.    private let databaseName: String?    /// Whether the shown database is personal, for its available tools.    private let personal: Bool    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(\.records) private var store    @Environment(\.tableDefinitions) private var definitions    /// The fan's answer and the ring's choices, the Tools card's view among    /// them: the fan's own over the pages it draws, else this board's.    @Environment(ToolViews.self) private var toolViews: ToolViews?    @State private var ownFan = ToolViews()    private var fan: ToolViews { toolViews ?? ownFan }    @Environment(\.toolDefinitions) private var dataTools    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(PendingTaps.self) private var taps: PendingTaps?    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    @Environment(DatabasesModel.self) private var databases: DatabasesModel?    /// How a tile's page draws inside Home's fan (`StackHost`).    @Environment(\.routePage) private var routePage    @State private var localQuery = ""    private let suppliedQuery: Binding<String>?    private var query: String { suppliedQuery?.wrappedValue ?? localQuery }    private var queryBinding: Binding<String> { suppliedQuery ?? $localQuery }    @State private var pageMenu = PageMenu()    /// The page's own stack button is open.    @State private var menuOpen = false    /// Home's fan is tucked away while its thought field is up for typing.    @State private var fanTyping = false    @Environment(\.fanCover) private var windowFanCover    @State private var ownFanCover = FanCover()    private var fanCover: FanCover { windowFanCover ?? ownFanCover }    /// The head's magnifier was tapped: the field stands over the head's    /// row, the fan and the record button are put away (fan3 part 6).    @State private var headSearching = false    /// A page under the fan has its search field open (`PageSearchingKey`).    @State private var pageSearching = false    /// The tile a spoken "show …" turns the fan to, until it has turned.    @State private var fanShow: String?    /// What the record button's toast says now (`FanToastKey`): the fan    /// draws it in the page region above itself.    @State private var fanToast: FanToast?    /// A typed thought's receipt (`HomeReceiptKey`), drawn at the toast edge.    @State private var homeReceipt: HomeReceipt?    @State private var loadedTools = ToolDefinitions([])    @State private var refresh = 0    /// What the catalogue was last read for: a return to the board reads nothing again.    @State private var readFor: Read?    @Environment(\.cottonSync) private var sync    @Environment(BootModel.self) private var boot: BootModel?    /// The one input's newest change, the table it was written to, and    /// whether its receipt took it back.    @State private var change: (record: ChangeRecord, table: TableDefinition?)?    @State private var undoneChange: String?    /// What the one input said beside it, until it is let go.    @State private var note: OneInputNote?    /// A thought the capture surface kept (the picture path), on the    /// overlay's receipt until it is let go.    @State private var kept: ThoughtFiled?    /// The capture up is the picture path's: latched when the picture is    /// held, because the capture surface TAKES the picture as it mounts and a    /// body reading `waitingPicture` alone would swap the surface out under it.    @State private var pictureCapture = false    /// - Parameters:    ///   - project: the switcher's choice, nil for All; the board's host puts    ///     it in the environment as `\.currentProject` for every surface.    ///   - arrangement: Home's tiles (`HomeModel.homeTiles`), which place    ///     the database's package tools — the only tools there are — and say    ///     which tiles are faint.    ///   - projects: the switcher's fallback projects (`HomeModel.switcherProjects`).    ///   - board: the board this page is, for its id and picture.    ///   - entries: the parts the page draws, in order, as the core answered them.    ///   - home: Home's read, for the head, notices, asked and done parts.    ///   - results: drawn in the tiles' place, with the cap, when not nil.    init(        project: Binding<String?>,        arrangement: HomeTiles? = nil,        query: Binding<String>? = nil,        projects: [TableRecord] = [],        databaseName: String? = nil,        personal: Bool = true,        board: BoardDefinition,        entries: [BoardEntry] = [],        home: BoardHome,        title: String? = nil,        root: Bool = true,        everyTool: Bool = false,        menu: [PopoverMenuItem] = [],        results: Results?,        onOpenTable: @escaping (TableDefinition) -> Void    ) {        _project = project        self.arrangement = arrangement        self.suppliedQuery = query        self.projects = projects        self.databaseName = databaseName        self.personal = personal        self.board = board        self.entries = entries        self.home = home        self.title = title        self.root = root        self.everyTool = everyTool        self.menu = menu        self.results = results        self.onOpenTable = onOpenTable    }    /// What says whether the Bin is a tile on Home.    private struct BinTiles: Equatable {        var tiles: HomeTiles?        var bins: [String]    }    private struct Read: Equatable {        var database: String?        var revision: UInt64        var refresh: Int        /// A screen covers the board (`BoardCover`): nothing is read until        /// it shows.        var covered: Bool    }    /// Whether a screen covers the board now, or a link is about to open one.    /// A pushed board is the screen on top whenever it is drawn.    private var covered: Bool {        guard root else { return false }        return BoardCover.covered(navigator?.stack ?? [], columns: false, arriving: taps?.arriving == true)    }    /// The database's tools: the environment's, else those this board read.    private var catalogue: ToolDefinitions { dataTools.all.isEmpty ? loadedTools : dataTools }    /// The page comes back to each database at the place this window left it;    /// a project's page keeps a place of its own, so it opens at its head. A    /// pushed board keeps its place apart from Home's.    private var place: PagePlace? {        guard let places = scene?.places else { return nil }        let key = scene?.shownId.map { id in project.map { id + "/" + $0 } ?? id }.map { root ? $0 : $0 + "#" + board.id }        return PagePlace(key: key, read: places.place(of:), write: { places.keep($1, for: $0) })    }    // ── The board's parts ────────────────────────────────────────────────    /// The parts drawn, in the answer's order, and the room above each: a    /// notice stands 16 under the head, as it did when the two were one    /// stack; every other row 20. A part the core says is not shown takes no    /// room; a `notices` part may still say what only this window holds.    static func rows(_ entries: [BoardEntry], context: BoardHome) -> [(entry: BoardEntry, gap: CGFloat)] {        let drawn = entries.filter { $0.shown || ($0.kind == "notices" && BoardNotices.saysOwn(context, in: $0)) }        return drawn.enumerated().map { at, entry in            guard at > 0 else { return (entry, 0) }            return (entry, entry.kind == "notices" && drawn[at - 1].kind == "head" ? 16 : 20)        }    }    /// The `tools` part's tiles, whole, as the fan's answer shape draws them.    private var toolTiles: [FanAnswer.Tile] { entries.first { $0.kind == "tools" }?.tools ?? [] }    private var page: some View { parts(homeHead: false) }    /// Home's head: the person's print and name from the window's box, a    /// tap opening their own page. Only Home's own page (iOS) asks for it;    /// the macOS stub compiles `parts` too, so it answers nothing there.    private var homeHead: AnyView {        #if os(iOS)        AnyView(HomeHead(face: personRead.face) { navigator?.open(.me) })        #else        AnyView(EmptyView())        #endif    }    /// The parts in the answer's order; on Home's own page (`homePage`) the    /// head is the person (`homeHead`), never a board's head.    private func parts(homeHead: Bool) -> some View {        VStack(alignment: .leading, spacing: 0) {            ForEach(Self.rows(entries, context: home), id: \.entry.id) { row in                (homeHead && row.entry.kind == "head" ? self.homeHead : part(row.entry)).padding(.top, row.gap)            }        }        .environment(\.shownDatabaseName, databaseName)        .environment(\.headSearch, headSearch)    }    /// The head's magnifier: the field over the head's row, where the    /// query is the one Home's results read (`query`). A Mac window    /// searches in its toolbar.    private var headSearch: (@MainActor @Sendable () -> Void)? {        #if os(iOS)        guard entries.contains(where: { $0.kind == "search" && $0.why?.key == "magnifier" }) else { return nil }        return { headSearching = true }        #else        return nil        #endif    }    /// The field over the head's row while the magnifier holds it; its    /// close clears the words, then gives the head back.    @ViewBuilder private var headSearchField: some View {        if headSearching {            SearchPill(text: queryBinding, placeholder: ShellLines.line("record", "search_database", ["name": "\(shownName ?? BoardHeadWords.fallbackName)"])) {                headSearching = false            }            .padding(.top, theme.scale.navRowTop)            .accessibilityIdentifier("bar-search-field")        }    }    /// THE PART SWITCH: every kind a board can name is drawn here, once, by    /// its own case; no case draws a board or another part. Each is boxed    /// so the page's type stays shallow (the phone's 1 MB main-thread stack,    /// 976f01a4c).    private func part(_ entry: BoardEntry) -> AnyView {        switch entry.kind {        case "head":            return AnyView(BoardHeadPart(                context: home, tags: entry.tags, asked: entry.headAsked.compactMap(AskedItem.init),                askedTotal: entry.headAskedTotal, done: entry.headDone.compactMap(DoneItem.init)))        case "notices":            return AnyView(BoardNotices(context: home, entry: entry))        case "tools":            return AnyView(toolsPart(entry))        case "asked":            return AnyView(BoardAskedList(home: home.model, items: entry.asked.compactMap(AskedItem.init)))        case "done":            return AnyView(BoardDoneList(home: home.model, now: home.now, items: entry.done.compactMap(DoneItem.init)))        case "list":            return AnyView(BoardListPart(                entry: entry, onOpen: { open($0) }, onOpenRecord: { openRecord($0, of: $1) }, onToggle: { tick($0, in: $1) }))        case "facts":            return AnyView(BoardFactsPart(entry: entry) {                if let source = entry.source, let id = entry.record { navigator?.open(.tableRecord(table: source, id: id)) }            })        case "about":            return AnyView(ToolsAboutFooter())        case "recent":            return AnyView(RecentShelf(                heading: entry.heading ?? "", limit: entry.settings.number("limit") ?? 0, tiles: toolTiles.map(gridTile), shown: true,                onTile: { tap($0) },                onRecord: { record, definition in                    navigator?.open(BoardRecord.route(table: definition.id, id: record.id, definition: definition))                }))        case "search":            return AnyView(searchSlip)        case "today":            return AnyView(HomeToday(home: home.model, today: entry))        case "sync":            return AnyView(HomeSync())        case "device":            return AnyView(entry.card.map { BoardDevicePart(id: $0) })        case "figure":            return AnyView(BoardFigurePart(heading: entry.heading ?? "", line: entry.line))        default:            return AnyView(EmptyView())        }    }    /// The board's search as a field: a slip at the slips' full width; it    /// opens the search of every database held.    private var searchSlip: some View {        SearchSlip(            placeholder: ShellLines.line("record", "search_database", ["name": "\(shownName ?? BoardHeadWords.fallbackName)"]),            identifier: "bar-search"        ) { navigator?.open(.search) }    }    /// The `tools` part: a sideways row of tiles, or a grid of them, in the    /// answer's order. Home draws the grid whatever the part says: the fan    /// under it is the page's frame (`fanHome`), never the board's.    @ViewBuilder private func toolsPart(_ entry: BoardEntry) -> some View {        let tiles = entry.tools.map(gridTile)        if root || entry.settings.text("face") == BoardToolsFace.grid.rawValue,           let columns = entry.settings.number("columns"),           let size = entry.settings.text("size").flatMap(BoardToolsSize.init(rawValue:)) {            VStack(alignment: .leading, spacing: 12) {                BoardToolGrid(                    tiles: tiles, columns: columns, size: size,                    faint: Set(entry.tools.filter { $0.hidden == true }.map(\.key)),                    onOpen: { tap($0) })            }        } else {            HomeToolRow(tiles: tiles) { open($0) }        }    }    // ── The page ─────────────────────────────────────────────────────────    /// The scaffold the parts stand on: no circles on Home (owner, 6 Oct): no    /// Back at the stack's root and no search button, so the title row stands    /// where the circles were — no empty band. A pushed board has its Back,    /// and its stack button when it has a menu.    @ViewBuilder private var paper: some View {        if everyTool, decks {            // The Tools card on the dial opens a deck, one card per tool,            // never a grid (row B of the deck faces, 23 Oct 2026).            // Its ring's two views: the tools Home shows, or those the            // arrangement hides (`shell.fan`'s Tools tile).            let showsHidden = fan.current(of: GridTile.tools.key)?.id == ToolView.toolsHidden            ToolsDeck(tiles: toolTiles.filter { ($0.hidden == true) == showsHidden }.map(gridTile)) { tap($0) }        } else if menu.isEmpty {            PaperScreen(title: title, showsBack: !root, place: place) { AnyView(page) }        } else {            PaperScreen(title: title, showsBack: !root, place: place, trailing: {                TrayStackButton { menuOpen = true }                    .accessibilityIdentifier("board-\(board.id)-menu")            }) { AnyView(page) }        }    }    var body: some View {        // Built in stages, each in a frame of its own and handed on as        // `AnyView` (as `RecordListSurface.body` is, after build 230's crash):        // one body holding the whole board and its modifiers spent 291 KB of        // main-thread stack per evaluation, and the phone has 1 MB for all of        // SwiftUI. `RouteSurfaceStackTests` holds what it may use.        reads(scoped(face))    }    /// Capture raised over Home, or the board (or the results in its place)    /// with the input box at its foot and its menus.    private var face: AnyView {        // Capture raised over Home itself takes the board's place; raised        // over pushed screens the stack host draws it over them        // (`Navigator.captureOverStack`, `CaptureLayer`).        if root, (navigator?.capture != nil && navigator?.captureOverStack != true) || kept != nil {            return AnyView(CaptureLayer(kept: $kept, pictureCapture: pictureCapture) { Task { await read() } })        }        let ground: AnyView        if let results {            ground = AnyView(results.frame(maxWidth: .infinity, maxHeight: .infinity))        } else if drawsFan {            // Another database chosen: its fan, built for it, stands in the            // frame that shows it — a cut, never a cross-fade: a switch is            // two frames, the old Home and the new (295 A, walker294). Keyed            // on the database the window's calls name, as the stack is            // (`RootView.shownKey`): the held list naming the database a            // launch already shows rebuilt the fan and dealt it again            // (295 B).            ground = AnyView(fanHome.id(fanKey))        } else {            ground = AnyView(paper)        }        return AnyView(ZStack(alignment: .top) {            framed(ground)            headSearchField        })    }    // ── The fan (lane fan, 14 Oct 2026) ─────────────────────────────────    /// THE FRAME (owner with the architect, 16 Oct 2026: the dial is    /// chrome): on the phone, Home — the root every page is pushed over —    /// draws the fan, the database caps on their arc under it    /// (`DatabaseCapArc`) and the record button, on every database, always.    /// It is written here in code and no board part decides it: a board says    /// only which cards are on the fan, in what order, and what each page    /// shows. The Mac draws the grid; a pushed board is a page under the frame.    private var drawsFan: Bool { DialFrame.draws(root: root) }    /// What the fan's own closures (`Navigator.fanBrings`, `fanOpens`) read:    /// they are set again whenever it changes.    private struct FanArming: Equatable {        let tiles: [String]        let tables: [String]        let tools: [String]        let arranged: Bool        let paged: Bool    }    /// The caps arc is the frame's, with the fan — but for a business app    /// that shows one database (`FlavourManifest`), which has no caps at all.    private var drawsCaps: Bool { DialFrame.drawsCaps(fan: drawsFan, manifest: FlavourManifest.current) }    /// What the fan is built for: the shown database as the window's calls    /// name it, "personal" for the personal one and before the held list    /// names any — never the raw shown id, which moves from nothing to the    /// personal database's id as the list arrives.    private var fanKey: String {        databases.flatMap { scene?.shown(in: $0) }.flatMap { $0.isPersonal ? nil : $0.databaseId } ?? "personal"    }    /// The shown database's Home read has come back (`HomeModel.readShown`)    /// AND the fan is laid out from it: the read is observed here a frame    /// before the order it brings reaches this board from its host, and the    /// launch stood on a fan of Me and Tools that was dealt again 0.2–2 s    /// later (295 B, the launch walk's log: read true, ready false).    private var homeRead: Bool {        home.model.readShown(scene: scene, in: databases)            && FanLaunchRule.laidOut(arrangement?.tools, from: home.model.drawnTiles(scene: scene, in: databases)?.tools)            && fan.answer != nil    }    /// The page shown in the fan holds its foot — a composer of its own, or    /// a tray raised on it, the tile's own page included.    private var composerShown: Bool {        guard drawsFan, let navigator else { return false }        // An app whose face is one stream of chats (`shell.fan`'s `stream`)        // draws no fan and no hub: each chat holds its own foot. The arc        // stands only while a card's acts are offered on it (Account's).        if fan.answer?.stream != nil { return !DeckEditor.session.isEditing }        let root = fanTiles.first { TileStacks.key(database: scene?.shownId, tile: $0.key) == navigator.tile }.flatMap(route(of:))        return navigator.footHeld(root: root)    }    /// The fan's tiles as the core deals them (`shell.fan`): its order, its    /// names and pictures, each opening what it is.    private var fanTiles: [GridTile] { (fan.answer?.tiles ?? []).map(gridTile) }    private func gridTile(_ tile: FanAnswer.Tile) -> GridTile {        let tool = catalogue.all.first { $0.id == (tile.tool ?? tile.key) }.map(GridTile.Opens.dataTool)        let opens: GridTile.Opens        switch tile.kind {        case .home: opens = .home        case .tools: opens = .tools        case .settings: opens = .route(.toolBoard(id: SettingsRing.tool))        case .tool: opens = tool ?? .route(.toolBoard(id: tile.key))        case .view:            let shown = tile.view.flatMap { HomeTiles.route(of: HomeTile(id: $0.id, tool: tile.tool, name: $0.name, opens: $0.opens, table: $0.table)) }            opens = shown.map(GridTile.Opens.route) ?? tool ?? .route(.toolBoard(id: tile.tool ?? tile.key))        }        return GridTile(key: tile.key, name: tile.name, picture: picture(of: tile),                        stock: tile.kind == .home ? GridTile.home.stock : tile.stock,                        opens: opens, wears: tile.kind == .view ? tile.tool : nil)    }    /// A tile's picture as this app draws it: the object it names where the    /// app ships it, else its photo; the shell's own cards their object.    private func picture(of tile: FanAnswer.Tile) -> ToolPicture? {        if let named = tile.picture {            if let object = named.object, named.photo == nil || ToolObjects.ships(object) { return .asset(object) }            if let photo = named.photo { return .photo(photo) }        }        switch tile.kind {        case .tools, .settings: return ToolObjects.picture(for: tile.key)        case .view: return ToolObjects.picture(for: tile.tool ?? tile.key)        case .home, .tool: return nil        }    }    /// The tile the fan opens at, as the core answers it.    private var fanOpens: Int {        fan.answer?.opens.tool.flatMap { key in fanTiles.firstIndex { $0.key == key } } ?? 0    }    /// Me's card and head: the person's name and print, read from this    /// phone's own file (`read.you`) — an observable box (`HomeRead`), never    /// view state, because Me's page draws it inside the fan's live page.    @State private var ownHomeRead = HomeRead()    /// The record the board's `device` part names, in the box Home's deck    /// reads (`HomeDevicePart`): filled each time the board is read, since    /// Home's page is drawn inside the fan's live page.    @State private var homeDevice = HomeDevicePart()    /// The window's box, set above the switch's rebuild (`RootView.stack`):    /// you are a person of the personal database whichever is shown    /// (`read.you`), so a switch draws Me's head and card at once. A fresh    /// box drew no head — Today standing where the head goes, as if    /// scrolled — and a blank card until the read answered (293 row 2,    /// walker292 on the real household).    @Environment(HomeRead.self) private var keptHomeRead: HomeRead?    private var personRead: HomeRead { keptHomeRead ?? ownHomeRead }    /// Home's own search for a spoken command that named no record.    private var voiceSearchHere: (@MainActor (String) -> Void)? {        guard root else { return nil }        let query = queryBinding        let searching = $headSearching        return { words in            query.wrappedValue = words            searching.wrappedValue = true        }    }    private var fanHome: AnyView {        #if os(iOS)        let tiles = fanTiles        let faces = fanFaces        return AnyView(FanHome(            tiles: faces,            // Never past the tiles held now: a page asked for a tile the            // arrangement no longer holds is the paper (`FanPageRule.held`).            page: { index in                guard tiles.indices.contains(index), faces.indices.contains(index) else { return AnyView(paper) }                return tilePage(fanPage(tiles[index], face: faces[index]), faces[index])            },            tucked: fanTyping || headSearching || pageSearching || composerShown,            stands: navigator.map { FanPageStand(key: $0.tile ?? "", path: $0.stack.last?.path ?? "") } ?? FanPageStand(),            settles: { navigator?.tile = tileKey($0) },            toRoot: { navigator?.back(to: 0) },            database: scene?.shownId,            show: $fanShow,            caps: drawsCaps,            toast: fanToast,            ready: fan.answer != nil,            read: homeRead,            opens: fanOpens,            pageOpen: navigator?.pageOpen == true,            hostedPages: true,            shellCover: fanCover,            fan: fan)        // A spoken command that named no record, said over Home: Home's own        // search, with the words (a deck's fan opens its deck's Find instead).        .environment(\.voiceSearch, voiceSearchHere)        // The Databases sheet over Home: nothing of the fan is read under it.        .environment(\.fanPagesCovered, scene?.choosing == true)        .fanArcHidden(scene?.choosing == true)        .task(id: core != nil) { await readHome() }        // The one open a fan makes: the settled card's page, once it is the        // page the person sees — never a turn passing over it.        .task(id: navigator?.tile) { await countSettledOpen() }        // A card asked for from Home turns the fan to its tool's deck. The        // closures read this board as it stands when they are set — its        // tables, its tools, its arrangement — so they are set again as any        // of those comes: set on the first tiles alone, a landing after the        // object's definitions replaced the kit's asked the board as it stood        // before, and where that board held no tile for the table the record        // was stacked as a page over the deck instead of brought onto it.        .task(id: FanArming(tiles: tiles.map(\.key), tables: definitions.all.map(\.id), tools: catalogue.all.map(\.id),                            arranged: arrangement != nil, paged: routePage != nil)) {            navigator?.fanBrings = { bringOnFan(table: $0, id: $1, many: $2) }            guard arrangement != nil, !catalogue.all.isEmpty else { return }            navigator?.fanOpens = { asked in                guard drawsFan, let tile = fanTiles.first(where: { tile in                    let tool: String?                    if case .dataTool(let definition) = tile.opens { tool = definition.id } else { tool = nil }                    return BoardLayout.arrives(asked, at: route(of: tile), tool: tool)                }),                      drawsInPlace(tile) else { return false }                navigator?.standsAtRoot(tileKey(tile.key))                fanShow = tile.key                return true            }        }        .onMediaArrival { if personRead.face?.picture == nil { await readHome() } }        // A Home that stops drawing the fan pushes every record again.        .onDisappear { navigator?.tile = nil }        .onPreferenceChange(PageSearchingKey.self) { pageSearching = $0 })        #else        return AnyView(paper)        #endif    }    /// What a spoken "show …" can name on the fan; nothing on a grid.    private var fanNames: [(key: String, name: String)] {        #if os(iOS)        return drawsFan ? fanFaces.map { ($0.key, $0.name) } : []        #else        return []        #endif    }    /// Whether the phone draws its pages as decks: always, on the phone.    private var decks: Bool {        #if os(iOS)        true        #else        false        #endif    }    #if os(iOS)    /// A fan tile's page as one surface: its own page, turned in place to the    /// records opened on it (`TilePage`).    private func tilePage(_ root: AnyView, _ face: FanTile) -> AnyView {        guard let navigator else { return root }        // Its root is a whole's parts while its fan stands inside one (`WholeRoot`).        let key = tileKey(face.key)        return AnyView(TilePage(key: key, root: AnyView(WholeRoot(key: key, tool: face.name, root: root)),                                rootTitle: face.name, navigator: navigator))    }    /// A fan tile's stack is the database's own: another database's Notes    /// keeps its own.    private func tileKey(_ tile: String) -> String { TileStacks.key(database: scene?.shownId, tile: tile) }    /// The fan's tiles, in `fanTiles`' order; Me's wears the person's print.    private var fanFaces: [FanTile] {        fanTiles.map {            FanTile(                key: $0.key, name: $0.name, picture: $0.picture, stock: $0.stock ?? ToolCardTint.of($0.stockKey),                face: $0.key == GridTile.home.key ? homeFace : nil,                families: ScreenFamily(rawValue: $0.stockKey).map { [$0] }, poster: !drawsInPlace($0),                ringed: fan.tile($0.key)?.ringed == true)        }    }    /// Me's card: the person's print, carrying the picture Home's board names    /// for the window to show while there is no picture and no name — a    /// database just founded, on a phone or a Mac, or a business app.    private var homeFace: HomeFace {        var face = personRead.face ?? HomeFace(name: "", picture: nil, seed: "home")        if case .asset(let object)? = (board.id == BoardDefinition.home.id ? board : BoardDefinition.home).picture?.drawn {            face.object = object        }        return face    }    /// Home's page, the fan's centre, in every flavour (owner, 19 Oct 2026:    /// the root page is Home, never Me): the home board's sections in its    /// order — the board Cotton ships, or the one a business app's manifest    /// names, which the core holds in its place (`declare_home`). The head is    /// the person — their print and name, which open their own page in place    /// — with the sync line under it; then today (`HomeToday`: today's events    /// and due todos), the notices, what is asked of them and what was done    /// for them, each but the head and today drawn only when it has    /// something, and a table's list as a section. No tiles: the fan is the    /// tiles. The page's title is `HomeHead`'s name, so the screen carries    /// none of its own — the fan card's word is never drawn over the    /// person's name.    @ViewBuilder private var homePage: some View {        if decks {            // Home as a deck (row C of the deck faces, 23 Oct 2026): today's            // cards, the unread conversations, then each part of Home with            // something to say on a card of its own.            // This device's own record leads the deck, as the head leads a            // page: named by the board, through its box (`homeDevice`).            HomeToday(home: home.model, deckPage: true, devicePart: homeDevice, parts: homeCards)                .environment(\.shownDatabaseName, databaseName)        } else {            PaperScreen(title: nil, showsBack: false, place: place) { AnyView(parts(homeHead: true)) }        }    }    /// Home's bands, each as a card; the core deals one only where it speaks.    private var homeCards: [HomePartCard] {        entries.compactMap { entry in            switch entry.kind {            case "notices", "asked", "done": HomePartCard(id: entry.kind, face: part(entry))            default: nil            }        }    }    /// Reads who the person is and decodes their print at the card's size, so the    /// card is drawn once with it. No print: their initials.    private func readHome() async {        guard let core else { return }        let you: YouRead        switch await MeOpening.read(core) {        case .person(let read): you = read        case .notYet, .refused: return        }        let name = you.name ?? ""        let print = you.print.flatMap { $0.isEmpty ? nil : $0 }        let seed = you.personId ?? "home"        // The same person, name and print as held: nothing to draw again.        guard personRead.differs(name: name, print: print, seed: seed) else { return }        var picture: CGImage?        if let print {            let edge = CGFloat(theme.scale[.fanTileW]) * UIScreen.main.scale * 2            if case .ready(let image) = await MediaImages.load(from: core, key: print, edge: edge) { picture = image.cgImage }        }        personRead.take(HomeFace(name: name, picture: picture, seed: seed), print: print)    }    /// A tile's page in the fan: the list its tap opens, drawn in place with    /// no Back (it is the root of nothing) under the dial, the phone's one    /// input. Only a list-tier route is drawn in    /// place — a table's list, a data tool's own board of tiles    /// (`/tools/board/[id]`), the Tools board; Home's own tile is Home's    /// board itself. A tile that opens anything else — a record, a screen    /// that takes no id, the camera —    /// shows its tile, and a tap presents it over the whole screen as a tile    /// tap does (architect, 14 Oct 2026: the fan is for pages, not modals).    private func fanPage(_ tile: GridTile, face: FanTile) -> AnyView {        if tile.key == GridTile.home.key { return AnyView(homePage) }        guard drawsInPlace(tile), let route = route(of: tile), let routePage else {            return AnyView(FanPoster(tile: face) { open(tile) })        }        // The app's face is one stream of chats: its tool's page is the        // stream, whatever view its ring last stood on.        if let stream = fan.answer?.stream, stream.tool == tile.key {            return AnyView(SourceTableStore(table: stream.table, filter: [:]) { ChatStream(table: stream.table, tool: stream.tool) }                .environment(\.cottonAtColumnRoot, true)                .environment(\.countsOpens, false))        }        // An imported tool's page is one list of the view its ring chose:        // its home table read as the view says (`ToolViewRoute`). A tool        // whose home table names its own screen draws that screen.        // A card that stands left of the tool's first view reads no table:        // its page is its own (Account, `shell.account`).        if face.ringed, let aside = fan.current(of: tile.key), aside.aside, aside.id == SendCenter.sentCard {            return AnyView(SentPage()                .environment(\.cottonAtColumnRoot, true)                .environment(\.countsOpens, false))        }        if face.ringed, let aside = fan.current(of: tile.key), aside.aside {            return AnyView(AccountPage(card: aside.id, table: fan.tile(tile.key)?.viewsTable ?? "")                .environment(\.cottonAtColumnRoot, true)                .environment(\.countsOpens, false))        }        if face.ringed, let table = fan.tile(tile.key)?.viewsTable {            return AnyView(ToolViewRoute(of: tile.key, table: table)                .environment(\.cottonAtColumnRoot, true)                .environment(\.countsOpens, false))        }        return AnyView(routePage.draw(route)            .environment(\.cottonAtColumnRoot, true)            .environment(\.countsOpens, false))    }    #endif    #if os(iOS)    /// Whether a tile's page is drawn in place in the fan (a list or a    /// page, with a stack to draw it — Me and Camera too) rather than as its    /// poster: a card opens its page directly.    private func drawsInPlace(_ tile: GridTile) -> Bool {        routePage != nil && fan.tile(tile.key).map { !$0.poster } == true    }    #endif    #if os(iOS)    /// Logs the settled card's page as an open (`RouteScreen.countsOpen`).    private func countSettledOpen() async {        guard let tile = navigator?.tile, drawsFan,              let shown = fanTiles.first(where: { tileKey($0.key) == tile }),              drawsInPlace(shown), let route = route(of: shown),              RouteScreen.countsOpen(route, paintsPicture: false, countsOpens: true) else { return }        await store?.recordViewOpened(route)    }    #endif    /// The route a tile's tap opens — `open(_:)`, as a route.    private func route(of tile: GridTile) -> Route? {        switch tile.opens {        case .dataTool(let tool): return BoardLayout.route(for: tool, in: definitions, tools: catalogue.all)        case .tools: return .tools        case .home: return .me        case .route(let route): return route        }    }    /// ONE cap in one place whichever body is up, so the search keeps its    /// focus while its results take the tiles' place.    private func framed(_ ground: AnyView) -> AnyView {        return AnyView(ZStack(alignment: .bottom) { ground }        // The input box stands on the page's foot inside the safe        // area, so the page always scrolls clear of it — its receipt        // and a growing box included (Spec 7; the last section sat        // behind the old bar on build 55). Home's alone: a pushed        // board leaves it to the Home beneath.        .safeAreaInset(edge: .bottom, spacing: 0) {            if root {                VStack(spacing: FanRoom.recordGap) {                    // Put away while a search field is open over the page.                    homeInput.onPreferenceChange(FanToastKey.self) { fanToast = $0 }                        .onPreferenceChange(HomeReceiptKey.self) { homeReceipt = $0 }                        .opacity(headSearching || pageSearching ? 0 : 1)                        .allowsHitTesting(!(headSearching || pageSearching))                        .accessibilityHidden(headSearching || pageSearching)                }                // A page with a composer of its own stands its composer at                // the foot instead (`Navigator.composerShown`): the record                // button takes no room, kept as it was for the page's close.                .frame(height: composerShown ? 0 : nil, alignment: .top)                .clipped()                .opacity(composerShown ? 0 : 1)                .allowsHitTesting(!composerShown)                .accessibilityHidden(composerShown)            }        }        // The receipts stand at the toast edge, the top, over the page —        // never above the record button over the fan (the owner, 17 Nov        // 2026). Home's alone, as the input box is.        .receiptAtToastEdge {            if root, !composerShown { receipt }        }        .composerColumn()        .menuTray(isOpen: Binding(get: { pageMenu.isOpen }, set: { pageMenu.isOpen = $0 }), items: pageMenu.items)        .menuTray(isOpen: $menuOpen, items: menu, title: title))    }    /// What the board answers: the parts it passes over, its environment,    /// the project the switcher and the scope choose.    private func scoped(_ face: AnyView) -> AnyView {        AnyView(face        // A part this build does not draw is filed once in Feedback, never a crash.        .onChange(of: board, initial: true) { _, board in            for kind in entries.filter({ $0.why?.key == "unknown" }).map(\.kind) {                BoardFeedback.passedOver(                    part: kind, board: board.id, databaseId: scene?.shownId,                    databaseName: shownName ?? databases.flatMap { scene?.shown(in: $0) }?.name,                    boards: core.map { CoreBoards(core: $0) })            }        }        // The record the board's `device` part names, into the box Home's        // deck reads: every board read, whenever it lands.        .onChange(of: HomeDevicePart.named(in: entries), initial: true) { _, id in            homeDevice.id = id        }        // Whether the Bin is a tile on Home (`BinShelf`), off the tiles and        // the shown database's own tables, read where both are drawn.        .onChange(of: BinTiles(tiles: arrangement, bins: definitions.all.filter { $0.binned != nil }.map(\.id)), initial: true) { _, read in            if let tiles = read.tiles { BinShelf.read(tiles: tiles, definitions: definitions.all.filter { read.bins.contains($0.id) }) }        }        .environment(\.toolDefinitions, loadedTools)        .environment(\.pageMenu, pageMenu)        .environment(\.databaseTools, arrangement.map { Set($0.tools) })        .modifier(CapturePictureLatch(pictureCapture: $pictureCapture, navigator: navigator))        // A Home that draws no fan pushes every record: no card is shown.        .onChange(of: drawsFan, initial: true) { _, fan in            if root, !fan { navigator?.tile = nil }        }        // Each card's stack as it was left, across a relaunch (`TileStacks`).        .modifier(TileStacksKept(navigator: root ? navigator : nil))        .onChange(of: navigator?.projectRequest, initial: true) { _, slug in            // The switcher's own choice (`ProjectSwitcher.choose`): the scope            // names the project and the watcher below turns it into the page's,            // so it is still chosen after a list is opened and left.            // Home's to answer: a pushed board leaves the request to the root.            guard root, let slug else { return }            navigator?.projectScope = ProjectScope([slug])            navigator?.projectRequest = nil        }        // Picking a database — this one again too — is the way back from a        // project a link chose to the database's own page.        .onChange(of: scene?.picks) { _, _ in navigator?.projectScope = .all }        .onChange(of: navigator?.projectScope, initial: true) { _, scope in            guard let scope else { return }            if scope.isAll { project = nil; return }            Task {                guard let store, let projects = definitions.playing(.project), let slug = projects.scopeBy,                    let rows = try? await store.list(table: projects.id, project: nil, query: nil, page: 0)                else { return }                project = rows.records.first { $0[slug].text.map(scope.contains) ?? false }?.id            }        })    }    /// The read that keeps the data tools' tiles placed while the board is up.    private func reads(_ face: AnyView) -> AnyView {        AnyView(face        .task(id: reading) {            // Nothing is read while the host's results take the board's place,            // nor under a screen that covers it: back to the board reads.            guard results == nil, !covered else { return }            let asked = reading            // A return to the board (the task starts again as it appears)            // reads nothing: what others wrote moves `foreignRevision`.            guard readFor != asked else { return }            let began = Date()            await read()            Log.write("board: read the tools \(Int(Date().timeIntervalSince(began) * 1000)) ms\(Task.isCancelled ? " cancelled" : "")")            if !Task.isCancelled { readFor = asked }        }        .onAppear { Log.write("board: shown") })    }    private var reading: Read {        Read(database: scene?.shownId, revision: UInt64(sync?.foreignRevision ?? 0), refresh: refresh, covered: covered)    }    /// A slip on the board opens its record (S1 extended), never the list:    /// through the route that addresses it, or its table's page — a data    /// tool's table, an alarm (`BoardRecord.route`).    private func openRecord(_ record: TableRecord, of section: BoardSectionItem) {        navigator?.open(BoardRecord.route(table: section.definition.id, id: record.id, definition: section.definition))    }    /// A tile, or its section's heading, opens what the tile stands for: a    /// tool by the one route rule (`BoardLayout.route(for:in:)`), the Tools    /// screen, Me, or the route a view names.    ///    /// A tool that opens straight to its home table opens it through the    /// host's rule (`onOpenTable`), which on the phone is that same route    /// rule by the table; any other opens its route.    private func open(_ tile: GridTile) {        switch tile.opens {        case .dataTool(let tool):            // A tool over a table another tool owns opens its own page, never            // the table's (`BoardLayout.route`).            if BoardLayout.ownsHome(tool, in: definitions, tools: catalogue.all),               BoardLayout.declaredRoute(for: tool, in: definitions, tools: catalogue.all) == nil,               !BoardLayout.opensOnViews(tool, in: definitions),               let table = BoardLayout.directTable(for: tool, in: definitions) { onOpenTable(table) }            else { navigator?.open(BoardLayout.route(for: tool, in: definitions, tools: catalogue.all)) }        case .tools: navigator?.open(.tools)        case .home: navigator?.open(.me)        case .route(let route): navigator?.open(route)        }    }    /// A record of a deck tool, asked for where the fan stands: the fan turns    /// to the tile whose tool's home table holds it, that tile's page back at    /// its deck, and the deck opens at the card (`Navigator.bringing`). False    /// where no tile on the fan draws the table's deck — a chat, a tool whose    /// list is not a deck, a tool not on the fan — and the record opens on    /// its own deck instead (`RecordOpening`).    private func bringOnFan(table: String, id: String, many: Bool) -> Bool {        #if os(iOS)        guard drawsFan, let navigator, let definition = definitions[table],              !definition.drawsConversation, DeckSwitch.draws(definition, view: nil, plain: true),              let tile = fanTiles.first(where: { tile in                  guard case .dataTool(let tool) = tile.opens else { return false }                  return BoardLayout.home(for: tool, in: definitions)?.id == table              }),              drawsInPlace(tile)        else { return false }        navigator.standsAtRoot(tileKey(tile.key))        // A ring standing on a card aside (Sent to you, Account) draws that        // card's own page, never the deck: it turns to the tool's own view,        // whose deck takes the record (send-walk, 13 Nov 2026: a kept send's        // Open stood on Sent to you).        if fan.current(of: tile.key)?.aside == true,           let view = fan.views(of: tile.key).first(where: { $0.isDefault && !$0.aside }) ?? fan.views(of: tile.key).first(where: { !$0.aside }) {            fan.choose(view.id, of: tile.key)        }        navigator.bringing = .init(table: table, id: id, many: many)        fanShow = tile.key        return true        #else        return false        #endif    }    /// A tile tapped on Home's grid. On a fan Home a tile whose page the fan    /// draws turns the fan to it, and its page shows in place — no push, no    /// Back (fan2 part 5); one with no page of its own (a poster) opens what    /// it stands for, as everywhere else.    private func tap(_ tile: GridTile) {        #if os(iOS)        if drawsFan, drawsInPlace(tile) { return fanShow = tile.key }        #endif        open(tile)    }    /// A slip's check, ticked on the page: the write its list would make, its    /// change on the receipt (Undo there).    private func tick(_ record: TableRecord, in definition: TableDefinition) {        guard let store, let (key, value) = record.said?.toggle?.first else { return }        Task {            do {                let written = try await store.update(table: definition.id, id: record.id, patch: [key: value])                undoneChange = nil                change = (written, definition)            } catch {                toasts?.show(RecordsSection.refusal(error), tone: .error)            }        }    }    /// The one input's newest change on the change receipt, and its note under    /// it, with Undo; Done lets the receipt go.    @ViewBuilder private var receipt: some View {        VStack(spacing: 8) {            if let change {                ChangeReceipt(                    change: change.record, table: change.table, undone: undoneChange == change.record.id,                    onUndone: { _ in                        undoneChange = change.record.id                        Task { await read() }                    },                    onDismiss: { self.change = nil })                .id(change.record.id)                .accessibilityIdentifier("board-receipt")            }            if let note {                OneInputNoteCard(note: note) { self.note = nil }            }            if let homeReceipt {                HomeThoughtReceipt(sentence: homeReceipt.sentence, words: homeReceipt.words, undo: homeReceipt.undo,                                   onDismiss: homeReceipt.onDismiss)            }        }        .padding(.horizontal, ChromeKnobs.chromeSettingsMargin)    }    /// Home and its cap keep the database name, independently of the person.    private var shownName: String? { databaseName }    /// The tools' catalogue, which places the data tools' tiles.    private func read() async {        guard let store else { return }        if let tools = try? await store.toolDefinitions(), !Task.isCancelled { loadedTools = ToolDefinitions(tools) }    }    /// The input box (`HomeInput.swift`): a thought kept in the database this    /// window shows, over the dock the capture surface mounts.    @ViewBuilder private var homeInput: some View {        Hosted(unwired: { core, _ in            CaptureSurfaceModel(                read: ScreenRead(core: core, read: CaptureSurfaceModel.readName, families: [.core]),                dictionary: { await VoiceBias.hints(core: core) }            )        }) { surface in            HomeInput(model: surface, databaseName: shownName) { Task { await read() } }                .voiced(                    drawsFan, typing: $fanTyping, fan: fanNames, show: $fanShow,                    caps: drawsCaps && !DatabaseCapRow.caps(databases).isEmpty)        }    }}/// The shown database's whole name, handed to the page head so the title,/// cap and receipt keep the same name independently of the owner person.private struct ShownDatabaseNameKey: EnvironmentKey {    static let defaultValue: String? = nil}extension EnvironmentValues {    var shownDatabaseName: String? {        get { self[ShownDatabaseNameKey.self] }        set { self[ShownDatabaseNameKey.self] = newValue }    }}/// A record drawn on a board or a data tool's board, opened as ITSELF (S1/// extended): the route that addresses it, or its table's page.enum BoardRecord {    /// The route a record's own screen lives at: its definition's    /// `record_route`, else its table's page (`/lists/[table]/[id]`) — a data    /// tool's row, an alarm. Every record has one, so nothing is ever pushed    /// beside the path, and no table is known here by its id.    static func ownRoute(_ definition: TableDefinition?, id: String) -> Route? {        definition?.recordRoutePattern.flatMap { Route.record($0, id: id) }    }    static func route(table: String, id: String, definition: TableDefinition?) -> Route {        ownRoute(definition, id: id) ?? .tableRecord(table: table, id: id)    }}/// Whether a screen covers Home's board, off the window's path.enum BoardCover {    /// The phone: anything pushed covers it. The Mac's columns: the board is    /// the list column's root, so only a list-tier route covers it — a page    /// opens beside it.    /// A link still arriving covers it too: it is about to open a screen, and    /// the board's read would start a moment before the push.    static func covered(_ path: [Route], columns: Bool, arriving: Bool = false) -> Bool {        arriving || (columns ? path.contains { $0.tier == .list } : !path.isEmpty)    }}/// Me's face as read (`read.you`), observed where it is drawn. Me's page is/// drawn inside the fan's live page, which is `.equatable()` on its tile and/// the tiles (`FanLivePage`): it redraws for what its body observes and never/// for a value a closure captured. Held as view state, a face read — or its/// picture — that landed after the page's first draw was never drawn: the/// head stayed "Me" with a blank picture, or the name with its letter, until/// the next opening (owner's phone, build 288).@MainActor@Observablefinal class HomeRead {    /// The person's name and print; nil until read, when the head draws    /// nothing and the fan card its label alone.    private(set) var face: HomeFace?    /// The print `face` was decoded from; nil for none.    @ObservationIgnored private(set) var print: String?    /// Whether a read of you differs from the face held: another person,    /// name or print, or a print whose picture could not be had last time.    /// A face is a picture of its print, and every decode of the print is a    /// new picture — a new face, which the fan's print of Me's card no    /// longer matches, so Me's card stood blank until it was printed again    /// at every read (295 B, walker294: Me blinking out of the fan while the    /// databases arrived).    func differs(name: String, print: String?, seed: String) -> Bool {        guard let face else { return true }        return face.name != name || face.seed != seed || self.print != print || (print != nil && face.picture == nil)    }    /// The face read, from `print`.    func take(_ face: HomeFace, print: String?) {        self.face = face        self.print = print    }}/// The app's ONE frame — the fan, the caps arc and the record button — and/// where it is drawn: the phone's root, every database, whatever its board.enum DialFrame {    static func draws(root: Bool) -> Bool {        #if os(iOS)        return root        #else        return false        #endif    }    /// The caps arc stands with the fan in Cotton. A business app that shows    /// one database has no caps: nothing to switch to, so nothing is drawn,    /// and the cards close up over the record button (`FanHome.caps`).    static func drawsCaps(fan: Bool, manifest: FlavourManifest?) -> Bool {        fan && manifest?.isSingleDatabase != true    }}