Cotton code
869 lines · 42.2 KB · SwiftRaw
// The slip: one record on the one slip paper (`ObjectSlip`), its slots filled// from its table's slip layout (recordface row 1, 21 Oct 2026: one slip face// on every list). What the layout names decides what goes in which slot:////   * a TOGGLE drawn as a SWITCH (`toggle_style: "switch"`): the title as the//     headline — a time as its figures with the meridiem small beside them —//     the subtitle in the serif under it, the trailing value in pencil, and//     the paper switch at the side. Off prints the lettering faint, never//     struck. An empty slot reads its column's placeholder in pencil;//   * a TOGGLE drawn as a check: the check leading, the title typed as its//     prose, the trailing value and the project along the foot — on an//     `upcoming` list how late it is, the hour or when a snooze brings it//     back, in place of the day its heading names — then the badge, the//     byline by hand and the DONE / DROPPED stamp at the foot's end;//   * a PLAYER: the title in the serif, its line in pencil, and below them//     the play disc and the waveform (`MeetingWaveform`, seeded by the id).//     The disc is a picture of "a recording", not a control: the slip opens//     the record's page, which plays it. Only bytes on this phone draw it;//   * TWO PICTURES — a `photo` and a `trailing_picture` that is a photo too://     the pair below, each under its column's name with its own words,//     each a tap that opens the record its column `opens`;//   * a PHOTO column: the print leading, or nothing — never initials — and//     the note by hand at the title's end: the byline when it is red, else//     the trailing value;//   * an OBJECT column: the catalogue object leading;//   * a TRAILING PICTURE: the picture at the side (a place's map, a photo);//   * anything else: the title in the serif, the subtitle as prose, the//     trailing value along the foot. A STUB is the day's stub leading; a//     numbered table (`ordinal`) writes the record's place there.//// Every slip: the unread dot in its top corner while its `opened` column is// empty; the badge at its foot's end (or its corner when it has no foot);// the figure typed and the byline by hand there; its `links` by hand under// the paper; and, while it asks its owner something, its verbs under the// paper — the reply in red hand first, then the typed answers. A `red_when`// value writes the foot in red. Only a notice (`edge: receipt`) keeps its// perforated edge; every other slip's edge is the theme's.import CottonValuesimport SwiftUIpublic struct SlipFace: View {    @Environment(\.theme) private var theme    private let definition: TableDefinition    private let record: TableRecord    private let onToggle: (() -> Void)?    private let compact: Bool    private let ordinal: Int?    private let upcoming: Bool    /// What the heading this slip stands under already said of its day.    private let dayWords: DayWords    private let onAnswer: ((String) -> Void)?    private let onReply: (() -> Void)?    private let answering: Bool    /// What the core said of the record (`RecordSaid`): the row a list    /// answered, else what the record carries from its read.    private let said: RecordSaid    @Environment(\.linkTitles) private var links    @Environment(\.cottonCore) private var core    /// Whether the player's recording is on this phone, once the ledger has    /// said: a slip offers no play disc for bytes that are not here.    @State private var recordingHere: Bool?    @Environment(\.recordOpener) private var opener    /// - Parameters:    ///   - onToggle: what a tap on the check does; nil draws the check    ///     without a control (a tile, the preview).    ///   - compact: one of several across a list's grid.    ///   - ordinal: the record's place in its list, counted from 1, for a    ///     table whose slip numbers its records.    ///   - upcoming: drawn under a day heading of an `upcoming` list, which    ///     names the day: the foot says how late, the hour, or when a snooze    ///     brings the record back (`upcomingFoot`), never the day again.    ///   - onAnswer: what a tap on one of the slip's answers does, handed the    ///     value it writes; nil draws no answers (a tile, the preview).    ///   - onReply: what a tap on the slip's reply does (opens its sheet);    ///     nil draws no reply.    ///   - answering: an answer is on its way: the verbs wait, faint.    public init(        definition: TableDefinition, record: TableRecord, onToggle: (() -> Void)? = nil,        compact: Bool = false, ordinal: Int? = nil, upcoming: Bool = false,        onAnswer: ((String) -> Void)? = nil, onReply: (() -> Void)? = nil, answering: Bool = false,        dayWords: DayWords = .full    ) {        self.init(definition: definition, record: record, onToggle: onToggle, compact: compact, ordinal: ordinal,                  upcoming: upcoming, onAnswer: onAnswer, onReply: onReply, answering: answering, dayWords: dayWords, row: nil)    }    /// A list's slip, its words as the core answered them (`said`).    init(        definition: TableDefinition, record: TableRecord, onToggle: (() -> Void)? = nil,        compact: Bool = false, ordinal: Int? = nil, upcoming: Bool = false,        onAnswer: ((String) -> Void)? = nil, onReply: (() -> Void)? = nil, answering: Bool = false,        dayWords: DayWords = .full, row: ListAnswer.Row?    ) {        self.said = row?.said ?? record.said ?? .nothing        // A slip typed by a choice column draws this record's variant.        self.definition = definition.slip(for: record)        self.record = record        self.onToggle = onToggle        self.compact = compact        self.ordinal = definition.slip.ordinal ? ordinal : nil        self.upcoming = upcoming        self.dayWords = dayWords        self.onAnswer = onAnswer        self.onReply = onReply        self.answering = answering    }    /// Each part built in its own frame and handed on boxed (`boxed`): one    /// evaluation of this body touched 737 KB of main-thread stack in a debug    /// build — the phone has 1 MB for all of SwiftUI (builds 227/230/231).    /// Guard: `FaceStackTests`.    /// A slip that opens a record: on a fan tile's page, the record grows out of it (`TilePage`).    public var body: some View { face.zoomSource() }    @ViewBuilder private var face: some View {        // Only a slip that asks its owner something stands its verbs under        // it, and only one naming its links their hand links.        if definition.slip.answers == nil, definition.slip.reply == nil, definition.slip.links == nil,            definition.slip.lines == nil        {            return boxed { dotted }        }        return boxed {            VStack(alignment: .leading, spacing: SlipFaceKnobs.slipRowContentSpacing) {                boxed { dotted }                boxed { rowLines }                boxed { verbs }                boxed { linkRow }            }        }    }    /// The rows of another table the slip names (an order's items), one    /// pencil line each, as the core said them.    @ViewBuilder private var rowLines: some View {        let lines = definition.slipRowLines(of: record)        if !lines.isEmpty {            VStack(alignment: .leading, spacing: SlipFaceKnobs.slipRowLineGap) {                ForEach(Array(lines.enumerated()), id: \.offset) { _, line in                    Text(line).paperMeta(theme.scale.metaSize)                }            }            .padding(.horizontal, SlipFaceKnobs.slipButtonHorizontalPadding)            .accessibilityElement(children: .combine)            .accessibilityIdentifier("slip-\(definition.id)-lines-\(record.id)")        }    }    /// The records this one is linked to, by hand under the slip ("Todo    /// \u{203A}"), each opening its record through `recordOpener`; nothing    /// when there is no opener (a tile, the preview) or no link.    @ViewBuilder private var linkRow: some View {        let linked = definition.slipLinks(of: record)        if let opener, !linked.isEmpty {            HStack(spacing: SlipFaceKnobs.slipActionGap) {                ForEach(linked, id: \.key) { link in                    Button { opener(link.table, TableRecord(id: link.id, values: [:])) } label: {                        Text(link.handLink)                            .paperHand(theme.scale.handSize + 1, ink: .pencil)                            .frame(minHeight: SlipFaceKnobs.slipLinkMinHeight)                            .contentShape(Rectangle())                    }                    .buttonStyle(OpacityButtonStyle())                    .accessibilityLabel(ShellLines.line("faces", "slip.open_linked", ["kind": BadgeKind.label(forKind: link.table).lowercased()]))                    .accessibilityIdentifier("slip-\(definition.id)-link-\(link.table)-\(link.id)-\(record.id)")                }                Spacer(minLength: 0)            }            .padding(.horizontal, SlipFaceKnobs.slipButtonHorizontalPadding)        }    }    /// The paper, wearing the red ink dot while its record is unread.    private var dotted: some View {        paper            .overlay(alignment: .topTrailing) {                if said.slip.unread {                    UnreadDot(spoken: true)                        .padding(SlipFaceKnobs.slipUnreadDotPadding)                        .accessibilityIdentifier("\(definition.id)-\(record.id)-unread")                }            }    }    /// The reply and the typed answers, while the question is open: the    /// reply first, then one verb each in its column's order, side by side or    /// stacked when the slip is narrow.    @ViewBuilder private var verbs: some View {        let reply = onReply == nil ? nil : definition.replyOffered(record)        let answers = onAnswer == nil ? [] : definition.answerVerbs(record)        if reply != nil || !answers.isEmpty {            ViewThatFits(in: .horizontal) {                HStack(spacing: SlipFaceKnobs.slipVerbGap) { verbButtons(reply, answers) }                VStack(alignment: .leading, spacing: 0) { verbButtons(reply, answers) }            }            .disabled(answering)            .opacity(answering ? 0.5 : 1)            .padding(.horizontal, SlipFaceKnobs.slipButtonHorizontalPadding)            .accessibilityIdentifier("slip-\(definition.id)-answers-\(record.id)")        }    }    @ViewBuilder private func verbButtons(_ reply: SlipReply?, _ answers: [(value: String, words: String)]) -> some View {        if let reply, let onReply {            Button(action: onReply) {                Text(reply.verb)                    .paperHand(theme.scale.handSize + 3, ink: .red)                    .underline(color: theme.print(.red).opacity(SlipFaceKnobs.faceSlipUnderlineOpacity))                    .frame(minWidth: SlipFaceKnobs.slipButtonMinTarget, minHeight: SlipFaceKnobs.slipButtonMinTarget)                    .contentShape(Rectangle())            }            .buttonStyle(OpacityButtonStyle())            .accessibilityLabel("\(reply.verb) \u{2014} \(title)")            .accessibilityIdentifier("slip-\(definition.id)-reply-\(record.id)")        }        if let onAnswer {            ForEach(answers, id: \.value) { verb in                // The agreeing answer (`primary`) is a filled capsule; the rest typed words.                Group {                    if verb.value == definition.slip.answers?.primary {                        VerbCapsule(title: verb.words) { onAnswer(verb.value) }                    } else {                        PaperTypedButton(verb.words, size: SlipFaceKnobs.slipAnswerSize) { onAnswer(verb.value) }                    }                }                .accessibilityLabel("\(verb.words) \u{2014} \(title)")                .accessibilityIdentifier("slip-\(definition.id)-answer-\(verb.value)-\(record.id)")            }        }    }    /// Each paper in its own frame (`boxed`): only the one drawn is entered.    private var paper: AnyView {        switch said.toggled.map({ on in definition.drawsSwitch ? Form.switched(on) : Form.checked(on) }) ?? Self.form(definition, record) {        case .switched(let on): return boxed { switched(on) }        case .checked(let on): return boxed { checked(on) }        case .played(let recording): return boxed { cornered { played(has: recording) } }        case .pair: return boxed { cornered { pair } }        case .strip(let photo): return boxed { cornered { strip(photo: photo) } }        case .object(let key): return boxed { cornered { objectStrip(key) } }        case .pictured: return boxed { cornered { pictured } }        case .memory: return boxed { memory }        }    }    /// A slip with no foot of its own wears its badge in the bottom corner.    private func cornered<Paper: View>(@ViewBuilder _ paper: () -> Paper) -> some View {        paper().overlay(alignment: .bottomTrailing) {            badgeMark.padding(SlipFaceKnobs.slipUnreadDotPadding)        }    }    /// Whether the slip is the receipt: its `edge` says so.    static func isReceipt(_ definition: TableDefinition) -> Bool { definition.slip.edge == .receipt }    /// Which paper a slip is, in the order the layout's slots win: a toggle,    /// a player, a photo, a trailing picture, else the memory slip.    enum Form: Equatable {        /// A toggle drawn as a switch, and whether it is on.        case switched(Bool)        case checked(Bool)        /// Whether the player column holds a recording.        case played(Bool)        /// Two pictures side by side (`photo` and a photo `trailing_picture`).        case pair        case strip(String?)        /// A catalogue object at the left, named by the slip's `object` column.        case object(String?)        case pictured        case memory    }    static func form(_ definition: TableDefinition, _ record: TableRecord) -> Form {        if let player = definition.slip.player { return .played(!RecordValue.isBlank(record[player])) }        if let photo = definition.slip.photo, definition.column(photo)?.type == .photo,            definition.column(definition.slip.trailingPicture)?.type == .photo        {            return .pair        }        if definition.slip.photoName != nil { return .strip(record[definition.slip.photo].text) }        if let photo = definition.slip.photo { return .strip(record[photo].text) }        if let object = definition.slip.object { return .object(record[object].text) }        if definition.slip.trailingPicture != nil { return .pictured }        return .memory    }    /// The record's title, else its day's weekday (a journal page has none).    private var title: String {        said.slip.title ?? ""    }    /// The caption when the layout has one; else, under a weekday title, the    /// date written out rather than the weekday again; else the trailing    /// column. Under a day or month heading a date says only what the heading    /// did not (`dayWords`, R7 b, c).    private var trailing: String? {        said.slip.day_foot ?? said.slip.caption ?? said.slip.trailing    }    private func ink(_ key: String?, fallback: PaperInk = .ink) -> PaperInk {        record.ink(key, fallback: fallback)    }    private var titleInk: PaperInk {        let key = RecordValue.isBlank(record[definition.slip.title])            ? definition.slip.titleFallback ?? definition.title : definition.slip.title        return ink(key)    }    private var trailingInk: PaperInk {        let keys = definition.slip.caption.map { $0.columns + [$0.status].compactMap { $0 } + $0.dates }            ?? [definition.slip.trailing].compactMap { $0 }        return keys.contains { ink($0) == .red } || overdue ? .red : .pencil    }    /// Whether the caption's date has gone by on a record still open: a    /// column that names its past (`past_name`, a goal's "Was") is a day    /// that was aimed at, and missing it reads in the attention colour    /// (walker 604bcce6), never the quiet grey of a day ahead.    private var overdue: Bool {        said.slip.caption_late == true    }    /// The foot's red where a `red_when` names its value; nil otherwise, so    /// a foot's own red (a todo late, a record `isRed`) still reads.    private var trailingRed: PaperInk? { trailingInk == .red ? .red : nil }    private var stamp: StampKind? {        said.stamp.flatMap(StampKind.of(status:))    }    /// Whether the slip's check is on, as answered; nil with no check.    private var toggled: Bool? { said.toggled }    /// The slip's paper: the stock its state names, else its table's dye    /// (`slip.dye` — a pink slip anywhere is a todo), else the run's.    private var dye: PaperDye {        if let stock = said.slip.stock.flatMap(SlipStock.init(rawValue:)) { return FaceTint.dye(for: record.id, stock: stock) }        return definition.slip.dye.flatMap(PaperDye.init(rawValue:)) ?? FaceTint.dye(for: record.id)    }    private var subtitleInk: PaperInk { ink(definition.slip.subtitle, fallback: .pencil) }    private var figure: String? {        said.slip.figure?.text    }    /// The first subtitle column holding words, else its `subtitle_fallback`'s — unless the    /// title already says it (a title fallen back to the site).    private var subtitle: String? {        said.slip.subtitle == title ? nil : said.slip.subtitle    }    private var byline: String? { said.slip.byline?.words }    /// The project's name, when the table files records under one.    private var project: String? {        said.slip.project_words    }    // ── The todo slip ───────────────────────────────────────────────────────    /// On an upcoming list, an open record's foot is `upcomingFoot` (or no    /// day at all); a done one keeps its own date.    private var upcomingFoot: (day: String?, late: Bool) {        guard upcoming, definition.upcoming != nil, toggled != true else { return (trailing, false) }        return (said.slip.foot?.text ?? trailing, said.slip.foot_late?.bool ?? false)    }    private func checked(_ on: Bool) -> some View {        let foot = upcomingFoot        return ObjectSlip(            seed: record.id,            dye: dye,            proseInk: titleInk,            metaInk: trailingRed,            prose: title,            clamp: definition.slip.titleLines(otherwise: SlipFaceKnobs.paperSlipProseLines),            meta: TodoSlipFoot.line(day: foot.day, meta: nil, project: project),            metaLate: foot.late,            struck: definition.strikes(record),            leading: {                if let onToggle {                    TodoPaperCheck(done: on, side: FieldLineKnobs.slipCheckSide, label: title) { _ in onToggle() }                } else {                    TodoCheckSquare(done: on, side: FieldLineKnobs.slipCheckSide)                }            },            trailing: { stamped }        )        .contentShape(Rectangle())    }    /// The badge, the byline by hand ("high priority") and the stamp, in    /// that order, at the foot's end.    @ViewBuilder private var stamped: some View {        HStack(alignment: .center, spacing: SlipFaceKnobs.slipStampGap) {            badgeMark            if let byline {                Text(byline)                    .paperHand(theme.scale.handSize - 1, ink: .red)                    .lineLimit(1)                    .accessibilityIdentifier("slip-\(definition.id)-byline-\(record.id)")            }            if let stamp {                Stamp(stamp, width: SlipFaceKnobs.slipStampWidth)                    .rotationEffect(.degrees(SlipFaceKnobs.faceSlipStampRotationDegrees))            }        }    }    /// The slip's badge (`slip.badge`) while its column holds a value: the    /// one place any slip draws it, at its foot's end — a todo's repeat, an    /// email's star — or in the corner of a slip with no foot.    private var showsBadge: Bool { said.slip.badge != nil }    @ViewBuilder private var badgeMark: some View {        if let badge = definition.slip.badge, showsBadge {            Image(systemName: badge.symbol)                .font(theme.type.interface(SlipFaceKnobs.slipBadgeSize, weight: .medium))                .foregroundStyle(theme.print(.ink))                .blendMode(theme.printBlend)                .accessibilityLabel(badge.spoken)                .accessibilityIdentifier("slip-\(definition.id)-badge-\(record.id)")        }    }    // ── The switch paper ────────────────────────────────────────────────────    /// The slip and its switch at the side. The words are one element for    /// VoiceOver, read as the slip says them ("6:30 am, Wake, Monday,    /// Friday"); the switch is its own control.    private func switched(_ on: Bool) -> AnyView {        let spoken = definition.spoken(record, links: links.byID)        let digits = compact ? SlipFaceKnobs.slipSwitchCardDigitsSize : SlipFaceKnobs.slipSwitchRowDigitsSize        let meridiem = compact ? SlipFaceKnobs.slipSwitchCardMeridiemSize : SlipFaceKnobs.slipSwitchRowMeridiemSize        let words = VStack(alignment: .leading, spacing: SlipFaceKnobs.slipSwitchDetailGap) {            boxed { switchHeadline(digits: digits, meridiem: meridiem) }            boxed { switchName(compact ? SlipFaceKnobs.slipSwitchTitleSize : SlipFaceKnobs.slipSwitchRowTitleSize) }            boxed { switchFoot }        }        .accessibilityElement(children: .ignore)        .accessibilityLabel(spoken)        return boxed {            ObjectSlip(                seed: record.id, dye: dye,                headline: AnyView(words),                side: AnyView(paperSwitch(on, spoken).scaleEffect(compact ? SlipFaceKnobs.faceSlipSwitchScale : 1)),                leading: { EmptyView() }, trailing: { EmptyView() })        }    }    /// The lettering's strength: full when on, faint when off.    private var lettering: Double {        toggled == false ? TableDefinition.offStrength : 1    }    /// The title, large: a time as its figures with the meridiem small on the    /// same baseline ("6:30" and "am"), anything else in the serif.    @ViewBuilder private func switchHeadline(digits: CGFloat, meridiem: CGFloat) -> some View {        let column = definition.column(definition.slip.title)        if column?.type == .time, let clock = FaceText.clockParts(record.columnWords(definition.slip.title)?.said) {            HStack(alignment: .firstTextBaseline, spacing: SlipFaceKnobs.slipSwitchBaselineGap) {                // The figures shrink to the card's width, never cut: an                // ellipsis took "11:45" to "11:..." (290 walk, Alarms).                Text(clock.digits).paperBody(digits).lineLimit(1).minimumScaleFactor(SlipFaceKnobs.slipSwitchDigitsMinScale)                if let small = clock.meridiem { Text(small).paperBody(meridiem) }            }            .opacity(lettering)        } else if let words = definition.slipWords(definition.slip.title, of: record, links: links.byID) {            Text(words.text)                .paperTitle(digits * SlipFaceKnobs.slipSwitchWordsScale, ink: words.placeholder ? .pencil : .ink)                .lineLimit(nil)                .fixedSize(horizontal: false, vertical: true)                .opacity(lettering)        }    }    /// The subtitle in the serif, or its placeholder in pencil.    @ViewBuilder private func switchName(_ size: CGFloat) -> some View {        if let words = definition.slipWords(definition.slip.subtitle, of: record, links: links.byID) {            Text(words.text)                .paperTitle(size, ink: words.placeholder ? .pencil : .ink)                .lineLimit(nil)                .fixedSize(horizontal: false, vertical: true)                .opacity(lettering)        }    }    /// The trailing value in pencil ("Mon\u{2013}Fri"), or its placeholder.    @ViewBuilder private var switchFoot: some View {        HStack(alignment: .firstTextBaseline, spacing: SlipFaceKnobs.slipStampGap) {            if let words = definition.slipWords(definition.slip.trailing, of: record, links: links.byID) {                Text(words.text)                    .paperBody(theme.scale.bodySize - 1.5, ink: .pencil)                    .lineLimit(nil)                    .fixedSize(horizontal: false, vertical: true)                    .opacity(lettering)            }            badgeMark        }    }    /// The paper switch: a tap writes the toggle through `onToggle`; without    /// one (a tile, the preview) it is drawn and does nothing. The slip's    /// words are what VoiceOver reads for it.    private func paperSwitch(_ on: Bool, _ spoken: String) -> some View {        Toggle(            spoken,            isOn: Binding(get: { on }, set: { _ in onToggle?() })        )        .labelsHidden()        .toggleStyle(.paper)        .disabled(onToggle == nil)        .accessibilityIdentifier("slip-\(definition.id)-switch-\(record.id)")    }    // ── The message strip ───────────────────────────────────────────────────    @ViewBuilder private func strip(photo: String?) -> some View {        if let nameColumn = definition.slip.photoName {            printed {                RecordPrint(key: photo, name: record[nameColumn].text ?? "Somebody", detail: nil,                    seed: record[nameColumn].text ?? record.id, caption: nil,                    edge: SlipFaceKnobs.paperStripLeadingSide, size: .thumb, tilts: false)            }        } else if let photo {            printed {                InstantPrint(seed: record.id, size: .thumb) {                    RecordPicture(avatarKey: photo, edge: SlipFaceKnobs.paperStripLeadingSide)                }            }        } else {            printed { EmptyView() }        }    }    /// The slip with a photographed object leading — the same picture Home's    /// tile draws, its label left off since the slip says the name. A key    /// with no object draws the slip alone, never a hole.    @ViewBuilder private func objectStrip(_ key: String?) -> some View {        printed {            if let key, let asset = ToolObjects.asset(for: key) {                ToolObject(name: title, asset: asset, printing: .contentOnly, side: SlipFaceKnobs.paperStripLeadingSide)                    .accessibilityHidden(true)            }        }    }    /// A slip with a picture leading: the title on one line with the note by    /// hand at its end — the byline by hand stands in it when nothing    /// trails ("Very likely"), and a red one ("suggested") is the note even    /// when something does — and the subtitle on one line under it.    private func printed<Print: View>(@ViewBuilder _ print: @escaping () -> Print) -> some View {        let note = definition.bylineIsRed ? (byline ?? trailing) : (trailing ?? byline)        return ObjectSlip(            seed: record.id, dye: dye,            title: title, titleInk: titleInk, proseInk: subtitleInk,            titleLines: 1, prose: subtitle, clamp: 1,            note: note, noteInk: trailingInk,            leading: {                // No print, no gap: nothing stands in for a missing picture.                if Print.self != EmptyView.self {                    print().frame(width: SlipFaceKnobs.paperStripLeadingSide)                }            },            trailing: { EmptyView() })    }    // ── The pair ────────────────────────────────────────────────────────────    private var pair: some View {        ObjectSlip(            seed: record.id, dye: dye, meta: trailing,            below: AnyView(HStack(alignment: .top, spacing: SlipFaceKnobs.slipPairSideGap) {                side(definition.slip.photo)                side(definition.slip.trailingPicture)            }),            leading: { EmptyView() }, trailing: { EmptyView() })    }    /// One side of the pair: its column's name, its picture opening what the    /// column `opens` (or quiet ground when the picture is gone), its words.    private func side(_ key: String?) -> some View {        let column = definition.column(key)        let picture = record[key].text        let target = definition.opening(record, column: key)        return VStack(alignment: .leading, spacing: SlipFaceKnobs.slipPairLabelGap) {            Text(column?.label ?? "")                .paperMeta(theme.scale.metaSize - 0.5)            Button {                if let target { opener?(target.table, TableRecord(id: target.id, values: [:])) }            } label: {                GeometryReader { geo in                    if let picture {                        RecordPicture(avatarKey: picture, edge: geo.size.width)                    } else {                        ZStack {                            Rectangle().fill(theme.colors.groundMuted.color)                            Text(ShellLines.line("faces", "slip.picture_gone"))                                .paperHand(theme.scale.handSize - 1, ink: .pencil)                                .multilineTextAlignment(.center)                                .padding(SlipFaceKnobs.slipPairGonePadding)                        }                    }                }                .aspectRatio(1, contentMode: .fit)                .clipShape(PaperShape(edge: .cut, seed: record.id + "-\(key ?? "")", theme: theme))            }            .buttonStyle(MotionButtonStyle())            .disabled(target == nil || opener == nil || picture == nil)            .accessibilityIdentifier("slip-\(definition.id)-\(record.id)-\(key ?? "")")            if let words = definition.pictureCaption(of: key, in: record, links: links.byID) {                Text(words)                    .paperBody(theme.scale.bodySize - 2, ink: .pencil)                    .lineLimit(SlipFaceKnobs.slipPairWordsMaxLines)            }        }        .frame(maxWidth: .infinity, alignment: .leading)    }    // ── The meeting sheet ───────────────────────────────────────────────────    private func played(has recording: Bool) -> some View {        // Nothing is offered that cannot work: the disc and the waveform        // only for a recording whose bytes are on this phone (a store with        // no ledger to ask draws what the record names).        let player = HStack(spacing: SlipFaceKnobs.slipMeetingPlayerGap) {            playDisc(enabled: true)            waveform        }        .frame(height: SlipFaceKnobs.slipMeetingPlayerHeight)        return ObjectSlip(            seed: record.id, dye: dye,            title: title, titleInk: titleInk,            proseInk: ink(subtitle == nil ? definition.slip.trailing : definition.slip.subtitle, fallback: .pencil),            titleLines: definition.slip.titleLines(otherwise: SlipFaceKnobs.slipMeetingTitleLines),            prose: Self.playerLine(subtitle: subtitle, trailing: trailing), clamp: 2,            below: recording && (core == nil || recordingHere == true) ? AnyView(player) : nil,            leading: { EmptyView() }, trailing: { EmptyView() })        .task(id: playerKey) { await askRecordingHere() }        .onMediaArrival { await askRecordingHere() }    }    /// The object key of the recording the slip's player names.    private var playerKey: String? {        definition.slip.player.flatMap { MediaStage.key(record[$0]) }    }    /// Asks the ledger whether the recording's bytes are here — never a fetch.    private func askRecordingHere() async {        guard let core, let key = playerKey else { return }        recordingHere = await PhotosMediaSource(core: core).answer(for: key, tier: .original) != nil    }    static func playerLine(subtitle: String?, trailing: String?) -> String? {        let parts = [subtitle, trailing].compactMap { $0 }.filter { !$0.isEmpty }        var seen: Set<String> = []        let unique = parts.filter { seen.insert($0).inserted }        return unique.isEmpty ? nil : unique.joined(separator: " · ")    }    /// The sheet's picture of a recording; hidden from VoiceOver, since the    /// whole slip is the control.    private func playDisc(enabled: Bool) -> some View {        ZStack {            Circle().fill(theme.print(.pencil).opacity(SlipFaceKnobs.faceSlipControlFillOpacity))            Image(systemName: "play.fill")                .font(theme.type.interface(SlipFaceKnobs.slipMeetingDiscSymbolSize))                .foregroundStyle(theme.print(.ink))                .offset(x: 1)        }        .frame(width: SlipFaceKnobs.slipMeetingDiscSide, height: SlipFaceKnobs.slipMeetingDiscSide)        .opacity(enabled ? 1 : SlipFaceKnobs.faceSlipControlDisabledOpacity)        .accessibilityHidden(true)    }    private var waveform: some View {        GeometryReader { geo in            Waveform(                samples: MeetingWaveform.bars(                    MeetingWaveform.samples(id: record.id),                    count: MeetingWaveform.barCount(width: geo.size.width, pitch: SlipFaceKnobs.slipMeetingWavePitch)                ),                barFraction: SlipFaceKnobs.slipMeetingWaveBarFraction,                theme: theme            )            .fill(theme.print(.pencil))        }        .accessibilityHidden(true)    }    // ── The place row ───────────────────────────────────────────────────────    private var pictured: some View {        ObjectSlip(            seed: record.id, dye: dye,            title: title, titleInk: titleInk,            proseInk: ink(subtitle == nil ? definition.slip.trailing : definition.slip.subtitle, fallback: .pencil),            titleLines: definition.slip.titleLines(otherwise: 1),            prose: subtitle ?? trailing, clamp: 1,            side: TrailingPicture.has(definition, record) ? AnyView(                TrailingPicture(definition: definition, record: record)                    .clipShape(PaperShape(edge: .cut, seed: record.id + "-picture", theme: theme))                    .frame(width: SlipFaceKnobs.slipPlacePictureWidth, height: SlipFaceKnobs.slipPlacePictureHeight)            ) : nil,            leading: { EmptyView() }, trailing: { EmptyView() })    }    // ── The memory slip ─────────────────────────────────────────────────────    /// With a stamp only when it wears one: a slip whose foot is empty draws    /// no foot band (`ObjectSlip.foot`).    @ViewBuilder private var memory: some View {        if let stamp {            memory(mark: { figured { Stamp(stamp, width: SlipFaceKnobs.slipStampWidth).rotationEffect(.degrees(SlipFaceKnobs.faceSlipStampRotationDegrees)) } })                .accessibilityValue(stamp.spoken)        } else if figure != nil || byline != nil || showsBadge {            memory(mark: { figured { EmptyView() } })        } else {            memory(mark: { EmptyView() })        }    }    /// The byline by hand, then the figure, typed, before whatever else ends    /// the foot.    private func figured<Mark: View>(@ViewBuilder _ mark: () -> Mark) -> some View {        HStack(alignment: .firstTextBaseline, spacing: SlipFaceKnobs.slipFigureGap) {            if let byline {                Text(byline)                    .paperHand(theme.scale.handSize - 1, ink: definition.bylineIsRed ? .red : .pencil)                    .lineLimit(1)                    .accessibilityIdentifier("slip-\(definition.id)-byline-\(record.id)")            }            if let figure {                Text(figure)                    .font(theme.type.body(theme.scale.bodySize - 0.5))                    .foregroundStyle(ink(definition.slip.figure) == .red ? theme.print(.red) : theme.colors.ink.color)                    .fixedSize()            }            badgeMark            mark()        }    }    private func memory<Mark: View>(@ViewBuilder mark: @escaping () -> Mark) -> some View {        let stub = definition.slip.stub == nil ? nil : said.slip.stub.map { stub in            (day: stub.day?.text ?? stub.day?.number.map { String(Int($0)) } ?? "", month: stub.month?.text ?? "")        }        return ObjectSlip(            seed: record.id,            dye: dye,            // Only a notice keeps its perforated edge; the rest are the theme's.            edge: Self.isReceipt(definition) ? .receipt : nil,            title: title.isEmpty ? nil : title,            titleInk: titleInk,            proseInk: ink(definition.slip.subtitle),            metaInk: trailingRed,            // A receipt is read whole: its server sentences are not folded.            titleLines: Self.isReceipt(definition) ? Int.max : definition.slip.titleLines(otherwise: compact ? SlipFaceKnobs.slipMemoryCompactTitleLines : SlipFaceKnobs.slipMemoryTitleLines),            prose: subtitle,            clamp: Self.isReceipt(definition) ? Int.max : (compact ? SlipFaceKnobs.slipMemoryCompactProseLines : SlipFaceKnobs.paperSlipProseLines),            meta: TodoSlipFoot.line(day: trailing, meta: nil, project: project),            metaLate: definition.isRed(record),            leading: {                if definition.slip.stub != nil {                    DayStub(stub: stub, seed: record.id)                } else if let ordinal {                    Text("\(ordinal)")                        .paperHand(theme.scale.handSize + 6, ink: .pencil)                        .frame(minWidth: SlipFaceKnobs.slipOrdinalMinWidth, alignment: .leading)                        .accessibilityIdentifier("\(definition.id)-\(record.id)-ordinal")                }            },            trailing: mark        )    }}/// A receipt's stub: the day's number large over its month small, both by/// hand, on a tab a dashed pencil tear divides from the slip. An empty stub/// stays blank paper rather than a made-up day.struct DayStub: View {    @Environment(\.theme) private var theme    let stub: (day: String, month: String)?    let seed: String    var body: some View {        HStack(spacing: SlipFaceKnobs.slipStubGap) {            VStack(spacing: SlipFaceKnobs.slipStubLineGap) {                if let stub {                    Text(stub.day).paperHand(theme.scale.handSize + 6)                    Text(stub.month).paperHand(theme.scale.handSize - 2)                }            }            .frame(width: SlipFaceKnobs.slipStubWidth)            PencilDash(seed: seed, startRange: SlipFaceKnobs.slipStubDashStartRange)                .stroke(theme.print(.pencil), style: StrokeStyle(lineWidth: 1, dash: [SlipFaceKnobs.slipStubDashLength, SlipFaceKnobs.slipStubDashGap]))                .frame(width: 1)        }        .fixedSize(horizontal: true, vertical: false)        .accessibilityElement(children: .combine)    }}/// A vertical pencil line the dash pattern breaks into a tear; the seed/// nudges where the dashes start so two stubs never match exactly.struct PencilDash: Shape {    let seed: String    /// How far down the dashes may start, read from the theme by the stub.    let startRange: CGFloat    func path(in rect: CGRect) -> Path {        let start = CGFloat(PaperNoise(seed: seed, salt: 0x7374_7562, count: 4).value(at: 0)) * startRange        var path = Path()        path.move(to: CGPoint(x: rect.midX, y: rect.minY + start))        path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))        return path    }}/// The sizes, counts and timings SlipFace draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum SlipFaceKnobs {    /// How far a switch paper's time may shrink to stand whole on its card.    static let slipSwitchDigitsMinScale: CGFloat = 0.5    static let faceSlipControlDisabledOpacity: CGFloat = 0.4    static let faceSlipControlFillOpacity: CGFloat = 0.16    static let faceSlipStampRotationDegrees: CGFloat = -9    static let faceSlipSwitchScale: CGFloat = 0.72    static let faceSlipUnderlineOpacity: CGFloat = 0.6    static let paperSlipProseLines = 3    static let paperStripLeadingSide: CGFloat = 44    static let slipActionGap: CGFloat = 14    static let slipAnswerSize: CGFloat = 15    static let slipBadgeSize: CGFloat = 11    static let slipButtonHorizontalPadding: CGFloat = 6    static let slipButtonMinTarget: CGFloat = 44    static let slipFigureGap: CGFloat = 8    static let slipLinkMinHeight: CGFloat = 32    static let slipMeetingDiscSide: CGFloat = 32    static let slipMeetingDiscSymbolSize: CGFloat = 12    static let slipMeetingPlayerGap: CGFloat = 12    static let slipMeetingPlayerHeight: CGFloat = 34    static let slipMeetingTitleLines = 2    static let slipMeetingWaveBarFraction: CGFloat = 0.45    static let slipMeetingWavePitch: CGFloat = 3    static let slipMemoryCompactProseLines = 5    static let slipMemoryCompactTitleLines = 3    static let slipMemoryTitleLines = 2    static let slipOrdinalMinWidth: CGFloat = 22    static let slipPairGonePadding: CGFloat = 6    static let slipPairLabelGap: CGFloat = 4    /// Between the lines a slip says from another table (an order's items).    static let slipRowLineGap: CGFloat = 2    static let slipPairSideGap: CGFloat = 12    static let slipPairWordsMaxLines = 2    static let slipPlacePictureHeight: CGFloat = 50    static let slipPlacePictureWidth: CGFloat = 72    static let slipRowContentSpacing: CGFloat = 6    static let slipStampGap: CGFloat = 8    static let slipStampWidth: CGFloat = 88    static let slipStubDashGap: CGFloat = 3    static let slipStubDashLength: CGFloat = 3    static let slipStubDashStartRange: CGFloat = 3    static let slipStubGap: CGFloat = 10    static let slipStubLineGap: CGFloat = -2    static let slipStubWidth: CGFloat = 34    static let slipSwitchBaselineGap: CGFloat = 5    static let slipSwitchCardDigitsSize: CGFloat = 38    static let slipSwitchCardMeridiemSize: CGFloat = 15    static let slipSwitchDetailGap: CGFloat = 3    static let slipSwitchRowDigitsSize: CGFloat = 26    static let slipSwitchRowMeridiemSize: CGFloat = 12    static let slipSwitchRowTitleSize: CGFloat = 17    static let slipSwitchTitleSize: CGFloat = 19    static let slipSwitchWordsScale: CGFloat = 0.75    static let slipUnreadDotPadding: CGFloat = 10    static let slipVerbGap: CGFloat = 18}