Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Features/Library/LibraryView.swift4// Description: Local library: search, filters, sorting, folders, favourites, Recently Deleted, import from Files and Photos, batch actions.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import CoreTransferable10import ORIXAudioCore11import PhotosUI12import SwiftData13import SwiftUI14import UniformTypeIdentifiers1516enum LibraryScope: Hashable {17 case all, recent, favorites, folder(UUID), trash18}1920enum LibrarySort: String, CaseIterable, Identifiable {21 case newest, oldest, title, longest, largest22 var id: String { rawValue }23 var title: LocalizedStringKey {24 switch self { case .newest: "Newest first"; case .oldest: "Oldest first"; case .title: "Title"; case .longest: "Longest first"; case .largest: "Largest first" }25 }26}2728enum LibraryFilter: String, CaseIterable, Identifiable {29 case any, transcribed, notTranscribed, meetings, imported, lossless30 var id: String { rawValue }31 var title: LocalizedStringKey {32 switch self {33 case .any: "All kinds"; case .transcribed: "With transcript"; case .notTranscribed: "Without transcript"34 case .meetings: "Meetings"; case .imported: "Imported"; case .lossless: "Lossless"35 }36 }37}3839/// A video picked from Photos, copied to a temporary file the importer can read.40struct PickedVideo: Transferable {41 let url: URL42 static var transferRepresentation: some TransferRepresentation {43 FileRepresentation(importedContentType: .movie) { received in44 let copy = FileManager.default.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString)-\(received.file.lastPathComponent)")45 try FileManager.default.copyItem(at: received.file, to: copy)46 return PickedVideo(url: copy)47 }48 }49}5051struct LibraryRootView: View {52 @Binding var path: [UUID]53 var body: some View {54 NavigationStack(path: $path) {55 LibraryView()56 .navigationDestination(for: UUID.self) { RecordingDetailView(recordingID: $0) }57 }58 }59}6061struct LibraryView: View {62 @Environment(AppModel.self) private var model63 @Environment(\.modelContext) private var context64 @Query(sort: \Recording.createdAt, order: .reverse) private var recordings: [Recording]65 @Query(sort: \Folder.name) private var folders: [Folder]66 @State private var scope: LibraryScope = .all67 @State private var sort: LibrarySort = .newest68 @State private var filter: LibraryFilter = .any69 @State private var search = ""70 @State private var transcriptMatches: Set<UUID> = []71 @State private var showFileImporter = false72 @State private var photoItem: PhotosPickerItem?73 @State private var showPhotoPicker = false74 @State private var renaming: Recording?75 @State private var renameText = ""76 @State private var showNewFolder = false77 @State private var newFolderName = ""78 @State private var editMode: EditMode = .inactive79 @State private var selection: Set<UUID> = []80 @State private var share: SharePayload?81 @State private var showWorkflowPicker = false82 @State private var confirmEmptyTrash = false8384 private var visible: [Recording] {85 var list = recordings.filter { r in86 switch scope {87 case .trash: r.deletedAt != nil88 case .all: r.deletedAt == nil89 case .recent: r.deletedAt == nil && r.createdAt > Date.now.addingTimeInterval(-7 * 24 * 3600)90 case .favorites: r.deletedAt == nil && r.isFavorite91 case .folder(let id): r.deletedAt == nil && r.folder?.id == id92 }93 }94 list = list.filter { r in95 switch filter {96 case .any: true97 case .transcribed: r.transcriptStatus == .done98 case .notTranscribed: r.transcriptStatus != .done99 case .meetings: r.kind == .meeting100 case .imported: r.source == .importedAudio || r.source == .importedVideo101 case .lossless: r.isLossless102 }103 }104 let q = search.trimmingCharacters(in: .whitespaces)105 if !q.isEmpty {106 list = list.filter {107 $0.title.localizedStandardContains(q) || $0.notes.localizedStandardContains(q) || $0.participants.localizedStandardContains(q) || transcriptMatches.contains($0.id)108 }109 }110 switch sort {111 case .newest: break112 case .oldest: list.reverse()113 case .title: list.sort { $0.title.localizedStandardCompare($1.title) == .orderedAscending }114 case .longest: list.sort { $0.duration > $1.duration }115 case .largest: list.sort { $0.fileSize > $1.fileSize }116 }117 return list118 }119120 var body: some View {121 List(selection: $selection) {122 Section { scopeBar.listRowInsets(EdgeInsets()).listRowBackground(Color.clear) }123 if let progress = model.importProgress {124 Section { ProgressRow(title: "Importing…", progress: progress) }125 }126 if visible.isEmpty {127 Section {128 EmptyStateView(symbol: scope == .trash ? "trash" : "waveform", title: scope == .trash ? "Nothing here" : "No recordings",129 message: scope == .trash ? "Deleted recordings stay here for 30 days." : (search.isEmpty ? "Record something, or import audio or video from Files or Photos." : "No recording matches your search."))130 .listRowBackground(Color.clear)131 }132 } else {133 Section {134 ForEach(visible) { recording in135 NavigationLink(value: recording.id) { RecordingRow(recording: recording, transcriptHit: transcriptMatches.contains(recording.id) && !search.isEmpty) }136 .tag(recording.id)137 .swipeActions(edge: .trailing) { trailingActions(recording) }138 .swipeActions(edge: .leading) {139 if scope != .trash {140 Button { recording.isFavorite.toggle() } label: { Label(recording.isFavorite ? "Unfavourite" : "Favourite", systemImage: recording.isFavorite ? "star.slash" : "star.fill") }.tint(.yellow)141 }142 }143 .contextMenu { contextMenu(recording) }144 }145 } header: {146 Text("\(visible.count) recordings · \(Formatters.duration(visible.reduce(0) { $0 + $1.duration })) · \(Formatters.bytes(visible.reduce(0) { $0 + $1.fileSize }))")147 }148 }149 }150 .listStyle(.insetGrouped)151 .scrollContentBackground(.hidden)152 .orixScreenBackground()153 .environment(\.editMode, $editMode)154 .navigationTitle("Library")155 .searchable(text: $search, prompt: "Titles, notes and transcripts")156 .task(id: search) { await searchTranscripts() }157 .toolbar { toolbar }158 .fileImporter(isPresented: $showFileImporter, allowedContentTypes: MediaImporter.allTypes, allowsMultipleSelection: true) { result in159 if case .success(let urls) = result { Task { await model.importFiles(urls) } }160 }161 .photosPicker(isPresented: $showPhotoPicker, selection: $photoItem, matching: .videos)162 .onChange(of: photoItem) { _, item in163 guard let item else { return }164 Task {165 if let video = try? await item.loadTransferable(type: PickedVideo.self) {166 await model.importFiles([video.url])167 try? FileManager.default.removeItem(at: video.url)168 } else { model.importError = String(localized: "That video couldn't be loaded from Photos.") }169 photoItem = nil170 }171 }172 .alert("Rename", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {173 TextField("Title", text: $renameText)174 Button("Save") { if let r = renaming, !renameText.trimmingCharacters(in: .whitespaces).isEmpty { r.title = renameText } ; renaming = nil }175 Button("Cancel", role: .cancel) { renaming = nil }176 }177 .alert("New folder", isPresented: $showNewFolder) {178 TextField("Name", text: $newFolderName)179 Button("Create") {180 let name = newFolderName.trimmingCharacters(in: .whitespaces)181 if !name.isEmpty { context.insert(Folder(name: name)) }182 newFolderName = ""183 }184 Button("Cancel", role: .cancel) { newFolderName = "" }185 }186 .confirmationDialog("Permanently delete everything in Recently Deleted?", isPresented: $confirmEmptyTrash, titleVisibility: .visible) {187 Button("Delete all", role: .destructive) { for r in recordings where r.deletedAt != nil { model.purge(r) } }188 }189 .sheet(isPresented: $showWorkflowPicker) {190 WorkflowPickerSheet(recordings: recordings.filter { selection.contains($0.id) }) { editMode = .inactive; selection = [] }191 }192 .shareSheet($share)193 }194195 private var scopeBar: some View {196 ScrollView(.horizontal, showsIndicators: false) {197 HStack(spacing: 8) {198 scopeButton(.all, "All", "tray.full")199 scopeButton(.recent, "Recent", "clock")200 scopeButton(.favorites, "Favourites", "star")201 ForEach(folders) { folder in202 scopeButton(.folder(folder.id), LocalizedStringKey(folder.name), "folder")203 .contextMenu { Button("Delete folder", systemImage: "trash", role: .destructive) { if scope == .folder(folder.id) { scope = .all }; context.delete(folder) } }204 }205 scopeButton(.trash, "Recently Deleted", "trash")206 }207 .padding(.horizontal, 16).padding(.vertical, 4)208 }209 }210211 private func scopeButton(_ value: LibraryScope, _ title: LocalizedStringKey, _ symbol: String) -> some View {212 Button { scope = value; selection = [] } label: {213 Label(title, systemImage: symbol).font(.subheadline.weight(.medium))214 .padding(.horizontal, 12).padding(.vertical, 7)215 .background(scope == value ? ORIX.Palette.cyan.opacity(0.18) : ORIX.Palette.raised, in: Capsule())216 .foregroundStyle(scope == value ? ORIX.Palette.cyan : ORIX.Palette.text)217 }218 .buttonStyle(.plain)219 .accessibilityAddTraits(scope == value ? .isSelected : [])220 }221222 @ViewBuilder private func trailingActions(_ recording: Recording) -> some View {223 if scope == .trash {224 Button(role: .destructive) { model.purge(recording) } label: { Label("Delete now", systemImage: "trash.slash") }225 Button { model.restore(recording) } label: { Label("Restore", systemImage: "arrow.uturn.backward") }.tint(ORIX.Palette.good)226 } else {227 Button(role: .destructive) { model.moveToTrash(recording) } label: { Label("Delete", systemImage: "trash") }228 }229 }230231 @ViewBuilder private func contextMenu(_ recording: Recording) -> some View {232 if scope == .trash {233 Button("Restore", systemImage: "arrow.uturn.backward") { model.restore(recording) }234 Button("Delete now", systemImage: "trash.slash", role: .destructive) { model.purge(recording) }235 } else {236 Button("Rename", systemImage: "pencil") { renameText = recording.title; renaming = recording }237 Button(recording.isFavorite ? "Unfavourite" : "Favourite", systemImage: "star") { recording.isFavorite.toggle() }238 Button("Duplicate", systemImage: "plus.square.on.square") { model.duplicate(recording) }239 Menu("Move to folder", systemImage: "folder") {240 Button("No folder") { recording.folder = nil }241 ForEach(folders) { folder in Button(folder.name) { recording.folder = folder } }242 }243 Button("Share audio", systemImage: "square.and.arrow.up") { share = SharePayload(urls: [recording.audioURL]) }244 Button("Delete", systemImage: "trash", role: .destructive) { model.moveToTrash(recording) }245 }246 }247248 @ToolbarContentBuilder private var toolbar: some ToolbarContent {249 ToolbarItem(placement: .topBarLeading) {250 if scope == .trash {251 Button("Empty", role: .destructive) { confirmEmptyTrash = true }.disabled(visible.isEmpty)252 } else {253 Button(editMode == .active ? "Done" : "Select") { withAnimation { editMode = editMode == .active ? .inactive : .active; selection = [] } }254 }255 }256 ToolbarItemGroup(placement: .topBarTrailing) {257 Menu {258 Picker("Sort", selection: $sort) { ForEach(LibrarySort.allCases) { Text($0.title).tag($0) } }259 Picker("Filter", selection: $filter) { ForEach(LibraryFilter.allCases) { Text($0.title).tag($0) } }260 Button("New folder", systemImage: "folder.badge.plus") { showNewFolder = true }261 } label: { Label("Sort and filter", systemImage: filter == .any ? "line.3.horizontal.decrease.circle" : "line.3.horizontal.decrease.circle.fill") }262 Menu {263 Button("Audio or video from Files", systemImage: "folder") { showFileImporter = true }264 Button("Video from Photos", systemImage: "photo.on.rectangle") { showPhotoPicker = true }265 } label: { Label("Import", systemImage: "square.and.arrow.down") }266 .accessibilityIdentifier("importMenu")267 }268 if editMode == .active && !selection.isEmpty {269 ToolbarItemGroup(placement: .bottomBar) {270 Button("Run action", systemImage: "bolt.fill") { showWorkflowPicker = true }271 Spacer()272 Menu("Move", systemImage: "folder") {273 Button("No folder") { for r in recordings where selection.contains(r.id) { r.folder = nil } }274 ForEach(folders) { folder in Button(folder.name) { for r in recordings where selection.contains(r.id) { r.folder = folder } } }275 }276 Spacer()277 Button("Delete", systemImage: "trash", role: .destructive) {278 for r in recordings where selection.contains(r.id) { model.moveToTrash(r) }279 selection = []; editMode = .inactive280 }281 }282 }283 }284285 /// Searches transcript text off the main thread; results merge into the title / notes matches.286 private func searchTranscripts() async {287 let q = search.trimmingCharacters(in: .whitespaces)288 guard q.count >= 2 else { transcriptMatches = []; return }289 try? await Task.sleep(for: .milliseconds(250))290 guard !Task.isCancelled else { return }291 let ids = recordings.filter { $0.transcriptStatus == .done }.map(\.id)292 let matches = await Task.detached(priority: .userInitiated) { () -> Set<UUID> in293 var out = Set<UUID>()294 for id in ids { if Task.isCancelled { break }; if let t = LibraryFiles.transcript(id), !t.search(q).isEmpty { out.insert(id) } }295 return out296 }.value297 if !Task.isCancelled { transcriptMatches = matches }298 }299}300301struct RecordingRow: View {302 @Environment(AppModel.self) private var model303 let recording: Recording304 var transcriptHit = false305306 var body: some View {307 HStack(spacing: 12) {308 WaveformThumbnail(recordingID: recording.id, revision: model.processing.revision)309 .frame(width: 64, height: 44)310 .background(ORIX.Palette.plot, in: RoundedRectangle(cornerRadius: 10, style: .continuous))311 VStack(alignment: .leading, spacing: 4) {312 HStack(spacing: 5) {313 if recording.isFavorite { Image(systemName: "star.fill").imageScale(.small).foregroundStyle(.yellow).accessibilityLabel(Text("Favourite")) }314 Text(recording.title).font(.body.weight(.medium)).lineLimit(2)315 }316 Text("\(Formatters.date(recording.createdAt)) · \(Formatters.duration(recording.duration)) · \(Formatters.bytes(recording.fileSize))")317 .font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2).fixedSize(horizontal: false, vertical: true)318 FlowLayout(spacing: 5) {319 Chip(text: recording.codec.replacingOccurrences(of: "Apple Lossless (ALAC)", with: "ALAC").replacingOccurrences(of: "Linear PCM", with: "PCM"), symbol: recording.kind.symbol)320 if recording.transcriptStatus == .done { Chip(text: String(localized: "Transcript"), symbol: "text.quote", tint: ORIX.Palette.cyan) }321 if recording.hasNotes { Chip(text: String(localized: "Notes"), symbol: "sparkles", tint: ORIX.Palette.violet) }322 if model.processing.isRunning(recording.id, .analysis) || model.processing.isRunning(recording.id, .transcription) { ProgressView().controlSize(.mini) }323 if transcriptHit { Chip(text: String(localized: "Found in transcript"), symbol: "magnifyingglass", tint: ORIX.Palette.good) }324 }325 }326 }327 .padding(.vertical, 2)328 .accessibilityElement(children: .combine)329 .accessibilityIdentifier("recordingRow")330 }331}332