SPB Git

Repository Public

DocsStore.swift 10.7 KB 226 lines swift

1// ORIX DJ2// File: App/Sources/Features/Docs/DocsStore.swift3// Description: Loads the ORIX Script documentation bundled with the app (Markdown chapters + manifest), builds the4//              table of contents, resolves links between chapters and searches the full text.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Observation1011struct DocChapter: Identifiable, Sendable {12    var id: String { file }13    /// Path relative to the documentation folder, e.g. "timing.md" or "examples/README.md".14    var file: String15    var title: String16    var document: MarkdownDocument17    /// Source lines with the Markdown punctuation removed, for search.18    var searchLines: [(line: Int, text: String)]19}2021struct DocEntry: Identifiable, Sendable, Equatable {22    var id: String { file }23    var file: String24    var title: String25    /// Chapter number in reading order; nil for the pages listed under a chapter.26    var number: Int?27    var parent: String?28    var hasChildren = false29}3031struct DocSearchHit: Identifiable, Sendable {32    var id: Int33    var file: String34    var line: Int35    var text: String36    var match: Range<String.Index>37}3839struct DocSearchGroup: Identifiable, Sendable {40    var id: String { file }41    var file: String42    var title: String43    var hits: [DocSearchHit]44}4546@MainActor @Observable47final class DocsStore {48    enum Phase { case loading, ready, unavailable }4950    private(set) var phase: Phase = .loading51    private(set) var chapters: [String: DocChapter] = [:]52    private(set) var entries: [DocEntry] = []53    /// Chapters named by the manifest whose file is not in this build.54    private(set) var missingFiles: [String] = []55    private(set) var usedManifest = false56    var expanded: Set<String> = []5758    /// Where the reader should scroll after the current chapter is shown.59    private(set) var scrollNode: Int?60    private(set) var scrollToken = 061    /// Block marked as the search match or link target.62    private(set) var markedNode: Int?63    /// Code block to run in the simulator as soon as it is shown (`-ORIXDocsRunFirst YES`).64    var autoRunSource: String?6566    private struct Loaded: Sendable {67        var chapters: [String: DocChapter]68        var entries: [DocEntry]69        var missing: [String]70        var usedManifest: Bool71    }7273    nonisolated static func resolve(_ destination: String, from file: String) -> (file: String, anchor: String?) {74        let parts = destination.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false)75        let path = (parts.first.map(String.init) ?? "").removingPercentEncoding ?? ""76        let anchor = parts.count > 1 ? String(parts[1]) : nil77        guard !path.isEmpty else { return (file, anchor) }78        var components = path.hasPrefix("/") ? [] : Array(file.split(separator: "/").dropLast().map(String.init))79        for c in path.split(separator: "/") {80            if c == "." { continue }81            if c == ".." { if !components.isEmpty { components.removeLast() }; continue }82            components.append(String(c))83        }84        return (components.joined(separator: "/"), anchor)85    }8687    nonisolated static func isExternal(_ destination: String) -> Bool {88        let d = destination.lowercased()89        return d.hasPrefix("http://") || d.hasPrefix("https://") || d.hasPrefix("mailto:")90    }9192    private nonisolated static func searchText(_ line: String) -> String {93        var t = line.trimmingCharacters(in: .whitespaces)94        if t.hasPrefix("```") || t.hasPrefix("~~~") { return "" }95        while let f = t.first, f == "#" || f == ">" { t.removeFirst() }96        t = t.trimmingCharacters(in: .whitespaces)97        if t.hasPrefix("- ") || t.hasPrefix("* ") { t.removeFirst(2) }98        if t.hasPrefix("|") {99            if t.allSatisfy({ "|-: ".contains($0) }) { return "" }100            t = MarkdownParser.cells(t).joined(separator: "  ·  ")101        }102        // Links keep their label only.103        t = t.replacingOccurrences(of: #"\[([^\]]*)\]\([^)]*\)"#, with: "$1", options: .regularExpression)104        t = t.replacingOccurrences(of: "**", with: "").replacingOccurrences(of: "`", with: "")105        return t106    }107108    private nonisolated static func read(root: URL) -> Loaded {109        let fm = FileManager.default110        var chapters: [String: DocChapter] = [:]111        let base = root.standardizedFileURL.path112        if let walker = fm.enumerator(at: root, includingPropertiesForKeys: nil) {113            for case let url as URL in walker where url.pathExtension.lowercased() == "md" {114                let full = url.standardizedFileURL.path115                guard full.hasPrefix(base), let data = try? Data(contentsOf: url) else { continue }116                let relative = String(full.dropFirst(base.count)).trimmingCharacters(in: CharacterSet(charactersIn: "/"))117                let text = String(decoding: data, as: UTF8.self)118                let document = MarkdownParser.parse(text)119                let title = document.headings.first?.title ?? url.deletingPathExtension().lastPathComponent120                let lines = text.components(separatedBy: "\n").enumerated().compactMap { i, l -> (line: Int, text: String)? in121                    let s = searchText(l); return s.isEmpty ? nil : (i + 1, s)122                }123                chapters[relative] = DocChapter(file: relative, title: title, document: document, searchLines: lines)124            }125        }126127        struct ManifestEntry: Decodable { var title: String; var file: String }128        var entries: [DocEntry] = []129        var missing: [String] = []130        var usedManifest = false131        if let data = try? Data(contentsOf: root.appendingPathComponent("manifest.json")), let manifest = try? JSONDecoder().decode([ManifestEntry].self, from: data), !manifest.isEmpty {132            usedManifest = true133            let listed = Set(manifest.map(\.file))134            var number = 0135            var placed: Set<String> = []136            for m in manifest {137                number += 1138                guard let chapter = chapters[m.file] else { missing.append(m.title); continue }139                chapters[m.file]?.title = m.title140                var entry = DocEntry(file: m.file, title: m.title, number: number)141                // Pages a chapter links to that are not chapters themselves (the examples) are listed under it.142                var children: [DocEntry] = []143                for link in chapter.document.links where !isExternal(link.destination) {144                    let target = resolve(link.destination, from: m.file).file145                    guard target.hasSuffix(".md"), let child = chapters[target], !listed.contains(target), !placed.contains(target) else { continue }146                    placed.insert(target)147                    children.append(DocEntry(file: target, title: child.title, parent: m.file))148                }149                entry.hasChildren = !children.isEmpty150                entries.append(entry)151                entries += children152            }153        }154        if !usedManifest {155            let files = chapters.keys.sorted { a, b in156                let ra = a.lowercased().hasSuffix("readme.md") || a == "introduction.md", rb = b.lowercased().hasSuffix("readme.md") || b == "introduction.md"157                return ra != rb ? ra : a.localizedStandardCompare(b) == .orderedAscending158            }159            entries = files.enumerated().map { DocEntry(file: $0.element, title: chapters[$0.element]?.title ?? $0.element, number: $0.offset + 1) }160        }161        return Loaded(chapters: chapters, entries: entries, missing: missing, usedManifest: usedManifest)162    }163164    func load() async {165        guard phase == .loading else { return }166        guard let root = Bundle.main.url(forResource: "orix-script", withExtension: nil) else { phase = .unavailable; return }167        let loaded = await Task.detached(priority: .userInitiated) { Self.read(root: root) }.value168        chapters = loaded.chapters; entries = loaded.entries; missingFiles = loaded.missing; usedManifest = loaded.usedManifest169        phase = entries.isEmpty ? .unavailable : .ready170    }171172    // MARK: Navigation173174    func entry(for file: String?) -> DocEntry? { entries.first { $0.file == file } }175176    /// Entries shown in the sidebar: children only under an expanded chapter.177    var visibleEntries: [DocEntry] { entries.filter { $0.parent == nil || expanded.contains($0.parent ?? "") } }178179    func neighbour(of file: String?, offset: Int) -> DocEntry? {180        guard let i = entries.firstIndex(where: { $0.file == file }), entries.indices.contains(i + offset) else { return nil }181        return entries[i + offset]182    }183184    /// Records where to scroll in `file` (the caller sets the model's current chapter).185    func target(file: String, anchor: String? = nil, line: Int? = nil, node: Int? = nil) {186        if let parent = entry(for: file)?.parent { expanded.insert(parent) }187        if entry(for: file)?.hasChildren == true { expanded.insert(file) }188        var id: Int? = node189        if let document = chapters[file]?.document {190            if let anchor, !anchor.isEmpty {191                let wanted = anchor.lowercased()192                id = document.headings.first { $0.anchor == wanted }?.id ?? document.headings.first { MarkdownParser.slug($0.title) == wanted }?.id193                // Nested headings are not scroll targets: use the enclosing top-level block.194                if let found = id, !document.nodes.contains(where: { $0.id == found }) { id = document.nodes.last { $0.id <= found }?.id }195            } else if let line { id = document.node(containingLine: line)?.id }196        }197        scrollNode = id198        markedNode = (line != nil || node != nil) ? id : nil199        scrollToken += 1200    }201202    func clearMark() { markedNode = nil }203204    // MARK: Search205206    func search(_ query: String, limit: Int = 400) -> (groups: [DocSearchGroup], total: Int, truncated: Bool) {207        let q = query.trimmingCharacters(in: .whitespaces)208        guard q.count >= 2 else { return ([], 0, false) }209        var groups: [DocSearchGroup] = []210        var total = 0211        var seen: Set<String> = []212        for entry in entries where !seen.contains(entry.file) {213            seen.insert(entry.file)214            guard let chapter = chapters[entry.file] else { continue }215            var hits: [DocSearchHit] = []216            for l in chapter.searchLines {217                guard let r = l.text.range(of: q, options: [.caseInsensitive, .diacriticInsensitive]) else { continue }218                total += 1219                if total <= limit { hits.append(DocSearchHit(id: total, file: entry.file, line: l.line, text: l.text, match: r)) }220            }221            if !hits.isEmpty { groups.append(DocSearchGroup(file: entry.file, title: entry.title, hits: hits)) }222        }223        return (groups, total, total > limit)224    }225}226
Files main
Menu

Theme