Repository Public
1// SP Notes iOS2// File: Features/Drawing/DrawingBlockScreen.swift3// Description: The detail screen of a `drawing` block: loads the drawing (PencilKit data, or strokes rebuilt from the ink), edits4// it in the PencilKit editor and writes ink + preview + PencilKit data back through the block detail context. A5// drawing whose files are missing is announced as such and left untouched.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import PencilKit10import SPNotesCore11import SPNotesDesign12import SwiftUI1314struct DrawingBlockScreen: View {15 let node: PMNode16 let context: BlockDetailContext17 var recognizer: any HandwritingRecognizing = VisionHandwritingRecognizer()1819 enum Phase { case loading, ready(DrawingBlockIO.Loaded), failed(DrawingBlockIO.Failure) }20 @State private var phase = Phase.loading21 @State private var isSaving = false22 @State private var error: String?2324 private var block: DrawingBlock { DrawingBlock(node: node) ?? DrawingBlock() }2526 var body: some View {27 Group {28 switch phase {29 case .loading:30 ProgressView().accessibilityLabel(Text("Ouverture du dessin")).frame(maxWidth: .infinity, maxHeight: .infinity).background(NVColor.bg)31 case .ready(let loaded):32 if context.isEditable {33 DrawingEditor(drawing: loaded.drawing, background: loaded.origin == .new ? DrawingPaper.white : block.background, canInsertText: true,34 isSaving: isSaving, recognizer: recognizer, onDone: { save($0, loaded: loaded) }, onCancel: context.dismiss)35 } else {36 DrawingViewer(drawing: loaded.drawing, background: block.background, onClose: context.dismiss)37 }38 case .failed(let failure):39 NavigationStack {40 NVEmptyState(systemImage: "scribble.variable", title: String(localized: "Dessin indisponible"), message: failure.message)41 .accessibilityIdentifier("drawing-unavailable")42 .background(NVColor.bg)43 .navigationTitle(Text("Dessin"))44 .navigationBarTitleDisplayMode(.inline)45 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(action: context.dismiss) { Text("Fermer") }.accessibilityIdentifier("drawing-close") } }46 }47 }48 }49 .task {50 guard case .loading = phase else { return }51 switch await DrawingBlockIO.load(block, app: context.app) {52 case .success(let loaded): phase = .ready(loaded)53 case .failure(let failure): phase = .failed(failure)54 }55 }56 .alert("SP Notes", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {57 Button("OK", role: .cancel) {}58 } message: { Text(error ?? "") }59 }6061 private func save(_ output: DrawingEditorOutput, loaded: DrawingBlockIO.Loaded) {62 let unchanged = output.drawing == loaded.drawing && (loaded.origin == .new || output.background == block.background)63 // nothing drawn in a new block, or nothing changed: nothing is written64 if (loaded.origin == .new && output.drawing.strokes.isEmpty) || (unchanged && loaded.origin != .new) {65 output.insertions.forEach(context.insertMarkdownBelow)66 context.dismiss()67 return68 }69 isSaving = true70 Task { @MainActor in71 do {72 let saved = try await DrawingBlockIO.save(output.drawing, background: output.background, into: block, app: context.app, noteId: context.noteId)73 context.commit(saved.block.node())74 output.insertions.forEach(context.insertMarkdownBelow)75 Haptics.success()76 context.dismiss()77 } catch {78 isSaving = false79 self.error = String(localized: "Le dessin n’a pas pu être enregistré : \(error.localizedDescription) Tes traits sont toujours là, réessaie.")80 }81 }82 }83}8485/// A drawing shown without any way to change it (a note in the trash, a read-only presentation).86struct DrawingViewer: View {87 let drawing: PKDrawing88 let background: String89 var onClose: () -> Void9091 var body: some View {92 NavigationStack {93 ScrollView([.horizontal, .vertical]) {94 Image(uiImage: DrawingRenderer.image(of: drawing, in: frame, background: DrawingPaper.color(background) ?? .white))95 .accessibilityLabel(Text("Dessin"))96 .padding(NVSpace.lg)97 }98 .background(NVColor.bgSunken)99 .navigationTitle(Text("Dessin"))100 .navigationBarTitleDisplayMode(.inline)101 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(action: onClose) { Text("Fermer") }.accessibilityIdentifier("drawing-close") } }102 }103 }104105 private var frame: CGRect {106 let bounds = drawing.bounds107 return bounds.isNull || bounds.isInfinite || bounds.isEmpty ? CGRect(x: 0, y: 0, width: 120, height: 80) : bounds.insetBy(dx: -24, dy: -24).integral108 }109}110111/// Editing a 1.0 drawing (a picture + its PencilKit source). On "Terminé" the user chooses: convert it into a `drawing` block,112/// or keep the 1.0 format exactly as before. Never converted without being asked.113struct LegacyDrawingScreen: View {114 let drawingData: Data115 /// Keep the 1.0 format: the caller stores the picture and the source as 1.0 did.116 var onKeep: @MainActor (DrawingResult) -> Void117 /// Convert: the caller writes the `drawing` block in place of the picture.118 var onConvert: @MainActor (DrawingEditorOutput) -> Void119 var onCancel: @MainActor () -> Void120121 @State private var pending: DrawingEditorOutput?122123 var body: some View {124 DrawingEditor(drawing: (try? PKDrawing(data: drawingData)) ?? PKDrawing(), background: DrawingPaper.none, offersBackground: false,125 onDone: { output in126 if output.drawing.strokes.isEmpty { onKeep(Self.result(output)) } else { pending = output }127 }, onCancel: onCancel)128 .confirmationDialog(Text("Enregistrer le dessin"), isPresented: Binding(get: { pending != nil }, set: { if !$0 { pending = nil } }), titleVisibility: .visible, presenting: pending) { output in129 Button { pending = nil; onConvert(output) } label: { Text("Convertir en bloc Dessin") }130 .accessibilityIdentifier("drawing-convert")131 Button { pending = nil; onKeep(Self.result(output)) } label: { Text("Garder le format actuel") }132 .accessibilityIdentifier("drawing-keep-format")133 Button(role: .cancel) { pending = nil } label: { Text("Continuer le dessin") }134 } message: { _ in135 Text("Un bloc Dessin se modifie aussi sur le Web et sur Mac. L’image et la source actuelles restent dans les pièces jointes de la note.")136 }137 }138139 @MainActor140 static func result(_ output: DrawingEditorOutput) -> DrawingResult {141 let text = output.insertions.joined(separator: "\n\n")142 return DrawingResult(drawingData: output.drawing.dataRepresentation(), png: DrawingRenderer.png(of: output.drawing), recognizedText: text.isEmpty ? nil : text,143 isEmpty: output.drawing.strokes.isEmpty)144 }145}146