Cotton code
361 lines · 14.6 KB · SwiftRaw
// The opened card installs the face's editable tap map, in place on its deck// (`OpenedInPlace`). At rest the same tagged fields open the record; edits// and their ink marks live here.import CottonKitimport CottonPaperimport CottonValuesimport SwiftUIenum DeckEditableKnobs {    /// How long a press turns the fan into the card's acts.    static let hold = 0.45    /// How long the ink mark stays before it fades.    static let markStays = 1.6    static let markFades = 0.6    /// The ring's reach round the corner's words.    static let ringPad = CGSize(width: 14, height: 9)    /// Card design draws each picture inside this share of its square.    static let artFill: CGFloat = 0.7    /// The ink mark's drawn side, and its inset from the card's top corner.    static let mark: CGFloat = 18    static let markInset = EdgeInsets(top: 6, leading: 0, bottom: 0, trailing: 6)}/// The card a face stands on, as the deck handed it down.struct DeckCardTarget: Equatable {    var target: DeckEditTarget    var record: TableRecord}private struct DeckCardTargetKey: EnvironmentKey {    static let defaultValue: DeckCardTarget? = nil}extension EnvironmentValues {    var deckCardTarget: DeckCardTarget? {        get { self[DeckCardTargetKey.self] }        set { self[DeckCardTargetKey.self] = newValue }    }}extension View {    /// The opened card: its editing target rides down to the face while    /// `live`; at rest none does, so the tagged fields open the record.    public func deckEditable(definition: TableDefinition, record: TableRecord, live: Bool = true) -> some View {        modifier(DeckEditableCard(definition: definition, record: record, live: live))    }    /// A deck's empty placeholder: with no card to hold, a long press on it    /// opens its table's tool acts on the fan (`tools.acts`), as a card's    /// does; where the tool offers none, its table's "+" doors (`DeckDoors`);    /// where it has neither it is the placeholder it was.    func deckEmptyActs(table: String, doors: [DeckOffer] = []) -> some View {        modifier(DeckEmptyActs(table: table, doors: doors))    }    /// The face's date corner: a tap opens the days, circled while open.    public func deckCorner() -> some View {        modifier(DeckCornerEditing())    }    /// The footer's status word ("waiting", "dropped"): a tap turns the fan    /// into the record's statuses.    public func deckStatusWord() -> some View {        modifier(DeckStatusWord())    }    /// A day the card shows past its corner: a tap opens the days, as the    /// corner's does, with no ring and no room of its own.    public func deckWhen() -> some View {        modifier(DeckWhen())    }    /// The group the card stands in: a tap turns the fan into the table's    /// groups, the record's own marked.    public func deckGroups() -> some View {        modifier(DeckGroupsWord())    }    /// The words a place shows: a tap writes `column` in the shell, in the    /// editor the core answers — a longtext on the whole screen, a text in    /// the short-text input.    public func deckWords(column: String) -> some View {        modifier(DeckWords(column: column))    }    /// The deck's floating line: it stands through a hold and every tier    /// the fan raises for a card (owner, 3 Nov 2026: nothing on screen    /// changes on a long press but the acts fanning), and fades only while    /// words are being written in the shell's input or editor.    public func deckEditingFades() -> some View {        modifier(DeckEditingFades())    }}struct DeckEditableCard: ViewModifier {    let definition: TableDefinition    let record: TableRecord    var live = true    @Environment(\.deckEditor) private var editor    @Environment(\.cottonHaptics) private var haptics    @Environment(\.cottonCore) private var core    private var target: DeckEditTarget {        DeckEditTarget(table: definition.id, record: record.id, date: definition.whenColumn)    }    func body(content: Content) -> some View {        // A group deck's card (`GroupFace`) stands for a person, not a row:        // there is nothing on it to edit.        if let editor, definition.card?.face != .group {            content                .environment(\.deckCardTarget, live ? DeckCardTarget(target: target, record: record) : nil)                // A save's ink mark sits by the card's top corner (image 4a),                // on the card itself: a save can take the date's own place away.                .overlay(alignment: .topTrailing) {                    if let mark = editor.marked, mark.record == record.id {                        InkMark(mark: mark, editor: editor)                            .padding(DeckEditableKnobs.markInset)                            .allowsHitTesting(false)                    }                }                .accessibilityActions {                    if live {                        Button(ShellLines.line("editing", "acts.when")) { editor.openDays(target, record: record, core: nil) }                    }                }        } else {            content.environment(\.deckCardTarget, nil)        }    }}struct DeckEmptyActs: ViewModifier {    let table: String    /// The table's "+" doors (`DeckDoors`): held where the view's deck    /// offers no tool act, the placeholder opens the same choice tier Plus    /// does — Books' empty Reading offers Find a book, Add a file and Bring    /// Goodreads in (the coordinator, 4 Nov 2026).    var doors: [DeckOffer] = []    @Environment(\.deckEditor) private var editor    @Environment(\.cottonHaptics) private var haptics    @Environment(\.cottonCore) private var core    @Environment(\.scenePhase) private var scenePhase    @Environment(\.deckViewName) private var view    /// The tool's acts that stand now on this view's deck, read as the    /// placeholder stands and again as the app comes back (from Google's    /// consent page, or a sign-in). A hold asks once more before it opens:    /// the account acts turn on a sign-in made inside the app (the sheet    /// the Sign in act raises), which changes no scene phase, and the deck    /// stands on through it.    @State private var acts: [CardAction] = []    /// Their tool's fan tile, as the core answered it with them.    @State private var tile: FanTileLook?    func body(content: Content) -> some View {        // One view path: the acts come in after the placeholder stands, and        // a swapped wrapper would rebuild the placeholder under it.        let holds = editor != nil && (!acts.isEmpty || !doors.isEmpty)        content            .background { Color.clear.contentShape(Rectangle()).allowsHitTesting(holds) }            .gesture(LongPressGesture(minimumDuration: DeckEditableKnobs.hold).onEnded { _ in                guard let editor else { return }                haptics.press()                Task {                    let standing = await DeckEditor.toolActsAnswer(of: table, view: view, core: core)                    if !standing.actions.isEmpty { (acts, tile) = (standing.actions, standing.tile) }                    if acts.isEmpty { editor.offer(doors, for: .emptyDeck(of: table)) }                    else { editor.openToolActs(acts, for: .emptyDeck(of: table), tile: tile) }                }            }, including: holds ? .all : .subviews)        .task(id: "\(table)|\(view ?? "")|\(scenePhase == .active)") {            guard editor != nil, scenePhase == .active else { return }            let standing = await DeckEditor.toolActsAnswer(of: table, view: view, core: core)            (acts, tile) = (standing.actions, standing.tile)        }    }}struct DeckCornerEditing: ViewModifier {    @Environment(\.deckEditor) private var editor    @Environment(\.deckCardTarget) private var card    @Environment(\.cottonCore) private var core    @Environment(\.cottonHaptics) private var haptics    /// This date place, apart from the card's other one.    @State private var place = UUID().uuidString    func body(content: Content) -> some View {        if let editor, let card, card.target.date != nil {            content                .padding(.vertical, DeckEditableKnobs.ringPad.height / 2)                .overlay {                    if editor.circles(card.target.record, at: place) {                        CornerRing()                            .padding(.horizontal, -DeckEditableKnobs.ringPad.width)                            .padding(.vertical, -DeckEditableKnobs.ringPad.height / 2)                            // In with a fade, out at once: back from When the                            // card never keeps its red ring (real-data walk 8).                            .transition(.asymmetric(insertion: .opacity, removal: .identity))                            .allowsHitTesting(false)                    }                }                .contentShape(Rectangle().inset(by: -DeckEditableKnobs.ringPad.width))                .onTapGesture {                    haptics.press()                    editor.openDays(card.target, record: card.record, core: core, at: place)                }                .animation(.easeOut(duration: 0.18), value: editor.circles(card.target.record, at: place))                .accessibilityAddTraits(.isButton)                .accessibilityIdentifier("deck-corner-edit")        } else {            content        }    }}struct DeckStatusWord: ViewModifier {    @Environment(\.deckEditor) private var editor    @Environment(\.deckCardTarget) private var card    @Environment(\.cottonHaptics) private var haptics    @Environment(\.cottonCore) private var core    func body(content: Content) -> some View {        // A state no status verb changes (a film's stub, a secret's kind) is        // drawn as it is: the core leaves it out of the card's parts.        if let editor, let card, editor.part("state", on: card.target.record)?.does == "statuses" {            content                .contentShape(Rectangle().inset(by: -8))                .onTapGesture {                    haptics.press()                    editor.openStatuses(card.target, record: card.record, core: core)                }                .accessibilityAddTraits(.isButton)                .accessibilityIdentifier("deck-status-word")        } else {            content        }    }}struct DeckWhen: ViewModifier {    @Environment(\.deckEditor) private var editor    @Environment(\.deckCardTarget) private var card    @Environment(\.cottonCore) private var core    @Environment(\.cottonHaptics) private var haptics    func body(content: Content) -> some View {        if let editor, let card, card.target.date != nil {            content                .contentShape(Rectangle())                .onTapGesture {                    haptics.press()                    editor.openDays(card.target, record: card.record, core: core)                }                .accessibilityAddTraits(.isButton)        } else {            content        }    }}struct DeckGroupsWord: ViewModifier {    @Environment(\.deckEditor) private var editor    @Environment(\.deckCardTarget) private var card    @Environment(\.cottonCore) private var core    @Environment(\.cottonHaptics) private var haptics    func body(content: Content) -> some View {        if let editor, let card, editor.part("group", on: card.target.record)?.does == "groups" {            content                .contentShape(Rectangle())                .onTapGesture {                    haptics.press()                    editor.open(.groups(card.target), core: core)                }                .accessibilityAddTraits(.isButton)        } else {            content        }    }}struct DeckWords: ViewModifier {    let column: String    @Environment(\.deckEditor) private var editor    @Environment(\.deckCardTarget) private var card    @Environment(\.records) private var store    @Environment(\.cottonCore) private var core    @Environment(\.cottonHaptics) private var haptics    func body(content: Content) -> some View {        if let editor, let card {            content                .contentShape(Rectangle())                .onTapGesture {                    haptics.press()                    editor.write(card.target, column: column, store: store, core: core)                }                .accessibilityAddTraits(.isButton)        } else {            content        }    }}struct DeckEditingFades: ViewModifier {    @Environment(\.deckEditor) private var editor    func body(content: Content) -> some View {        let writing = editor?.writing != nil        content            .opacity(writing ? 0 : 1)            .allowsHitTesting(!writing)            .animation(.easeOut(duration: 0.2), value: writing)    }}/// The small ink mark a saved edit leaves (image 4a, step 3): two short/// strokes off the corner, there a moment, then gone.struct InkMark: View {    let mark: DeckInkMark    let editor: DeckEditor    @Environment(\.theme) private var theme    @State private var shown = false    var body: some View {        Group {            if let drawn = CottonMedia.image("edit-ink-mark") {                drawn.resizable().scaledToFit()                    .frame(width: DeckEditableKnobs.mark / DeckEditableKnobs.artFill, height: DeckEditableKnobs.mark / DeckEditableKnobs.artFill)            } else {                Strokes()                    .stroke(theme.print(.red), style: StrokeStyle(lineWidth: 1.4, lineCap: .round))                    .frame(width: 14, height: 12)            }        }        .blendMode(theme.printBlend)        .opacity(shown ? 1 : 0)        .task(id: mark.at) {            withAnimation(.easeOut(duration: 0.15)) { shown = true }            try? await Task.sleep(for: .seconds(DeckEditableKnobs.markStays))            withAnimation(.easeIn(duration: DeckEditableKnobs.markFades)) { shown = false }            try? await Task.sleep(for: .seconds(DeckEditableKnobs.markFades))            editor.unmark(mark)        }        .accessibilityHidden(true)    }    private struct Strokes: Shape {        func path(in rect: CGRect) -> Path {            var path = Path()            path.move(to: CGPoint(x: rect.minX + rect.width * 0.1, y: rect.maxY * 0.55))            path.addQuadCurve(to: CGPoint(x: rect.minX + rect.width * 0.55, y: rect.minY),                              control: CGPoint(x: rect.minX + rect.width * 0.22, y: rect.minY + rect.height * 0.15))            path.move(to: CGPoint(x: rect.minX + rect.width * 0.45, y: rect.maxY))            path.addQuadCurve(to: CGPoint(x: rect.maxX, y: rect.minY + rect.height * 0.35),                              control: CGPoint(x: rect.minX + rect.width * 0.7, y: rect.maxY * 0.62))            return path        }    }}