Cotton code
424 lines · 19.9 KB · SwiftRaw
// Home's fan of tiles, as numbers (lane fan, 14 Oct 2026; the owner's go at// 19:05 IST after the prototype he tried on his phone). Every Home tile is a// tile on an arc whose pivot sits below the screen; the settled tile stands// upright at the centre and its neighbours lean away. The fan is TURNED, not// scrolled: its one state is `theta`, the angle in degrees of the arc under the// centre line, so tile `i` stands at `i * step - theta` degrees.//// Everything here is pure — no view, no clock — so the snap, the clamp, the// rubber band and the hit-test are tested as functions (`FanGeometryTests`).// Every number is a theme key (`scale.tokens.fan_*`, shipped in paper.json and// plain.json): the reading below has no default of its own.import CoreGraphicsimport Foundationstruct FanGeometry: Equatable, Sendable {    /// A tile's size, portrait.    var tileWidth: Double    var tileHeight: Double    /// The arc's radius: the pivot is this far below the settled tile's centre.    var radius: Double    /// The angle between two tiles, in degrees.    var step: Double    /// Tiles further than this from the centre line are not drawn, in degrees.    var visible: Double    /// The tiles' band: down to the raised settled tile's foot and one band    /// gap under it (`band`).    var height: Double    /// The settled tile's top edge, below the fan's top.    var top: Double    /// How far the settled tile rises, and how much it grows.    var lift: Double    var settledScale: Double    /// How far past either end the fan turns under a finger, as a fraction of a step.    var overscroll: Double    /// A release faster than this, in points a second, is a fling; slower,    /// it is a swipe and turns one tile.    var flingMin: Double    /// A fling released at this speed, in points a second, crosses    /// `flingReach` of the whole fan; faster or slower in proportion.    var flingFull: Double    var flingReach: Double    /// How far a swipe leans, as a fraction of a step, before it turns a tile.    var swipeLean: Double    /// Under this many points of movement a touch is a tap.    var tapSlop: Double    /// A programmatic turn (a tap on a tile, a spoken "show"): its duration    /// per degree and its bounds, in milliseconds.    var turnPerDegree: Double    var turnLongest: Double    var turnShortest: Double    init(        tileWidth: Double, tileHeight: Double, radius: Double, step: Double, visible: Double,        height: Double, top: Double, lift: Double, settledScale: Double,        overscroll: Double, flingMin: Double, flingFull: Double, flingReach: Double, swipeLean: Double,        tapSlop: Double, turnPerDegree: Double, turnLongest: Double, turnShortest: Double    ) {        self.tileWidth = tileWidth        self.tileHeight = tileHeight        self.radius = radius        self.step = step        self.visible = visible        self.height = height        self.top = top        self.lift = lift        self.settledScale = settledScale        self.overscroll = overscroll        self.flingMin = flingMin        self.flingFull = flingFull        self.flingReach = flingReach        self.swipeLean = swipeLean        self.tapSlop = tapSlop        self.turnPerDegree = turnPerDegree        self.turnLongest = turnLongest        self.turnShortest = turnShortest    }    /// The fan the theme draws.    init(scale: ThemeScale) {        // A fan tile is Home's tile (`ToolCard`) at the fan's width: its        // height is the tile's own aspect, never a number of the fan's.        let tileHeight = Double(ToolCardMetrics(scale: scale).height(width: scale[.fanTileW]))        let top = Double(scale[.fanTop]), lift = Double(scale[.fanLift])        let settledScale = Double(scale[.fanSettledScale])        self.init(            tileWidth: Double(scale[.fanTileW]), tileHeight: tileHeight,            radius: Double(scale[.fanRadius]), step: Double(scale[.fanStepDeg]),            visible: Double(scale[.fanVisibleDeg]),            height: Self.band(top: top, tileHeight: tileHeight, lift: lift, settledScale: settledScale,                              gap: Double(scale[.fanCapsGap])),            top: top, lift: lift, settledScale: settledScale,            overscroll: Double(scale[.fanOverscroll]), flingMin: Double(scale[.fanFlingMin]),            flingFull: Double(scale[.fanFlingFull]), flingReach: Double(scale[.fanFlingReach]),            swipeLean: Double(scale[.fanSwipeLean]), tapSlop: Double(scale[.fanTapSlop]), turnPerDegree: Double(scale[.fanTurnMsPerDeg]),            turnLongest: Double(scale[.fanTurnMsMax]), turnShortest: Double(scale[.fanTurnMsMin]))    }    /// The tiles' band from the tile's own size (architect, 15 Oct 2026,    /// 16:50 IST: the owner's 72-wide tiles left wide gaps in bands tuned for    /// 118): from the fan's top down to the raised settled tile's foot, and    /// one band gap under it. No height of the fan assumes one tile size.    static func band(top: Double, tileHeight: Double, lift: Double, settledScale: Double, gap: Double) -> Double {        top - lift + tileHeight * (1 + settledScale) / 2 + gap    }    /// The raised settled tile's foot, in the fan's own frame.    var settledFoot: Double { top + tileHeight / 2 - lift + tileHeight * settledScale / 2 }    // ── Turning ──────────────────────────────────────────────────────────    /// Degrees the fan turns per point a finger moves sideways: a point on    /// the arc's rim follows the finger.    var degreesPerPoint: Double { 180 / (Double.pi * radius) }    /// The last tile's angle.    func end(count: Int) -> Double { Double(max(0, count - 1)) * step }    /// The fan as a finger leaves it: `raw` is where the drag alone would put    /// it, and past either end the fan follows ever less — a rubber band that    /// approaches, and never reaches, `overscroll` of a step beyond the end.    func shown(raw: Double, count: Int) -> Double {        shown(raw: raw, from: 0, to: end(count: count))    }    /// The fan under a finger that came down on tile `start`: it follows the    /// finger as far as the next tile either way, and past that the same    /// rubber band as at the ends — a swipe turns one tile, so it never    /// shows the fan running on under a slow finger (walker pass 2, 16 Oct 2026).    func shown(raw: Double, swipingFrom start: Int, count: Int) -> Double {        let last = end(count: count)        let low = max(0, Double(start - 1) * step), high = min(last, Double(start + 1) * step)        return shown(raw: raw, from: low, to: high)    }    private func shown(raw: Double, from low: Double, to high: Double) -> Double {        let reach = overscroll * step        guard reach > 0 else { return min(max(raw, low), high) }        func band(_ excess: Double) -> Double { reach * excess / (excess + reach) }        if raw < low { return low - band(low - raw) }        if raw > high { return high + band(raw - high) }        return raw    }    /// The tile nearest the centre line.    func nearest(_ theta: Double, count: Int) -> Int {        guard count > 0, step > 0 else { return 0 }        return min(max(Int((theta / step).rounded()), 0), count - 1)    }    /// The tile a release settles on, for a finger that came down on tile    /// `start` and lifted at `theta` moving `pointsPerSecond` sideways    /// (architect, walker pass 2, 16 Oct 2026). A swipe turns ONE tile — the    /// next one the way it leaned, once it leaned `swipeLean` of a step, else    /// back to `start`. A fling, faster than `flingMin`, travels on by its    /// speed: one at `flingFull` crosses `flingReach` of the whole fan, so    /// Tools to Me is two or three flings, whatever the fan's length. With    /// `flings` off (Reduce Motion) every release is a swipe.    func target(from start: Int, releasing theta: Double, pointsPerSecond: Double, count: Int, flings: Bool = true) -> Int {        let last = max(0, count - 1)        func clamped(_ index: Int) -> Int { min(max(index, 0), last) }        let speed = abs(pointsPerSecond)        // A finger moving left turns the fan on (`FanMotion.drag`).        if flings, speed >= flingMin, flingFull > 0 {            let tiles = max(1, Int((speed / flingFull * flingReach * Double(last)).rounded()))            return clamped(start + (pointsPerSecond < 0 ? tiles : -tiles))        }        let leaned = theta - Double(start) * step        guard abs(leaned) >= swipeLean * step else { return clamped(start) }        return clamped(start + (leaned > 0 ? 1 : -1))    }    /// How long a programmatic turn of `degrees` takes, in seconds.    func turnDuration(degrees: Double) -> Double {        min(max(abs(degrees) * turnPerDegree, turnShortest), turnLongest) / 1000    }    // ── Where each tile stands ───────────────────────────────────────────    struct Placement: Equatable {        /// The tile's lean, in degrees: negative to the left.        var angle: Double        /// The tile's centre, in the fan's own frame.        var centre: CGPoint        var scale: Double        /// How near the tile is to settled, 0 to 1: its lift, its shadow.        var nearness: Double        /// Drawn over every tile further from the centre.        var order: Double    }    /// The arc's pivot in a fan `width` wide: under the settled tile's centre.    func pivot(width: Double) -> CGPoint {        CGPoint(x: width / 2, y: top + tileHeight / 2 + radius)    }    /// Where tile `index` stands with the fan at `theta`; nil past `visible`.    func placement(index: Int, theta: Double, width: Double) -> Placement? {        placement(angle: Double(index) * step - theta, width: width)    }    /// Where a tile leaning `angle` degrees from the centre line stands — a    /// card sliding between two slots (`FanSlide`) stands on the arc, too.    func placement(angle: Double, width: Double) -> Placement? {        guard abs(angle) < visible else { return nil }        let nearness = Self.depth(angle: angle, step: step)        let scale = 1 + nearness * (settledScale - 1)        // The nearer card rises by the lift.        let reach = radius + nearness * lift        let radians = angle * .pi / 180        let pivot = pivot(width: width)        return Placement(            angle: angle,            centre: CGPoint(x: pivot.x + reach * sin(radians), y: pivot.y - reach * cos(radians)),            scale: scale,            nearness: nearness,            // Nearer the centre is drawn over; the curve and the distance            // order the same, so order and size never disagree.            order: -abs(angle))    }    /// How near a tile `angle` degrees from the centre line is to standing    /// settled, 0 to 1, on one smooth curve: a raised cosine of the distance    /// over the step, 1 at the centre and 0 a step away, flat at both ends.    /// Lift, scale and drawing order all follow it, so there is no settled    /// state while the fan turns and no tile ever changes depth in one frame    /// (owner, build 280: a tile dived behind its neighbour); two tiles    /// equally far from the centre are the same size and lift, which is the    /// one place their drawing order may swap.    static func depth(angle: Double, step: Double) -> Double {        guard step > 0 else { return 1 }        let distance = min(abs(angle) / step, 1)        return (1 + cos(distance * .pi)) / 2    }    /// The tile under `point` (in the fan's frame), the one drawn on top    /// where two overlap; nil when the point touches none.    func tile(at point: CGPoint, theta: Double, count: Int, width: Double) -> Int? {        var best: (index: Int, order: Double)?        for index in 0..<max(0, count) {            guard let place = placement(index: index, theta: theta, width: width) else { continue }            // Into the tile's own frame: undo the lean about its centre.            let radians = -place.angle * .pi / 180            let dx = Double(point.x - place.centre.x), dy = Double(point.y - place.centre.y)            let x = dx * cos(radians) - dy * sin(radians)            let y = dx * sin(radians) + dy * cos(radians)            let halfWidth = tileWidth * place.scale / 2, halfHeight = tileHeight * place.scale / 2            guard abs(x) <= halfWidth, abs(y) <= halfHeight else { continue }            if best == nil || place.order > best!.order { best = (index, place.order) }        }        return best?.index    }}/// The fan's spring: the snap after a release, integrated a frame at a time so/// the fan knows its angular speed every frame (the live page waits for it to/// drop) and which tile crosses the centre (the haptic tick). `response` and/// `damping` are SwiftUI's spring terms, read from the theme.struct FanSpring: Equatable, Sendable {    var response: Double    var damping: Double    init(response: Double, damping: Double) {        self.response = response        self.damping = damping    }    init(scale: ThemeScale) {        self.init(response: Double(scale[.fanSnapResponse]), damping: Double(scale[.fanSnapDamping]))    }    /// One step of `dt` seconds toward `target`: the new angle and velocity.    /// Integrated in steps no longer than a 240 Hz frame, so a dropped frame    /// does not throw the spring.    func step(theta: Double, velocity: Double, target: Double, dt: Double) -> (theta: Double, velocity: Double) {        guard response > 0 else { return (target, 0) }        let stiffness = pow(2 * Double.pi / response, 2)        let friction = 4 * Double.pi * damping / response        var theta = theta, velocity = velocity, left = max(0, dt)        let longest = 1.0 / 240        while left > 0 {            let h = min(left, longest)            velocity += (-stiffness * (theta - target) - friction * velocity) * h            theta += velocity * h            left -= h        }        return (theta, velocity)    }    /// Close enough to call it still: within a hundredth of a degree and    /// slower than half a degree a second.    static func rests(theta: Double, velocity: Double, target: Double) -> Bool {        abs(theta - target) < 0.01 && abs(velocity) < 0.5    }}/// Cards sliding to new slots when the arc's set changes (291 direction E,/// 17 Oct 2026): at a switch the fan draws every shipped tool from the/// bundle, and the read then adds the database's own tools — each card that/// arrives late slides into its slot with the fan's motion, never a pop.////// A kept card turns along the arc from the lean it was shown at to its new/// slot's; an arriving card stands in its slot and fades in. The target is/// worked out on every frame, so the fan turning at the same time (it keeps/// the tile it rested on) is followed, not fought.struct FanSlide: Equatable {    /// Each kept card's lean when the set changed, by key.    var from: [String: Double] = [:]    /// The cards that were not on the arc before.    var arriving: Set<String> = []    var start: Double = 0    var duration: Double = 0    /// A slide from `shown` (each card's lean now) to the arc of `keys`;    /// nil when the set did not change or there was nothing drawn before.    static func between(shown: [String: Double], keys: [String], at now: Double, duration: Double) -> FanSlide? {        guard duration > 0, !shown.isEmpty, Set(shown.keys) != Set(keys) || shown.count != keys.count else { return nil }        return FanSlide(            from: shown.filter { keys.contains($0.key) },            arriving: Set(keys.filter { shown[$0] == nil }),            start: now, duration: duration)    }    /// How far through, 0 to 1, eased out as the fan's own turns are.    func progress(at now: Double) -> Double {        guard duration > 0 else { return 1 }        let linear = min(max((now - start) / duration, 0), 1)        return 1 - pow(1 - linear, 3)    }    func done(at now: Double) -> Bool { now - start >= duration }    /// The lean card `key` is drawn at, heading for `target`.    func angle(of key: String, target: Double, at now: Double) -> Double {        guard let from = from[key] else { return target }        return from + (target - from) * progress(at: now)    }    /// How much of its own opacity card `key` is drawn with.    func opacity(of key: String, at now: Double) -> Double {        arriving.contains(key) ? progress(at: now) : 1    }}/// When a turn of an arc of choices — the database caps, a tool's ring of/// view slips — is a person's choice, apart from how it is drawn.enum ArcChoice {    /// What moved the arc to an item.    enum Move: Equatable {        /// The arc heads for the item: a tap's turn starts, or a swipe's        /// finger lifts and its fling and spring begin.        case heading        /// The arc came to rest on the item.        case settled    }    /// RULE: an item is chosen by a person's settled choice — a tap's turn at    /// once (the switch starts as the arc turns, 292), a swipe only where it    /// comes to rest. A swipe's heading is where a fling may land, so choosing    /// on it switched database as the caps scrolled, through every database    /// on the way to a far cap (walker294 row 18). A rest or a turn nobody    /// asked for (the arc mounting, its items arriving, a turn back) chooses    /// nothing.    static func chooses(_ move: Move, byPerson: Bool, swiped: Bool) -> Bool {        guard byPerson else { return false }        switch move {        case .heading: return !swiped        case .settled: return swiped        }    }}// The label's fitted box is shared by painting and geometry assertions.extension FanGeometry {    /// The words' box under a tier card's picture: wide enough for a    /// door's "Goodreads" at the typewriter's size, deep enough for two    /// lines (`FanTierWords`).    static let labelWidthRatio = 0.7    static let labelHeightRatio = 0.24    static let labelCentreRatio = 0.77    func labelFrame(index: Int, theta: Double, width: Double) -> CGRect? {        guard let place = placement(index: index, theta: theta, width: width) else { return nil }        let radians = place.angle * .pi / 180        let offset = tileHeight * (Self.labelCentreRatio - 0.5) * place.scale        let centre = CGPoint(x: place.centre.x - offset * sin(radians), y: place.centre.y + offset * cos(radians))        let w = tileWidth * Self.labelWidthRatio * place.scale        let h = tileHeight * Self.labelHeightRatio * place.scale        let bounds = CGSize(width: abs(w * cos(radians)) + abs(h * sin(radians)),                            height: abs(w * sin(radians)) + abs(h * cos(radians)))        return CGRect(x: centre.x - bounds.width / 2, y: centre.y - bounds.height / 2, width: bounds.width, height: bounds.height)    }}extension FanGeometry {    // Measured from peek-close.png: tool 222px, slips 200px, headers    // 40px high, steps 31px, type 20px; the slips lean by a few degrees.    static let peekWidthRatio = 0.90    static let peekHeightRatio = 0.18    static let peekStepRatio = 0.14    static let peekTypeRatio = 0.09    static let peekAngles = [-1.0, 2.0, -2.0]    var peekHeight: Double { tileWidth * (Self.peekHeightRatio + 2 * Self.peekStepRatio) }    struct PeekPlacement: Equatable {        let width: Double        let height: Double        let rise: Double        let angle: Double        let typeSize: Double    }    func peekCentre(attachedTo card: Placement) -> CGPoint {        let rise = (tileHeight / 2 + peekHeight / 2 - tileWidth * 0.02) * card.scale        let radians = card.angle * Double.pi / 180        return CGPoint(x: card.centre.x + rise * sin(radians), y: card.centre.y - rise * cos(radians))    }    func peekPlacement(index: Int) -> PeekPlacement {        PeekPlacement(width: tileWidth * Self.peekWidthRatio, height: tileWidth * Self.peekHeightRatio,                      rise: Double(index) * tileWidth * Self.peekStepRatio,                      angle: Self.peekAngles[index], typeSize: tileWidth * Self.peekTypeRatio)    }}