// The one stack, as a value every screen can reach. // // Before I2 a screen learned how to navigate by being HANDED closures — an // `onOpen: (Route) -> Void` and an `onBack: () -> Void` threaded through every // initialiser between `RootView` and the row that wanted them (167 `onOpen` // declarations at the count that opened the lane), and the day lane threaded // the path itself as a `@Binding var path: [Route]`. Three spellings of one // fact, and every new screen chose one. // // Now the stack lives HERE and the value travels in the environment: on the // phone each page surface's stack (`tileStacks`), every page opened in place // on it (lane inplace, 16 Oct 2026); on the Mac the columns' `path`. A screen that opens another // says `navigator.push(route)`; a screen that is done says `dismiss()` — the // environment's own, which pops a pushed screen exactly as the system back // does — and the handful that must swap the top rather than grow the stack // (Find opening a place, a note's history redirect) say `replace(with:)`. // // `Route` stays the wire protocol (notifications, deep links); this // class only holds the list of them the stack is showing. // // **`open` is the one entry point a TAP comes through** — a deep link, // Home's New thought pill, ⌘N on the Mac, a held tap // replayed. `push` stays what a screen says to a screen. The two differ over // one thing and it is the reason `open` exists: an `action`-tier route // (`RouteTier`, `CottonMailbox/RouteTier.swift`) is an INSTRUCTION rather than a // screen, so it sets `capture` and pushes nothing. A tap that pushed // `/capture` onto the stack would be a second capture surface over whatever // the person was already reading. import CottonKit import CottonValues import SwiftUI /// How a capture surface opens: listening to the microphone, or with the /// keyboard up. The phone's pill is `.listening` and the Mac's ⌘N is /// `.typing` — a keyboard is already under the hands there. public enum CaptureStart { case listening case typing } /// **What a route that arrived from OUTSIDE does to the path** — a deep link, /// a notification, a held tap replayed at launch. /// /// The one thing `open` must know that differs between the two hosts, and it /// is set by the host rather than read off the platform: `Boot/StackHost.swift` /// leaves the default and `Boot/ColumnsHost.swift` says `.columns`. public enum RouteArrival: Sendable { /// ONE stack, rooted on Home. The route is pushed over whatever is on the /// stack, and capture is a surface HOME draws — so the stack goes back to /// Home before it is raised, or the surface opens behind three screens. case stack /// Mac windows over one path. A link names its list context and page /// (`Route.columnPath`) and replaces the routed path. Capture belongs to /// the board window and leaves child-window destinations intact. case columns } // **Not `final`, for one subclass.** The Mac's list column hands its screens a // `ColumnNavigator` (`Boot/ColumnsHost.swift`) that shares THIS path and // answers `push` by the column's own rule — a record chosen from a list // replaces the record being read rather than stacking on it. Nothing else // subclasses it, and the phone never sees one. @MainActor @Observable public class Navigator { /// The shown fan; editing shells push choices through this same stack. /// Borrowed, never held: FanSurface owns it, and a tier's tap handler /// that reaches this navigator would otherwise hold it in a cycle. weak var fanTiers: FanTiers? /// The Mac's columns: the routed path, root excluded (`ColumnsHost`). /// The phone never pushes, so on the phone it stays empty. public var path: [Route] = [] /// The pages opened in place, per page surface, by its key (lanes trail /// and inplace, 15–16 Oct 2026): each fan tile's page is one surface /// whose history this is, the tool's own page under the first, and a /// phone Home that draws no fan is one more (`rootTile`). The surface /// draws the last of its stack as its page (`TilePage`); nothing on the /// phone is pushed over the whole screen. Kept for every tile while the /// app lives and across a relaunch, so turning back to a tile shows where /// it was left. public private(set) var tileStacks: [String: [Route]] = [:] /// The fan tile whose page is showing, said by Home while it draws a fan /// on the phone; `nil` everywhere else. public var tile: String? /// The phone's page surface when Home draws no fan: the root's own stack. public static let rootTile = "\u{1F}root" /// The page surfaces whose own root page has a layer standing over it (a /// page a screen opened of its own, `PageDestination.swift`), by key. A /// layer is a page like any pushed one: while it stands on the shown /// tile's root the dial folds (`pageOpen`). public var layeredRoots: Set = [] /// Whether a page stands over the shown surface's root: a route on its /// stack, or a layer on its root page. The dial folds while one does. public var pageOpen: Bool { !stack.isEmpty || layeredRoots.contains(tile ?? Self.rootTile) } /// The routes on screen over the root, the top last: on the phone the /// shown page surface's stack (the fan tile's, else the root's), on the /// Mac the columns' path. public var stack: [Route] { get { arrival == .stack ? tileStacks[tile ?? Self.rootTile] ?? [] : path } set { guard arrival == .stack else { path = newValue; return } tileStacks[tile ?? Self.rootTile] = newValue.isEmpty ? nil : newValue } } /// Each record page's title line as its page last drew it (the heading /// of `TableDefinition.headingWords`), by its route: the words a fan /// card's back row says for the page under it. public private(set) var titles: [Route: String] = [:] /// The pages on a stack whose definition carries a composer of its own /// (`TableDefinition.composer`), by their route, as each page said when /// it appeared. public private(set) var composers: Set = [] /// The page at `route` carries a composer, or not. public func carries(composer: Bool, on route: Route) { if composer != composers.contains(route) { if composer { composers.insert(route) } else { composers.remove(route) } } } /// The trays raised on each page, by its route: each tray host says when /// its tray rises and drops (`TrayHost`), so two on one page never undo /// each other. public private(set) var traysUp: [Route: Set] = [:] /// The tray `host` on the page at `route` is raised, or not. public func tray(_ host: UUID, up: Bool, on route: Route) { var hosts = traysUp[route] ?? [] guard up != hosts.contains(host) else { return } if up { hosts.insert(host) } else { hosts.remove(host) } traysUp[route] = hosts.isEmpty ? nil : hosts } /// The page shown carries its own composer: Home puts the fan, the caps /// and the record button away while it stands (lane inplace, 16 Oct /// 2026), and they come back as they were when it closes. public var composerShown: Bool { footHeld(root: nil) } /// The page shown holds its foot — it carries its own composer, or a tray /// is raised on it — so Home puts the fan, the caps and the record button /// away while it does: nothing rises over a tray (walker pass 4, 16 Oct /// 2026: Thoughts' Every act rose under the fan). `root` is the shown /// tile's own page, which no route on the stack names: the page shown /// when nothing stands over it. public func footHeld(root: Route?) -> Bool { guard let shown = stack.last ?? root else { return false } return composers.contains(shown) || traysUp[shown] != nil } /// A record page drew `title` for `route`. public func titled(_ route: Route, _ title: String) { if titles[route] != title { titles[route] = title } } /// Capturing a thought, and how it started; `nil` is not capturing. It is /// deliberately NOT a route: capture is a surface a host draws over what /// is already there, so it has no place on the stack. public var capture: CaptureStart? /// Capture rose over pushed screens: the stack host draws it over them /// and nothing is popped, so closing it leaves the person on the screen /// they raised it from — a Todos group or a record pushed outside `path` /// included (S2; popping to Home and putting back only `path` lost them). public private(set) var captureOverStack = false /// A picture already in the file, waiting for the capture surface to put /// it on a draft — the share sheet's hand-over (`ShareIntake.swift` branch /// 2). Beside `capture` rather than inside `CaptureStart` for the reason /// `capture` is not a route: the START is how the surface opens, and this /// is what it opens holding. A surface already up takes it the moment it /// lands; one that is not takes it on arrival. /// /// Not `private(set)`, for the Mac's column navigator, which forwards it /// to the host navigator with everything else. public var waitingPicture: CapturedPicture? /// The projects the content is narrowed to (Mac redesign spec §4). The /// Mac cap sets it; the phone never does, so there it is always /// `.all`. Like `capture` it is not a route: a filter is a lens over the /// path, and the same list under a different scope is the same place. public var projectScope: ProjectScope = .all /// The project a link asked the database page to show, by slug; the page /// takes it and clears it (`BoardSurface`). public var projectRequest: String? /// **How the host turns an arriving route into a path** (see /// ``RouteArrival``). /// /// The phone's rule is the default and the Mac's host says otherwise — /// **in its `init`, not in a `.task`**, because a route can arrive before /// any host's task has run: a cold launch's deep link is held by /// `PendingTaps` and replayed from `RootView`'s own task, and the two have /// no order between them. A host is BUILT while `RootView.body` is being /// evaluated, which is strictly before either task, so an init is the one /// place the rule is certainly in hand when the first link lands. /// /// No `#if` here on purpose: which host is up is `RootView.hosts`' /// question and `ScreenPlatformSweepTests` holds it to the three files /// that may ask it. public var arrival: RouteArrival = .stack /// **Whether a route has ever arrived from outside.** /// /// The Mac's host selects Todos on launch, because the path is not /// persisted and a list is a better first frame than a restored record /// that has moved — but ONLY when nobody asked for anything else. A link /// delivered before the host's first `.task` ran would otherwise be /// overwritten by that default, and `/home`, whose path is deliberately /// empty (the launcher is never in a path; the list column draws Home when /// the path names no list), would never be Home at all — which is walk-00. public var arrived = false /// What each screen on the path stands for, by its route: the record its /// page shows, and the row last opened from it — so the page pushed over /// it can leave out a link that would only lead back there /// (`TableDefinition.leadsBack`). Not drawn from, so not observed. @ObservationIgnored public var pageShown: [Route: PathRecord] = [:] @ObservationIgnored public var rowOpened: [Route: PathRecord] = [:] /// The row a screen on the path opened, as that screen had already read /// it — the record the page pushed for it is opened with. The page draws /// it on its first frame and reads it again behind it; a page that read /// first stood as bare paper and Close for the second a connection's /// live read takes (walker294 row 40). Nil when no screen opened it. public func openedRow(table: String, id: String) -> TableRecord? { for route in stack.reversed() { if let row = rowOpened[route], row.table == table, row.record.id == id { return row.record } } return rowOpened.values.first { $0.table == table && $0.record.id == id }?.record } /// The records the screen under `route` stands for, while `route` is the /// path's last: its page's record and the row it opened. None off the /// path or over its root. public func beneath(_ route: Route?) -> [PathRecord] { let path = stack guard let route, path.count >= 2, path.last == route else { return [] } let under = path[path.count - 2] return [pageShown[under], rowOpened[under]].compactMap { $0 } } public init() {} /// What is on top, or `nil` at the root. public var top: Route? { stack.last } /// Push a screen. A `launcher` route — `/` or `/home` — is not pushed: /// the root IS Home, so a link to Home goes back to it rather than drawing /// a second one on top. /// A card asked for where the fan stands (a Home card's tap): the fan /// turns to the tool whose deck holds it and that deck opens at it, with /// its chips, its long press and When — never a deck stacked on Home with /// no fan and no way back (real-data walk, 23 Oct). Home's fan sets it; /// it answers false where no tile on the fan holds the table. /// `many`: the record is the first of many brought at once (a Goodreads /// library), and the deck stands on its tool's whole view (`Bringing.many`). @ObservationIgnored public var fanBrings: ((_ table: String, _ id: String, _ many: Bool) -> Bool)? /// Tool arrivals use the same mounted fan page as a tile tap. A cold /// arrival is adopted once the fan has read its tiles. @ObservationIgnored private var waitingFanRoute: Route? @ObservationIgnored var fanOpens: ((Route) -> Bool)? { didSet { guard let fanOpens else { return } if let route = waitingFanRoute { waitingFanRoute = nil if !fanOpens(route) { land(route) } return } let surface = tile ?? Self.rootTile if let route = top, fanOpens(route) { tileStacks[surface] = nil } } } /// The card the deck on the turned-to tile opens at, taken by that deck. public var bringing: Bringing? public struct Bringing: Equatable, Sendable { public let table: String public let id: String /// The first of many records brought at once: the deck of the tool's /// view that reads the table whole (Books' All) takes it, every other /// view's deck turning the ring there first (`DeckSurface.takeBrought`). public var many = false public init(table: String, id: String, many: Bool = false) { self.table = table self.id = id self.many = many } } /// The tile's surface back at its own root page, its stack let go: the /// deck a card is brought to is the one that shows (`fanBrings`), never /// a whole's parts over it. public func standsAtRoot(_ tile: String) { tileStacks[tile] = nil layeredRoots.remove(tile) wholes[tile] = nil } /// THE NESTED FAN (`WholePath`): the wholes each tile's fan stands /// inside, outermost first, by the tile's key. While a tile has one its /// fan holds the last whole's parts and its page deals them. Kept per /// tile while the app lives, as its stack is; never across a launch. public private(set) var wholes: [String: [WholeLevel]] = [:] /// The wholes the shown tile's fan stands inside. public var shownWholes: [WholeLevel] { wholes[tile ?? Self.rootTile] ?? [] } /// The card at the front of a whole's parts deck, as it says it: the /// fan rests on that part. public var partFront: String? /// A whole's card opened on the shown tile: the fan turns into its /// parts, the page deals them, over the tool's own page. public func enter(_ whole: WholeLevel) { let key = tile ?? Self.rootTile tileStacks[key] = nil layeredRoots.remove(key) partFront = nil wholes[key] = WholePath.entering(whole, wholes[key] ?? []) fanTiers?.alignWholes(shownWholes) } /// Out to `depth` wholes on the shown tile (0: the tool's own deck): the /// deck under opens at the card of the whole just left. public func leaveWholes(to depth: Int) { let key = tile ?? Self.rootTile guard let step = WholePath.leaving(wholes[key] ?? [], to: depth) else { return } partFront = nil wholes[key] = step.path.isEmpty ? nil : step.path fanTiers?.alignWholes(shownWholes) bringing = .init(table: step.opensAt.table, id: step.opensAt.id) } /// The hub: one level up; from the top level, out of the whole. public func backWhole() { guard let step = WholePath.back(shownWholes) else { return } leaveWholes(to: step.path.count) } /// Opens a record on its tool's deck where the fan can turn to it, else /// as its page in place. public func open(table: String, id: String, definition: TableDefinition?) { if fanBrings?(table, id, false) == true { return } push(BoardRecord.route(table: table, id: id, definition: definition)) } public func push(_ route: Route) { if route.tier == .launcher { // Home is the database's own page, not a project a link chose. projectScope = .all popToRoot() return } // A project has no screen of its own: its page is the database page // with that project chosen, so a link to one goes home and asks. if case .projectsSlug(let slug) = route { projectRequest = slug popToRoot() return } PageClock.asked(route.path) // The screen already on top is never stacked again (S2): a link, // a notification or a tile opening the list that is showing would // leave Back landing on its copy, which reads as Back doing nothing. // Meetings asked to import or to record, and People asked to import // or to tidy, are the same list with the picker or a sheet up // (`listArrival`). if let top = stack.last { if top == route { return } switch Self.listArrival(of: route, over: top) { case .stays?: return case .replaces?: stack[stack.count - 1] = route return case nil: break } } // The phone opens every page in place, on the shown surface's stack // (`PageOpening`); the Mac's columns stack it on the path. stack = arrival == .stack ? PageOpening.opening(route, on: stack) : stack + [route] } /// What a route to a list that raises flows does to that list already /// standing. enum ListArrival: Equatable { /// It takes the top's place. case replaces /// Nothing: a sheet is up over the list and stays up. case stays } /// **A list is ONE list, whatever it was opened for.** Meetings plain, /// with the importer up (`?import=1`), or with the recorder up /// (`/meetings/record`, the list's "Record a meeting" act); People plain, /// or with the import up (`/people/import`) — the list's "Import /// contacts". So a route to the same list takes the top's place /// rather than standing on it, and the act raises its sheet over the list /// it was chosen on. /// /// **Except over a sheet that is up.** It is never replaced by a link (a /// notification, the + fan, a tile opening the list): the /// list is already under it, and replacing the entry would tear down the /// sheet the microphone is being driven from, or the one changing the /// address book's cards. Leaving it is the sheet's own close /// (`MeetingListFlow`, `PeopleListFlow`). /// /// `nil` when the two are not the same list: the ordinary push. static func listArrival(of route: Route, over top: Route) -> ListArrival? { guard let list = top.raisingList, route.raisingList == list else { return nil } return top.raisesSheet ? .stays : .replaces } /// Open a route that came from a TAP rather than from a screen. /// /// An `action`-tier route is an instruction: it raises capture mode. On the /// phone over Home itself, Home draws it; over pushed screens the stack /// host draws it OVER them (`captureOverStack`) — from ANY caller (a pushed /// list's "New thought", a Home tile, a deep link) — and nothing is /// popped, so closing it leaves every screen where it was. The Mac's /// columns draw it in place. /// /// Everything else is the host's own rule (``land``): the phone pushes over /// the stack, and the Mac replaces the path with the columns the route /// names, so a link to a record opens the list it belongs to AND the /// record. /// /// A capture opened while a picture is waiting opens TYPING, whatever the /// caller asked: the person has just chosen what the thought is about, and /// a microphone switched on over it is a surprise, where a keyboard under /// the picture is the next move. public func open(_ route: Route, start: CaptureStart = .listening) { arrived = true if route.tier == .action { captureOverStack = arrival == .stack && tileStacks[Self.rootTile] != nil capture = waitingPicture == nil ? start : .typing return } if arrival == .stack { // Keep Home mounted until its fan can place a cold list arrival. // Pushing first prevents the root hosting controller from ever // appearing, so its fan cannot register an arrival handler. if fanOpens == nil, route.tier == .list { waitingFanRoute = route return } if fanOpens?(route) == true { return } } land(route) } /// Hold a picture for the capture surface. A second one before the first /// was taken replaces it: one share is one landing, and the surface opens /// on the latest, which is what sharing them in that order meant. public func hold(picture: CapturedPicture) { waitingPicture = picture } /// Once: the dock that takes it owns it from here. public func takeWaitingPicture() -> CapturedPicture? { defer { waitingPicture = nil } return waitingPicture } /// Where a non-action arrival LANDS — the host's rule, and the one thing /// a subclass changes. /// /// The phone pushes it over the stack. The Mac replaces the path with the /// columns the route names, so a link to a record opens the list it /// belongs to AND the record, and a link to a list becomes the list /// column's root rather than a screen pushed over the Todos the launch /// selected. The Mac's LIST column navigator overrides it back to a push /// (`Boot/ColumnsHost.swift`): a tap handed to a screen inside the list window is /// that window's own, and replacing the whole path from inside it would /// throw away the list the screen is standing in. func land(_ route: Route) { if case .projectsSlug = route { push(route); return } // A sheet that is up over its list is never replaced, by any host's rule. if let top = stack.last, Self.listArrival(of: route, over: top) == .stays { return } if route.tier == .launcher { projectScope = .all } switch arrival { case .stack: push(route) case .columns: path = route.columnPath } } /// Capture is over — kept or discarded, the surface comes down. The host /// that drew it files the thought; this only puts the flag back. /// Out of capture. Unless `restoring` is false — a kept thought's receipt /// still to show where it was kept — the layer over the stack comes down /// too, and the person is on the screen they raised it from. public func closeCapture(restoring: Bool = true) { capture = nil if restoring { captureOverStack = false } } /// Step back one page. public func pop() { if !stack.isEmpty { stack.removeLast() } } /// A card's page goes back to the page at `depth` on its stack: 0 is the /// tool's own page, one less than the stack's count a step back (the /// back control, its long-press list, the left-edge swipe, the settled /// card's tap). The shown card's unless another is named. public func back(to depth: Int, on key: String? = nil) { let key = key ?? tile ?? Self.rootTile guard let stack = tileStacks[key], depth >= 0, depth < stack.count else { return } tileStacks[key] = depth == 0 ? nil : Array(stack.prefix(depth)) } /// The stacks as they stood when the app last ran (`TileStacks`): each /// card's, as it was left. Never a page over the whole Home (the root's /// stack): a launch lands on Home's settled card, and a page restored /// over all of it is a page nobody opened this launch (294 row 5). public func restore(_ stacks: [String: [Route]]) { tileStacks = stacks.filter { !$0.value.isEmpty && $0.key != Self.rootTile } } /// Swap the top screen for another rather than pushing over it — what /// `router.replace` meant: a search that opened a place three times leaves /// three places behind and not three searches, and a stack of peer /// surfaces would be a history nobody made. At the root, a push. public func replace(with route: Route) { if stack.isEmpty { stack = [route] } else { stack[stack.count - 1] = route } } /// A left database must not supply routes or drafts to the next one. public func resetForDatabaseChange() { waitingFanRoute = nil fanOpens = nil captureOverStack = false path.removeAll() tileStacks.removeAll() wholes.removeAll() partFront = nil capture = nil waitingPicture = nil projectScope = .all projectRequest = nil } /// Back to the root. The fan tiles' own stacks are kept: each tile is /// where it was left. public func popToRoot() { path.removeAll() tileStacks[Self.rootTile] = nil } } /// One record a screen on the path stands for, with its table /// (`Navigator.pageShown`, `Navigator.rowOpened`). public struct PathRecord: Hashable, Sendable { public var table: String public var record: TableRecord public init(table: String, record: TableRecord) { self.table = table self.record = record } } extension Route { /// The lists one route can stand for, opened plain or with a flow up. fileprivate enum RaisingList { case meetings case people } /// Which of them this route is: the Meetings list, opened plain, to /// import, or to record; the People list, opened plain, to import or to /// tidy. fileprivate var raisingList: RaisingList? { switch self { case .meetings, .meetingsRecord: return .meetings case .people, .peopleImport: return .people default: return nil } } /// The list with a sheet up over it — what no link replaces. fileprivate var raisesSheet: Bool { switch self { case .meetingsRecord, .peopleImport: return true default: return false } } }