Cotton code
774 lines · 32.4 KB · SwiftRaw
// One fan tile's page (lane trail, 15 Oct 2026; the owner ruled the risen// record card read as a sheet; amendments of 13:05, 13:20 and 13:30 IST).// The page above the fan is ONE surface: a record opened from it opens in// place, on the card's own stack (`Navigator.tileStacks`), while the fan and the// record button stand still.//// THE ZOOM. A record grows out of the slip that was tapped and settles into// the page; back shrinks it into that slip — the system's zoom transition, as// Photos and the App Store draw it. The fan owns the sideways axis (sideways is// another tool), so a record never slides in. With no slip on screen (a voice// "open", a restored stack, a jump back several) the page cross-fades, quick// (`fan_open_fade_ms`); Reduce Motion cross-fades everywhere.//// NEVER BLANK. A page is shown only once it has drawn its record: a record// opened by route has no row to draw until it has read one, so the zoom mounts// it unseen, waits for `pageDrawn` (`fan_picture_settle_ms` at the longest,// `DrawnWait`) and only then grows it out of its slip; a cross-fade holds the// leaving page over it the same way (lane zoomframe, 15 Oct 2026).//// BACK is the zoom's own idiom: one small round glass chevron at the left of// the page head, with no words (`TileBackCircle`) — a tap shrinks the record// back into its slip, a long press lists the stack's title lines to jump back// several — and the left-edge swipe, which drags it back interactively. A tap// on the settled fan tile goes back to the tool's own page, which has no// back control.//// Why UIKit: SwiftUI's zoom needs a NavigationStack, and Home already stands in// the app's own; a stack nested in another is not supported. A navigation// controller embedded in the page is UIKit's ordinary containment, and its// zoom is the same transition SwiftUI's wraps.import CottonKitimport SwiftUI#if os(iOS)import UIKitstruct TilePage: View {    /// The fan tile's key: whose stack this page draws.    let key: String    /// The tool's own page, under the first record.    let root: AnyView    /// The tool's own page's title line: the back row's text one step in.    let rootTitle: String    let navigator: Navigator    var body: some View {        TileStackHost(            key: key, root: root, rootTitle: rootTitle, navigator: navigator,            routes: navigator.tileStacks[key] ?? [], titles: navigator.titles)    }}/// The page's slips that open records: where a record's zoom grows from and/// shrinks back to. A slip does not know the route its opener pushes (every/// list's opener says), so the slip a record grew from is the marked slip/// under the finger that just lifted; a record opened with no touch — a voice/// "open", a restored stack — has none, and cross-fades.@MainActorfinal class ZoomSources {    private let slips = NSHashTable<UIView>.weakObjects()    private var grown: [Route: WeakView] = [:]    /// Where and when a finger last came down on the page, in the window.    private var touch: (point: CGPoint, at: Date)?    private struct WeakView { weak var view: UIView? }    /// How long after a touch a record opened is taken as opened by it.    static let touchReach: TimeInterval = 1    func register(_ slip: UIView) { slips.add(slip) }    func touched(at point: CGPoint) { touch = (point, Date()) }    /// The slip `route` grows from: the marked slip under the last touch, if    /// that touch was just now. Kept for its way back.    func source(opening route: Route) -> UIView? {        defer { touch = nil }        guard let touch, Date().timeIntervalSince(touch.at) < Self.touchReach else { return nil }        let under = slips.allObjects.filter { slip in            guard let window = slip.window, !slip.isHidden else { return false }            return slip.convert(slip.bounds, to: window).contains(touch.point)        }        // The innermost slip under the finger: a slip inside a slip is the one tapped.        guard let slip = under.min(by: { $0.bounds.width * $0.bounds.height < $1.bounds.width * $1.bounds.height })        else { return nil }        grown[route] = WeakView(view: slip)        return slip    }    /// The slip `route` grew from, while it is still in the page: what a step    /// back shrinks into once the page beneath stands again.    func held(_ route: Route) -> UIView? { grown[route]?.view }}private struct ZoomSourcesKey: EnvironmentKey {    static let defaultValue: ZoomSources? = nil}extension EnvironmentValues {    /// The slips of the fan tile page a screen stands on (`TilePage`).    var zoomSources: ZoomSources? {        get { self[ZoomSourcesKey.self] }        set { self[ZoomSourcesKey.self] = newValue }    }}private struct ZoomSourceMark: ViewModifier {    @Environment(\.zoomSources) private var sources    func body(content: Content) -> some View {        if let sources {            content.background { ZoomSourceView(sources: sources) }.modifier(UnreadUnderTheFan())        } else {            content.modifier(UnreadUnderTheFan())        }    }}extension EnvironmentValues {    /// Something presented over Home — the Databases sheet — covers every    /// fan tile's pages: none of them is read under it.    @Entry var fanPagesCovered = false}/// An empty view the size of the slip, kept by the page's sources.private struct ZoomSourceView: UIViewRepresentable {    let sources: ZoomSources    func makeUIView(context: Context) -> UIView {        let view = UIView()        view.isUserInteractionEnabled = false        view.backgroundColor = .clear        sources.register(view)        return view    }    func updateUIView(_ view: UIView, context: Context) {}}/// Notes where a finger comes down on the page, and never takes the touch.private final class TouchNote: UIGestureRecognizer, UIGestureRecognizerDelegate {    private let noted: (CGPoint) -> Void    init(_ noted: @escaping (CGPoint) -> Void) {        self.noted = noted        super.init(target: nil, action: nil)        cancelsTouchesInView = false        delaysTouchesBegan = false        delaysTouchesEnded = false        delegate = self    }    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {        if let touch = touches.first, let window = view?.window { noted(touch.location(in: window)) }        state = .failed    }    func gestureRecognizer(_ a: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith b: UIGestureRecognizer) -> Bool { true }}private struct TileStackHost: UIViewControllerRepresentable {    let key: String    let root: AnyView    let rootTitle: String    let navigator: Navigator    let routes: [Route]    let titles: [Route: String]    @Environment(\.self) private var environment    @Environment(\.theme) private var theme    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @Environment(\.fanPagesCovered) private var covered    func makeUIViewController(context: Context) -> TileStack {        TileStack(key: key, navigator: navigator)    }    func updateUIViewController(_ stack: TileStack, context: Context) {        stack.select(key: key)        stack.navigator = navigator        stack.fade = Double(theme.scale[.fanOpenFadeMs]) / 1000        stack.settle = Double(theme.scale[.fanPictureSettleMs]) / 1000        stack.reduceMotion = reduceMotion        stack.covered = covered        stack.update(root: root, rootTitle: rootTitle, routes: routes, titles: titles, environment: environment)    }}/// The card's stack: the tool's own page, then a page for each record.final class TileStack: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {    private(set) var key: String    var navigator: Navigator    var fade = 0.0    /// The longest a cross-fade waits for the record it opens to draw.    var settle = 0.0    var reduceMotion = false    /// A sheet stands over Home: no page of the stack is read under it —    /// SwiftUI's hiding never reaches a UIKit stack (walker pass 4, 16 Oct    /// 2026: Thoughts read under the Databases sheet).    var covered = false {        didSet { if covered != oldValue { readsTop() } }    }    private(set) var sources = ZoomSources()    private let rootHost = UIHostingController(rootView: AnyView(EmptyView()))    private var environment = EnvironmentValues()    private var rootTitle = ""    private var titles: [Route: String] = [:]    /// A record that will grow out of its slip, mounted unseen until it has    /// drawn (`zoomIn`).    private var arriving: RecordHost?    /// What draws a route's page: the route table's (`routePage`) unless    /// this is set — a guard's page that reads and reports drawn as a    /// record's does (`TileStackZoomTests`).    var drawsRoute: ((Route) -> AnyView)?    init(key: String, navigator: Navigator) {        self.key = key        self.navigator = navigator        super.init(nibName: nil, bundle: nil)        rootHost.view.backgroundColor = .clear        rootHost.view.isOpaque = false        viewControllers = [rootHost]        setNavigationBarHidden(true, animated: false)        delegate = self        view.backgroundColor = .clear        view.isOpaque = false    }    @available(*, unavailable)    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }    /// A tool change keeps the controller and root host, dropping only the    /// previous tool's record controllers and zoom sources.    func select(key: String) {        guard self.key != key else { return }        self.key = key        if let arriving {            arriving.willMove(toParent: nil)            arriving.view.removeFromSuperview()            arriving.removeFromParent()            self.arriving = nil        }        sources = ZoomSources()        delegate = nil        setViewControllers([rootHost], animated: false)        delegate = self    }    /// The routes the stack shows, the tool's own page excluded.    var routes: [Route] { viewControllers.compactMap { ($0 as? RecordHost)?.route } }    override func viewDidLoad() {        super.viewDidLoad()        // The edge swipe with no bar shown.        interactivePopGestureRecognizer?.delegate = self        view.addGestureRecognizer(TouchNote { [weak self] in self?.sources.touched(at: $0) })    }    /// The stack's edge swipe steps back a page — unless a layer stands over    /// the page on top, whose own edge swipe closes it.    func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {        guard viewControllers.count > 1 else { return false }        return !((viewControllers.last as? RecordHost)?.layered ?? false)    }    func update(        root: AnyView, rootTitle: String, routes target: [Route], titles: [Route: String], environment: EnvironmentValues    ) {        self.environment = environment        self.rootTitle = rootTitle        self.titles = titles        rootHost.rootView = AnyView(            root.id(key)                .pageSurface()                .modifier(FanGroundReport())                .environment(\.fanLaysGround, environment.fanLaysGround && target.isEmpty)                // Under the shell's writer the page stands still for its                // keyboard: this host lays its content out for one itself.                .deckStillUnderWriter()                .modifier(MeasuresHostTopInset())                .environment(\.tileHere, TileBack(titles: [], key: key, navigator: navigator))                // A layer on the root page is a page over it: the dial folds.                .environment(\.pageLayerShown, { [weak navigator = self.navigator, key = self.key] shown in                    if shown { navigator?.layeredRoots.insert(key) } else { navigator?.layeredRoots.remove(key) }                })                .environment(\.pageOwnTitle, rootTitle)                .environment(\.zoomSources, sources)                .environment(\.self, environment))        for (index, controller) in viewControllers.enumerated() {            if let host = controller as? RecordHost { draw(host, depth: index, under: routes) }        }        if let arriving { draw(arriving, depth: viewControllers.count, under: routes + [arriving.route]) }        move(to: target)    }    /// Brings the stack to `target`: a record opened from a slip on screen    /// zooms out of it, a step back from a zoomed record zooms into its slip,    /// and anything with no slip to grow from cross-fades.    private func move(to target: [Route]) {        let shown = routes        if let arriving {            // Still drawing on its way in; any other path drops it.            if target == shown + [arriving.route] { return }            arriving.view.removeFromSuperview()            self.arriving = nil        }        guard shown != target else { return }        // A change asked for while UIKit moves the stack (its edge swipe, the        // zoom's own pull) is made once that move ends, never dropped: a        // dropped one left a closed page standing, read under the page shown        // (walker pass 3, 16 Oct 2026: Thoughts' cards after a swipe down).        if let transition = transitionCoordinator {            transition.animate(alongsideTransition: nil) { [weak self] _ in                guard let self else { return }                self.move(to: self.navigator.tileStacks[self.key] ?? [])            }            return        }        let way = TileMove.way(from: shown, to: target, sourced: { self.sources.source(opening: $0) != nil },                               zoomed: (viewControllers.last as? RecordHost)?.zoomed ?? false, reduceMotion: reduceMotion)        let kept = TileMove.kept(shown, target)        var hosts = Array(viewControllers.prefix(kept + 1))        for (offset, route) in target.dropFirst(kept).enumerated() {            let host = RecordHost(route: route)            host.view.backgroundColor = .clear            host.view.isOpaque = false            draw(host, depth: kept + offset + 1, under: target)            zooms(host)            hosts.append(host)        }        switch way {        case .zoomIn:            guard let host = hosts.last as? RecordHost else { return }            host.zoomed = true            zoomIn(host)        case .zoomOut:            // The closed page leaves the accessibility tree at once, not            // when the zoom ends.            viewControllers.last?.view.accessibilityElementsHidden = true            popViewController(animated: true)        case .fade:            crossFade(to: hosts)        }    }    /// The record grows out of its slip once it has drawn: until then it    /// stands in the page unseen (alpha 0, under the stack's own pages), so it    /// reads and lays out its record, and the zoom never shows a page with    /// nothing on it. The push moves the same view into the transition, in the    /// same window, so the page keeps what it read.    private func zoomIn(_ host: RecordHost) {        arriving = host        host.view.frame = view.bounds        host.view.alpha = 0        host.view.isUserInteractionEnabled = false        host.view.accessibilityElementsHidden = true        view.insertSubview(host.view, at: 0)        host.drawnWait.then(settle: settle) { [weak self, weak host] in            guard let self, let host, self.arriving === host else { return }            self.arriving = nil            host.view.alpha = 1            host.view.isUserInteractionEnabled = true            host.view.accessibilityElementsHidden = false            self.pushViewController(host, animated: true)        }    }    /// The leaving page stays, as its snapshot, over the arriving one until    /// that one has drawn its record (`pageDrawn`, or `settle` at the    /// longest), then fades out over it: neither page is ever half gone    /// over the bare ground.    private func crossFade(to hosts: [UIViewController]) {        let leaving = view.snapshotView(afterScreenUpdates: false)        setViewControllers(hosts, animated: false)        readsTop()        guard let leaving else { return }        leaving.frame = view.bounds        leaving.isUserInteractionEnabled = false        view.addSubview(leaving)        guard let arriving = hosts.last as? RecordHost else { return reveal(leaving) }        arriving.drawnWait.then(settle: settle) { [weak self, weak leaving] in            if let leaving { self?.reveal(leaving) }        }    }    /// The leaving pages fading out now, each once.    private var fading: Set<ObjectIdentifier> = []    private func reveal(_ leaving: UIView) {        let id = ObjectIdentifier(leaving)        guard leaving.superview != nil, fading.insert(id).inserted else { return }        UIView.animate(withDuration: fade, delay: 0, options: [.allowUserInteraction]) { leaving.alpha = 0 }            completion: { [weak self] _ in                leaving.removeFromSuperview()                self?.fading.remove(id)            }    }    /// The record shrinks back into the slip it grew from, wherever that slip    /// stands when it goes; the edge swipe drives it.    private func zooms(_ host: RecordHost) {        let route = host.route        host.preferredTransition = .zoom { [weak self] _ in self?.sources.held(route) }    }    /// A page's SwiftUI content with the window's environment: the record,    /// its back control, and this page's slips.    private func draw(_ host: RecordHost, depth: Int, under path: [Route]) {        let page: AnyView        if let drawsRoute {            page = drawsRoute(host.route)        } else if let routePage = environment.routePage {            page = AnyView(routePage.draw(host.route))        } else {            return        }        let titles = (0..<depth).map { at in at == 0 ? rootTitle : self.titles[path[at - 1]] ?? rootTitle }        let route = host.route        host.rootView = AnyView(            page                .pageSurface()                .modifier(FanGroundReport())                .environment(\.fanLaysGround, environment.fanLaysGround && depth == path.count)                .deckStillUnderWriter()                .modifier(MeasuresHostTopInset())                .environment(\.tileBack, TileBack.of(titles: titles, key: key, navigator: navigator))                .environment(\.tileHere, TileBack(titles: titles, key: key, navigator: navigator))                .environment(\.pageOwnTitle, self.titles[route] ?? rootTitle)                .environment(\.pageLayerShown, { [weak host] in host?.layered = $0 })                .environment(\.zoomSources, sources)                .environment(\.pageDrawn, { [weak host] in host?.markDrawn() })                .environment(\.self, environment))    }    /// UIKit took a page off itself — the edge swipe, the zoom's pull: the    /// card's stack says so.    func navigationController(_ controller: UINavigationController, didShow shown: UIViewController, animated: Bool) {        readsTop()        let now = routes        if now.count < (navigator.tileStacks[key] ?? []).count { navigator.back(to: now.count, on: key) }    }    func navigationController(_ controller: UINavigationController, willShow shown: UIViewController, animated: Bool) {        readsTop()        // The edge swipe's step back is the card's stack the moment the        // finger lets it go, not when UIKit's slide has finished: the dial        // rises with the page's last slide, in the one motion (home-next row        // 1; walk 16 Oct 2026: Journal's edge swipe left the fan folded about        // a second after the page had gone). A cancelled swipe changes nothing.        guard let transition = controller.transitionCoordinator, transition.isInteractive else { return }        transition.notifyWhenInteractionChanges { [weak self, weak shown] context in            guard let self, let shown, !context.isCancelled,                  let depth = controller.viewControllers.firstIndex(of: shown) else { return }            if depth < (self.navigator.tileStacks[self.key] ?? []).count { self.navigator.back(to: depth, on: self.key) }        }    }    /// One page in the accessibility tree at a time: the top one, and none    /// while a sheet covers Home. The pages under it are read again only    /// when it goes (walker pass 3, 16 Oct 2026: Journal's, News' and Money's    /// lists read behind an open record).    func readsTop() {        for controller in viewControllers {            controller.view.accessibilityElementsHidden = covered || controller !== viewControllers.last        }        // And the stack names its one readable page to the tree reader        // itself: the hidden flag alone did not hold through SwiftUI's bridge        // (walker 298: People's headers, A–Z index and tiles read under a        // person's page; the arc learnt the same, `FanArcView`).        let top = covered ? nil : viewControllers.last?.view        let readable: [Any] = top.map { [$0] } ?? []        if (view.accessibilityElements as? [UIView]) != readable as? [UIView] {            view.accessibilityElements = readable            UIAccessibility.post(notification: .screenChanged, argument: top)        }    }}/// One record's page on the card's stack.final class RecordHost: UIHostingController<AnyView> {    let route: Route    /// It grew from a slip on screen, so a step back shrinks into it.    var zoomed = false    /// A layer a screen opened of its own stands over it (`PageDestination`).    var layered = false    /// What waits on its record being drawn: the zoom that shows it, a    /// cross-fade holding the leaving page.    let drawnWait = DrawnWait()    /// The page has read its record: once that frame is committed, whatever    /// waits on it goes.    func markDrawn() {        DispatchQueue.main.async { [drawnWait] in drawnWait.markDrawn() }    }    init(route: Route) {        self.route = route        super.init(rootView: AnyView(EmptyView()))    }    @available(*, unavailable)    @MainActor required dynamic init?(coder: NSCoder) { fatalError("init(coder:) is not used") }}#endif/// What waits on a page to draw its record (`pageDrawn`): it goes once, when/// the page has drawn or when the settle ceiling has passed, whichever is/// first, and never before either — a page is never shown blank, nor held/// longer than the ceiling.@MainActorfinal class DrawnWait {    private(set) var drawn = false    private var waiting: [Waiter] = []    /// Sleeps out the ceiling; tests hold it.    private let ceiling: @MainActor (Double) async -> Void    private final class Waiter {        var go: (@MainActor () -> Void)?        init(_ go: @escaping @MainActor () -> Void) { self.go = go }        @MainActor func fire() {            guard let go else { return }            self.go = nil            go()        }    }    init(ceiling: @escaping @MainActor (Double) async -> Void = { try? await Task.sleep(for: .seconds($0)) }) {        self.ceiling = ceiling    }    func markDrawn() {        guard !drawn else { return }        drawn = true        let now = waiting        waiting = []        now.forEach { $0.fire() }    }    /// Runs `go` once: now when the page has drawn, else when it does or    /// after `settle` seconds.    func then(settle: Double, _ go: @escaping @MainActor () -> Void) {        guard !drawn else { return go() }        let waiter = Waiter(go)        waiting.append(waiter)        let ceiling = self.ceiling        Task { @MainActor in            await ceiling(settle)            waiter.fire()        }    }}extension View {    /// This is a slip that opens a record: on a fan tile's page, the record    /// grows out of it and shrinks back into it. Elsewhere nothing.    @ViewBuilder func zoomSource() -> some View {        #if os(iOS)        modifier(ZoomSourceMark())        #else        self        #endif    }}/// How the card's stack moves to a new path: what the guards hold.enum TileMove: Equatable {    /// One record, opened from a slip on screen, grows out of it.    case zoomIn    /// One step back from a record that grew from a slip shrinks into it.    case zoomOut    /// Anything else — no slip to grow from, a jump of several, Reduce    /// Motion — cross-fades. Never a slide.    case fade    static func kept(_ shown: [Route], _ target: [Route]) -> Int { zip(shown, target).prefix { $0 == $1 }.count }    static func way(        from shown: [Route], to target: [Route], sourced: (Route) -> Bool, zoomed: Bool, reduceMotion: Bool    ) -> TileMove {        guard !reduceMotion else { return .fade }        let kept = kept(shown, target)        if target.count == shown.count + 1, kept == shown.count, let route = target.last, sourced(route) { return .zoomIn }        if target.count == shown.count - 1, kept == target.count, zoomed { return .zoomOut }        return .fade    }}/// The way back from a page on a page surface: the title lines of the pages/// under it, the tool's own first, and the way back to one. The first/// `routeDepth` are the surface's stack (the navigator steps back), the rest/// layers a screen opened of its own (`PageDestination`), each closed by its/// own close. Compared by its words, its depth and its navigator's identity,/// so the value is the same on every pass and never redraws the page it is/// set on. A tool's own page has none.struct TileBack: Equatable {    let titles: [String]    let key: String    let navigator: Navigator    /// How many of `titles` are the surface's stack.    var routeDepth: Int    /// The closes of the layers over the stack, the lowest first.    var layerCloses: [() -> Void] = []    init(titles: [String], key: String, navigator: Navigator, routeDepth: Int? = nil, layerCloses: [() -> Void] = []) {        self.titles = titles        self.key = key        self.navigator = navigator        self.routeDepth = routeDepth ?? titles.count        self.layerCloses = layerCloses    }    /// Back to the page at `depth`: 0 is the tool's own, one less than    /// `titles.count` is a step back.    @MainActor func back(to depth: Int) {        if depth < routeDepth { navigator.back(to: depth, on: key) }        else if depth - routeDepth < layerCloses.count { layerCloses[depth - routeDepth]() }    }    /// The page's X: one level back — the page shrinks into the slip of the    /// page beneath it, or fades off it, never further.    @MainActor func close() { back(to: titles.count - 1) }    /// The way back of a layer opened over the page `title` names, with this    /// under it.    func adding(title: String) -> TileBack {        TileBack(titles: titles + [title], key: key, navigator: navigator, routeDepth: routeDepth, layerCloses: layerCloses)    }    /// This, for a layer that `close` closes.    func layered(close: @escaping () -> Void) -> TileBack {        TileBack(titles: titles, key: key, navigator: navigator, routeDepth: routeDepth, layerCloses: layerCloses + [close])    }    /// The back control of the page with `titles` under it: none with nothing    /// under it — a tool's own page has no back.    static func of(titles: [String], key: String, navigator: Navigator) -> TileBack? {        titles.isEmpty ? nil : TileBack(titles: titles, key: key, navigator: navigator)    }    static func == (a: Self, b: Self) -> Bool {        a.titles == b.titles && a.key == b.key && a.navigator === b.navigator && a.routeDepth == b.routeDepth            && a.layerCloses.count == b.layerCloses.count    }}private struct PageDrawnKey: EnvironmentKey {    static let defaultValue: (@MainActor () -> Void)? = nil}extension EnvironmentValues {    /// Set on a record drawn on a fan tile's page: the page calls it once    /// everything it draws has been read, so a cross-fade waits for the    /// record rather than dissolving into an empty page.    var pageDrawn: (@MainActor () -> Void)? {        get { self[PageDrawnKey.self] }        set { self[PageDrawnKey.self] = newValue }    }}private struct TileBackKey: EnvironmentKey {    static var defaultValue: TileBack? { nil }}private struct TileHereKey: EnvironmentKey {    static var defaultValue: TileBack? { nil }}extension EnvironmentValues {    /// Where a page stands on its page surface — the pages under it, the    /// tool's own page included — for the layers it opens    /// (`PageDestination`).    var tileHere: TileBack? {        get { self[TileHereKey.self] }        set { self[TileHereKey.self] = newValue }    }    /// Set on a page drawn on a page surface, over the tool's own page:    /// its head's back is `TileBackCircle`, not the push's chevron — unless    /// the screen was presented from inside the page (a sheet), whose own    /// dismiss is its Back.    var tileBack: TileBack? {        get { self[TileBackKey.self] }        set { self[TileBackKey.self] = newValue }    }}/// The zoom's close (part 10, 16:10 IST — the App Store card idiom): one/// small round glass X at the head row's right, no words. A tap closes one/// level — the record shrinks into its slip; a long press lists the stack,/// the newest at the bottom, to jump back several.struct TileBackCircle: View {    let back: TileBack    @Environment(\.cottonHaptics) private var haptics    var body: some View {        Menu {            ForEach(Array(back.titles.enumerated()), id: \.offset) { depth, title in                Button(title) {                    haptics.press()                    back.back(to: depth)                }            }        } label: {            Image(systemName: Glyph.symbol("x") ?? "xmark")                .font(.system(size: NavCircleKnobs.chromeNavGlyphSize, weight: .regular))                .foregroundStyle(NavChrome.glyphInk)                .frame(width: NavCircleKnobs.chromeNavCircleDiameter, height: NavCircleKnobs.chromeNavCircleDiameter)                .glassEffect(.regular.interactive(), in: Circle())                .frame(width: ScreenBarKnobs.chromeNavCircleTarget, height: ScreenBarKnobs.chromeNavCircleTarget)                .contentShape(Rectangle())        } primaryAction: {            haptics.press()            back.close()        }        .menuOrder(.fixed)        .accessibilityLabel(CottonStrings.close)        .accessibilityIdentifier("page-back")    }}/// Each fan tile's stack kept across a relaunch: the scene's own restoration/// (`SceneStorage`), the routes by their paths. A route that no longer parses/// is left out; a record deleted since opens its page's own "not found".enum TileStacks {    /// A card's stack is its database's: the same tool in another database    /// keeps its own.    static func key(database: String?, tile: String) -> String { (database ?? "") + "\u{1F}" + tile }    static func encode(_ stacks: [String: [Route]]) -> String {        let paths = stacks.filter { !$0.value.isEmpty }.mapValues { $0.map(\.path) }        guard let data = try? JSONEncoder().encode(paths) else { return "" }        return String(decoding: data, as: UTF8.self)    }    static func decode(_ text: String) -> [String: [Route]] {        guard let paths = try? JSONDecoder().decode([String: [String]].self, from: Data(text.utf8)) else { return [:] }        return paths.mapValues { $0.compactMap(Route.parse) }.filter { !$0.value.isEmpty }    }}/// Home keeps its cards' stacks in the scene's restoration and puts them back/// once, at launch.struct TileStacksKept: ViewModifier {    let navigator: Navigator?    @SceneStorage("cotton.tileStacks") private var kept = ""    @MainActor static var restored = false    func body(content: Content) -> some View {        content            .task {                guard let navigator else { return }                kept = Self.arrive(navigator, kept: kept, restored: &Self.restored)            }            .onChange(of: navigator?.tileStacks) { _, stacks in                if let stacks { kept = TileStacks.encode(stacks) }            }    }    /// Each time Home comes on screen: the first time in a process it puts    /// the kept stacks back; every later time it keeps what stands now.    /// Home runs this again when a page over the whole of it closes, and the    /// kept text is the one written while the page stood (`onChange` does not    /// run for a Home off screen) — restoring it put the closed page straight    /// back, so its Close did nothing and every relaunch reopened it (294    /// row 5, walker293: Copies opened from Me's sync line).    @MainActor static func arrive(_ navigator: Navigator, kept: String, restored: inout Bool) -> String {        if !restored {            restored = true            if navigator.tileStacks.isEmpty, !kept.isEmpty { navigator.restore(TileStacks.decode(kept)) }        }        return TileStacks.encode(navigator.tileStacks)    }}