// THE PILL — the app's hero, and the natural-language half of the dock.//// Its VIEW half; every decision it makes about state lives in// `DockModel.swift`, and the BOX it is drawn in — the card, its one control// row, and how far the words may grow — is `ComposerCard.swift`, shared with// every chat.//// A big, inviting field that takes the thought and lets go: type + send, or tap// the mic and SPEAK — the transcript streams into the field as you talk. It// stays ignorant of AI the same way it stays ignorant of the dock: it renders// what the model says and draws whatever the host puts in its plan slot.//// ## THE MIC AND SEND ARE BOTH ALWAYS DRAWN//// They used to share one slot: the mic while the field was empty, send the// moment there were words. The reasoning was that a thought you have already// typed has exactly one next move — and it is wrong, as the owner reported// after living with it. A thought is very often typed halfway and then// spoken (a name you cannot spell, a sentence too long for thumbs), and a// field you cannot speak into after the first word makes you delete what you// typed to reach the microphone. So the card draws both, with send DIMMED// while there is nothing to send, and the dictation SPLICES onto the words// already there (`DockModel.startDictation`'s prefix, which was written for// exactly this and was until now unreachable).//// ## Three places SwiftUI and the old toolkit disagree, and what was done//// **1. The growing field.** RN's `<TextInput multiline>` sizes itself to its// content. SwiftUI's `TextEditor` does NOT self-size — it is a scroll view, and// a bare frame would pin it at one height for ever. So an invisible twin `Text`// holding the same words in the same type is what the stack measures// (`ComposerWords`), and the editor fills whatever that comes to, clamped// between one line and ``ComposerGrowth/fieldCap(column:)``.//// **2. The caret.** The whole `#`/`@` grammar is "which token is the caret// standing in", so a field that cannot report its caret cannot have the// grammar. `TextEditor(text:selection:)` is the one control that reports one,// which is the reason it is used here over `TextField(axis: .vertical)` — whose// native growth and native placeholder would otherwise have made both problems// above disappear. The offset is converted to CHARACTERS in ONE function// (``caretOffset(of:in:)``), because that is the index space// `SigilTokenizer.swift` reports its spans in and a UTF-16 offset passed// through raw would cut through a grapheme.//// **3. Read-only while dictating.** The field is not merely disabled then — it// is REPLACED by `ComposerTranscript`, a scroller that follows the newest// words. A disabled editor cannot be told where to scroll, and it stopped at// the top of a transcript that went on growing. Swapping it also keeps the// keyboard down, which is the behaviour the owner asked to keep: a tap on the// mic ends editing, and nothing here puts it back.//// ## What did NOT port//// The `embedded` and page forms. The composer had three dresses — docked,// embedded in Home's capture block, and a bordered card — and 4d has one host:// the dock. Home mounts no composer at all (capture-chat spec 2026-09-02), so// the other two would be two dresses nothing wears, and a form with no host is// a form nobody notices going wrong.importSwiftUIpublicstructCaptureComposer<Plan: View>: View {privatelet model: DockModel/// The pill's invitation. The composer's own voice by default; the dock/// overrides it per PLACE ("Add to Meri…" on a project page) — the scoping/// rule's visible half.privatelet placeholder: String?/// The plan chips, drawn ABOVE the words inside the card so what the/// capture is about to become sits with the words that made it.////// **`/thoughts` passes none**, and that is the surface's own decision, not/// an omission: the capture chat mounts no live plan preview, so nothing is/// drawn in this band there and it takes no height.privatelet planSlot: () -> Plan/// What the `+` at the left end of the control row does — the dock's fan./// It lives INSIDE the card now (the Claude composer's own shape, which is/// what was asked for), so the dock hands its action down rather than/// standing a circle beside the pill.privatelet onAdd: (() -> Void)?privatelet addLabel: String/// What a tap on the project pill does — the dock's projects sheet. `nil`/// draws no pill.privatelet onChooseProject: (() -> Void)?/// The accessibility-identifier stem — the dock's own stem with/// `-composer` appended, which for the one host that exists is this/// default.privatelet identifier: String/// Whether the recording row offers the keyboard disc that lands the words/// and switches to typing. Home's capture surface says yes; the chat's dock/// keeps the row it has.privatelet offersTypingSwitch: Bool/// The database chip beside the `+` — the database page's box (Spec 7).privatelet chip: ComposerChip?/// The share of the column the card may grow to.privatelet share: CGFloat/// Whether the recording row sends what was heard at once, and a hold on/// the mic speaks and sends.privatelet sendsWhileSpeaking: Bool/// A dictated draft's command, handed to the send (`DockModel.SpokenCommand`).privatelet runsSpokenCommand: DockModel.SpokenCommand?/// Cancel in the words' row, and whether the control row is put away/// (`ComposerCard.onCancel`, `rowHidden`).privatevar onCancel: (() -> Void)?privatevar rowHidden = false// `TextSelection` is iOS 18 / macOS 15; on the Mac's 14 floor the editor// runs without a selection and the caret is read as the end of the text. #if os(iOS) @State privatevar selection: TextSelection? #endif @FocusState privatevar isFocused: Bool/// The column the dock stands in, measured by the host — see/// `ComposerCard.swift`'s header on why the cap cannot be a constant. @Environment(\.cottonComposerColumn) privatevar columninit( model: DockModel, placeholder: String? = nil, identifier: String = "dock-composer", onAdd: (() -> Void)? = nil, addLabel: String = ShellLines.line("capture", "composer.make_something"), onChooseProject: (() -> Void)? = nil, offersTypingSwitch: Bool = false, chip: ComposerChip? = nil, share: CGFloat = ComposerGrowth.share, sendsWhileSpeaking: Bool = false, runsSpokenCommand: DockModel.SpokenCommand? = nil, @ViewBuilder planSlot: @escaping () -> Plan ) {self.runsSpokenCommand = runsSpokenCommandself.chip = chipself.share = shareself.sendsWhileSpeaking = sendsWhileSpeakingself.model = modelself.placeholder = placeholderself.identifier = identifierself.onAdd = onAddself.addLabel = addLabelself.onChooseProject = onChooseProjectself.offersTypingSwitch = offersTypingSwitchself.planSlot = planSlot }publicvar body: someView {ComposerCard( controls: ComposerControls.decide( isLive: model.isDictationLive, isFinishing: model.isFinishing,// Words, and no picture still on its way in — see// `DockModel.isReadyToSend`. canSend: model.isReadyToSend ), identifier: identifier, onAdd: onAdd, addLabel: addLabel, pill: onChooseProject.map { choose inComposerPill( label: model.projectPillLabel, isAimed: !model.aimedProjects.isEmpty, accessibilityLabel: ShellLines.line("capture", "composer.project_pill", ["project": model.projectPillLabel]), action: choose ) }, chip: chip, sendLabel: "Capture", waveform: model.dictationWaveform, isListening: model.isListening, clock: model.dictationClock, onSwitchToTyping: offersTypingSwitch ? { Task { await model.switchToTyping() } } : nil, onDictate: { Task { await model.startDictation() } }, onSend: { Task { await model.send(runsSpokenCommand: runsSpokenCommand) } }, onCancelDictation: { model.cancelDictation() }, onFinishDictation: { Task { await model.finishDictation() } }, onSendDictation: sendsWhileSpeaking ? {Task {await model.finishDictation()if model.isReadyToSend { await model.send(runsSpokenCommand: runsSpokenCommand) } } } : nil, onCancel: onCancel, rowHidden: rowHidden ) {// What this is about to become, above the words that made it —// absent, and taking no height, until the classifier has something// to say. Nothing at all while dictating: a plan chip describing// pre-dictation words would be a stale promise.if !model.isDictationLive { planSlot() }// The pictures on the draft, above the words they are the other// half of — drawn while dictating too, because they are on the// capture whatever the field is doing. Absent, and taking no// height, until there is one.DockPictureStrip( pictures: model.pictures, arriving: model.picturesArriving, identifier: identifier, onRemove: { model.detach(picture: $0) } ) field }// No identifier on the card itself: one set out here is what every// control inside answered to, so the mic, the arrow and the chip were// all `identifier` and none could be told from another. }/// Cancel at the right of the words' row; `rowHidden` puts the control/// row away and stands send beside it.func cancelling(_ action: @escaping () -> Void, rowHidden: Bool, when on: Bool = true) -> Self {guard on else { returnself }var composer = self composer.onCancel = action composer.rowHidden = rowHiddenreturn composer }// ── The words ─────────────────────────────────────────────────────────privatevar field: someView {ComposerWords( shown: model.displayText, placeholder: placeholder ?? ShellLines.line("capture", "composer.placeholder"), isDictating: model.isDictationLive, cap: ComposerGrowth.fieldCap(column: column, share: share), identifier: identifier ) { editor .scrollContentBackground(.hidden) .paperBody(composerTypeSize) .focused($isFocused)// Put the keyboard in the pill NOW — the capture deep link's// whole requirement (`tinmen-cotton://capture`). A COUNTER// rather than an `autoFocus` flag, for the reason the dock has// always needed an imperative handle: it acts when the field// MOUNTS, and the dock's host is the root of its stack and// never remounts, so a warm tap would change nothing a// mount-time fact can see. .onChange(of: model.focusRequests) { _, _ in isFocused = true } #if os(iOS) .onChange(of: selection) { _, next inguard !model.isDictationLive else { return } model.caretMoved(to: caretOffset(of: next, in: model.text)) } #endif .accessibilityIdentifier("\(identifier)-input") .accessibilityLabel(placeholder ?? ShellLines.line("capture", "composer.placeholder")) } }/// The field's words, and the one way in.////// The setter goes through the model rather than to a `@State` of its own/// because three writers want this string — the keyboard, dictation, and/// the dock cutting a `#meri` out once its chip has landed — and a field/// that owned it would make them race.privatevar fieldBinding: Binding<String> {Binding( get: { model.displayText }, set: { model.fieldEdited($0) } ) }/// The editor, with a selection binding where the platform has one.privatevar editor: someView { #if os(iOS)TextEditor(text: fieldBinding, selection: $selection) #elseTextEditor(text: fieldBinding) #endif }/// A `TextSelection` as a CHARACTER offset — the index space the tokenizer/// reports its spans in.////// `String.distance` counts extended grapheme clusters, which is what/// `Array(text)` counts on the other side of the seam, so a caret standing/// after an emoji arrives as the same number both sides read. #if os(iOS)privatefunc caretOffset(of selection: TextSelection?, in text: String) -> Int {guardlet selection else { return text.count }switch selection.indices {case .selection(let range):return offset(of: range.lowerBound, in: text)case .multiSelection(let set):// A multi-selection has no single caret; the earliest is the one a// completion would be read against.guardlet first = set.ranges.first else { return text.count }return offset(of: first.lowerBound, in: text) @unknown default:return text.count } } #endif/// The character offset of an index that may not belong to `text` any more.////// **Every measurement is bounds-checked first, and that is not/// defensiveness.** The index comes from the string the `TextEditor` is/// bound to; `text` here is `DockModel`'s, and `DockModel.attach`/// deliberately SHORTENS it out from under the editor when a chip lands —/// the cut `#meri`, the window `caretMoved(to:)`'s own comment names. A/// selection reported across that window points past the end, and/// `String.distance` walking past `endIndex` is a TRAP in Swift where it/// was a clamp in JavaScript. `caretMoved` clamps the RESULT; this clamps/// the index, which is one line earlier and the line that crashes.////// Comparing two `String.Index` values is total — it compares their encoded/// positions and never traps — so the bounds test is safe where the walk/// that follows it is not. Out of range answers the END of the text, which/// is where a programmatic edit has just put the caret anyway.privatefunc offset(of index: String.Index, in text: String) -> Int {guard index >= text.startIndex, index <= text.endIndex else { return text.count }return text.distance(from: text.startIndex, to: index) }}extensionCaptureComposerwherePlan == EmptyView {/// A composer with NO plan band — `/thoughts`' own form, and the one a/// surface takes when nothing is classifying.init( model: DockModel, placeholder: String? = nil, identifier: String = "dock-composer", onAdd: (() -> Void)? = nil, addLabel: String = ShellLines.line("capture", "composer.make_something"), onChooseProject: (() -> Void)? = nil, offersTypingSwitch: Bool = false, chip: ComposerChip? = nil, share: CGFloat = ComposerGrowth.share, sendsWhileSpeaking: Bool = false, runsSpokenCommand: DockModel.SpokenCommand? = nil ) {self.init( model: model, placeholder: placeholder, identifier: identifier, onAdd: onAdd, addLabel: addLabel, onChooseProject: onChooseProject, offersTypingSwitch: offersTypingSwitch, chip: chip, share: share, sendsWhileSpeaking: sendsWhileSpeaking, runsSpokenCommand: runsSpokenCommand ) {EmptyView() } }}