SPB Git

Repository Public

PDFAnnotationScreen.swift 25.3 KB 519 lines swift

1// SP Notes iOS2// File: Features/PDF/PDFAnnotationScreen.swift3// Description: The detail screen of a `pdf` block: reads the PDF with PDFKit and annotates it — Pencil ink on a transparent4//              PencilKit overlay per page, text highlights from a selection, pinned notes — with the list of annotations and a5//              page jump. Annotations live in the block's attributes (normalised coordinates, SPEC §2) and are drawn as overlays:6//              the PDF file is never modified.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import PDFKit11import PencilKit12import SPNotesCore13import SPNotesDesign14import SwiftUI15import UIKit1617struct PDFAnnotationScreen: View {18    let context: BlockDetailContext19    @State private var model: PDFAnnotationModel20    @State private var showsList = false21    @State private var showsPageJump = false22    @State private var pageText = ""23    @State private var fingerDrawing = DrawingModel.defaultFingerDrawing24    @State private var highlightRequest = 02526    init(node: PMNode, context: BlockDetailContext) {27        self.context = context28        _model = State(initialValue: PDFAnnotationModel(block: PDFBlock(node: node) ?? PDFBlock(attachmentId: "", name: ""), isEditable: context.isEditable, commit: context.commit))29    }3031    /// Standalone presentation with a model made elsewhere (previews, tests, debug routes).32    init(model: PDFAnnotationModel, context: BlockDetailContext, showsList: Bool = false) {33        self.context = context34        _model = State(initialValue: model)35        _showsList = State(initialValue: showsList)36    }3738    var body: some View {39        NavigationStack {40            content41                .background(NVColor.bgSunken)42                .navigationTitle(Text(verbatim: model.block.name.isEmpty ? String(localized: "PDF") : model.block.name))43                .navigationBarTitleDisplayMode(.inline)44                .toolbar { toolbar }45        }46        .task { await model.load(app: context.app) }47        .sheet(isPresented: $showsList) {48            PDFAnnotationList(model: model) { showsList = false }49        }50        .sheet(item: Binding(get: { model.editing }, set: { model.editing = $0 })) { annotation in51            PDFAnnotationEditor(annotation: annotation, isEditable: model.isEditable, onSave: { model.update($0); model.editing = nil },52                                onDelete: { model.remove(annotation.id) }, onClose: { model.editing = nil })53        }54        .alert(Text("Aller à la page"), isPresented: $showsPageJump) {55            TextField(String(localized: "Numéro de page"), text: $pageText).keyboardType(.numberPad)56            Button("Aller") { if let page = Int(pageText.trimmingCharacters(in: .whitespaces)) { model.go(toPage: page) } }57            Button("Annuler", role: .cancel) {}58        } message: { Text("De 1 à \(model.pageCount)") }59    }6061    @ViewBuilder private var content: some View {62        switch model.phase {63        case .loading:64            ProgressView().accessibilityLabel(Text("Ouverture du PDF")).frame(maxWidth: .infinity, maxHeight: .infinity)65        case .failed(let message):66            NVEmptyState(systemImage: "doc.richtext", title: String(localized: "PDF indisponible"), message: message)67                .accessibilityIdentifier("pdf-unavailable")68        case .ready:69            PDFAnnotationView(model: model, fingerDrawing: fingerDrawing, highlightRequest: highlightRequest)70                .ignoresSafeArea(edges: .bottom)71                .overlay(alignment: .bottom) { if model.isEditable { tools.padding(.bottom, NVSpace.lg).padding(.horizontal, NVSpace.md) } }72                .overlay(alignment: .top) {73                    if model.isEditable, model.tool == .select, model.hasSelection {74                        Button { highlightRequest += 1 } label: {75                            Label("Surligner", systemImage: "highlighter").nvFont(.uiStrong).foregroundStyle(NVColor.fg)76                                .padding(.horizontal, NVSpace.lg).frame(minHeight: 44)77                        }78                        .buttonStyle(.plain)79                        .nvGlass(radius: NVRadius.pill)80                        .padding(.top, NVSpace.md)81                        .accessibilityIdentifier("pdf-highlight-selection")82                        .transition(.opacity)83                    }84                }85                .nvAnimation(.fast, value: model.hasSelection)86        }87    }8889    // MARK: tools9091    private var tools: some View {92        VStack(spacing: NVSpace.sm) {93            if let hint { Text(hint).nvFont(.micro).foregroundStyle(NVColor.fgMuted).padding(.horizontal, NVSpace.md).padding(.vertical, NVSpace.xs + 1).nvGlass(radius: NVRadius.pill) }94            NVToolbarGlass(spacing: NVSpace.xs) {95                toolButton(.select, title: "Sélection", symbol: "character.cursor.ibeam")96                toolButton(.ink, title: "Stylo", symbol: "pencil.tip")97                toolButton(.note, title: "Note", symbol: "note.text")98                Rectangle().fill(NVColor.lineStrong).frame(width: 1, height: 22).padding(.horizontal, NVSpace.xxs).accessibilityHidden(true)99                ForEach(model.tool == .ink ? PDFAnnotationFactory.inkColors : PDFAnnotationFactory.highlightColors, id: \.self) { hex in100                    swatch(hex)101                }102                if model.tool == .ink {103                    Rectangle().fill(NVColor.lineStrong).frame(width: 1, height: 22).padding(.horizontal, NVSpace.xxs).accessibilityHidden(true)104                    Button {105                        fingerDrawing.toggle()106                        UserDefaults.standard.set(fingerDrawing, forKey: DrawingModel.fingerDrawingKey)107                        Haptics.selection()108                    } label: {109                        Image(systemName: fingerDrawing ? "hand.draw.fill" : "hand.draw").frame(minWidth: 40, minHeight: 40)110                            .foregroundStyle(fingerDrawing ? NVColor.accent : NVColor.fg)111                    }112                    .accessibilityLabel(Text("Dessiner au doigt"))113                    .accessibilityValue(fingerDrawing ? Text("Activé") : Text("Désactivé"))114                    .accessibilityIdentifier("pdf-finger-toggle")115                }116            }117        }118        .nvAnimation(.fast, value: model.tool)119    }120121    private var hint: LocalizedStringKey? {122        switch model.tool {123        case .select: nil124        case .ink: fingerDrawing ? "Dessine sur la page" : "Dessine avec l’Apple Pencil — le doigt fait défiler"125        case .note: "Touche la page pour y épingler une note"126        }127    }128129    private func toolButton(_ tool: PDFAnnotationModel.Tool, title: LocalizedStringKey, symbol: String) -> some View {130        let isOn = model.tool == tool131        return Button {132            model.tool = tool133            Haptics.selection()134        } label: {135            HStack(spacing: NVSpace.xs) {136                Image(systemName: symbol).imageScale(.medium)137                Text(title).nvFont(.uiStrong).lineLimit(1)138            }139            .foregroundStyle(isOn ? NVColor.accentFg : NVColor.fg)140            .padding(.horizontal, NVSpace.md)141            .frame(minHeight: 36)142            .background(isOn ? AnyShapeStyle(NVColor.accent) : AnyShapeStyle(Color.clear), in: Capsule())143            .contentShape(Capsule())144        }145        .buttonStyle(.plain)146        .accessibilityLabel(Text(title))147        .accessibilityAddTraits(isOn ? .isSelected : [])148        .accessibilityIdentifier("pdf-tool-\(tool.rawValue)")149    }150151    private func swatch(_ hex: String) -> some View {152        let isInk = model.tool == .ink153        let isOn = (isInk ? model.inkColor : model.highlightColor) == hex154        return Button {155            if isInk { model.inkColor = hex } else { model.highlightColor = hex }156            Haptics.selection()157        } label: {158            Circle().fill(Color(uiColor: PDFAnnotationFactory.color(hex)))159                .frame(width: 22, height: 22)160                .overlay(Circle().strokeBorder(NVColor.lineStrong, lineWidth: 1))161                .padding(4)162                .overlay(Circle().strokeBorder(isOn ? NVColor.accent : .clear, lineWidth: 2))163                .frame(minWidth: 36, minHeight: 40)164                .contentShape(Rectangle())165        }166        .buttonStyle(.plain)167        .accessibilityLabel(Text(PDFAnnotationList.colorName(hex)))168        .accessibilityAddTraits(isOn ? .isSelected : [])169    }170171    @ToolbarContentBuilder private var toolbar: some ToolbarContent {172        ToolbarItem(placement: .cancellationAction) {173            Button {174                model.commitPageIfNeeded()175                context.dismiss()176            } label: { Text("Fermer") }177                .accessibilityIdentifier("pdf-close")178        }179        ToolbarItemGroup(placement: .primaryAction) {180            if model.phase == .ready {181                Button {182                    pageText = ""183                    showsPageJump = true184                } label: { Text(verbatim: "\(model.currentPage) / \(model.pageCount)").monospacedDigit() }185                    .accessibilityLabel(Text("Page \(model.currentPage) sur \(model.pageCount). Aller à une page"))186                    .accessibilityIdentifier("pdf-page-indicator")187                Button { showsList = true } label: {188                    Label("Annotations", systemImage: model.annotations.isEmpty ? "list.bullet.rectangle" : "list.bullet.rectangle.fill")189                }190                .accessibilityValue(Text(verbatim: "\(model.annotations.count)"))191                .accessibilityIdentifier("pdf-annotations-list")192            }193        }194    }195}196197// MARK: - PDFKit view198199private struct PDFAnnotationView: UIViewRepresentable {200    let model: PDFAnnotationModel201    let fingerDrawing: Bool202    let highlightRequest: Int203204    func makeCoordinator() -> PDFAnnotationCoordinator { PDFAnnotationCoordinator(model: model) }205206    func makeUIView(context: Context) -> PDFView {207        let view = PDFView()208        view.backgroundColor = UIColor(NVColor.bgSunken)209        view.displayMode = .singlePageContinuous210        view.displayDirection = .vertical211        view.autoScales = true212        view.pageShadowsEnabled = true213        view.pageOverlayViewProvider = context.coordinator214        view.document = model.document215        view.accessibilityIdentifier = "pdf-view"216        context.coordinator.attach(to: view)217        if let page = model.document?.page(at: model.currentPage - 1) { view.go(to: page) }218        return view219    }220221    func updateUIView(_ view: PDFView, context: Context) {222        let coordinator = context.coordinator223        coordinator.apply(tool: model.tool, fingerDrawing: fingerDrawing, color: model.inkColor, width: model.inkWidth, revision: model.revision)224        if let request = model.pageRequest {225            if let page = view.document?.page(at: request - 1) { view.go(to: page) }226            DispatchQueue.main.async { model.pageRequest = nil }227        }228        if coordinator.handledHighlightRequest != highlightRequest {229            coordinator.handledHighlightRequest = highlightRequest230            if let selection = view.currentSelection, model.highlight(selection) > 0 { view.clearSelection() }231        }232    }233234    static func dismantleUIView(_ view: PDFView, coordinator: PDFAnnotationCoordinator) { coordinator.detach() }235}236237/// Glue between PDFKit and the model: the per-page overlays, page changes, selection changes and taps.238@MainActor239final class PDFAnnotationCoordinator: NSObject, @preconcurrency PDFPageOverlayViewProvider, UIGestureRecognizerDelegate {240    let model: PDFAnnotationModel241    private weak var view: PDFView?242    private var overlays: [Int: PDFPageOverlayView] = [:]243    private var observers: [NSObjectProtocol] = []244    private var shown: (tool: PDFAnnotationModel.Tool, finger: Bool, color: String, width: CGFloat, revision: Int)?245    var handledHighlightRequest = 0246247    init(model: PDFAnnotationModel) { self.model = model }248249    func attach(to view: PDFView) {250        self.view = view251        let center = NotificationCenter.default252        observers.append(center.addObserver(forName: .PDFViewPageChanged, object: view, queue: .main) { [weak self] _ in253            MainActor.assumeIsolated { self?.pageChanged() }254        })255        observers.append(center.addObserver(forName: .PDFViewSelectionChanged, object: view, queue: .main) { [weak self] _ in256            MainActor.assumeIsolated { self?.selectionChanged() }257        })258        let tap = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))259        tap.delegate = self260        view.addGestureRecognizer(tap)261    }262263    func detach() {264        observers.forEach(NotificationCenter.default.removeObserver)265        observers = []266    }267268    private func pageChanged() {269        guard let view, let page = view.currentPage, let index = view.document?.index(for: page), index != NSNotFound else { return }270        model.pageChanged(to: index + 1)271    }272273    private func selectionChanged() {274        let text = view?.currentSelection?.string?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""275        model.hasSelection = !text.isEmpty276    }277278    func apply(tool: PDFAnnotationModel.Tool, fingerDrawing: Bool, color: String, width: CGFloat, revision: Int) {279        if let shown, shown == (tool, fingerDrawing, color, width, revision) { return }280        let annotationsChanged = shown?.revision != revision281        shown = (tool, fingerDrawing, color, width, revision)282        // in markup mode PDFKit leaves the touches of the page to the overlay (no text selection under the Pencil)283        view?.isInMarkupMode = tool == .ink284        for overlay in overlays.values {285            configure(overlay)286            if annotationsChanged { overlay.show(model.annotations(onPage: overlay.pageNumber)) }287        }288    }289290    private func configure(_ overlay: PDFPageOverlayView) {291        let color = PDFAnnotationFactory.color(model.inkColor)292        overlay.configure(inkEnabled: model.isEditable && model.tool == .ink, fingerDrawing: shown?.finger ?? false, tool: PKInkingTool(.pen, color: color, width: model.inkWidth))293    }294295    // MARK: PDFPageOverlayViewProvider296297    func pdfView(_ view: PDFView, overlayViewFor page: PDFPage) -> UIView? {298        guard let index = view.document?.index(for: page), index != NSNotFound else { return nil }299        let number = index + 1300        let overlay = overlays[number] ?? PDFPageOverlayView(pageNumber: number)301        overlays[number] = overlay302        overlay.onStroke = { [weak self, weak overlay] points, ink, width in303            guard let self, let overlay else { return }304            let color = InkConversion.inkColor(ink.color)305            self.model.addInk(viewPoints: points, in: overlay.bounds.size, page: number, color: String(color.hex.prefix(7)), lineWidth: width, opacity: color.opacity)306        }307        configure(overlay)308        overlay.show(model.annotations(onPage: number))309        return overlay310    }311312    func pdfView(_ pdfView: PDFView, willEndDisplayingOverlayView overlayView: UIView, for page: PDFPage) {313        if let overlay = overlayView as? PDFPageOverlayView { overlays[overlay.pageNumber] = nil }314    }315316    // MARK: taps (open an annotation, pin a note)317318    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }319320    @objc private func tapped(_ gesture: UITapGestureRecognizer) {321        guard let view, model.tool != .ink else { return }322        let location = gesture.location(in: view)323        guard let page = view.page(for: location, nearest: false), let index = view.document?.index(for: page), index != NSNotFound else { return }324        let geometry = PDFPageGeometry(page: page)325        let point = geometry.normalized(view.convert(location, to: page))326        guard point.x >= 0, point.x <= 1, point.y >= 0, point.y <= 1 else { return }327        if model.tool == .note {328            let size = geometry.displaySize329            model.addNote(at: point, page: index + 1, pageAspect: size.height > 0 ? Double(size.width / size.height) : 1)330        } else {331            model.tap(at: point, page: index + 1)332        }333    }334}335336// MARK: - list337338struct PDFAnnotationList: View {339    let model: PDFAnnotationModel340    var onClose: () -> Void341342    var body: some View {343        NavigationStack {344            Group {345                if model.annotations.isEmpty {346                    NVEmptyState(systemImage: "highlighter", title: String(localized: "Aucune annotation"),347                                 message: String(localized: "Sélectionne du texte pour le surligner, dessine avec le stylo ou épingle une note sur la page."))348                } else {349                    List {350                        ForEach(pages, id: \.self) { page in351                            Section {352                                ForEach(model.annotations(onPage: page)) { annotation in353                                    Button {354                                        model.go(toPage: annotation.page)355                                        onClose()356                                    } label: { Self.row(annotation) }357                                    .buttonStyle(.plain)358                                    .swipeActions(edge: .trailing, allowsFullSwipe: true) {359                                        if model.isEditable {360                                            Button(role: .destructive) { model.remove(annotation.id) } label: { Label("Supprimer", systemImage: "trash") }361                                        }362                                    }363                                    .swipeActions(edge: .leading) {364                                        Button { onClose(); model.editing = annotation } label: { Label("Modifier", systemImage: "square.and.pencil") }.tint(NVColor.accent)365                                    }366                                    .contextMenu {367                                        Button { onClose(); model.editing = annotation } label: { Label("Modifier", systemImage: "square.and.pencil") }368                                        if model.isEditable { Button(role: .destructive) { model.remove(annotation.id) } label: { Label("Supprimer", systemImage: "trash") } }369                                    }370                                    .accessibilityIdentifier("pdf-annotation-row")371                                }372                            } header: { Text("Page \(page)") }373                        }374                    }375                    .listStyle(.insetGrouped)376                    .scrollContentBackground(.hidden)377                }378            }379            .background(NVColor.bg)380            .navigationTitle(Text("Annotations"))381            .navigationBarTitleDisplayMode(.inline)382            .toolbar { ToolbarItem(placement: .confirmationAction) { Button(action: onClose) { Text("OK").bold() }.accessibilityIdentifier("pdf-list-close") } }383        }384        .pencilSheetDetents()385    }386387    private var pages: [Int] { Array(Set(model.annotations.map(\.page))).sorted() }388389    static func kindName(_ kind: PDFAnnotationKind) -> String {390        switch kind {391        case .highlight: String(localized: "Surlignage")392        case .note: String(localized: "Note")393        case .ink: String(localized: "Trait")394        default: String(localized: "Annotation")395        }396    }397398    static func symbol(_ kind: PDFAnnotationKind) -> String {399        switch kind {400        case .highlight: "highlighter"401        case .note: "note.text"402        case .ink: "scribble"403        default: "questionmark.square.dashed"404        }405    }406407    static func colorName(_ hex: String) -> String {408        switch hex.lowercased() {409        case "#ffd54a": String(localized: "Jaune")410        case "#7ee081", "#008b4e": String(localized: "Vert")411        case "#7cc4ff", "#2f5ddb": String(localized: "Bleu")412        case "#ff9ec4": String(localized: "Rose")413        case "#cc272e": String(localized: "Rouge")414        case "#151922": String(localized: "Noir")415        default: hex416        }417    }418419    /// What a row says: the highlighted text, the note, or the kind when there is neither.420    static func title(_ annotation: PDFAnnotation) -> String {421        let text = annotation.text.trimmingCharacters(in: .whitespacesAndNewlines), note = annotation.note.trimmingCharacters(in: .whitespacesAndNewlines)422        if !text.isEmpty { return text }423        if !note.isEmpty { return note }424        return annotation.kind == .note ? String(localized: "Note vide") : kindName(annotation.kind)425    }426427    @ViewBuilder static func row(_ annotation: PDFAnnotation) -> some View {428        let text = annotation.text.trimmingCharacters(in: .whitespacesAndNewlines), note = annotation.note.trimmingCharacters(in: .whitespacesAndNewlines)429        HStack(alignment: .top, spacing: NVSpace.md) {430            Image(systemName: symbol(annotation.kind))431                .foregroundStyle(NVColor.fg)432                .frame(width: 32, height: 32)433                .background(Color(uiColor: PDFAnnotationFactory.color(annotation.color)).opacity(annotation.kind == .ink ? 0.25 : 0.6), in: RoundedRectangle(cornerRadius: NVRadius.sm, style: .continuous))434                .accessibilityHidden(true)435            VStack(alignment: .leading, spacing: NVSpace.xxs) {436                Text(verbatim: title(annotation)).nvFont(.body).foregroundStyle(NVColor.fg).lineLimit(3)437                if !text.isEmpty, !note.isEmpty { Text(verbatim: note).nvFont(.ui).foregroundStyle(NVColor.fgMuted).lineLimit(3) }438                Text(verbatim: text.isEmpty && note.isEmpty && annotation.kind != .note ? colorName(annotation.color) : "\(kindName(annotation.kind)) · \(colorName(annotation.color))")439                    .nvFont(.micro).foregroundStyle(NVColor.fgMuted)440            }441            Spacer(minLength: 0)442        }443        .padding(.vertical, NVSpace.xxs)444        .contentShape(Rectangle())445        .accessibilityElement(children: .combine)446    }447}448449// MARK: - editor of one annotation450451struct PDFAnnotationEditor: View {452    @State var annotation: PDFAnnotation453    let isEditable: Bool454    var onSave: (PDFAnnotation) -> Void455    var onDelete: () -> Void456    var onClose: () -> Void457    @FocusState private var noteFocused: Bool458459    var body: some View {460        NavigationStack {461            Form {462                if !annotation.text.isEmpty {463                    Section { Text(verbatim: annotation.text).nvFont(.reading).foregroundStyle(NVColor.fg).textSelection(.enabled) } header: { Text("Texte surligné") }464                }465                Section {466                    TextEditor(text: Binding(get: { annotation.note }, set: { annotation.note = $0 }))467                        .frame(minHeight: 110)468                        .focused($noteFocused)469                        .disabled(!isEditable)470                        .accessibilityIdentifier("pdf-annotation-note")471                } header: { Text("Note") }472                if isEditable {473                    Section {474                        HStack(spacing: NVSpace.md) {475                            ForEach(annotation.kind == .ink ? PDFAnnotationFactory.inkColors : PDFAnnotationFactory.highlightColors, id: \.self) { hex in476                                Button { annotation.color = hex } label: {477                                    Circle().fill(Color(uiColor: PDFAnnotationFactory.color(hex))).frame(width: 30, height: 30)478                                        .overlay(Circle().strokeBorder(NVColor.lineStrong, lineWidth: 1))479                                        .padding(4)480                                        .overlay(Circle().strokeBorder(annotation.color.lowercased() == hex ? NVColor.accent : .clear, lineWidth: 2))481                                }482                                .buttonStyle(.plain)483                                .accessibilityLabel(Text(PDFAnnotationList.colorName(hex)))484                                .accessibilityAddTraits(annotation.color.lowercased() == hex ? .isSelected : [])485                            }486                        }487                    } header: { Text("Couleur") }488                    Section {489                        Button(role: .destructive, action: onDelete) { Label("Supprimer l’annotation", systemImage: "trash") }490                            .accessibilityIdentifier("pdf-annotation-delete")491                    }492                }493            }494            .navigationTitle(Text(verbatim: "\(PDFAnnotationList.kindName(annotation.kind)) — \(String(localized: "page")) \(annotation.page)"))495            .navigationBarTitleDisplayMode(.inline)496            .toolbar {497                ToolbarItem(placement: .cancellationAction) { Button(action: onClose) { Text(isEditable ? "Annuler" : "Fermer") } }498                if isEditable {499                    ToolbarItem(placement: .confirmationAction) { Button { onSave(annotation) } label: { Text("Enregistrer").bold() }.accessibilityIdentifier("pdf-annotation-save") }500                }501            }502            .onAppear { if isEditable, annotation.kind == .note, annotation.note.isEmpty { noteFocused = true } }503        }504        .pencilSheetDetents()505    }506}507508extension View {509    /// Half height then full on a compact width; full height on a regular width, where a half sheet is a small card that clips.510    func pencilSheetDetents() -> some View { modifier(PencilSheetDetents()) }511}512513private struct PencilSheetDetents: ViewModifier {514    func body(content: Content) -> some View {515        // (the size class seen from inside a sheet is the sheet's own, compact even on an iPad: the device decides)516        content.presentationDetents(UIDevice.current.userInterfaceIdiom == .pad ? [.large] : [.medium, .large])517    }518}519
Files main
Menu

Theme