SPB Git

Repository Public License

PageOrganizerView.swift 6.9 KB 160 lines swift

1// ORIX Scan2// File: App/Sources/Document/PageOrganizerView.swift3// Description: Page organizer: reorder, rotate, duplicate, delete, extract to a new document, split.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import ORIXDesign8import ORIXKit9import SwiftUI1011struct PageOrganizerView: View {12    @Environment(AppModel.self) private var model13    @Environment(\.dismiss) private var dismiss14    let documentID: UUID15    @State private var selection: Set<UUID> = []16    @State private var showSplit = false17    @State private var editMode: EditMode = .active1819    private var pages: [PageRecord] { model.manifest(documentID)?.pages ?? [] }20    private var orderedSelection: [UUID] { pages.map(\.id).filter(selection.contains) }2122    var body: some View {23        NavigationStack {24            List(selection: $selection) {25                Section {26                    ForEach(Array(pages.enumerated()), id: \.element.id) { index, page in27                        HStack(spacing: ORIX.Space.md) {28                            PageThumbnail(documentID: documentID, page: page, maxDimension: 240).frame(width: 54, height: 72)29                            VStack(alignment: .leading, spacing: 2) {30                                Text("Page \(index + 1)").font(.orixHeadline)31                                Text(page.source.isPDF ? "Imported PDF page" : "Scanned image").font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)32                            }33                        }34                        .accessibilityElement(children: .combine)35                    }36                    .onMove { source, destination in37                        var reordered = pages38                        reordered.move(fromOffsets: source, toOffset: destination)39                        ORIXHaptics.tick()40                        Task { await model.setPages(reordered, in: documentID) }41                    }42                } footer: {43                    Text("Drag to reorder. Select pages to rotate, duplicate, extract or delete them.")44                }45            }46            .environment(\.editMode, $editMode)47            .navigationTitle("Organize Pages")48            .navigationBarTitleDisplayMode(.inline)49            .toolbar {50                ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.fontWeight(.semibold) }51                ToolbarItem(placement: .topBarLeading) {52                    Button { showSplit = true } label: { Label("Split", systemImage: "square.split.2x1") }53                        .disabled(pages.count < 2)54                }55                ToolbarItemGroup(placement: .bottomBar) {56                    Button { rotate() } label: { Label("Rotate", systemImage: "rotate.right") }57                    Spacer()58                    Button { Task { for id in orderedSelection { await model.duplicatePage(id, in: documentID) } } } label: { Label("Duplicate", systemImage: "plus.square.on.square") }59                    Spacer()60                    Button { extract() } label: { Label("Extract", systemImage: "arrow.up.doc") }61                    Spacer()62                    Button(role: .destructive) {63                        let ids = selection64                        selection = []65                        Task { await model.deletePages(ids, in: documentID) }66                    } label: { Label("Delete", systemImage: "trash") }67                    .disabled(selection.count >= pages.count)68                }69            }70            .toolbar(selection.isEmpty ? .hidden : .visible, for: .bottomBar)71            .sheet(isPresented: $showSplit) { SplitSheet(documentID: documentID) { dismiss() } }72        }73    }7475    private func rotate() {76        let ids = selection77        Task { await model.updateEdits(in: documentID, pages: ids) { edit, _ in edit.quarterTurns = (edit.quarterTurns + 1) % 4 } }78    }7980    private func extract() {81        let ids = orderedSelection82        let title = model.manifest(documentID)?.title ?? ""83        Task {84            if let new = await model.derive(from: documentID, pages: ids, title: String(localized: "\(title) (extract)")) {85                dismiss()86                model.router.open(new)87            }88        }89    }90}9192/// Splits a document into several new documents. The original is kept.93struct SplitSheet: View {94    enum Mode: Hashable { case every, at }95    @Environment(AppModel.self) private var model96    @Environment(\.dismiss) private var dismiss97    let documentID: UUID98    var onDone: () -> Void99    @State private var mode: Mode = .at100    @State private var count = 1101    @State private var position = 1102103    private var pages: [PageRecord] { model.manifest(documentID)?.pages ?? [] }104105    private var groups: [[UUID]] {106        let ids = pages.map(\.id)107        switch mode {108        case .every:109            return stride(from: 0, to: ids.count, by: max(count, 1)).map { Array(ids[$0..<min($0 + max(count, 1), ids.count)]) }110        case .at:111            let cut = min(max(position, 1), max(ids.count - 1, 1))112            return [Array(ids[..<cut]), Array(ids[cut...])].filter { !$0.isEmpty }113        }114    }115116    var body: some View {117        NavigationStack {118            Form {119                Picker("Split", selection: $mode) {120                    Text("After a Page").tag(Mode.at)121                    Text("Every N Pages").tag(Mode.every)122                }123                .pickerStyle(.segmented)124                switch mode {125                case .at:126                    Stepper("After page \(position)", value: $position, in: 1...max(pages.count - 1, 1))127                case .every:128                    Stepper("Every \(count) pages", value: $count, in: 1...max(pages.count - 1, 1))129                }130                Section {131                    LabeledContent("New Documents", value: groups.count.formatted())132                } footer: {133                    Text("The original document stays in your library.")134                }135            }136            .navigationTitle("Split Document")137            .navigationBarTitleDisplayMode(.inline)138            .toolbar {139                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }140                ToolbarItem(placement: .confirmationAction) {141                    Button("Split") {142                        let parts = groups143                        let title = model.manifest(documentID)?.title ?? ""144                        Task {145                            for (n, part) in parts.enumerated() {146                                await model.derive(from: documentID, pages: part, title: String(localized: "\(title) – part \(n + 1)"))147                            }148                            model.toast = String(localized: "\(parts.count) documents created")149                            dismiss()150                            onDone()151                        }152                    }153                    .disabled(groups.count < 2)154                }155            }156        }157        .presentationDetents([.medium])158    }159}160
Files main
Menu

Theme