import CottonFaces import CoreText import CottonKit import CottonPaper import CottonValues import SwiftUI /// Data carried by every tier, including choices supplied by the editing shell. struct FanTier: Identifiable, Equatable { struct Card: Identifiable, Equatable { enum Style: Equatable { case object, leaf, person } let id: String let label: String var picture: ToolPicture? = nil var object: String? = nil var style: Style = .leaf var 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:`), 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? = nil var red = false var primary = false var 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: String var cards: [Card] var raised: String? = nil var 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? = nil var restingIndex: Int? { guard !cards.isEmpty else { return nil } return cards.firstIndex { $0.id == raised } ?? 0 } mutating func replaceCards(_ next: [Card], restingAt index: Int) { let changed = cards.map(\.id) != next.map(\.id) cards = next if 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. struct FanSwatch: Equatable { enum Kind: 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 @Observable final class FanTiers { private struct Entry { var tier: FanTier var tap: (FanTier.Card) -> Void var onPop: (() -> Void)? = nil } /// The tools tier's id, where the core has not named it yet. static let toolsTier = "tools" private var entries: [Entry] = [] /// A root stands at the foot of the path (`setRoot`). private var rooted = false var depth: Int { entries.count } var open: 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 { return nil } 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) { guard let 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) } static func 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 = 0 let stale = entries.firstIndex { entry in guard entry.tier.id.hasPrefix("whole-") else { return false } defer { matched += 1 } return matched >= wanted.count || entry.tier.id != wanted[matched] } if let 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 }) == true else { return } entries[entries.count - 1].tier.raised = id } } #if os(iOS) /// The same arc and spring used by tools, for every higher tier. struct FanTierArc: View { let tier: FanTier let geometry: FanGeometry let tiers: FanTiers var 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) private var theme @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.displayScale) private var displayScale @Environment(\.cottonCore) private var core @Environment(\.self) private var environment @State private var motion: FanMotion? @State private var prints = FanPrints() @State private var photographsAsked: Set = [] /// A list's pictures asked for its tile, until bytes land again. @State private var listPicturesAsked: Set = [] /// 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 private var landed = 0 struct Look: Equatable { let card: FanTier.Card let raised: Bool let width: Double let height: Double var ground: FaceGround? = nil /// The tier's fan tile (`FanTier.tile`). var tile: FanTileLook? = nil } var body: some View { ZStack { if let motion { FanArcDeck(items: tier.cards.map { card in FanArcItem(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 in guard tier.cards.indices.contains(index) else { return false } return onHold?(tier.cards[index]) ?? false }) { index in guard tier.cards.indices.contains(index) else { return } let card = tier.cards[index] tiers.activate(card.id, centred: tier.cards[motion.settled].id) { id in if let at = tier.cards.firstIndex(where: { $0.id == id }) { motion.turn(to: at, animated: !reduceMotion) } } } } } .overlay { if let motion, tier.cards.indices.contains(motion.settled) { let card = tier.cards[motion.settled] FanPeekLayer(next: card.next, owner: card.id, motion: motion, geometry: geometry) { if let enter { enter(card) } else { tiers.choose(card.id) } } } } .frame(height: geometry.height) .onAppear { start() } .onChange(of: motion?.settled) { _, index in if let 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") } private func identifier(_ card: FanTier.Card) -> String { guard tier.editorState != nil else { return "tier-\(tier.id)-\(card.id)" } let prefix = DeckEditor.session.openedTarget != nil && DeckEditor.session.holdsActs ? "opened-" : "edit-fan-" return prefix + card.id } private func 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 = handler return arc } private func start() { guard let 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()) if let 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 in Set(tier.cards.compactMap(\.pictogram)) { loadPhotograph(photo, pixels: markPixels) } } // A painted next tier peeks on its stock (`FanPeekCards`). for stock in Set(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) == nil else { 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. private func loadListPictures(_ card: FanTier.Card) { guard let 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 { guard await ListTilePictureCache.load(keys, core: core, edge: edge) else { return } landed += 1 } } private func loadPicture(_ card: FanTier.Card) { guard case .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`). private func loadPhotograph(_ reference: String, pixels: Int) { guard ToolPhotographs.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. guard await ToolPhotographs.load(reference, core: core, maxPixel: pixels) != nil else { photographsAsked.remove(reference) return } landed += 1 } } } struct FanTierCard: 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) private var growth: CGFloat @Environment(\.theme) private var theme @Environment(\.openedCardGround) private var ground @Environment(\.fanCover) private var cover var body: some View { if let swatch = look.card.swatch { FanSwatchCard(label: look.card.label, swatch: swatch, width: look.width, height: look.height) } else if let tile = look.tile, tile.painted { FanPaintedCard(look: look, tile: tile, growth: growth) } else if let item = look.card.item { ZStack { RoundedRectangle(cornerRadius: 6).fill(theme.sheet(.cream)) if look.card.style == .person { Group { if let 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) } else if let 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() } else if 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) } else if let list = look.card.list { ListTile(pictures: list, label: look.card.label, count: look.card.count, width: look.width, height: look.height, growth: growth) } else if let 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) if let 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. struct FanPaintedCard: View { let look: FanTierArc.Look let tile: FanTileLook let growth: CGFloat @Environment(\.theme) private var theme /// A red act's red; nil, the type's own ink. private var red: Color? { look.card.red ? theme.print(.red) : nil } var body: some View { 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 } } private var side: Double { look.width * PaintedTileKnobs.markSide } @ViewBuilder private var mark: some View { let pictogram = look.card.pictogram.flatMap(ToolPhotographs.image).map { PaintedPictogram(Image(uiImage: $0), red: red, type: tile.paintedType) } if let list = look.card.list { switch ListTileArt.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.stackShare let 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 } } } #endif extension FanTileLook { /// 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 : .courier guard let 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. enum FanPaintedKnobs { /// A list's own picture, cover-fit, its corner in points. static let ownCorner: CGFloat = 6 /// The box's side against the width the list tile's stack is laid on. static let 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. enum FanTierWords { static let lines = 2 /// The words' size, and a day's date under them, against the card's width. static let word = 0.14 static let detail = 0.1 static func 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 = preferred while size > Step.least { if InkFit.fits(words, face: .courier, size: size, width: width, lines: lines) { return size } size -= step } return Step.least } /// `words` as a Text should be given them at `size` (`InkFit.broken`). static func broken(_ words: String, size: CGFloat, cardWidth: Double) -> String { InkFit.broken(words, face: .courier, size: size, width: CGFloat(cardWidth * FanGeometry.labelWidthRatio)) } private enum Step { static let least: CGFloat = 1 static let share: CGFloat = 0.02 } } #if os(iOS) /// A swatch card (`FanSwatch`), its type set to the card's size. struct FanSwatchCard: View { let label: String let swatch: FanSwatch let width: Double let height: Double var body: some View { 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 in Capsule().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() } } #endif extension FanGeometry { /// 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 / 2 return 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. enum FanHub { static func foldScale(collapsed: Bool, scale: ThemeScale) -> CGFloat { collapsed ? scale[.fanCollapsedSize] / max(scale[.fanRecordSize], 1) : 1 } }