Cotton code
464 lines · 21.4 KB · SwiftRaw
// Lift, dim, list: the one way a thing on a page offers its acts (slipacts,// the owner's go 18 Oct 2026).//// Tap a thing with more than one act — a slip on a record page first; a// message, a comment, a row and a tile adopt it next — and it lifts (scale and// shadow, `slip_lift`, `slip_shadow`; the `press` haptic), the rest of the page// darkens by `page_dim` (no blur), and a card of the page's paper hangs under// it — over it when it sits in the lower third, or when the card would not fit// beneath — listing its acts one row each: the act's object and its word, rows// never under `slip_act_row`, the act that takes the thing away last, in red.// The thing's own words stay whole above the card. A row acts and the card// folds; so does a tap or a drag down anywhere dimmed. Reduce Motion// crossfades. While the card is up nothing on the page moves: the thing is// drawn lifted over its own place, which keeps its room.//// A row that edits (a fact of a lifted fact group, `LiftedEditor`) does not// fold the card: the same card swaps its rows for that fact's editor, with// back to the rows at its head and Done — and Clear, for a fact that may be// empty — at its foot (actlift row 1, 21 Oct 2026). Done writes what the// editor holds; back drops it. One surface: never a second sheet.//// The words, objects and order of the acts are the caller's data, ranked by// the core where the core answered them (`card_actions::ranked`, red last);// this file names no act, no object and no measure.import CottonKitimport CottonValuesimport SwiftUI/// One row of the lifted card: an act's object and word, and what it does.struct LiftedAct: Identifiable {    var id: String    var word: String    var object: CardEnamel?    /// It takes the thing away: drawn red, and last.    var destroys: Bool    /// A quiet line at the row's end: when a channel was last used.    var detail: String? = nil    /// A fact with nothing in it: its word in pencil, the sign it is written here.    var blank: Bool = false    /// Why the row neither acts nor edits (the core's line): drawn under it.    var why: String? = nil    /// The row edits in the card itself instead of acting (a fact's row).    var editor: LiftedEditor? = nil    var perform: () -> Void}/// A fact edited in the lifted card: its value, the editor that changes a/// draft of it, and the write Done (or Clear) makes. The editor never/// writes; it hands each change back, and the card holds it as the draft.struct LiftedEditor {    var value: RecordValue    /// The fact may be emptied: the card offers Clear.    var clears: Bool    /// The editor showing `value` (the draft), handing each change back.    var view: (_ value: RecordValue, _ change: @escaping (RecordValue) -> Void) -> AnyView    /// One ordinary write, with the undo pill.    var write: (RecordValue) -> Void}/// What is lifted: which thing, where it stands on the screen, how it draws,/// and its acts.struct Lifted: Identifiable {    var id: String    var frame: CGRect    var face: AnyView    var acts: [LiftedAct]    /// The thing as a layer standing at `origin` on the screen draws it:    /// its frame was measured on the screen (`.global`).    func drawn(from origin: CGPoint) -> Lifted {        Lifted(id: id, frame: frame.offsetBy(dx: -origin.x, dy: -origin.y), face: face, acts: acts)    }}/// The lifting region's one lifted thing. A page that draws things with acts/// hosts it (`liftsActs()`); the things lift into it.@MainActor @Observablefinal class ActLift {    private(set) var lifted: Lifted?    /// The row whose editor the card shows instead of its rows.    private(set) var editing: String?    /// What that editor holds, before Done writes it.    var draft: RecordValue?    func lift(_ thing: Lifted) {        editing = nil        draft = nil        lifted = thing    }    func fold() {        lifted = nil        editing = nil        draft = nil    }    /// The card becomes this row's editor.    func edit(_ row: String) {        draft = nil        editing = row    }    /// Back to the rows; the draft is dropped.    func back() {        editing = nil        draft = nil    }    /// Done or Clear: the card folds and the value is written.    func write(_ editor: LiftedEditor, _ value: RecordValue) {        fold()        if value != editor.value { editor.write(value) }    }}private struct ActLiftKey: EnvironmentKey {    static let defaultValue: ActLift? = nil}extension EnvironmentValues {    /// The region a thing with several acts lifts into.    var actLift: ActLift? {        get { self[ActLiftKey.self] }        set { self[ActLiftKey.self] = newValue }    }}/// Where a lifted card stands: a pure function of the thing's frame, the/// region and the card's size.enum LiftedActsLayout {    /// The card hangs over the thing — never under it — when the thing sits    /// in the region's lower third, or when the card would not fit beneath    /// it but would above.    static func above(thing: CGRect, card: CGFloat, region: CGSize, gap: CGFloat) -> Bool {        if thing.midY > region.height * LiftedActsKnobs.lowerThird { return true }        let beneath = region.height - thing.maxY - gap        return beneath < card && thing.minY - gap > beneath    }    /// The card's width: the thing's, and never under `least`, inside the region.    static func width(thing: CGRect, least: CGFloat, region: CGSize, inset: CGFloat) -> CGFloat {        min(max(thing.width, least), max(0, region.width - 2 * inset))    }    /// The band of the region the card hangs in: from the thing's foot down,    /// or from the region's top to the thing's head. The card is laid inside    /// it, against the thing's side of it, so placing the card never moves    /// the thing — the lifted thing stays exactly over its own place (walker    /// 298: a held message in the lower third dropped by the card's height    /// to the composer, its list above it).    static func room(thing: CGRect, above: Bool, region: CGSize, gap: CGFloat) -> CGRect {        above            ? CGRect(x: 0, y: 0, width: region.width, height: max(0, thing.minY - gap))            : CGRect(x: 0, y: thing.maxY + gap, width: region.width, height: max(0, region.height - thing.maxY - gap))    }    /// The card's height before it is measured: its rows at their least    /// height and the rules between them. The above-or-beneath choice reads    /// this card's height, never the last lift's.    static func cardHeight(rows: Int, row: CGFloat, rule: CGFloat) -> CGFloat {        CGFloat(rows) * row + CGFloat(max(0, rows - 1)) * rule    }    /// Where the card stands for any host — slip, row, message, tile, tray:    /// in its band beneath the thing, or above it in the lower third, at the    /// thing's leading edge moved in only to stay in the region. Never beside.    static func card(thing: CGRect, height: CGFloat, region: CGSize, gap: CGFloat, inset: CGFloat, least: CGFloat) -> CGRect {        let above = above(thing: thing, card: height, region: region, gap: gap)        let room = room(thing: thing, above: above, region: region, gap: gap)        let width = width(thing: thing, least: least, region: region, inset: inset)        let x = leading(thing: thing, width: width, region: region, inset: inset)        return CGRect(x: x, y: above ? room.maxY - height : room.minY, width: width, height: height)    }    /// The card's leading edge: under the thing's, moved in only as far as    /// keeps the card in the region.    static func leading(thing: CGRect, width: CGFloat, region: CGSize, inset: CGFloat) -> CGFloat {        max(inset, min(thing.minX, region.width - inset - width))    }}extension View {    /// The region things on this page lift into: it dims under the lifted    /// thing and hangs its acts by it. The widest region hosts: under a    /// region that already lifts (Home's whole screen, its chrome and dial    /// with it) this passes the page through, so the dim reaches every edge.    func liftsActs() -> some View { modifier(LiftedActsRegion()) }}private struct LiftedActsRegion: ViewModifier {    @Environment(\.actLift) private var outer    func body(content: Content) -> some View {        if outer == nil {            content.modifier(LiftedActsHost())        } else {            content        }    }}/// The region's host: the page, and over it, while a thing is lifted, the/// dimmed paper, the thing lifted over its own place and its card of acts.private struct LiftedActsHost: ViewModifier {    @Environment(\.theme) private var theme    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var lift = ActLift()    /// The card as last measured, and whose card it was.    @State private var measured: (id: String, height: CGFloat)?    func body(content: Content) -> some View {        let lifted = lift.lifted        content            // Modal to a tree reader: while a thing is lifted only it and its            // rows are read. The page under the dim leaves the tree with every            // UIKit arc and every tile stack in it — SwiftUI's hide alone left            // the 38 buttons behind the dim read (walker 298).            .coveredUnread(lifted != nil)            .coversTheTileStacks(lifted != nil)            // The status bar steps aside while a thing is lifted, so a tap on            // the dimmed strip it stood in reaches the fold like any other.            .hidesTheStatusBar(lifted != nil)            .environment(\.actLift, lift)            .overlay {                // The rest of the page darkens to the screen's edges; a tap                // or a drag down on it folds the card.                if lifted != nil {                    Rectangle()                        .fill(theme.colors.shadow.color.opacity(Double(theme.scale[.pageDim])))                        .ignoresSafeArea()                        .contentShape(Rectangle())                        .onTapGesture { lift.fold() }                        .accessibilityHidden(true)                        .transition(.opacity)                }            }            .overlay {                GeometryReader { region in                    // The thing was measured on the screen; the layer draws                    // from its own place on it.                    let origin = region.frame(in: .global).origin                    if let lifted { raised(lifted.drawn(from: origin), region: region.size) }                }                // To the screen's edges, as the dim: its tap-to-fold covers the                // status-bar and home-indicator strips too (walker 298: a tap                // on the dimmed status-bar strip left the list up). Never the                // keyboard's: a slip that is typed into hangs its card above it.                .ignoresSafeArea(.container)            }            .animation(reduceMotion ? .easeInOut(duration: Double(LiftedActsKnobs.crossfade))                : .spring(response: Double(LiftedActsKnobs.liftResponse), dampingFraction: Double(LiftedActsKnobs.liftDamping)),                value: lifted?.id)            .animation(reduceMotion ? .easeInOut(duration: Double(LiftedActsKnobs.crossfade))                : .spring(response: Double(LiftedActsKnobs.liftResponse), dampingFraction: Double(LiftedActsKnobs.liftDamping)),                value: lift.editing)    }    private func raised(_ lifted: Lifted, region: CGSize) -> some View {        let scale = theme.scale        let gap = scale[.slipGap]        let inset = scale[.slipPad]        // The lifted thing grows about its centre: the card clears its grown edge.        let grown = reduceMotion ? 1 : scale[.slipLift]        let thing = lifted.frame.insetBy(dx: -lifted.frame.width * (grown - 1) / 2, dy: -lifted.frame.height * (grown - 1) / 2)        let least = LiftedActsLayout.cardHeight(rows: lift.editing == nil ? lifted.acts.count : 2, row: scale[.slipActRow], rule: scale[.slipEdge])        let shown = lifted.id + "/" + (lift.editing ?? "")        let card = max(least, measured.flatMap { $0.id == shown ? $0.height : nil } ?? 0)        let above = LiftedActsLayout.above(thing: thing, card: card, region: region, gap: gap)        let width = LiftedActsLayout.width(thing: thing, least: scale[.slipListW], region: region, inset: inset)        let x = LiftedActsLayout.leading(thing: thing, width: width, region: region, inset: inset)        let room = LiftedActsLayout.room(thing: thing, above: above, region: region, gap: gap)        return ZStack(alignment: .topLeading) {            // Taps between the thing and its card fold it, as the dim does.            Color.clear                .contentShape(Rectangle())                .onTapGesture { lift.fold() }                .accessibilityHidden(true)            lifted.face                .frame(width: lifted.frame.width, height: lifted.frame.height)                .scaleEffect(grown)                .shadow(color: theme.colors.shadow.color.opacity(Double(LiftedActsKnobs.shadowOpacity)), radius: scale[.slipShadow])                .offset(x: lifted.frame.minX, y: lifted.frame.minY)                .allowsHitTesting(false)                // The lifted thing reads as itself, first, above its rows.                .accessibilityElement(children: .combine)                .accessibilityRemoveTraits(.isButton)                .accessibilitySortPriority(1)                .transition(.identity)            Group {                if let row = lifted.acts.first(where: { $0.id == lift.editing }), let editor = row.editor {                    LiftedEditorCard(word: row.word, editor: editor, lift: lift)                } else {                    LiftedActsCard(acts: lifted.acts) { act in                        if act.editor != nil { return lift.edit(act.id) }                        lift.fold()                        act.perform()                    }                }            }            .frame(width: width)            .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { measured = (shown, $0) }            // Laid in its own band against the thing, never by an alignment            // guide: a card hung by its foot from the stack's top grew the            // stack upward, and the stack's frame then pushed everything in            // it — the lifted thing too — down by the card's height.            .padding(.leading, x)            .frame(width: room.width, height: room.height, alignment: above ? .bottomLeading : .topLeading)            .offset(y: room.minY)            .transition(reduceMotion ? .opacity                : .scale(scale: LiftedActsKnobs.unfoldFrom, anchor: above ? .bottom : .top).combined(with: .opacity))        }        .frame(width: region.width, height: region.height, alignment: .topLeading)        .simultaneousGesture(DragGesture(minimumDistance: scale[.slipPad]).onEnded { drag in            if drag.translation.height > 0 { lift.fold() }        })        // Its rows stay buttons of their own; the escape gesture folds it.        .accessibilityElement(children: .contain)        .accessibilityAddTraits(.isModal)        .accessibilityAction(.escape) { lift.fold() }    }}extension View {    /// Every UIKit tile stack under this view leaves the tree while covered    /// (`TileStack.readsTop`); the Mac has none.    func coversTheTileStacks(_ covered: Bool) -> some View {        #if os(iOS)        transformEnvironment(\.fanPagesCovered) { $0 = $0 || covered }        #else        self        #endif    }    /// The phone's status bar is hidden while `hidden`; the Mac has none.    func hidesTheStatusBar(_ hidden: Bool) -> some View {        #if os(iOS)        statusBarHidden(hidden)        #else        self        #endif    }}/// The lifted thing's card of acts: one row each, the act's object and its/// word in the body face, a pencil line between rows.struct LiftedActsCard: View {    @Environment(\.theme) private var theme    let acts: [LiftedAct]    var onAct: (LiftedAct) -> Void    var body: some View {        let scale = theme.scale        let shape = RoundedRectangle(cornerRadius: scale[.slipRadius], style: .continuous)        VStack(spacing: 0) {            ForEach(Array(acts.enumerated()), id: \.element.id) { index, act in                if index > 0 {                    Rectangle().fill(theme.colors.hairline.color).frame(height: scale[.slipEdge])                }                Button { onAct(act) } label: {                    HStack(spacing: scale[.slipPad]) {                        if let object = act.object {                            CardObjectView(object: .enamel(object), side: scale[.slipActGlyph])                                .frame(width: scale[.slipActGlyph], height: scale[.slipActGlyph])                        }                        VStack(alignment: .leading, spacing: 2) {                            HStack(spacing: scale[.slipPad]) {                                Text(act.word)                                    .paperBody(nil, ink: act.destroys ? .red : act.blank ? .pencil : .ink)                                    .fixedSize(horizontal: false, vertical: true)                                Spacer(minLength: 0)                                if let detail = act.detail {                                    Text(detail).paperMeta(scale.metaSize)                                }                            }                            if let why = act.why {                                Text(why).paperMeta(scale.metaSize)                                    .fixedSize(horizontal: false, vertical: true)                            }                        }                    }                    .padding(.vertical, act.why == nil ? 0 : scale[.slipPad] / 2)                    .padding(.horizontal, scale[.slipPad])                    .frame(maxWidth: .infinity, minHeight: scale[.slipActRow], alignment: .leading)                    .contentShape(Rectangle())                }                .buttonStyle(.plain)                // A row that says why it is closed takes no tap.                .allowsHitTesting(act.why == nil)                .accessibilityLabel(act.word)                .accessibilityValue([act.detail, act.why].compactMap(\.self).joined(separator: ", "))                .accessibilityRemoveTraits(act.why == nil ? [] : .isButton)                .accessibilityIdentifier("slip-act-\(act.id)")            }        }        .background(shape.fill(theme.sheet(.cream)))        .overlay(shape.stroke(theme.colors.hairline.color, lineWidth: scale[.slipEdge]))        .clipShape(shape)        .shadow(color: theme.colors.shadow.color.opacity(Double(LiftedActsKnobs.shadowOpacity)), radius: scale[.slipShadow] / 2)    }}/// The lifted card as one fact's editor: back to the rows with the fact's/// word at its head, the editor on the draft, and Done — with Clear, when/// the fact may be empty — at its foot.struct LiftedEditorCard: View {    @Environment(\.theme) private var theme    let word: String    let editor: LiftedEditor    let lift: ActLift    var body: some View {        let scale = theme.scale        let shape = RoundedRectangle(cornerRadius: scale[.slipRadius], style: .continuous)        let value = lift.draft ?? editor.value        VStack(alignment: .leading, spacing: 0) {            Button { lift.back() } label: {                HStack(spacing: scale[.slipPad] / 2) {                    SlipChevron().scaleEffect(x: -1, y: 1)                    Text(word).paperBody(nil, ink: .ink)                    Spacer(minLength: 0)                }                .padding(.horizontal, scale[.slipPad])                .frame(maxWidth: .infinity, minHeight: scale[.slipActRow], alignment: .leading)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityLabel(word)            .accessibilityHint(ShellLines.line("chrome", "lifted.back"))            .accessibilityIdentifier("slip-edit-back")            Rectangle().fill(theme.colors.hairline.color).frame(height: scale[.slipEdge])            editor.view(value) { lift.draft = $0 }                .padding(scale[.slipPad])            Rectangle().fill(theme.colors.hairline.color).frame(height: scale[.slipEdge])            HStack(spacing: scale[.slipPad]) {                if editor.clears {                    PaperTypedButton("Clear") { lift.write(editor, .null) }                        .accessibilityIdentifier("slip-edit-clear")                }                Spacer(minLength: 0)                PaperTypedButton("Done") { lift.write(editor, value) }                    .accessibilityIdentifier("slip-edit-done")            }            .padding(.horizontal, scale[.slipPad])            .frame(maxWidth: .infinity, minHeight: scale[.slipActRow])        }        .background(shape.fill(theme.sheet(.cream)))        .overlay(shape.stroke(theme.colors.hairline.color, lineWidth: scale[.slipEdge]))        .clipShape(shape)        .shadow(color: theme.colors.shadow.color.opacity(Double(LiftedActsKnobs.shadowOpacity)), radius: scale[.slipShadow] / 2)    }}/// The lift's spring, Reduce Motion's crossfade, how far the card unfolds/// from, the shadow's strength and where the lower third begins: Swift's/// own, beside their reader.enum LiftedActsKnobs {    static let liftResponse: CGFloat = 0.28    static let liftDamping: CGFloat = 0.78    static let crossfade: CGFloat = 0.18    static let unfoldFrom: CGFloat = 0.94    static let shadowOpacity: CGFloat = 0.18    static let lowerThird: CGFloat = 2.0 / 3.0}