Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/InkViews.swift3// Description: Ink on screen: `InkCanvasView` draws an `InkDocument` with Core's renderer inside a SwiftUI Canvas;4// `InkEditorView` is the mouse / trackpad / touch editor (the iOS app plugs PencilKit instead, in the app);5// `DrawingBlockViewer` shows a `drawing` node (ink, else its preview picture, else a neutral placeholder).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SPNotesDesign10import SPNotesDocument11import SwiftUI1213/// Draws ink aspect-fitted in the available space. Paper is white by design in both appearances (ink colours are data).14public struct InkCanvasView: View {15 private let document: InkDocument16 private let liveStroke: InkStroke?17 private let background: String18 private let showsPaper: Bool1920 public init(document: InkDocument, liveStroke: InkStroke? = nil, background: String = "none", showsPaper: Bool = true) {21 self.document = document22 self.liveStroke = liveStroke23 self.background = background24 self.showsPaper = showsPaper25 }2627 public var body: some View {28 Canvas { context, size in29 let mapping = InkCanvasMapping(canvas: document.size, in: size)30 let paper = mapping.canvasRect(document.size)31 if showsPaper {32 let fill: Color = InkColor(hex: background).map { Color(.sRGB, red: Double($0.red) / 255, green: Double($0.green) / 255, blue: Double($0.blue) / 255, opacity: $0.opacity) } ?? .white33 context.fill(Path(roundedRect: paper, cornerRadius: NVRadius.sm), with: .color(fill))34 }35 context.clip(to: Path(paper))36 context.withCGContext { cg in37 cg.translateBy(x: mapping.offset.x, y: mapping.offset.y)38 cg.scaleBy(x: mapping.scale, y: mapping.scale)39 InkRenderer.draw(document, in: cg)40 if let liveStroke { InkRenderer.draw(liveStroke, in: cg) }41 }42 }43 .accessibilityElement()44 .accessibilityLabel(LF("Dessin, %lld traits", document.strokes.count))45 }46}4748/// The ink editor. `onSave` receives the document and its preview PNG; the caller uploads both (`InkDrawingExport`).49public struct InkEditorView: View {50 @Environment(\.featureSizeClass) private var inheritedSizeClass51 @State private var model: InkEditorModel52 @State private var drawing = false53 private let background: String54 private let canSave: Bool55 private let onCancel: () -> Void56 private let onSave: (InkDocument, Data?) -> Void5758 public init(document: InkDocument, background: String = "none", canSave: Bool = true, onCancel: @escaping () -> Void, onSave: @escaping (InkDocument, Data?) -> Void) {59 _model = State(initialValue: InkEditorModel(document: document))60 self.background = background61 self.canSave = canSave62 self.onCancel = onCancel63 self.onSave = onSave64 }6566 public init(model: InkEditorModel, background: String = "none", canSave: Bool = true, onCancel: @escaping () -> Void, onSave: @escaping (InkDocument, Data?) -> Void) {67 _model = State(initialValue: model)68 self.background = background69 self.canSave = canSave70 self.onCancel = onCancel71 self.onSave = onSave72 }7374 public var body: some View {75 FeatureLayoutReader { sizeClass in76 VStack(spacing: 0) {77 header(compact: sizeClass.isCompact)78 surface79 .padding(sizeClass.isCompact ? NVSpace.md : NVSpace.xl)80 .frame(maxWidth: .infinity, maxHeight: .infinity)81 .background(NVColor.bgSunken)82 tools(compact: sizeClass.isCompact)83 }84 .background(NVColor.bg)85 }86 }8788 private func header(compact: Bool) -> some View {89 HStack(spacing: NVSpace.sm) {90 FeatureButton(L("Annuler"), action: onCancel)91 Spacer(minLength: NVSpace.sm)92 if !compact { Text(L("Dessin")).nvFont(.h3).foregroundStyle(NVColor.fg) }93 Spacer(minLength: NVSpace.sm)94 FeatureIconButton("arrow.uturn.backward", label: L("Annuler le dernier trait")) { model.undo() }95 .disabled(!model.canUndo).opacity(model.canUndo ? 1 : 0.4)96 FeatureIconButton("arrow.uturn.forward", label: L("Rétablir")) { model.redo() }97 .disabled(!model.canRedo).opacity(model.canRedo ? 1 : 0.4)98 FeatureButton(L("Enregistrer"), systemImage: "checkmark", kind: .primary) { onSave(model.document, model.previewPNG(background: background)) }99 .disabled(!canSave).opacity(canSave ? 1 : 0.5)100 }101 .padding(.horizontal, NVSpace.lg)102 .padding(.vertical, NVSpace.md)103 }104105 private var surface: some View {106 GeometryReader { proxy in107 let mapping = InkCanvasMapping(canvas: model.document.size, in: proxy.size)108 InkCanvasView(document: model.document, liveStroke: model.liveStroke, background: background)109 .overlay(NVRadius.shape(NVRadius.sm).path(in: mapping.canvasRect(model.document.size)).stroke(NVColor.lineStrong, lineWidth: 1))110 .contentShape(Rectangle())111 .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .local)112 .onChanged { value in113 if !drawing {114 drawing = true115 model.begin(at: mapping.toCanvas(value.startLocation))116 }117 model.move(to: mapping.toCanvas(value.location))118 }119 .onEnded { _ in120 model.end()121 drawing = false122 })123 }124 }125126 private static func name(_ tool: InkEditorModel.Tool) -> String {127 switch tool {128 case .pen: return L("Stylo")129 case .marker: return L("Feutre")130 case .highlighter: return L("Surligneur")131 case .eraser: return L("Gomme")132 }133 }134135 private static func symbol(_ tool: InkEditorModel.Tool) -> String {136 switch tool {137 case .pen: return "pencil.tip"138 case .marker: return "paintbrush.pointed"139 case .highlighter: return "highlighter"140 case .eraser: return "eraser"141 }142 }143144 private func tools(compact: Bool) -> some View {145 let toolRow = HStack(spacing: NVSpace.xs) {146 ForEach(InkEditorModel.Tool.allCases) { tool in147 Button { model.tool = tool } label: {148 Image(systemName: Self.symbol(tool))149 .font(.system(size: 17, weight: .medium))150 .foregroundStyle(model.tool == tool ? NVColor.accent : NVColor.fgMuted)151 .frame(minWidth: 44, minHeight: 44)152 .background(model.tool == tool ? NVColor.accentSoft : .clear, in: NVRadius.shape(NVRadius.md))153 .contentShape(Rectangle())154 }155 .buttonStyle(.plain)156 .accessibilityLabel(Self.name(tool))157 .accessibilityAddTraits(model.tool == tool ? .isSelected : [])158 }159 }160 let colorRow = HStack(spacing: NVSpace.sm) {161 ForEach(InkEditorModel.palette, id: \.self) { color in162 Button { model.color = color } label: {163 Circle()164 .fill(Color(.sRGB, red: Double(color.red) / 255, green: Double(color.green) / 255, blue: Double(color.blue) / 255))165 .frame(width: 24, height: 24)166 .overlay(Circle().strokeBorder(NVColor.bgElevated, lineWidth: 2))167 .overlay(Circle().strokeBorder(model.color == color ? NVColor.accent : NVColor.lineStrong, lineWidth: model.color == color ? 2 : 1).padding(-2))168 .frame(minWidth: 36, minHeight: 44)169 .contentShape(Rectangle())170 }171 .buttonStyle(.plain)172 .accessibilityLabel(LF("Couleur %@", color.hex))173 .accessibilityAddTraits(model.color == color ? .isSelected : [])174 }175 }176 let widthRow = HStack(spacing: NVSpace.sm) {177 Image(systemName: "lineweight").foregroundStyle(NVColor.fgMuted).accessibilityHidden(true)178 Slider(value: $model.width, in: 1...32)179 .frame(minWidth: 100, maxWidth: 180)180 .accessibilityLabel(L("Épaisseur du trait"))181 Text(LF("%.0f pt", model.width)).nvFont(.micro).foregroundStyle(NVColor.fgMuted).monospacedDigit()182 FeatureIconButton("trash", label: L("Tout effacer"), tone: .danger) { model.clear() }183 }184 return Group {185 if compact {186 VStack(spacing: NVSpace.xs) { HStack { toolRow; Spacer(minLength: 0) }; HStack { colorRow; Spacer(minLength: 0) }; widthRow }187 } else {188 HStack(spacing: NVSpace.xl) { toolRow; colorRow; Spacer(minLength: 0); widthRow }189 }190 }191 .padding(.horizontal, NVSpace.lg)192 .padding(.vertical, NVSpace.sm)193 .background(NVColor.bgElevated)194 .overlay(alignment: .top) { Rectangle().fill(NVColor.line).frame(height: 1) }195 }196}197198/// Read-only view of a `drawing` node for the editors' atom sheets. Loads the `spn-ink-1` attachment through the199/// environment's `featureAttachmentLoader`; falls back on the PNG preview, then on a neutral placeholder.200public struct DrawingBlockViewer: View {201 enum Content { case loading, ink(InkDocument), preview(CGImage), missing(FeatureFailure?) }202203 @Environment(\.featureAttachmentLoader) private var loader204 @State private var content: Content205 private let block: DrawingBlock206 private let onEdit: ((InkDocument) -> Void)?207208 /// - Parameter onEdit: when given, an « Modifier » control passes the current ink (or an empty document of the209 /// node's size) to the caller, which presents `InkEditorView` (macOS) or PencilKit (iOS app).210 public init(block: DrawingBlock, onEdit: ((InkDocument) -> Void)? = nil) {211 self.block = block212 self.onEdit = onEdit213 _content = State(initialValue: .loading)214 }215216 /// Renders a document that is already in memory (previews, snapshots, the canvas).217 public init(block: DrawingBlock, ink: InkDocument, onEdit: ((InkDocument) -> Void)? = nil) {218 self.block = block219 self.onEdit = onEdit220 _content = State(initialValue: .ink(ink))221 }222223 public var body: some View {224 VStack(alignment: .leading, spacing: NVSpace.sm) {225 Group {226 switch content {227 case .loading:228 FeatureLoadingView()229 case .ink(let document):230 InkCanvasView(document: document, background: block.background)231 .aspectRatio(document.width > 0 && document.height > 0 ? document.width / document.height : 1.5, contentMode: .fit)232 case .preview(let image):233 Image(decorative: image, scale: 2).resizable().scaledToFit()234 .background(Color.white, in: NVRadius.shape(NVRadius.sm))235 .accessibilityLabel(L("Aperçu du dessin"))236 case .missing(let failure):237 NVEmptyState(systemImage: "scribble.variable", title: L("Dessin indisponible"),238 message: failure?.message ?? L("Ce dessin n'a pas encore de tracé."))239 }240 }241 .frame(maxWidth: .infinity, minHeight: 160)242 if let onEdit {243 HStack {244 Spacer(minLength: 0)245 FeatureButton(L("Modifier le dessin"), systemImage: "pencil.tip") {246 if case .ink(let document) = content { onEdit(document) } else {247 onEdit(InkDocument(width: block.width > 0 ? block.width : 800, height: block.height > 0 ? block.height : 500))248 }249 }250 }251 }252 }253 .task(id: block.ink ?? block.preview ?? "") { await load() }254 }255256 private func load() async {257 if case .ink = content { return }258 content = await Self.resolve(block, loader: loader)259 }260261 /// What to show for a node: its ink, else its preview picture, else why there is nothing.262 static func resolve(_ block: DrawingBlock, loader: FeatureAttachmentLoader) async -> Content {263 var failure: FeatureFailure?264 if let id = block.ink {265 do { return .ink(try InkDocument(data: try await loader.data(id: id))) } catch { failure = FeatureFailure(error) }266 }267 if let id = block.preview, let data = try? await loader.data(id: id), let image = CanvasMediaDecoder.image(from: data, pdf: false, maxPixel: 2048) {268 return .preview(image)269 }270 return .missing(block.ink == nil && block.preview == nil ? nil : failure)271 }272}273