Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeaturesCatalog/Samples+Blocks.swift3// Description: Sample data of the « Blocks » area for the catalogue and the tests: a source page for the cross-references,4// the answers of `POST /api/query` (recorded ones for pages / database / references / backlinks, a larger5// hand-made task list in the exact shape of API-NEXT §4.7), a stateful stub of the transcription routes6// (API-NEXT-AI §6: queued → pending → done with the documented answer), typed sample nodes, a drawn PNG7// standing for a Mermaid render and a generated sine recording.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import AVFoundation12import CoreGraphics13import Foundation14import ImageIO15import SPNotesDocument16import SPNotesFeatures17import SPNotesTestSupport18import UniformTypeIdentifiers1920public enum BlockSamples {21 public static let sourcePageId = "7b2e0c5e-2b22-4c7e-8b20-0000000000c1"22 public static let audioAttachmentId = "82f70f18-d19f-4d58-ba81-8a4d72099e17"23 public static let mermaidPreviewId = "7b2e0c5e-2b22-4c7e-8b20-0000000000f1"24 public static let missingPageId = "7b2e0c5e-2b22-4c7e-8b20-00000000dead"2526 // MARK: source page of the references2728 /// A page with one block of each kind the reference renderer draws.29 public static var sourceDocument: Data {30 func text(_ value: String, _ marks: [String] = []) -> [String: Any] {31 var node: [String: Any] = ["type": "text", "text": value]32 if !marks.isEmpty { node["marks"] = marks.map { ["type": $0] } }33 return node34 }35 func paragraph(_ id: String?, _ content: [[String: Any]]) -> [String: Any] {36 var node: [String: Any] = ["type": "paragraph", "content": content]37 if let id { node["attrs"] = ["id": id] }38 return node39 }40 let content: [[String: Any]] = [41 ["type": "heading", "attrs": ["id": "ref-h1", "level": 2], "content": [text("Hypothèses de travail")]],42 paragraph("ref-p1", [text("La volatilité réalisée à "), text("une minute", ["bold"]), text(" précède la détérioration comptable de "), text("deux trimestres", ["italic"]), text(".")]),43 ["type": "bulletList", "attrs": ["id": "ref-list"], "content": [44 ["type": "listItem", "attrs": ["id": "ref-li1"], "content": [paragraph(nil, [text("Échantillon : Russell 3000, 2010–2025")])]],45 ["type": "listItem", "attrs": ["id": "ref-li2"], "content": [paragraph(nil, [text("Fréquences comparées : 1 min, 5 min, 30 min, quotidien")]),46 ["type": "bulletList", "content": [["type": "listItem", "content": [paragraph(nil, [text("Le quotidien sert de témoin")])]]]]]],47 ]],48 ["type": "taskList", "attrs": ["id": "ref-tasks"], "content": [49 ["type": "taskItem", "attrs": ["id": "ref-t1", "checked": true], "content": [paragraph(nil, [text("Nettoyer les doublons de l'univers")])]],50 ["type": "taskItem", "attrs": ["id": "ref-t2", "checked": false], "content": [paragraph(nil, [text("Relancer l'estimation avec erreurs groupées")])]],51 ]],52 ["type": "callout", "attrs": ["id": "ref-callout", "kind": "decision", "icon": "⚖️"], "content": [53 paragraph(nil, [text("Décision : on garde la fenêtre de 60 jours.")]),54 paragraph(nil, [text("À revoir si la couverture des petites capitalisations baisse.")]),55 ]],56 ["type": "codeBlock", "attrs": ["id": "ref-code", "language": "python"], "content": [text("rv = (returns ** 2).resample(\"1D\").sum()\nsignal = rv.rolling(60).mean()")]],57 ["type": "blockquote", "attrs": ["id": "ref-quote"], "content": [paragraph(nil, [text("Ce qui se mesure à haute fréquence finit par apparaître au bilan.")])]],58 ["type": "table", "attrs": ["id": "ref-table"], "content": []],59 ]60 return try! JSONSerialization.data(withJSONObject: ["type": "doc", "content": content], options: [.sortedKeys])61 }6263 public static func blockRef(_ blockId: String?, mode: BlockRefMode = .embed, pageId: String = sourcePageId) -> BlockRefBlock {64 BlockRefBlock(pageId: pageId, blockId: blockId, mode: mode)65 }6667 // MARK: living blocks6869 /// `POST /api/query` for tasks, in the recorded shape (API-NEXT §4.7), with enough rows to judge the layouts.70 public static var tasksQueryJSON: String {71 let rows: [(String, String, String, String?, String, String?)] = [72 ("Relire la section 2", "todo", "high", "2026-11-17T12:00:00.000Z", "Volatilité conditionnelle", "WP 46"),73 ("Mettre à jour la table des variantes", "doing", "medium", "2026-11-21T12:00:00.000Z", "Modèles GARCH", "WP 46"),74 ("Répondre à l'arbitre B", "doing", "high", "2026-11-20T12:00:00.000Z", "Revue de littérature", nil),75 ("Préparer la séance 12", "todo", "medium", "2026-11-24T12:00:00.000Z", "Cours IMM1003", nil),76 ("Vérifier les unités de la figure 4", "todo", "low", nil, "Courbe des taux", "WP 47"),77 ("Archiver les données de 2024", "done", "low", "2026-11-12T12:00:00.000Z", "Archive 2024", nil),78 ("Envoyer le barème aux correcteurs", "done", "medium", "2026-11-14T12:00:00.000Z", "Barème de correction", nil),79 ]80 func q(_ value: String?) -> String { value.map { "\"\($0)\"" } ?? "null" }81 let jsonRows = rows.enumerated().map { index, row in82 "{\"id\":\"7b2e0c5e-2b22-4c7e-8b20-0000000001\(String(format: "%02d", index))\",\"pageId\":\"\(sourcePageId)\",\"blockId\":\"ref-t\(index % 2 + 1)\",\"title\":\"\(row.0)\",\"status\":\"\(row.1)\",\"priority\":\"\(row.2)\",\"dueAt\":\(q(row.3)),\"completedAt\":null,\"pageTitle\":\"\(row.4)\",\"project\":\(q(row.5))}"83 }.joined(separator: ",")84 let tableRows = rows.map { row in "[\"\(row.0)\",\"\(row.1)\",\"\(row.2)\",\(q(row.3)),\"\(row.4)\",\(q(row.5))]" }.joined(separator: ",")85 return """86 {"source":"tasks","columns":[{"key":"title","label":"Tâche","type":"text"},{"key":"status","label":"État","type":"select"},{"key":"priority","label":"Priorité","type":"select"},{"key":"dueAt","label":"Échéance","type":"date"},{"key":"pageTitle","label":"Page","type":"page"},{"key":"project","label":"Projet","type":"text"}],"rows":[\(jsonRows)],"total":9,"limit":7,"table":{"columns":["Tâche","État","Priorité","Échéance","Page","Projet"],"rows":[\(tableRows)]},"resolvedAt":"2026-11-19T14:58:00.000Z"}87 """88 }8990 public static var emptyQueryJSON: String {91 "{\"source\":\"tasks\",\"columns\":[{\"key\":\"title\",\"label\":\"Tâche\",\"type\":\"text\"}],\"rows\":[],\"total\":0,\"limit\":25,\"table\":{\"columns\":[\"Tâche\"],\"rows\":[]},\"resolvedAt\":\"2026-11-19T14:58:00.000Z\"}"92 }9394 public static func queryView(_ source: QuerySource = .tasks, layout: QueryLayout = .list, title: String = "Tâches ouvertes du projet") -> QueryViewBlock {95 QueryViewBlock(source: source, title: title, layout: layout, limit: 25, databaseId: source == .database ? "5aa3a103-d4d7-4d6e-8f78-8b122393dc1f" : nil)96 }9798 // MARK: voice note99100 public static let transcriptionPendingJSON = """101 {"queued":true,"jobId":"1b60aa7a-da87-4306-b323-e37c5f233ca9","attachmentId":"\(audioAttachmentId)","status":"pending","transcript":[],"text":"","engine":null,"model":null,"language":null,"duration":null,"segments":null,"summary":null,"error":null,"costUsd":null,"requestedAt":"2026-11-19T18:22:31.175Z","finishedAt":null}102 """103104 /// The documented answer of `GET /api/audio/<id>` once done (API-NEXT-AI §6.2), with its summary.105 public static let transcriptionDoneJSON = """106 {"attachmentId":"\(audioAttachmentId)","status":"done","transcript":[{"t":0,"text":"Réunion du 19 novembre. Nous retenons le taux fixe de 5 ans."},{"t":4.4,"text":"Marie envoie les documents à la banque lundi matin."}],"text":"Réunion du 19 novembre. Nous retenons le taux fixe de 5 ans. Marie envoie les documents à la banque lundi matin.","engine":"openai","model":"whisper-1","language":"french","duration":6.869999885559082,"segments":true,"summary":{"at":"2026-11-19T18:22:36.405Z","text":"Réunion du 19 novembre. Ils retiennent un taux fixe de 5 ans. Marie enverra les documents à la banque lundi matin.","model":"gpt-5.4-mini","tasks":["Marie envoie les documents à la banque lundi matin."],"decisions":["Ils retiennent le taux fixe de 5 ans."]},"error":null,"costUsd":null,"requestedAt":"2026-11-19T18:22:31.175Z","finishedAt":"2026-11-19T18:22:36.408Z"}107 """108109 public static let transcriptionFailedJSON = """110 {"attachmentId":"\(audioAttachmentId)","status":"failed","transcript":[],"text":"","engine":"openai","model":"whisper-1","language":null,"duration":null,"segments":null,"summary":null,"error":"Le fichier audio est illisible","costUsd":null,"requestedAt":"2026-11-19T18:22:31.175Z","finishedAt":"2026-11-19T18:22:33.000Z"}111 """112113 /// A voice note that already has its transcript and summary (the documented server answer copied into the node).114 public static var transcribedAudio: AudioBlock {115 var block = AudioBlock(attachmentId: audioAttachmentId, duration: 6.87, title: "Réunion hypothèque", recordedAt: Date(timeIntervalSince1970: 1_795_112_551))116 block.transcript = [TranscriptSegment(t: 0, text: "Réunion du 19 novembre. Nous retenons le taux fixe de 5 ans."),117 TranscriptSegment(t: 4.4, text: "Marie envoie les documents à la banque lundi matin.")]118 block.transcriptStatus = .done119 block.transcriptEngine = "openai:whisper-1"120 block[attr: "summary"] = .object(["text": "Réunion du 19 novembre. Ils retiennent un taux fixe de 5 ans. Marie enverra les documents à la banque lundi matin.",121 "decisions": ["Ils retiennent le taux fixe de 5 ans."], "tasks": ["Marie envoie les documents à la banque lundi matin."],122 "model": "gpt-5.4-mini", "at": "2026-11-19T18:22:36.405Z"])123 return block124 }125126 public static var untranscribedAudio: AudioBlock {127 AudioBlock(attachmentId: audioAttachmentId, duration: 6.87, title: "Réunion hypothèque", recordedAt: Date(timeIntervalSince1970: 1_795_112_551))128 }129130 /// Writes a real, short AAC recording of a 440 Hz sine (quiet) and returns its file.131 public static func sineRecording(seconds: Double = 2) throws -> URL {132 let url = FileManager.default.temporaryDirectory.appendingPathComponent("spn-sample-\(UUID().uuidString.lowercased()).m4a")133 let sampleRate = 44_100.0134 guard let format = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 1),135 let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(sampleRate * seconds)) else {136 throw CocoaError(.fileWriteUnknown)137 }138 buffer.frameLength = buffer.frameCapacity139 if let samples = buffer.floatChannelData?[0] {140 for frame in 0..<Int(buffer.frameLength) { samples[frame] = Float(sin(2 * Double.pi * 440 * Double(frame) / sampleRate) * 0.05) }141 }142 let settings: [String: Any] = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: sampleRate, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 64_000]143 let file = try AVAudioFile(forWriting: url, settings: settings)144 try file.write(from: buffer)145 return url146 }147148 // MARK: Mermaid149150 public static let mermaidCode = "flowchart LR\n Capture --> Tri\n Tri --> Page\n Page --> Graphe"151152 /// A node whose render matches its source.153 public static var mermaidWithPreview: MermaidBlock {154 var block = MermaidBlock(code: mermaidCode)155 block.setPreview(attachmentId: mermaidPreviewId)156 return block157 }158159 /// A drawn PNG (2×) standing for the render the web editor uploads — NOT a Mermaid renderer.160 public static func mermaidPreviewPNG() -> Data {161 let labels = ["Capture", "Tri", "Page", "Graphe"]162 let width = 1240, height = 240163 guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!,164 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return Data() }165 context.setFillColor(CGColor(srgbRed: 1, green: 1, blue: 1, alpha: 1))166 context.fill(CGRect(x: 0, y: 0, width: width, height: height))167 let boxWidth = 230.0, boxHeight = 110.0, gap = 80.0, y = (Double(height) - boxHeight) / 2168 for index in labels.indices {169 let x = 40 + Double(index) * (boxWidth + gap)170 let rect = CGRect(x: x, y: y, width: boxWidth, height: boxHeight)171 context.setFillColor(CGColor(srgbRed: 0.898, green: 0.941, blue: 1, alpha: 1))172 context.setStrokeColor(CGColor(srgbRed: 0.184, green: 0.365, blue: 0.859, alpha: 1))173 context.setLineWidth(4)174 let path = CGPath(roundedRect: rect, cornerWidth: 18, cornerHeight: 18, transform: nil)175 context.addPath(path); context.fillPath()176 context.addPath(path); context.strokePath()177 // A bar standing for the label (no text engine needed in this sample).178 context.setFillColor(CGColor(srgbRed: 0.184, green: 0.365, blue: 0.859, alpha: 1))179 let bar = Double(labels[index].count) * 18180 context.fill(CGRect(x: x + (boxWidth - bar) / 2, y: y + boxHeight / 2 - 7, width: bar, height: 14))181 if index < labels.count - 1 {182 let startX = x + boxWidth, endX = x + boxWidth + gap, midY = y + boxHeight / 2183 context.move(to: CGPoint(x: startX, y: midY)); context.addLine(to: CGPoint(x: endX - 6, y: midY)); context.strokePath()184 context.move(to: CGPoint(x: endX - 22, y: midY - 12)); context.addLine(to: CGPoint(x: endX - 4, y: midY)); context.addLine(to: CGPoint(x: endX - 22, y: midY + 12)); context.strokePath()185 }186 }187 guard let image = context.makeImage() else { return Data() }188 let data = NSMutableData()189 guard let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { return Data() }190 CGImageDestinationAddImage(destination, image, nil)191 CGImageDestinationFinalize(destination)192 return data as Data193 }194195 public static let imageLoader: BlockImageLoader = { id in196 guard id == mermaidPreviewId else { throw CocoaError(.fileNoSuchFile) }197 return mermaidPreviewPNG()198 }199200 // MARK: runnable code201202 public static var runCode: RunCodeBlock {203 var block = RunCodeBlock(language: "javascript", code: "const rendements = [0.012, -0.004, 0.021, -0.013];\nconst variance = rendements.reduce((s, r) => s + r * r, 0);\nconsole.log(\"Volatilité réalisée :\", Math.sqrt(variance).toFixed(4));")204 block[attr: "output"] = .object(["text": "Volatilité réalisée : 0.0279", "error": false, "ms": 3, "at": "2026-11-19T14:41:07.000Z"])205 return block206 }207208 public static var runCodeFailed: RunCodeBlock {209 var block = RunCodeBlock(language: "javascript", code: "const x = donnees.map((d) => d.prix);")210 block[attr: "output"] = .object(["text": "ReferenceError: donnees is not defined", "error": true, "ms": 1.4, "at": "2026-11-19T14:42:10.000Z"])211 return block212 }213214 // MARK: audio file provider of the samples215216 /// Serves a generated sine file for any attachment; adopting a recording is left to the upload path.217 public struct Files: AudioFileProvider {218 public init() {}219 public func localFileURL(attachmentId: String) async throws -> URL { try BlockSamples.sineRecording(seconds: 6.87) }220 }221}222223/// Stateful stub of the transcription routes: `transcribe` queues, the first read is still pending, the next is done.224final class SampleTranscriptionServer: @unchecked Sendable {225 private let lock = NSLock()226 private var requested = false227 private var reads = 0228229 func install(on fake: FakeBackend) {230 fake.stub("POST", path: "^/api/audio/[0-9a-f-]{36}/transcribe") { [self] _ in231 lock.withLock { requested = true; reads = 0 }232 return .json(BlockSamples.transcriptionPendingJSON, status: 202)233 }234 fake.stub("GET", path: "^/api/audio/[0-9a-f-]{36}") { [self] _ in235 let state: Int = lock.withLock {236 guard requested else { return 0 }237 reads += 1238 return reads239 }240 if state == 0 { return .json(BlockSamples.transcriptionPendingJSON.replacingOccurrences(of: "\"queued\":true,", with: "").replacingOccurrences(of: "\"status\":\"pending\"", with: "\"status\":\"none\"")) }241 return .json(state >= 2 ? BlockSamples.transcriptionDoneJSON : BlockSamples.transcriptionPendingJSON)242 }243 }244}245246extension FeatureSamples {247 static func installBlocks(on world: FeatureWorld) {248 let fake = world.fake249 _ = fake.webCreatePage(id: BlockSamples.sourcePageId, title: "Plan de l'étude", content: BlockSamples.sourceDocument, section: "projects")250 fake.stub("POST", path: "^/api/query$") { request in251 // The live chart of the Media samples answers for its own database (the areas share one fake).252 if String(decoding: request.body, as: UTF8.self).contains(FeatureSamples.chartDatabaseId) { return nil }253 let body = (try? JSONSerialization.jsonObject(with: request.body)) as? [String: Any]254 switch body?["source"] as? String {255 case "pages": return .json(FeatureSamples.text("knowledge", "query-pages"))256 case "database": return .json(FeatureSamples.text("knowledge", "query-database"))257 case "references": return .json(FeatureSamples.text("knowledge", "query-references"))258 case "backlinks": return .json(FeatureSamples.text("knowledge", "query-backlinks"))259 default:260 let filter = body?["filter"] as? [String: Any]261 if (filter?["text"] as? String) == "introuvable" { return .json(BlockSamples.emptyQueryJSON) }262 return .json(BlockSamples.tasksQueryJSON)263 }264 }265 SampleTranscriptionServer().install(on: fake)266 }267}268