Cotton code
403 lines · 19.2 KB · SwiftRaw
// Home's grid (owner, 12 Oct 2026; architect, 13 Oct 2026): one photographed// tile per view the board places, in Home's order, each opening its view. The// grid never draws a view's records as rows — a tile is its picture, its name// and the figures under it; the notices line is the only thing on Home that// asks for attention.import CottonKitimport CottonValuesimport SwiftUI/// One tile in the grid, and what a tap on it opens.struct GridTile: Identifiable {    enum Opens {        /// A package tool: opens by the one route rule        /// (`BoardLayout.route(for:in:)`).        case dataTool(ToolDefinition)        case tools        /// The owner's own person (`/me`).        case home        /// A view of a tool: a group's list, or the path its definition names.        case route(Route)    }    let key: String    let name: String    /// What the tile shows: the picture its definition names, else the    /// object the app ships for the key.    let picture: ToolPicture?    /// The paper its definition names; nil prints it on the key's default.    var stock: ToolCardTint? = nil    let opens: Opens    /// The tool whose photograph the tile is printed with; nil, its own key.    var wears: String? = nil    var id: String { key }    /// The key `ToolCard` prints by: the tool the tile wears.    var stockKey: String { wears ?? key }    /// The last tile in Home's sideways row: the Tools screen.    static let tools = GridTile(key: "tools", name: "Tools", picture: ToolObjects.picture(for: "tools"), opens: .tools)    /// The first tile on the personal database's Home (owner, 11 Oct 2026):    /// the owner's own person. Cotton has no account, so there is no "You"    /// over anything — the person is their Personal database, and Me is a    /// tile in it. No tool and no arrangement: nobody puts themselves away.    static let home = GridTile(key: "home", name: "Home", picture: nil, stock: .rose, opens: .home)    /// The dial's last card where a flavour names it (`fan.settings`): the    /// settings list — This device (Debug), About — one place reachable from    /// every page by the dial (architect, 22 Oct 2026). Rigby in place of    /// Tools; Cotton after Tools, the same card (the owner, 23 Oct 2026).    static var settings: GridTile {        GridTile(key: "settings", name: ShellLines.line("board", "dial.settings"),                 picture: ToolObjects.picture(for: "settings"), opens: .route(.toolBoard(id: "settings")))    }}extension HomeTiles {    /// One tile per view on Home, in draw order (owner, 12 Oct 2026: a tile    /// points at any view of its tool): each wears its tool's tile from    /// `base` — the tools laid out once — under the view's own name, and opens    /// the view. Me and Tools, which are no views, stand among them by name.    func place(_ base: [GridTile]) -> [GridTile] {        let byKey = Dictionary(base.map { ($0.key, $0) }, uniquingKeysWith: { first, _ in first })        let placed = tiles.compactMap { tile -> GridTile? in            let worn = tile.id == Self.everything ? HomeData.everythingKey : tile.tool            guard let worn else { return nil }            guard let tool = byKey[worn] else {                // A project's section wears a shipped tool's photograph, a tool                // this database need not hold (the section exists because none                // of its tools covers it).                guard Self.section(of: tile.id) != nil, let route = Self.route(of: tile) else { return nil }                return GridTile(                    key: tile.key, name: tile.name ?? worn, picture: ToolObjects.picture(for: worn),                    opens: .route(route), wears: worn)            }            if tile.key == tool.key { return tool }            return GridTile(                key: tile.key, name: tile.name ?? tool.name, picture: tool.picture, stock: tool.stock,                opens: Self.route(of: tile).map(GridTile.Opens.route) ?? tool.opens, wears: tool.stockKey)        }        // The core answers the tiles in their order (alphabetical, always):        // Me first and Tools last stand beside them as the grid draws them.        return base.filter { $0.key == GridTile.home.key } + placed + base.filter { $0.key == GridTile.tools.key }    }    /// The project section and slug a view names — `project/<section>/<slug>`,    /// a section of a project that no tool of the database covers (architect,    /// 13 Oct 2026: the database page draws no list of rows; each section is a    /// tile). Nil for any other view.    static func section(of view: String) -> (ProjectSection, String)? {        let parts = view.split(separator: "/", omittingEmptySubsequences: false)        guard parts.count == 3, parts[0] == "project", !parts[2].isEmpty,              let section = ProjectSections.named(String(parts[1])) else { return nil }        return (section, String(parts[2]))    }    /// Where a table's tile opens, wherever it is drawn — Home, a board:    /// the table's list.    public static func listRoute(forTable table: String) -> Route { BoardLayout.listRoute(forTable: table) }    /// Where a view's tile opens: the path its definition names, its table's    /// list, a project section's own screen, a group's own list; nil opens    /// its tool.    static func route(of tile: HomeTile) -> Route? {        if let opens = tile.opens { return Route.parse(opens) }        if let table = tile.table { return BoardLayout.listRoute(forTable: table) }        if let (section, slug) = section(of: tile.id) { return ProjectSections.route(section, slug: slug) }        let parts = tile.id.split(separator: "/", omittingEmptySubsequences: false)        guard parts.count == 2, !["tool", "ready", "chart"].contains(String(parts[0])), !parts[1].isEmpty else { return nil }        let filter = (try? JSONSerialization.data(withJSONObject: ["group": String(parts[1])])).flatMap { String(data: $0, encoding: .utf8) }        return .tableList(table: String(parts[0]), filter: filter, title: tile.name, query: nil)    }}/// A tool with something current: its tile, its table and what was read.struct BoardSectionItem: Identifiable {    let tile: GridTile    let definition: TableDefinition    let read: ToolTileRead    /// The section draws every record read, not only the current ones — a    /// board's `list` part.    var whole = false    var id: String { tile.key }}/// A section: the heading, the count with its arrow, and the face on the paper./// The heading opens the tool and every slip its record; a slip's check is/// ticked where it lies, as on a list.struct BoardSection: View {    let section: BoardSectionItem    let onOpen: () -> Void    var onToggle: ((TableRecord) -> Void)? = nil    /// A slip opens ITS RECORD wherever it is drawn (S1 extended): nil opens    /// the tool, as the heading does.    var onOpenRecord: ((TableRecord) -> Void)? = nil    @Environment(\.theme) private var theme    var body: some View {        let current = section.read.records        VStack(alignment: .leading, spacing: BoardPageKnobs.boardSectionRowGap) {            if let slips = Self.slips(section.definition, current) {                // A list of records is the project page's section: the first                // three as full slips in their paper, and "n of m" beside the                // heading.                Button(action: onOpen) {                    ProjectSectionHeading(                        title: section.tile.name,                        count: SectionFace.count(shown: min(slips.count, SectionFace.shown), total: section.read.count ?? slips.count))                        // The whole row is the button, the room between the                        // name and the count too.                        .contentShape(Rectangle())                }                .buttonStyle(MotionButtonStyle())                .accessibilityIdentifier("section-\(section.tile.key)")                SectionFace(                    definition: section.definition, records: slips, headed: false,                    onToggle: section.definition.column(section.definition.slip.toggle) == nil ? nil : onToggle,                    onSlip: { record in onOpenRecord?(record) ?? onOpen() })                    .environment(\.linkTitles, section.read.linkTitles)                summary            } else if onOpenRecord != nil, BoardTile.opensRecords(section.definition.tile.face) {                // Covers, polaroids, caps: the heading opens the tool and each                // object opens ITS record (S1 extended) — never one button                // over the lot, which opened the list from a record.                Button(action: onOpen) {                    ProjectSectionHeading(title: section.tile.name, count: section.read.count.map { "\($0)" })                        .contentShape(Rectangle())                }                .buttonStyle(MotionButtonStyle())                .accessibilityIdentifier("section-\(section.tile.key)")                BoardTile(definition: section.definition, records: current, size: .medium, framed: false, onOpenRecord: onOpenRecord)                    .environment(\.linkTitles, section.read.linkTitles)                summary            } else {                Button(action: onOpen) {                    VStack(alignment: .leading, spacing: BoardPageKnobs.boardSectionRowGap) {                        ProjectSectionHeading(title: section.tile.name, count: section.read.count.map { "\($0)" })                        BoardTile(definition: section.definition, records: current, size: .medium, framed: false, onOpenRecord: onOpenRecord)                            .environment(\.linkTitles, section.read.linkTitles)                        summary                    }                    .frame(maxWidth: .infinity, alignment: .leading)                    .contentShape(Rectangle())                    .accessibilityElement(children: .combine)                    .accessibilityLabel(section.tile.name)                }                .buttonStyle(MotionButtonStyle())                .accessibilityIdentifier("section-\(section.tile.key)")            }        }        .frame(maxWidth: .infinity, alignment: .leading)    }    @ViewBuilder private var summary: some View {        if let line = SummaryFigure.line(section.read.summaries, in: section.definition) {            Text(line)                .font(CottonFonts.serif(theme.scale.metaSize + 0.5))                .foregroundStyle(theme.print(.pencil))                .lineLimit(1)        }    }    /// The records a slip section draws, in its list's order with the finished    /// left out; nil for a face that is not a list of slips (covers, people,    /// caps), which keeps its own drawing.    static func slips(_ definition: TableDefinition, _ records: [TableRecord], now: Date = Date()) -> [TableRecord]? {        switch definition.tile.face {        case .slipList: return records        case .sectionList: return records        default: return nil        }    }}/// A sideways deck under Search; the data starts underneath it.struct HomeToolRow: View {    let tiles: [GridTile]    let onOpen: (GridTile) -> Void    @Environment(\.theme) private var theme    var body: some View {        ScrollView(.horizontal) {            HStack(spacing: RecordListSurfaceKnobs.paperGap) {                ForEach(tiles) { tile in                    Button { onOpen(tile) } label: {                        ToolCard(key: tile.stockKey, name: tile.name, picture: tile.picture, stock: tile.stock, width: BoardPageKnobs.boardRowTileWidth)                    }                    .buttonStyle(MotionButtonStyle())                    .accessibilityIdentifier("home-tool-\(tile.key)")                }            }            .padding(.vertical, BoardPageKnobs.boardRowVerticalPadding)        }        .scrollIndicators(.hidden)        .frame(height: ToolCardMetrics(scale: theme.scale).height(width: BoardPageKnobs.boardRowTileWidth)            + BoardPageKnobs.boardRowVerticalPadding + BoardPageKnobs.boardRowVerticalPadding)        .accessibilityIdentifier("home-tools-row")    }}/// A board's `tools` part as a grid: `columns` across, each tile large/// (`.large`, the row's whole photograph) or small (`.small`, a square crop/// of the same photograph). Eager. A/// tool hidden from the fan is drawn grey (`BoardFaint`).struct BoardToolGrid: View {    let tiles: [GridTile]    let columns: Int    let size: BoardToolsSize    /// The tools hidden from the fan, by key (`HomeTiles.hiddenFromFan`).    var faint: Set<String> = []    /// A pencil line under a tile, by key — a table's figures on a tool's    /// board ("3 running"); none on Home.    var captions: [String: String] = [:]    /// What a tile is found by in a walk: Home's `board-tool-<key>`, a tool    /// board's `tool-table-<table>`.    var identifierPrefix = "board-tool-"    let onOpen: (GridTile) -> Void    /// The widest a cell grows, so a wide window does not draw poster-sized tiles.    @Environment(\.theme) private var theme    /// **ONE MEASUREMENT FOR THE WHOLE GRID, and every tile drawn at it.** A    /// tile handed its width takes `ToolCard`'s sized path, which is a picture    /// drawn once and kept (`.drawingGroup()`); a tile left to measure itself is    /// a `GeometryReader` per tile and a tree the compositor re-composites on    /// every frame of every scroll. The five-across grid (10 Oct) handed none,    /// and the scroll jitter over Home's tools came back with it.    @State private var measured: CGFloat?    /// The day's start, not "now": the tiles print the date and nothing finer,    /// and a fresh `Date()` on every body would make every tile a new value,    /// so no tile would ever be skipped when the board redraws.    private var today: Date { Calendar.current.startOfDay(for: Date()) }    var body: some View {        let across = max(1, columns)        let rows = stride(from: 0, to: tiles.count, by: across).map { Array(tiles[$0..<min($0 + across, tiles.count)]) }        let widest = (size == .small ? BoardPageKnobs.boardTileCellWidthSmall : BoardPageKnobs.boardTileCellWidthLarge)        Grid(alignment: .topLeading, horizontalSpacing: RecordListSurfaceKnobs.paperGap, verticalSpacing: RecordListSurfaceKnobs.paperGap) {            ForEach(Array(rows.enumerated()), id: \.offset) { _, row in                GridRow {                    ForEach(row) { tile in cell(tile) }                    // The last row keeps its columns' width.                    ForEach(0..<(across - row.count), id: \.self) { _ in Color.clear.gridCellUnsizedAxes(.vertical) }                }            }        }        .frame(maxWidth: (widest + RecordListSurfaceKnobs.paperGap) * CGFloat(across), alignment: .leading)        .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { width in            let cell = ((width - RecordListSurfaceKnobs.paperGap * CGFloat(across - 1)) / CGFloat(across)).rounded(.down)            if cell > 0, cell != measured { measured = cell }        }        // A container of its own: an identifier on a bare container is handed        // down to every child, and each tool would answer "board-tools-grid".        .accessibilityElement(children: .contain)        .accessibilityIdentifier("board-tools-grid")    }    private func cell(_ tile: GridTile) -> some View {        Button { onOpen(tile) } label: {            VStack(spacing: BoardPageKnobs.boardCaptionGap) {                face(tile)                // The figures under the tile, on the paper — never on the tile.                if let caption = captions[tile.key] {                    // Whole words, cut at a word, never mid-word (the card-text rule).                    Text(measured.map { InkFit.fitting(caption, face: theme.type.title, size: theme.scale.metaSize,                                                       width: $0, lines: 1) } ?? caption)                        .accessibilityLabel(caption)                        .font(theme.type.title(theme.scale.metaSize))                        .foregroundStyle(theme.print(.pencil))                        .lineLimit(1)                }            }            .frame(maxWidth: .infinity)        }        .buttonStyle(MotionButtonStyle())        // One node a tool: the card is an element of its own inside the        // button, and without this both were read (walker pass 4).        .accessibilityElement(children: .combine)        .accessibilityIdentifier(identifierPrefix + tile.key)    }    private func face(_ tile: GridTile) -> some View {            Group {                if size == .small {                    ToolCard(key: tile.stockKey, name: tile.name, picture: tile.picture, stock: tile.stock, now: today, imageVariant: .small, fillsSpace: true)                        .aspectRatio(1, contentMode: .fit)                } else if let measured {                    ToolCard(key: tile.stockKey, name: tile.name, picture: tile.picture, stock: tile.stock, now: today, width: measured)                } else {                    ToolCard(key: tile.stockKey, name: tile.name, picture: tile.picture, stock: tile.stock, now: today)                }            }            .modifier(BoardFaint(faint: faint.contains(tile.key)))    }}/// A tool hidden from the fan: black and white and faint, until it is put on/// the fan again (walker pass 4, 16 Oct 2026 — grey once meant "holds/// nothing", which greyed tools that stood on the fan in colour).struct BoardFaint: ViewModifier {    let faint: Bool    @Environment(\.theme) private var theme    func body(content: Content) -> some View {        content            .grayscale(faint ? 1 : 0)            .opacity(faint ? BoardPageKnobs.faceBoardTileFaintOpacity : 1)    }}/// The database's tools, by key, for what the page draws above the tool/// sections (a project's own sections); nil before Home's read answers them.private struct DatabaseToolsKey: EnvironmentKey {    static let defaultValue: Set<String>? = nil}extension EnvironmentValues {    var databaseTools: Set<String>? {        get { self[DatabaseToolsKey.self] }        set { self[DatabaseToolsKey.self] = newValue }    }}/// A menu the page holds up for something drawn inside it (a project's stack/// button): its tray rises over the WHOLE page, where a tray laid over the/// part that opened it would cover that part alone.@MainActor @Observablefinal class PageMenu {    var items: [PopoverMenuItem] = []    var isOpen = false    func open(_ items: [PopoverMenuItem]) {        self.items = items        isOpen = true    }}private struct PageMenuKey: EnvironmentKey {    static let defaultValue: PageMenu? = nil}extension EnvironmentValues {    var pageMenu: PageMenu? {        get { self[PageMenuKey.self] }        set { self[PageMenuKey.self] = newValue }    }}/// The sizes, counts and timings BoardPage draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum BoardPageKnobs {    static let boardTileCellWidthLarge: CGFloat = 140    static let boardTileCellWidthSmall: CGFloat = 110    static let boardRowTileWidth: CGFloat = 80    static let boardRowVerticalPadding: CGFloat = 4    static let boardSectionRowGap: CGFloat = 8    static let faceBoardTileFaintOpacity: CGFloat = 0.5    static let boardCaptionGap: CGFloat = 4}