Repository Public License
1// ORIX Scan2// File: App/Sources/Library/LibraryView.swift3// Description: Document library: grid or list, search, sorting, filtering, folders, batch selection, Recently Deleted.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDesign8import ORIXKit9import SwiftData10import SwiftUI1112struct LibraryView: View {13 @Environment(AppModel.self) private var model14 @Environment(\.orixAccent) private var accent15 @Environment(\.horizontalSizeClass) private var sizeClass16 @Query private var records: [DocumentRecord]17 @Query(sort: \FolderRecord.name) private var folders: [FolderRecord]1819 let scope: LibraryScope20 @State private var search = ""21 @State private var filter: LibraryFilter = .all22 @State private var selecting = false23 @State private var selection: Set<UUID> = []24 @State private var renaming: DocumentRecord?25 @State private var newTitle = ""26 @State private var moving: [UUID]?27 @State private var share: SharePayload?28 @State private var confirmEmptyTrash = false29 @State private var confirmDeleteForever: [UUID]?30 @State private var newFolderName = ""31 @State private var creatingFolder = false32 @State private var folderToRename: FolderRecord?3334 private var results: [DocumentRecord] {35 Library.query(records, scope: scope, filter: filter, search: search, sort: model.settings.librarySort, ascending: model.settings.librarySortAscending)36 }3738 private var isTrash: Bool { scope == .recentlyDeleted }3940 private var title: String {41 switch scope {42 case .all: String(localized: "Library")43 case .favorites: String(localized: "Favourites")44 case .recentlyDeleted: String(localized: "Recently Deleted")45 case .unfiled: String(localized: "Unfiled")46 case let .folder(id): folders.first { $0.id == id }?.name ?? String(localized: "Folder")47 }48 }4950 var body: some View {51 content52 .background(ORIX.Palette.canvas)53 .navigationTitle(title)54 .searchable(text: $search, prompt: "Search titles and text")55 .toolbar { toolbar }56 .safeAreaInset(edge: .bottom) { if selecting { batchBar } }57 .alert("Rename Document", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {58 TextField("Name", text: $newTitle)59 Button("Cancel", role: .cancel) {}60 Button("Rename") { if let r = renaming { Task { await model.rename(r.id, to: newTitle) } } }61 }62 .alert("New Folder", isPresented: $creatingFolder) {63 TextField("Name", text: $newFolderName)64 Button("Cancel", role: .cancel) { newFolderName = "" }65 Button("Create") { model.index.folder(named: newFolderName); newFolderName = "" }66 }67 .alert("Rename Folder", isPresented: Binding(get: { folderToRename != nil }, set: { if !$0 { folderToRename = nil } })) {68 TextField("Name", text: $newFolderName)69 Button("Cancel", role: .cancel) { newFolderName = "" }70 Button("Rename") {71 let name = newFolderName.trimmingCharacters(in: .whitespacesAndNewlines)72 if !name.isEmpty { folderToRename?.name = name; try? model.index.context.save() }73 newFolderName = ""74 }75 }76 .sheet(item: Binding(get: { moving.map(MoveRequest.init) }, set: { if $0 == nil { moving = nil } })) { request in77 FolderPicker(documentIDs: request.ids) { selecting = false; selection = [] }78 }79 .sheet(item: $share) { payload in ShareSheet(items: payload.urls) }80 .confirmationDialog("Delete all documents in Recently Deleted? This can't be undone.", isPresented: $confirmEmptyTrash, titleVisibility: .visible) {81 Button("Delete All", role: .destructive) { Task { await model.deletePermanently(results.map(\.id)) } }82 }83 .confirmationDialog("These documents will be deleted permanently. This can't be undone.",84 isPresented: Binding(get: { confirmDeleteForever != nil }, set: { if !$0 { confirmDeleteForever = nil } }), titleVisibility: .visible) {85 Button("Delete Permanently", role: .destructive) {86 if let ids = confirmDeleteForever { Task { await model.deletePermanently(ids) } }87 selecting = false; selection = []88 }89 }90 }9192 private struct MoveRequest: Identifiable {93 let ids: [UUID]94 var id: String { ids.map(\.uuidString).joined() }95 }9697 // MARK: Content9899 @ViewBuilder private var content: some View {100 if results.isEmpty && (scope != .all || folders.isEmpty || !search.isEmpty) {101 emptyState102 } else {103 ScrollView {104 VStack(alignment: .leading, spacing: ORIX.Space.lg) {105 if scope == .all && search.isEmpty && sizeClass != .regular && !folders.isEmpty { folderStrip }106 if isTrash {107 ORIXBanner(.info, title: Text("Documents are kept for \(Library.retentionDays) days"),108 message: Text("After that they are deleted from this device for good."))109 }110 if filter != .all {111 HStack {112 ORIXChip(Text(filter.title), systemName: "line.3.horizontal.decrease", tint: accent.primary)113 Button("Clear") { filter = .all }.font(.orixCaption)114 }115 }116 if model.settings.libraryShowsList {117 LazyVStack(spacing: 0) {118 ForEach(results) { record in119 item(record) { DocumentRow(record: record, selected: selecting ? selection.contains(record.id) : nil) }120 Divider().padding(.leading, 60)121 }122 }123 .padding(.horizontal, ORIX.Space.sm)124 .orixCard(padding: 4)125 } else {126 LazyVGrid(columns: [GridItem(.adaptive(minimum: sizeClass == .regular ? 190 : 150), spacing: ORIX.Space.md)], spacing: ORIX.Space.lg) {127 ForEach(results) { record in128 item(record) { DocumentCard(record: record, selected: selecting ? selection.contains(record.id) : nil) }129 }130 }131 }132 }133 .padding(ORIX.Space.md)134 }135 }136 }137138 private func item<Content: View>(_ record: DocumentRecord, @ViewBuilder label: () -> Content) -> some View {139 Button {140 if selecting {141 if selection.contains(record.id) { selection.remove(record.id) } else { selection.insert(record.id) }142 ORIXHaptics.tick()143 } else if !isTrash {144 model.router.open(record.id)145 }146 } label: { label() }147 .buttonStyle(.plain)148 .accessibilityIdentifier("library.document")149 .contextMenu {150 if isTrash {151 Button { model.restore([record.id]) } label: { Label("Restore", systemImage: "arrow.uturn.backward") }152 Button(role: .destructive) { confirmDeleteForever = [record.id] } label: { Label("Delete Permanently", systemImage: "trash") }153 } else {154 DocumentMenuItems(record: record, onRename: { newTitle = record.title; renaming = record }, onMove: { moving = [record.id] })155 }156 }157 .draggable(DocumentTransfer(id: record.id, title: record.title, processor: model.processor)) {158 DocumentThumbnail(id: record.id).frame(width: 90).environment(model)159 }160 }161162 private var folderStrip: some View {163 ScrollView(.horizontal, showsIndicators: false) {164 HStack(spacing: ORIX.Space.xs) {165 ForEach(folders) { folder in166 Button { model.router.push(.library(.folder(folder.id))) } label: {167 HStack(spacing: 6) {168 Image(systemName: "folder.fill").foregroundStyle(accent.primary)169 Text(folder.name).foregroundStyle(ORIX.Palette.textPrimary)170 Text(folder.documents.filter { $0.deletedAt == nil }.count, format: .number).foregroundStyle(ORIX.Palette.textSecondary)171 }172 .font(.orixCallout.weight(.medium))173 .padding(.horizontal, ORIX.Space.sm)174 .frame(minHeight: ORIX.minimumTarget)175 .background(ORIX.Palette.surface, in: Capsule())176 }177 .buttonStyle(.plain)178 .contextMenu {179 Button { newFolderName = folder.name; folderToRename = folder } label: { Label("Rename", systemImage: "pencil") }180 Button(role: .destructive) { model.index.deleteFolder(folder) } label: { Label("Delete Folder", systemImage: "trash") }181 }182 }183 }184 .padding(.horizontal, ORIX.Space.md)185 }186 .padding(.horizontal, -ORIX.Space.md)187 }188189 @ViewBuilder private var emptyState: some View {190 if !search.isEmpty {191 ORIXEmptyState(systemName: "magnifyingglass", title: "No Results", message: "No document title or recognized text matches your search.")192 } else if isTrash {193 ORIXEmptyState(systemName: "trash", title: "Nothing Deleted", message: "Documents you delete stay here for 30 days before they are removed.")194 } else if scope == .favorites {195 ORIXEmptyState(systemName: "star", title: "No Favourites", message: "Mark documents as favourites to find them here.")196 } else if case .folder = scope {197 ORIXEmptyState(systemName: "folder", title: "Empty Folder", message: "Move documents here from the library.")198 } else {199 ORIXEmptyState(systemName: "books.vertical", title: "Your Library Is Empty", message: "Scan a document or import photos and files to get started.") {200 Button { model.request(.scan) } label: { Label("Scan Document", systemImage: "camera.viewfinder") }201 .buttonStyle(.orixPrimary)202 .accessibilityIdentifier("library.empty.scan")203 Button { model.request(.files) } label: { Label("Import Files", systemImage: "folder") }204 .buttonStyle(.orixSecondary)205 }206 }207 }208209 // MARK: Toolbar210211 @ToolbarContentBuilder private var toolbar: some ToolbarContent {212 ToolbarItem(placement: .topBarTrailing) {213 if selecting {214 Button("Done") { selecting = false; selection = [] }.fontWeight(.semibold)215 } else {216 Menu {217 if !isTrash {218 Button { selecting = true } label: { Label("Select", systemImage: "checkmark.circle") }219 Button { creatingFolder = true } label: { Label("New Folder", systemImage: "folder.badge.plus") }220 Divider()221 } else if !results.isEmpty {222 Button { selecting = true } label: { Label("Select", systemImage: "checkmark.circle") }223 Button(role: .destructive) { confirmEmptyTrash = true } label: { Label("Delete All", systemImage: "trash") }224 Divider()225 }226 Picker("View", selection: Binding(get: { model.settings.libraryShowsList }, set: { model.settings.libraryShowsList = $0 })) {227 Label("Grid", systemImage: "square.grid.2x2").tag(false)228 Label("List", systemImage: "list.bullet").tag(true)229 }230 Menu {231 Picker("Sort By", selection: Binding(get: { model.settings.librarySort }, set: { model.settings.librarySort = $0 })) {232 ForEach(LibrarySort.allCases) { Text($0.title).tag($0) }233 }234 Picker("Order", selection: Binding(get: { model.settings.librarySortAscending }, set: { model.settings.librarySortAscending = $0 })) {235 Text("Descending").tag(false)236 Text("Ascending").tag(true)237 }238 } label: { Label("Sort", systemImage: "arrow.up.arrow.down") }239 if !isTrash {240 Picker(selection: $filter) {241 ForEach(LibraryFilter.allCases) { Text($0.title).tag($0) }242 } label: { Label("Filter", systemImage: "line.3.horizontal.decrease") }243 .pickerStyle(.menu)244 }245 } label: { Label("Options", systemImage: "ellipsis.circle") }246 .accessibilityIdentifier("library.options")247 }248 }249 if selecting {250 ToolbarItem(placement: .topBarLeading) {251 Button(selection.count == results.count ? "Deselect All" : "Select All") {252 selection = selection.count == results.count ? [] : Set(results.map(\.id))253 }254 }255 }256 }257258 // MARK: Batch actions259260 private var batchBar: some View {261 let ids = results.map(\.id).filter(selection.contains)262 return HStack {263 if isTrash {264 batchButton("Restore", symbol: "arrow.uturn.backward") { model.restore(ids); selecting = false; selection = [] }265 Spacer()266 batchButton("Delete", symbol: "trash", role: .destructive) { confirmDeleteForever = ids }267 } else {268 batchButton("Export", symbol: "square.and.arrow.up") { Task { await batchExport(ids) } }269 Spacer()270 batchButton("Move", symbol: "folder") { moving = ids }271 Spacer()272 batchButton("Favourite", symbol: "star") { model.index.setFavorite(ids, true); selecting = false; selection = [] }273 Spacer()274 batchButton("Merge", symbol: "arrow.triangle.merge") {275 Task {276 if let id = await model.merge(ids) { selecting = false; selection = []; model.router.open(id) }277 }278 }279 .disabled(ids.count < 2)280 Spacer()281 batchButton("Delete", symbol: "trash", role: .destructive) { model.moveToTrash(ids); selecting = false; selection = [] }282 }283 }284 .disabled(ids.isEmpty)285 .padding(.horizontal, ORIX.Space.md)286 .padding(.vertical, ORIX.Space.xs)287 .background(.bar)288 .overlay(alignment: .top) { Divider() }289 }290291 private func batchButton(_ title: LocalizedStringKey, symbol: String, role: ButtonRole? = nil, action: @escaping () -> Void) -> some View {292 Button(role: role, action: action) {293 VStack(spacing: 2) {294 Image(systemName: symbol).font(.body.weight(.medium))295 Text(title).font(.caption2)296 }297 .frame(minWidth: ORIX.minimumTarget, minHeight: ORIX.minimumTarget)298 }299 }300301 /// Exports every selected document as a PDF with the default settings and hands the files to the share sheet.302 private func batchExport(_ ids: [UUID]) async {303 var urls: [URL] = []304 let options = ExportOptions(preset: model.settings.exportPreset, searchable: true, pageSize: model.settings.pageSize)305 let task = Task {306 for (n, id) in ids.enumerated() {307 if Task.isCancelled { break }308 model.activity?.detail = String(localized: "\(n + 1) of \(ids.count)")309 model.activity?.fraction = Double(n) / Double(ids.count)310 if let result = await model.attempt({ try await model.processor.exportPDF(id, options: options) }) { urls.append(result.url) }311 }312 }313 model.activity = Activity(title: String(localized: "Exporting…"), fraction: 0, task: task)314 await task.value315 model.activity = nil316 if !urls.isEmpty && !task.isCancelled { share = SharePayload(urls: urls) }317 selecting = false318 selection = []319 }320}321322/// Sheet listing folders, to file one or more documents.323struct FolderPicker: View {324 @Environment(AppModel.self) private var model325 @Environment(\.dismiss) private var dismiss326 @Query(sort: \FolderRecord.name) private var folders: [FolderRecord]327 let documentIDs: [UUID]328 var onDone: () -> Void = {}329 @State private var name = ""330331 var body: some View {332 NavigationStack {333 List {334 Section {335 Button { move(to: nil) } label: { Label("No Folder", systemImage: "tray") }336 ForEach(folders) { folder in337 Button { move(to: folder) } label: { Label(folder.name, systemImage: "folder") }338 }339 }340 Section("New Folder") {341 HStack {342 TextField("Name", text: $name).submitLabel(.done).onSubmit(create)343 Button("Create", action: create).disabled(name.trimmingCharacters(in: .whitespaces).isEmpty)344 }345 }346 }347 .navigationTitle("Move to Folder")348 .navigationBarTitleDisplayMode(.inline)349 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }350 }351 .presentationDetents([.medium, .large])352 }353354 private func create() {355 if let folder = model.index.folder(named: name) { move(to: folder) }356 }357358 private func move(to folder: FolderRecord?) {359 model.index.move(documentIDs, to: folder)360 ORIXHaptics.tick()361 onDone()362 dismiss()363 }364}365366/// Dragging a document out of the app delivers its PDF, built when the drop happens.367struct DocumentTransfer: Transferable {368 let id: UUID369 let title: String370 let processor: DocumentProcessor371372 static var transferRepresentation: some TransferRepresentation {373 FileRepresentation(exportedContentType: .pdf) { item in374 let result = try await item.processor.exportPDF(item.id)375 return SentTransferredFile(result.url)376 }377 .suggestedFileName { $0.title }378 }379}380