Cotton code
435 lines · 17.5 KB · SwiftRaw
// The shared composer (owner's direction, 19 Nov 2026): one input bar for// every Cotton app that takes typed or spoken words. A rounded panel at the// foot: the text area on top, growing to about seven lines; beneath it a row// of controls, left to right: the app's add slot (optional), the pick chip// (optional), then the microphone and send. While dictating the row is ✕,// a live waveform, stop and send; the words land in the same text as they// are heard. Stop keeps them, ✕ throws away only what this dictation added,// send stops and sends. Where the app records voice messages (a recorder is// handed in), the same microphone held records one: the time and the// loudness stand where the add slot was, let go sends it, slid away first// throws it out; a tap still dictates. One microphone, never two.//// It knows nothing of the app: every word, the chip's rows and their order,// the send rule and the colours are handed in.import SwiftUIpublic struct Composer<Leading: View>: View {    @Binding private var text: String    private let lines: ComposerLines    private let pick: ComposerPick?    private let style: ComposerStyle    private let dictation: (any ComposerDictation)?    private let recorder: (any ComposerRecorder)?    private let sendRule: Bool?    private let returnSends: Bool    private let focused: Binding<Bool>?    private let identifier: String    private let leading: Leading    private let send: () -> Void    private var picked: (ComposerPickChoice) -> Void = { _ in }    /// The height an app stands over the field inside its writing box (where a message goes, an edit's strip).    private var reserved: CGFloat = 0    /// Where the person's selection is (UTF-16), for a dictation to begin there.    @State private var selection: NSRange?    /// A held voice message slid far enough to be thrown out on letting go.    @State private var slidAway = false    /// - Parameters:    ///   - sendRule: the send button's state when the app decides it; nil    ///     enables it whenever the text holds more than space.    ///   - returnSends: Return sends (true) or writes a new line (false).    ///   - recorder: where the microphone held records a voice message; nil, a hold is a tap.    ///   - identifier: the prefix of every control's accessibility identifier.    public init(        text: Binding<String>,        lines: ComposerLines,        pick: ComposerPick? = nil,        style: ComposerStyle,        dictation: (any ComposerDictation)? = nil,        recorder: (any ComposerRecorder)? = nil,        sendRule: Bool? = nil,        returnSends: Bool = false,        focused: Binding<Bool>? = nil,        identifier: String = "composer",        @ViewBuilder leading: () -> Leading,        send: @escaping () -> Void    ) {        _text = text        self.lines = lines        self.pick = pick        self.style = style        self.dictation = dictation        self.recorder = recorder        self.sendRule = sendRule        self.returnSends = returnSends        self.focused = focused        self.identifier = identifier        self.leading = leading()        self.send = send    }    /// The height the app stands over the field inside its writing box: the text area gives way first, so the    /// whole box, its Send among it, stays above the keyboard at the largest text.    public func reserving(_ height: CGFloat) -> Self {        var copy = self        copy.reserved = max(0, height)        return copy    }    /// What a tap in the pick menu chose.    public func onPick(_ action: @escaping (ComposerPickChoice) -> Void) -> Self {        var copy = self        copy.picked = action        return copy    }    private var phase: ComposerDictationPhase { dictation?.phase ?? .idle }    private var canSend: Bool { ComposerRules.canSend(text: text, rule: sendRule) }    public var body: some View {        VStack(alignment: .leading, spacing: 4) {            area            controls        }        .padding(.horizontal, 14)        .padding(.top, 6)        .padding(.bottom, 8)        .background(            RoundedRectangle(cornerRadius: style.cornerRadius, style: .continuous)                .fill(style.panel)                .overlay(RoundedRectangle(cornerRadius: style.cornerRadius, style: .continuous).strokeBorder(style.rim, lineWidth: 1))                .shadow(color: .black.opacity(0.08), radius: 8, x: 0, y: 2)        )        .onChange(of: dictation?.shown) { _, shown in            // The dictation's words land in the text as they are heard.            guard let dictation, let shown, shown != text else { return }            dictation.didWrite(shown)            text = shown        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier(identifier)    }    // MARK: The text    @ViewBuilder private var area: some View {        ZStack(alignment: .topLeading) {            if text.isEmpty {                Text(verbatim: lines.hint)                    .font(style.face.font)                    .foregroundStyle(style.faint)                    .padding(.vertical, 8)                    .lineLimit(1)                    .allowsHitTesting(false)                    .accessibilityHidden(true)            }            #if canImport(UIKit)            ComposerTextArea(                text: $text,                focused: focused,                face: style.face,                ink: style.ink,                faint: style.faint,                tentative: dictation?.shown == nil ? nil : dictation?.tentativeRange,                caret: dictation?.shown == nil ? nil : dictation?.caret,                returnSends: returnSends,                label: lines.hint,                identifier: "\(identifier)-text",                send: sendNow,                edited: { now in dictation?.fieldChanged(now) },                selected: { range in                    selection = range                    dictation?.selectionChanged(range)                },                reserved: reserved            )            #else            TextField(text: $text, axis: .vertical) { Text(verbatim: lines.hint) }                .lineLimit(1 ... ComposerRules.maxLines)                .font(style.face.font)                .foregroundStyle(style.ink)                .textFieldStyle(.plain)                .padding(.vertical, 8)                .onSubmit { if returnSends { sendNow() } }                .accessibilityIdentifier("\(identifier)-text")            #endif        }    }    // MARK: The row beneath    @ViewBuilder private var controls: some View {        HStack(spacing: 8) {            if phase.isDictating {                round(symbol: "xmark", label: lines.cancel, id: "cancel", filled: false, action: cancel)                ComposerWaveform(level: dictation?.level ?? 0, live: phase == .listening, colour: style.accent, faint: style.faint)                    .frame(maxWidth: .infinity)                    .frame(height: 32)                    .accessibilityElement()                    .accessibilityLabel(Text(verbatim: lines.listening))                    .accessibilityIdentifier("\(identifier)-waveform")                if phase == .listening {                    round(symbol: "stop.fill", label: lines.stop, id: "stop", filled: false, action: stop)                } else {                    ProgressView()                        .controlSize(.small)                        .tint(style.ink)                        .frame(width: 44, height: 44)                        .accessibilityLabel(Text(verbatim: lines.listening))                }                sendButton            } else {                if let recorder, recorder.recording {                    recordingState(recorder)                } else {                    leading                    if let pick {                        ComposerPickChip(pick: pick, style: style, identifier: identifier, picked: picked)                            .layoutPriority(1)                    }                    Spacer(minLength: 0)                }                // The one microphone: a tap dictates, held it records (where a recorder is handed in).                // It keeps its place in the row while held, so the hold is never lost as the row changes.                if dictation != nil || recorder != nil {                    ComposerMic(symbol: failed ? "mic.slash" : "mic", label: failedWords ?? lines.mic, identifier: "\(identifier)-mic",                                style: style, recorder: recorder, away: $slidAway, tap: mic)                }                sendButton            }        }        .frame(minHeight: 44)        .animation(.easeOut(duration: 0.18), value: phase.isDictating)    }    /// A voice message being recorded: a dot, its time and its loudness where the add slot stood;    /// slid away, they turn the danger colour (letting go throws it out).    private func recordingState(_ recorder: any ComposerRecorder) -> some View {        HStack(spacing: 8) {            Circle().fill(style.danger).frame(width: 8, height: 8).padding(.leading, 6)            Text(verbatim: Duration.seconds(recorder.elapsed).formatted(.time(pattern: .minuteSecond)))                .font(style.face.font)                .monospacedDigit()                .foregroundStyle(slidAway ? style.danger : style.ink)                .fixedSize()                .accessibilityIdentifier("\(identifier)-record-time")            ComposerWaveform(level: recorder.level, live: !slidAway, colour: style.accent, faint: style.danger.opacity(0.5))                .frame(maxWidth: .infinity)                .frame(height: 32)                // At the largest text the time leaves little room: the bars keep to theirs.                .clipped()                .accessibilityHidden(true)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("\(identifier)-recording")    }    private var sendButton: some View {        let ready = canSend || phase.isDictating        return Button(action: sendNow) {            Image(systemName: "arrow.up")                .font(.system(size: 17, weight: .semibold))                .foregroundStyle(ready ? style.onAccent : style.faint)                .frame(width: 36, height: 36)                .background(Circle().fill(ready ? style.accent : style.faint.opacity(0.25)))                .frame(width: 44, height: 44)                .contentShape(Circle())        }        .buttonStyle(.plain)        .disabled(!ready)        .accessibilityLabel(Text(verbatim: lines.send))        .accessibilityIdentifier("\(identifier)-send")    }    private func round(symbol: String, label: String, id: String, filled: Bool, action: @escaping () -> Void) -> some View {        Button(action: action) {            Image(systemName: symbol)                .font(.system(size: 19, weight: .regular))                .foregroundStyle(filled ? style.onAccent : style.ink)                .frame(width: 44, height: 44)                .background(Circle().fill(filled ? style.accent : Color.clear).padding(4))                .contentShape(Circle())        }        .buttonStyle(.plain)        .accessibilityLabel(Text(verbatim: label))        .accessibilityIdentifier("\(identifier)-\(id)")    }    private var failed: Bool { if case .failed = phase { true } else { false } }    private var failedWords: String? { if case .failed(let why) = phase { why } else { nil } }    // MARK: Acts    private func mic() {        guard let dictation else { return }        let from = selection        Task { await dictation.start(text: text, selection: from) }    }    private func stop() {        guard let dictation else { return }        Task { text = await dictation.stop() }    }    private func cancel() {        guard let dictation else { return }        text = dictation.cancel()    }    private func sendNow() {        if let dictation, phase.isDictating {            Task {                text = await dictation.stop()                if ComposerRules.canSend(text: text, rule: sendRule) { send() }            }            return        }        guard canSend else { return }        send()    }}public extension Composer where Leading == EmptyView {    init(        text: Binding<String>,        lines: ComposerLines,        pick: ComposerPick? = nil,        style: ComposerStyle,        dictation: (any ComposerDictation)? = nil,        recorder: (any ComposerRecorder)? = nil,        sendRule: Bool? = nil,        returnSends: Bool = false,        focused: Binding<Bool>? = nil,        identifier: String = "composer",        send: @escaping () -> Void    ) {        self.init(            text: text, lines: lines, pick: pick, style: style, dictation: dictation, recorder: recorder, sendRule: sendRule,            returnSends: returnSends, focused: focused, identifier: identifier, leading: { EmptyView() }, send: send        )    }}// MARK: - The microphone/// The composer's one microphone. A tap dictates. With a recorder, a press/// held past ``ComposerRules/holdToRecord`` records a voice message: let go/// and it goes, slid more than ``ComposerRules/slideAway`` first and it is/// thrown out (the round turns the danger colour). A screen reader, which/// cannot hold, has the hold as a named action: once to record, once more/// (or the plain double tap) to send.struct ComposerMic: View {    let symbol: String    let label: String    let identifier: String    let style: ComposerStyle    let recorder: (any ComposerRecorder)?    @Binding var away: Bool    let tap: () -> Void    @State private var down = false    @State private var held = false    @State private var waiting: Task<Void, Never>?    private var recording: Bool { recorder?.recording ?? false }    var body: some View {        Image(systemName: recording ? "mic.fill" : symbol)            .font(.system(size: 19, weight: recording ? .semibold : .regular))            .foregroundStyle(recording ? style.onAccent : style.ink)            .frame(width: 44, height: 44)            .background(Circle().fill(recording ? (away ? style.danger : style.accent) : Color.clear)                .scaleEffect(recording ? 1.2 + (recorder?.level ?? 0) * 0.3 : 1))            .contentShape(Circle())            .gesture(DragGesture(minimumDistance: 0)                .onChanged { value in                    if !down {                        down = true                        guard let recorder else { return }                        waiting = Task {                            try? await Task.sleep(for: ComposerRules.holdToRecord)                            guard !Task.isCancelled, down else { return }                            held = true                            await recorder.begin()                        }                    }                    if held { away = ComposerRules.slidAway(value.translation) }                }                .onEnded { _ in                    waiting?.cancel()                    waiting = nil                    down = false                    if held {                        held = false                        recorder?.end(cancelled: away)                    } else {                        tap()                    }                    away = false                })            .sensoryFeedback(.impact, trigger: recording)            .animation(.easeOut(duration: 0.15), value: recording)            .accessibilityElement()            .accessibilityLabel(Text(verbatim: label))            .accessibilityAddTraits(.isButton)            .accessibilityAction {                if let recorder, recording { recorder.end(cancelled: false) } else { tap() }            }            .modifier(HoldAction(recorder: recorder, recording: recording))            .accessibilityIdentifier(identifier)    }}/// The hold as a screen reader's named action ("Hold to record"): records, and again sends.private struct HoldAction: ViewModifier {    let recorder: (any ComposerRecorder)?    let recording: Bool    func body(content: Content) -> some View {        if let recorder {            content.accessibilityAction(named: Text(verbatim: recorder.holdLabel)) {                if recording { recorder.end(cancelled: false) } else { Task { await recorder.begin() } }            }        } else {            content        }    }}// MARK: - The waveform/// The voice's loudness, newest at the right, as bars that rise with it.struct ComposerWaveform: View {    let level: Double    let live: Bool    let colour: Color    let faint: Color    static let bars = 36    @State private var history: [Double] = []    var body: some View {        GeometryReader { box in            let count = Self.bars            let gap: CGFloat = 3            let width = max(1.5, (box.size.width - gap * CGFloat(count - 1)) / CGFloat(count))            let padded = Array(repeating: 0.0, count: max(0, count - history.count)) + history            HStack(alignment: .center, spacing: gap) {                ForEach(Array(padded.enumerated()), id: \.offset) { _, value in                    Capsule()                        .fill(live ? colour : faint)                        .frame(width: width, height: max(3, box.size.height * value))                }            }            .frame(width: box.size.width, height: box.size.height)        }        .onChange(of: level) { _, now in            // A whisper still shows: the level is lifted on a curve.            history = ComposerRules.waveform(history, adding: live ? pow(now, 0.6) : 0, count: Self.bars)        }        .animation(.linear(duration: 0.08), value: history)    }}