// THE COMPOSER CARD — one rounded box, the words on top and ONE control row // beneath, drawn the same by every composer in this app. // // The capture dock (`CaptureComposer`) and every chat (`ChatComposerBar`) each // drew a bar of their own: a field with discs standing beside it, and — while a // dictation was live — a listening line stacked above the words and the ✕/stop // pair below them. Three rows for one act. What a person actually reads there // is one object: a box holding the thought, with the verbs sitting along its // bottom edge. So the box is this file, and both hosts fill it. // // ## The four shapes, stated once // // • **Idle / typing.** `+` (where the host has one) at the LEFT end, the mic // and the send arrow at the RIGHT end. **Both are always drawn** — the mic // is no longer replaced by send the moment there are words, because a // thought is very often typed halfway and then spoken, and a field you // cannot speak into after the first word is a field that makes you delete // what you typed. Send is DIMMED, never hidden, while there is nothing to // send. // • **Recording.** The same one row, and nothing in it moves (Spec 7, note // 708fe4fa): ✕ at the left end, the clock and the live meter, and at the // right end the SAME two places the mic and the arrow stand in — the mic's // place is now stop, which lands the words in the box to fix, and the // arrow sends what was heard at once. A host with no send-while-speaking // keeps the one ✓ it had. // • **Which of the two is filled says what a tap would do next.** With the // box empty the mic is the filled disc and the arrow is faint; once there // are words the arrow is. Neither changes place or size. // • **A hold on the mic speaks and sends.** Hold, speak, let go: the words // are sent without a second tap. A tap starts a take that stays up. // • **The words grow with the thought** to ``ComposerGrowth/share`` of the // column the host has, and scroll inside the box past that. The old ceiling // was 160pt — eight lines — and a long dictation ran off the bottom of it. // • **While dictating the box follows the NEWEST words.** A transcript that // stops at the top of the box while the speaking continues is the exact // failure the owner reported: the field filled, the last sentence was // clipped, and there was no way to see what had been heard. // // ## Why the cap is measured and not a number // // "80% of the screen" cannot be a constant: the column a composer has is the // screen MINUS the keyboard, and a card sized against the whole screen while // the keyboard is up runs its own controls off the bottom edge — the dock's // oldest bug, in a new dress. So the host measures the column the composer // stands in (``SwiftUICore/View/composerColumn()``) and publishes it; the card // reads it and spends a share of it. A host that forgets keeps the old 160pt // ceiling, which is a visibly smaller box and never a broken one. // // The arithmetic is PURE and lives in ``ComposerGrowth``, because a height // computed inside a `body` is a height nothing can test — // `DictationListening.swift`'s own rule, kept. import SwiftUI // MARK: - The column the host has private struct ComposerColumnKey: EnvironmentKey { /// Zero, and zero is HONEST: it means nobody has measured yet. It is not a /// stand-in for a device height — ``ComposerGrowth/fieldCap(column:)`` /// answers the old ceiling for it rather than guessing a screen. static let defaultValue: CGFloat = 0 } extension EnvironmentValues { /// The height of the column the composer stands in — the screen minus the /// keyboard, minus whatever chrome the host has above it. /// /// Published by ``SwiftUICore/View/composerColumn()``, which a host applies /// to the column that holds its composer. public var cottonComposerColumn: CGFloat { get { self[ComposerColumnKey.self] } set { self[ComposerColumnKey.self] = newValue } } } private struct ComposerColumnPreference: PreferenceKey { static let defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } } /// Measure how much of this column is ON SCREEN and publish it as /// `\.cottonComposerColumn`. /// /// **Its own height is the wrong number, and that is the whole subtlety.** A /// column that ends at the keyboard is laid out against a SHRUNK safe area, but /// what SwiftUI hands a `GeometryReader` in `.local` space is only how tall the /// view is, with nothing said about where it sits. Read in the WINDOW's space /// and clipped to it, the frame answers both at once — measured on a 16: /// `62…840` with the keyboard down and `62…539` with it up, which is 778pt and /// 477pt of usable column and exactly the two numbers the card has to spend a /// share of. /// /// Not a layout loop: the column's frame is decided by its parent, and a /// composer growing inside it moves nothing here — the dock is anchored to the /// bottom, so a taller card takes the space upward. public struct MeasuresComposerColumn: ViewModifier { @State private var column: CGFloat = 0 public init() {} public func body(content: Content) -> some View { content .background( GeometryReader { proxy in let frame = proxy.frame(in: .global) Color.clear.preference( key: ComposerColumnPreference.self, value: max(0, frame.maxY - max(frame.minY, 0)) ) } ) .onPreferenceChange(ComposerColumnPreference.self) { measured in // Guarded so a transient zero — a background layout pass while // a sheet is up — never un-measures the column. if measured > 0 { column = measured } } .environment(\.cottonComposerColumn, column) } } extension View { /// Say that THIS view is the column a composer inside it has to grow into. /// /// Applied to the column a composer is mounted in — not to the composer, /// whose own height is the thing being decided. public func composerColumn() -> some View { modifier(MeasuresComposerColumn()) } } // MARK: - How far the words may grow /// The card's growth arithmetic, and the one decision about following a live /// transcript. Pure, so both are pinned by `ComposerCardTests`. public enum ComposerGrowth { /// The share of its host's column the whole CARD may take before the words /// start scrolling inside it — "about 80% of the screen", as asked for, /// read against the column that actually exists. public static let share: CGFloat = 0.8 /// The share the INPUT BOX takes — the box on the database page, a list /// and a record's page (Spec 7): about half the screen, then it scrolls /// inside. Reading the list is the main act there, so the box never takes /// what a chat's composer may. public static let boxShare: CGFloat = 0.5 /// One line at rest — `min-h-[44px]`, carried across from the phone. public static let minHeight: CGFloat = 44 /// What the card spends on everything that is NOT the words: the control /// row, the gap above it, and the padding at both ends. Subtracted from the /// share so the CARD honours 80%, not the field plus 70 points more. public static let chrome: CGFloat = cardPadding * 2 + wordsGap + rowHeight /// The ceiling when nobody has measured the column — the height the dock /// shipped before this file existed. A host that forgets /// ``SwiftUICore/View/composerColumn()`` gets a visibly small box, never one /// whose controls have walked off the screen. public static let unmeasuredCeiling: CGFloat = 160 /// The control row's height, and the card's own padding — the numbers the /// card lays out with, named here because ``chrome`` is made of them. public static let rowHeight: CGFloat = 44 public static let cardPadding: CGFloat = 10 public static let wordsGap: CGFloat = 4 /// The tallest the words may grow before they scroll inside the box. public static func fieldCap(column: CGFloat, share: CGFloat = share) -> CGFloat { guard column > 0 else { return unmeasuredCeiling } return max(minHeight, column * share - chrome) } /// Whether an arriving change should pull the box down to its newest words. /// /// Only a DICTATION does. Typing already moves the caret and the platform /// keeps the caret in view; forcing a scroll on every keystroke would fight /// a person who has scrolled up to re-read what they wrote. An unchanged /// string scrolls nothing either — a redraw is not an arrival. public static func followsNewest( isDictating: Bool, from previous: String, to next: String ) -> Bool { isDictating && previous != next } } // MARK: - What the right end draws /// Which controls the card's row draws — a pure decision, so a test pins it /// without a microphone. public enum ComposerControls: Equatable, Sendable { /// ✕ and ✓, both inert while the finish is in flight. case dictating(finishing: Bool) /// The mic and the arrow, both always drawn; the arrow is dimmed when /// there is nothing to send. case composing(canSend: Bool) public static func decide(isLive: Bool, isFinishing: Bool, canSend: Bool) -> Self { isLive ? .dictating(finishing: isFinishing) : .composing(canSend: canSend) } } // MARK: - The discs /// The visible disc, and the target around it — 40 inside 44, the rule /// `NavCircle` already spends: the disc is what you see, the target is what /// you hit. enum ComposerDisc { static let diameter: CGFloat = 40 static let target: CGFloat = 44 static let glyphSize: CGFloat = 19 } /// One disc on the control row. Filled discs are the affirmative verbs (send, /// finish); outlined ones are the quiet ones (add, mic, discard). struct ComposerDiscButton: View { @Environment(\.theme) private var theme let identifier: String let label: String let symbol: String let tint: TextInk let filled: Bool let disabled: Bool /// Dimmed rather than hidden — the arrow with nothing to send. var dimmed = false var fill: Color = CottonColors.accent let action: () -> Void var body: some View { Button(action: action) { ZStack { if filled { Circle().fill(fill) } else { // The card is `groundMuted`; a quiet disc has to sit ABOVE // it or it disappears into the box it stands on. Circle().fill(CottonColors.groundElevated) Circle().strokeBorder(CottonColors.hairline, lineWidth: ComposerCardKnobs.chromeHairline) } // An unmapped lucide name draws NOTHING rather than a wrong // picture — `Glyph`'s own rule. if let sfSymbol = Glyph.symbol(symbol) { Image(systemName: sfSymbol) .font(.system(size: ComposerDisc.glyphSize, weight: .regular)) .foregroundStyle(tint.color) } } .frame(width: ComposerDisc.diameter, height: ComposerDisc.diameter) .opacity(dimmed ? DisabledOpacity.control : 1) .frame(width: ComposerDisc.target, height: ComposerDisc.target) // NO disabled dim on the dictation pair, deliberately: finishing // changes nothing about how the two discs are painted — the // `loader` glyph swapped in is the whole signal, and a fade over a // spinner reads as a broken button rather than a busy one. .contentShape(Circle()) } .buttonStyle(MotionButtonStyle()) .disabled(disabled) .accessibilityLabel(label) .accessibilityIdentifier(identifier) } } // MARK: - The meter /// The live level meter — the bars, and nothing else. /// /// It takes values rather than a model, because its hosts hold different ones /// (`DockModel` and the `DictationModel` a chat bar built itself) and a shared /// view that needed one of them would not be shared at all. struct ComposerMeter: View { /// The newest levels, oldest first — `DictationModel.waveform`. let waveform: [Double] /// A session is up or coming up. let isListening: Bool /// The ERROR tone rather than the accent, for the palette's own reason: a /// recording indicator is the one thing on the screen that must read as /// "this is live", and the accent is the app's interactive colour. /// It takes the whole width it is given, as many bars as fit, newest on /// the right. var body: some View { GeometryReader { geo in let bars = min( DictationWaveform.barCount, MeetingWaveform.barCount( width: geo.size.width + DictationWaveform.gap, pitch: DictationWaveform.pitch)) HStack(alignment: .center, spacing: DictationWaveform.gap) { ForEach(Array(DictationWaveform.heights(waveform, bars: bars).enumerated()), id: \.offset) { _, height in Capsule() .fill(CottonColors.statusError) .frame(width: DictationWaveform.bar, height: 16 * height) .opacity(isListening ? 1 : 0.4) } } .frame(width: geo.size.width, height: geo.size.height, alignment: .trailing) } .frame(maxWidth: .infinity) .frame(height: 16) .animation(.linear(duration: 0.08), value: waveform) .accessibilityHidden(true) } } // MARK: - The card /// The pill in the idle row: what it says, and what a tap on it opens. struct ComposerPill { let label: String /// Whether the label names a project — it then wears the `#` a project /// chip wears. "No project" does not. let isAimed: Bool let accessibilityLabel: String let action: () -> Void } /// The database chip in the idle row: a small bottle cap in the database's own /// colour and its name, the way the Claude app shows its model — it says where /// the words will go, and a tap opens the Databases screen (Spec 7). struct ComposerChip { let name: String let colour: CapColour /// The chip's own identifier, whole: the walks know it as `bar-database`. let identifier: String let action: () -> Void /// The cap is drawn at exactly the discs' diameter. static var capSide: CGFloat { ComposerDisc.diameter } /// What the cap says aloud: what it is, which one, and what a tap does. static func spoken(_ name: String) -> String { ShellLines.line("capture", "composer.database_chip", ["name": name]) } } /// The box: the words a host draws, and the one control row beneath them. /// /// Every verb is a closure rather than a model call, for the reason the meter /// takes values: the dock and the chat bar keep different brains and a card /// that knew either of them would be the dock's card with a chat hosted in it. struct ComposerCard: View { let controls: ComposerControls /// The accessibility-identifier stem the row's discs hang off. let identifier: String /// The `+` at the left end — `nil` where the host has none. A chat has /// nothing to make; the capture dock opens its fan here. var onAdd: (() -> Void)? var addLabel: String = ShellLines.line("capture", "composer.make_something") /// The pill beside the `+` — where the Claude app shows its model, the /// capture dock shows the project the thought will land in. `nil` for a /// host with nothing to aim, and then the row is exactly `+` · mic · send. var pill: ComposerPill? = nil /// The database chip beside the `+` — the database page's box alone. var chip: ComposerChip? = nil /// Send's own name — "Capture" in the dock, "Send" in a chat. var sendLabel: String = "Send" var waveform: [Double] = [] var isListening = false var clock: String = "" /// The mic is unreachable until the host has an engine to start. var canDictate = true /// A keyboard disc in the RECORDING row, beside ✕: land the words heard so /// far and go on typing (design 2026-09-13 D5, "the keyboard glyph inside /// the surface switches to typing"). `nil` for a host that offers no such /// switch — every chat, and the capture dock as the chat mounts it — and /// then the row is exactly the ✕ · clock · meter · ✓ it has always been. var onSwitchToTyping: (() -> Void)? = nil let onDictate: () -> Void let onSend: () -> Void let onCancelDictation: () -> Void let onFinishDictation: () -> Void /// Send what was heard at once, from the recording row: land the words /// and send them. `nil` for a host with one finish and no send while /// speaking, which keeps its ✓. var onSendDictation: (() -> Void)? = nil /// Cancel at the right of the words' own row — Home's thought field /// raised from the record button (architect, 14 Oct 2026: nothing of the /// box draws over the page). `nil` everywhere else. var onCancel: (() -> Void)? = nil /// The control row is put away — the keyboard is up under Home's thought /// field — and send stands in the words' row beside Cancel. var rowHidden = false /// A hold on the mic is in flight: letting go sends. @State private var holding = false /// When the last hold ended — the tap that lifting a held finger also /// makes is not a second verb. @State private var holdEnded = Date.distantPast @ViewBuilder let words: () -> Words var body: some View { VStack(alignment: .leading, spacing: ComposerGrowth.wordsGap) { if let onCancel { HStack(alignment: .bottom, spacing: 4) { VStack(alignment: .leading, spacing: ComposerGrowth.wordsGap) { words() } Button(HomeInputWords.cancel, action: onCancel) .cottonType(.body, ink: .secondary) .frame(height: ComposerDisc.target) .accessibilityIdentifier("\(identifier)-cancel") if rowHidden { arrow } } } else { words() } if !rowHidden { row } } // Its IDEAL height, never what its host has spare: the words are // bounded (a least and a most), and a bounded view takes whatever it // is offered up to its most — so at the foot of a page the empty box // stood at its full grown height and never grew. .fixedSize(horizontal: false, vertical: true) .padding(.horizontal, ComposerGrowth.cardPadding) .padding(.vertical, ComposerGrowth.cardPadding) // The input paper — a cream, cut sheet (redesign phase 15, picture // 30). The paper's own edge and shadow are its outline; there is no // hairline to draw around a sheet. .background(PaperSurface(dye: .cream, edge: .cut, seed: "\(identifier)-card")) // The card is a CONTAINER with its own name: an identifier set on // it bare is what every control inside answered to, so the mic, the // arrow, the chip and the words were all `…-card` and a walk could // not tell one from another. .accessibilityElement(children: .contain) .accessibilityIdentifier("\(identifier)-card") } /// ONE row, whatever the state: something at the left end, the spare /// width, and at the right end two places that never move — the mic's, /// which is stop while a take is up, and the arrow's. @ViewBuilder private var row: some View { HStack(spacing: 4) { switch controls { case .dictating(let finishing): ComposerDiscButton( identifier: "\(identifier)-dictation-cancel", label: CottonStrings.discardDictation, symbol: "x", tint: .secondary, filled: false, disabled: finishing, action: onCancelDictation ) if let onSwitchToTyping { ComposerDiscButton( identifier: "\(identifier)-dictation-keyboard", label: ShellLines.line("capture", "composer.type_instead"), symbol: "keyboard", tint: .secondary, filled: false, disabled: finishing, action: onSwitchToTyping ) } // The clock is kept, and kept SMALL: the elapsed time is worth // knowing and is not what the row is for. Text(clock) .cottonType(.caption, ink: .tertiary, tabular: true) .accessibilityLabel(ShellLines.line("capture", "composer.recorded", ["clock": clock])) // The meter IS the row: it fills the whole gap to the stop // button (owner, build 280: a meter in 60% of the row read as // a row half built). ComposerMeter(waveform: waveform, isListening: isListening) .accessibilityIdentifier("\(identifier)-listening") case .composing: if let onAdd { ComposerDiscButton( identifier: "\(identifier)-add", label: addLabel, symbol: "plus", tint: .secondary, filled: false, disabled: false, action: onAdd ) } if let chip { // The database's cap ALONE, at the discs' own diameter in // their own touch area, so the row reads as four equal // rounds: + · cap · mic · send (owner, 6 Oct). No name text. Button(action: chip.action) { ProjectCap(name: chip.name, colour: chip.colour, side: ComposerChip.capSide) .frame(width: ComposerChip.capSide, height: ComposerChip.capSide) .frame(width: ComposerDisc.target, height: ComposerDisc.target) .contentShape(Rectangle()) } .buttonStyle(MotionButtonStyle()) .accessibilityLabel(ComposerChip.spoken(chip.name)) .accessibilityIdentifier(chip.identifier) } if let pill { Chip( label: pill.label, prefix: pill.isAimed ? .project : nil, accessibilityLabel: pill.accessibilityLabel, action: pill.action ) .lineLimit(1) .truncationMode(.tail) .layoutPriority(-1) .accessibilityIdentifier("\(identifier)-project-pill") } Spacer(minLength: 8) } // The two places at the right end, the SAME two views in both // states: a hold that starts a take is still on the mic's disc // when the row under it becomes the recording row. speak arrow } .frame(height: ComposerGrowth.rowHeight) } private var finishing: Bool { if case .dictating(let finishing) = controls { return finishing } return false } private var isLive: Bool { if case .dictating = controls { return true } return false } private var sendable: Bool { if case .composing(let canSend) = controls { return canSend } return false } /// The mic's place: the mic, filled while the box is empty; stop while a /// take is up — or the ✓ a host with no send-while-speaking has always had. @ViewBuilder private var speak: some View { let done = onSendDictation == nil ComposerDiscButton( identifier: isLive ? "\(identifier)-dictation-done" : "\(identifier)-mic", label: isLive ? CottonStrings.finishDictation : CottonStrings.dictateHint, symbol: isLive ? (finishing ? "loader" : (done ? "check" : "square")) : "mic", tint: isLive ? (done ? .inverse : .accent) : (sendable ? .accent : .inverse), filled: isLive ? done : !sendable, disabled: isLive ? finishing : !canDictate, action: { // Lifting a held finger is not a tap. guard !holding, Date().timeIntervalSince(holdEnded) > 0.4 else { return } if isLive { onFinishDictation() } else { onDictate() } } ) .simultaneousGesture(hold) } /// Hold the mic, speak, let go: the words are sent. Only where the host /// sends while speaking, and only from rest. private var hold: some Gesture { LongPressGesture(minimumDuration: 0.35) .sequenced(before: DragGesture(minimumDistance: 0)) .onChanged { value in guard case .second(true, _) = value, !holding, onSendDictation != nil, !isLive, canDictate else { return } holding = true onDictate() } .onEnded { _ in guard holding else { return } holding = false holdEnded = Date() onSendDictation?() } } /// The arrow's place: faint with nothing to send, filled once there are /// words; while a take is up it sends what was heard. @ViewBuilder private var arrow: some View { if isLive { if let onSendDictation { ComposerDiscButton( identifier: "\(identifier)-dictation-send", label: sendLabel, symbol: "arrow-up", tint: .inverse, filled: true, disabled: finishing, action: onSendDictation ) } } else { ComposerDiscButton( identifier: "\(identifier)-send", label: sendLabel, symbol: "arrow-up", tint: sendable ? .inverse : .secondary, filled: sendable, disabled: !sendable, dimmed: !sendable, action: onSend ) } } } // MARK: - The words /// The inset a `TextEditor` puts around its own text. The measuring twin and /// the transcript both mirror it, or the box is a few points short of the /// words it holds. let composerTextInset = EdgeInsets(top: 8, leading: 5, bottom: 8, trailing: 5) /// The size of the typing in a composer — the words a person is putting onto /// the paper are typed, like the words already on it (picture 30). ONE number /// for the editor, its measuring twin, the placeholder and the transcript, or /// the twin measures a height the editor does not fill. let composerTypeSize: CGFloat = 16 /// The words half of the card: an editor while the person owns the field, the /// live transcript while a dictation does, and the invisible twin that gives /// both of them a height. /// /// **Why a twin.** `TextEditor` does not self-size — it is a scroll view, and a /// bare frame would pin it at one height for ever. So a hidden `Text` holding /// the same words in the same type is what the stack measures, and the editor /// fills whatever that comes to, clamped between one line and the cap. struct ComposerWords: View { /// What the field is SHOWING — the live transcript while dictating, the /// draft otherwise. The twin measures this, not the draft. let shown: String let placeholder: String let isDictating: Bool /// The tallest these words may grow — ``ComposerGrowth/fieldCap(column:)``. let cap: CGFloat let identifier: String @ViewBuilder let editor: () -> Editor var body: some View { ZStack(alignment: .topLeading) { // The measuring twin. A single space stands in for an empty draft // so the stack never collapses below one line. Text(shown.isEmpty ? " " : shown) .paperBody(composerTypeSize) .padding(composerTextInset) .frame(maxWidth: .infinity, alignment: .topLeading) .opacity(0) .accessibilityHidden(true) if shown.isEmpty && !isDictating { Text(placeholder) .paperBody(composerTypeSize, ink: .pencil) .padding(composerTextInset) .allowsHitTesting(false) } if isDictating { ComposerTranscript(text: shown, identifier: identifier) } else { editor() } } .frame(minHeight: ComposerGrowth.minHeight, maxHeight: cap) } } /// The words a dictation is putting into the field: read-only, and always /// scrolled to the NEWEST of them. /// /// A `Text` in a scroller rather than the disabled editor the field used to /// keep: the editor cannot be told where to scroll, and it stopped at the top /// of a transcript that went on growing — the owner's report, and the whole /// reason this view exists. Nothing is lost by the swap, because the field is /// not editable while a dictation owns it either way. struct ComposerTranscript: View { let text: String let identifier: String /// The anchor at the very end of the words — what "the newest" means to a /// scroller. private static let newest = "composer-transcript-newest" var body: some View { ScrollViewReader { proxy in ScrollView(.vertical, showsIndicators: false) { VStack(alignment: .leading, spacing: 0) { Text(text) .paperBody(composerTypeSize) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .topLeading) Color.clear.frame(height: 1).id(Self.newest) } .padding(composerTextInset) } .scrollContentBackground(.hidden) .onChange(of: text) { previous, next in guard ComposerGrowth.followsNewest(isDictating: true, from: previous, to: next) else { return } withAnimation(.easeOut(duration: 0.12)) { proxy.scrollTo(Self.newest, anchor: .bottom) } } // A session that starts over words already in the field opens at // their end, not at their top. .onAppear { proxy.scrollTo(Self.newest, anchor: .bottom) } } .accessibilityIdentifier("\(identifier)-transcript") } } /// The sizes, counts and timings ComposerCard draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum ComposerCardKnobs { static let chromeHairline: CGFloat = 0.7 }