Repository Public
1// SP Notes iOS2// File: App/SampleData+Blocks.swift3// Description: The seeded note « Blocs 3.0 » of the sample workspace (UI tests and screenshots only): one of every block of4// SPEC §2 built with the Core's typed views, the extended task items and callouts, a toggle, a footnote and one5// block of an unknown type. Its files (a sample diagram render, an ink drawing, a two-page PDF, a short silent6// recording) are generated here and attached like any file; two references are put in the local research copy.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import SPNotesCore12import UIKit1314extension SampleData {15 static let blocksNoteID = id(20)16 /// Reserved for a sample canvas page (none is seeded by the editor: the card of the canvas link says so).17 static let sampleCanvasID = id(21)18 static let sampleReferenceIDs = ["5eed0000-0000-4000-8000-0000000000a1", "5eed0000-0000-4000-8000-0000000000a2"]19 static let blocksIntroBlockID = "blocs30int"2021 /// Builds the document of the note (attaching its generated files to the page, which must exist) .22 @MainActor23 static func blocksDocument(in app: AppModel, pageId: String) async throws -> NoteDocument {24 func attachmentID(_ node: PMNode) -> String {25 node.stringAttr("attachmentId") ?? AttachmentFiles.attachmentID(fromSource: node.stringAttr("src") ?? "") ?? ""26 }27 var lines: [Line] = []28 func paragraph(_ text: String) { lines.append(Line.paragraph(text: text)) }29 func heading(_ text: String) { lines.append(Line.heading(level: 2, [.text(text, marks: [])])) }30 func block(_ node: PMNode) { lines.append(Line(blockAtom: node)) }3132 var intro = Line.paragraph(text: "Cette note réunit les blocs de SP Notes 3.0 : chacun s’affiche en carte et s’ouvre d’un toucher.")33 intro.attrs["id"] = .string(blocksIntroBlockID)34 lines.append(intro)3536 heading("Diagrammes")37 let code = "graph TD\n A[Idée] --> B{Décision}\n B -->|oui| C[Action]\n B -->|non| D[Abandon]"38 var mermaid = MermaidBlock(code: code)39 let render = try await app.attach(data: sampleDiagramPNG(), filename: "diagramme.png", mime: "image/png", to: pageId)40 mermaid.setPreview(attachmentId: attachmentID(render))41 block(mermaid.node())42 block(MermaidBlock(code: "sequenceDiagram\n Alice->>Bob: Bonjour\n Bob-->>Alice: Salut").node())4344 heading("Données")45 block(ChartBlock(kind: .bar, title: "Ventes par trimestre", columns: ["Trimestre", "Ventes", "Objectif"],46 rows: [["T1", 120, 110], ["T2", 135.5, 130], ["T3", 98, 140], ["T4", 162, 150]], x: "Trimestre", y: ["Ventes", "Objectif"]).node())47 block(QueryViewBlock(source: .tasks, title: "Tâches ouvertes", filter: QueryFilter(status: "open")).node())48 block(CanvasLinkBlock(pageId: sampleCanvasID).node())4950 heading("Médias")51 let ink = sampleInk()52 let inkFile = try await app.attach(data: try ink.jsonData(), filename: "dessin.ink.json", mime: "application/json", to: pageId)53 var drawing = DrawingBlock(width: ink.width, height: ink.height, background: "none")54 if let png = InkRenderer.pngData(ink, scale: 2, background: .none, crop: .canvas) {55 let preview = try await app.attach(data: png, filename: "dessin.png", mime: "image/png", to: pageId)56 drawing.setInk(attachmentId: attachmentID(inkFile), preview: attachmentID(preview), width: ink.width, height: ink.height)57 }58 block(drawing.node())59 let pdfFile = try await app.attach(data: samplePDF(), filename: "Rapport annuel.pdf", mime: "application/pdf", to: pageId)60 var pdf = PDFBlock(attachmentId: attachmentID(pdfFile), name: "Rapport annuel.pdf", page: 1)61 pdf.add(PDFAnnotation(page: 1, kind: .highlight, rects: [PDFRect(x: 0.1, y: 0.2, width: 0.5, height: 0.03)], text: "Croissance de 12 % sur l’année", note: "À citer en introduction"))62 pdf.add(PDFAnnotation(page: 2, kind: .note, rects: [PDFRect(x: 0.6, y: 0.4, width: 0.05, height: 0.05)], text: "", note: "Vérifier ce tableau"))63 block(pdf.node())64 let audioFile = try await app.attach(data: sampleWAV(seconds: 2), filename: "Réunion budget.wav", mime: "audio/wav", to: pageId)65 var audio = AudioBlock(attachmentId: attachmentID(audioFile), duration: 2, title: "Réunion budget", recordedAt: Date(timeIntervalSince1970: 1_795_000_000))66 // a transcript as the server writes one (sample text of the demo workspace)67 audio[attr: "transcript"] = .array([68 .object(["t": .int(0), "text": .string("On ouvre avec le budget du prochain trimestre.")]),69 .object(["t": .int(1), "text": .string("La priorité reste la refonte de l’éditeur.")]),70 ])71 audio[attr: "transcriptStatus"] = .string("done")72 audio[attr: "transcriptEngine"] = .string("exemple")73 block(audio.node())7475 heading("Code")76 var run = RunCodeBlock(language: "javascript", code: "const prix = [12, 18, 7];\nconst total = prix.reduce((a, b) => a + b, 0);\nconsole.log(`Total : ${total} $`);")77 run[attr: "output"] = .object(["text": .string("Total : 37 $"), "error": .bool(false), "ms": .int(4), "at": .string("2026-11-19T14:02:11.000Z")])78 block(run.node())7980 heading("Références")81 lines.append(Line.paragraph([.text("Les marchés intègrent l’information disponible ", marks: []),82 .atom(CitationInline(refId: sampleReferenceIDs[0], label: "Fama 1970", locator: "p. 383").node()),83 .text(", ce que nuance la finance comportementale ", marks: []),84 .atom(CitationInline(refId: sampleReferenceIDs[1], label: "Shiller 2003", locator: "").node()),85 .text(".", marks: [])]))86 block(BlockRefBlock(pageId: pageId, blockId: blocksIntroBlockID, mode: .embed).node())87 block(BibliographyBlock().node())8889 heading("Tâches, encadrés et suite")90 var document = NoteDocument(lines: lines)91 let tasks = NoteDocument(markdown: "- [ ] Relire le chapitre 2\n- [ ] Envoyer le résumé au comité\n- [x] Réserver la salle")92 let first = document.lines.count93 document.insert(lines: tasks.lines, at: first)94 document.setTaskDue(TaskItemDetail.dayString(Date().addingTimeInterval(2 * 86_400)), at: first)95 document.setTaskPriority(.high, at: first)96 document.setTaskPriority(.medium, at: first + 1)97 document.setTaskDue(TaskItemDetail.dayString(Date().addingTimeInterval(-3 * 86_400)), at: first + 1)98 for (kind, text) in [(CalloutKind.decision, "On garde le format ProseMirror comme source de vérité."), (.question, "Faut-il un mode hors ligne pour les bases de données ?"),99 (.hypothesis, "Les cartes natives rendent la lecture plus rapide que les blocs web.")] {100 let index = document.lines.count101 document.insert(lines: [Line.paragraph(text: text)], at: index)102 document.toggleCallout(kind, at: index..<(index + 1))103 }104 document.insert(lines: [Line(blockAtom: PMNode(type: "blocFutur", attrs: ["version": .int(4), "note": .string("écrit par un éditeur plus récent")])),105 Line.paragraph(text: "Fin de la note.")], at: document.lines.count)106 document.ensureBlockIds()107 return document108 }109110 /// Two references of the sample research library, as the entity feed would deliver them.111 @MainActor112 static func seedSampleReferences(into app: AppModel) async {113 let rows: [(String, String)] = [114 (sampleReferenceIDs[0], #"{"id":"\#(sampleReferenceIDs[0])","pageId":null,"citeKey":"fama1970efficient","entryType":"article","title":"Efficient Capital Markets: A Review of Theory and Empirical Work","authors":["Eugene F. Fama"],"year":1970,"journal":"The Journal of Finance","rev":1}"#),115 (sampleReferenceIDs[1], #"{"id":"\#(sampleReferenceIDs[1])","pageId":null,"citeKey":"shiller2003efficient","entryType":"article","title":"From Efficient Markets Theory to Behavioral Finance","authors":["Robert J. Shiller"],"year":2003,"journal":"Journal of Economic Perspectives","rev":2}"#),116 ]117 _ = try? await app.store.applyRemoteEntities(rows.enumerated().map { RemoteEntity(kind: .reference, id: $0.element.0, rev: Int64($0.offset + 1), json: Data($0.element.1.utf8)) })118 }119120 // MARK: generated files121122 /// A simple flow drawn here to stand for the render the Web uploads (the sample has no Web to render it).123 @MainActor124 static func sampleDiagramPNG() -> Data {125 let size = CGSize(width: 320, height: 250)126 let format = UIGraphicsImageRendererFormat()127 format.scale = 2128 format.opaque = false129 return UIGraphicsImageRenderer(size: size, format: format).pngData { context in130 let cg = context.cgContext131 UIColor.white.setFill(); UIRectFill(CGRect(origin: .zero, size: size)) // a render is a picture on its own background132 let stroke = UIColor(red: 0.18, green: 0.36, blue: 0.86, alpha: 1), fill = UIColor(red: 0.90, green: 0.94, blue: 1, alpha: 1), ink = UIColor(red: 0.08, green: 0.10, blue: 0.13, alpha: 1)133 func label(_ text: String, in rect: CGRect) {134 let string = NSAttributedString(string: text, attributes: [.font: UIFont.systemFont(ofSize: 13, weight: .medium), .foregroundColor: ink])135 let s = string.size()136 string.draw(at: CGPoint(x: rect.midX - s.width / 2, y: rect.midY - s.height / 2))137 }138 func box(_ text: String, _ rect: CGRect, diamond: Bool = false) {139 let path: UIBezierPath140 if diamond {141 path = UIBezierPath()142 path.move(to: CGPoint(x: rect.midX, y: rect.minY)); path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))143 path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY)); path.addLine(to: CGPoint(x: rect.minX, y: rect.midY)); path.close()144 } else { path = UIBezierPath(roundedRect: rect, cornerRadius: 6) }145 fill.setFill(); path.fill(); stroke.setStroke(); path.lineWidth = 1.5; path.stroke()146 label(text, in: rect)147 }148 func arrow(_ from: CGPoint, _ to: CGPoint) {149 cg.setStrokeColor(stroke.cgColor); cg.setLineWidth(1.5)150 cg.move(to: from); cg.addLine(to: to); cg.strokePath()151 let angle = atan2(to.y - from.y, to.x - from.x)152 cg.move(to: to)153 cg.addLine(to: CGPoint(x: to.x - 7 * cos(angle - 0.45), y: to.y - 7 * sin(angle - 0.45)))154 cg.move(to: to)155 cg.addLine(to: CGPoint(x: to.x - 7 * cos(angle + 0.45), y: to.y - 7 * sin(angle + 0.45)))156 cg.strokePath()157 }158 box("Idée", CGRect(x: 120, y: 10, width: 80, height: 34))159 box("Décision", CGRect(x: 100, y: 80, width: 120, height: 70), diamond: true)160 box("Action", CGRect(x: 30, y: 200, width: 90, height: 34))161 box("Abandon", CGRect(x: 200, y: 200, width: 90, height: 34))162 arrow(CGPoint(x: 160, y: 44), CGPoint(x: 160, y: 80))163 arrow(CGPoint(x: 130, y: 135), CGPoint(x: 80, y: 200))164 arrow(CGPoint(x: 190, y: 135), CGPoint(x: 240, y: 200))165 label("oui", in: CGRect(x: 70, y: 150, width: 40, height: 20))166 label("non", in: CGRect(x: 215, y: 150, width: 40, height: 20))167 }168 }169170 static func sampleInk() -> InkDocument {171 func stroke(_ tool: InkTool, _ color: String, _ width: Double, _ points: [(Double, Double)]) -> InkStroke? {172 guard let colour = InkColor(hex: color) else { return nil }173 return InkStroke(tool: tool, color: colour, width: width, points: points.map { InkPoint(x: $0.0, y: $0.1, pressure: 0.6) })174 }175 var strokes: [InkStroke] = []176 // a wave, an underline and a highlighted zone177 let wave = stride(from: 0.0, through: 1.0, by: 0.04).map { t in (40 + t * 520, 110 + sin(t * 4 * Double.pi) * 55) }178 if let s = stroke(.pen, "#2f5ddbff", 4, wave) { strokes.append(s) }179 if let s = stroke(.marker, "#151922ff", 6, [(60, 210), (200, 216), (360, 208), (540, 214)]) { strokes.append(s) }180 if let s = stroke(.highlighter, "#f2af48ff", 26, [(220, 60), (420, 62)]) { strokes.append(s) }181 return InkDocument(width: 600, height: 260, strokes: strokes)182 }183184 @MainActor185 static func samplePDF() -> Data {186 let bounds = CGRect(x: 0, y: 0, width: 612, height: 792)187 return UIGraphicsPDFRenderer(bounds: bounds).pdfData { context in188 for (index, title) in ["Rapport annuel", "Annexe — tableaux"].enumerated() {189 context.beginPage()190 (title as NSString).draw(at: CGPoint(x: 72, y: 80), withAttributes: [.font: UIFont.systemFont(ofSize: 30, weight: .bold)])191 let body = index == 0 ? "Croissance de 12 % sur l’année, portée par les abonnements.\nLes dépenses restent sous le budget prévu." : "Tableau 1 — Revenus par trimestre\nTableau 2 — Dépenses par poste"192 (body as NSString).draw(in: CGRect(x: 72, y: 150, width: 468, height: 300), withAttributes: [.font: UIFont.systemFont(ofSize: 15)])193 }194 }195 }196197 /// A valid mono 8 kHz 16-bit PCM WAV file of silence.198 static func sampleWAV(seconds: Int) -> Data {199 let rate: UInt32 = 8000, samples = UInt32(max(1, seconds)) * rate, dataSize = samples * 2200 var data = Data()201 func append32(_ v: UInt32) { withUnsafeBytes(of: v.littleEndian) { data.append(contentsOf: $0) } }202 func append16(_ v: UInt16) { withUnsafeBytes(of: v.littleEndian) { data.append(contentsOf: $0) } }203 data.append(contentsOf: Array("RIFF".utf8)); append32(36 + dataSize); data.append(contentsOf: Array("WAVE".utf8))204 data.append(contentsOf: Array("fmt ".utf8)); append32(16); append16(1); append16(1); append32(rate); append32(rate * 2); append16(2); append16(16)205 data.append(contentsOf: Array("data".utf8)); append32(dataSize)206 data.append(Data(count: Int(dataSize)))207 return data208 }209}210