Repository Public
1// SP Notes iOS2// File: Features/Voice/VoiceRecorderView.swift3// Description: The recorder as the user sees it: the Lumen record button, elapsed time, the live level meter (static under Reduce4// Motion), pause / resume / stop, and the explanatory screen when the microphone is refused. Used inline in Quick5// Capture and as a sheet from the editor (« Note vocale » inserts an `audio` block at the caret).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesCore10import SPNotesDesign11import SwiftUI12import UIKit1314// MARK: - Level meter1516/// The last input levels as bars. Under Reduce Motion the bars do not animate: one steady bar shows the current level.17struct LevelMeterView: View {18 var history: [Float]19 var level: Float20 var isLive: Bool21 var capacity = VoiceRecorderModel.historyCapacity22 @Environment(\.accessibilityReduceMotion) private var reduceMotion2324 var body: some View {25 Group {26 if reduceMotion {27 // static: a single gauge, no moving bars28 GeometryReader { proxy in29 ZStack(alignment: .leading) {30 Capsule().fill(NVColor.bgSunken)31 Capsule().fill(isLive ? AnyShapeStyle(NVColor.lumen) : AnyShapeStyle(NVColor.lineStrong))32 .frame(width: max(8, proxy.size.width * CGFloat(Self.steadyLevel(level))))33 }34 }35 .frame(height: 10)36 .frame(maxHeight: .infinity, alignment: .center)37 } else {38 GeometryReader { proxy in39 let spacing: CGFloat = 340 let width = max(2, (proxy.size.width - spacing * CGFloat(capacity - 1)) / CGFloat(capacity))41 HStack(alignment: .center, spacing: spacing) {42 ForEach(0..<capacity, id: \.self) { index in43 let value = Self.bar(at: index, history: history, capacity: capacity)44 Capsule()45 .fill(isLive ? AnyShapeStyle(NVColor.lumen) : AnyShapeStyle(NVColor.lineStrong))46 .frame(width: width, height: max(3, proxy.size.height * CGFloat(value)))47 .opacity(value > 0 ? 1 : 0.45)48 }49 }50 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)51 .animation(.linear(duration: 0.05), value: history)52 }53 }54 }55 .frame(height: 56)56 .accessibilityElement()57 .accessibilityLabel(Text("Niveau du microphone"))58 .accessibilityValue(Text(isLive ? "\(Int((level * 100).rounded())) %" : String(localized: "en pause")))59 .accessibilityIdentifier("voice-meter")60 }6162 /// The value of bar `index` (the history is right-aligned: the newest level is the last bar).63 static func bar(at index: Int, history: [Float], capacity: Int) -> Float {64 let offset = capacity - history.count65 guard index >= offset, history.indices.contains(index - offset) else { return 0 }66 return history[index - offset]67 }6869 /// Under Reduce Motion the gauge moves in five steps, not continuously.70 static func steadyLevel(_ level: Float) -> Float { (min(1, max(0, level)) * 4).rounded() / 4 }71}7273// MARK: - Microphone refused7475/// Why recording is impossible and what to do about it. Never a dead end: Settings, or a way back.76struct MicrophoneDeniedView: View {77 var restricted: Bool78 var onRetry: (() -> Void)?7980 var body: some View {81 VStack(spacing: NVSpace.md) {82 Image(systemName: "mic.slash.fill")83 .font(.system(size: 34, weight: .semibold))84 .foregroundStyle(NVColor.fgMuted)85 .accessibilityHidden(true)86 Text(restricted ? "Microphone restreint" : "Microphone non autorisé")87 .nvFont(.h3)88 .foregroundStyle(NVColor.fg)89 .multilineTextAlignment(.center)90 Text(restricted91 ? "L’accès au microphone est bloqué par une restriction de cet appareil (Temps d’écran ou profil de gestion). SP Notes ne peut pas enregistrer tant qu’elle est active."92 : "Pour enregistrer une note vocale ou dicter, autorise le microphone pour SP Notes dans Réglages. Rien n’est enregistré sans ton action.")93 .nvFont(.ui)94 .foregroundStyle(NVColor.fgMuted)95 .multilineTextAlignment(.center)96 .fixedSize(horizontal: false, vertical: true)97 if !restricted {98 Button {99 if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }100 } label: {101 Label("Ouvrir Réglages", systemImage: "gear").frame(maxWidth: .infinity)102 }103 .buttonStyle(.borderedProminent)104 .controlSize(.large)105 .accessibilityIdentifier("voice-open-settings")106 }107 if let onRetry {108 Button("Réessayer", action: onRetry)109 .nvFont(.ui)110 .accessibilityIdentifier("voice-permission-retry")111 }112 }113 .padding(NVSpace.xl)114 .frame(maxWidth: .infinity)115 .nvCard()116 .accessibilityElement(children: .contain)117 .accessibilityIdentifier("voice-mic-denied")118 }119}120121// MARK: - Recorder122123/// The recorder controls. `onFinish` receives the finished recording when the user stops.124struct VoiceRecorderView: View {125 let recorder: VoiceRecorderModel126 var onFinish: (RecordedAudio) -> Void = { _ in }127 @Environment(\.accessibilityReduceMotion) private var reduceMotion128 @Environment(\.scenePhase) private var scenePhase129130 var body: some View {131 VStack(spacing: NVSpace.lg) {132 switch recorder.phase {133 case .denied(let restricted):134 MicrophoneDeniedView(restricted: restricted) { Task { recorder.refreshPermission(); await recorder.start() } }135 case .failed(let message):136 VStack(spacing: NVSpace.sm) {137 Label(message, systemImage: "exclamationmark.triangle.fill")138 .nvFont(.ui).foregroundStyle(NVColor.fg).multilineTextAlignment(.center)139 Button("Réessayer") { Task { await recorder.start() } }.accessibilityIdentifier("voice-retry")140 }141 .padding(NVSpace.lg).frame(maxWidth: .infinity).nvCard()142 case .stopped(let audio):143 HStack(spacing: NVSpace.md) {144 Image(systemName: "waveform").foregroundStyle(NVColor.accent).accessibilityHidden(true)145 VStack(alignment: .leading, spacing: NVSpace.xxs) {146 Text("Enregistrement prêt").nvFont(.uiStrong).foregroundStyle(NVColor.fg)147 Text(VoiceNoteIO.timecode(audio.duration)).nvFont(.ui).foregroundStyle(NVColor.fgMuted).monospacedDigit()148 }149 Spacer(minLength: NVSpace.sm)150 Button(role: .destructive) { recorder.discard() } label: { Label("Recommencer", systemImage: "arrow.counterclockwise") }151 .labelStyle(.iconOnly).frame(minWidth: 44, minHeight: 44)152 .accessibilityIdentifier("voice-discard")153 }154 .padding(NVSpace.lg).nvCard()155 .accessibilityIdentifier("voice-ready")156 default:157 live158 }159 }160 .onChange(of: scenePhase) { _, phase in if phase == .active { recorder.refreshPermission() } }161 }162163 private var isRecording: Bool { recorder.phase == .recording }164165 private var live: some View {166 VStack(spacing: NVSpace.lg) {167 Text(VoiceNoteIO.timecode(recorder.elapsed))168 .font(.system(size: 44, weight: .semibold, design: .serif)).monospacedDigit()169 .foregroundStyle(NVColor.fg)170 .contentTransition(reduceMotion ? .identity : .numericText())171 .accessibilityLabel(Text("Durée enregistrée"))172 .accessibilityValue(Text(VoiceNoteIO.timecode(recorder.elapsed)))173 .accessibilityIdentifier("voice-elapsed")174 LevelMeterView(history: recorder.history, level: recorder.level, isLive: isRecording)175 Text(statusText).nvFont(.ui).foregroundStyle(NVColor.fgMuted).multilineTextAlignment(.center)176 .fixedSize(horizontal: false, vertical: true)177 .accessibilityIdentifier("voice-status")178 HStack(spacing: NVSpace.xl) {179 if recorder.isActive {180 Button {181 Haptics.tap()182 if isRecording { recorder.pause() } else { recorder.resume() }183 } label: {184 Image(systemName: isRecording ? "pause.fill" : "play.fill").font(.title2)185 .frame(width: 56, height: 56).background(NVColor.bgSunken, in: Circle())186 }187 .accessibilityLabel(Text(isRecording ? "Mettre en pause" : "Reprendre"))188 .accessibilityIdentifier("voice-pause")189 }190 Button {191 if recorder.isActive {192 Haptics.success()193 if let audio = recorder.stop() { onFinish(audio) }194 } else {195 Haptics.tap()196 Task { await recorder.start() }197 }198 } label: {199 ZStack {200 Circle().fill(NVColor.lumen).frame(width: 76, height: 76)201 if recorder.isActive {202 RoundedRectangle(cornerRadius: 6, style: .continuous).fill(NVColor.accentFg).frame(width: 26, height: 26)203 } else {204 Image(systemName: "mic.fill").font(.title).foregroundStyle(NVColor.accentFg)205 }206 }207 .overlay { Circle().strokeBorder(NVColor.accentFg.opacity(0.35), lineWidth: 2).padding(4) }208 }209 .disabled(recorder.phase == .requestingPermission)210 .accessibilityLabel(Text(recorder.isActive ? "Terminer l’enregistrement" : "Enregistrer"))211 .accessibilityIdentifier("voice-record")212 if recorder.isActive {213 Button(role: .destructive) { Haptics.warning(); recorder.discard() } label: {214 Image(systemName: "trash").font(.title3)215 .frame(width: 56, height: 56).background(NVColor.bgSunken, in: Circle())216 }217 .accessibilityLabel(Text("Supprimer l’enregistrement"))218 .accessibilityIdentifier("voice-cancel")219 }220 }221 }222 .padding(NVSpace.lg)223 .frame(maxWidth: .infinity)224 .nvCard()225 }226227 private var statusText: String {228 switch recorder.phase {229 case .recording: return String(localized: "Enregistrement en cours")230 case .paused(.user): return String(localized: "En pause")231 case .paused(.interruption): return String(localized: "En pause : un appel ou une autre app a pris le micro. L’enregistrement est conservé.")232 case .paused(.inputLost): return String(localized: "En pause : le micro utilisé a été débranché. L’enregistrement est conservé.")233 case .paused(.background): return String(localized: "En pause : SP Notes est passée en arrière-plan. L’enregistrement est conservé.")234 case .requestingPermission: return String(localized: "Autorisation du microphone…")235 default: return String(localized: "Touche le bouton pour enregistrer")236 }237 }238}239240// MARK: - Sheet from the editor241242/// « Note vocale » from the editor: records, then inserts the `audio` block through the block detail context (at the caret).243struct VoiceRecorderSheet: View {244 let context: BlockDetailContext245 @State private var recorder: VoiceRecorderModel246 @State private var title = ""247 @State private var isSaving = false248 @State private var confirmsDiscard = false249250 init(context: BlockDetailContext, recorder: VoiceRecorderModel? = nil) {251 self.context = context252 _recorder = State(initialValue: recorder ?? VoiceDebug.recorder() ?? VoiceRecorderModel.system())253 }254255 var body: some View {256 NavigationStack {257 ScrollView {258 VStack(alignment: .leading, spacing: NVSpace.lg) {259 TextField("Titre (facultatif)", text: $title)260 .nvFont(.h3)261 .accessibilityIdentifier("voice-title")262 VoiceRecorderView(recorder: recorder)263 }264 .padding(NVSpace.lg)265 }266 .background(NVColor.bg)267 .navigationTitle("Note vocale")268 .navigationBarTitleDisplayMode(.inline)269 .toolbar {270 ToolbarItem(placement: .cancellationAction) {271 Button("Annuler") { if recorder.isActive || recorder.result != nil { confirmsDiscard = true } else { context.dismiss() } }272 }273 ToolbarItem(placement: .confirmationAction) {274 Button("Insérer") { insert() }275 .disabled(isSaving || (!recorder.isActive && recorder.result == nil))276 .accessibilityIdentifier("voice-insert")277 }278 }279 .confirmationDialog("Supprimer cet enregistrement ?", isPresented: $confirmsDiscard, titleVisibility: .visible) {280 Button("Supprimer", role: .destructive) { recorder.discard(); context.dismiss() }281 Button("Continuer", role: .cancel) {}282 }283 .task { if recorder.phase == .idle { await recorder.start() } }284 }285 .interactiveDismissDisabled(recorder.isActive || recorder.result != nil)286 }287288 private func insert() {289 guard let audio = recorder.result ?? recorder.stop() else { return }290 isSaving = true291 Task {292 do {293 let voice = VoiceCapture(fileURL: audio.fileURL, duration: audio.duration, recordedAt: audio.startedAt, title: title.trimmingCharacters(in: .whitespacesAndNewlines))294 context.commit(try await VoiceNoteIO.audioNode(for: voice, app: context.app, noteId: context.noteId))295 MediaTemp.discard(audio.fileURL)296 recorder.reset()297 Haptics.success()298 context.dismiss()299 } catch {300 context.app.banner = error.localizedDescription301 isSaving = false302 }303 }304 }305}306