Cotton code
185 lines · 6.9 KB · SwiftRaw
// The list column's keyboard selection: ↑↓ move it, return opens it.//// A window with a list in it is read from the keyboard as much as the pointer,// and the paper collections are scroll views of objects rather than a SwiftUI// `List`, so nothing gives them a selection for free. This is that selection,// and it is deliberately small: WHICH object is selected, in what order the// objects sit, and the one arithmetic that moves between them.//// **Who does what.** The HOST owns one of these per list column and puts it in// the environment (`\.cottonListKeyboard`); the host reads the keys and opens// what is selected. A `PaperCollection` that was told what each of its objects// opens (`opens:`) registers those routes here and draws the mark on the// selected one; `PaperScreen` scrolls the selected object into view. The phone// sets nothing, so on the phone every one of those reads finds `nil` and draws// what it always drew. Nothing here branches on the platform.//// **The order is the page's, read off the screen.** One screen can hold several// collections — the notes list is one per month — and each registers as a// SEGMENT with where its top currently sits. The order is the segments sorted// top to bottom, so it is whatever order a person sees, and no screen has to// declare it. A collection that leaves the screen (a lazy stack unloading a// month) takes its segment with it; moving down scrolls the next one in, which// registers it.import CottonKitimport Observationimport SwiftUI/// Which way a key moves the selection.public enum ListKeyboardMove: Sendable {    case up    case down}@MainActor@Observablepublic final class ListKeyboard {    /// One object a collection can open: the route, and the id its cell is    /// laid out under (what a scroll view scrolls to).    public struct Entry: Equatable {        public let route: Route        public let anchor: AnyHashable        public init(route: Route, anchor: AnyHashable) {            self.route = route            self.anchor = anchor        }    }    /// The selected object's route, or nothing.    public private(set) var selected: Route?    /// The selected object's cell id, when a registered collection holds it —    /// what `PaperScreen` scrolls to.    public private(set) var selectedAnchor: AnyHashable?    /// One collection's objects and where its top sits on screen.    ///    /// Not observed: the tops change on every frame of a scroll, and nothing    /// draws them — they are read only when a key is pressed.    private struct Segment {        var top: CGFloat        var entries: [Entry]    }    @ObservationIgnored private var segments: [UUID: Segment] = [:]    public init() {}    // MARK: - Collections register    /// A collection's objects, in its own order.    public func register(_ segment: UUID, entries: [Entry]) {        let top = segments[segment]?.top ?? 0        segments[segment] = Segment(top: top, entries: entries)        refreshAnchor()    }    /// Where a collection's top currently is, in the window.    public func place(_ segment: UUID, top: CGFloat) {        segments[segment]?.top = top    }    /// A collection left the screen.    public func unregister(_ segment: UUID) {        segments[segment] = nil    }    /// Every registered object, top to bottom.    public var order: [Entry] {        segments            // Ties (two collections side by side) break on the id so the order            // is the same on every press rather than whatever a dictionary gave.            .sorted { ($0.value.top, $0.key.uuidString) < ($1.value.top, $1.key.uuidString) }            .flatMap(\.value.entries)    }    // MARK: - Keys move it    /// ↑ or ↓: select the neighbour, or the first (last) object when nothing    /// registered is selected yet.    public func move(_ direction: ListKeyboardMove) {        let entries = order        guard            let index = Self.index(                after: entries.map(\.route).firstIndex(where: { $0 == selected }),                count: entries.count,                moving: direction            )        else { return }        selected = entries[index].route        selectedAnchor = entries[index].anchor    }    /// The host says what is open, so the selection starts from the object    /// the person last clicked rather than from the top.    public func follow(_ route: Route?) {        guard route != selected else { return }        selected = route        refreshAnchor()    }    /// The column's root changed: a different list, so nothing in it is    /// selected yet.    public func clear() {        selected = nil        selectedAnchor = nil    }    private func refreshAnchor() {        let anchor = order.first(where: { $0.route == selected })?.anchor        if anchor != selectedAnchor { selectedAnchor = anchor }    }    // MARK: - The arithmetic    /// Where a move lands, over `count` objects, from the selected position.    ///    /// - Nothing to move through: nowhere.    /// - Nothing selected (or the selection is not on this screen): ↓ is the    ///   first object and ↑ the last, the two ends a person reaches for.    /// - Otherwise one step, stopping at either end rather than wrapping — a    ///   list that wraps puts the top of the list under a key held at its foot.    nonisolated static func index(after current: Int?, count: Int, moving direction: ListKeyboardMove) -> Int? {        guard count > 0 else { return nil }        guard let current, current >= 0, current < count else {            return direction == .down ? 0 : count - 1        }        switch direction {        case .down: return min(current + 1, count - 1)        case .up: return max(current - 1, 0)        }    }}private struct CottonListKeyboardKey: EnvironmentKey {    /// Nil, and nil is the phone: no column, no keyboard selection.    static let defaultValue: ListKeyboard? = nil}extension EnvironmentValues {    /// The list column's keyboard selection, set by the Mac's host on column 2    /// only. Read by `PaperCollection` and `PaperScreen`; no screen reads it.    public var cottonListKeyboard: ListKeyboard? {        get { self[CottonListKeyboardKey.self] }        set { self[CottonListKeyboardKey.self] = newValue }    }}extension View {    /// The mark on the object the keyboard has selected: a thin ink outline a    /// few points outside the object, so it reads as a pencil ring around the    /// paper rather than a system focus ring laid on it.    func cottonKeyboardSelected(_ selected: Bool) -> some View {        overlay {            if selected {                RoundedRectangle(cornerRadius: 8, style: .continuous)                    .stroke(CottonColors.ink.opacity(0.55), lineWidth: 1.5)                    .padding(-5)                    .allowsHitTesting(false)                    .accessibilityHidden(true)            }        }        .accessibilityAddTraits(selected ? .isSelected : [])    }}