Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/PDFBlockView.swift3// Description: Detail view of a `pdf` node: the document in a PDFKit `PDFView` (text selection, zoom, pages), a toolbar4// to highlight the selection, attach a note or draw ink, and the list of the node's annotations (jump,5// edit the note, recolour, delete). Regular: the list sits beside the page; compact: it replaces the lower6// part on demand. PDFKit only — no web view.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import PDFKit11import SPNotesDesign12import SPNotesDocument13import SwiftUI1415public struct PDFBlockView: View {16 @Environment(\.featureAttachmentLoader) private var environmentLoader17 @State private var model: PDFBlockModel?18 @State private var noteDraft = ""19 @State private var composingNote = false20 @Environment(\.pdfStaticRendering) private var staticRendering21 private let block: PDFBlock22 private let onChange: (PDFBlock) -> Void2324 /// - Parameter onChange: receives the node with its updated attributes (annotations, page) after each edit; the25 /// caller writes it into the document and saves the page.26 public init(block: PDFBlock, onChange: @escaping (PDFBlock) -> Void = { _ in }) {27 self.block = block28 self.onChange = onChange29 }3031 public init(model: PDFBlockModel) {32 block = model.block33 onChange = { _ in }34 _model = State(initialValue: model)35 }3637 public var body: some View {38 FeatureLayoutReader { sizeClass in39 if let model {40 content(model, compact: sizeClass.isCompact)41 } else {42 FeatureLoadingView()43 }44 }45 .background(NVColor.bg)46 .task {47 if model == nil { model = PDFBlockModel(block: block, loader: environmentLoader, onChange: onChange) }48 if model?.phase == .idle { await model?.load() }49 }50 .onDisappear { model?.commitPage() }51 }5253 @ViewBuilder54 private func content(_ model: PDFBlockModel, compact: Bool) -> some View {55 VStack(spacing: 0) {56 header(model, compact: compact)57 FeatureStatusBanner(failure: model.actionFailure, freshness: nil).padding(.horizontal, NVSpace.lg)58 FeaturePhaseView(phase: model.phase, hasData: model.document != nil, retry: { Task { await model.load() } }, empty: { EmptyView() }) {59 if compact {60 VStack(spacing: 0) {61 page(model)62 if model.showsAnnotations {63 Rectangle().fill(NVColor.line).frame(height: 1)64 annotationList(model).frame(maxHeight: 300)65 }66 toolbar(model, compact: true)67 }68 } else {69 HStack(spacing: 0) {70 VStack(spacing: 0) { page(model); toolbar(model, compact: false) }71 Rectangle().fill(NVColor.line).frame(width: 1)72 annotationList(model).frame(width: 320).background(NVColor.bgSidebar)73 }74 }75 }76 }77 }7879 private func header(_ model: PDFBlockModel, compact: Bool) -> some View {80 HStack(spacing: NVSpace.sm) {81 Image(systemName: "doc.richtext").foregroundStyle(NVColor.accent).accessibilityHidden(true)82 Text(model.block.name.isEmpty ? L("Document PDF") : model.block.name).nvFont(compact ? .uiStrong : .h3).foregroundStyle(NVColor.fg).lineLimit(1).truncationMode(.middle)83 Spacer(minLength: NVSpace.sm)84 if model.pageCount > 0 {85 FeatureIconButton("chevron.left", label: L("Page précédente")) { model.go(to: model.page - 1) }86 .disabled(!model.canGoBack).opacity(model.canGoBack ? 1 : 0.4)87 Text(LF("%lld / %lld", model.page, model.pageCount)).nvFont(.ui).monospacedDigit().foregroundStyle(NVColor.fgMuted)88 .accessibilityLabel(LF("Page %lld sur %lld", model.page, model.pageCount))89 FeatureIconButton("chevron.right", label: L("Page suivante")) { model.go(to: model.page + 1) }90 .disabled(!model.canGoForward).opacity(model.canGoForward ? 1 : 0.4)91 }92 }93 .padding(.horizontal, NVSpace.lg)94 .padding(.vertical, NVSpace.md)95 }9697 @ViewBuilder98 private func page(_ model: PDFBlockModel) -> some View {99 if staticRendering {100 PDFStaticPageView(model: model)101 .frame(maxWidth: .infinity, maxHeight: .infinity)102 .background(NVColor.bgSunken)103 } else {104 PDFKitPageView(model: model)105 .overlay { if model.tool == .ink { PDFInkOverlay(model: model) } }106 .frame(maxWidth: .infinity, maxHeight: .infinity)107 .background(NVColor.bgSunken)108 }109 }110111 private func toolbar(_ model: PDFBlockModel, compact: Bool) -> some View {112 @Bindable var model = model113 let hasSelection = model.selection != nil114 return VStack(alignment: .leading, spacing: NVSpace.sm) {115 if composingNote, hasSelection {116 HStack(spacing: NVSpace.sm) {117 TextField(L("Note sur le passage sélectionné"), text: $noteDraft, axis: .vertical)118 .textFieldStyle(.roundedBorder)119 .lineLimit(1...3)120 FeatureButton(L("Ajouter"), kind: .primary) {121 model.annotateSelection(note: noteDraft)122 noteDraft = ""123 composingNote = false124 }125 }126 }127 HStack(spacing: NVSpace.sm) {128 FeatureButton(L("Surligner"), systemImage: "highlighter", kind: hasSelection ? .primary : .secondary) { model.annotateSelection() }129 .disabled(!hasSelection).opacity(hasSelection ? 1 : 0.5)130 FeatureButton(L("Note"), systemImage: "note.text") { composingNote.toggle() }131 .disabled(!hasSelection).opacity(hasSelection ? 1 : 0.5)132 FeatureIconButton("scribble.variable", label: model.tool == .ink ? L("Arrêter de dessiner") : L("Dessiner sur la page"), tone: model.tool == .ink ? .accent : .neutral) {133 model.tool = model.tool == .ink ? .read : .ink134 }135 Spacer(minLength: 0)136 if !compact {137 ForEach(PDFBlockModel.colors, id: \.self) { hex in swatch(hex, selected: model.color == hex, size: 20) { model.color = hex } }138 }139 if compact {140 Button { model.showsAnnotations.toggle() } label: {141 HStack(spacing: NVSpace.xs) {142 Image(systemName: model.showsAnnotations ? "chevron.down" : "list.bullet")143 Text(LF("%lld", model.annotations.count)).monospacedDigit()144 }145 .nvFont(.uiStrong).foregroundStyle(NVColor.fg)146 .padding(.horizontal, NVSpace.md).frame(minHeight: 44)147 .background(NVColor.bgHover.opacity(0.6), in: NVRadius.shape(NVRadius.sm))148 .contentShape(Rectangle())149 }150 .buttonStyle(.plain)151 .accessibilityLabel(model.showsAnnotations ? L("Masquer les annotations") : LF("Afficher les annotations (%lld)", model.annotations.count))152 }153 }154 if compact {155 HStack(spacing: NVSpace.sm) {156 ForEach(PDFBlockModel.colors, id: \.self) { hex in swatch(hex, selected: model.color == hex, size: 24) { model.color = hex } }157 Spacer(minLength: 0)158 Text(hasSelection ? L("Passage sélectionné") : (model.tool == .ink ? L("Tracez sur la page") : L("Sélectionnez du texte pour l'annoter")))159 .nvFont(.micro).foregroundStyle(NVColor.fgMuted)160 }161 }162 }163 .padding(.horizontal, NVSpace.lg)164 .padding(.vertical, NVSpace.sm)165 .background(NVColor.bgElevated)166 .overlay(alignment: .top) { Rectangle().fill(NVColor.line).frame(height: 1) }167 }168169 private func swatch(_ hex: String, selected: Bool, size: CGFloat, action: @escaping () -> Void) -> some View {170 Button(action: action) {171 Circle().fill(NVRGB(hexString: hex)?.color ?? NVColor.warning)172 .frame(width: size, height: size)173 .overlay(Circle().strokeBorder(selected ? NVColor.accent : NVColor.lineStrong, lineWidth: selected ? 2 : 1).padding(-3))174 .frame(minWidth: size + 12, minHeight: size + 12)175 .contentShape(Rectangle())176 }177 .buttonStyle(.plain)178 .accessibilityLabel(LF("Couleur %@", hex))179 .accessibilityAddTraits(selected ? .isSelected : [])180 }181182 private func annotationList(_ model: PDFBlockModel) -> some View {183 ScrollView {184 VStack(alignment: .leading, spacing: NVSpace.sm) {185 NVSectionHeader(L("Annotations"), subtitle: model.annotations.isEmpty ? nil : LF("%lld dans ce document", model.annotations.count))186 if model.annotations.isEmpty {187 Text(L("Sélectionnez un passage puis « Surligner » ou « Note ». Les annotations sont enregistrées dans la note, pas dans le fichier."))188 .nvFont(.ui).foregroundStyle(NVColor.fgMuted).fixedSize(horizontal: false, vertical: true)189 }190 ForEach(model.annotations) { annotation in PDFAnnotationRow(model: model, annotation: annotation) }191 }192 .padding(NVSpace.lg)193 }194 }195}196197/// One annotation of the node in the list.198struct PDFAnnotationRow: View {199 @Bindable var model: PDFBlockModel200 let annotation: SPNotesDocument.PDFAnnotation201202 static func kindName(_ kind: SPNotesDocument.PDFAnnotationKind) -> String {203 switch kind {204 case .note: return L("Note")205 case .ink: return L("Tracé")206 default: return L("Surlignage")207 }208 }209210 var body: some View {211 let selected = model.selectedAnnotationId == annotation.id212 VStack(alignment: .leading, spacing: NVSpace.xs) {213 Button { model.show(annotation) } label: {214 HStack(alignment: .top, spacing: NVSpace.sm) {215 RoundedRectangle(cornerRadius: 2).fill(NVRGB(hexString: annotation.color)?.color ?? NVColor.warning).frame(width: 4).frame(minHeight: 32)216 VStack(alignment: .leading, spacing: NVSpace.xxs) {217 Text(LF("%@ · p. %lld", Self.kindName(annotation.kind), annotation.page)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)218 if !annotation.text.isEmpty {219 Text(annotation.text).nvFont(.ui).foregroundStyle(NVColor.fg).lineLimit(4).multilineTextAlignment(.leading)220 } else if annotation.kind == .ink {221 Text(L("Tracé à main levée")).nvFont(.ui).foregroundStyle(NVColor.fg)222 }223 }224 Spacer(minLength: 0)225 }226 .contentShape(Rectangle())227 }228 .buttonStyle(.plain)229 .accessibilityLabel(LF("%@, page %lld : %@", Self.kindName(annotation.kind), annotation.page, annotation.text))230 if annotation.kind != .ink {231 TextField(L("Ajouter une note"), text: Binding(get: { model.annotations.first { $0.id == annotation.id }?.note ?? "" }, set: { model.setNote($0, of: annotation.id) }), axis: .vertical)232 .textFieldStyle(.plain)233 .nvFont(.ui)234 .foregroundStyle(NVColor.fg)235 .lineLimit(1...4)236 .padding(NVSpace.sm)237 .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.sm))238 }239 if selected {240 HStack(spacing: NVSpace.xs) {241 ForEach(PDFBlockModel.colors, id: \.self) { hex in242 Button { model.setColor(hex, of: annotation.id) } label: {243 Circle().fill(NVRGB(hexString: hex)?.color ?? NVColor.warning).frame(width: 16, height: 16)244 .overlay(Circle().strokeBorder(annotation.color == hex ? NVColor.accent : NVColor.lineStrong, lineWidth: annotation.color == hex ? 2 : 1).padding(-2))245 .frame(minWidth: 28, minHeight: 28).contentShape(Rectangle())246 }247 .buttonStyle(.plain)248 .accessibilityLabel(LF("Couleur %@", hex))249 }250 Spacer(minLength: 0)251 FeatureIconButton("trash", label: L("Supprimer l'annotation"), tone: .danger) { model.remove(annotation.id) }252 }253 }254 }255 .padding(NVSpace.sm)256 .frame(maxWidth: .infinity, alignment: .leading)257 .background(selected ? NVColor.accentSoft : NVColor.bgElevated, in: NVRadius.shape(NVRadius.md))258 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(selected ? NVColor.accent : NVColor.line, lineWidth: 1))259 }260}261262private struct PDFStaticRenderingKey: EnvironmentKey { static let defaultValue = false }263264public extension EnvironmentValues {265 /// When true, `PDFBlockView` shows the current page as a picture drawn by PDFKit (`PDFPage.draw`, with the same266 /// annotations) instead of the interactive `PDFView`: thumbnails, print, hosted renders. No selection, no ink.267 var pdfStaticRendering: Bool {268 get { self[PDFStaticRenderingKey.self] }269 set { self[PDFStaticRenderingKey.self] = newValue }270 }271}272273/// The current page as PDFKit draws it (content and annotations), fitted in the available space.274struct PDFStaticPageView: View {275 let model: PDFBlockModel276277 var body: some View {278 // Reading `revision` makes the picture follow annotation edits and page changes.279 let _ = model.revision280 if let image = model.pageImage(page: model.page) {281 Image(decorative: image, scale: 1).resizable().scaledToFit()282 .shadow(color: .black.opacity(0.12), radius: 6, y: 2)283 .padding(NVSpace.lg)284 .accessibilityLabel(LF("Page %lld sur %lld", model.page, model.pageCount))285 } else {286 NVEmptyState(systemImage: "doc.richtext", title: L("Page indisponible"))287 }288 }289}290291/// Converts between the PDFKit view and its pages for the ink overlay.292@MainActor293final class PDFViewBridge {294 weak var view: PDFView?295296 /// A point of the overlay (top-left origin, same frame as the PDF view) → the page under it and the point in page space.297 func pagePoint(at point: CGPoint) -> (page: PDFPage, point: CGPoint)? {298 guard let view else { return nil }299 #if os(macOS)300 let local = view.isFlipped ? point : CGPoint(x: point.x, y: view.bounds.height - point.y)301 #else302 let local = point303 #endif304 guard let page = view.page(for: local, nearest: true) else { return nil }305 return (page, view.convert(local, to: page))306 }307}308309/// The drawing layer over the page while the ink tool is on: a stroke becomes one `ink` annotation of the node.310struct PDFInkOverlay: View {311 @Bindable var model: PDFBlockModel312 @State private var points: [CGPoint] = []313314 var body: some View {315 Canvas { context, _ in316 guard points.count > 1 else { return }317 var path = Path()318 path.addLines(points)319 context.stroke(path, with: .color(NVRGB(hexString: model.color)?.color ?? NVColor.danger), style: StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))320 }321 .contentShape(Rectangle())322 .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)323 .onChanged { points.append($0.location) }324 .onEnded { _ in325 defer { points = [] }326 guard let bridge = model.bridge, let first = points.first.flatMap(bridge.pagePoint(at:)), let document = model.document else { return }327 let pagePoints = points.compactMap { point -> CGPoint? in328 guard let hit = bridge.pagePoint(at: point), hit.page === first.page else { return nil }329 return hit.point330 }331 model.addInk(page: document.index(for: first.page) + 1, pagePoints: pagePoints)332 })333 .accessibilityLabel(L("Zone de dessin sur la page"))334 }335}336337#if os(macOS)338struct PDFKitPageView: NSViewRepresentable {339 let model: PDFBlockModel340341 func makeCoordinator() -> PDFKitCoordinator { PDFKitCoordinator(model: model) }342 func makeNSView(context: Context) -> PDFView { context.coordinator.makeView() }343 func updateNSView(_ view: PDFView, context: Context) { context.coordinator.update(view, revision: model.revision) }344}345#else346struct PDFKitPageView: UIViewRepresentable {347 let model: PDFBlockModel348349 func makeCoordinator() -> PDFKitCoordinator { PDFKitCoordinator(model: model) }350 func makeUIView(context: Context) -> PDFView { context.coordinator.makeView() }351 func updateUIView(_ view: PDFView, context: Context) { context.coordinator.update(view, revision: model.revision) }352}353#endif354355@MainActor356final class PDFKitCoordinator: NSObject {357 let model: PDFBlockModel358 private var shownRevision = -1359360 init(model: PDFBlockModel) { self.model = model }361362 func makeView() -> PDFView {363 let view = PDFView()364 view.autoScales = true365 view.displayMode = .singlePage366 view.displaysPageBreaks = false367 view.backgroundColor = .clear368 NotificationCenter.default.addObserver(self, selector: #selector(selectionChanged(_:)), name: .PDFViewSelectionChanged, object: view)369 NotificationCenter.default.addObserver(self, selector: #selector(pageChanged(_:)), name: .PDFViewPageChanged, object: view)370 let bridge = PDFViewBridge()371 bridge.view = view372 model.bridge = bridge373 return view374 }375376 func update(_ view: PDFView, revision: Int) {377 if view.document !== model.document { view.document = model.document }378 guard revision != shownRevision else { return }379 shownRevision = revision380 if let page = model.document?.page(at: model.page - 1), view.currentPage !== page { view.go(to: page) }381 #if os(macOS)382 view.needsDisplay = true383 view.documentView?.needsDisplay = true384 #else385 view.setNeedsDisplay()386 #endif387 }388389 @objc private func selectionChanged(_ notification: Notification) {390 guard let view = notification.object as? PDFView else { return }391 let selection = view.currentSelection392 model.capture(selection?.string?.isEmpty == false ? selection : nil)393 }394395 @objc private func pageChanged(_ notification: Notification) {396 guard let view = notification.object as? PDFView, let page = view.currentPage, let document = view.document else { return }397 model.pageShown(document.index(for: page) + 1)398 }399}400