// A voice message in Comms: its player in the bubble, drawn from// assets/design/chat/voice-player.html (the owner's feedback, Comms build 23,// item 2: voice notes played but the player looked unfinished). Play and// pause in Comms' own glyphs, the core's 36 bars filling from the player's// real position, the length counting down what is left, one speed for every// note (1×, 1.5×, 2×: `chat.settings` voiceSpeed, the person's, synced), a// note of theirs not played until it has played a second (`chat.act played`,// never told to the sender), loading with nothing blank, and the core's words// when the file can't be fetched (Try again) or has gone. One note plays at a// time; each keeps its place for the sitting when another starts.//// Under the player, the words its sender's phone heard in it, so nobody has to// listen. The words are heard on the sending phone only, after the message// has gone (`chat.act transcript`), by the same on-device engine dictation// uses (`DictationModel.live(audio: .file)`: Apple's DictationTranscriber,// iOS 26). A phone with no on-device model for the language hears nothing,// and the voice message goes without words; audio is never sent anywhere to// be heard.#if os(iOS)import AVFoundationimportCottonKitimportSwiftUI/// The words in a recorded voice message, heard on this phone and nowhere else.@MainActorenumChatVoiceWords {/// The words heard in `file`, or nil: none heard, or this phone has no/// on-device model for the language. The recording plays into the engine/// at the pace it was spoken.staticfunc heard(in file: URL) async -> String? { #if COTTON_DEV// Chat Dev's invented recording says known words; `-chat-warm-voice-hear YES` hears it with the real engine.ifChatWarmSeed.asked, ChatWarmSeed.voice, !ChatWarmSeed.voiceHear { returnChatWarmSeed.voiceWords } #endifguardlet audio = try? AVAudioFile(forReading: file) else { returnnil }let seconds = Double(audio.length) / audio.processingFormat.sampleRatelet dictation = DictationModel.live(audio: .file(file))defer { dictation.release() }ifawait dictation.start(prefix: "", hints: DictationHints()) != nil { returnnil }// The language's model is fetched on first use.let deadline = ContinuousClock.now + .seconds(60)while dictation.phase == .starting, ContinuousClock.now < deadline {try? awaitTask.sleep(for: .milliseconds(100)) }guard dictation.phase == .listening else { returnnil }try? awaitTask.sleep(for: .seconds(seconds + 0.8))let words = await dictation.finish().text.trimmingCharacters(in: .whitespacesAndNewlines)return words.isEmpty ? nil : words }}/// A voice file's loudness as a waveform: the highest sample in each of/// `count` slices, 0…1. For a voice message that came with none (sent by an/// older phone, or imported): the core keeps it (`chat.waveform`) and works/// out the bars from it, as it does for every other.enumChatVoicePeaks {staticfunc of(_ url: URL, count: Int = 64) -> [Double]? {guardlet file = try? AVAudioFile(forReading: url), file.length >= AVAudioFramePosition(count) else { returnnil }let format = file.processingFormatlet total = Int(file.length), share = total / count, chunk: AVAudioFrameCount = 16_384guard share > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: chunk) else { returnnil }var peaks = [Double](repeating: 0, count: count)var at = 0// Read a piece at a time, so a long note never sits whole in memory.while at < total {guard (try? file.read(into: buffer, frameCount: chunk)) != nil, buffer.frameLength > 0, let channel = buffer.floatChannelData?[0] else { break }for i in stride(from: 0, to: Int(buffer.frameLength), by: 4) {let slice = min(count - 1, (at + i) / share) peaks[slice] = max(peaks[slice], Double(min(1, abs(channel[i])))) } at += Int(buffer.frameLength) }return peaks }}/// The player's own word that a note has played to its end, passed to the one player.finalclassChatVoiceEnding: NSObject, AVAudioPlayerDelegate {privatelet done: @MainActor (AVAudioPlayer) -> Voidinit(_ done: @escaping @MainActor (AVAudioPlayer) -> Void) { self.done = done }func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {let done = self.done nonisolated(unsafe) let player = playerTask { @MainActor in done(player) } }}/// Where one voice message stands.enumChatVoicePhase: Equatable {/// Not started: its length whole, no speed.case rest/// Tapped, its file not on the phone yet: the arc turns in the round.case loadingcase playing/// Paused part-way: its place kept for the sitting.case paused/// The file can't be fetched now: Try again, in the core's words.case offline(String)/// The file has gone, or won't play: nothing to tap, in the core's words.case gone(String)}/// The one voice message playing, from its file on this phone (`chat.file`),/// and every note's place for the sitting.@MainActor@ObservablefinalclassChatVoicePlayer {staticlet shared = ChatVoicePlayer()/// The message the player holds (playing, or paused part-way), and where in it, in seconds of the note's own time.private(set) var message: String?private(set) var playing = falseprivate(set) var position: TimeInterval = 0/// The note being fetched to play.private(set) var loading: String?/// One speed for every voice message (`chat.settings` voiceSpeed).private(set) var speed: Double = 1/// The other notes' places, kept for the sitting when another started.private(set) var places: [String: TimeInterval] = [:]/// Notes whose file can't be fetched now, or has gone / won't play, with the core's words.private(set) var offline: [String: String] = [:]private(set) var broken: [String: String] = [:]/// Notes of theirs played here this sitting: drawn played at once.private(set) var playedHere: Set<String> = []/// Each note's length as its file says, once opened.private(set) var lengths: [String: TimeInterval] = [:]staticlet speeds: [Double] = [1, 1.5, 2]/// A note becomes played once it has played this long (or to its end, when shorter).staticlet playedAfter: TimeInterval = 1 @ObservationIgnored privatevar player: AVAudioPlayer? @ObservationIgnored privatevar ticker: Task<Void, Never>? @ObservationIgnored privatevar fetch: Task<Void, Never>? @ObservationIgnored privatevar book: (any ChatBook)? @ObservationIgnored privatevar unplayed = false @ObservationIgnored privatevar onPlayed: (String) -> Void = { _ in } @ObservationIgnored privatevar observers: [any NSObjectProtocol] = []/// Told by the player itself when a note has played to its end: the only word that it has. @ObservationIgnored privatelazyvar ending = ChatVoiceEnding { [weakself] player inself?.ended(player) }privateinit() {let center = NotificationCenter.default// A call (an interruption) or the headphones coming out pauses, keeping the place. observers.append(center.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { [weakself] note inlet began = (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt).flatMap(AVAudioSession.InterruptionType.init) == .beganif began { MainActor.assumeIsolated { self?.pause() } } }) observers.append(center.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weakself] note inlet gone = (note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt).flatMap(AVAudioSession.RouteChangeReason.init) == .oldDeviceUnavailableif gone { MainActor.assumeIsolated { self?.pause() } } }) }/// The chat opened: the speed as the core keeps it.funcopen(_ book: any ChatBook) async {self.book = book speed = await book.voiceSpeed() }/// Where `message` stands now.func phase(_ message: String, part: ChatMediaPart?) -> ChatVoicePhase {iflet words = broken[message] { return .gone(words) }if part?.gone == true { return .gone(ShellLines.line("chat", "app.notice.file_gone")) }iflet words = offline[message] { return .offline(words) }if loading == message { return .loading }ifself.message == message { return playing ? .playing : .paused }if places[message] != nil { return .paused }return .rest }/// Where in `message` the place stands, in seconds.func place(_ message: String) -> TimeInterval {self.message == message ? position : places[message] ?? 0 }/// The note's whole length, in seconds: the core's, else its file's.func length(_ message: String, part: ChatMediaPart?) -> TimeInterval {iflet ms = part?.durationMs, ms > 0 { returnDouble(ms) / 1_000 }return lengths[message] ?? 0 }/// The round tapped: play from its place or the start, pause keeping it, stop a loading, or try again.func tap(_ bubble: ChatBubble, part: ChatMediaPart, book: (any ChatBook)?, played: @escaping (String) -> Void) {let id = bubble.messageswitch phase(id, part: part) {case .gone: returncase .loading: fetch?.cancel() fetch = nil loading = nilcase .playing: pause()case .paused where message == id:iflet player { resume(player) }case .rest, .paused, .offline: start(bubble, part: part, book: book ?? self.book, played: played) } }privatefunc start(_ bubble: ChatBubble, part: ChatMediaPart, book: (any ChatBook)?, played: @escaping (String) -> Void) {let id = bubble.messagelet from = places[id] ?? 0// Another note playing pauses where it stands, its place kept. hold() offline[id] = nilguardlet book else { return } loading = id fetch?.cancel() fetch = Task { [weakself] indo {let file = tryawait book.file(message: id, index: part.index)guard !Task.isCancelled, letself, self.loading == id else { return }self.loading = nillet url = URL(fileURLWithPath: file.path)guardlet player = try? AVAudioPlayer(contentsOf: url) else {self.broken[id] = ShellLines.line("chat", "app.voice.unplayable")return }// A note that came with no waveform gets one from this phone, kept by the core for every phone.if part.bars == nil, part.waveform?.isEmpty ?? true { Task.detached(priority: .utility) { awaitChatVoicePlayer.waveform(of: url, message: id, index: part.index, book: book) } } player.enableRate = true player.delegate = self.ending player.prepareToPlay()self.lengths[id] = player.durationtry? AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio)try? AVAudioSession.sharedInstance().setActive(true)self.player = playerself.message = idself.unplayed = !bubble.mine && part.played == false && !self.playedHere.contains(id)self.onPlayed = played player.currentTime = min(from, max(0, player.duration - 0.05))self.position = player.currentTimeself.places[id] = nilself.resume(player) } catchlet refusal asCottonCallError {guardletself, self.loading == id else { return }self.loading = nilif refusal.code == "file_gone" { self.broken[id] = refusal.message } else { self.offline[id] = refusal.message } } catch {guardletself, self.loading == id, !Task.isCancelled else { return }self.loading = nilself.offline[id] = ShellLines.line("chat", "app.notice.file_offline") } } }privatefunc resume(_ player: AVAudioPlayer) { player.rate = Float(speed)try? AVAudioSession.sharedInstance().setActive(true)guard player.play() || (player.prepareToPlay() && player.play()) else {// No silent failure: a note that will not play says so, in the core's words.iflet message { broken[message] = ShellLines.line("chat", "app.voice.unplayable") }return release() } playing = true ticker?.cancel() ticker = Task { [weakself] invar stalled = 0while !Task.isCancelled {try? awaitTask.sleep(for: .milliseconds(50))guardletself, let player = self.player else { return }// Not playing for a moment is not its end (Comms 26, B5: a seek dropped the note back to its start). A// player sets `isPlaying` false for a moment as its place is moved; only the player's own word that it// finished ends the note (`ended`). One that stays still part-way while it should play is asked again.if !player.isPlaying, self.playing, player.currentTime < player.duration - 0.1 { stalled += 1if stalled >= 6 { stalled = 0; player.play() } } else { stalled = 0 }self.position = player.currentTimeifself.unplayed, player.currentTime >= Self.playedAfter { self.markPlayed() } } } }/// The player says its note played to its end: back to the start, the length whole again.privatefunc ended(_ finished: AVAudioPlayer) {guard finished === player, playing else { return }if unplayed { markPlayed() } finish() }privatefunc markPlayed() {guard unplayed, let message else { return } unplayed = false playedHere.insert(message) onPlayed(message) }/// Paused where it stands.func pause() {guardlet player, playing else { return } player.pause() position = player.currentTime playing = false ticker?.cancel() }/// The note playing paused and set down, its place kept for the sitting.privatefunc hold() {guardlet player, let message else { return } player.pause()let at = player.currentTimeif at > 0, at < player.duration { places[message] = at } release() }/// Played to its end: at its start again.privatefunc finish() {iflet message { places[message] = nil } release() }privatefunc release() { ticker?.cancel() ticker = nil player?.stop() player = nil message = nil playing = false position = 0try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) }/// The chat left: the note stops, and the places kept for the sitting go.func stop() { fetch?.cancel() fetch = nil loading = nil release() places = [:] offline = [:] }/// The place moved, by a drag or a tap on the bars, or VoiceOver's swipe: playing or paused.func seek(_ message: String, to at: TimeInterval, length: TimeInterval) {let at = max(0, min(at, max(0, length - 0.05)))ifself.message == message, let player { player.currentTime = at position = at #if COTTON_DEV// `-chat-voice-seek-stalls YES`: the player stands still a moment after each move of its place, as a// phone's does, so a test can see that a seek never ends the note.if playing, UserDefaults.standard.bool(forKey: "chat-voice-seek-stalls") { player.pause()Task { [weakself] intry? awaitTask.sleep(for: .milliseconds(400))ifletself, self.playing, self.player === player { player.play() } } } #endif } elseif places[message] != nil { places[message] = at } }/// The pill tapped: the next speed, round again; the note keeps playing from where it was.func nextSpeed() {let at = Self.speeds.firstIndex(of: speed) ?? 0 speed = Self.speeds[(at + 1) % Self.speeds.count] player?.rate = Float(speed)let chosen = speediflet book { Task { await book.setVoiceSpeed(chosen) } } } nonisolated staticfunc waveform(of url: URL, message: String, index: Int, book: any ChatBook) async {guardlet peaks = ChatVoicePeaks.of(url) else { return }await book.setWaveforms([ChatWaveformMade(message: message, index: index, waveform: peaks)]) }}// MARK: words/// The player's words, every one a kit line (`app.voice.*`).enumChatVoiceSaid {staticfunc line(_ key: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("chat", "app.voice.\(key)", fills) }/// `m:ss`, minutes not padded, as the core writes a length; rounded up, so 0:00 only at the end.staticfunc time(_ seconds: TimeInterval) -> String {let whole = max(0, Int(seconds.rounded(.up)))let tens = (whole % 60) / 10, ones = whole % 10return"\(whole / 60):\(tens)\(ones)" }staticfunc speed(_ n: Double) -> String { n == n.rounded() ? String(Int(n)) : String(n) }}// MARK: the glyphs, in Comms' own line (no borrowed icon set)privatestructVoicePlayGlyph: Shape {func path(in rect: CGRect) -> Path {let s = rect.width / 24var p = Path() p.move(to: CGPoint(x: 9 * s, y: 6.6 * s)) p.addLine(to: CGPoint(x: 9 * s, y: 17.4 * s)) p.addQuadCurve(to: CGPoint(x: 10.6 * s, y: 18.25 * s), control: CGPoint(x: 9 * s, y: 18.9 * s)) p.addLine(to: CGPoint(x: 18.9 * s, y: 12.85 * s)) p.addQuadCurve(to: CGPoint(x: 18.9 * s, y: 11.15 * s), control: CGPoint(x: 19.7 * s, y: 12 * s)) p.addLine(to: CGPoint(x: 10.6 * s, y: 5.75 * s)) p.addQuadCurve(to: CGPoint(x: 9 * s, y: 6.6 * s), control: CGPoint(x: 9 * s, y: 5.1 * s)) p.closeSubpath()return p }}privatestructVoicePauseGlyph: Shape {func path(in rect: CGRect) -> Path {let s = rect.width / 24var p = Path() p.addRoundedRect(in: CGRect(x: 6.6 * s, y: 5.8 * s, width: 3.8 * s, height: 12.4 * s), cornerSize: CGSize(width: 1.5 * s, height: 1.5 * s)) p.addRoundedRect(in: CGRect(x: 13.6 * s, y: 5.8 * s, width: 3.8 * s, height: 12.4 * s), cornerSize: CGSize(width: 1.5 * s, height: 1.5 * s))return p }}privatestructVoiceRetryGlyph: Shape {func path(in rect: CGRect) -> Path {let s = rect.width / 24var p = Path() p.addArc(center: CGPoint(x: 11.95 * s, y: 12.3 * s), radius: 6.5 * s, startAngle: .degrees(3), endAngle: .degrees(-38), clockwise: false) p.move(to: CGPoint(x: 17.2 * s, y: 4.4 * s)) p.addLine(to: CGPoint(x: 17.2 * s, y: 7.9 * s)) p.addLine(to: CGPoint(x: 13.7 * s, y: 7.9 * s))return p.strokedPath(StrokeStyle(lineWidth: 2 * s, lineCap: .round, lineJoin: .round)) }}/// The loading arc: one turn a second, still under Reduce Motion.privatestructVoiceLoadingArc: View {let colour: Color @Environment(\.accessibilityReduceMotion) privatevar still @State privatevar turned = falsevar body: someView {Circle() .trim(from: 0, to: 0.25) .stroke(colour, style: StrokeStyle(lineWidth: 2.2, lineCap: .round)) .frame(width: 22, height: 22) .rotationEffect(.degrees(turned ? 360 : 0)) .frame(width: 26, height: 26) .onAppear {guard !still else { return } withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) { turned = true } } }}// MARK: the player/// A voice message: the round, the 36 bars (or the thin track), the length/// and, while it has started, the speed; under it the words its sender's/// phone heard in it, or the core's words when its file can't be had.structChatVoiceView: View {let bubble: ChatBubblelet ink: Colorlet dim: Color/// A note of theirs has played a second: the thread asks `chat.act played` and draws the bubble answered.var played: (String) -> Void = { _ in } @Environment(\.chatLook) privatevar look @Environment(\.chatBook) privatevar book @Environment(\.dynamicTypeSize) privatevar typeSize @Environment(\.colorScheme) privatevar schemeprivatevar player: ChatVoicePlayer { .shared }/// Posted with the message's id when the player's height changes in place: the thread measures its row again.staticlet resized = Notification.Name("chat.voice.resized")staticlet round: CGFloat = 40staticlet gap: CGFloat = 10staticlet bars = 36staticlet row: CGFloat = 28/// The drawn player's width at the default sizes: 40 + 10 + 178.staticlet width: CGFloat = 228privatevar part: ChatMediaPart? { bubble.media.first { $0.kind == .voice || $0.kind == .audio } ?? bubble.media.first }privatevar big: Bool { typeSize.isAccessibilitySize }privatevar mine: Bool { bubble.mine }privatevar c: ChatColours { look.colours }privatevar mineInk: Color { c.bubbleOutText }privatevar unplayed: Bool { !mine && part?.played == false && !player.playedHere.contains(bubble.message) }var body: someView {let id = bubble.messagelet phase = player.phase(id, part: part)let length = player.length(id, part: part)let at = player.place(id)let started = phase == .playing || phase == .paused VStack(alignment: .leading, spacing: 4) { HStack(alignment: .top, spacing: Self.gap) { roundButton(phase: phase, length: length, at: at) VStack(alignment: .leading, spacing: 1) {BarsView(part: part, progress: started && length > 0 ? at / length : 0, started: started, mine: mine, gone: isGone(phase), big: big, heard: mine ? mineInk : c.text, unheard: mine ? mineInk.opacity(scheme == .dark ? 0.30 : 0.28) : c.faint) { fraction inguard started, length > 0else { return } player.seek(id, to: fraction * length, length: length) } .padding(.top, 6) .accessibilityElement() .accessibilityLabel(Text(verbatim: ChatVoiceSaid.line("position"))) .accessibilityValue(Text(verbatim: ChatVoiceSaid.line("position_value", ["at": ChatVoiceSaid.time(at), "length": ChatVoiceSaid.time(length)]))) .accessibilityAdjustableAction { direction inlet step: TimeInterval = direction == .increment ? 5 : -5 player.seek(id, to: at + step, length: length) } .accessibilityIdentifier("chat-voice-position-\(id)")// Read only once the note has started: at rest the bars are not read. .accessibilityHidden(!started) foot(phase: phase, length: length, at: at, started: started) } .frame(maxWidth: big ? .infinity : 178, alignment: .leading) } under(phase: phase) } .frame(maxWidth: big ? .infinity : Self.width, alignment: .leading) .onChange(of: Self.shape(phase, started: started, big: big)) {NotificationCenter.default.post(name: Self.resized, object: id) } }/// What decides the player's height: the words under it, and at the largest text the speed's own line.privatestaticfunc shape(_ phase: ChatVoicePhase, started: Bool, big: Bool) -> Int {let under: Intswitch phase {case .offline: under = 1case .gone: under = 2default: under = 0 }return under * 2 + (big && started ? 1 : 0) }privatefunc isGone(_ phase: ChatVoicePhase) -> Bool {ifcase .gone = phase { returntrue }returnfalse }// The round: play, pause, loading, try again, or faint when gone. Drawn at 40, met at 44. @ViewBuilder privatefunc roundButton(phase: ChatVoicePhase, length: TimeInterval, at: TimeInterval) -> someView {let id = bubble.messagelet (fill, glyph) = roundColours(phase)Button {guardlet part else { return } player.tap(bubble, part: part, book: book, played: played) } label: { ZStack {Circle().fill(fill)switch phase {case .playing:VoicePauseGlyph().fill(glyph).frame(width: 18, height: 18)case .loading:VoiceLoadingArc(colour: glyph)case .offline:VoiceRetryGlyph().fill(glyph).frame(width: 18, height: 18)default:VoicePlayGlyph().fill(glyph).overlay(VoicePlayGlyph().stroke(glyph, style: StrokeStyle(lineWidth: 1.2, lineJoin: .round))).frame(width: 18, height: 18) } } .frame(width: Self.round, height: Self.round) .padding(2) .contentShape(Rectangle()) } .buttonStyle(.plain) .padding(-2) .disabled(isGone(phase)) .accessibilityLabel(Text(verbatim: roundSaid(phase))) .accessibilityValue(Text(verbatim: roundValue(phase, length: length, at: at))) .accessibilityIdentifier("chat-voice-play-\(id)") }privatefunc roundColours(_ phase: ChatVoicePhase) -> (Color, Color) {switch phase {case .gone: return (c.bar, c.faint)case .offline: return mine ? (mineInk.opacity(0.10), mineInk) : (c.bar, c.text)default:if mine { return (mineInk, c.bubbleOut) }return unplayed ? (c.accent, c.onAccent) : (c.text, c.ground) } }privatefunc roundSaid(_ phase: ChatVoicePhase) -> String {switch phase {case .playing: ChatVoiceSaid.line("pause")case .loading: ChatVoiceSaid.line("loading")case .offline: ChatWords.line("thread.retry")case .gone: ChatVoiceSaid.line("gone")case .rest, .paused: ChatVoiceSaid.line("play") } }privatefunc roundValue(_ phase: ChatVoicePhase, length: TimeInterval, at: TimeInterval) -> String {switch phase {case .playing, .paused: returnChatVoiceSaid.line("left", ["time": ChatVoiceSaid.time(length - at)])case .offline(let words): return wordscase .gone, .loading: return""case .rest:let whole = part?.length ?? ChatVoiceSaid.time(length)return unplayed ? [whole, ChatVoiceSaid.line("not_played")].joined(separator: ", ") : whole } }// The foot line: the length (counting down once started), the not-played dot, the speed at the right. @ViewBuilder privatefunc foot(phase: ChatVoicePhase, length: TimeInterval, at: TimeInterval, started: Bool) -> someView {let id = bubble.messagelet shown = started ? ChatVoiceSaid.time(length - at) : (part?.length ?? ChatVoiceSaid.time(length))let lengthText = HStack(spacing: 6) {Text(verbatim: shown) .font(look.font(12.5)) .monospacedDigit() .foregroundStyle(mine ? mineInk.opacity(0.72) : c.dim) .fixedSize()if unplayed, !started, !isGone(phase) {Circle().fill(c.accent).frame(width: big ? 12 : 7, height: big ? 12 : 7) } } .accessibilityIdentifier("chat-voice-length-\(id)") .accessibilityHidden(true)let pill = Button { player.nextSpeed() } label: {Text(verbatim: ChatVoiceSaid.line("speed_short", ["n": ChatVoiceSaid.speed(player.speed)])) .font(look.font(13, .semibold)) .monospacedDigit() .foregroundStyle(mine ? mineInk : c.text) .padding(.vertical, 5) .padding(.horizontal, 8) .background(Capsule().fill(mine ? mineInk.opacity(0.10) : c.bar)) .frame(minWidth: 44, minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(.plain) .padding(.vertical, -10) .accessibilityLabel(Text(verbatim: ChatVoiceSaid.line("speed"))) .accessibilityValue(Text(verbatim: ChatVoiceSaid.line("speed_value", ["n": ChatVoiceSaid.speed(player.speed)]))) .accessibilityIdentifier("chat-voice-speed-\(id)")if big {// At the largest text the length and the speed wrap onto their own lines rather than squeeze. VStack(alignment: .leading, spacing: 6) { lengthTextif started { pill.padding(.vertical, 10) } } .frame(minHeight: 44, alignment: .leading) } else { HStack(spacing: 0) { lengthTextSpacer(minLength: 6)if started { pill } } .frame(minHeight: 24) } }// Under the player: the core's words when its file can't be had, else the words heard in it. @ViewBuilder privatefunc under(phase: ChatVoicePhase) -> someView {let id = bubble.messagelet wide: CGFloat? = big ? nil : Self.widthswitch phase {case .offline(let words):Button {guardlet part else { return } player.tap(bubble, part: part, book: book, played: played) } label: { (Text(verbatim: words).foregroundStyle(mine ? mineInk : c.danger) + Text(verbatim: " ") + Text(verbatim: ChatWords.line("thread.retry")).fontWeight(.semibold).foregroundStyle(mine ? mineInk : c.text)) .font(look.font(14.5)) .multilineTextAlignment(.leading) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: wide, alignment: .leading) .frame(minHeight: 44, alignment: .topLeading) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: ChatWords.line("thread.retry"))) .accessibilityValue(Text(verbatim: words)) .accessibilityIdentifier("chat-voice-retry-\(id)")case .gone(let words):Text(verbatim: words) .font(look.font(14.5)) .foregroundStyle(mine ? mineInk.opacity(0.75) : c.dim) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: wide, alignment: .leading) .accessibilityIdentifier("chat-voice-gone-\(id)")default:iflet words = part?.transcript, !words.isEmpty {Text(verbatim: words) .font(look.font(14.5)) .foregroundStyle(mine ? mineInk.opacity(0.75) : c.dim) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: wide, alignment: .leading)// The words land in a bubble already drawn: they stand at once, never faded in. .transition(.identity)// Said with the bubble (WarmSpoken), as they stand under the player. .accessibilityIdentifier("chat-voice-transcript-\(id)") .accessibilityHidden(true) } } }}/// The 36 bars the core answered, filling from the place; a note with none draws the thin track./// A drag along them (or a tap) moves the place; their target is 44 tall.privatestructBarsView: View {let part: ChatMediaPart?let progress: Doublelet started: Boollet mine: Boollet gone: Boollet big: Boollet heard: Colorlet unheard: Colorlet moved: (Double) -> Void/// This touch, once it has gone a few points: along the bars (it moves the place) or up the chat (it scrolls, and/// the place stays where it was). @State privatevar sideways: Bool?var body: someView {GeometryReader { box inlet width = box.size.widthGroup {iflet bars = part?.bars, !bars.isEmpty {let gap: CGFloat = big ? 1.5 : 2let bar: CGFloat = big ? max(2, (width - gap * CGFloat(bars.count - 1)) / CGFloat(bars.count)) : 3 HStack(alignment: .center, spacing: gap) {ForEach(Array(bars.enumerated()), id: \.offset) { i, h inCapsule() .fill(progress > 0 && Double(i) / Double(bars.count) < progress ? heard : unheard) .frame(width: big ? min(bar, 2) : bar, height: 3 + 21 * max(0, min(1, h))) } } .opacity(gone ? 0.55 : 1) .frame(width: width, height: ChatVoiceView.row, alignment: .leading) } else { ZStack(alignment: .leading) {Capsule().fill(unheard).frame(height: 4)Capsule().fill(heard).frame(width: width * progress, height: 4)if started {Circle().fill(heard).frame(width: 10, height: 10).offset(x: max(0, width * progress - 5)) } } .frame(width: width, height: ChatVoiceView.row) } } .overlay {Color.clear .frame(width: width, height: 44) .contentShape(Rectangle())// A tap sets the place; a drag along the bars moves it. A drag that starts up or down is the// chat scrolling past, and leaves the place alone. .onTapGesture(coordinateSpace: .local) { point inguard started, width > 0else { return } moved(max(0, min(1, point.x / width))) } .simultaneousGesture(DragGesture(minimumDistance: 6).onChanged { drag inguard started, width > 0else { return }if sideways == nil { sideways = abs(drag.translation.width) > abs(drag.translation.height) }guard sideways == trueelse { return } moved(max(0, min(1, drag.location.x / width))) }.onEnded { _ in sideways = nil }) .allowsHitTesting(started) } } .frame(width: big ? nil : 178, height: ChatVoiceView.row) .frame(maxWidth: big ? .infinity : 178, alignment: .leading) }}#endif