Repository Public License
1// ORIX Scan2// File: App/Sources/Document/DocumentView.swift3// Description: Document workspace: page grid on iPhone, page rail plus large editor on iPad; entry to text, export, page tools.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDesign8import ORIXKit9import SwiftData10import SwiftUI1112struct DocumentView: View {13 @Environment(AppModel.self) private var model14 @Environment(\.orixAccent) private var accent15 @Environment(\.horizontalSizeClass) private var sizeClass16 @Environment(\.dismiss) private var dismiss17 @Query private var records: [DocumentRecord]1819 let id: UUID20 @State private var selectedPage: UUID?21 @State private var editingPage: UUID?22 @State private var showText = false23 @State private var showExport = false24 @State private var showOrganizer = false25 @State private var showMetadata = false26 @State private var showMove = false27 @State private var renaming = false28 @State private var newTitle = ""29 @State private var loaded = false3031 init(id: UUID) {32 self.id = id33 _records = Query(filter: #Predicate<DocumentRecord> { $0.id == id })34 }3536 private var record: DocumentRecord? { records.first }37 private var manifest: DocumentManifest? { model.manifest(id) }3839 var body: some View {40 Group {41 if let manifest {42 if sizeClass == .regular { workspace(manifest) } else { grid(manifest) }43 } else if loaded {44 ORIXEmptyState(systemName: "doc.questionmark", title: "Document Unavailable", message: "This document is no longer in your library.")45 } else {46 ProgressView()47 }48 }49 .frame(maxWidth: .infinity, maxHeight: .infinity)50 .background(ORIX.Palette.desk)51 .navigationTitle(manifest?.title ?? "")52 .navigationBarTitleDisplayMode(.inline)53 .toolbar { toolbar }54 .toolbar(.hidden, for: .tabBar)55 .task(id: id) {56 await model.load(id)57 loaded = true58 if selectedPage == nil { selectedPage = model.manifest(id)?.pages.first?.id }59 }60 .navigationDestination(item: $editingPage) { pageID in61 PageEditorView(documentID: id, pageID: pageID, embedded: false)62 }63 .sheet(isPresented: $showText) { DocumentTextView(documentID: id) }64 .sheet(isPresented: $showExport) { ExportSheet(documentID: id) }65 .sheet(isPresented: $showOrganizer) { PageOrganizerView(documentID: id) }66 .sheet(isPresented: $showMetadata) { MetadataSheet(documentID: id) }67 .sheet(isPresented: $showMove) { FolderPicker(documentIDs: [id]) }68 .alert("Rename Document", isPresented: $renaming) {69 TextField("Name", text: $newTitle)70 Button("Cancel", role: .cancel) {}71 Button("Rename") { Task { await model.rename(id, to: newTitle) } }72 }73 .userActivity("ai.spboucher.orix.scan.open-document") { activity in74 activity.title = manifest?.title75 activity.isEligibleForHandoff = false76 }77 }7879 // MARK: iPhone8081 private func grid(_ manifest: DocumentManifest) -> some View {82 ScrollView {83 VStack(spacing: ORIX.Space.md) {84 statusBanner85 LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: ORIX.Space.md)], spacing: ORIX.Space.lg) {86 ForEach(Array(manifest.pages.enumerated()), id: \.element.id) { index, page in87 Button { editingPage = page.id } label: {88 VStack(spacing: ORIX.Space.xs) {89 PageThumbnail(documentID: id, page: page)90 .frame(maxWidth: .infinity)91 .frame(height: 210)92 Text(index + 1, format: .number).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary).monospacedDigit()93 }94 }95 .buttonStyle(.plain)96 .contextMenu { pageMenu(page, in: manifest) }97 .accessibilityLabel("Page \(index + 1)")98 .accessibilityHint("Opens the page editor")99 .accessibilityIdentifier("document.page")100 }101 }102 }103 .padding(ORIX.Space.md)104 }105 }106107 // MARK: iPad108109 private func workspace(_ manifest: DocumentManifest) -> some View {110 HStack(spacing: 0) {111 ScrollView {112 LazyVStack(spacing: ORIX.Space.md) {113 ForEach(Array(manifest.pages.enumerated()), id: \.element.id) { index, page in114 Button { selectedPage = page.id } label: {115 VStack(spacing: 6) {116 PageThumbnail(documentID: id, page: page, maxDimension: 360)117 .frame(maxWidth: .infinity)118 .frame(height: 190)119 .padding(6)120 .background(selectedPage == page.id ? accent.primary.opacity(0.18) : .clear,121 in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))122 Text(index + 1, format: .number).font(.orixCaption).monospacedDigit()123 .foregroundStyle(selectedPage == page.id ? accent.primary : ORIX.Palette.textSecondary)124 }125 }126 .buttonStyle(.plain)127 .contextMenu { pageMenu(page, in: manifest) }128 .accessibilityLabel("Page \(index + 1)")129 .accessibilityAddTraits(selectedPage == page.id ? .isSelected : [])130 .accessibilityIdentifier("document.page")131 }132 }133 .padding(ORIX.Space.sm)134 }135 .frame(width: 210)136 .background(ORIX.Palette.canvas)137 Divider()138 VStack(spacing: 0) {139 statusBanner.padding([.horizontal, .top], ORIX.Space.md)140 if let pageID = selectedPage ?? manifest.pages.first?.id, manifest.pages.contains(where: { $0.id == pageID }) {141 PageEditorView(documentID: id, pageID: pageID, embedded: true).id(pageID)142 } else {143 Spacer()144 }145 }146 }147 .onChange(of: manifest.pages.map(\.id)) { _, ids in148 if let current = selectedPage, !ids.contains(current) { selectedPage = ids.first }149 }150 }151152 // MARK: Shared pieces153154 @ViewBuilder private var statusBanner: some View {155 if let progress = model.recognitionProgress[id] {156 VStack(alignment: .leading, spacing: ORIX.Space.xs) {157 HStack {158 Label("Recognizing text on this device…", systemImage: "text.viewfinder").font(.orixCallout.weight(.medium))159 Spacer()160 Button("Cancel") { model.cancelRecognition(id) }.font(.orixCallout)161 }162 ORIXProgressBar(value: progress)163 }164 .orixCard(padding: ORIX.Space.sm)165 .accessibilityIdentifier("document.recognizing")166 } else if let record, !record.hasText {167 ORIXBanner(.info, title: Text("No text recognized yet"), message: Text("Recognize the text to search, copy and export a searchable PDF.")) {168 Button("Recognize") { model.startRecognition(id) }169 .buttonStyle(.borderedProminent)170 .accessibilityIdentifier("document.recognize")171 }172 }173 }174175 @ViewBuilder private func pageMenu(_ page: PageRecord, in manifest: DocumentManifest) -> some View {176 Button { Task { await model.updateEdits(in: id, pages: [page.id]) { edit, _ in edit.quarterTurns = (edit.quarterTurns + 1) % 4 } } } label: {177 Label("Rotate Right", systemImage: "rotate.right")178 }179 Button { Task { await model.duplicatePage(page.id, in: id) } } label: { Label("Duplicate", systemImage: "plus.square.on.square") }180 if !page.source.isPDF {181 Button { model.request(.scan, for: .retake(document: id, page: page.id)) } label: { Label("Retake", systemImage: "camera") }182 }183 if manifest.pages.count > 1 {184 Divider()185 Button(role: .destructive) { Task { await model.deletePages([page.id], in: id) } } label: { Label("Delete Page", systemImage: "trash") }186 }187 }188189 @ToolbarContentBuilder private var toolbar: some ToolbarContent {190 ToolbarItem(placement: .topBarTrailing) {191 Menu {192 if let record {193 Button { model.index.setFavorite([id], !record.isFavorite) } label: {194 Label(record.isFavorite ? "Remove from Favourites" : "Add to Favourites", systemImage: record.isFavorite ? "star.slash" : "star")195 }196 }197 Button { newTitle = manifest?.title ?? ""; renaming = true } label: { Label("Rename", systemImage: "pencil") }198 Button { showMove = true } label: { Label("Move to Folder", systemImage: "folder") }199 Button { showMetadata = true } label: { Label("Document Info", systemImage: "info.circle") }200 Divider()201 Button { showOrganizer = true } label: { Label("Organize Pages", systemImage: "rectangle.stack") }202 Button { model.startRecognition(id, force: true) } label: { Label("Recognize Text Again", systemImage: "arrow.clockwise") }203 .disabled(model.isRecognizing(id))204 Menu {205 ForEach(Workflow.presets.filter { $0.input == .library || $0.presetKey == "compressPDF" || $0.presetKey == "extractText" || $0.presetKey == "extractTables" || $0.presetKey == "documentCleanup" }) { workflow in206 Button { model.workflowRun = WorkflowRun(workflow: workflow, documentIDs: [id]) } label: { Label(workflow.displayName, systemImage: workflow.symbol) }207 }208 } label: { Label("Run Action", systemImage: "wand.and.stars") }209 Divider()210 Button(role: .destructive) { model.moveToTrash([id]) } label: { Label("Delete Document", systemImage: "trash") }211 } label: { Label("More", systemImage: "ellipsis.circle") }212 .accessibilityIdentifier("document.more")213 }214 ToolbarItemGroup(placement: .bottomBar) {215 Menu {216 Button { model.request(.scan, for: .append(id)) } label: { Label("Scan Pages", systemImage: "camera.viewfinder") }217 Button { model.request(.photos, for: .append(id)) } label: { Label("Add Photos", systemImage: "photo.on.rectangle") }218 Button { model.request(.files, for: .append(id)) } label: { Label("Add Files", systemImage: "folder") }219 } label: { Label("Add Pages", systemImage: "plus") }220 .accessibilityIdentifier("document.add")221 Spacer()222 Button { showOrganizer = true } label: { Label("Organize", systemImage: "rectangle.stack") }223 .accessibilityIdentifier("document.organize")224 Spacer()225 Button { showText = true } label: { Label("Text", systemImage: "text.viewfinder") }226 .accessibilityIdentifier("document.text")227 Spacer()228 Button { showExport = true } label: { Label("Export", systemImage: "square.and.arrow.up") }229 .keyboardShortcut("e", modifiers: .command)230 .accessibilityIdentifier("document.export")231 }232 }233}234235/// Title, PDF metadata and storage facts of a document.236struct MetadataSheet: View {237 @Environment(AppModel.self) private var model238 @Environment(\.dismiss) private var dismiss239 let documentID: UUID240 @State private var title = ""241 @State private var author = ""242 @State private var subject = ""243 @State private var keywords = ""244 @State private var size: Int64 = 0245246 var body: some View {247 NavigationStack {248 Form {249 Section("PDF Metadata") {250 LabeledContent("Title") { TextField("Title", text: $title).multilineTextAlignment(.trailing) }251 LabeledContent("Author") { TextField("Optional", text: $author).multilineTextAlignment(.trailing) }252 LabeledContent("Subject") { TextField("Optional", text: $subject).multilineTextAlignment(.trailing) }253 LabeledContent("Keywords") { TextField("Comma separated", text: $keywords).multilineTextAlignment(.trailing) }254 }255 if let manifest = model.manifest(documentID) {256 Section("Details") {257 LabeledContent("Pages", value: manifest.pages.count.formatted())258 LabeledContent("Created", value: manifest.createdAt.formatted(date: .abbreviated, time: .shortened))259 LabeledContent("Modified", value: manifest.modifiedAt.formatted(date: .abbreviated, time: .shortened))260 LabeledContent("Size on This Device", value: size.byteCountString)261 }262 Section {263 Text("Metadata is written into the PDFs you export. Everything is stored on this device.")264 .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)265 }266 }267 }268 .navigationTitle("Document Info")269 .navigationBarTitleDisplayMode(.inline)270 .toolbar {271 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }272 ToolbarItem(placement: .confirmationAction) {273 Button("Save") {274 let list = keywords.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }275 Task {276 await model.setMetadata(DocumentMetadata(author: author, subject: subject, keywords: list), title: title, in: documentID)277 dismiss()278 }279 }280 }281 }282 .task {283 guard let manifest = model.manifest(documentID) else { return }284 title = manifest.title285 author = manifest.metadata.author286 subject = manifest.metadata.subject287 keywords = manifest.metadata.keywords.joined(separator: ", ")288 size = await model.processor.store.byteSize(of: documentID)289 }290 }291 }292}293