SPB Git

Repository Public

Samples+Media.swift 12.9 KB 187 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeaturesCatalog/Samples+Media.swift3// Description: Sample data of the « Media » area for the catalogue and the tests: a canvas with every node kind of4//              `spn-canvas-1` (and one unknown kind), its attachments (picture, PDF, ink), a multi-page PDF with5//              annotations, charts of the five kinds, and the stub of the live query a database-backed chart reads.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import CoreGraphics10import CoreText11import Foundation12import ImageIO13import PDFKit14import SPNotesDocument15import SPNotesFeatures16import SPNotesTestSupport1718extension FeatureSamples {19    public static let canvasPageId = "c0a50001-0000-4000-8000-000000000001"20    public static let canvasLinkedPageId = "c0a50001-0000-4000-8000-000000000002"21    /// Engle (1982) of the sample library (`Samples+Assistant`): the areas share one set of references.22    public static let canvasReferenceId = AssistantSamples.referenceId(0)23    public static let canvasImageId = "c0a50001-0000-4000-8000-000000000004"24    public static let canvasPDFId = "c0a50001-0000-4000-8000-000000000005"25    public static let canvasInkId = "c0a50001-0000-4000-8000-000000000006"26    public static let chartDatabaseId = "5aa3a103-d4d7-4d6e-8f78-8b1223930c47"2728    static func installMedia(on world: FeatureWorld) {29        let fake = world.fake30        _ = fake.webCreatePage(id: canvasLinkedPageId, title: "Volatilité conditionnelle — notes de lecture")31        _ = fake.webCreateCanvas(id: canvasPageId, title: "Carte du projet")32        _ = fake.webAddAttachment(id: canvasImageId, pageId: canvasPageId, filename: "courbe.png", mime: "image/png", bytes: samplePNG())33        _ = fake.webAddAttachment(id: canvasPDFId, pageId: canvasPageId, filename: "article.pdf", mime: "application/pdf", bytes: samplePDF())34        _ = fake.webAddAttachment(id: canvasInkId, pageId: canvasPageId, filename: "dessin.spn-ink.json", mime: "application/json", bytes: sampleInk().jsonData())35        fake.webSaveCanvas(canvasPageId, data: sampleCanvas().jsonData())36        fake.stub("POST", path: "^/api/query$") { request in37            guard String(decoding: request.body, as: UTF8.self).contains(chartDatabaseId) else { return nil }38            return .json(text("knowledge", "query-database-chart"))39        }40    }4142    /// The attachment access of the sample device (local file, else the fake server).43    public static func attachmentLoader(_ world: FeatureWorld) -> FeatureAttachmentLoader {44        .standard(repositories: world.repositories, files: world.files)45    }4647    /// A canvas with every known node kind, one unknown kind, and edges of every style.48    public static func sampleCanvas() -> CanvasDocument {49        func node(_ id: String, _ kind: CanvasNodeKind, _ x: Double, _ y: Double, _ w: Double, _ h: Double, _ configure: (inout CanvasNode) -> Void = { _ in }) -> CanvasNode {50            var node = CanvasNode(id: id, kind: kind, x: x, y: y, w: w, h: h)51            configure(&node)52            return node53        }54        let nodes = [55            node("n-text", .text, 40, 40, 240, 120) { $0.text = "Question de recherche\nLa volatilité réalisée prédit-elle mieux que GARCH(1,1) à un jour ?"; $0.color = "#2f5ddb" },56            node("n-page", .page, 360, 30, 280, 132) { $0.pageId = canvasLinkedPageId },57            node("n-ref", .reference, 720, 40, 300, 120) { $0.refId = canvasReferenceId },58            node("n-shape", .shape, 80, 240, 170, 120) { $0.shape = .diamond; $0.text = "Hypothèse H1"; $0.color = "#d98b09" },59            node("n-ellipse", .shape, 80, 420, 170, 110) { $0.shape = .ellipse; $0.text = "Données 2010–2025"; $0.color = "#008b4e" },60            node("n-math", .math, 340, 230, 280, 100) { $0.latex = "\\sigma_t^2 = \\omega + \\alpha\\,\\varepsilon_{t-1}^2 + \\beta\\,\\sigma_{t-1}^2" },61            node("n-table", .table, 340, 380, 320, 150) { $0.text = "| Modèle | QLIKE | MSE |\n| --- | --- | --- |\n| GARCH | 0,412 | 1,93 |\n| HAR-RV | 0,388 | 1,71 |" },62            node("n-image", .image, 720, 210, 260, 180) { $0.attachmentId = canvasImageId; $0.text = "Courbe de volatilité" },63            node("n-pdf", .pdf, 1040, 40, 200, 270) { $0.attachmentId = canvasPDFId; $0.text = "Engle (1982)" },64            node("n-drawing", .drawing, 720, 430, 260, 170) { $0.ink = canvasInkId },65            node("n-link", .link, 1020, 360, 250, 96) { $0.url = "https://www.econometricsociety.org/publications/econometrica"; $0.text = "Econometrica" },66            node("n-unknown", CanvasNodeKind(rawValue: "hologram"), 1020, 500, 250, 100) { $0.text = "Carte d'une version future" },67        ]68        var edges = [69            CanvasEdge(id: "e1", from: "n-text", to: "n-page", label: "voir", kind: .arrow),70            CanvasEdge(id: "e2", from: "n-page", to: "n-ref", label: "cite", kind: .arrow),71            CanvasEdge(id: "e3", from: "n-text", to: "n-shape", kind: .arrow),72            CanvasEdge(id: "e4", from: "n-shape", to: "n-ellipse", label: "testée sur", kind: .line),73            CanvasEdge(id: "e5", from: "n-math", to: "n-table", kind: .arrow, color: "#cc272e"),74            CanvasEdge(id: "e6", from: "n-ref", to: "n-pdf", kind: .arrow),75            CanvasEdge(id: "e7", from: "n-table", to: "n-image", label: "figure", kind: .arrow),76        ]77        edges[4]["route"] = .string("orthogonal")78        edges[6]["route"] = .string("curved")79        return CanvasDocument(nodes: nodes, edges: edges, viewport: CanvasViewport(x: -110, y: -30, zoom: 0.62))80    }8182    /// A small drawing: a curve in pen, an underline in marker, a highlight.83    public static func sampleInk() -> InkDocument {84        let curve = (0...40).map { i -> InkPoint in85            let t = Double(i) / 4086            return InkPoint(x: 40 + t * 440, y: 150 - sin(t * .pi * 2) * 70 - t * 40, pressure: 0.4 + 0.6 * abs(sin(t * .pi)))87        }88        let pen = InkStroke(tool: .pen, color: InkColor(hex: "#2f5ddbff") ?? .black, width: 4, points: curve)89        let marker = InkStroke(tool: .marker, color: InkColor(hex: "#cc272eff") ?? .black, width: 6, points: [InkPoint(x: 60, y: 250), InkPoint(x: 260, y: 258), InkPoint(x: 460, y: 246)])90        let highlight = InkStroke(tool: .highlighter, color: InkColor(hex: "#ffd54aff") ?? .black, width: 22, points: [InkPoint(x: 300, y: 60), InkPoint(x: 470, y: 60)])91        return InkDocument(width: 520, height: 300, strokes: [highlight, pen, marker])92    }9394    /// A PNG drawn on the spot (a tinted chart-like picture).95    public static func samplePNG(width: Int = 520, height: Int = 360) -> Data {96        guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),97                                      bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return Data() }98        context.setFillColor(CGColor(red: 0.90, green: 0.94, blue: 1, alpha: 1))99        context.fill(CGRect(x: 0, y: 0, width: width, height: height))100        context.setStrokeColor(CGColor(red: 0.18, green: 0.36, blue: 0.86, alpha: 1))101        context.setLineWidth(5)102        context.move(to: CGPoint(x: 20, y: 60))103        for i in 1...50 {104            let t = Double(i) / 50105            context.addLine(to: CGPoint(x: 20 + t * Double(width - 40), y: 60 + (sin(t * 9) * 0.25 + t * 0.6 + 0.2) * Double(height - 140)))106        }107        context.strokePath()108        context.setFillColor(CGColor(red: 0.49, green: 0.25, blue: 0.82, alpha: 0.5))109        for i in 0..<8 { context.fill(CGRect(x: 40 + i * 58, y: 20, width: 34, height: 20 + (i * 37) % 90)) }110        guard let image = context.makeImage() else { return Data() }111        let data = NSMutableData()112        guard let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil) else { return Data() }113        CGImageDestinationAddImage(destination, image, nil)114        CGImageDestinationFinalize(destination)115        return data as Data116    }117118    /// A PDF with real, selectable text. `rotations` gives the `/Rotate` of each page (one page per entry).119    public static func samplePDF(rotations: [Int] = [0, 0, 90], mediaBox: CGRect = CGRect(x: 0, y: 0, width: 612, height: 792)) -> Data {120        let data = NSMutableData()121        var box = mediaBox122        guard let consumer = CGDataConsumer(data: data), let context = CGContext(consumer: consumer, mediaBox: &box, nil) else { return Data() }123        let paragraphs = [124            "Autoregressive Conditional Heteroscedasticity",125            "Traditional econometric models assume a constant one-period forecast variance.",126            "To generalize this implausible assumption, a new class of stochastic processes",127            "called autoregressive conditional heteroscedastic (ARCH) processes are introduced.",128            "These are mean zero, serially uncorrelated processes with nonconstant variances",129            "conditional on the past, but constant unconditional variances.",130        ]131        for (index, rotation) in rotations.enumerated() {132            var pageBox = mediaBox133            let info: [CFString: Any] = [kCGPDFContextMediaBox: Data(bytes: &pageBox, count: MemoryLayout<CGRect>.size)]134            context.beginPDFPage(info as CFDictionary)135            func draw(_ string: String, size: CGFloat, at point: CGPoint) {136                let font = CTFontCreateWithName("Helvetica" as CFString, size, nil)137                let line = CTLineCreateWithAttributedString(NSAttributedString(string: string, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font]))138                context.textPosition = point139                CTLineDraw(line, context)140            }141            draw("Page \(index + 1) — Engle (1982)", size: 20, at: CGPoint(x: mediaBox.minX + 72, y: mediaBox.maxY - 90))142            for (row, text) in paragraphs.enumerated() { draw(text, size: 12, at: CGPoint(x: mediaBox.minX + 72, y: mediaBox.maxY - 140 - CGFloat(row) * 22)) }143            context.endPDFPage()144            _ = (index, rotation)145        }146        context.closePDF()147        // CoreGraphics cannot write `/Rotate`: PDFKit sets it and rewrites the file.148        guard rotations.contains(where: { $0 != 0 }), let document = PDFDocument(data: data as Data) else { return data as Data }149        for (index, rotation) in rotations.enumerated() { document.page(at: index)?.rotation = rotation }150        return document.dataRepresentation() ?? (data as Data)151    }152153    /// A `pdf` node on the sample PDF with a highlight, a note and an ink annotation.154    public static func samplePDFBlock() -> PDFBlock {155        var block = PDFBlock(attachmentId: canvasPDFId, name: "article.pdf", page: 1)156        let created = now157        // The text lines of `samplePDF` start at x = 72 and sit every 22 pt under y = 792 − 140 (12 pt Helvetica).158        func line(_ row: Int, width: Double) -> PDFRect {159            let top = 792 - 140 - 22 * Double(row) + 10.5160            return PDFRect(x: 70 / 612, y: 1 - top / 792, width: width / 612, height: 15 / 792)161        }162        block.add(PDFAnnotation(id: "a-highlight", page: 1, kind: .highlight, color: "#ffd54a", rects: [line(1, width: 432)],163                                text: "Traditional econometric models assume a constant one-period forecast variance.", createdAt: created))164        block.add(PDFAnnotation(id: "a-note", page: 1, kind: .note, color: "#7cc4ff", rects: [line(3, width: 462), line(4, width: 446)],165                                text: "called autoregressive conditional heteroscedastic (ARCH) processes are introduced. These are mean zero, serially uncorrelated processes with nonconstant variances",166                                note: "Définition à citer dans l'introduction.", createdAt: created))167        block.add(PDFAnnotation(id: "a-ink", page: 1, kind: .ink, color: "#cc272e", rects: [PDFRect(x: 0.1, y: 0.37, width: 0.3, height: 0.06)],168                                ink: (0...24).map { i in PDFPoint(x: 0.1 + Double(i) / 24 * 0.3, y: 0.40 + sin(Double(i) / 24 * .pi * 4) * 0.03) }, createdAt: created))169        return block170    }171172    /// One chart per kind, on the same small table.173    public static func sampleChart(_ kind: ChartKind) -> ChartBlock {174        ChartBlock(kind: kind, title: kind == .pie ? "Répartition des erreurs" : "Erreur de prévision par modèle",175                   columns: ["Modèle", "QLIKE", "MSE"],176                   rows: [["GARCH", 0.412, 1.93], ["EGARCH", 0.401, 1.84], ["GJR", 0.397, 1.80], ["HAR-RV", 0.388, 1.71], ["Chronos", 0.379, 1.66]],177                   x: "Modèle", y: kind == .pie ? ["MSE"] : ["QLIKE", "MSE"])178    }179180    /// A chart fed live by a database (the stub of `POST /api/query` answers it); its own rows are the last snapshot.181    public static func sampleLiveChart() -> ChartBlock {182        var block = ChartBlock(kind: .bar, title: "Pages par article", columns: ["Article", "Année", "Pages"], rows: [["Engle (1982)", 1982, 21]], x: "Article", y: ["Pages"])183        block.source = ChartSource(databaseId: chartDatabaseId)184        return block185    }186}187
Files main
Menu

Theme