importCottonFacesimportCoreTextimportCottonKitimportCottonPaperimportCottonValuesimportSwiftUI/// Data carried by every tier, including choices supplied by the editing shell.structFanTier: Identifiable, Equatable {structCard: Identifiable, Equatable {enumStyle: Equatable { case object, leaf, person }let id: Stringlet label: Stringvar picture: ToolPicture? = nilvar object: String? = nilvar style: Style = .leafvar count: Int? = nil/// A view's painted tile, by its catalogue name (`ViewTile.asset`):/// the picture is the whole card, the label and count typed on it.var painted: String? = nil/// A list's tile (`ListTile`): made from its members' pictures, or/// the person's own picture for it.var list: ListTilePictures? = nil/// The kit pictogram at the head of its tile, by reference/// (`photo:<sha256>`), drawn on its tier's painted tile (`FanTier.tile`).var pictogram: String? = nil/// Words under its name where it has no count: a card's state at a/// glance (the Account card's "Signed out", "Synced 13:46").var detail: String? = nilvar red = falsevar primary = falsevar next: FanTier? = nil/// Drawn as a thing of its own rather than a word on cream: a/// reader's face as a page in its stock, a pencil by its line.var swatch: FanSwatch? = nil #if os(iOS)var item: EditingItem? = nil #endif }let id: Stringvar cards: [Card]var raised: String? = nilvar editorState: DeckEditing? = nil/// The fan tile of the tool the tier is dealt under (`FanTileLook`): its/// cards are drawn on its stock, in its type. Nil, the shell's own tiles.var tile: FanTileLook? = nilvar restingIndex: Int? {guard !cards.isEmpty else { returnnil }return cards.firstIndex { $0.id == raised } ?? 0 }mutatingfunc replaceCards(_ next: [Card], restingAt index: Int) {let changed = cards.map(\.id) != next.map(\.id) cards = nextif changed || !cards.contains(where: { $0.id == raised }) { raised = cards.indices.contains(index) ? cards[index].id : cards.first?.id } }}/// A tier card drawn as what it chooses (`FanTier.Card.swatch`), in live/// type: a reader's face as a small page in its own ground, its name in its/// ink over a hairline and three ruled lines of sample type; a pencil as its/// name on cream over the line it draws.structFanSwatch: Equatable {enumKind: Equatable { case page, pencil }var kind: Kind/// The page's ground (a face), or the card's paper (a pencil).var ground: Color/// The words' ink.var ink: Color/// The face's hairline under its name, or the pencil's line.var line: Color}/// Keeps the whole path for close and presents only the open tier./// FanHome owns this and hands it to pages through the environment.@MainActor @ObservablefinalclassFanTiers {privatestructEntry {var tier: FanTiervar tap: (FanTier.Card) -> Voidvar onPop: (() -> Void)? = nil }/// The tools tier's id, where the core has not named it yet.staticlet toolsTier = "tools"privatevar entries: [Entry] = []/// A root stands at the foot of the path (`setRoot`).privatevar rooted = falsevar depth: Int { entries.count }varopen: FanTier? { entries.last?.tier }var visible: [FanTier] { entries.suffix(1).map(\.tier) }var closes: Bool { depth > 1 }/// The fan's first tier: the tools, or one tool's views (`shell.fan`'s `root`).var root: FanTier? { rooted ? entries.first?.tier : nil }/// The fan's first tier, standing in for the one before it whatever its/// id: a kit's tools giving way to its one tool's views (`shell.fan`) is/// the same root, never a tier over it.func setRoot(_ tier: FanTier, onTap: @escaping (FanTier.Card) -> Void = { _ in }) {let entry = Entry(tier: tier, tap: onTap)if rooted, !entries.isEmpty { entries[0] = entry } else { entries.insert(entry, at: 0) } rooted = true }func reset() { entries = []; rooted = false }func push(_ tier: FanTier, onPop: (() -> Void)? = nil, onTap: @escaping (FanTier.Card) -> Void) { entries.append(Entry(tier: tier, tap: onTap, onPop: onPop)) } @discardableResult func pop() -> FanTier? {guard closes else { returnnil }let entry = entries.removeLast() entry.onPop?()return entry.tier }func replaceOpen(_ tier: FanTier, onPop: (() -> Void)? = nil, onTap: @escaping (FanTier.Card) -> Void) {let entry = Entry(tier: tier, tap: onTap, onPop: onPop ?? entries.last?.onPop)if entries.isEmpty { entries.append(entry) } else { entries[entries.count - 1] = entry } }func choose(_ id: String) {guardlet entry = entries.last, let card = entry.tier.cards.first(where: { $0.id == id }) else { return } entry.tap(card) }/// A side tap only turns. The centred card and its peek share entry.func activate(_ id: String, centred: String, turn: (String) -> Void) {guard id == centred else { turn(id); return } choose(id) }staticfunc wholeID(_ whole: WholeLevel) -> String { "whole-\(whole.table)-\(whole.id)" }/// Preserve each parent's dealt cards when entering or leaving a whole./// The whole tiers standing are the path's, in its order: the first that/// is not the path's next goes with every tier above it (an opened/// record's acts over it too), wherever it stands — a crumb tap left a/// whole tier beneath an open one that was not a whole's.func alignWholes(_ path: [WholeLevel]) {let wanted = path.map(Self.wholeID)var matched = 0let stale = entries.firstIndex { entry inguard entry.tier.id.hasPrefix("whole-") else { returnfalse }defer { matched += 1 }return matched >= wanted.count || entry.tier.id != wanted[matched] }iflet stale { while entries.count > stale, pop() != nil {} }let standing = Set(entries.map { $0.tier.id })for id in wanted where !standing.contains(id) { push(FanTier(id: id, cards: [])) { _ in } } }func raise(_ id: String) {guard entries.last?.tier.cards.contains(where: { $0.id == id }) == trueelse { return } entries[entries.count - 1].tier.raised = id }}#if os(iOS)/// The same arc and spring used by tools, for every higher tier.structFanTierArc: View {let tier: FanTierlet geometry: FanGeometrylet tiers: FanTiersvar onHold: ((FanTier.Card) -> Bool)? = nil/// The arc came to rest on a card; `chose` when the rest is a person's/// swipe coming to rest (`ArcChoice.chooses(.settled, ...)`). The host/// decides what a rest does: only a views tier shows the view rested on/// (`ViewTier.choosesOnRest`), never acts, choices or faces.var onSettle: (_ card: FanTier.Card, _ chose: Bool) -> Void = { _, _ in }/// A tap on the centred card's peek: entering the tier it previews./// Nil, the card's own tap (`FanTiers.choose`), as a tool's peek opens/// its views; the reader's faces wear a face on a tap and enter the/// knobs behind them by the peek.var enter: ((FanTier.Card) -> Void)? = nil @Environment(\.theme) privatevar theme @Environment(\.accessibilityReduceMotion) privatevar reduceMotion @Environment(\.displayScale) privatevar displayScale @Environment(\.cottonCore) privatevar core @Environment(\.self) privatevar environment @State privatevar motion: FanMotion? @State privatevar prints = FanPrints<Look>() @State privatevar photographsAsked: Set<String> = []/// A list's pictures asked for its tile, until bytes land again. @State privatevar listPicturesAsked: Set<String> = []/// Pictures landed for this arc's prints, counted. A load's task holds/// the arc as it was when it asked — its tier may since have changed —/// so a landing only counts here, and the arc as it is now prints again. @State privatevar landed = 0structLook: Equatable {let card: FanTier.Cardlet raised: Boollet width: Doublelet height: Doublevar ground: FaceGround? = nil/// The tier's fan tile (`FanTier.tile`).var tile: FanTileLook? = nil }var body: someView { ZStack {iflet motion {FanArcDeck(items: tier.cards.map { card inFanArcItem(key: card.id, label: card.label + (card.count.map { ", \($0)" } ?? card.detail.map { ", \($0)" } ?? ""), picture: prints.picture(card.id, look(card)), identifier: identifier(card)) }, motion: motion, geometry: geometry, reach: 4, reduceMotion: reduceMotion, onHold: { index inguard tier.cards.indices.contains(index) else { returnfalse }return onHold?(tier.cards[index]) ?? false }) { index inguard tier.cards.indices.contains(index) else { return }let card = tier.cards[index] tiers.activate(card.id, centred: tier.cards[motion.settled].id) { id iniflet at = tier.cards.firstIndex(where: { $0.id == id }) { motion.turn(to: at, animated: !reduceMotion) } } } } } .overlay {iflet motion, tier.cards.indices.contains(motion.settled) {let card = tier.cards[motion.settled]FanPeekLayer(next: card.next, owner: card.id, motion: motion, geometry: geometry) {iflet enter { enter(card) } else { tiers.choose(card.id) } } } } .frame(height: geometry.height) .onAppear { start() } .onChange(of: motion?.settled) { _, index iniflet index, tier.cards.indices.contains(index) { tiers.raise(tier.cards[index].id)let chose = motion.map { ArcChoice.chooses(.settled, byPerson: $0.byPerson, swiped: $0.swiped) } ?? false onSettle(tier.cards[index], chose) } } .onChange(of: tier) { _, _ in start() } .onChange(of: landed) { _, _ in prints.clear(); start() }// Bytes landed: a list's picture not here before is asked again. .onMediaArrival { listPicturesAsked = [] start() } .onChange(of: theme) { _, _ in prints.clear(); start() } .onChange(of: environment.openedCardGround ?? environment.fanCover?.ground) { _, _ in prints.clear(); start() }// Contained, so a peek over the settled card keeps its own fan-peek id. .accessibilityElement(children: .contain) .accessibilityIdentifier(tier.editorState == nil ? "fan-tier" : "edit-fan") }privatefunc identifier(_ card: FanTier.Card) -> String {guard tier.editorState != nilelse { return"tier-\(tier.id)-\(card.id)" }let prefix = DeckEditor.session.openedTarget != nil && DeckEditor.session.holdsActs ? "opened-" : "edit-fan-"return prefix + card.id }privatefunc look(_ card: FanTier.Card) -> Look {Look(card: card, raised: tier.raised == card.id, width: geometry.tileWidth, height: geometry.tileHeight, ground: environment.openedCardGround ?? environment.fanCover?.ground, tile: tier.tile) }func holding(_ handler: @escaping (FanTier.Card) -> Bool) -> FanTierArc {var arc = self arc.onHold = handlerreturn arc }privatefunc start() {guardlet index = tier.restingIndex else { return }let motion = self.motion ?? FanMotion(geometry: geometry, spring: FanSpring(scale: theme.scale)) motion.geometry = geometry motion.spring = FanSpring(scale: theme.scale) motion.recount(tier.cards.count)if !motion.moving { motion.turn(to: index, animated: false) }self.motion = motion prints.keepOnly(Set(tier.cards.map(\.id)))let stockPixels = Int((geometry.tileWidth * Double(displayScale) * geometry.settledScale).rounded())iflet tile = tier.tile, tile.painted, let stock = tile.stock {// The tile's stock and its pictograms are drawn as decoded: in// hand before the tier prints, printed again as each lands.let markPixels = Int((geometry.tileWidth * PaintedTileKnobs.markSide * Double(displayScale) * geometry.settledScale).rounded()) loadPhotograph(stock, pixels: stockPixels)for photo inSet(tier.cards.compactMap(\.pictogram)) { loadPhotograph(photo, pixels: markPixels) } }// A painted next tier peeks on its stock (`FanPeekCards`).for stock inSet(tier.cards.compactMap { $0.next?.tile }.filter(\.painted).compactMap(\.stock)) { loadPhotograph(stock, pixels: stockPixels) }for card in tier.cards { loadPicture(card) loadListPictures(card)let look = look(card)guard prints.picture(card.id, look) == nilelse { continue } prints.draw(card.id, look, scale: Double(displayScale), environment: environment, content: FanTierCard(look: look).padding(4)) } }/// A list's tile is printed from pictures in hand (`ListTilePictureCache`):/// those this phone holds are decoded first, and the arc prints again.privatefunc loadListPictures(_ card: FanTier.Card) {guardlet list = card.list, let core else { return }let keys = ListTilePictureCache.missing(list).filter { !listPicturesAsked.contains($0) }guard !keys.isEmpty else { return } listPicturesAsked.formUnion(keys)let edge = geometry.tileWidth * ListTileKnobs.printWidth * Double(displayScale)Task {guardawaitListTilePictureCache.load(keys, core: core, edge: edge) else { return } landed += 1 } }privatefunc loadPicture(_ card: FanTier.Card) {guardcase .photo(let reference) = card.picture else { return } loadPhotograph(reference, pixels: Int((geometry.tileWidth * Double(displayScale) * geometry.settledScale).rounded())) }/// A kit or tool picture decoded for the tier's prints: asked once, and/// the tier printed again when it lands (`landed`).privatefunc loadPhotograph(_ reference: String, pixels: Int) {guardToolPhotographs.image(reference) == nil, !photographsAsked.contains(reference), let core else { return } photographsAsked.insert(reference)ToolPhotographs.ask(reference)Task {// One that could not be had yet (its bytes still on their way to// this phone) is asked again on the tier's next print — a tier// change or bytes landing — never left bare for good.guardawaitToolPhotographs.load(reference, core: core, maxPixel: pixels) != nilelse { photographsAsked.remove(reference)return } landed += 1 } }}structFanTierCard: View {let look: FanTierArc.Look/// The phone's text size: a tile keeps its dimensions, its words grow/// with Dynamic Type as far as they fit it (`FanTierWords`). @TextGrowth(relativeTo: .footnote) privatevar growth: CGFloat @Environment(\.theme) privatevar theme @Environment(\.openedCardGround) privatevar ground @Environment(\.fanCover) privatevar covervar body: someView {iflet swatch = look.card.swatch {FanSwatchCard(label: look.card.label, swatch: swatch, width: look.width, height: look.height) } elseiflet tile = look.tile, tile.painted {FanPaintedCard(look: look, tile: tile, growth: growth) } elseiflet item = look.card.item { ZStack {RoundedRectangle(cornerRadius: 6).fill(theme.sheet(.cream))if look.card.style == .person {Group {iflet picture = look.card.object.flatMap(CottonMedia.image) { picture.resizable().scaledToFill() } else {Text(item.initials ?? "") .font(CottonFonts.type(look.width * 0.26)) .foregroundStyle(theme.print(.ink)) } } .frame(width: look.width * 0.62, height: look.width * 0.62) .background(theme.sheet(.cream), in: Circle()).clipShape(Circle()) .position(x: look.width / 2, y: look.height * 0.35) } elseiflet picture = look.card.object.flatMap(CottonMedia.image) { picture.resizable().scaledToFit() .frame(width: look.width * 0.65, height: look.height * 0.55) .position(x: look.width / 2, y: look.height * 0.34) }let words = look.card.style == .person ? String(look.card.label.split(separator: " ").first ?? "") : look.card.label VStack(spacing: 3) {// Never cut: two lines, then smaller (`FanTierWords`).let size = FanTierWords.size(words, cardWidth: look.width, preferred: FanTierWords.word * growth)Text(FanTierWords.broken(words, size: size, cardWidth: look.width)) .font(CottonFonts.type(size)) .multilineTextAlignment(.center) .lineLimit(FanTierWords.lines) .fixedSize(horizontal: false, vertical: true)if look.card.style == .leaf, let detail = item.detail {Text(detail) .font(CottonFonts.type(FanTierWords.size(detail, cardWidth: look.width, preferred: FanTierWords.detail * growth, lines: 1))) .lineLimit(1) .fixedSize(horizontal: false, vertical: true) } } .foregroundStyle(theme.print(look.card.red ? .red : .ink)) .frame(width: look.width * FanGeometry.labelWidthRatio, height: look.height * FanGeometry.labelHeightRatio) .position(x: look.width / 2, y: look.height * FanGeometry.labelCentreRatio) } .frame(width: look.width, height: look.height) .softShadow() } elseif look.card.style == .object || look.card.style == .person {ToolCard(key: look.card.id, name: look.card.label, picture: look.card.picture ?? look.card.object.map(ToolPicture.asset), stock: .cream, width: look.width, face: look.card.style == .person && look.card.picture == nil ? HomeFace(name: look.card.label, picture: nil, seed: look.card.id, object: look.card.object) : nil, current: look.raised) } elseiflet list = look.card.list {ListTile(pictures: list, label: look.card.label, count: look.card.count, width: look.width, height: look.height, growth: growth) } elseiflet painted = look.card.painted {ViewTile(painted: painted, label: look.card.label, count: look.card.count, width: look.width, height: look.height, growth: growth) } else { VStack(spacing: 6) {// A view's name and count grow with the text size, as far as// the tile holds them: two lines, then smaller (`FanTierWords`).let name = FanTierWords.size(look.card.label, cardWidth: look.width, preferred: 13 * growth / look.width)Text(FanTierWords.broken(look.card.label, size: name, cardWidth: look.width)) .font(CottonFonts.type(name)).multilineTextAlignment(.center) .lineLimit(FanTierWords.lines) .fixedSize(horizontal: false, vertical: true)iflet figure = look.card.count.map(String.init) ?? look.card.detail {Text(figure) .font(CottonFonts.type(FanTierWords.size(figure, cardWidth: look.width, preferred: 11 * growth / look.width, lines: 1))) .lineLimit(1) .fixedSize(horizontal: false, vertical: true) } } .frame(width: look.width * FanGeometry.labelWidthRatio) .foregroundStyle(theme.print(.ink)) .padding(6) .frame(width: look.width, height: look.height) .background(RoundedRectangle(cornerRadius: 6).fill(theme.sheet(.cream))) .softShadow() } }}#endif#if os(iOS)/// A tier card on its tool's painted tile (`FanTileLook.painted`,/// `PaintedTile`), whatever its type: the tile's stock as its face, the/// card's pictogram in the box at its head — a list's own picture, else its/// first members' covers, else the list pictogram — and its words beneath in/// the tile's type (`FanTileLook.paintedType`); a red act's words and/// pictogram in the kit's red; the centred card lifted. Every picture is the/// one decoded (`ToolPhotographs`, `ListTilePictureCache`); one not in hand/// yet leaves its place empty until the tier prints again.structFanPaintedCard: View {let look: FanTierArc.Looklet tile: FanTileLooklet growth: CGFloat @Environment(\.theme) privatevar theme/// A red act's red; nil, the type's own ink.privatevar red: Color? { look.card.red ? theme.print(.red) : nil }var body: someView {PaintedTile(stock: tile.stock.flatMap(ToolPhotographs.image).map { Image(uiImage: $0) }, type: tile.paintedType, label: look.card.label, figure: look.card.count.map(String.init) ?? look.card.detail ?? look.card.item?.detail, ink: red, centred: look.raised, width: look.width, height: look.height, growth: growth) { mark } }privatevar side: Double { look.width * PaintedTileKnobs.markSide } @ViewBuilder privatevar mark: someView {let pictogram = look.card.pictogram.flatMap(ToolPhotographs.image).map {PaintedPictogram(Image(uiImage: $0), red: red, type: tile.paintedType) }iflet list = look.card.list {switchListTileArt.drawn(own: list.cover.flatMap(ListTilePictureCache.image), stack: list.stack.map(ListTilePictureCache.image)) {case .own(let picture):Image(uiImage: picture).resizable().scaledToFill() .frame(width: side, height: side) .clipShape(RoundedRectangle(cornerRadius: FanPaintedKnobs.ownCorner))case .stack(let pictures):// The list tile's own stack, scaled so its place fills the box.let width = side / FanPaintedKnobs.stackSharelet height = width * look.height / max(look.width, 1)ListTileArt(drawn: .stack(pictures), width: width, height: height) .offset(y: (0.5 - ListTileKnobs.centre) * height) .frame(width: side, height: side)case .plain: pictogram } } else { pictogram } }}#endifextensionFanTileLook {/// How its painted tiles' words are set: the letterboard's capitals,/// else courier — the shell's typed face — in the ink and at the/// baselines its words name (`words`), else the type's own: the/// letterboard's cream, courier's theme ink.var paintedType: PaintedTileType {let type: PaintedTileType = letterboard ? .letterboard : .courierguardlet words else { return type }return type.worded(ink: words.ink.flatMap(ThemeColor.init(hex:)), nameBaseline: words.nameBaseline, countOne: words.countBaselineOne, countTwo: words.countBaselineTwo) }}/// A painted tile's list pictures, against its pictogram box.enumFanPaintedKnobs {/// A list's own picture, cover-fit, its corner in points.staticlet ownCorner: CGFloat = 6/// The box's side against the width the list tile's stack is laid on.staticlet stackShare = 0.8}/// A tier tile's words — an act, a door, a choice, a person's first name:/// they fit by wrapping to two lines, then by setting smaller, and are never/// cut (the coordinator, 4 Nov 2026: "Find a bo…", "Bring Goo…" on Books'/// Plus tier), as the fan's view cards' words wrap ("Want to read"). The/// size is the typewriter's, measured as it is drawn (`InkFit`), inside the/// label's box (`FanGeometry.labelWidthRatio`); print on a card is fixed/// type and does not grow with the phone's text size.enumFanTierWords {staticlet lines = 2/// The words' size, and a day's date under them, against the card's width.staticlet word = 0.14staticlet detail = 0.1staticfunc size(_ words: String, cardWidth: Double, preferred share: Double = word, lines: Int = lines) -> CGFloat {let width = CGFloat(cardWidth * FanGeometry.labelWidthRatio)let preferred = CGFloat(cardWidth * share)let step = max(Step.least, preferred * Step.share)var size = preferredwhile size > Step.least {ifInkFit.fits(words, face: .courier, size: size, width: width, lines: lines) { return size } size -= step }returnStep.least }/// `words` as a Text should be given them at `size` (`InkFit.broken`).staticfunc broken(_ words: String, size: CGFloat, cardWidth: Double) -> String {InkFit.broken(words, face: .courier, size: size, width: CGFloat(cardWidth * FanGeometry.labelWidthRatio)) }privateenumStep {staticlet least: CGFloat = 1staticlet share: CGFloat = 0.02 }}#if os(iOS)/// A swatch card (`FanSwatch`), its type set to the card's size.structFanSwatchCard: View {let label: Stringlet swatch: FanSwatchlet width: Doublelet height: Doublevar body: someView { ZStack(alignment: .top) {RoundedRectangle(cornerRadius: 6).fill(swatch.ground)switch swatch.kind {case .page: VStack(spacing: height * 0.045) {Text(label) .font(CottonFonts.caslon(width * 0.17)) .lineLimit(1).minimumScaleFactor(0.6)Rectangle().fill(swatch.line).frame(width: width * 0.62, height: 1) VStack(alignment: .leading, spacing: height * 0.06) {ForEach(Array([0.74, 0.66, 0.5].enumerated()), id: \.offset) { _, share inCapsule().fill(swatch.ink.opacity(0.6)).frame(width: width * share, height: max(1.5, height * 0.016)) } } .frame(width: width * 0.74, alignment: .leading) .padding(.top, height * 0.03) } .foregroundStyle(swatch.ink) .padding(.top, height * 0.16)case .pencil: VStack(spacing: height * 0.05) {Text(label) .font(CottonFonts.caslon(width * 0.17)) .foregroundStyle(swatch.ink) .lineLimit(1).minimumScaleFactor(0.6)Capsule().fill(swatch.line).frame(width: width * 0.62, height: max(2.5, height * 0.03)) } .frame(maxHeight: .infinity) } } .frame(width: width, height: height) .softShadow() }}#endifextensionFanGeometry {/// Keep the tools' arc; reserve a fixed band for its peek and hub.func withHub(diameter: Double) -> FanGeometry {var fan = self// Reserve the preview's header above the arc. At bottom alignment// top and height grow together, leaving every card and hub in place. fan.top += 35// Keep the tools' original arc and angular spacing. Membership never// changes this window; the remaining cards wait for a riffle. fan.visible = fan.step * 2.5 fan.height = fan.hub(width: 0, diameter: diameter).y + diameter / 2return fan }/// The disc sits under the raised card; the arc's mathematical pivot/// remains below it, shared by every tier.func hub(width: Double, diameter: Double) -> CGPoint { CGPoint(x: width / 2, y: settledFoot + diameter / 2 + lift) }}/// Folding changes drawing only; the hub never changes the page's layout.enumFanHub {staticfunc foldScale(collapsed: Bool, scale: ThemeScale) -> CGFloat { collapsed ? scale[.fanCollapsedSize] / max(scale[.fanRecordSize], 1) : 1 }}