SPB Git

Repository Public

AudioBlockView.swift 19.7 KB 418 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/Audio/AudioBlockView.swift3// Description: Detail of a voice note: the recorder (record / pause / resume / stop with a level meter), the player4//              (play, scrubber, ±15 s, rate), the transcript with tap-to-seek and the line being spoken, and the AI5//              summary. Compact = one column; regular = audio on the left, transcript on the right.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesDesign10import SPNotesDocument11import SwiftUI1213public struct AudioBlockView: View {14    @State private var model: AudioBlockModel15    @State private var title: String16    @Environment(\.accessibilityReduceMotion) private var reduceMotion1718    private let closesOnDisappear: Bool1920    /// - Parameter closesOnDisappear: stops an unfinished recording (kept on the device) and the playback when the view21    ///   goes away. Pass false when the host keeps the model alive across presentations and calls `model.close()` itself.22    public init(model: AudioBlockModel, closesOnDisappear: Bool = true) {23        _model = State(initialValue: model)24        _title = State(initialValue: model.title)25        self.closesOnDisappear = closesOnDisappear26    }2728    public var body: some View {29        BlockDetailContainer(title: L("Note vocale"), systemImage: "waveform", subtitle: subtitle) { sizeClass in30            VStack(alignment: .leading, spacing: NVSpace.lg) {31                if let failure = model.actionFailure {32                    BlockActionFailure(failure: failure) { model.actionFailure = nil }33                }34                if sizeClass.isCompact {35                    audioColumn(compact: true)36                    transcriptColumn(compact: true)37                } else {38                    HStack(alignment: .top, spacing: NVSpace.xl) {39                        audioColumn(compact: false).frame(maxWidth: 420, alignment: .topLeading)40                        transcriptColumn(compact: false).frame(maxWidth: .infinity, alignment: .topLeading)41                    }42                }43            }44        }45        .task { await model.load() }46        .onChange(of: model.title) { _, value in if value != title { title = value } }47        .onDisappear { if closesOnDisappear { model.close() } }48    }4950    private var subtitle: String? {51        var parts: [String] = []52        if model.block.duration > 0 { parts.append(FeatureFormat.clock(model.block.duration)) }53        if let recordedAt = model.block.recordedAt, let date = TaskItemDetail.date(from: recordedAt) { parts.append(FeatureFormat.dayTime(date)) }54        return parts.isEmpty ? nil : parts.joined(separator: " · ")55    }5657    // MARK: audio column5859    @ViewBuilder60    private func audioColumn(compact: Bool) -> some View {61        VStack(alignment: .leading, spacing: NVSpace.lg) {62            VStack(alignment: .leading, spacing: NVSpace.xs) {63                BlockSectionLabel(text: L("Titre"))64                BlockTextField(placeholder: L("Titre de la note vocale"), text: $title) { model.setTitle(title) }65                    .onChange(of: title) { _, value in model.setTitle(value) }66            }67            switch model.stage {68            case .empty, .recording, .paused:69                recorderCard(compact: compact)70            case .recorded, .uploading, .ready:71                playerCard(compact: compact)72                if model.stage == .recorded { pendingUploadCard }73                if model.stage == .uploading { FeatureLoadingView(L("Envoi de l'enregistrement…")).frame(minHeight: 72) }74            }75        }76    }7778    private func recorderCard(compact: Bool) -> some View {79        NVCard {80            VStack(spacing: NVSpace.lg) {81                if model.permissionDenied {82                    BlockNotice(systemImage: "mic.slash", text: L("L'accès au micro est refusé. Autorisez SP Notes dans les réglages de confidentialité du système, puis réessayez."), tone: .warning)83                }84                AudioLevelMeter(level: model.inputLevel, active: model.stage == .recording)85                    .frame(height: 44)86                Text(FeatureFormat.clock(model.elapsed))87                    .font(NVFont.fixed(.h1).monospacedDigit())88                    .foregroundStyle(model.stage == .recording ? NVColor.fg : NVColor.fgMuted)89                    .accessibilityLabel(LF("Durée enregistrée : %@", FeatureFormat.clock(model.elapsed)))90                Text(recorderStatus).nvFont(.ui).foregroundStyle(NVColor.fgMuted)91                HStack(spacing: NVSpace.lg) {92                    switch model.stage {93                    case .empty:94                        AudioRoundButton(systemImage: "mic.fill", label: L("Enregistrer"), kind: .record) { Task { await model.startRecording() } }95                    case .recording:96                        AudioRoundButton(systemImage: "pause.fill", label: L("Mettre en pause"), kind: .secondary) { model.pauseRecording() }97                        AudioRoundButton(systemImage: "stop.fill", label: L("Terminer l'enregistrement"), kind: .record) { Task { await model.stopRecording() } }98                    case .paused:99                        AudioRoundButton(systemImage: "mic.fill", label: L("Reprendre l'enregistrement"), kind: .secondary) { model.resumeRecording() }100                        AudioRoundButton(systemImage: "stop.fill", label: L("Terminer l'enregistrement"), kind: .record) { Task { await model.stopRecording() } }101                    default: EmptyView()102                    }103                }104                if model.stage == .paused {105                    FeatureButton(L("Abandonner"), systemImage: "trash", kind: .destructive) { model.discardRecording() }106                }107            }108            .frame(maxWidth: .infinity)109        }110    }111112    private var recorderStatus: String {113        switch model.stage {114        case .recording: return L("Enregistrement en cours")115        case .paused: return L("En pause")116        default: return L("Prêt à enregistrer")117        }118    }119120    private func playerCard(compact: Bool) -> some View {121        NVCard {122            VStack(alignment: .leading, spacing: NVSpace.md) {123                AudioScrubber(fraction: model.progress, duration: model.playbackDuration) { fraction in124                    Task { await model.seek(toFraction: fraction) }125                }126                HStack {127                    Text(FeatureFormat.clock(model.position)).font(NVFont.fixed(.micro).monospacedDigit()).foregroundStyle(NVColor.fgMuted)128                    Spacer()129                    Text(FeatureFormat.clock(model.playbackDuration)).font(NVFont.fixed(.micro).monospacedDigit()).foregroundStyle(NVColor.fgMuted)130                }131                .accessibilityHidden(true)132                HStack(spacing: NVSpace.md) {133                    Spacer(minLength: 0)134                    AudioRoundButton(systemImage: "gobackward.15", label: L("Reculer de 15 secondes"), kind: .quiet) { Task { await model.skip(-15) } }135                    AudioRoundButton(systemImage: model.isPlaying ? "pause.fill" : "play.fill", label: model.isPlaying ? L("Pause") : L("Lire"), kind: .primary) {136                        Task { await model.togglePlayback() }137                    }138                    AudioRoundButton(systemImage: "goforward.15", label: L("Avancer de 15 secondes"), kind: .quiet) { Task { await model.skip(15) } }139                    Spacer(minLength: 0)140                }141                HStack(spacing: NVSpace.xs) {142                    Text(L("Vitesse")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)143                    Spacer(minLength: NVSpace.sm)144                    ForEach(AudioBlockModel.rates, id: \.self) { rate in145                        NVChip(AudioBlockView.rateLabel(rate), tone: .accent, isSelected: model.rate == rate) { model.setRate(rate) }146                            .accessibilityLabel(LF("Vitesse %@", AudioBlockView.rateLabel(rate)))147                    }148                }149                if let failure = model.playbackFailure {150                    BlockNotice(systemImage: failure.isOffline ? "wifi.slash" : "speaker.slash", text: failure.message)151                }152            }153        }154    }155156    static func rateLabel(_ rate: Double) -> String {157        let text = rate == rate.rounded() ? String(format: "%.0f", rate) : String(format: "%g", rate)158        return text.replacingOccurrences(of: ".", with: ",") + "×"159    }160161    private var pendingUploadCard: some View {162        VStack(alignment: .leading, spacing: NVSpace.sm) {163            BlockNotice(systemImage: "internaldrive", text: L("L'enregistrement est sur cet appareil ; il n'a pas encore été ajouté à la page."))164            HStack(spacing: NVSpace.sm) {165                FeatureButton(L("Réessayer l'envoi"), systemImage: "arrow.up.circle", kind: .primary) { Task { await model.store() } }166                FeatureButton(L("Supprimer"), systemImage: "trash", kind: .destructive) { model.discardRecording() }167            }168        }169    }170171    // MARK: transcript column172173    @ViewBuilder174    private func transcriptColumn(compact: Bool) -> some View {175        VStack(alignment: .leading, spacing: NVSpace.lg) {176            HStack(spacing: NVSpace.sm) {177                BlockSectionLabel(text: L("Transcription"))178                if !model.segments.isEmpty { NVAIBadge(model: model.block.transcriptEngine, style: .compact) }179                Spacer(minLength: 0)180            }181            transcriptBody(compact: compact)182            if let summary = model.summary { summaryCard(summary) }183        }184    }185186    @ViewBuilder187    private func transcriptBody(compact: Bool) -> some View {188        switch model.transcription {189        case .requesting:190            FeatureLoadingView(L("Demande de transcription…")).frame(minHeight: 96)191        case .pending:192            VStack(alignment: .leading, spacing: NVSpace.sm) {193                HStack(spacing: NVSpace.md) {194                    NVProgressDots()195                    Text(L("Le serveur transcrit l'enregistrement…")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)196                }197                HStack(spacing: NVSpace.sm) {198                    if model.isWaiting {199                        FeatureButton(L("Ne plus attendre"), systemImage: "xmark") { model.stopWaiting() }200                    }201                    FeatureButton(L("Vérifier"), systemImage: "arrow.clockwise") { Task { await model.checkTranscription() } }202                }203                Text(L("La transcription continue sur le serveur même si vous fermez cette vue.")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)204            }205        case .failed(let reason):206            VStack(alignment: .leading, spacing: NVSpace.sm) {207                BlockNotice(systemImage: "exclamationmark.triangle", text: reason.isEmpty ? L("La transcription a échoué.") : LF("La transcription a échoué : %@", reason), tone: .danger)208                requestControls(retry: true)209            }210        case .none:211            VStack(alignment: .leading, spacing: NVSpace.sm) {212                Text(model.stage == .ready ? L("Aucune transcription pour l'instant.") : L("La transcription sera possible une fois l'enregistrement ajouté à la page."))213                    .nvFont(.body).foregroundStyle(NVColor.fgMuted)214                if model.stage == .ready { requestControls(retry: false) }215            }216        case .done:217            if model.segments.isEmpty {218                Text(L("La transcription est vide : aucune parole n'a été reconnue.")).nvFont(.body).foregroundStyle(NVColor.fgMuted)219            } else {220                VStack(alignment: .leading, spacing: NVSpace.xxs) {221                    let timed = AudioTranscriptLogic.hasTimings(model.segments)222                    ForEach(Array(model.segments.enumerated()), id: \.offset) { index, segment in223                        AudioTranscriptRow(segment: segment, isActive: model.activeSegmentIndex == index, showsTime: timed, compact: compact) {224                            Task { await model.seek(toSegment: index) }225                        }226                    }227                }228                .nvAnimation(.fast, value: model.activeSegmentIndex)229            }230        }231    }232233    private func requestControls(retry: Bool) -> some View {234        VStack(alignment: .leading, spacing: NVSpace.sm) {235            Toggle(isOn: Binding(get: { model.wantsSummary }, set: { model.wantsSummary = $0 })) {236                Text(L("Demander aussi un résumé (décisions et tâches)")).nvFont(.ui).foregroundStyle(NVColor.fg)237            }238            .tint(NVColor.ai)239            FeatureButton(retry ? L("Transcrire de nouveau") : L("Transcrire"), systemImage: "text.bubble", kind: .ai) {240                Task { await model.requestTranscription(force: retry) }241            }242            .disabled(!model.canTranscribe)243            Text(L("Appel payant à un modèle sur le serveur, lancé seulement par ce bouton."))244                .nvFont(.micro).foregroundStyle(NVColor.fgMuted)245        }246    }247248    private func summaryCard(_ summary: AudioSummary) -> some View {249        FeatureAICard(model: summary.model, title: L("Résumé")) {250            Text(summary.text).nvFont(.body).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)251            if !summary.decisions.isEmpty { summaryList(L("Décisions"), "checkmark.seal", summary.decisions) }252            if !summary.tasks.isEmpty { summaryList(L("Tâches évoquées"), "checklist", summary.tasks) }253        }254    }255256    private func summaryList(_ title: String, _ symbol: String, _ items: [String]) -> some View {257        VStack(alignment: .leading, spacing: NVSpace.xs) {258            Text(title).nvFont(.uiStrong).foregroundStyle(NVColor.fg)259            ForEach(Array(items.enumerated()), id: \.offset) { _, item in260                HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {261                    Image(systemName: symbol).foregroundStyle(NVColor.ai).accessibilityHidden(true)262                    Text(item).nvFont(.body).foregroundStyle(NVColor.fg).fixedSize(horizontal: false, vertical: true)263                }264            }265        }266    }267}268269// MARK: - pieces270271struct AudioTranscriptRow: View {272    let segment: TranscriptSegment273    let isActive: Bool274    let showsTime: Bool275    let compact: Bool276    let action: () -> Void277278    var body: some View {279        Button(action: action) {280            HStack(alignment: .firstTextBaseline, spacing: NVSpace.md) {281                if showsTime {282                    Text(segment.timecode)283                        .font(NVFont.fixed(.code).monospacedDigit())284                        .foregroundStyle(isActive ? NVColor.accent : NVColor.fgMuted)285                        .frame(minWidth: 46, alignment: .leading)286                }287                Text(segment.text)288                    .nvFont(.body)289                    .foregroundStyle(NVColor.fg)290                    .multilineTextAlignment(.leading)291                    .fixedSize(horizontal: false, vertical: true)292                Spacer(minLength: 0)293            }294            .padding(.horizontal, NVSpace.md)295            .padding(.vertical, NVSpace.sm)296            .frame(minHeight: compact ? 44 : nil)297            .background(isActive ? NVColor.accentSoft : Color.clear, in: NVRadius.shape(NVRadius.sm))298            .contentShape(Rectangle())299        }300        .buttonStyle(.plain)301        .accessibilityLabel(showsTime ? LF("%1$@, à %2$@", segment.text, segment.timecode) : segment.text)302        .accessibilityHint(L("Lire à partir de ce passage"))303        .accessibilityAddTraits(isActive ? .isSelected : [])304    }305}306307struct AudioRoundButton: View {308    enum Kind { case primary, record, secondary, quiet }309    let systemImage: String310    let label: String311    let kind: Kind312    let action: () -> Void313314    var body: some View {315        let size: CGFloat = kind == .quiet ? 44 : 56316        Button(action: action) {317            Image(systemName: systemImage)318                .font(.system(size: kind == .quiet ? 20 : 22, weight: .semibold))319                .foregroundStyle(foreground)320                .frame(width: size, height: size)321                .background(background, in: Circle())322                .overlay(Circle().strokeBorder(kind == .secondary ? NVColor.lineStrong : .clear, lineWidth: 1))323                .contentShape(Circle())324        }325        .buttonStyle(.plain)326        .accessibilityLabel(label)327        #if os(macOS)328        .help(label)329        #endif330    }331332    private var foreground: Color {333        switch kind {334        case .primary: return NVColor.accentFg335        case .record: return NVColor.accentFg336        case .secondary: return NVColor.fg337        case .quiet: return NVColor.fgMuted338        }339    }340341    private var background: Color {342        switch kind {343        case .primary: return NVColor.accent344        case .record: return NVColor.danger345        case .secondary: return NVColor.bgElevated346        case .quiet: return NVColor.bgHover.opacity(0.6)347        }348    }349}350351/// Input level as a row of bars (static when not recording).352struct AudioLevelMeter: View {353    let level: Double354    let active: Bool355    private let bars = 28356357    var body: some View {358        GeometryReader { proxy in359            let spacing: CGFloat = 3360            let width = max(2, (proxy.size.width - spacing * CGFloat(bars - 1)) / CGFloat(bars))361            HStack(alignment: .center, spacing: spacing) {362                ForEach(0..<bars, id: \.self) { index in363                    Capsule()364                        .fill(active ? NVColor.danger.opacity(0.85) : NVColor.lineStrong)365                        .frame(width: width, height: max(4, proxy.size.height * AudioLevelMeter.height(bar: index, of: bars, level: active ? level : 0)))366                }367            }368            .frame(maxWidth: .infinity, maxHeight: .infinity)369        }370        .nvAnimation(.instant, value: level)371        .accessibilityHidden(true)372    }373374    /// Height 0…1 of a bar: a fixed bell shape scaled by the level (deterministic, no randomness).375    static func height(bar: Int, of count: Int, level: Double) -> Double {376        let x = (Double(bar) + 0.5) / Double(count) * 2 - 1377        let bell = 0.35 + 0.65 * (1 - x * x)378        let ripple = 0.75 + 0.25 * abs(sin(Double(bar) * 1.7))379        return min(1, max(0.08, level * bell * ripple))380    }381}382383/// Playback position: a track that can be tapped or dragged; adjustable with VoiceOver.384struct AudioScrubber: View {385    let fraction: Double386    let duration: Double387    let seek: (Double) -> Void388    @State private var dragging: Double?389390    var body: some View {391        GeometryReader { proxy in392            let value = dragging ?? fraction393            ZStack(alignment: .leading) {394                Capsule().fill(NVColor.lineStrong).frame(height: 6)395                Capsule().fill(NVColor.accent).frame(width: max(6, proxy.size.width * value), height: 6)396                Circle().fill(NVColor.accent).frame(width: 16, height: 16)397                    .offset(x: min(max(0, proxy.size.width * value - 8), proxy.size.width - 16))398            }399            .frame(maxHeight: .infinity)400            .contentShape(Rectangle())401            .gesture(DragGesture(minimumDistance: 0)402                .onChanged { gesture in dragging = min(1, max(0, gesture.location.x / max(1, proxy.size.width))) }403                .onEnded { gesture in404                    seek(min(1, max(0, gesture.location.x / max(1, proxy.size.width))))405                    dragging = nil406                })407        }408        .frame(height: 28)409        .accessibilityElement()410        .accessibilityLabel(L("Position de lecture"))411        .accessibilityValue(LF("%1$@ sur %2$@", FeatureFormat.clock(fraction * duration), FeatureFormat.clock(duration)))412        .accessibilityAdjustableAction { direction in413            let step = duration > 0 ? 15 / duration : 0.1414            seek(min(1, max(0, fraction + (direction == .increment ? step : -step))))415        }416    }417}418
Files main
Menu

Theme