Cotton code
1675 lines · 87.2 KB · SwiftRaw
// Home as a fan of tiles (lane fan, 14 Oct 2026; decision "Home becomes a fan// of tiles with a voice-first button", the owner's go at 19:05 IST). On the// phone Home is two things top to bottom, on every database, whatever its// board (the dial is chrome, 16 Oct 2026: `DialFrame`)://// 1. THE PAGE of the settled tile, full width and scrollable — the same//    surface that draws that tile's view when it is opened (`RoutePage`), or,//    for the first tile, Home's own board (head, notices, the tile grid).// 2. THE FAN: every Home tile is a tile on an arc whose pivot sits below the//    screen (`FanGeometry`). The settled tile stands upright at the centre and//    lifts; its neighbours lean away. A swipe turns the fan and the spring//    snaps it to a tile; a tap on a tile turns to it. Its page is already//    the page; a record opened from it turns that page to the record in//    place, on the tile's own stack, and a tap on the settled tile goes//    back to the tool's own page (lane trail; `PageOpening`).//// Exactly one page is live, and only once the fan rests on a// tile; while it turns the page area shows the nearest tile's PICTURE, kept// for every tile and drawn off screen while the window is still// (`PagePictures`), crossfading as tiles pass.//// The order is the board's arrangement — the person's own — and never use: a// fan learnt by position must not reorder itself under the finger (architect).// Every number is a theme key (`scale.tokens.fan_*`).import CottonKitimport CottonVoiceimport CottonValuesimport SwiftUI/// One tile of Home's.struct FanTile: Identifiable, Equatable {    let key: String    let name: String    let picture: ToolPicture?    let stock: ToolCardTint    /// Me's card: the person's print in the object's place.    var face: HomeFace? = nil    /// The screen families its page draws, so a change stales its picture    /// only when it shows that change; nil when not known (any change).    var families: Set<ScreenFamily>? = nil    /// Its page is its own tile drawn large (`FanPoster`), not a list: no    /// picture is painted for it, and while the fan turns it shows as a    /// ghost (`FanGhost`).    var poster = false    /// Its page is a list its views ring (`shell.fan`'s `ringed`).    var ringed = false    var id: String { key }    /// The tile as the fan draws it: Home's own tile (`ToolCard` — the    /// object on its dyed stock, the rule, the name in the double-line    /// frame), at `width`. A fan tile and a Home tile differ only in size and    /// lean (owner, 14 Oct 2026): the fan has no face, label or frame of its    /// own.    func printed(width: Double, current: Bool = false) -> ToolCard {        ToolCard(key: key, name: name, picture: picture, stock: stock, width: CGFloat(width), face: face, current: current)    }}/// How a route draws as a page inside Home's fan: the screen the stack would/// push for it — the route table's own (`RouteScreen`), over the stack's/// deps, set by the stack's host (`StackHost`). A host that sets none draws/// Home's board in its place.@MainActorstruct RoutePage {    let deps: RouteDeps    func draw(_ route: Route) -> RouteScreen { RouteScreen(route: route, deps: deps) }}private struct RoutePageKey: EnvironmentKey {    static let defaultValue: RoutePage? = nil}extension EnvironmentValues {    var routePage: RoutePage? {        get { self[RoutePageKey.self] }        set { self[RoutePageKey.self] = newValue }    }}/// The words the fan says.enum FanWords {    /// The title of a stack's root that is no tile's own page.    static let home = "Home"}#if os(iOS)/// The page over the fan. Exactly one live page is mounted, and only once the/// fan rests on a tile (`FanPageRule`); while it turns the page/// area shows the nearest tile's picture (`PagePictures`), crossfading as/// tiles pass. The live page is taken as its own picture once it has stood/// still, so a finger landing on the fan costs nothing.struct FanHome: View {    let tiles: [FanTile]    /// The page of tile `index`.    let page: (Int) -> AnyView    /// The fan is put away under Home's thought field while it types.    var tucked = false    /// What the shown tile's page stands at: its tool's own page or a record    /// opened on it. A new one is a page turned in place: its picture is    /// stale and its scroll is watched, the fan left as it stands.    var stands = FanPageStand()    /// The tile the fan rests on, by its key, as it comes to rest.    var settles: (String) -> Void = { _ in }    /// A tap on the settled tile: its page goes back to the tool's own.    var toRoot: () -> Void = {}    /// The database shown: the tiles' stacks are keyed by it (`TileStacks.key`).    var database: String?    /// A spoken "show …": the key of the tile to turn to, cleared once turned.    var show: Binding<String?>?    /// The Home board holds the `databases` part: the caps' arc stands under    /// the tiles' (`DatabaseCapArc`), turned with them out of the way.    var caps = false    /// The record button's toast (`FanRecord`): drawn in the page region,    /// its foot one caps gap above the fan's top.    var toast: FanToast?    /// The session's collapse (`FanCollapse`): while the page is read the    /// arcs fold into the record button's circle.    var collapse = FanCollapse.session    /// The tiles are the database's own answer: until then its page is not    /// the page yet.    var ready = true    /// The shown database's Home read has come back — answered, refused or    /// waiting on its arriving copy (`HomeModel.readShown`): at a launch the    /// splash stands until it has (`FanLaunch`).    var read = true    /// The tile the fan opens at: its centre — Me.    var opens = 0    /// A page stands over the shown tile's own: the dial is collapsed.    var pageOpen = false    /// No record button stands under this fan (a customer's shell,    /// `CustomerShell`), so a card edited on it has no close in the    /// button's place: the close (`FanClose`) stands just above the    /// fan instead. Without it a customer's Book fan, once up, never went    /// (the walk of 24 Oct 2026).    var closesEdits = false    /// Cotton pages cross a UIKit stack; customer pages are direct SwiftUI.    var hostedPages = false    /// Home shares this box with the microphone inset outside the fan.    var shellCover: FanCover? = nil    /// The fan as the core answers it (`shell.fan`), for the database    /// shown; nil for a fan whose tiles are another's (a customer's shell,    /// `CustomerShell`), which rings no views.    var fan: ToolViews? = nil    /// A card edited in place: while it stands the fan's arc holds that    /// card's values, not the tools (cardtrial CT3, `EditingFan`).    private var editor: DeckEditor { .session }    /// The wholes the shown tile's fan stands inside: while there is one    /// the arc holds its parts, not the tools (`WholeFan`).    @Environment(Navigator.self) private var navigator: Navigator?    /// Home's search, where this fan stands on Home (`voiceSearch`).    @Environment(\.voiceSearch) var voiceSearch    /// A spoken command, from the hub's mic while the fan stands open: the    /// words go to the universal search, and the record they name opens.    @State private var command: VoiceSession?    private var wholes: [WholeLevel] { navigator?.shownWholes ?? [] }    /// The tools are off the arc: a card's values or a whole's parts stand    /// there, or the fan's root is its one tool's views (`shell.fan`).    private var toolsAway: Bool { editor.isEditing || !wholes.isEmpty || tiers.closes || rootViews != nil }    /// A tier stands on the shared arc in the tools' place.    private var tierStands: Bool { tiers.closes || rootViews != nil }    @Environment(\.theme) private var theme    @Environment(DatabaseScene.self) private var scene: DatabaseScene?    /// Each database's pictures, kept over a switch (`StalePages`).    @Environment(StalePages.self) private var stale: StalePages?    @Environment(\.cottonHaptics) private var haptics    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @Environment(\.self) private var environment    @State private var motion: FanMotion?    @State private var pictures: PagePictures?    /// The database this fan was built for: a fan still standing for a    /// frame after the window turned never marks the new one's page live on    /// the switch's timeline.    @State private var builtFor: String?    @State private var ownPrints = FanTilePrints()    /// The tiles' prints, the window's own (`StalePages.prints`): the same    /// cards on every database, so a switch's fan stands whole in its first    /// frame rather than printing every card in sight again first.    private var prints: FanTilePrints { stale?.prints ?? ownPrints }    @Environment(\.displayScale) private var displayScale    @Environment(\.recordsRevision) private var revision    @Environment(\.cottonCore) private var core    @Environment(\.records) private var tierRecords    @Environment(\.cottonSync) private var sync    @Environment(\.tableDefinitions) private var definitions    @Environment(\.toolDefinitions) private var dataTools    /// Tool photographs asked for, so each is loaded once (`photographReady`).    @State private var photographsAsked: Set<String> = []    /// The page area beside the standing fan — the page runs on under the    /// fan to the foot of Home — as the live page lays itself out in it: its    /// frame in the window and the safe-area insets that reach out of it.    @State private var region = PageRegion()    /// The page area in the window as it stands now, the fan standing or    /// not: where the scroll watch finds the page. A fan built while folded    /// (a database switch under the circle) never measured `region`, and its    /// watch found nothing, so no scroll bloomed it (walker pass 3).    @State private var watchArea = CGRect.zero    /// The page area's height now, the fan standing or not, for its edge.    @State private var pageHeight = 0.0    /// The caps' arc's own height, under the tiles while they stand.    @State private var capsHeight = 0.0    /// A fan with no answer of the core's (a customer's shell) rings nothing.    @State private var ownViews = ToolViews()    /// Each tool's views and the one its ring chose, for the database shown.    private var toolViews: ToolViews { fan ?? ownViews }    @State private var tiers = FanTiers()    /// Counts taps on the open tool's card: each draws its page afresh, at    /// the top of its default view, as tapping a selected tab does.    @State private var fresh = 0    /// Starts the painter again: a change, new tiles, the fan at rest.    @State private var paint = 0    /// Where the bloomed fan covers the page (`FanCover`), handed to the    /// pages once; a fold changes only its edge.    @State private var ownCover = FanCover()    private var cover: FanCover { shellCover ?? ownCover }    /// The two arcs' own height, as they stand.    @State private var arcsHeight = 0.0    /// The keyboard is up: the fan goes, so the page and the field have the room.    @State private var keyboardUp = false    @State private var scrollWatch = FanScrollWatch()    /// The tile whose live page has drawn a frame.    @State private var drawnLive: String?    /// The tile the fan last came to rest on, kept by key: a change of tiles    /// moves the fan with it (`FanPageRule.rest`).    @State private var restsOn: String?    /// The fan is not standing: tucked, under the keyboard, or folded into    /// the circle. Pictures are kept at the full fan's page size, so nothing    /// is drawn or measured meanwhile.    private var fanDown: Bool { tucked || keyboardUp || (collapse.collapsed && !editor.isEditing) }    /// Folded into the circle, and not put away (`FanRoom.folded`): a scale    /// and an opacity on the arcs, never a frame.    private var folded: Bool { FanRoom.folded(collapsed: collapse.collapsed && !editor.isEditing, tucked: tucked, keyboardUp: keyboardUp) }    /// The room the tiles take (`FanRoom.deck`).    private var deckHeight: Double {        FanRoom.deck(height: geometry.height, tucked: tucked, keyboardUp: keyboardUp)    }    /// The caps' arc stands: the tiles have their whole room.    private var capsStand: Bool { FanRoom.caps(natural: 1, deck: deckHeight, height: geometry.height) > 0 }    /// The arcs hang below the fan's foot, beside the record button, unless    /// the fan slides away (tucked, under the keyboard). A fold is not a    /// slide: the arcs shrink into the circle whole, and a clip that turned    /// flat as the fold began cut every outer tile and cap at the band for    /// the length of the fold and the bloom (smooth, 16 Oct 2026).    private var hangs: Bool { capsStand }    /// The fan's room over the band now (`FanRoom.page`): where the toast    /// stands. Never the page's inset — the page's inset is the band alone.    private var room: Double {        FanRoom.page(height: geometry.height, caps: caps ? capsHeight : 0, tucked: tucked, keyboardUp: keyboardUp)    }    /// The standing fan's room over the band: where its cover of the page    /// begins and the page's pictures end, whatever the fan is doing now.    private var standingRoom: Double {        FanRoom.page(height: geometry.height, caps: caps ? capsHeight : 0, tucked: false, keyboardUp: false)    }    /// How small the arcs grow as they fold: to the circle's width.    private var foldScale: Double {        max(Double(scale[.fanCollapsedSize]) / max(Double(region.frame.width), 1), 0.01)    }    /// The folded arcs meet the hub without changing the page's inset.    private var circleAnchor: UnitPoint {        guard arcsHeight > 0 else { return .bottom }        return UnitPoint(x: 0.5, y: geometry.hub(width: 0, diameter: Double(scale[.fanRecordSize])).y / arcsHeight)    }    private var scale: ThemeScale { theme.scale }    /// The page area's picture region in the window: all the live page    /// draws (`PageRegion.drawn`, from the window's top) down to the standing    /// fan's top — what the fan covers is never a page's picture.    private var area: CGRect {        let drawn = region.drawn        let height = Double(region.insets.top) + Double(region.frame.height) - standingRoom        return CGRect(origin: drawn.origin, size: CGSize(width: drawn.width, height: max(0, height)))    }    private var geometry: FanGeometry { FanGeometry(scale: theme.scale).withHub(diameter: Double(scale[.fanRecordSize])) }    /// The tool whose views tier was opened over the tools.    @State private var openedViews: String?    /// The fan's one tool, whose views are its root (`shell.fan`'s    /// `opens`); nil when the root is the tools.    @State private var rootViews: String?    /// The tool whose views tier stands: the one opened, or the root's.    private var viewsTool: String? { openedViews ?? rootViews }    private var keys: [String] { tiles.map(\.key) }    private var posters: Set<String> { Set(tiles.filter(\.poster).map(\.key)) }    @State private var turn = FanPageTurn()    private var fanLayout: some View {        ZStack(alignment: .bottom) {            if let motion, let pictures {                // The page area runs to the band, folded or not, and its                // scroll on under the band to the foot of the screen: ONE                // bottom inset, the band's, whether the fan stands or folds                // (architect's ruling 01:30 IST 17 Oct 2026, 291 row F). The                // standing fan lies over the page's foot; a fold is a scale                // and an opacity on the fan, so the list is never laid out                // again in a fold's spring.                // The tile the fan rests on, else the one it opens at: the same                // read as `tiles`, so a launch's page is its own from the first frame.                FanPageArea(tiles: tiles, motion: motion, fresh: "\(database ?? "")\u{1F}\(fresh)", rests: restsOn ?? (tiles.indices.contains(opens) ? tiles[opens].key : nil),                            pictures: pictures, turn: turn, cover: cover, page: { framed($0, laysGround: true) }) { drawnLive = $0 }                    .frame(maxWidth: .infinity, maxHeight: .infinity)                    .measuresPageRegion { measured in                        pageHeight = measured.frame.height                        watchArea = measured.frame                        // A fold moves nothing here; a fan put away under                        // the keyboard only lends the page its room a while.                        guard !FanRoom.putAway(tucked: tucked, keyboardUp: keyboardUp) else { return }                        region = measured                    }                // The page (including a deck's face ground) reaches the foot.                // Catch taps between standing tiles without painting over it.                Color.clear                    .frame(height: max(room, 0))                    .contentShape(Rectangle())                    .allowsHitTesting(!fanDown)                    .ignoresSafeArea(.container, edges: .bottom)                    .accessibilityHidden(true)                // The fan over the page's foot: the tiles' arc, the caps' under it.                VStack(spacing: 0) {                    FanDeck(tiles: tiles, motion: motion, geometry: geometry, prints: prints, reduceMotion: reduceMotion,                            onGrab: grab, onHold: { index in                                openViews(of: tiles[index].key)                                return true                            }) { index in                        haptics.press()                        tiers.activate(tiles[index].key, centred: tiles[motion.settled].key) { id in                            if let at = keys.firstIndex(of: id) { prepareTurn(to: at) }                        }                    }                    .overlay {                        if keys.indices.contains(motion.settled), !toolsAway {                            let tool = keys[motion.settled]                            FanPeekLayer(next: nextViews(of: tool), owner: tool, motion: motion, geometry: geometry) {                                tiers.choose(tool)                            }                        }                    }                    // Its top edge is kept as its room closes: the tiles slide                    // down out of the screen, clipped at the record button.                    // Only the deck's room and its fading animate: an                    // animation on the whole deck moved every card with it                    // when an arrangement changed in the same update — the                    // switch's re-deal, cards flying past (294 row 2).                    .animation(.easeOut(duration: Double(theme.scale[.fanTurnMsMin]) / 1000)) {                        $0.frame(height: deckHeight, alignment: .top)                            .opacity(deckHeight == 0 ? 0 : 1)                    }                    .allowsHitTesting(deckHeight > 0)                    .fanArcHidden(deckHeight == 0)                    // A higher tier replaces the tools on the shared arc.                    .scaleEffect(toolsAway && !reduceMotion ? 0.28 : 1, anchor: tierAnchor)                    .opacity(toolsAway ? 0 : 1)                    .allowsHitTesting(!toolsAway)                    .fanArcHidden(toolsAway)                    .overlay(alignment: .top) {                        if let open = tiers.open, tierStands, deckHeight > 0 {                            FanTierArc(tier: open, geometry: geometry, tiers: tiers,                                       onSettle: { card, chose in                                           if open.id.hasPrefix("whole-") { tiers.raise(card.id) }                                           // A swipe that comes to rest on a view shows it, as a tap                                           // on the centred card does; the fan stays open to browse.                                           if let tool = viewsTool, ViewTier.choosesOnRest(tier: open.id, viewsTool: tool, chose: chose) {                                               toolViews.choose(card.id, of: tool)                                           }                                       })                                .holding { card in                                    // One of Send's people held: what the core says a hold on them offers (Always keep from them).                                    if case .send(let person)? = card.item?.does, let hold = person.holds.first, let trust = hold.trust,                                       let target = editor.target {                                        let (core, toasts) = (core, toasts)                                        editor.offer([DeckOffer(id: hold.id, word: hold.words) { _ in                                            await SendCenter.session.trust(trust, core: core, toasts: toasts)                                        }], for: target)                                        return true                                    }                                    guard let tool = viewsTool, open.id == ViewTier.id(of: tool),                                          let view = toolViews.views(of: tool).first(where: { $0.id == card.id }) else { return false }                                    // A list's tile held: the list's own acts, as its deck offers them.                                    if view.group != nil {                                        openListActs(tool: tool, view: view)                                        return true                                    }                                    guard let target = SettingsRing.exports(tool: tool, view: view) else { return false }                                    editor.openExports(target, record: nil)                                    return true                                }                                .id(open.id)                                .transition(.scale(scale: reduceMotion ? 1 : 0.28, anchor: tierAnchor).combined(with: .opacity))                        }                        if editor.isEditing { EditingFan(editor: editor, fan: geometry) }                    }                    .animation(.easeOut(duration: Double(theme.scale[.fanTurnMsMin]) / 1000), value: editor.isEditing)                    .animation(.easeOut(duration: Double(theme.scale[.fanTurnMsMin]) / 1000), value: wholes)                    if caps {                        // About the tiles' pivot; it goes with them when the fan                        // is put down and comes back with them.                        let standing = capsStand                        // ONE gap on both sides of it (owner, 16 Oct 2026 18:30                        // IST): `fan_caps_gap` under the raised card's foot (the                        // tiles' band, `FanGeometry.band`) and the same over the                        // record button. In front of                        // everything — every cap, the new-or-join cap at its end                        // too, takes its tap (owner's rule 8).                        DatabaseCapArc(fan: geometry, above: geometry.height)                            .padding(.bottom, theme.scale[.fanCapsGap])                            // Its own height, read while it stands at it.                            .onGeometryChange(for: Double.self, of: { Double($0.size.height) }) { height in                                if standing, height > 0 { capsHeight = height }                            }                            // Not clipped: the caps either side lean down                            // beside the record button, as the tiles do.                            .frame(height: standing ? nil : 0, alignment: .top)                            .opacity(standing ? 1 : 0)                            .allowsHitTesting(standing)                            .fanArcHidden(!standing)                            .animation(.easeOut(duration: Double(theme.scale[.fanTurnMsMin]) / 1000), value: standing)                    }                }                .onGeometryChange(for: Double.self, of: { Double($0.size.height) }) { arcsHeight = $0 }                // Folded: both arcs shrink into the circle and fade into it,                // drawn from their pictures — with Reduce Motion they only                // fade. They stand where they stood: a scale and an opacity,                // never a frame, so the fold lays nothing out.                .scaleEffect(folded && !reduceMotion ? foldScale : 1, anchor: circleAnchor)                .opacity(folded ? 0 : 1)                .allowsHitTesting(!folded)                .fanArcHidden(folded)                // The toast after the words are taken, at the toast edge:                // the top of the screen, never over the fan, the hub or the                // mic (the owner, 17 Nov 2026), as every receipt stands.                if let toast = commandToast ?? toast {                    FanVoiceLine(toast: toast)                        .fixedSize(horizontal: false, vertical: true)                        .atToastEdge()                        .transition(.opacity)                }                GeometryReader { proxy in                    let hub = geometry.hub(width: proxy.size.width, diameter: Double(scale[.fanRecordSize]))                    ZStack {                        Group {                            if editor.isEditing {                                FanClose(size: scale[.fanRecordSize], acts: editor.openedTarget == nil && editor.holdsActs) { editor.close() }                            } else if tiers.closes {                                FanClose(size: scale[.fanRecordSize], acts: true) { popTier() }                            } else {                                switch FanButton.of(editing: editor.isEditing, inWhole: !wholes.isEmpty) {                                case .closesEdit:                                    FanClose(size: scale[.fanRecordSize], acts: editor.openedTarget == nil && editor.holdsActs) { editor.close() }                                case .closesWhole:                                    FanClose(size: scale[.fanRecordSize], acts: true) { navigator?.backWhole() }                                case .fan where rootViews != nil && !collapse.collapsed:                                    // No tools tier under the root's views: the X closes the fan.                                    FanClose(size: scale[.fanRecordSize], acts: true,                                             close: { collapse.fold(animation: FanCollapse.animation(scale, reduceMotion: reduceMotion)) },                                             identifier: "fan-hub")                                case .fan:                                    let open = !collapse.collapsed && !collapse.ringTucked                                    Button {                                        // The fan open, the hub is its mic: a tap                                        // speaks a command, a tap again ends it.                                        // Folded, it blooms the fan as it always has.                                        if open { commandTapped() } else { collapse.tapped(animation: FanCollapse.animation(scale, reduceMotion: reduceMotion)) }                                    } label: {                                        ZStack {                                            Circle().fill(command?.phase == .listening ? theme.colors.accent.color : NavChrome.circleFill)                                                .frame(width: scale[.fanRecordSize], height: scale[.fanRecordSize])                                                .softShadow()                                            if open {                                                Image(systemName: command?.phase == .listening ? "mic.fill" : "mic")                                                    .font(.system(size: scale[.fanRecordSize] * 0.32, weight: .medium))                                                    .foregroundStyle(command?.phase == .listening ? theme.colors.accentContrast.color : NavChrome.glyphInk)                                            }                                        }                                    }                                    .buttonStyle(MotionButtonStyle())                                    .accessibilityLabel(Text(verbatim: open ? command?.line(command?.phase == .listening ? "listening" : "command_hint") ?? VoiceLines.line("command_hint") : FanWords.home))                                    .accessibilityValue(Text(verbatim: String(describing: command?.phase ?? VoiceSession.Phase.idle)))                                    .accessibilityIdentifier("fan-hub")                                }                            }                        }                        .scaleEffect(FanHub.foldScale(collapsed: folded, scale: scale))                        .position(hub)                    }                }                .frame(height: geometry.height)                .padding(.bottom, caps ? capsHeight + Double(scale[.fanCapsGap]) : 0)                .opacity(tucked || keyboardUp ? 0 : 1)                .allowsHitTesting(!(tucked || keyboardUp))            } else {                Color.clear            }        }    }    private var tieredFan: some View {        fanLayout        .animation(.easeOut(duration: Double(scale[.fanTurnMsMin]) / 1000), value: toast)        .animation(.easeOut(duration: Double(scale[.fanTurnMsMin]) / 1000), value: editor.isEditing)        .environment(\.deckEditor, editor)        // The fan put away, a page opened or another tool settled: an edit        // left open is closed, never carried to another card.        .onAppear { editor.connect(tiers) }        .onChange(of: fanDown) { _, down in if down { editor.close() } }        .onChange(of: pageOpen) { _, _ in editor.close() }        .onChange(of: restsOn) { _, _ in editor.close() }        .onChange(of: wholes, initial: true) { _, path in tiers.alignWholes(path) }        .background {            if !wholes.isEmpty { WholeFan(path: wholes, fan: geometry, tiles: toolViews.answer?.tiles.compactMap(\.tile) ?? []) }        }        // Launch: the splash (the logo on the paper, `SplashOverlay`) stands        // until Home is read and stands whole under it — the read come back,        // the settled card's page drawn, every card in sight printed — and        // then goes in one frame, so the first frame seen is the whole Home        // at full (295 B, walker294). Once a process; the window's ceiling        // (`FanLaunch.waitOutCeiling`) takes it down if Home never stands.        .onChange(of: read, initial: true) { _, read in if read { SwitchClock.mark("home-read", SwitchClock.launch) } }        .onChange(of: launchStands, initial: true) { _, stands in if stands { FanLaunch.stand() } }        // A new picture region stales every picture drawn at the old size.        .onChange(of: area.size) { _, size in            guard size.width > 0, size.height > 0 else { return }            pictures?.resized(to: size)            paint += 1        }        // A fan sliding away goes out under the record button; a standing        // one's outer caps and tiles hang down beside it, whole (FanBandTests).        .clipShape(FanFootClip(hangs: hangs))        .onAppear { start() }        // The ring's choices are the shown database's.        .onChange(of: scene?.shownId, initial: true) { _, shown in            toolViews.show(shown)            while tiers.closes { tiers.pop() }            openedViews = nil        }        // One read of the fan per state: the database, the tile it stands        // on (whose views are counted, live even while the deck stays put),        // a view chosen, a change of data or of definitions. A window whose        // shown database is not known yet holds no copy to read: the fan is        // first asked when it is, of that database (`ToolViews.reload`).        .task(id: ToolViews.Reading(database: scene?.shownId, focus: tierStands ? viewsTool : restsOn,                                    chosen: toolViews.chosen, revision: revision, definitions: definitions.stamp)) {            guard let fan, scene == nil || scene?.shownId != nil else { return }            do { try await fan.reload(core: core, database: scene?.shownId, standing: tierStands ? viewsTool : restsOn) }            catch { if !Task.isCancelled { unreadFan() } }        }        .onChange(of: toolViews.answer) { _, _ in refreshViews() }        .onChange(of: toolViews.chosen) { _, _ in refreshViews() }        .onChange(of: tiers.open?.id) { _, _ in refreshViews() }        .onChange(of: tiers.depth) { _, _ in collapse.swipedUp(animation: tierAnimation) }        .environment(toolViews)        .environment(tiers)        .onChange(of: tiles, initial: true) { _, _ in standRoot() }        .animation(tierAnimation, value: tiers.depth)        .animation(tierAnimation, value: tiers.open?.id)    }    private var observedFan: some View {        tieredFan        .onChange(of: ready, initial: true) { was, ready in            if ready, !was {                // The database's own tiles: the fan stands at their centre.                restsOn = nil                motion?.recount(keys.count)                motion?.turn(to: opens, animated: false)                SwitchClock.markDrawn("arranged", scene?.shownId)                // Its live page may be taken as its picture now.                paint += 1            }            standLive()        }        .onChange(of: drawnLive) { _, _ in standLive() }        // A tile drawn anew (Me's print arriving): its picture again, and the        // painter started over on the new tiles — one still holding the old        // ones would draw the old tile back over the new.        .onChange(of: tiles) { _, _ in            paint += 1            DispatchQueue.main.async { drawPrintsInSight() }        }        .onChange(of: keys) { _, keys in            motion?.recount(keys.count)            // The fan stays on the tile it rested on, wherever the change put            // it — Me, at launch — never on whatever card took its slot.            if let motion, !motion.moving {                let at = FanPageRule.rest(on: restsOn, keys: keys, opens: opens)                if at != motion.settled { motion.turn(to: at, animated: false) }                // The navigator names the tile shown, always: a page opened                // meanwhile — a deep link, a notification — lands on the                // stack of the card under the finger, never on one the                // fan left (sharing2, 16 Oct 2026: a deep link folded the                // dial over Documents and its page drew nowhere).                if keys.indices.contains(motion.settled) { settles(keys[motion.settled]) }            }            pictures?.keepOnly(keys)            prints.keepOnly(tiles)            drawPrintsInSight()            paint += 1            turnToShown()        }        // The tile the fan heads for — known as the finger lifts — is        // decoded first, then its neighbours.        .onChange(of: motion?.heading) { _, heading in            guard let pictures, let heading else { return }            pictures.refocus(keys: keys, settled: heading)        }        .onChange(of: motion?.settled, initial: true) { _, settled in            paint += 1            // The tiles now in sight drawn, a turn without a finger (the            // fan opening on Me) included.            DispatchQueue.main.async { drawPrintsInSight() }            if let settled, keys.indices.contains(settled) {                // At rest: nothing decoded outside its reach stays.                pictures?.refocus(keys: keys, settled: settled)                turn.didSettle(on: keys[settled])                restsOn = keys[settled]                settles(keys[settled])            }        }        // The shown page turned in place: its picture is of the page before.        .onChange(of: stands) { old, new in            if FanPageStand.changedPage(from: old, to: new) != nil, let liveKey { pictures?.invalidate(key: liveKey) }            paint += 1        }        // A spoken "show …" stands the fan up and turns it to the tile.        .onChange(of: show?.wrappedValue) { _, _ in turnToShown() }        // At a cold launch the fan settles before the shown database is known:        // the navigator's tile is named again under the database's key, or a        // page opened on Home lands on a stack its ✕ does not close.        .onChange(of: database) { _, _ in            if let motion, keys.indices.contains(motion.settled) { settles(keys[motion.settled]) }        }        .onChange(of: theme.scale) { _, scale in            motion?.geometry = geometry            motion?.spring = FanSpring(scale: scale)        }        // A tile's picture is of the tile in this theme: another draws them again.        .onChange(of: theme) { _, _ in            prints.clear()            drawPrintsInSight()            paint += 1        }        // A photograph arrived — its bytes, or a package's picture as the        // tool asset rows a sync brings: a card printed without it is        // printed again with it.        .onMediaArrival { reprintBare() }        .onChange(of: sync?.toolPackagesRevision) { _, _ in reprintBare() }        // A switch's fan stands on the window's prints: a bare one is asked        // again now, not at the next arrival.        .onChange(of: scene?.shownId, initial: true) { _, _ in reprintBare() }        // A change of data makes the pictures that draw it stale; they are        // drawn again at the next still window, and shown until then.        .rereading { families in            pictures?.invalidate(families)            paint += 1            return nil        }        // Other table definitions read: a page pictured under the ones before        // is drawn again (a table defined since refused there).        .onChange(of: definitions.stamp, initial: true) { _, stamp in            guard let stamp else { return }            pictures?.invalidate(definitions: stamp)            paint += 1        }        .onChange(of: turn.key) { _, key in if key == nil { paint += 1 } }        .task(id: paint) { await painting() }        // The live page's scroll: a finger scrolling down folds the fan into        // the circle, a finger scrolling up blooms it (`FanCollapse`). A new        // page, or one turned in place, is watched afresh and the fan is        // left as it is: the collapse is the session's, not the page's.        .task(id: [liveKey ?? "", stands.path, FanRoom.putAway(tucked: tucked, keyboardUp: keyboardUp) ? "away" : "",                   watchArea.isEmpty ? "" : "measured"]) {            await watchScroll()        }        .onChange(of: collapse.collapsed) { _, collapsed in if !collapsed { haptics.select() } }        .onChange(of: standingRoom, initial: true) { _, room in cover.scrollClearance = room }        .onChange(of: coverEdge, initial: true) { _, edge in cover.edge = edge }        .onChange(of: standingEdge, initial: true) { _, edge in cover.standingEdge = edge }        .onDisappear { scrollWatch.stop() }    }    var body: some View {        observedFan        // The shell's short-text input rides the keyboard over the dimmed        // page (`DeckWritingLayer`): the fan stands under the dim as it was.        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in            guard editor.writing == nil else { return }            keyboardUp = true            cover.keyboardUp = true        }        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in            keyboardUp = false        }        // Down only once it is gone, so the deck's card never measures the        // page in the keyboard's last frames.        .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardDidHideNotification)) { _ in            cover.keyboardUp = false        }        .onChange(of: fanDown) { _, down in if !down { paint += 1 } }        // A page opened over the tile's own folds the dial; its close blooms        // it in the same frame (`FanCollapse.page`).        .onChange(of: pageOpen, initial: true) { _, open in            collapse.page(open: open, animation: FanCollapse.animation(theme.scale, reduceMotion: reduceMotion))        }        .task { if FanPictureCheck.asked { await checkPictures() } }        // A container of its own, so the tiles keep their identifiers.        .accessibilityElement(children: .contain)        .accessibilityIdentifier("home-fan")    }    private func start() {        SwitchClock.mark("fan", scene?.shownId)        let scale = theme.scale        let motion = self.motion ?? FanMotion(            geometry: geometry, spring: FanSpring(scale: scale))        motion.onCross = { [haptics] in haptics.select() }        motion.recount(tiles.count)        if self.motion == nil, ready { motion.turn(to: opens, animated: false) }        self.motion = motion        // The tiles in sight are drawn the frame after the fan appears, the        // rest in the still windows that follow.        DispatchQueue.main.async { drawPrintsInSight() }        if pictures == nil {            let make = {                PagePictures(                    quality: Double(scale[.fanPictureQuality]), reach: scale.count(.fanPictureReach),                    scale: Double(scale[.fanPictureScale]))            }            // The database's own, kept over a switch: its last pages show at once.            pictures = scene?.shownId.flatMap { shown in stale?.pictures(of: shown, make: make) } ?? make()            builtFor = scene?.shownId        }        turnToShown()    }    /// Home is read, its settled card's page drawn and every card in sight    /// printed (`FanLaunchRule.stands`).    private var launchStands: Bool {        guard let motion else { return false }        let settled = motion.settled        return FanLaunchRule.stands(            read: read,            settledDrawn: keys.indices.contains(settled) && drawnLive == keys[settled],            printsInSight: tiles.indices.allSatisfy { index in                Double(abs(index - settled)) * geometry.step >= geometry.visible || prints.picture(of: tiles[index]) != nil            })    }    /// The settled tile's live page has drawn, arranged: it is the page.    private func standLive() {        guard ready, let motion, let drawnLive, keys.indices.contains(motion.settled), keys[motion.settled] == drawnLive,              builtFor == scene?.shownId        else { return }        SwitchClock.markDrawn("live", scene?.shownId)    }    /// Draws the pictures of the tiles the fan shows now that have none.    private func drawPrintsInSight() {        guard let motion else { return }        let geometry = geometry        for (index, tile) in tiles.enumerated()        where Double(abs(index - motion.settled)) * geometry.step < geometry.visible && photographReady(tile) {            // The settled tile's current print too, so the fan stands on it            // from its first frame.            for current in FanCurrentPrint.kinds(theme) where (!current || index == motion.settled)                && prints.picture(of: tile, current: current) == nil {                prints.draw(tile, current: current, width: geometry.tileWidth,                            scale: Double(displayScale) * geometry.settledScale, environment: environment)            }        }    }    /// A card whose picture is a photograph the database holds — a package's    /// tool — is printed once its photograph is decoded: a print is one    /// synchronous render that runs no task, and the card printed before    /// stood without its picture for as long as it stood (292, walker292:    /// Disk and Quotas blank on the real household; the Tools page, drawn    /// live, showed them). The photograph is loaded here, then the card    /// printed; one that cannot be had is printed without it.    private func photographReady(_ tile: FanTile) -> Bool {        guard theme.family == .paper, case .photo(let reference) = tile.picture,              ToolPhotographs.image(reference) == nil else { return true }        if photographsAsked.contains(reference) { return !ToolPhotographs.loading(reference) }        guard let core else { return true }        photographsAsked.insert(reference)        // Loading from the ask, not from when the task starts: a second look        // in between read "asked, not loading" as done and printed the card        // bare (308, Disk: asked 31.478, printed bare 31.852, load began 31.865).        ToolPhotographs.ask(reference)        let pixels = Int((geometry.tileWidth * Double(displayScale) * geometry.settledScale).rounded())        Task {            await ToolPhotographs.load(reference, core: core, maxPixel: pixels)            paint += 1            drawPrintsInSight()        }        return false    }    /// The cards printed without their photograph — its bytes not yet on    /// this device when the card was printed (a package's picture on a phone    /// still fetching it) — asked for again and printed again once it is    /// decoded (308: Disk, Notebook, Quotas and Subscriptions bare on the fan    /// for good, while the Tools page, drawn live, drew them on arrival). An    /// arc tile keeps its print until the new one is drawn, so nothing blinks.    /// Asked or not by this fan: a switch's fan stands on the window's prints    /// (`StalePages.prints`), bare ones included.    private func reprintBare() {        let bare = tiles.filter { tile in            guard case .photo(let reference) = tile.picture else { return false }            return !ToolPhotographs.loading(reference) && ToolPhotographs.image(reference) == nil        }        guard !bare.isEmpty else { return }        for tile in bare { if case .photo(let reference) = tile.picture { photographsAsked.remove(reference) } }        let keys = Set(bare.map(\.key))        prints.keepOnly(tiles.filter { !keys.contains($0.key) })        drawPrintsInSight()        paint += 1    }    /// Turns to the tile a spoken "show …" named. A tile not on the fan yet    /// — another database's, chosen in the same line ("open notes on Tin    /// Factory"), whose tiles are still being read — waits for them.    private func turnToShown() {        guard let key = show?.wrappedValue, let motion, let index = keys.firstIndex(of: key) else { return }        show?.wrappedValue = nil        motion.turn(to: index, animated: !reduceMotion)    }    private func prepareTurn(to index: Int) {        guard let motion, keys.indices.contains(index) else { return }        let source = turn.snapshot ?? PagePictures.snapshot(area, page: hostedPages ? TileStacks.key(database: database, tile: liveKey ?? "") : nil)        guard let source else { return }        let key = keys[index]        let duration = reduceMotion ? 0.2 : geometry.turnDuration(degrees: Double(index) * geometry.step - motion.theta)        turn.prepare(key: key, snapshot: source, duration: duration) { reading in            cover.lay(reading)            motion.turn(to: index, animated: !reduceMotion)        }    }    private func nextViews(of tool: String) -> FanTier? {        let views = toolViews.views(of: tool)        guard !views.isEmpty else { return nil }        return ViewTier.make(tool: tool, views: views, current: toolViews.current(of: tool)?.id, tile: toolViews.tile(tool)?.tile)    }    /// The tool's views tier over the tools; its counts come with the read    /// the fan makes standing on it.    private func openViews(of tool: String) {        collapse.swipedUp(animation: tierAnimation)        openedViews = tool        guard toolViews.tile(tool)?.ringed == true else { return }        let tier = ViewTier.make(tool: tool, views: toolViews.views(of: tool), current: toolViews.current(of: tool)?.id, tile: toolViews.tile(tool)?.tile)        withAnimation(tierAnimation) {            tiers.push(tier) { card in toolViews.choose(card.id, of: tool) }        }    }    /// The fan that could not be read, said in its words.    private func unreadFan() {        _ = toasts?.show(ShellLines.line("reading", "list.could_not_read", ["plural": FanWords.home]), tone: .error)    }    /// A list's tile held on the lists tier: the fan becomes the list's own    /// acts (`tools.acts {held: list}`), run as its deck runs them.    private func openListActs(tool: String, view: ToolView) {        let table = view.read.table        Task { @MainActor in            let answer = await DeckEditor.toolActsAnswer(of: table, view: "\(tool)/\(view.id)", held: .list, core: core)            editor.openToolActs(answer.actions, for: .emptyDeck(of: table), tile: answer.tile)        }    }    /// The fan's first tier as the core answers it: its one tool's views    /// (Cotton Books), else its tools.    private func standRoot() {        if let answer = toolViews.answer, answer.opensOnViews, let tool = answer.opens.tool {            rootViews = tool            tiers.setRoot(ViewTier.make(tool: tool, views: toolViews.views(of: tool), current: toolViews.current(of: tool)?.id, tile: toolViews.tile(tool)?.tile)) { card in                toolViews.choose(card.id, of: tool)            }        } else {            rootViews = nil            let tier = FanTier(id: toolViews.answer?.root.id ?? FanTiers.toolsTier,                               cards: tiles.map { .init(id: $0.key, label: $0.name, picture: $0.picture, style: .object) },                               raised: restsOn ?? toolViews.answer?.root.raised)            tiers.setRoot(tier) { card in openViews(of: card.id) }        }        SwitchClock.mark(rootViews == nil ? "root-tools-\(tiles.count)" : "root-views", SwitchClock.launch)        navigator?.fanTiers = tiers    }    private func refreshViews() {        // The fan's root came, or changed: it stands anew.        let answeredRoot = toolViews.answer?.opensOnViews == true ? toolViews.answer?.opens.tool : nil        if answeredRoot != rootViews || rootViews != nil { return standRoot() }        guard let tool = viewsTool, tiers.open?.id == ViewTier.id(of: tool) else { return }        let tier = ViewTier.make(tool: tool, views: toolViews.views(of: tool), current: toolViews.current(of: tool)?.id, tile: toolViews.tile(tool)?.tile)        guard tier != tiers.open else { return }        tiers.replaceOpen(tier) { card in toolViews.choose(card.id, of: tool) }    }    private var tierAnchor: UnitPoint {        UnitPoint(x: 0.5, y: geometry.hub(width: 0, diameter: Double(scale[.fanRecordSize])).y / max(geometry.height, 1))    }    private var tierAnimation: Animation {        let spring = FanSpring(scale: scale)        return reduceMotion ? .linear(duration: 0.01) : .spring(response: min(spring.response, 0.34), dampingFraction: spring.damping)    }    private func popTier() {        collapse.swipedUp(animation: tierAnimation)        withAnimation(tierAnimation) {            if tiers.open?.id.hasPrefix("whole-") == true { navigator?.backWhole() }            else { _ = tiers.pop() }        }    }    /// A finger landed on the fan: the live page is snapshotted as it stands    /// and put in its own place in the same frame — what the turn starts from    /// IS the page, so nothing moves when it is swapped (owner, build 280: the    /// title dropped and a band showed). The render server makes the copy;    /// the main thread draws nothing as a finger lands.    private func grab() {        turn.cancel()        guard !fanDown, let motion, let pictures, case .live(let index) = motion.shows,              tiles.indices.contains(index),              let shot = PagePictures.snapshot(area, page: hostedPages ? TileStacks.key(database: database, tile: keys[index]) : nil)        else { return }        pictures.grab(shot, for: keys[index])    }    /// The live page's tile, while one is live.    private var liveKey: String? {        guard let motion, case .live(let index) = motion.shows, tiles.indices.contains(index) else { return nil }        return tiles[index].key    }    private func watchScroll() async {        collapse.watching()        scrollWatch.stop()        // Put away — a page's own composer, the keyboard — the page's scroll        // never folds or blooms the fan: it comes back as it was.        guard liveKey != nil, !FanRoom.putAway(tucked: tucked, keyboardUp: keyboardUp) else { return }        // The page has mounted and laid out its scroll view by then.        try? await Task.sleep(for: .milliseconds(Int(theme.scale[.fanTurnMsMin])))        guard !Task.isCancelled else { return }        let scale = theme.scale, animation = FanCollapse.animation(scale, reduceMotion: reduceMotion)        scrollWatch.watch(in: watchArea) { [collapse] offset, end, byFinger in            collapse.scrolled(offset: offset, end: end, byFinger: byFinger, scale: scale, animation: animation)        }    }    /// Tile `index`'s page as the fan shows it, live or painted: running on    /// under the fan and the band, its content inset by the band alone    /// (`FramedPage`), with the fan's one cover.    private func framed(_ index: Int, laysGround: Bool = false) -> FramedPage {        FramedPage(page: page(index), cover: cover, views: toolViews, tiers: tiers, laysGround: laysGround, hosted: hostedPages)    }    /// The bloomed fan's cover now (`FanRoom.cover`).    private var coverEdge: Double? {        FanRoom.cover(collapsed: collapse.collapsed, tucked: tucked, keyboardUp: keyboardUp,                      areaFoot: watchArea.isEmpty ? nil : Double(watchArea.maxY) - standingRoom)    }    /// The standing fan's top (`FanRoom.standingEdge`), from the page area    /// as measured with the fan out: open or closed, it stays.    private var standingEdge: Double? {        FanRoom.standingEdge(areaFoot: region.frame.isEmpty ? nil : Double(region.frame.maxY), standingRoom: standingRoom)    }    /// Draws the missing and stale pictures, nearest the settled tile first:    /// once the window has been still for `quiet`, every one left is drawn    /// back to back while it stays still — so on a warm app a first turn    /// meets a picture on every tile (architect, 15 Oct 2026) — and a touch,    /// a turn or the fan put down stops it until the next still window.    private func painting() async {        // No page is pictured before the shown database's definitions are        // read: a page drawn on the bundled set may show none of its own.        guard let motion, let pictures, definitions.stamp != nil else { return }        let quiet = StillWindow.quiet        let still = Double(quiet.components.seconds) + Double(quiet.components.attoseconds) / 1e18        let settle = Duration.milliseconds(Int(theme.scale[.fanPictureSettleMs]))        let scale = Double(theme.scale[.fanPictureScale])        while !Task.isCancelled {            let watch = TouchWatch.install()            defer { watch?.remove() }            do { try await Task.sleep(for: quiet) } catch { return }            // The window stays still: draw on, one picture after another.            while !Task.isCancelled, PagePainterGate.mayDraw(                touching: watch?.touched ?? false, moving: motion.moving || turn.key != nil, stillFor: still, quiet: still)            {                // The fan's own tiles first, nearest the settled one: each is                // drawn once as a picture of itself, so a turn only moves them.                if let next = prints.missing(of: tiles.filter(photographReady), around: motion.settled,                                             kinds: FanCurrentPrint.kinds(theme)) {                    prints.draw(next.tile, current: next.current, width: geometry.tileWidth,                                scale: Double(displayScale) * geometry.settledScale, environment: environment)                    // The frames and touches queued behind it go first.                    await Task.yield()                    continue                }                // A fan put down lends the page its room; pictures are of the                // page beside the full fan, so they wait for it to stand up.                guard !fanDown else { return }                // The live page, standing still on screen, is its own picture:                // taken here, in a still window, never as a finger lands.                // Not before its tiles are answered: an unanswered Home is                // no page to keep.                // Nor before the page has drawn: the ghost over it would be                // kept as the tile's picture.                if case .live(let index) = motion.shows, tiles.indices.contains(index), !tiles[index].poster,                   ready, drawnLive == keys[index], pictures.needsDrawing(keys[index]),                   let shot = PagePictures.capture(area, scale: scale, page: hostedPages ? TileStacks.key(database: database, tile: keys[index]) : nil) {                    await pictures.keep(shot, for: keys[index], families: tiles[index].families,                                        scrolled: !FanScrollWatch.atTop(FanScrollWatch.scrollView(in: watchArea)),                                        definitions: definitions.stamp)                    continue                }                guard let key = pictures.next(of: keys, settled: motion.settled, skipping: posters),                      let index = keys.firstIndex(of: key)                else {                    pictures.report(tiles: tiles.count)                    return                }                // A finger landing lets the page go at once, not after its                // settle: an off-screen page laid out under a turning fan is                // main-thread work in the turn's frames (fanperf, try4).                // Laid out as the live page is, under the standing fan; kept                // down to the picture region's foot.                let page = framed(index)                let region = region, kept = area.size                // Painted under the definitions it is kept under, never the                // older ones the fan's whole environment may still hold.                let drawnUnder = definitions.stamp                let painted = PagePainter.environment(environment, definitions: definitions, tools: dataTools)                let drawing = Task {                    await PagePainter.draw(                        page, environment: painted, region: region, keeping: kept, scale: scale,                        settle: settle, touched: { (watch?.touched ?? false) || motion.moving || turn.key != nil })                }                watch?.onTouch = { drawing.cancel() }                let drawn = await drawing.value                watch?.onTouch = nil                guard let drawn, !Task.isCancelled else { break }                await pictures.keep(drawn.image, for: key, families: tiles[index].families, scrolled: drawn.scrolled,                                    definitions: drawnUnder)            }        }    }    /// The check `FanPictureCheck` asks for: for the first three tiles with a    /// page of their own, the live page — its first frames and once settled —    /// against the painter's picture of it, at one pixel a point.    private func checkPictures() async {        guard let motion, let pictures else { return }        let settle = Duration.milliseconds(Int(theme.scale[.fanPictureSettleMs]))        // Every picture drawn first, as a person turning the fan meets them.        while pictures.next(of: keys, settled: motion.settled, skipping: posters) != nil {            try? await Task.sleep(for: settle)        }        var worst = 0.0        for index in tiles.indices.filter({ $0 > 0 && !tiles[$0].poster }).prefix(3) {            // Its picture decoded, as the fling that heads for it decodes it.            await pictures.focus(keys: keys, settled: index)            motion.turn(to: index, animated: false)            // The live page's first drawn frame — its picture over it,            // starting to fade — then halfway through the fade.            var waited = Duration.zero            while FanPictureCheck.appeared != keys[index], waited < .seconds(3) {                try? await Task.sleep(for: FanPictureCheck.frame)                waited += FanPictureCheck.frame            }            try? await Task.sleep(for: FanPictureCheck.frame)            let first = PagePictures.capture(area, scale: 1)            try? await Task.sleep(for: .milliseconds(Int(theme.scale[.fanTurnMsMin]) / 2))            let midway = PagePictures.capture(area, scale: 1)            try? await Task.sleep(for: settle * 3)            let settled = PagePictures.capture(area, scale: 1)            // The picture a person saw while the fan turned: the one kept            // (painted when the window was still, compressed, decoded),            // drawn at one pixel a point. Compare its opaque objects: the            // window supplies its clear ground and blends its soft edges.            let painted = pictures.decoded[keys[index]].map { PagePictures.redraw($0, size: area.size) }            guard let first, let midway, let settled, let painted else {                FanPictureCheck.log("\(keys[index]) could not be drawn")                worst = 1                continue            }            FanPictureCheck.keep(                [("first", first), ("midway", midway), ("settled", settled), ("painted", painted)], key: keys[index])            let picture = PagePictures.pixels(painted)            let atFirst = PictureDiff.fraction(PagePictures.pixels(first), picture, tolerance: FanPictureCheck.tolerance, opaqueReference: true)            let atMidway = PictureDiff.fraction(PagePictures.pixels(midway), picture, tolerance: FanPictureCheck.tolerance, opaqueReference: true)            let atRest = PictureDiff.fraction(PagePictures.pixels(settled), picture, tolerance: FanPictureCheck.tolerance, opaqueReference: true)            worst = max(worst, atFirst, atMidway, atRest)            FanPictureCheck.log(String(                format: "%@ first %.2f%% midway %.2f%% settled %.2f%%",                keys[index], atFirst * 100, atMidway * 100, atRest * 100))        }        // The touch-down swap, on Home's own page and the first list: the live        // page as it stands, against the frame after a finger lands (its own        // picture in its place) — the same pixels, or the page moved.        for index in [0] + tiles.indices.filter({ $0 > 0 && !tiles[$0].poster }).prefix(1) {            motion.turn(to: index, animated: false)            try? await Task.sleep(for: settle * 3)            guard let before = PagePictures.capture(area, scale: 1) else { continue }            var instant = Transaction()            instant.disablesAnimations = true            withTransaction(instant) {                grab()                motion.beginDrag()            }            try? await Task.sleep(for: FanPictureCheck.frame * 4)            let after = PagePictures.capture(area, scale: 1)            motion.release(pointsPerSecond: 0, flings: false)            guard let after else { continue }            let swap = PictureDiff.fraction(                PagePictures.pixels(before), PagePictures.pixels(after), tolerance: FanPictureCheck.tolerance)            worst = max(worst, swap)            FanPictureCheck.log(String(format: "%@ touch-down swap %.2f%%", keys[index], swap * 100))            try? await Task.sleep(for: settle * 2)        }        motion.turn(to: 0, animated: false)        FanPictureCheck.log(String(format: "done worst %.2f%%", worst * 100))    }}/// The page area: the live page when the fan rests on a tile, a picture/// otherwise — never blank. While the fan turns it shows the nearest tile's/// page picture; one not decoded yet leaves the last picture shown in place/// until it is; a tile with no page of its own, or none drawn yet with/// nothing shown before, shows as a ghost — its tile blurred and washed,/// never sharp at page scale (architect, 14 Oct 2026). A crossfade is/// between two page pictures when both exist. Reads the motion's `shows`,/// which changes only when what is drawn changes — not every frame.private struct FanPageArea: View {    let tiles: [FanTile]    let motion: FanMotion    /// The database shown and the taps on the open tool's card: a change of    /// either draws the live page afresh, under its stack's own key.    let fresh: String    /// The key of the tile the fan rests on (`FanPageRule.resting`).    let rests: String?    /// The tiles' keys this area last drew: a change of them is a deal, and    /// only then does the page follow the resting key over the index.    @State private var keysSeen: [String]?    let pictures: PagePictures    let turn: FanPageTurn    let cover: FanCover    let page: (Int) -> FramedPage    /// The live page of a tile has drawn a frame.    let drawn: (String) -> Void    /// The live page has drawn a frame: its picture may fade.    @State private var liveDrawn: String?    /// The tile whose live page is mounted: the last one the fan rested on.    /// A finger on the fan hides it under its picture and never takes it    /// down, so a touch that lands back on the same tile shows the same    /// page — no remount, no list read again (fanremount, 21 Oct 2026: every    /// touch re-read People's 1,700 rows). Only a rest on another tile    /// mounts another page.    @State private var mounted: String?    /// The pictures the area shows, in one box of their own: an animation's    /// completion captures this view, and with `@State` values it captured    /// the pictures themselves — on iOS 26.5 SwiftUI keeps those completions    /// pending while a finger turns the fan, and every page picture shown in    /// a turn stayed alive (fan3 leak, 15 Oct: 156 decoded pictures held by    /// GestureGraph.pendingTransactions after 42 flings). The box is one    /// reference; a picture replaced in it goes.    @State private var shown = FanShown()    /// How far the turn's dissolve has run (`PaperDissolve`): 0 the leaving    /// picture whole, 1 the arriving one whole.    @State private var topIn = 1.0    @Environment(\.theme) private var theme    var body: some View {        // Over the tiles held now (`FanPageRule.held`): the nearest card        // when they shrank under a settled fan.        let held = FanPageRule.held(motion.shows, count: tiles.count) ?? motion.shows        let dealt = keysSeen != tiles.map(\.key)        let shows = dealt ? FanPageRule.resting(held, keys: tiles.map(\.key), on: rests) : held        let index: Int = { switch shows { case .live(let index), .picture(let index): return index } }()        let tile = tiles.indices.contains(index) ? tiles[index] : nil        let key = tile?.key ?? FanWords.home        let live = isLive(shows)        let fade = Double(theme.scale[.fanTurnMsMin]) / 1000        let decoded = pictures.decoded[key]        let grabbed = pictures.grabbed.flatMap { $0.key == key ? $0.view : nil }        // A tile with no list page has no picture but the snapshot of it live.        let picture = tile?.poster == true ? decoded : decoded ?? (shown.heldKey == key ? shown.held : nil)        // The ghost wash paints only during a turn: at rest, at launch and        // at a switch no faded card stands over the page (294 row 3).        let visual: FanVisual? = grabbed.map(FanVisual.snapshot)            ?? picture.map(FanVisual.picture) ?? (motion.moving ? tile.map(FanVisual.ghost) : nil)        // The page mounted now: the resting tile's, or while the fan moves        // the one it last rested on, if that tile is still dealt.        let pageKey = turn.key ?? (live ? (tile == nil ? nil : key) : mounted)        let generation = turn.generation        let pageIndex = pageKey.flatMap { pageKey in tiles.firstIndex { $0.key == pageKey } }        ZStack {            // A fan with no tile draws no live page.            if let pageKey, let pageIndex {                FanLivePage(key: pageKey, index: pageIndex, tiles: tiles.map(\.key), fresh: fresh, page: page,                            arrival: FanPageArrival(id: "\(pageKey)\u{1F}\(generation)") { reading in                                guard reading.ready, generation == turn.generation else { return }                                if turn.key != nil {                                    turn.report(reading, key: pageKey, generation: generation)                                } else if live {                                    cover.lay(reading.ground)                                }                                if turn.key == nil || turn.ready {                                    liveDrawn = pageKey                                    drawn(pageKey)                                    if FanPictureCheck.asked { FanPictureCheck.appeared = pageKey }                                }                            }, request: generation)                    .equatable()                    // Database changes and a tap on the current tile reset                    // the page; choosing another tool keeps its UIKit host.                    .id(fresh)                    // Under the moving fan it stands, unseen and untouched,                    // behind the pictures.                    .opacity(turn.key != nil ? (turn.ready ? 1 : 0) : (live ? 1 : 0))                    .allowsHitTesting(live && turn.key == nil)                    .accessibilityHidden(!live || turn.key != nil)            }            if turn.key == nil && (liveDrawn != key || !live) {                ZStack {                    // Through the paper, never text over text (291 row B2):                    // the leaving picture is gone by the dissolve's midpoint                    // and the arriving one comes in only after it.                    if let under = shown.under {                        under.view().modifier(PaperDissolve(progress: topIn, leaving: true))                    }                    if let top = shown.top {                        top.view().modifier(PaperDissolve(progress: shown.under == nil ? 1 : topIn, leaving: false))                    }                }                .allowsHitTesting(false)                .transition(.opacity)            }            if let snapshot = turn.snapshot {                FanVisual.snapshot(snapshot).view()                    .opacity(turn.opacity)                    .allowsHitTesting(false)                    .accessibilityHidden(true)            }        }        .onChange(of: turn.key) { _, key in if let key { mounted = key } }        .onChange(of: fresh) { _, _ in turn.cancel() }        .onChange(of: decoded, initial: true) { _, picture in if let picture { shown.held = picture; shown.heldKey = key } }        // Seen once the fan has been turned to the tile's new place.        .onChange(of: FanDeal(keys: tiles.map(\.key), shows: motion.shows, rests: rests), initial: true) { _, deal in            if FanPageRule.resting(deal.shows, keys: deal.keys, on: deal.rests) == deal.shows { keysSeen = deal.keys }        }        // The fan left the snapshot's tile: it goes once its crossfade is done        // (the page area keeps it as `under` until then).        .onChange(of: key) { _, key in if pictures.grabbed?.key != key { pictures.letGo() } }        .onChange(of: FanVisualState(visual: visual?.id, live: live), initial: true) { old, new in            guard turn.key == nil, new.visual != shown.top?.id || shown.top == nil else { return }            // Out of the live page into its own picture: in the same frame,            // with no fade (the picture IS the page).            let instant = (old.live && !new.live) || shown.top == nil            shown.under = instant ? nil : shown.top            shown.top = visual            // On the switch's timeline only while it is what the area shows.            if let visual, liveDrawn != key || !live { SwitchClock.markDrawn(visual.kind) }            guard !instant else { return topIn = 1 }            topIn = 0            withAnimation(.easeInOut(duration: fade)) { topIn = 1 } completion: {                if shown.top?.id == new.visual { shown.under = nil }            }        }        // The fan at rest on its drawn live page: a touch that turned        // nothing lets its snapshot go.        .onChange(of: motion.moving) { _, moving in            if !FanSnapshotRule.holds(grabbed: pictures.grabbed?.key, moving: moving, live: live, drawn: liveDrawn) {                pictures.letGo()            }        }        .onChange(of: live && tile != nil ? key : nil, initial: true) { _, resting in            if let resting { mounted = resting }        }        .onChange(of: live) { _, live in            // Moving, the mounted page keeps its drawn frame: a rest back on            // it lets its picture go at once.            guard live else { return }            if liveDrawn == key {                drawn(key)                pictures.letGo()            }            // The live page mounts under the settled tile's own picture: that            // picture stands whole over it, with no fade still running from            // the turn, and only then fades away to the page.            var instant = Transaction()            instant.disablesAnimations = true            withTransaction(instant) {                shown.under = nil                topIn = 1            }        }    }    private func isLive(_ shows: FanPageRule.Shows) -> Bool {        if case .live = shows { return true }        return false    }}/// What the page area shows while no live page is drawn: the one coming in/// (`top`) and the one before (`under`), which dissolve through the page's/// ground one after the other (`PaperDissolve`) — never both drawn at once —/// and the last page picture shown (`held`), kept until the next is decoded.@MainActor@Observableprivate final class FanShown {    var held: UIImage?    var heldKey: String?    var top: FanVisual?    var under: FanVisual?}/// What the page area shows in place of a live page.private enum FanVisual {    case picture(UIImage)    /// The render server's snapshot of the live page, as a finger landed.    case snapshot(UIView)    case ghost(FanTile)    /// What it is, for the switch's timeline.    var kind: String {        switch self {        case .picture: return "picture"        case .snapshot: return "snapshot"        case .ghost: return "ghost"        }    }    var id: String {        switch self {        case .picture(let image): return "picture-\(ObjectIdentifier(image).hashValue)"        case .snapshot(let view): return "snapshot-\(ObjectIdentifier(view).hashValue)"        case .ghost(let tile): return "ghost-\(tile.key)"        }    }    /// A picture at the size it was drawn, from the top — never scaled, so it    /// lines up with the live page that replaces it.    @MainActor @ViewBuilder func view() -> some View {        switch self {        case .picture(let image):            Image(uiImage: image)                .resizable()                .frame(width: image.size.width, height: image.size.height)                .inPageArea()        case .snapshot(let view):            FanSnapshot(view: view)                .frame(width: view.bounds.width, height: view.bounds.height)                .inPageArea()        case .ghost(let tile):            FanGhost(tile: tile).inPageArea()        }    }}/// A render-server snapshot in the page area, at its own size.struct FanSnapshot: UIViewRepresentable {    let view: UIView    func makeUIView(context: Context) -> UIView {        let holder = UIView()        holder.isUserInteractionEnabled = false        holder.addSubview(view)        return holder    }    func updateUIView(_ holder: UIView, context: Context) {        guard view.superview !== holder else { return }        holder.subviews.forEach { $0.removeFromSuperview() }        holder.addSubview(view)    }}private struct FanDeal: Equatable {    let keys: [String]    let shows: FanPageRule.Shows    let rests: String?}private struct FanVisualState: Equatable {    let visual: String?    let live: Bool}/// A tile standing in for a page that has no picture yet: the tile at its own/// size in the fan, centred on the page's ground under a light wash — a/// placeholder, never a blur and never a billboard (architect, 15 Oct 2026).private struct FanGhost: View {    let tile: FanTile    @Environment(\.theme) private var theme    var body: some View {        let scale = theme.scale        ZStack {            // The shell holds the leaving deck's ground until the live page            // knows its first card. A placeholder must not wash it with paper.            tile.printed(width: Double(scale[.fanTileW]))                .opacity(1 - Double(scale[.fanGhostWash]))        }        .frame(maxWidth: .infinity, maxHeight: .infinity)        .accessibilityHidden(true)    }}/// The one live page, redrawn only when its tile changes — or the tiles do:/// Home's own page draws them, and after a database switch they arrive with/// its answer while the fan already stands on Home (lane stalepic, 15 Oct/// 2026: the switched-to Home kept its unanswered page, no tile on it).struct FanLivePage: View, Equatable {    let key: String    let index: Int    let tiles: [String]    var fresh = ""    let page: (Int) -> FramedPage    var arrival: FanPageArrival? = nil    var request = 0    nonisolated static func == (lhs: Self, rhs: Self) -> Bool {        lhs.key == rhs.key && lhs.index == rhs.index && lhs.tiles == rhs.tiles && lhs.fresh == rhs.fresh && lhs.request == rhs.request    }    var body: some View {        var framed = page(index)        framed.arrival = arrival        return framed    }}/// The page area of a tile whose tile opens no list: its tile, larger, on/// the page's ground; a tap opens it as the tile's tap does.struct FanPoster: View {    let tile: FanTile    let onOpen: () -> Void    @Environment(\.theme) private var theme    var body: some View {        let scale = Double(theme.scale[.fanPosterScale])        Button(action: onOpen) {            tile.printed(width: Double(theme.scale[.fanTileW]) * scale)        }        .buttonStyle(MotionButtonStyle())        .frame(maxWidth: .infinity, maxHeight: .infinity)        .accessibilityIdentifier("fan-poster-\(tile.key)")    }}/// Every tile of the fan as a picture of itself (fan3 part 0). A card's/// drawing is a photograph flattened into a texture (`ToolCard`'s/// `drawingGroup`); scaled a little differently in every frame of a turn,/// it was drawn again every frame — its photographs decompressed from the/// asset catalogue and resampled inside each commit (60–100 ms commits)./// A picture drawn once at the fan's largest size (`fan_settled_scale`) is/// only moved, scaled and leant (`FanArc`). The tiles in sight are drawn/// the frame after the fan appears, the rest while the window is still,/// nearest the settled tile first, and kept for the tiles on Home (30 tiles/// ≈ 0.8 MB each).typealias FanTilePrints = FanPrints<FanTilePrint>/// A tile's print as it was drawn: the tile, whether its photograph was/// decoded then — a card printed bare is drawn again once it is — and/// whether it is the tile's current print.struct FanTilePrint: Equatable {    let tile: FanTile    let photographed: Bool    let current: Bool    @MainActor init(_ tile: FanTile, current: Bool = false) {        self.tile = tile        self.current = current        if case .photo(let reference) = tile.picture {            photographed = ToolPhotographs.image(reference) != nil        } else {            photographed = false        }    }}/// The launch's splash on the phone: it stands over the window until the/// first Home is read and stands whole (`FanLaunchRule.stands`), then goes in/// one frame (`SplashOverlay.cut`). Nothing else covers the window: a plain/// view of the ground laid over the key window hid the splash's logo, and/// the person saw bare paper for up to a second before Home (295 B,/// walker294). A switch turns only once the new database's Home is read/// (`DatabaseScene.show`).@MainActorenum FanLaunch {    /// The splash has come down.    static private(set) var stood = false    /// When the window first waited on the ceiling: a fan or a stack rebuilt    /// under the splash never starts it again.    static private var began: ContinuousClock.Instant?    /// Takes the splash down, once, in one frame.    static func stand() {        guard !stood else { return }        stood = true        SwitchClock.mark("splash-down", SwitchClock.launch)        LaunchMarks.mark("splash-down")        hideSplashOnce()    }    /// An app drawn without the fan (Story, Days, Notes, Health, Vault) has    /// read its first screen from the phone's own copy: the splash goes on    /// the next frame, with that screen drawn under it. Before these called    /// it, their splash waited out the whole ceiling on every open — the    /// owner's 5 to 10 seconds before Story, Days or Notes showed anything    /// (launch-fast, 20 Nov 2026).    static func firstContent() {        LaunchMarks.mark("first-content")        DispatchQueue.main.async { stand() }    }    /// Waits out the ceiling from the window's first wait, then stands. A    /// task cancelled meanwhile stands nothing: a cancelled sleep is not a    /// ceiling reached (the fan's own wait swallowed its cancellation, and a    /// fan rebuilt under the cover lifted it at once, 295 B).    static func waitOutCeiling() async {        guard !stood else { return }        let began = Self.began ?? .now        Self.began = began        do { try await Task.sleep(until: began + FanLaunchRule.ceiling, clock: .continuous) } catch { return }        stand()    }}/// The fan's current tile under a look that fills it (`Theme.currentTileFill`)/// is a second print of that tile, drawn once beside its plain one while/// the window is still, like every print: the arc swaps which of the two/// its item shows when the fan comes to rest (`FanArcItem.current`), so a/// turn still only moves pictures and no frame draws a card.enum FanCurrentPrint {    /// The key a tile's current print is kept under, beside its plain one.    static func key(_ key: String) -> String { key + "\u{1F}current" }    /// The prints a tile has under `theme`: the plain one, and the current    /// one only where the look fills the current tile.    static func kinds(_ theme: Theme) -> [Bool] { theme.currentTileFill == nil ? [false] : [false, true] }}extension FanPrints where Signature == FanTilePrint {    func picture(of tile: FanTile, current: Bool = false) -> UIImage? {        picture(current ? FanCurrentPrint.key(tile.key) : tile.key, FanTilePrint(tile, current: current))    }    /// The print to draw next: every tile's plain one nearest `settled`    /// first, then — under a look that fills the current tile — each tile's    /// current one, nearest first.    func missing(of tiles: [FanTile], around settled: Int, kinds: [Bool] = [false]) -> (tile: FanTile, current: Bool)? {        let near = tiles.indices.sorted { abs($0 - settled) < abs($1 - settled) }.map { tiles[$0] }        for current in kinds {            if let tile = near.first(where: { picture(of: $0, current: current) == nil }) { return (tile, current) }        }        return nil    }    /// The tile at `width`, its shadow whole inside the picture.    func draw(_ tile: FanTile, current: Bool = false, width: Double, scale: Double, environment: EnvironmentValues) {        let reach = Double(ToolCardMetrics.shadowReach(width: CGFloat(width)))        draw(current ? FanCurrentPrint.key(tile.key) : tile.key, FanTilePrint(tile, current: current), scale: scale,             environment: environment, content: tile.printed(width: width, current: current).padding(reach))    }    func keepOnly(_ tiles: [FanTile]) { keepOnly(Set(tiles.flatMap { [$0.key, FanCurrentPrint.key($0.key)] })) }}/// The tiles on their arc, and the finger that turns them (`FanArcDeck`).private struct FanDeck: View {    let tiles: [FanTile]    let motion: FanMotion    let geometry: FanGeometry    let prints: FanTilePrints    let reduceMotion: Bool    /// A finger landed, before the fan moves: the live page is taken.    let onGrab: () -> Void    var onHold: ((Int) -> Bool)? = nil    let onTap: (Int) -> Void    var body: some View {        FanArcDeck(            items: tiles.map {                FanArcItem(key: $0.key, label: $0.name, picture: prints.picture(of: $0), identifier: "fan-tile-\($0.key)",                           current: prints.picture(of: $0, current: true))            },            motion: motion, geometry: geometry,            reach: Double(ToolCardMetrics.shadowReach(width: CGFloat(geometry.tileWidth))),            reduceMotion: reduceMotion,            // A card added to a fan already seen slides into its slot at the            // fan's own shortest turn (291 direction E). Under the launch's            // splash the first set is laid out, never slid: a slide begun            // there was still fading its cards in when the splash went            // (295 B, the launch walk).            slide: FanLaunch.stood ? geometry.turnShortest / 1000 : 0, onDown: onGrab, onHold: onHold, onTap: onTap)    }}#endif/// When the fan draws its own close for a card being edited: on a fan with/// no record button under it, while a card is edited and the fan stands.enum FanEditCloses {    static func stands(closesEdits: Bool, editing: Bool, fanDown: Bool) -> Bool { closesEdits && editing && !fanDown }}/// A turn's pictures dissolve through the paper (291 row B2, architect 01:50/// IST 17 Oct 2026): the leaving page fades to the page's ground by the/// dissolve's midpoint and the arriving one fades in from it after — at no/// frame are two pages' pictures both drawn, which read as a double exposure/// (one page's head over the other's rows). Reduce Motion the same. Animated/// on `progress`, so each picture's opacity follows its own half.nonisolated struct PaperDissolve: ViewModifier, Animatable {    var progress: Double    let leaving: Bool    var animatableData: Double {        get { progress }        set { progress = newValue }    }    /// The leaving and the arriving picture's opacity at `progress`.    static func opacities(_ progress: Double) -> (leaving: Double, arriving: Double) {        let p = min(max(progress, 0), 1)        return (max(0, 1 - 2 * p), max(0, 2 * p - 1))    }    func body(content: Content) -> some View {        let shown = Self.opacities(progress)        content.opacity(leaving ? shown.leaving : shown.arriving)    }}// MARK: The hub's mic: spoken commands (the voice plan, 17 Nov 2026)#if os(iOS)extension FanHome {    /// What the page region above the fan says while a command is spoken:    /// the words as heard, or the core's hint before any.    var commandToast: FanToast? {        guard let command, command.isActive else { return nil }        let heard = command.region.display        return FanToast(words: heard.isEmpty ? command.line("command_hint") : heard, act: nil)    }    func commandTapped() {        if let command, command.isActive {            Task {                await command.stop()            }            return        }        guard let core else { return }        let session = command ?? VoiceSessions.make(core: core)        session.onCommand = { [navigator, voiceSearch] said in VoiceCommands.run(said, navigator: navigator, search: voiceSearch) }        command = session        session.dismiss()        Task { await session.start(VoicePlanRequest(surface: "fan", database: database, mode: .command)) }    }}#endif