Cotton code
432 lines · 17.0 KB · SwiftRaw
// An arc of pictures turned by one angle (fan3 part 0b). Home's tiles stand on// it, and the database caps on a smaller one about the same pivot: one// implementation, parameterised by the geometry (`FanGeometry` — its radius,// step, size, lift and scale), never a copy.//// The arc is UIKit, not SwiftUI, for one reason: a frame of a turn must cost// nothing. Each item is a view holding its picture, drawn once// (`FanTilePrints`); the motion's display link moves, leans and scales them// directly (`FanMotion.onMove`), in one Core Animation transaction with no// SwiftUI pass, no body and no redraw. Drawn by SwiftUI, every frame// re-evaluated thirty tiles and re-rasterised each picture at its new scale// (fanperf, fan3: 12–96 ms commits while turning).//// The finger is SwiftUI's (the `DragGesture` around the arc); the items are// accessibility elements of their own, at their own frames, so VoiceOver and// XCUITest find each tile where it stands.#if os(iOS)import SwiftUIimport UIKit/// One picture on the arc.struct FanArcItem: Equatable {    let key: String    let label: String    /// The item drawn once, its shadow inside; nil until it is drawn.    let picture: UIImage?    let identifier: String    /// Its picture while the arc rests on it, where it has one of its own    /// (a look's filled current tile, `FanCurrentPrint`); nil shows `picture`.    var current: UIImage? = nil}struct FanArc: UIViewRepresentable {    let items: [FanArcItem]    let geometry: FanGeometry    let motion: FanMotion    /// How far each picture reaches past its item's frame, on every side.    let reach: Double    /// The opacity of an item a step or more from the centre; 1 at the centre.    let faintest: Double    let settled: Int    /// The arc is not read out (`fanArcUnread`): an input, so a change of it    /// updates the UIKit view — read from `context.environment` alone it did    /// not, and a tucked fan's cards stayed in VoiceOver's reach (walk, 16    /// Oct 2026).    let unread: Bool    /// How long a card takes to slide to a new slot when the set changes,    /// in seconds; 0 moves it at once (`FanSlide`).    var slide: Double = 0    let onActivate: (Int) -> Void    func makeUIView(context: Context) -> FanArcView {        let view = FanArcView(geometry: geometry)        motion.onMove = { [weak view] theta in view?.move(to: theta) }        return view    }    func updateUIView(_ view: FanArcView, context: Context) {        // The arc's items are UIKit's: SwiftUI's accessibilityHidden over        // the arc never reaches them (walker pass 3: a folded fan read its        // ~20 tiles and the caps as tiny buttons), and neither did the        // view's own accessibilityElementsHidden through SwiftUI's bridge        // (walker on 289: 32 tiles and 15 caps in a 0.25 × 0.05 strip), so        // each item stops being an element itself.        view.unread = unread        view.geometry = geometry        view.reach = reach        view.faintest = faintest        view.settled = settled        view.slideDuration = slide        view.onActivate = onActivate        view.show(items)        view.move(to: motion.theta)    }}final class FanArcView: UIView {    var geometry: FanGeometry    var reach: Double = 0    var faintest: Double = 1    var settled = 0    var slideDuration: Double = 0    var onActivate: (Int) -> Void = { _ in }    /// Not read out: no item is an accessibility element while it holds.    var unread = false {        didSet {            guard unread != oldValue else { return }            accessibilityElementsHidden = unread            tiles.forEach { $0.unread = unread }            UIAccessibility.post(notification: .layoutChanged, argument: nil)        }    }    /// Unread, the arc offers no element at all; a tree reader that walks    /// subviews met each item's button trait and identifier still (walker294    /// rows 33, 96: ~60 tiles and caps under the mic and under a tray).    override var accessibilityElements: [Any]? {        get { unread ? [] : super.accessibilityElements }        set { super.accessibilityElements = newValue }    }    private var items: [FanArcItem] = []    private var tiles: [FanArcTile] = []    private var theta: Double = 0    /// Each card's lean as last drawn, by key: where a slide starts from.    private var drawn: [String: Double] = [:]    private var slide: FanSlide?    private var slideLink: CADisplayLink?    init(geometry: FanGeometry) {        self.geometry = geometry        super.init(frame: .zero)        // The finger is the SwiftUI gesture's around the arc.        isUserInteractionEnabled = false        clipsToBounds = false    }    @available(*, unavailable)    required init?(coder: NSCoder) { nil }    func show(_ next: [FanArcItem]) {        guard next != items else { return }        if next.map(\.key) != items.map(\.key) {            let shown = Dictionary(tiles.enumerated().map { index, tile in                (tile.key, drawn[tile.key] ?? Double(index) * geometry.step - theta)            }, uniquingKeysWith: { first, _ in first })            slide = FanSlide.between(                shown: shown, keys: next.map(\.key), at: CACurrentMediaTime(), duration: slideDuration) ?? slide            if slide != nil, slideLink == nil {                let link = CADisplayLink(target: self, selector: #selector(slideFrame))                link.add(to: .main, forMode: .common)                slideLink = link            }        }        // Keep each item's view by key, so a picture arriving swaps contents only.        var kept = Dictionary(tiles.map { ($0.key, $0) }, uniquingKeysWith: { first, _ in first })        tiles = next.enumerated().map { index, item in            let tile = kept.removeValue(forKey: item.key) ?? FanArcTile(key: item.key)            tile.index = index            tile.owner = self            tile.unread = unread            tile.show(item)            if tile.superview !== self { addSubview(tile) }            return tile        }        kept.values.forEach { $0.removeFromSuperview() }        items = next        place()    }    func move(to theta: Double) {        self.theta = theta        place()    }    override func layoutSubviews() {        super.layoutSubviews()        place()    }    fileprivate func activate(_ index: Int) { onActivate(index) }    @objc private func slideFrame() {        place()        guard let slide, !slide.done(at: CACurrentMediaTime()) else {            slide = nil            slideLink?.invalidate()            slideLink = nil            place()            return        }    }    override func removeFromSuperview() {        slideLink?.invalidate()        slideLink = nil        super.removeFromSuperview()    }    private func place() {        CATransaction.begin()        CATransaction.setDisableActions(true)        let width = Double(bounds.width)        let size = CGSize(width: geometry.tileWidth + reach * 2, height: geometry.tileHeight + reach * 2)        let now = CACurrentMediaTime()        drawn = [:]        for (index, tile) in tiles.enumerated() {            let target = Double(index) * geometry.step - theta            let angle = slide?.angle(of: tile.key, target: target, at: now) ?? target            drawn[tile.key] = angle            guard let place = geometry.placement(angle: angle, width: width) else {                tile.isHidden = true                continue            }            tile.isHidden = false            if tile.bounds.size != size { tile.bounds = CGRect(origin: .zero, size: size) }            tile.center = place.centre            tile.transform = CGAffineTransform(rotationAngle: place.angle * .pi / 180)                .scaledBy(x: place.scale, y: place.scale)            tile.layer.zPosition = place.order            tile.alpha = (faintest + (1 - faintest) * place.nearness) * (slide?.opacity(of: tile.key, at: now) ?? 1)            tile.accessibilityTraits = tile.unread ? .none : index == settled ? [.button, .selected] : .button            tile.rests(index == settled)        }        CATransaction.commit()    }}/// An arc and the finger that turns it — Home's tiles or the database caps./// A finger landing calls `onDown` before the arc moves; a touch that moves/// less than the tap slop is a tap on the item under it; a release flings/// and the spring snaps (`FanMotion`).struct FanArcDeck: View {    let items: [FanArcItem]    let motion: FanMotion    let geometry: FanGeometry    var reach: Double = 0    var faintest: Double = 1    let reduceMotion: Bool    /// Cards slide to new slots when the set changes (`FanSlide`); 0 for an    /// arc whose set does not grow under the finger.    var slide: Double = 0    var onDown: () -> Void = {}    /// A touch held still on an item (`PressRule.longPressSeconds`): answers    /// whether the hold opened something, and a hold taken neither taps nor    /// turns. Nil, a hold is a touch that stayed (Settings' Export chip,    /// `ViewRingArc`).    var onHold: ((Int) -> Bool)? = nil    let onTap: (Int) -> Void    @State private var dragging = false    /// The hold waiting under the finger, and the touch a hold was taken    /// on, by where it landed: the rest of that touch is the hold's.    @State private var holding: Task<Void, Never>?    @State private var heldAt: CGPoint?    @Environment(\.fanArcUnread) private var unread    var body: some View {        GeometryReader { proxy in            let width = Double(proxy.size.width)            ZStack(alignment: .topLeading) {                FanArc(                    items: items, geometry: geometry, motion: motion, reach: reach, faintest: faintest,                    settled: motion.settled, unread: unread, slide: reduceMotion ? 0 : slide, onActivate: onTap)                // The finger lands on SwiftUI's own layer over the arc: a                // gesture on the UIKit view itself never sees the touch.                Color.clear                    .contentShape(Rectangle())                    .gesture(turning(width: width))                    .accessibilityHidden(true)            }            .frame(width: proxy.size.width, height: proxy.size.height, alignment: .topLeading)        }    }    private func turning(width: Double) -> some Gesture {        DragGesture(minimumDistance: 0, coordinateSpace: .local)            .onChanged { value in                guard heldAt != value.startLocation else { return }                let moved = hypot(Double(value.translation.width), Double(value.translation.height))                if !dragging {                    dragging = true                    // What the finger lands on is replaced in one frame, with                    // no fade (the fan's page by its own picture).                    var instant = Transaction()                    instant.disablesAnimations = true                    withTransaction(instant) {                        onDown()                        motion.beginDrag()                    }                    if let onHold { holding = hold(at: value.startLocation, width: width, onHold) }                }                if moved >= geometry.tapSlop { holding?.cancel() }                motion.drag(Double(value.translation.width))            }            .onEnded { value in                holding?.cancel()                holding = nil                dragging = false                if heldAt == value.startLocation {                    heldAt = nil                    return                }                let moved = hypot(Double(value.translation.width), Double(value.translation.height))                if moved < geometry.tapSlop,                   let index = geometry.tile(at: value.location, theta: motion.theta, count: items.count, width: width) {                    // The touch put the arc down where it was; the tap turns it.                    motion.release(pointsPerSecond: 0, flings: false)                    onTap(index)                    return                }                motion.release(pointsPerSecond: Double(value.velocity.width), flings: !reduceMotion)            }    }    /// The hold under a finger that landed at `point`: once it has stayed    /// still a long press, the item under it is offered the hold; taken, the    /// arc is put down where it stood.    private func hold(at point: CGPoint, width: Double, _ onHold: @escaping (Int) -> Bool) -> Task<Void, Never> {        Task { @MainActor in            try? await Task.sleep(for: .seconds(PressRule.longPressSeconds))            guard !Task.isCancelled, dragging,                  let index = geometry.tile(at: point, theta: motion.theta, count: items.count, width: width),                  onHold(index) else { return }            heldAt = point            motion.release(pointsPerSecond: 0, flings: false)        }    }}/// Pictures of the items on an arc, each drawn once while the window is/// still and kept for as long as its item is shown (fan3 part 0). A picture/// is of its item as it was drawn (`Signature`): an item that changes is/// drawn again.@MainActor@Observablefinal class FanPrints<Signature: Equatable> {    private(set) var prints: [String: UIImage] = [:]    @ObservationIgnored private var drawn: [String: Signature] = [:]    /// The picture of `key` as `signature` looks; nil until it is drawn. The    /// prints are read either way, so a body that found none is drawn again    /// once it is: cards that arrive after their fan opened (This device's    /// acts, read after the hold) were never shown.    func picture(_ key: String, _ signature: Signature) -> UIImage? {        let print = prints[key]        return drawn[key] == signature ? print : nil    }    func draw(_ key: String, _ signature: Signature, scale: Double, environment: EnvironmentValues, content: some View) {        let renderer = ImageRenderer(content: content.environment(\.self, environment))        renderer.scale = scale        renderer.isOpaque = false        guard let image = renderer.uiImage else { return }        drawn[key] = signature        prints[key] = image    }    func keepOnly(_ keys: Set<String>) {        drawn = drawn.filter { keys.contains($0.key) }        prints = prints.filter { keys.contains($0.key) }    }    func clear() {        drawn = [:]        prints = [:]    }}/// One item's view: its picture as the layer's contents, and its/// accessibility element.private final class FanArcTile: UIView {    let key: String    var index = 0    weak var owner: FanArcView?    /// Out of the tree: no element, nothing under it, and no button trait.    var unread = false {        didSet {            isAccessibilityElement = !unread            accessibilityElementsHidden = unread            if unread { accessibilityTraits = .none }        }    }    init(key: String) {        self.key = key        super.init(frame: .zero)        isAccessibilityElement = true        layer.contentsGravity = .resize    }    @available(*, unavailable)    required init?(coder: NSCoder) { nil }    private var item: FanArcItem?    /// The arc rests on it.    private var settled = false    func show(_ item: FanArcItem) {        accessibilityLabel = item.label        accessibilityIdentifier = item.identifier        self.item = item        paint()    }    /// The arc rests on it, or no longer: its current picture or its own.    /// Only the layer's contents change — nothing is drawn.    func rests(_ settled: Bool) {        guard settled != self.settled else { return }        self.settled = settled        paint()    }    private func paint() {        // A card being printed again keeps its last print until the new one        // is drawn: a card with no picture for those frames is a card blinking        // out of the arc (295 B: Me's card, printed again with each new face).        guard let picture = (settled ? item?.current : nil) ?? item?.picture else { return }        layer.contents = picture.cgImage        layer.contentsScale = picture.scale    }    override func accessibilityActivate() -> Bool {        owner?.activate(index)        return true    }}private struct FanArcUnreadKey: EnvironmentKey {    static let defaultValue = false}extension EnvironmentValues {    /// The arc is not read out: the fan is folded or put away.    var fanArcUnread: Bool {        get { self[FanArcUnreadKey.self] }        set { self[FanArcUnreadKey.self] = newValue }    }}extension View {    /// Out of the accessibility tree while `hidden`, the arcs' UIKit items    /// with it; an arc hidden by any view over it stays hidden.    ///    /// Only ever hides: `accessibilityHidden(false)` round a page brought    /// back everything the page itself hid (a card's paper as two unnamed    /// images, Comms' decoration over the status bar as an unnamed bar),    /// since every page under a card host (`cardLayers`) wore it while no    /// card was up.    func fanArcHidden(_ hidden: Bool) -> some View {        accessibilityHidden(true, isEnabled: hidden).transformEnvironment(\.fanArcUnread) { $0 = $0 || hidden }    }}#endif