Repository Public
1// SP Notes iOS2// File: Features/Voice/VoiceNoteScreen.swift3// Description: The full screen of a voice note (`audio` block): player with scrubber and speed, transcript whose lines seek the4// player, transcription on the device or on the server (paid, confirmed), the AI summary in violet inserted only5// on request, title, and keeping or deleting the original audio. Registered as the block detail of `audio` nodes.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SPNotesDesign11import SwiftUI1213/// The block detail provider of voice notes. `.platform` priority: this screen wins over the editor's minimal audio sheet.14@MainActor15struct VoiceBlockDetails: BlockDetailProviding {16 func canPresent(_ node: PMNode) -> Bool { node.type == AudioBlock.nodeType }17 func style(for node: PMNode) -> BlockDetailStyle { .sheet }18 func view(for node: PMNode, context: BlockDetailContext) -> AnyView { AnyView(VoiceNoteScreen(node: node, context: context)) }19}2021struct VoiceNoteScreen: View {22 @State private var model: VoiceNoteModel23 private let dismiss: () -> Void24 @State private var title: String25 @State private var confirmsDeleteAudio = false26 @State private var confirmsDeleteBlock = false27 @Environment(\.accessibilityReduceMotion) private var reduceMotion2829 init(node: PMNode, context: BlockDetailContext) {30 let model = VoiceNoteModel(node: node, context: context)31 _model = State(initialValue: model)32 _title = State(initialValue: model.title)33 dismiss = context.dismiss34 }3536 init(model: VoiceNoteModel, dismiss: @escaping () -> Void) {37 _model = State(initialValue: model)38 _title = State(initialValue: model.title)39 self.dismiss = dismiss40 }4142 var body: some View {43 NavigationStack {44 ScrollViewReader { proxy in45 ScrollView {46 VStack(alignment: .leading, spacing: NVSpace.xl) {47 header48 player49 stateBanner50 transcriptSection51 summarySection52 }53 .padding(NVSpace.lg)54 .frame(maxWidth: NVSpace.readingMeasure)55 .frame(maxWidth: .infinity)56 }57 .onChange(of: model.currentSegment) { _, index in58 guard let index, model.isPlaying else { return }59 withNVAnimation(.base, reduceMotion: reduceMotion) { proxy.scrollTo("segment-\(index)", anchor: .center) }60 }61 }62 .background(NVColor.bg)63 .navigationTitle("Note vocale")64 .navigationBarTitleDisplayMode(.inline)65 .toolbar {66 ToolbarItem(placement: .cancellationAction) {67 Button("Fermer") { commitTitle(); model.cancelWork(); dismiss() }.accessibilityIdentifier("voice-close")68 }69 if model.isEditable {70 ToolbarItem(placement: .primaryAction) {71 Menu {72 if model.hasAudio, !model.transcript.isEmpty {73 Button(role: .destructive) { confirmsDeleteAudio = true } label: { Label("Supprimer l’audio original", systemImage: "waveform.slash") }74 }75 Button(role: .destructive) { confirmsDeleteBlock = true } label: { Label("Supprimer la note vocale", systemImage: "trash") }76 } label: { Image(systemName: "ellipsis.circle") }77 .accessibilityLabel(Text("Plus d’actions"))78 .accessibilityIdentifier("voice-more")79 }80 }81 }82 .confirmationDialog("Supprimer l’audio original ?", isPresented: $confirmsDeleteAudio, titleVisibility: .visible) {83 Button("Supprimer l’audio, garder la transcription", role: .destructive) { Task { await model.deleteOriginalAudio() } }84 Button("Garder l’audio", role: .cancel) {}85 } message: { Text("L’enregistrement sera supprimé de cet appareil et du serveur. La transcription reste dans la note.") }86 .confirmationDialog("Supprimer cette note vocale ?", isPresented: $confirmsDeleteBlock, titleVisibility: .visible) {87 Button("Supprimer l’audio et la transcription", role: .destructive) { Task { await model.deleteBlock(); dismiss() } }88 Button("Annuler", role: .cancel) {}89 }90 .confirmationDialog("Transcrire sur le serveur ?", isPresented: paidBinding, titleVisibility: .visible) {91 Button("Transcrire") { model.confirmServerTranscription(summarize: false) }92 Button("Transcrire et résumer (IA)") { model.confirmServerTranscription(summarize: true) }93 Button("Annuler", role: .cancel) { model.cancelServerTranscription() }94 } message: {95 Text("C’est un appel payant : l’audio est envoyé au serveur SP Notes, puis au moteur de transcription du fournisseur d’IA. Le résumé est un second appel payant.")96 }97 .task { await model.load() }98 .onDisappear { model.stopPlayback() }99 }100 }101102 private var paidBinding: Binding<Bool> {103 Binding(get: { model.transcription == .confirmingPaid }, set: { if !$0 { model.cancelServerTranscription() } })104 }105106 private func commitTitle() { model.rename(title) }107108 // MARK: header109110 private var header: some View {111 VStack(alignment: .leading, spacing: NVSpace.xs) {112 TextField("Titre de la note vocale", text: $title, axis: .vertical)113 .nvFont(.h2)114 .foregroundStyle(NVColor.fg)115 .disabled(!model.isEditable)116 .submitLabel(.done)117 .onSubmit(commitTitle)118 .accessibilityIdentifier("voice-note-title")119 HStack(spacing: NVSpace.sm) {120 if let date = model.recordedAt { Text(date.formatted(date: .abbreviated, time: .shortened)) }121 if model.duration > 0 { Text("·").accessibilityHidden(true); Text(VoiceNoteIO.timecode(model.duration)).monospacedDigit() }122 }123 .nvFont(.ui)124 .foregroundStyle(NVColor.fgMuted)125 }126 }127128 // MARK: player129130 @ViewBuilder private var player: some View {131 switch model.audioState {132 case .removed:133 Label("L’audio original a été supprimé. La transcription est conservée.", systemImage: "waveform.slash")134 .nvFont(.ui).foregroundStyle(NVColor.fgMuted)135 .padding(NVSpace.lg).frame(maxWidth: .infinity, alignment: .leading).nvCard()136 .accessibilityIdentifier("voice-audio-removed")137 case .missing:138 Label("L’enregistrement n’est pas sur cet appareil et n’a pas pu être téléchargé.", systemImage: "icloud.slash")139 .nvFont(.ui).foregroundStyle(NVColor.fgMuted)140 .padding(NVSpace.lg).frame(maxWidth: .infinity, alignment: .leading).nvCard()141 .accessibilityIdentifier("voice-audio-missing")142 case .loading, .ready:143 VStack(spacing: NVSpace.md) {144 Slider(value: Binding(get: { min(model.position, max(model.duration, 0.01)) }, set: { model.seek(to: $0) }), in: 0...max(model.duration, 0.01))145 .tint(NVColor.accent)146 .disabled(model.audioState != .ready)147 .accessibilityLabel(Text("Position de lecture"))148 .accessibilityValue(Text(VoiceNoteIO.timecode(model.position)))149 .accessibilityIdentifier("voice-scrubber")150 HStack {151 Text(VoiceNoteIO.timecode(model.position)).accessibilityIdentifier("voice-position")152 Spacer()153 Text(VoiceNoteIO.timecode(model.duration))154 }155 .nvFont(.micro).monospacedDigit().foregroundStyle(NVColor.fgMuted)156 ViewThatFits(in: .horizontal) {157 HStack(spacing: NVSpace.xl) { controls }158 VStack(spacing: NVSpace.md) { controls }159 }160 }161 .padding(NVSpace.lg)162 .nvCard()163 }164 }165166 @ViewBuilder private var controls: some View {167 Button { model.seek(to: model.position - 15) } label: { Image(systemName: "gobackward.15").font(.title2).frame(minWidth: 44, minHeight: 44) }168 .accessibilityLabel(Text("Reculer de 15 secondes"))169 Button { Haptics.tap(); model.togglePlayback() } label: {170 Image(systemName: model.isPlaying ? "pause.fill" : "play.fill").font(.title)171 .foregroundStyle(NVColor.accentFg).frame(width: 64, height: 64).background(NVColor.accent, in: Circle())172 }173 .disabled(model.audioState != .ready)174 .accessibilityLabel(Text(model.isPlaying ? "Pause" : "Lire"))175 .accessibilityIdentifier("voice-play")176 Button { model.seek(to: model.position + 15) } label: { Image(systemName: "goforward.15").font(.title2).frame(minWidth: 44, minHeight: 44) }177 .accessibilityLabel(Text("Avancer de 15 secondes"))178 Button { Haptics.selection(); model.cycleSpeed() } label: {179 Text(Self.speedLabel(model.speed)).nvFont(.uiStrong).monospacedDigit()180 .padding(.horizontal, NVSpace.md).frame(minHeight: 44).background(NVColor.bgSunken, in: Capsule())181 }182 .accessibilityLabel(Text("Vitesse de lecture"))183 .accessibilityValue(Text(Self.speedLabel(model.speed)))184 .accessibilityIdentifier("voice-speed")185 }186187 static func speedLabel(_ speed: Float) -> String { speed.formatted(.number.precision(.fractionLength(0...2))) + "×" }188189 // MARK: states190191 @ViewBuilder private var stateBanner: some View {192 switch model.transcription {193 case .idle, .confirmingPaid: EmptyView()194 case .runningOnDevice: progress(String(localized: "Transcription sur l’appareil en cours…"))195 case .runningOnServer: progress(String(localized: "Transcription par le serveur en cours…"))196 case .failed(let message): notice(message, symbol: "exclamationmark.triangle.fill", id: "voice-state-failed")197 case .unsupported: notice(String(localized: "Ce serveur ne propose pas encore la transcription des notes vocales."), symbol: "server.rack", id: "voice-state-unsupported")198 case .offline: notice(String(localized: "Hors ligne : la transcription par le serveur a besoin du réseau, et l’enregistrement doit d’abord être synchronisé."), symbol: "wifi.slash", id: "voice-state-offline")199 case .unavailableOnDevice(let language):200 notice(String(localized: "La transcription sur l’appareil n’est pas disponible pour cette langue sur cet appareil (\(language))."), symbol: "character.bubble", id: "voice-state-unavailable")201 }202 }203204 private func progress(_ text: String) -> some View {205 HStack(spacing: NVSpace.md) {206 ProgressView()207 Text(text).nvFont(.ui).foregroundStyle(NVColor.fg)208 Spacer(minLength: 0)209 }210 .padding(NVSpace.lg).nvCard()211 .accessibilityIdentifier("voice-state-running")212 }213214 private func notice(_ text: String, symbol: String, id: String) -> some View {215 HStack(alignment: .top, spacing: NVSpace.md) {216 Image(systemName: symbol).foregroundStyle(NVColor.warning).accessibilityHidden(true)217 Text(text).nvFont(.ui).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)218 Spacer(minLength: 0)219 Button { model.dismissTranscriptionState() } label: { Image(systemName: "xmark").frame(minWidth: 44, minHeight: 44) }220 .accessibilityLabel(Text("Fermer le message"))221 }222 .padding(.leading, NVSpace.lg).padding(.vertical, NVSpace.sm).nvCard()223 .accessibilityIdentifier(id)224 }225226 // MARK: transcript227228 @ViewBuilder private var transcriptSection: some View {229 VStack(alignment: .leading, spacing: NVSpace.md) {230 NVSectionHeader(String(localized: "Transcription"), subtitle: model.transcript.isEmpty ? nil : model.engineLabel)231 if model.transcript.isEmpty {232 Text("Aucune transcription pour l’instant.")233 .nvFont(.ui).foregroundStyle(NVColor.fgMuted)234 if model.isEditable, model.hasAudio { transcribeActions }235 } else {236 VStack(alignment: .leading, spacing: NVSpace.xxs) {237 ForEach(Array(model.transcript.enumerated()), id: \.offset) { index, segment in238 Button { Haptics.selection(); model.seek(toSegment: index) } label: {239 HStack(alignment: .firstTextBaseline, spacing: NVSpace.md) {240 Text(segment.timecode).nvFont(.code).foregroundStyle(NVColor.accent).monospacedDigit()241 Text(segment.text).nvFont(.reading).foregroundStyle(NVColor.fg)242 .multilineTextAlignment(.leading).fixedSize(horizontal: false, vertical: true)243 Spacer(minLength: 0)244 }245 .padding(.vertical, NVSpace.sm).padding(.horizontal, NVSpace.md)246 .background(model.currentSegment == index ? NVColor.accentSoft : .clear, in: NVRadius.shape(NVRadius.md))247 .contentShape(Rectangle())248 }249 .buttonStyle(.plain)250 .disabled(!model.hasAudio || model.audioState != .ready)251 .id("segment-\(index)")252 .accessibilityLabel(Text("\(segment.timecode), \(segment.text)"))253 .accessibilityHint(Text("Lit l’enregistrement à partir de ce passage"))254 .accessibilityAddTraits(model.currentSegment == index ? .isSelected : [])255 .accessibilityIdentifier("voice-segment-\(index)")256 }257 }258 if model.isEditable, model.hasAudio, model.summary == nil, !model.isBusy {259 Button { model.requestServerTranscription() } label: { Label("Résumer avec l’IA du serveur…", systemImage: "sparkles") }260 .nvFont(.ui).tint(NVColor.ai)261 .accessibilityIdentifier("voice-summarize")262 }263 }264 }265 }266267 private var transcribeActions: some View {268 VStack(alignment: .leading, spacing: NVSpace.md) {269 Button { model.transcribeOnDevice() } label: {270 actionLabel(String(localized: "Transcrire sur l’appareil"), detail: String(localized: "Gratuit et privé : rien ne quitte cet appareil."), symbol: "iphone")271 }272 .buttonStyle(.plain).disabled(model.isBusy || model.audioState != .ready)273 .accessibilityIdentifier("voice-transcribe-device")274 Button { model.requestServerTranscription() } label: {275 actionLabel(String(localized: "Transcrire sur le serveur…"), detail: String(localized: "Appel payant, plus précis ; peut aussi produire un résumé par l’IA."), symbol: "server.rack")276 }277 .buttonStyle(.plain).disabled(model.isBusy)278 .accessibilityIdentifier("voice-transcribe-server")279 }280 }281282 private func actionLabel(_ title: String, detail: String, symbol: String) -> some View {283 HStack(spacing: NVSpace.md) {284 Image(systemName: symbol).font(.title3).foregroundStyle(NVColor.accent).frame(width: 32).accessibilityHidden(true)285 VStack(alignment: .leading, spacing: NVSpace.xxs) {286 Text(title).nvFont(.uiStrong).foregroundStyle(NVColor.fg)287 Text(detail).nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)288 }289 Spacer(minLength: 0)290 Image(systemName: "chevron.right").font(.footnote).foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)291 }292 .padding(NVSpace.lg).frame(minHeight: 44).nvCard().contentShape(Rectangle())293 }294295 // MARK: AI summary296297 @ViewBuilder private var summarySection: some View {298 if let summary = model.summary {299 VStack(alignment: .leading, spacing: NVSpace.md) {300 NVAIBadge(model: summary.model)301 Text(summary.text).nvFont(.reading).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)302 if !summary.decisions.isEmpty { list(String(localized: "Décisions"), items: summary.decisions, symbol: "checkmark.seal") }303 if !summary.tasks.isEmpty { list(String(localized: "Tâches"), items: summary.tasks, symbol: "circle") }304 if model.isEditable {305 ViewThatFits(in: .horizontal) {306 HStack(spacing: NVSpace.md) { summaryActions(summary) }307 VStack(alignment: .leading, spacing: NVSpace.sm) { summaryActions(summary) }308 }309 Text("Rien n’est ajouté à la note sans ton action.").nvFont(.micro).foregroundStyle(NVColor.fgMuted)310 }311 }312 .padding(NVSpace.lg)313 .frame(maxWidth: .infinity, alignment: .leading)314 .background(NVColor.aiSoft, in: NVRadius.shape(NVRadius.lg))315 .overlay { NVRadius.shape(NVRadius.lg).strokeBorder(NVColor.ai.opacity(0.35), lineWidth: 1) }316 .accessibilityElement(children: .contain)317 .accessibilityIdentifier("voice-summary")318 }319 }320321 @ViewBuilder private func summaryActions(_ summary: AudioSummary) -> some View {322 Button { Haptics.success(); model.insertSummary() } label: {323 Label(model.insertedSummary ? "Résumé inséré" : "Insérer le résumé", systemImage: model.insertedSummary ? "checkmark" : "text.insert")324 }325 .buttonStyle(.borderedProminent).tint(NVColor.ai)326 .accessibilityIdentifier("voice-insert-summary")327 if !summary.tasks.isEmpty {328 Button { Haptics.success(); model.createTasks() } label: {329 Label(model.insertedTasks ? "Tâches créées" : "Créer les tâches", systemImage: model.insertedTasks ? "checkmark" : "checklist")330 }331 .buttonStyle(.bordered).tint(NVColor.ai)332 .accessibilityIdentifier("voice-create-tasks")333 }334 }335336 private func list(_ title: String, items: [String], symbol: String) -> some View {337 VStack(alignment: .leading, spacing: NVSpace.xs) {338 Text(title).nvFont(.uiStrong).foregroundStyle(NVColor.ai)339 ForEach(Array(items.enumerated()), id: \.offset) { _, item in340 HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {341 Image(systemName: symbol).font(.footnote).foregroundStyle(NVColor.ai).accessibilityHidden(true)342 Text(item).nvFont(.body).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)343 }344 }345 }346 }347}348