SPB Git

Repository Public

Support.swift 11.4 KB 205 lines swift

1// SP Notes Core2// File: Tests/SPNotesDocumentTests/Support.swift3// Description: Test support: fixtures, a compact tree notation, a seeded generator and random document builders.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9@testable import SPNotesDocument1011enum Fixture {12    static func data(_ name: String) throws -> Data {13        let url = try #require(Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures"))14        return try Data(contentsOf: url)15    }16    static func node(_ name: String) throws -> PMNode { try PMNode(data: data(name)) }17    static func doc(_ name: String) throws -> NoteDocument { try NoteDocument(json: data(name)) }18    /// Reference outputs computed by the web application's own helpers (text.ts) for rich.json and unknown.json.19    static func expected(_ index: Int) throws -> JSONValue {20        try #require(try JSONValue(data: data("expected")).arrayValue)[index]21    }22}2324/// Compact notation of a tree: `ul(li(p("a")))`, text as `"a"[bold]`.25func sexp(_ n: PMNode) -> String {26    if n.type == "text" {27        let marks = (n.marks ?? []).map(\.type).joined(separator: ",")28        return "\"\(n.text ?? "")\"" + (marks.isEmpty ? "" : "[\(marks)]")29    }30    if n.type == "doc" { return (n.content ?? []).map(sexp).joined(separator: " ") }31    let name: String32    switch n.type {33    case "paragraph": name = "p"34    case "heading": name = "h\(n.attrs?["level"]?.intValue ?? 0)"35    case "bulletList": name = "ul"36    case "orderedList": name = "ol"37    case "taskList": name = "tl"38    case "listItem": name = "li"39    case "taskItem": name = n.attrs?["checked"] == .bool(true) ? "ti[x]" : "ti[ ]"40    case "blockquote": name = "bq"41    case "codeBlock": name = "code"42    case "horizontalRule": name = "hr"43    case "hardBreak": name = "br"44    default: name = n.type45    }46    let kids = (n.content ?? []).map(sexp).joined(separator: " ")47    return kids.isEmpty ? name : "\(name)(\(kids))"48}49func sexp(_ d: NoteDocument) -> String { sexp(d.pmNode()) }5051/// `#expect` for expressions calling mutating commands (the macro cannot capture those).52func check(_ condition: Bool, _ comment: Comment? = nil, sourceLocation: SourceLocation = #_sourceLocation) {53    #expect(condition, comment, sourceLocation: sourceLocation)54}5556func md(_ s: String) -> NoteDocument { NoteDocument(markdown: s) }5758/// Asserts the document is exactly what the web editor would serialize, and that it survives a round trip.59func expectValid(_ d: NoteDocument, _ label: String = "", sourceLocation: SourceLocation = #_sourceLocation) {60    let issues = d.schemaViolations(strict: true)61    #expect(issues.isEmpty, "\(label): \(issues.prefix(5))", sourceLocation: sourceLocation)62    let again = NoteDocument(node: d.pmNode())63    #expect(again.isStructurallyEqual(to: d), "\(label): unstable round trip", sourceLocation: sourceLocation)64    var keys: [Int: [Int]] = [:]65    for (i, line) in d.lines.enumerated() { for c in line.path { keys[c.key, default: []].append(i) } }66    for (k, lines) in keys { #expect(lines == Array(lines[0]...lines[lines.count - 1]), "\(label): container \(k) is not contiguous", sourceLocation: sourceLocation) }67}6869struct SplitMix64: RandomNumberGenerator {70    var state: UInt6471    init(seed: UInt64) { state = seed }72    mutating func next() -> UInt64 {73        state &+= 0x9E3779B97F4A7C1574        var z = state75        z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B976        z = (z ^ (z >> 27)) &* 0x94D049BB133111EB77        return z ^ (z >> 31)78    }79    mutating func int(_ n: Int) -> Int { Int(next() % UInt64(max(1, n))) }80    mutating func chance(_ percent: Int) -> Bool { int(100) < percent }81    mutating func pick<T>(_ a: [T]) -> T { a[int(a.count)] }82}8384enum Random {85    static let types = ["paragraph", "heading", "codeBlock", "footnote", "detailsSummary", "bulletList", "orderedList", "taskList", "listItem",86                        "taskItem", "blockquote", "callout", "aiBlock", "details", "detailsContent", "table", "tableRow", "tableCell", "image",87                        "fileBlock", "blockMath", "horizontalRule", "youtube", "hardBreak", "mention", "inlineMath", "footnoteRef", "text",88                        "text", "text", "widget", "columns", "x"]89    static let words = ["alpha", "bêta", "", " ", "l'été", "x\ny", "😀", "a|b", "<b>", "é\u{301}"]9091    static func value(_ r: inout SplitMix64, depth: Int = 2) -> JSONValue {92        switch r.int(depth > 0 ? 8 : 6) {93        case 0: return .null94        case 1: return .bool(r.chance(50))95        case 2: return .int(Int64(r.int(2000)) - 1000)96        case 3: return .double(Double(r.int(1000)) + 0.5)97        case 4, 5: return .string(r.pick(words))98        case 6: return .array((0..<r.int(3)).map { _ in value(&r, depth: depth - 1) })99        default: return .object(Dictionary((0..<r.int(3)).map { _ in (r.pick(["a", "id", "k"]), value(&r, depth: depth - 1)) }, uniquingKeysWith: { a, _ in a }))100        }101    }102103    static func attrs(_ r: inout SplitMix64) -> [String: JSONValue]? {104        if r.chance(25) { return nil }105        if r.chance(10) { return [:] }106        return Dictionary((0..<(1 + r.int(3))).map { _ in (r.pick(["id", "level", "checked", "src", "latex", "future", "textAlign"]), value(&r)) }, uniquingKeysWith: { a, _ in a })107    }108109    /// Any tree at all: known and unknown types in any arrangement, odd text nodes, unknown keys.110    static func anyNode(_ r: inout SplitMix64, depth: Int, type: String? = nil) -> PMNode {111        var n = PMNode(type: type ?? r.pick(types))112        n.attrs = attrs(&r)113        if n.type == "text" ? !r.chance(3) : r.chance(3) { n.text = r.pick(words) }114        if r.chance(n.type == "text" ? 40 : 3) {115            n.marks = (0..<r.int(4)).map { _ in PMMark(type: r.pick(["bold", "italic", "code", "link", "glow"]), attrs: r.chance(30) ? attrs(&r) : nil) }116        }117        if r.chance(5) { n.extra = ["x": value(&r)] }118        if depth > 0, r.chance(65) { n.content = (0..<r.int(5)).map { _ in anyNode(&r, depth: depth - 1) } }119        return n120    }121122    static func inlineRuns(_ r: inout SplitMix64) -> [InlineRun] {123        (0..<r.int(4)).map { _ -> InlineRun in124            switch r.int(8) {125            case 0: return .atom(.hardBreak())126            case 1: return .atom(.mention(id: "3f2b8c1e-7a4d-4e9b-9c1a-5d6e7f8a9b0c", label: "Page"))127            case 2: return .atom(.inlineMath(latex: "x^2"))128            default:129                var marks: [PMMark] = []130                if r.chance(30) { marks = InlineTools.adding(.mark(r.pick(MarkKind.allCases)), to: marks) }131                if r.chance(15) { marks = InlineTools.adding(.link(href: "https://example.org"), to: marks) }132                return .text(r.pick(["mot ", "deux mots ", "😀 emoji ", "x", "été "]), marks: marks)133            }134        }135    }136137    /// A schema-valid document built in the line model with every attribute, as the web editor serializes it.138    static func validDocument(_ r: inout SplitMix64) -> NoteDocument {139        var d = NoteDocument()140        d.lines = []141        blocks(&d, &r, path: [], depth: 0, count: 2 + r.int(5))142        d.ensureBlockIds()143        return d144    }145146    static func blocks(_ d: inout NoteDocument, _ r: inout SplitMix64, path: [Container], depth: Int, count: Int) {147        for _ in 0..<max(1, count) {148            switch r.int(depth >= 3 ? 6 : 12) {149            case 0, 1, 2: d.lines.append(.paragraph(InlineTools.normalized(inlineRuns(&r)), path: path))150            case 3: d.lines.append(.heading(level: 1 + r.int(3), InlineTools.normalized(inlineRuns(&r)), path: path))151            case 4: d.lines.append(.codeBlock(language: r.chance(50) ? "swift" : nil, text: r.pick(["", "a", "a\nb\n  c"]), path: path))152            case 5:153                let atom = [PMNode.horizontalRule(), .image(src: "/api/files/11111111-2222-4333-8444-555555555555", alt: "a"),154                            .blockMath(latex: "a^2"), .table(rows: 2, cols: 2, withHeaderRow: true),155                            .fileBlock(src: "/api/files/11111111-2222-4333-8444-555555555555", name: "f.pdf", size: 10, mime: "application/pdf", attachmentId: nil)]156                d.lines.append(Line(blockAtom: r.pick(atom), path: path))157            case 6, 7, 8:158                let kind = r.pick(ListKind.allCases)159                let list = d.makeContainer(kind.listType)160                for _ in 0..<(1 + r.int(3)) {161                    let item = d.makeContainer(kind.itemType, attrs: kind == .task ? ["checked": .bool(r.chance(50))] : [:])162                    d.lines.append(.paragraph(InlineTools.normalized(inlineRuns(&r)), path: path + [list, item]))163                    if r.chance(35) { blocks(&d, &r, path: path + [list, item], depth: depth + 1, count: 1 + r.int(2)) }164                }165            case 9:166                blocks(&d, &r, path: path + [d.makeContainer(NodeType.blockquote)], depth: depth + 1, count: 1 + r.int(3))167            case 10:168                blocks(&d, &r, path: path + [d.makeContainer(NodeType.callout, attrs: ["kind": "info", "icon": "ℹ️"])], depth: depth + 1, count: 1 + r.int(2))169            default:170                let details = d.makeContainer(NodeType.details)171                d.lines.append(Line(path: path + [details], type: NodeType.detailsSummary, content: .inline([.text("Résumé", marks: [])])))172                blocks(&d, &r, path: path + [details, d.makeContainer(NodeType.detailsContent)], depth: depth + 1, count: 1 + r.int(2))173            }174        }175    }176177    /// Applies one random command; returns its name.178    static func command(_ d: inout NoteDocument, _ r: inout SplitMix64) -> String {179        let n = d.lines.count180        let a = r.int(n), b = min(n, a + 1 + r.int(3))181        let range = a..<b182        let len = d.lines[a].inlineLength183        let lo = r.int(len + 1), hi = min(len, lo + r.int(6))184        switch r.int(22) {185        case 0: d.setLineType(r.pick([.paragraph, .heading(level: 1 + r.int(3)), .codeBlock(language: "js")]), at: range); return "setLineType"186        case 1, 2: d.toggleList(r.pick(ListKind.allCases), at: range); return "toggleList"187        case 3, 4: d.indentListItems(at: range); return "indent"188        case 5, 6: d.outdentListItems(at: range); return "outdent"189        case 7: d.toggleBlockquote(at: range); return "toggleBlockquote"190        case 8: d.toggleCallout(kind: r.pick(["note", "warning"]), icon: "💡", at: range); return "toggleCallout"191        case 9: d.setTaskChecked(r.chance(50), at: a); return "setTaskChecked"192        case 10, 11, 12: d.splitLine(at: a, offset: lo); return "splitLine"193        case 13, 14, 15: d.mergeWithPrevious(at: a); return "mergeWithPrevious"194        case 16:195            d.insertBlockAtom(r.pick([.horizontalRule(), .table(rows: 2, cols: 3, withHeaderRow: r.chance(50)), .image(src: "https://example.org/i.png"), .blockMath(latex: "x")]), after: r.chance(10) ? nil : a)196            return "insertBlockAtom"197        case 17: d.toggleMark(r.pick(MarkKind.allCases), in: lo..<hi, at: a); return "toggleMark"198        case 18: if r.chance(50) { d.setLink(href: "/p/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d", in: lo..<hi, at: a) } else { d.removeLink(in: lo..<hi, at: a) }; return "link"199        case 19: d.replaceText(in: lo..<hi, at: a, with: r.pick(["", "x", "deux\nlignes", "😀"])); return "replaceText"200        case 20: d.insertInlineAtom(r.pick([.hardBreak(), .inlineMath(latex: "y"), .mention(id: "3f2b8c1e-7a4d-4e9b-9c1a-5d6e7f8a9b0c", label: "P")]), at: lo, line: a); return "insertInlineAtom"201        default: d.deleteLine(at: a); return "deleteLine"202        }203    }204}205
Files main
Menu

Theme