Cotton code
231 lines · 10.9 KB · SwiftRaw
// The board both hosts draw (rebuild note 7b95efa4, "Surfaces": "Home is a// board with capture and search in the cap"). The phone roots its stack on it// (`Boot/RootView.swift`); the Mac's main window is it (`Boot/ColumnsHost.swift`).// ONE source and one view: the tools in the Home order, the projects, what is// asked of the owner, what Cotton did and the notices all come from the one// `HomeModel` read, and both hosts build the board through this type and never// `BoardSurface` directly (`HomeBoardNoLossTests` holds both to that).//// What the hosts still decide, as arguments: where a table opens (the phone// pushes its tool's route; the Mac opens its list window), and the search.// A route opens through `Navigator.open`, whose rule is each host's own. A host that hands// in its own search (the Mac's toolbar) filters the tiles with it; with none,// the cap's search is the GLOBAL search, and while it holds words its results// take the tiles' place — the same `SearchResults` the old Home put in place.//// THREE SCREENS, ONE BUILDER (design note 26203e21): Home, the Tools screen and// the database page are each a board — `BoardSurface` over the screen's board// row (`BoardModel`, `definitions.board`) — and each is built here, over the// same `HomeModel` read. Home is the stack's root and carries the input box;// the Tools screen and the database page are pushed over it.import CottonKitimport SwiftUIpublic struct HomeBoard: View {    private let home: HomeModel    private let databaseName: String?    /// Whether the shown database is personal, for its available tools.    private let personal: Bool    private let suppliedProject: Binding<String?>?    private let suppliedQuery: Binding<String>?    private let onOpenTableOverride: ((TableDefinition) -> Void)?    private let now: Date    /// The screen's board: "home", "tools" (the Tools screen) or "database"    /// (the database page). Home is the stack's root; the other two are pushed.    private let boardId: String    @Environment(Navigator.self) private var navigator: Navigator?    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    @Environment(DatabasesModel.self) private var databases: DatabasesModel?    @Environment(\.cottonCore) private var core    @Environment(\.cottonSync) private var sync    @Environment(\.tableDefinitions) private var definitions    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(\.scenePhase) private var scenePhase    @State private var localProject: String?    /// Search's brain, built once (a model made in a body is a new model on    /// every redraw) — only when the host hands in no search of its own.    @State private var find: SearchModel?    /// The screen's board, read from the database (`BoardModel`); nil until    /// the core is in hand, and this build's own board is drawn meanwhile.    @State private var boardModel: BoardModel?    /// What a board pushed over Home draws: the core's answer for it.    @State private var pushed: PushedBoardParts?    /// - Parameters:    ///   - home: the one read every part of the board draws from.    ///   - databaseName: what this database is called, for a join request.    ///   - project: the switcher's choice; the board keeps its own when nil.    ///   - query: the host's own search, which filters the tiles; nil makes the    ///     cap's search the global one.    ///   - onOpenTable: where a tile opens; nil opens its tool's own route.    ///   - board: the screen's board id — "home", "tools", "database".    public init(        home: HomeModel,        databaseName: String? = nil,        personal: Bool = true,        project: Binding<String?>? = nil,        query: Binding<String>? = nil,        onOpenTable: ((TableDefinition) -> Void)? = nil,        now: Date = Date(),        board: String = BoardDefinition.home.id    ) {        self.boardId = board        self.home = home        self.databaseName = databaseName        self.personal = personal        self.suppliedProject = project        self.suppliedQuery = query        self.onOpenTableOverride = onOpenTable        self.now = now    }    private var project: Binding<String?> { suppliedProject ?? $localProject }    /// The shown database as the window's calls name it ("" the personal    /// one), once the held list has named it; nil until then. A host with no    /// databases model has the one.    private var shownCalls: String? {        guard let scene, let databases else { return "" }        let shown = home.shownDatabase(scene: scene, in: databases)        return shown.known ? shown.database ?? "" : nil    }    /// The global search's words, through the one model.    private var globalQuery: Binding<String> {        Binding(get: { find?.query ?? "" }, set: { find?.type($0) })    }    private var query: Binding<String> { suppliedQuery ?? globalQuery }    /// Home is the root of its stack; the Tools screen and the database page    /// are pushed over it.    private var root: Bool { boardId == BoardDefinition.home.id }    public var body: some View {        BoardSurface(            project: project,            // The shown database's own order, resolved for it in this frame            // (`HomeModel.drawnTiles`): its answer, kept answer or shelf —            // never an order of the app's own.            arrangement: home.drawnTiles(scene: scene, in: databases),            query: root ? query : nil,            projects: home.switcherProjects,            databaseName: databaseName,            personal: personal,            board: boardModel?.board ?? BoardDefinition.shipped(boardId),            entries: root ? home.answer?.parts.board ?? [] : pushed?.parts ?? [],            home: BoardHome(                model: home, databaseName: databaseName, project: chosenProject, now: now,                onLeaveProject: { project.wrappedValue = nil }),            title: boardId == BoardDefinition.tools.id ? ToolsBoardWords.title : nil,            root: root,            everyTool: boardId == BoardDefinition.tools.id,            menu: [],            results: results,            onOpenTable: openTable        )        .environment(\.currentProject, project.wrappedValue)        // The screen's board, read as it shows and for each database the        // window turns to, and again when a fold names the board rows.        .task(id: scene?.shownId) {            guard let core else { return }            let model = boardModel ?? BoardModel(boards: CoreBoards(core: core), id: boardId)            boardModel = model            await model.load()            guard !root else { return }            let parts = pushed ?? PushedBoardParts { [home, boardId] in await home.boardParts(boardId) }            pushed = parts            await parts.load()        }        .rereading { families in            let board = boardModel?.reread(families)            let parts = pushed?.reread(families)            guard board != nil || parts != nil else { return nil }            return Task {                await board?.value                await parts?.value            }        }        // The splash comes down as the board shows — but not over the        // phone's Home, whose fan takes it down once Home is read and stands        // whole (`FanLaunch`, 295 B).        .onAppear { if !DialFrame.draws(root: root) { hideSplashOnce() } }        // Read as it shows — but a switch has just read the database it        // turned to (`HomeModel.prepare`), and that read is this one. At a        // launch, not before the held list names the database shown: the        // window's calls name the personal one until it does, and on a phone        // reopened on another database that read was thrown away while the        // shown one waited behind it. The read follows the naming        // (`shownCalls`' task below, and the calls' aim, `WindowSession`).        .task {            guard shownCalls != nil else { return }            await home.loadUnlessPrepared()        }        // An answer read for another database than the one shown (the calls        // were aimed after the read went out), or none yet (a launch, once        // the held list names the shown database), is read for this one.        .task(id: [shownCalls ?? "unnamed", home.answeredFor ?? "personal"]) {            guard let shownCalls else { return }            await home.readAgainIfAskedElsewhere(shown: shownCalls.isEmpty ? nil : shownCalls)        }        .refreshable { await home.load() }        .task {            if root, suppliedQuery == nil, find == nil, let core { find = SearchModel(core: core) }        }        // The device rows are read once per foreground, and there is no poll.        // Home's notices alone draw them.        //        // The serving Mac's backup is asked on the same beat, beside them:        // a dead off-Mac copy is a notice the owner sees on coming back to        // the phone, and Home's own read never waits on the Mac for it.        .task(id: scenePhase) {            guard root, scenePhase == .active else { return }            await home.readBackup()        }        // A write this device made to a table a tile counts reads the board        // again, so the tile's count is the database's after a delete (S6) —        // only then: a fold (another device, a database switch) never does        // (architect 2335 item 6: no re-read storm).        .onChange(of: sync?.localWrites) { _, _ in            guard let sync, HomeData.tileReads(sync.localWrote) else { return }            Task { await home.load() }        }    }    /// The global results in the tiles' place while the global search holds words.    private var results: SearchResults? {        guard suppliedQuery == nil, let find, !find.query.isEmpty else { return nil }        return SearchResults(model: find)    }    /// The switcher's project as the read knows it, for the link to its page.    private var chosenProject: (name: String, slug: String)? {        guard let id = project.wrappedValue,              let record = home.switcherProjects.first(where: { $0.id == id }),              let slug = record["slug"].text        else { return nil }        return (record["name"].text ?? slug, slug)    }    /// A route opens through the navigator's one door for a tap: the phone's    /// host pushes it, the Mac's opens the window it names (`Navigator.open`).    private func openRoute(_ route: Route) {        navigator?.open(route)    }    /// A tile opens its tool's home table by the one route rule    /// (`BoardLayout.route(forTable:)`): the screen the table's definition    /// names (`/todos`), else its list's route (`BoardLayout.listRoute`).    private func openTable(_ definition: TableDefinition) {        if let onOpenTableOverride { return onOpenTableOverride(definition) }        openRoute(BoardLayout.route(forTable: definition))    }}/// The Tools screen's words.enum ToolsBoardWords {    static let title = "Tools"}