SPB Git

Repository Public

MediaBlocksTests.swift 16.3 KB 279 lines swift

1// SP Notes Core2// File: Tests/SPNotesFeaturesTests/MediaBlocksTests.swift3// Description: The ink editor (strokes, simplification, eraser by hit test, undo / redo, view ⇄ canvas mapping, export of4//              `ink` + `preview` with `pk` cleared), the drawing viewer, and the chart block (the five kinds, axes, data5//              grid edits, live database rows with offline fallback, summary), with their hosted renders.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import Foundation11import SPNotesDocument12import SPNotesSync13import SwiftUI14import Testing15@testable import SPNotesFeatures16@testable import SPNotesFeaturesCatalog1718@Suite("Ink editor")19@MainActor20struct MediaInkTests {21    @Test("aspect-fit mapping between the view and the canvas units, both ways")22    func mapping() {23        let mapping = InkCanvasMapping(canvas: CGSize(width: 400, height: 200), in: CGSize(width: 1000, height: 300))24        #expect(mapping.scale == 1.5 && mapping.offset == CGPoint(x: 200, y: 0))25        #expect(mapping.toCanvas(CGPoint(x: 200, y: 0)) == .zero && mapping.toCanvas(CGPoint(x: 800, y: 300)) == CGPoint(x: 400, y: 200))26        #expect(mapping.toView(CGPoint(x: 200, y: 100)) == CGPoint(x: 500, y: 150))27        #expect(mapping.canvasRect(CGSize(width: 400, height: 200)) == CGRect(x: 200, y: 0, width: 600, height: 300))28        #expect(InkCanvasMapping(canvas: .zero, in: CGSize(width: 10, height: 10)).scale == 1)29    }3031    @Test("drawing: a stroke is simplified when it ends, with the tool, colour and width chosen; undo / redo / clear")32    func drawing() {33        let model = InkEditorModel(document: InkDocument(width: 400, height: 300))34        #expect(!model.canUndo && !model.hasChanges)35        model.color = InkEditorModel.palette[2]36        model.begin(at: CGPoint(x: 10, y: 10))37        for i in 1...100 { model.move(to: CGPoint(x: 10 + Double(i) * 3, y: 10)) }   // a straight line: 2 points are enough38        #expect(model.liveStroke?.points.count == 101 && model.document.strokes.isEmpty)39        model.end()40        #expect(model.liveStroke == nil && model.document.strokes.count == 1)41        let stroke = model.document.strokes[0]42        #expect(stroke.points.count == 2 && stroke.tool == .pen && stroke.color == InkEditorModel.palette[2] && stroke.width == 2.5)43        model.tool = .highlighter44        #expect(model.width == 16, "the width follows the tool")45        model.width = 2046        model.begin(at: CGPoint(x: 50, y: 100), pressure: 0.5)47        model.move(to: CGPoint(x: 50, y: 100))   // not moved: ignored48        model.move(to: CGPoint(x: 150, y: 160), pressure: 0.7)49        model.end()50        #expect(model.document.strokes.count == 2 && model.document.strokes[1].tool == .highlighter && model.document.strokes[1].width == 20)51        #expect(model.canUndo && model.hasChanges)52        model.undo()53        #expect(model.document.strokes.count == 1 && model.canRedo)54        model.redo()55        #expect(model.document.strokes.count == 2 && !model.canRedo)56        model.clear()57        #expect(model.document.strokes.isEmpty)58        model.undo()59        #expect(model.document.strokes.count == 2)60        model.begin(at: .zero)61        model.cancelStroke()62        model.end()63        #expect(model.document.strokes.count == 2, "a cancelled stroke leaves nothing")64        // The document it produces is valid spn-ink-1.65        let decoded = try? InkDocument(data: model.document.jsonData())66        #expect(decoded == model.document && decoded?.width == 400)67    }6869    @Test("eraser: removes the strokes under it by hit test; a whole gesture is one undo step")70    func eraser() {71        let model = InkEditorModel(document: FeatureSamples.sampleInk())72        model.tool = .eraser73        model.begin(at: CGPoint(x: 5, y: 5))          // nothing there74        model.end()75        #expect(model.document.strokes.count == 3 && !model.canUndo)76        model.begin(at: CGPoint(x: 260, y: 256))      // on the marker underline77        model.move(to: CGPoint(x: 385, y: 60))        // across the highlight78        model.end()79        #expect(model.document.strokes.count == 1 && model.document.strokes[0].tool == .pen)80        model.undo()81        #expect(model.document.strokes.count == 3, "both erasures come back together")82    }8384    @Test("export: ink JSON + preview PNG are uploaded, the node points to them and pk is cleared (SPEC §2)")85    func export() async throws {86        let world = try await FeatureWorld()87        let loader = FeatureSamples.attachmentLoader(world)88        var block = DrawingBlock(width: 10, height: 10)89        block.pk = "c0a50001-0000-4000-8000-0000000000bb"90        let ink = FeatureSamples.sampleInk()91        let png = try #require(InkDrawingExport.previewPNG(ink))92        #expect(png.prefix(4) == Data([0x89, 0x50, 0x4E, 0x47]))93        let image = try #require(CanvasMediaDecoder.image(from: png, pdf: false, maxPixel: 4096))94        #expect(image.width == 1040 && image.height == 600, "2× of the canvas size")95        let stored = try await InkDrawingExport.store(ink, into: block, pageId: FeatureSamples.canvasPageId, loader: loader)96        #expect(stored.pk == nil && stored.width == 520 && stored.height == 300)97        let inkId = try #require(stored.ink), previewId = try #require(stored.preview)98        #expect(try InkDocument(data: try await loader.data(id: inkId)) == ink)99        #expect(try await loader.data(id: previewId) == png)100        world.setOffline(true)101        do { _ = try await InkDrawingExport.store(ink, into: block, pageId: nil, loader: loader); Issue.record("should fail offline") } catch { #expect((error as? FeatureFailure)?.isOffline == true) }102        #expect(InkEditorModel(document: ink).previewPNG() == png)103    }104105    @Test("drawing viewer: the ink through the loader, else the preview picture, else a calm reason")106    func viewerResolution() async throws {107        let world = try await FeatureWorld()108        let loader = FeatureSamples.attachmentLoader(world)109        var block = DrawingBlock(width: 520, height: 300)110        if case .missing(let failure) = await DrawingBlockViewer.resolve(block, loader: loader) { #expect(failure == nil) } else { Issue.record("an empty node has nothing to show") }111        block.ink = FeatureSamples.canvasInkId112        if case .ink(let ink) = await DrawingBlockViewer.resolve(block, loader: loader) { #expect(ink == FeatureSamples.sampleInk()) } else { Issue.record("the ink should load") }113        // Ink this build cannot read (here: not ink at all) → the PNG preview.114        block.ink = FeatureSamples.canvasPDFId115        block.preview = FeatureSamples.canvasImageId116        if case .preview(let image) = await DrawingBlockViewer.resolve(block, loader: loader) { #expect(image.width > 0) } else { Issue.record("the preview should be used") }117        // The engine keeps pictures offline: the preview still shows without the network.118        world.setOffline(true)119        if case .preview = await DrawingBlockViewer.resolve(block, loader: loader) {} else { Issue.record("the offline copy of the preview should be used") }120        if case .missing(let failure) = await DrawingBlockViewer.resolve(block, loader: .unavailable) { #expect(failure?.isOffline == true) } else { Issue.record("no file access: nothing, calmly") }121    }122123    #if os(macOS)124    @Test("hosted renders: the ink editor and the drawing viewer (ink, empty)")125    func snapshots() async throws {126        let model = InkEditorModel(document: FeatureSamples.sampleInk())127        model.tool = .marker128        model.color = InkEditorModel.palette[1]129        Snapshot.render("ink-editor") { InkEditorView(model: model, onCancel: {}, onSave: { _, _ in }) }130        var block = DrawingBlock(width: 520, height: 300)131        block.ink = FeatureSamples.canvasInkId132        Snapshot.render("drawing-viewer", compactSize: CGSize(width: 390, height: 420), regularSize: CGSize(width: 760, height: 520)) {133            DrawingBlockViewer(block: block, ink: FeatureSamples.sampleInk(), onEdit: { _ in }).padding(16)134        }135    }136    #endif137}138139@Suite("Chart block")140@MainActor141struct MediaChartTests {142    @Test("the five kinds plot the node's table: marks per series, pie slices, numeric X for a scatter")143    func kinds() async {144        for kind in ChartKind.known {145            let model = ChartBlockModel(block: FeatureSamples.sampleChart(kind))146            await model.load()147            #expect(model.phase == .loaded && model.origin == .node && model.hasData)148            #expect(model.xColumn == "Modèle")149            if kind == .pie {150                #expect(model.slices.count == 5 && model.slices.map(\.label).first == "GARCH" && model.skippedCount == 0)151            } else {152                #expect(model.yColumns == ["QLIKE", "MSE"] && model.marks.count == 10)153                #expect(model.marks.first == ChartMarkPoint(id: "QLIKE#0", series: "QLIKE", label: "GARCH", x: nil, y: 0.412))154            }155            #expect(model.summary.contains(ChartBlockModel.kindName(kind).lowercased()))156        }157        let scatter = ChartBlockModel(block: ChartBlock(kind: .scatter, columns: ["x", "y"], rows: [[1, 2], [2.5, "3,5"], [4, nil], ["5", "n/a"]]))158        #expect(scatter.marks.map(\.x) == [1, 2.5] && scatter.marks.map(\.y) == [2, 3.5] && scatter.skippedCount == 2)159        let pie = ChartBlockModel(block: ChartBlock(kind: .pie, columns: ["k", "v"], rows: [["a", 2], ["b", -1], ["c", 0], ["d", 3]]))160        #expect(pie.slices.map(\.label) == ["a", "d"] && pie.skippedCount == 2)161        #expect(ChartBlockModel(block: FeatureSamples.sampleChart(.bar)).summary == "Erreur de prévision par modèle, graphique en barres, 5 lignes. QLIKE : de 0,379 (Chronos) à 0,412 (GARCH). MSE : de 1,66 (Chronos) à 1,93 (GARCH).")162    }163164    @Test("empty: nothing to plot is said, not drawn")165    func empty() async {166        let model = ChartBlockModel(block: ChartBlock())167        await model.load()168        #expect(model.phase == .loaded && !model.hasData && model.marks.isEmpty)169        #expect(model.summary == "Graphique sans titre : aucune donnée numérique à tracer.")170        let text = ChartBlockModel(block: ChartBlock(columns: ["a", "b"], rows: [["x", "y"]]))171        #expect(text.hasData && text.marks.isEmpty && text.skippedCount == 1)172    }173174    @Test("data grid edits go back as node attributes: cells (numbers with a comma), rows, columns, kind, axes; unknown attrs are kept")175    func editing() {176        var received: [ChartBlock] = []177        var block = FeatureSamples.sampleChart(.bar)178        block.storage.attrs = (block.storage.attrs ?? [:]).merging(["futur": .string("gardé")]) { _, new in new }179        let model = ChartBlockModel(block: block) { received.append($0) }180        #expect(ChartBlockModel.parse("1,5") == .number(1.5) && ChartBlockModel.parse(" 42 ") == .number(42) && ChartBlockModel.parse("") == .null && ChartBlockModel.parse("n/a") == .string("n/a"))181        #expect(ChartBlockModel.display(.number(0.412)) == "0,412" && ChartBlockModel.display(.null) == "" && ChartBlockModel.display(.number(1982)) == "1982")182        model.setCell(row: 0, column: 1, "0,5")183        #expect(received.last?.rows[0][1] == .number(0.5))184        model.setCell(row: 0, column: 1, "0,5")185        #expect(received.count == 1, "no change, no callback")186        model.setCell(row: 99, column: 0, "x")187        model.addRow()188        #expect(received.last?.rows.count == 6 && received.last?.rows[5] == [.null, .null, .null])189        model.removeRow(5)190        let name = model.addColumn()191        #expect(name == "Série 4" && received.last?.columns == ["Modèle", "QLIKE", "MSE", "Série 4"] && received.last?.rows[0].count == 4)192        model.renameColumn("Série 4", to: "MAE")193        model.renameColumn("MAE", to: "MSE")   // duplicate: refused194        #expect(received.last?.columns.last == "MAE")195        model.toggleY("MAE")196        #expect(model.yColumns == ["QLIKE", "MSE", "MAE"])197        model.toggleY("QLIKE")198        model.toggleY("MSE")199        model.toggleY("MAE")200        #expect(model.yColumns == ["MAE"], "the last series cannot be removed")201        model.renameColumn("MAE", to: "Erreur absolue")202        #expect(received.last?.y == ["Erreur absolue"])203        model.setX("QLIKE")204        #expect(model.xColumn == "QLIKE" && received.last?.x == "QLIKE")205        model.removeColumn("QLIKE")206        #expect(received.last?.x == nil && model.xColumn == "Modèle")207        model.setKind(.line)208        model.setTitle("Nouveau titre")209        #expect(received.last?.kind == .line && received.last?.title == "Nouveau titre")210        #expect(received.last?.storage.attrs?["futur"]?.stringValue == "gardé")211        let single = ChartBlockModel(block: ChartBlock(columns: ["seule"], rows: [[1]]))212        single.removeColumn("seule")213        #expect(single.columns == ["seule"], "the last column stays")214    }215216    @Test("live database chart: live rows online with their freshness, the cached answer offline, the node's snapshot when never fetched, and an explicit snapshot update")217    func live() async throws {218        let world = try await FeatureWorld()219        var received: [ChartBlock] = []220        let model = ChartBlockModel(block: FeatureSamples.sampleLiveChart(), repositories: world.repositories) { received.append($0) }221        #expect(model.isLive && !model.canEditCells)222        await model.load()223        guard case .live(let fresh) = model.origin else { Issue.record("expected live data"); return }224        #expect(!fresh.fromCache && model.rows.count == 4 && model.columns == ["Article", "Année", "Pages"] && model.databaseName == "Lectures")225        #expect(model.marks.map(\.y) == [21, 21, 24, 23] && model.snapshotIsOutdated && received.isEmpty, "looking at a chart does not edit the note")226        model.setCell(row: 0, column: 0, "x")227        model.addRow()228        #expect(received.isEmpty, "cells of a live chart are read-only")229        model.updateSnapshot()230        #expect(received.count == 1 && received[0].rows.count == 4 && received[0].source?.databaseId == FeatureSamples.chartDatabaseId && !model.snapshotIsOutdated)231232        world.setOffline(true)233        await model.load()234        guard case .live(let cached) = model.origin else { Issue.record("expected the cached answer"); return }235        #expect(cached.fromCache && model.rows.count == 4 && model.phase == .loaded)236237        // A device that never fetched it: the snapshot of the node, calmly.238        let other = try await FeatureWorld(samples: false)239        other.setOffline(true)240        let offline = ChartBlockModel(block: FeatureSamples.sampleLiveChart(), repositories: other.repositories)241        await offline.load()242        #expect(offline.origin == .snapshot && offline.liveFailure?.isOffline == true && offline.phase == .loaded && offline.rows.count == 1)243        // Server error: same fallback, the reason kept.244        other.setOffline(false)245        other.fake.stub("POST", path: "^/api/query$") { _ in .error(500, code: "boom", message: "Erreur interne") }246        await offline.load()247        #expect(offline.origin == .snapshot && offline.liveFailure?.kind == .server)248        // No snapshot at all and no server: a failure state, not a spinner.249        var bare = ChartBlock(kind: .bar)250        bare.source = ChartSource(databaseId: FeatureSamples.chartDatabaseId)251        let failing = ChartBlockModel(block: bare, repositories: other.repositories)252        await failing.load()253        #expect(failing.phase.failure?.kind == .server)254    }255256    #if os(macOS)257    @Test("hosted renders: the five chart kinds, the live chart online and on its snapshot offline, the empty chart")258    func snapshots() async throws {259        for kind in ChartKind.known {260            let model = ChartBlockModel(block: FeatureSamples.sampleChart(kind))261            await model.load()262            Snapshot.render("chart-\(kind.rawValue)") { ChartBlockView(model: model) }263        }264        let world = try await FeatureWorld()265        let live = ChartBlockModel(block: FeatureSamples.sampleLiveChart(), repositories: world.repositories)266        await live.load()267        Snapshot.render("chart-live") { ChartBlockView(model: live) }268        let other = try await FeatureWorld(samples: false)269        other.setOffline(true)270        let offline = ChartBlockModel(block: FeatureSamples.sampleLiveChart(), repositories: other.repositories)271        await offline.load()272        Snapshot.render("chart-live-offline") { ChartBlockView(model: offline) }273        let empty = ChartBlockModel(block: ChartBlock())274        await empty.load()275        Snapshot.render("chart-empty") { ChartBlockView(model: empty) }276    }277    #endif278}279
Files main
Menu

Theme