SPB Git

Repository Public

HTMLImporter.swift 53.2 KB 950 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocFormats/HTMLImporter.swift3// Description: HTML import with our own tolerant tree builder (no WebKit): paragraphs, headings, inline formatting, lists, tables4//              with spans, images from data URIs or the resource loader, a CSS subset, footnotes. Scripts, styles, frames and event5//              handlers are never interpreted and are reported as dropped.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import DocModel11import DocContainer1213public enum HTMLImporter {14    /// Never throws: an oversized input yields an empty document and a `.dropped` warning. Use `read` to get the error instead.15    /// `resourceLoader` receives the relative path of an image and returns its bytes; remote URLs are never fetched.16    public static func importDocument(_ html: String, resourceLoader: ((String) -> Data?)? = nil) -> ImportResult {17        do { return try read(html, resourceLoader: resourceLoader) } catch { return ImportFailure.result(error, format: .html) }18    }1920    public static func read(_ html: String, resourceLoader: ((String) -> Data?)? = nil) throws -> ImportResult {21        guard html.utf8.count <= FormatLimits.maxTextBytes else { throw FormatError.tooLarge("the HTML source is larger than \(FormatLimits.maxTextBytes) bytes") }22        let converter = HTMLConverter(loader: resourceLoader)23        return converter.run(html)24    }25}2627/// CSS and legacy attribute parsing shared by the converter.28enum CSSSupport {29    static func declarations(_ style: String) -> [(String, String)] {30        style.split(separator: ";").compactMap { part in31            guard let colon = part.firstIndex(of: ":") else { return nil }32            let key = part[..<colon].trimmingCharacters(in: .whitespacesAndNewlines).lowercased()33            let value = part[part.index(after: colon)...].trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "!important", with: "").trimmingCharacters(in: .whitespaces)34            return key.isEmpty || value.isEmpty ? nil : (key, value)35        }36    }3738    static let namedColours: [String: UInt32] = [39        "black": 0x000000, "white": 0xFFFFFF, "red": 0xFF0000, "green": 0x008000, "blue": 0x0000FF, "yellow": 0xFFFF00, "orange": 0xFFA500,40        "purple": 0x800080, "gray": 0x808080, "grey": 0x808080, "silver": 0xC0C0C0, "maroon": 0x800000, "navy": 0x000080, "teal": 0x008080,41        "olive": 0x808000, "lime": 0x00FF00, "aqua": 0x00FFFF, "cyan": 0x00FFFF, "fuchsia": 0xFF00FF, "magenta": 0xFF00FF, "brown": 0xA52A2A,42        "pink": 0xFFC0CB, "gold": 0xFFD700, "indigo": 0x4B0082, "violet": 0xEE82EE, "darkgray": 0xA9A9A9, "darkgrey": 0xA9A9A9,43        "lightgray": 0xD3D3D3, "lightgrey": 0xD3D3D3, "darkred": 0x8B0000, "darkgreen": 0x006400, "darkblue": 0x00008B, "crimson": 0xDC143C,44    ]4546    static func colour(_ raw: String) -> RGBA? {47        let v = raw.trimmingCharacters(in: .whitespaces).lowercased()48        if v.hasPrefix("#") {49            let hex = String(v.dropFirst())50            if hex.count == 3, hex.allSatisfy(\.isHexDigit) { return RGBA(hexString: hex.map { "\($0)\($0)" }.joined()) }51            if hex.count == 6 { return RGBA(hexString: hex) }52            if hex.count == 8, var c = RGBA(hexString: String(hex.prefix(6))), let a = UInt8(hex.suffix(2), radix: 16) { c.a = Double(a) / 255; return c }53            return nil54        }55        if v.hasPrefix("rgb"), let open = v.firstIndex(of: "("), let close = v.lastIndex(of: ")"), open < close {56            let parts = v[v.index(after: open)..<close].split(whereSeparator: { $0 == "," || $0 == " " || $0 == "/" }).map(String.init)57            guard parts.count >= 3 else { return nil }58            func channel(_ s: String) -> Double? {59                if s.hasSuffix("%"), let p = Double(s.dropLast()) { return max(0, min(1, p / 100)) }60                return Double(s).map { max(0, min(1, $0 / 255)) }61            }62            guard let r = channel(parts[0]), let g = channel(parts[1]), let b = channel(parts[2]) else { return nil }63            var alpha = 1.064            if parts.count >= 4 { alpha = parts[3].hasSuffix("%") ? (Double(parts[3].dropLast()) ?? 100) / 100 : Double(parts[3]) ?? 1 }65            return RGBA(r: r, g: g, b: b, a: max(0, min(1, alpha)))66        }67        return namedColours[v].map { RGBA(hex: $0) }68    }6970    /// A CSS length in points. `em` and `%` are relative to `base`.71    static func length(_ raw: String, base: Double) -> Double? {72        let v = raw.trimmingCharacters(in: .whitespaces).lowercased()73        func number(_ suffix: String) -> Double? { v.hasSuffix(suffix) ? Double(v.dropLast(suffix.count).trimmingCharacters(in: .whitespaces)) : nil }74        var result: Double?75        if let n = number("pt") { result = n }76        else if let n = number("px") { result = n * 0.75 }77        else if let n = number("rem") { result = n * 12 }78        else if let n = number("em") { result = n * base }79        else if let n = number("%") { result = n / 100 * base }80        else if let n = number("in") { result = n * 72 }81        else if let n = number("cm") { result = n * 72 / 2.54 }82        else if let n = number("mm") { result = n * 72 / 25.4 }83        else if let n = Double(v) { result = n * 0.75 }84        guard let r = result, r.isFinite else { return nil }85        return r86    }8788    static func alignment(_ raw: String) -> TextAlignment? {89        switch raw.trimmingCharacters(in: .whitespaces).lowercased() {90        case "left", "start": return .left91        case "right", "end": return .right92        case "center", "middle": return .center93        case "justify": return .justified94        default: return nil95        }96    }9798    static func fontFamily(_ raw: String) -> String? {99        let generic: Set<String> = ["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "inherit", "initial", "unset", "-apple-system", "blinkmacsystemfont"]100        for part in raw.split(separator: ",") {101            let name = part.trimmingCharacters(in: CharacterSet(charactersIn: " \t\n\"'"))102            if !name.isEmpty, !generic.contains(name.lowercased()), name.count <= 100 { return TextSanitizer.clean(name) }103        }104        return nil105    }106}107108final class HTMLConverter {109    private struct Frame {110        var name: String111        var char = CharProps.none112        var charStyle: String?113        var paraStyle = StyleID.normal114        var para = ParaProps.none115        var pre = false116        var skip = false117        var quote = 0118        var capture: Capture?119        var noteSection: NoteRef.Kind?120        var closingText: String?121        var isNoteItem = false122        var noteItemKind = NoteRef.Kind.footnote123        var listPushed = false124        var tablePushed = false125        var cellPushed = false126        var rowPushed = false127        var captionPushed = false128    }129    private enum Capture { case title, mathSpan(latex: String?, display: Bool), mathML(display: Bool), annotation, citation(String), noteRef(String), skipText }130131    private struct ParagraphBuilder {132        var style: String133        var props: ParaProps134        var list: ListItem?135        var runs: [Run] = []136        var lastSpace = true137        var pre: Bool138    }139    private struct Container {140        var blocks: [Block] = []141        var para: ParagraphBuilder?142        var listBase: Int143        var pending: [String] = []       // bookmarks waiting for the next paragraph144    }145    private struct ListContext { var id: String; var level: Int; var pendingItem = false; var itemOpen = false }146    private struct CellDraft { var paragraphs: [Paragraph]; var colSpan: Int; var rowSpan: Int; var header: Bool; var shading: RGBA? }147    private struct RowDraft { var cells: [CellDraft] = []; var inHead: Bool }148    private struct TableContext { var rows: [RowDraft] = []; var current: RowDraft?; var cell: CellDraft?; var section = ""; var caption: [Paragraph] = [] }149150    private var warnings = WarningCollector()151    private var images: ImageResolver152    private var lists = ListAllocator()153    private var stack: [Frame] = [Frame(name: "#root")]154    private var containers: [Container] = [Container(listBase: 0)]155    private var listStack: [ListContext] = []156    private var tables: [TableContext] = []157    private var overflow = 0158    private var captureText = ""159    private var annotationText: String?160    private var meta = DocumentMetadata()161    private var noteBodies: [String: (kind: NoteRef.Kind, paragraphs: [Paragraph])] = [:]162    private var noteContainerIDs: [String] = []163    private var optionalBookmarks: Set<String> = []164165    private static let voidElements: Set<String> = ["br", "hr", "img", "meta", "link", "input", "base", "col", "area", "embed", "source", "track", "wbr", "param"]166    private static let blockElements: Set<String> = ["p", "div", "section", "article", "main", "header", "footer", "aside", "nav", "figure", "figcaption", "address", "details",167        "summary", "dl", "dt", "dd", "form", "fieldset", "center", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre", "ul", "ol", "li", "table", "thead", "tbody", "tfoot",168        "tr", "td", "th", "caption", "hr", "body", "html", "menu", "dir"]169    private static let closesParagraph: Set<String> = ["p", "div", "section", "article", "main", "header", "footer", "aside", "nav", "figure", "figcaption", "address", "details",170        "summary", "dl", "form", "fieldset", "center", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "pre", "ul", "ol", "table", "hr", "menu", "dir"]171    private static let skippedElements: [String: (FormatWarning.Severity, String, String)] = [172        "iframe": (.dropped, "Active content", "Frames were removed; embedded pages are never loaded."),173        "frame": (.dropped, "Active content", "Frames were removed; embedded pages are never loaded."),174        "frameset": (.dropped, "Active content", "Frames were removed; embedded pages are never loaded."),175        "object": (.dropped, "Active content", "Embedded objects and plug-ins were removed."),176        "embed": (.dropped, "Active content", "Embedded objects and plug-ins were removed."),177        "applet": (.dropped, "Active content", "Embedded objects and plug-ins were removed."),178        "svg": (.dropped, "Embedded media", "Inline SVG, canvas, audio and video elements were removed."),179        "canvas": (.dropped, "Embedded media", "Inline SVG, canvas, audio and video elements were removed."),180        "audio": (.dropped, "Embedded media", "Inline SVG, canvas, audio and video elements were removed."),181        "video": (.dropped, "Embedded media", "Inline SVG, canvas, audio and video elements were removed."),182        "select": (.dropped, "Form controls", "Form controls were removed."),183        "textarea": (.dropped, "Form controls", "Form controls were removed."),184        "button": (.dropped, "Form controls", "Form controls were removed."),185        "template": (.info, "Templates", "Inert <template> content was ignored."),186        "noframes": (.info, "Templates", "Inert <template> content was ignored."),187    ]188189    init(loader: ((String) -> Data?)?) { images = ImageResolver(loader: loader) }190191    // MARK: Entry point192193    func run(_ html: String) -> ImportResult {194        var tokenizer = HTMLTokenizer(html)195        var steps = 0196        while let token = tokenizer.next() {197            steps += 1198            switch token {199            case .start(let name, let attributes, _): start(name, attributes)200            case .end(let name): end(name)201            case .text(let text): addText(text)202            case .rawText, .comment, .doctype: break      // script and style content is never looked at203            }204        }205        while stack.count > 1 { pop() }206        flushParagraph()207        var body = containers[0].blocks208        var notes: [String: Note] = [:]209        resolveNotes(&body, &notes)210        pruneBookmarks(&body)211        var doc = DocumentModel(meta: meta, body: body)212        doc.lists = lists.definitions213        doc.notes = notes214        doc.assets = images.assets215        return ImportResult(document: doc, warnings: warnings.warnings)216    }217218    // MARK: Text219220    private var top: Frame { stack[stack.count - 1] }221222    private func addText(_ raw: String) {223        let frame = top224        if frame.capture != nil { captureText += raw; return }225        if frame.skip { return }226        let ci = containers.count - 1227        if frame.pre {228            var text = TextSanitizer.clean(raw)229            if containers[ci].para == nil || containers[ci].para!.runs.isEmpty, text.hasPrefix(lineSeparatorCharacter) { text.removeFirst() }230            guard !text.isEmpty else { return }231            startParagraphIfNeeded()232            containers[ci].para!.runs.append(Run(text, props: frame.char, charStyle: frame.charStyle))233            containers[ci].para!.lastSpace = false234            return235        }236        var out = String.UnicodeScalarView()237        var lastSpace = containers[ci].para?.lastSpace ?? true238        for u in raw.unicodeScalars {239            switch u.value {240            case 0x20, 0x09, 0x0A, 0x0D, 0x0C:241                if !lastSpace { out.append(" "); lastSpace = true }242            case 0..<0x20, 0x7F: break243            case 0xFFFC: out.append("\u{FFFD}"); lastSpace = false244            default: out.append(u); lastSpace = false245            }246        }247        guard !out.isEmpty else { return }248        if containers[ci].para == nil {249            // White space alone never opens a paragraph.250            guard out.contains(where: { $0 != " " }) else { return }251            startParagraphIfNeeded()252        }253        containers[ci].para!.runs.append(Run(String(out), props: frame.char, charStyle: frame.charStyle))254        containers[ci].para!.lastSpace = lastSpace255    }256257    private func addInline(_ inline: Inline) {258        guard !top.skip else { return }259        startParagraphIfNeeded()260        let ci = containers.count - 1261        var run = Run(inline: inline)262        if case .image = inline, let link = top.char.link { run.props.link = link }263        containers[ci].para!.runs.append(run)264        containers[ci].para!.lastSpace = false265    }266267    private func startParagraphIfNeeded() {268        let ci = containers.count - 1269        guard containers[ci].para == nil else { return }270        let frame = top271        var builder = ParagraphBuilder(style: frame.paraStyle, props: frame.para, pre: frame.pre)272        if frame.quote > 0, builder.style == StyleID.normal { builder.style = StyleID.quote }273        if frame.quote > 1 { builder.props.indentLeft = 28 * Double(min(frame.quote, 12)) }274        if listStack.count > containers[ci].listBase, let k = Optional(listStack.count - 1) {275            let plain = builder.style == StyleID.normal || builder.style == StyleID.quote || builder.style == StyleID.tableText276            if listStack[k].pendingItem {277                builder.list = ListItem(listID: listStack[k].id, level: listStack[k].level)278                if plain { builder.style = StyleID.listParagraph }279                listStack[k].pendingItem = false280            } else if listStack[k].itemOpen, plain {281                builder.style = StyleID.listParagraph282                builder.props.indentLeft = 36 + 18 * Double(listStack[k].level)283            }284        }285        for name in containers[ci].pending { builder.runs.append(Run(inline: .bookmark(name))) }286        containers[ci].pending = []287        containers[ci].para = builder288    }289290    private func flushParagraph() {291        let ci = containers.count - 1292        guard var builder = containers[ci].para else { return }293        containers[ci].para = nil294        // Trim the trailing space (or the final line break of preformatted text).295        if let last = builder.runs.last, last.inline == nil {296            var text = last.text297            if builder.pre { if text.hasSuffix(lineSeparatorCharacter) { text.removeLast() } }298            else { while text.hasSuffix(" ") { text.removeLast() } }299            if text.isEmpty { builder.runs.removeLast() } else { builder.runs[builder.runs.count - 1].text = text }300        }301        if builder.runs.isEmpty, builder.list == nil { return }302        var p = Paragraph(style: builder.style, props: builder.props, runs: builder.runs, list: builder.list)303        p.healRunBoundaries()304        containers[ci].blocks.append(.paragraph(p))305    }306307    private func lineBreak() {308        guard !top.skip, top.capture == nil else { return }309        startParagraphIfNeeded()310        let ci = containers.count - 1311        if let last = containers[ci].para!.runs.last, last.inline == nil, last.text.hasSuffix(" ") {312            containers[ci].para!.runs[containers[ci].para!.runs.count - 1].text.removeLast()313        }314        containers[ci].para!.runs.append(Run(lineSeparatorCharacter, props: top.char, charStyle: top.charStyle))315        containers[ci].para!.lastSpace = true316    }317318    // MARK: Element stack319320    private func index(of name: String, boundary: Set<String>) -> Int? {321        var k = stack.count - 1322        while k >= 1 {323            if stack[k].name == name { return k }324            if boundary.contains(stack[k].name) { return nil }325            k -= 1326        }327        return nil328    }329330    private func popTo(_ k: Int) { while stack.count > k { pop() } }331332    private func closeImplied(by name: String) {333        switch name {334        case "li":335            if let k = index(of: "li", boundary: ["ul", "ol", "menu", "dir", "table", "td", "th"]) { popTo(k) }336        case "dd", "dt":337            for candidate in ["dd", "dt"] { if let k = index(of: candidate, boundary: ["dl", "table", "td", "th"]) { popTo(k) } }338        case "tr":339            for candidate in ["td", "th", "tr"] { if let k = index(of: candidate, boundary: ["table"]) { popTo(k) } }340            finishRow()          // cells that came without a <tr> form a row of their own341        case "td", "th":342            for candidate in ["td", "th"] { if let k = index(of: candidate, boundary: ["table"]) { popTo(k) } }343        case "thead", "tbody", "tfoot":344            for candidate in ["td", "th", "tr", "thead", "tbody", "tfoot"] { if let k = index(of: candidate, boundary: ["table"]) { popTo(k) } }345            finishRow()346        case "option":347            if let k = index(of: "option", boundary: ["select"]) { popTo(k) }348        default: break349        }350        if HTMLConverter.closesParagraph.contains(name) || name == "li", let k = index(of: "p", boundary: ["td", "th", "table", "li", "blockquote", "div", "section", "article"]) {351            popTo(k)352        }353    }354355    private func start(_ name: String, _ attributes: [String: String]) {356        if top.capture != nil {357            // Inside a captured element only the structure needed to find its end matters.358            if name == "annotation", (attributes["encoding"] ?? "").lowercased().contains("tex") {359                var frame = top; frame.name = name; frame.capture = .annotation360                annotationText = captureText; captureText = ""361                stack.append(frame)362            } else if !HTMLConverter.voidElements.contains(name) {363                if stack.count >= FormatLimits.maxHTMLDepth { overflow += 1 } else { var frame = top; frame.name = name; frame.capture = .skipText; stack.append(frame) }364            }365            return366        }367        if name == "script" { warnings.add(.dropped, "Active content", "Scripts were removed and never executed."); return }368        if name == "style" { warnings.add(.approximated, "Style sheets", "Embedded style sheets are ignored; only inline style attributes are read."); return }369        closeImplied(by: name)370        var frame = top371        frame.name = name372        frame.capture = nil; frame.closingText = nil; frame.isNoteItem = false373        frame.listPushed = false; frame.tablePushed = false; frame.cellPushed = false; frame.rowPushed = false; frame.captionPushed = false374        let classes = Set((attributes["class"] ?? "").lowercased().split(whereSeparator: { $0.isWhitespace }).map(String.init))375        let role = (attributes["role"] ?? "").lowercased()376        let isVoid = HTMLConverter.voidElements.contains(name)377378        if attributes.keys.contains(where: { $0.hasPrefix("on") && $0.count > 2 }) {379            warnings.add(.dropped, "Active content", "Event handler attributes were removed.")380        }381        if let (severity, feature, detail) = HTMLConverter.skippedElements[name] {382            warnings.add(severity, feature, detail)383            if !isVoid { frame.skip = true; push(frame) }384            return385        }386        if name == "title", tables.isEmpty, !frame.pre {387            // The document title, inside <head> or (in sloppy markup) anywhere else.388            frame.capture = .title; captureText = ""; push(frame); return389        }390        if frame.skip {391            // Inside <head> only the title and the metadata are read.392            if name == "meta" { readMeta(attributes) }393            if name == "link", (attributes["rel"] ?? "").lowercased().contains("stylesheet") {394                warnings.add(.approximated, "Style sheets", "External style sheets are never loaded; only inline style attributes are read.")395            }396            if !isVoid { push(frame) }397            return398        }399        if attributes["hidden"] != nil || (attributes["style"].map { s in CSSSupport.declarations(s).contains { $0.0 == "display" && $0.1.lowercased() == "none" } } ?? false) {400            warnings.add(.dropped, "Hidden content", "Elements hidden with CSS or the hidden attribute were not imported.")401            if !isVoid { frame.skip = true; push(frame) }402            return403        }404        let isBlock = HTMLConverter.blockElements.contains(name)405        if isBlock { flushParagraph() }406        if isBlock, name != "body", name != "html" {407            // Block-level formatting does not leak from an inline ancestor's link.408            frame.char.link = nil409            if frame.charStyle == StyleID.hyperlink { frame.charStyle = nil }410        }411412        // Anchors and ids.413        if let id = attributes["id"] ?? (name == "a" ? attributes["name"] : nil), !id.isEmpty, id.count <= 200 {414            let clean = TextSanitizer.clean(id)415            let explicit = name == "a" && attributes["href"] == nil416            if !explicit { optionalBookmarks.insert(clean) } else { optionalBookmarks.remove(clean) }417            if !classes.contains("footnote-ref"), !classes.contains("footnote-back"), frame.noteSection == nil || name != "li" {418                containers[containers.count - 1].pending.append(clean)419                if !isBlock, containers[containers.count - 1].para != nil {420                    let ci = containers.count - 1421                    for pending in containers[ci].pending { containers[ci].para!.runs.append(Run(inline: .bookmark(pending))) }422                    containers[ci].pending = []423                }424            }425        }426427        switch name {428        case "html":429            if let lang = attributes["lang"], !lang.isEmpty, lang.count <= 35 { meta.language = TextSanitizer.clean(lang) }430        case "head":431            frame.skip = true432        case "h1", "h2", "h3", "h4", "h5", "h6":433            frame.paraStyle = classes.contains("title") ? StyleID.title : StyleID.heading(Int(name.dropFirst()) ?? 1)434            frame.char = .none; frame.charStyle = nil435        case "p", "div":436            if classes.contains("subtitle") { frame.paraStyle = StyleID.subtitle }437            else if classes.contains("abstract") { frame.paraStyle = StyleID.abstract }438            else if classes.contains("caption") { frame.paraStyle = StyleID.caption }439            else if classes.contains("title") { frame.paraStyle = StyleID.title }440            if classes.contains("page-break") { containers[containers.count - 1].blocks.append(.pageBreak(BreakBlock())) }441            if classes.contains("math"), name == "div" { beginMathSpan(&frame, attributes, display: true); push(frame); return }442        case "blockquote":443            frame.quote += 1444            if frame.paraStyle == StyleID.normal || frame.paraStyle == StyleID.quote { frame.paraStyle = StyleID.quote }445            if frame.quote == 2 { warnings.add(.approximated, "Block quotes", "Nested block quotes are written as indented quotes.") }446        case "pre":447            frame.pre = true448            frame.paraStyle = StyleID.code449        case "figcaption":450            frame.paraStyle = StyleID.caption451        case "caption":452            frame.paraStyle = StyleID.caption453            if !tables.isEmpty { containers.append(Container(listBase: listStack.count)); frame.captionPushed = true }454        case "center":455            frame.para.alignment = .center456        case "dt": frame.char.bold = true457        case "dd": frame.para.indentLeft = (frame.para.indentLeft ?? 0) + 36458        case "b", "strong": frame.char.bold = true459        case "i", "em", "cite", "dfn", "var": frame.char.italic = true460        case "u", "ins": frame.char.underline = true461        case "s", "strike", "del": frame.char.strikethrough = true462        case "sub": frame.char.vertical = .subscript463        case "sup": frame.char.vertical = .superscript464        case "code", "kbd", "samp", "tt":465            if !frame.pre { frame.charStyle = StyleID.inlineCode }466        case "mark": frame.char.highlight = RGBA(hex: 0xFFF59D)467        case "q":468            addText("\u{201C}"); frame.closingText = "\u{201D}"469        case "font":470            if let c = attributes["color"].flatMap(CSSSupport.colour) { frame.char.color = c }471            if let f = attributes["face"].flatMap(CSSSupport.fontFamily) { frame.char.fontFamily = f }472        case "a":473            if classes.contains("footnote-ref") || role == "doc-noteref", let href = attributes["href"], href.hasPrefix("#") {474                frame.capture = .noteRef(String(href.dropFirst())); captureText = ""475                push(frame); return476            }477            if classes.contains("footnote-back") || classes.contains("fn-back") || role == "doc-backlink" {478                frame.capture = .skipText; push(frame); return479            }480            if let href = attributes["href"], !href.isEmpty {481                if let safe = LinkPolicy.sanitize(href) { frame.char.link = safe; frame.charStyle = StyleID.hyperlink }482                else { warnings.add(.dropped, "Active content", "A link with a script or data scheme was removed; its text was kept.") }483            }484        case "span":485            if classes.contains("math") { beginMathSpan(&frame, attributes, display: classes.contains("display")); push(frame); return }486            if classes.contains("citation"), let items = attributes["data-cite-items"] ?? attributes["data-cites"].map({ $0.split(separator: " ").map { "@" + $0 }.joined(separator: "; ") }) {487                frame.capture = .citation(items); captureText = ""488                push(frame); return489            }490        case "math":491            frame.capture = .mathML(display: (attributes["display"] ?? "").lowercased() == "block"); captureText = ""; annotationText = nil492            push(frame); return493        case "br": lineBreak()494        case "hr":495            if frame.noteSection == nil {496                if classes.contains("page-break") { containers[containers.count - 1].blocks.append(.pageBreak(BreakBlock())) }497                else { containers[containers.count - 1].blocks.append(.paragraph(ModelIdiom.rule())) }498            }499        case "img": image(attributes)500        case "ul", "ol", "menu", "dir":501            if frame.noteSection != nil, name == "ol" { break }502            let ordered = name == "ol"503            let startNumber = max(0, min(1_000_000, Int(attributes["start"] ?? "") ?? 1))504            var format: NumberFormat?505            switch attributes["type"] ?? "" {506            case "a": format = .lowerAlpha507            case "A": format = .upperAlpha508            case "i": format = .lowerRoman509            case "I": format = .upperRoman510            default: break511            }512            let base = containers[containers.count - 1].listBase513            if listStack.count > base, let parent = listStack.last {514                if parent.pendingItem {515                    // The parent item has no text of its own: its bullet still comes before the nested list.516                    flushParagraph()517                    containers[containers.count - 1].blocks.append(.paragraph(Paragraph(style: StyleID.listParagraph, list: ListItem(listID: parent.id, level: parent.level))))518                    listStack[listStack.count - 1].pendingItem = false519                }520                var level = parent.level + 1521                if level > FormatLimits.maxListLevel {522                    level = FormatLimits.maxListLevel523                    warnings.add(.approximated, "Deep lists", "Lists nested deeper than \(FormatLimits.maxListLevel + 1) levels are flattened to the deepest level.")524                }525                listStack.append(ListContext(id: lists.sublist(parent: parent.id, level: level, ordered: ordered, start: startNumber, format: format), level: level))526            } else {527                listStack.append(ListContext(id: lists.newList(ordered: ordered, start: startNumber, format: format), level: 0))528            }529            frame.listPushed = true530        case "li":531            if let section = frame.noteSection {532                // A footnote body.533                let id = attributes["id"] ?? "note-\(noteBodies.count + noteContainerIDs.count + 1)"534                containers.append(Container(listBase: listStack.count))535                noteContainerIDs.append(id)536                frame.isNoteItem = true537                frame.noteItemKind = section538                frame.paraStyle = StyleID.footnoteText539                frame.noteSection = nil          // lists inside the note are ordinary lists540                break541            }542            if listStack.count <= containers[containers.count - 1].listBase {543                // <li> outside any list: an implicit bulleted list.544                listStack.append(ListContext(id: lists.newList(ordered: false), level: 0))545                frame.listPushed = true546            }547            listStack[listStack.count - 1].pendingItem = true548            listStack[listStack.count - 1].itemOpen = true549        case "table":550            tables.append(TableContext())551            frame.tablePushed = true552            frame.char = .none; frame.charStyle = nil; frame.para = .none; frame.paraStyle = StyleID.normal; frame.quote = 0; frame.pre = false553        case "thead", "tbody", "tfoot":554            if !tables.isEmpty { tables[tables.count - 1].section = name }555        case "tr":556            if !tables.isEmpty {557                tables[tables.count - 1].current = RowDraft(inHead: tables[tables.count - 1].section == "thead")558                frame.rowPushed = true559            }560        case "td", "th":561            guard !tables.isEmpty else { break }562            if tables[tables.count - 1].current == nil { tables[tables.count - 1].current = RowDraft(inHead: tables[tables.count - 1].section == "thead") }563            let colSpan = max(1, min(FormatLimits.maxTableColumns, Int(attributes["colspan"] ?? "") ?? 1))564            let rowSpan = max(1, min(65_534, Int(attributes["rowspan"] ?? "") ?? 1))565            tables[tables.count - 1].cell = CellDraft(paragraphs: [], colSpan: colSpan, rowSpan: rowSpan, header: name == "th", shading: attributes["bgcolor"].flatMap(CSSSupport.colour))566            containers.append(Container(listBase: listStack.count))567            frame.cellPushed = true568            frame.paraStyle = StyleID.tableText569        case "section", "nav", "aside":570            if classes.contains("endnotes") { frame.noteSection = .endnote }571            else if classes.contains("footnotes") || role == "doc-endnotes" || role == "doc-footnotes" { frame.noteSection = .footnote }572            else if classes.contains("toc"), name == "nav" {573                var kind = TOCBlock.Kind.contents574                if let k = attributes["data-kind"], let parsed = TOCBlock.Kind(rawValue: k) { kind = parsed }575                let title = attributes["data-title"].map(TextSanitizer.clean)576                containers[containers.count - 1].blocks.append(.toc(TOCBlock(kind: kind, title: title, maxLevel: max(1, min(9, Int(attributes["data-max-level"] ?? "") ?? 3)))))577                frame.skip = true578            } else if classes.contains("orix-bibliography") {579                containers[containers.count - 1].blocks.append(.bibliography(BibliographyBlock(title: attributes["data-title"].map(TextSanitizer.clean))))580                frame.skip = true581            }582        case "input", "form", "fieldset":583            if name == "input" { warnings.add(.dropped, "Form controls", "Form controls were removed.") }584        case "base", "link", "meta":585            if name == "meta", (attributes["http-equiv"] ?? "").lowercased() == "refresh" { warnings.add(.dropped, "Active content", "A page refresh / redirect instruction was removed.") }586        default: break587        }588589        // Presentational attributes and the inline style subset.590        if let align = attributes["align"].flatMap(CSSSupport.alignment), isBlock { frame.para.alignment = align }591        if let dir = attributes["dir"]?.lowercased(), isBlock, dir == "rtl" || dir == "ltr" { frame.para.rightToLeft = dir == "rtl" }592        if let style = attributes["style"] { applyStyle(style, to: &frame, element: name) }593        if frame.cellPushed, let shading = frame.para.shading { tables[tables.count - 1].cell?.shading = shading; frame.para.shading = nil }594595        if !isVoid { push(frame) }596    }597598    private func push(_ frame: Frame) {599        if stack.count >= FormatLimits.maxHTMLDepth {600            // Too deep: the element is treated as transparent. Undo the side effects that expect a matching pop.601            overflow += 1602            if overflow == 1 { warnings.add(.approximated, "Deep nesting", "Elements nested deeper than \(FormatLimits.maxHTMLDepth) levels are flattened.") }603            var f = frame604            f.capture = nil605            close(f)606            return607        }608        stack.append(frame)609    }610611    private func end(_ name: String) {612        if overflow > 0, stack.count >= FormatLimits.maxHTMLDepth, stack.last?.name != name { overflow -= 1; return }613        if top.capture != nil {614            // Close captured elements up to the one that started the capture.615            guard let k = stack.lastIndex(where: { $0.name == name }), k >= 1, stack[k].capture != nil else { return }616            popTo(k)617            return618        }619        if name == "br" { lineBreak(); return }620        if name == "p", index(of: "p", boundary: ["td", "th", "table"]) == nil { flushParagraph(); return }621        if name == "body" || name == "html" { return }622        let boundary: Set<String>623        switch name {624        case "td", "th", "tr", "thead", "tbody", "tfoot", "caption": boundary = ["table"]625        case "table": boundary = []626        case "li": boundary = ["ul", "ol", "menu", "dir", "td", "th", "table"]627        default: boundary = ["td", "th", "table"]628        }629        guard let k = index(of: name, boundary: boundary) else { return }630        popTo(k)631    }632633    private func pop() {634        let frame = stack.removeLast()635        close(frame)636    }637638    private func close(_ frame: Frame) {639        if let capture = frame.capture { finishCapture(capture, frame); return }640        if let text = frame.closingText { addText(text) }641        let name = frame.name642        if HTMLConverter.blockElements.contains(name) { flushParagraph() }643        if frame.captionPushed {644            let container = containers.removeLast()645            if !tables.isEmpty { tables[tables.count - 1].caption += container.blocks.compactMap(\.paragraph) }646        }647        if frame.cellPushed { finishCell() }648        if frame.rowPushed || (name == "tr" && !tables.isEmpty) { finishRow() }649        if frame.tablePushed { finishTable() }650        if frame.isNoteItem {651            let container = containers.removeLast()652            let id = noteContainerIDs.removeLast()653            let paragraphs = flatten(container.blocks)654            if noteBodies[id] == nil { noteBodies[id] = (frame.noteItemKind, paragraphs.isEmpty ? [Paragraph(style: StyleID.footnoteText)] : paragraphs) }655        }656        if name == "li", !frame.isNoteItem, let last = listStack.indices.last, listStack.count > containers[containers.count - 1].listBase {657            if listStack[last].pendingItem {658                // An item without text of its own (it may hold only a nested list): keep its bullet.659                containers[containers.count - 1].blocks.append(.paragraph(Paragraph(style: StyleID.listParagraph, list: ListItem(listID: listStack[last].id, level: listStack[last].level))))660            }661            listStack[last].pendingItem = false662            listStack[last].itemOpen = false663        }664        if frame.listPushed, listStack.count > containers[containers.count - 1].listBase { listStack.removeLast() }665    }666667    // MARK: Captured elements668669    private func beginMathSpan(_ frame: inout Frame, _ attributes: [String: String], display: Bool) {670        frame.capture = .mathSpan(latex: attributes["data-latex"], display: display)671        captureText = ""672    }673674    private func finishCapture(_ capture: Capture, _ frame: Frame) {675        let text = captureText676        switch capture {677        case .skipText: return678        case .annotation:679            // Restore the text captured before the annotation and remember the LaTeX source.680            let latex = text681            captureText = annotationText ?? ""682            annotationText = latex683            return684        case .title:685            let title = TextSanitizer.clean(text).replacingOccurrences(of: lineSeparatorCharacter, with: " ").split(whereSeparator: { $0 == " " }).joined(separator: " ")686            if meta.title.isEmpty { meta.title = title }687        case .mathSpan(let latex, let display):688            var source = latex ?? text689            if latex == nil {690                // Without a data-latex attribute the span holds TeX only when it is delimited (MathJax / KaTeX convention).691                // Otherwise the producer already rendered the formula as HTML and its source is gone: keep the text.692                source = source.trimmingCharacters(in: .whitespacesAndNewlines)693                var delimited = false694                for (open, close) in [("\\(", "\\)"), ("\\[", "\\]"), ("$$", "$$"), ("$", "$")] where source.hasPrefix(open) && source.hasSuffix(close) && source.count >= open.count + close.count {695                    source = String(source.dropFirst(open.count).dropLast(close.count)); delimited = true; break696                }697                if !delimited {698                    warnings.add(.approximated, "Equations", "Formulas already rendered as HTML have no LaTeX source; they are kept as plain text.")699                    captureText = ""700                    addText(text)701                    return702                }703            }704            source = TextSanitizer.clean(source).replacingOccurrences(of: lineSeparatorCharacter, with: " ").trimmingCharacters(in: .whitespaces)705            if !source.isEmpty { addInline(.equation(Equation(latex: source, display: display))) }706        case .mathML(let display):707            if let latex = annotationText.map({ TextSanitizer.clean($0).replacingOccurrences(of: lineSeparatorCharacter, with: " ").trimmingCharacters(in: .whitespaces) }), !latex.isEmpty {708                addInline(.equation(Equation(latex: latex, display: display)))709            } else {710                warnings.add(.approximated, "Equations", "MathML without a LaTeX annotation is kept as plain text.")711                addText(text)712            }713            annotationText = nil714        case .citation(let items):715            if let citation = CitationSyntax.parse(items) { addInline(.citation(citation)) } else { addText(text) }716        case .noteRef(let target):717            addInline(.note(NoteRef(kind: .footnote, id: pendingNotePrefix + target + "\u{1}" + text.trimmingCharacters(in: .whitespacesAndNewlines))))718        }719        captureText = ""720    }721722    // MARK: Attributes723724    private func readMeta(_ attributes: [String: String]) {725        if (attributes["http-equiv"] ?? "").lowercased() == "refresh" { warnings.add(.dropped, "Active content", "A page refresh / redirect instruction was removed."); return }726        guard let name = attributes["name"]?.lowercased(), let content = attributes["content"].map(TextSanitizer.clean), !content.isEmpty else { return }727        switch name {728        case "author": meta.author = meta.author.isEmpty ? content : meta.author + ", " + content729        case "keywords": meta.keywords = content.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }730        case "description", "subject", "dcterms.subject": meta.subject = content731        default: break732        }733    }734735    private func applyStyle(_ style: String, to frame: inout Frame, element: String) {736        let isBlock = HTMLConverter.blockElements.contains(element)737        for (key, value) in CSSSupport.declarations(style) {738            let lower = value.lowercased()739            switch key {740            case "font-family": if let f = CSSSupport.fontFamily(value) { frame.char.fontFamily = f }741            case "font-size": if let size = CSSSupport.length(value, base: frame.char.fontSize ?? 12), size >= 1, size <= 1000 { frame.char.fontSize = (size * 100).rounded() / 100 }742            case "color": if let c = CSSSupport.colour(value) { frame.char.color = c }743            case "background-color", "background":744                guard let c = CSSSupport.colour(value) else { break }745                if isBlock { frame.para.shading = c } else { frame.char.highlight = c }746            case "text-align": if let a = CSSSupport.alignment(value) { frame.para.alignment = a }747            case "font-weight":748                if lower == "bold" || lower == "bolder" { frame.char.bold = true }749                else if lower == "normal" || lower == "lighter" { frame.char.bold = false }750                else if let weight = Int(lower) { frame.char.bold = weight >= 600 }751            case "font-style":752                if lower == "italic" || lower.hasPrefix("oblique") { frame.char.italic = true } else if lower == "normal" { frame.char.italic = false }753            case "text-decoration", "text-decoration-line":754                if lower.contains("underline") { frame.char.underline = true }755                if lower.contains("line-through") { frame.char.strikethrough = true }756                if lower == "none" { frame.char.underline = false; frame.char.strikethrough = false }757            case "vertical-align":758                if lower == "super" { frame.char.vertical = .superscript } else if lower == "sub" { frame.char.vertical = .subscript }759            case "font-variant", "font-variant-caps": if lower.contains("small-caps") { frame.char.smallCaps = true }760            case "text-transform": if lower == "uppercase" { frame.char.allCaps = true }761            case "white-space": if lower.hasPrefix("pre") { frame.pre = true }762            case "margin-top": if isBlock, let v = CSSSupport.length(value, base: frame.char.fontSize ?? 12), v >= 0, v <= 2000 { frame.para.spaceBefore = v }763            case "margin-bottom": if isBlock, let v = CSSSupport.length(value, base: frame.char.fontSize ?? 12), v >= 0, v <= 2000 { frame.para.spaceAfter = v }764            case "line-height":765                guard isBlock else { break }766                if let multiple = Double(lower), multiple > 0.2, multiple < 20 { frame.para.lineSpacing = .multiple((multiple / 1.2 * 1000).rounded() / 1000) }767                else if let v = CSSSupport.length(value, base: frame.char.fontSize ?? 12), v > 0, v <= 2000, !lower.hasSuffix("%"), !lower.hasSuffix("em") { frame.para.lineSpacing = .exact(v) }768            case "margin-left": if isBlock, let v = CSSSupport.length(value, base: frame.char.fontSize ?? 12), v >= 0, v <= 2000 { frame.para.indentLeft = v }769            case "margin-right": if isBlock, let v = CSSSupport.length(value, base: frame.char.fontSize ?? 12), v >= 0, v <= 2000 { frame.para.indentRight = v }770            case "text-indent": if isBlock, let v = CSSSupport.length(value, base: frame.char.fontSize ?? 12), abs(v) <= 2000 { frame.para.firstLineIndent = v }771            case "direction": if isBlock, lower == "rtl" || lower == "ltr" { frame.para.rightToLeft = lower == "rtl" }772            case "page-break-before", "break-before", "page-break-after", "break-after":773                if lower == "always" || lower == "page" { containers[containers.count - 1].blocks.append(.pageBreak(BreakBlock())) }774            default: break775            }776        }777    }778779    private func image(_ attributes: [String: String]) {780        let alt = attributes["alt"] ?? attributes["title"] ?? ""781        guard let src = attributes["src"], var object = images.resolve(src: src, alt: alt, warnings: &warnings) else {782            if attributes["src"] == nil { warnings.add(.dropped, "Images", "An image without a source was skipped.") }783            if !alt.isEmpty { addText(alt) }784            return785        }786        var width = attributes["width"].flatMap { CSSSupport.length($0, base: 12) }787        var height = attributes["height"].flatMap { CSSSupport.length($0, base: 12) }788        for (key, value) in CSSSupport.declarations(attributes["style"] ?? "") {789            if key == "width", let v = CSSSupport.length(value, base: 12), !value.hasSuffix("%") { width = v }790            if key == "height", let v = CSSSupport.length(value, base: 12), !value.hasSuffix("%") { height = v }791        }792        let ratio = object.height / max(1, object.width)793        if let w = width, w >= 1, w <= 5000 {794            object.width = w795            object.height = (height.flatMap { $0 >= 1 && $0 <= 5000 ? $0 : nil }) ?? w * ratio796        } else if let h = height, h >= 1, h <= 5000 {797            object.height = h798            object.width = h / max(0.0001, ratio)799        }800        addInline(.image(object))801    }802803    // MARK: Tables804805    private func flatten(_ blocks: [Block]) -> [Paragraph] {806        var out: [Paragraph] = []807        for block in blocks {808            switch block {809            case .paragraph(let p): out.append(p)810            case .table(let t):811                warnings.add(.approximated, "Nested tables", "A table inside a table cell or a note is flattened to paragraphs.")812                for row in t.rows { for cell in row.cells where cell.vMerge != .continue { out.append(contentsOf: cell.paragraphs.filter { !$0.isEmpty }) } }813            default: break814            }815        }816        return out817    }818819    private func finishCell() {820        let container = containers.removeLast()821        guard !tables.isEmpty, var cell = tables[tables.count - 1].cell else { return }822        cell.paragraphs = flatten(container.blocks)823        tables[tables.count - 1].cell = nil824        if tables[tables.count - 1].current == nil { tables[tables.count - 1].current = RowDraft(inHead: false) }825        tables[tables.count - 1].current!.cells.append(cell)826    }827828    private func finishRow() {829        guard !tables.isEmpty, let row = tables[tables.count - 1].current else { return }830        tables[tables.count - 1].current = nil831        tables[tables.count - 1].rows.append(row)832    }833834    private func finishTable() {835        guard var context = tables.popLast() else { return }836        if let row = context.current { context.rows.append(row) }837        let ci = containers.count - 1838        containers[ci].blocks.append(contentsOf: context.caption.map(Block.paragraph))839        guard let table = HTMLConverter.buildTable(context.rows.map { row in (row.cells.map { ($0.paragraphs, $0.colSpan, $0.rowSpan, $0.header, $0.shading) }, row.inHead) }, warnings: &warnings) else { return }840        containers[ci].blocks.append(.table(table))841    }842843    /// Lays cells with column and row spans out on a regular grid (colSpan + vMerge restart / continue).844    static func buildTable(_ rows: [(cells: [(paragraphs: [Paragraph], colSpan: Int, rowSpan: Int, header: Bool, shading: RGBA?)], inHead: Bool)],845                           warnings: inout WarningCollector) -> Table? {846        guard rows.contains(where: { !$0.cells.isEmpty }) else { return nil }847        var spans: [Int: (width: Int, remaining: Int, shading: RGBA?)] = [:]      // keyed by start column848        var out: [TableRow] = []849        var columnCount = 0850        var cellCount = 0851        var headerPossible = true852        var truncated = false853        for row in rows {854            var cells: [TableCell] = []855            var column = 0856            var queue = row.cells[...]857            func continueSpans() {858                while let span = spans[column] {859                    var cell = TableCell(colSpan: span.width, vMerge: .continue, shading: span.shading)860                    cell.paragraphs = [Paragraph(style: StyleID.tableText)]861                    cells.append(cell)862                    spans[column] = span.remaining > 1 ? (span.width, span.remaining - 1, span.shading) : nil863                    column += span.width864                }865            }866            continueSpans()867            while let draft = queue.first {868                queue = queue.dropFirst()869                guard column < FormatLimits.maxTableColumns, cellCount < FormatLimits.maxTableCells else { truncated = true; break }870                // A cell cannot overlap a vertical span that starts further right.871                var width = min(draft.colSpan, FormatLimits.maxTableColumns - column)872                for k in 1..<max(1, width) where spans[column + k] != nil { width = k; break }873                let cell = TableCell(paragraphs: draft.paragraphs.isEmpty ? [Paragraph(style: StyleID.tableText)] : draft.paragraphs, colSpan: width,874                                     vMerge: draft.rowSpan > 1 ? .restart : .none, shading: draft.shading)875                cells.append(cell)876                cellCount += 1877                if draft.rowSpan > 1 { spans[column] = (width, draft.rowSpan - 1, draft.shading) }878                column += width879                continueSpans()880            }881            // Vertical spans to the right of the last cell of this row.882            for start in spans.keys.sorted() where start >= column {883                while column < start { cells.append(TableCell()); column += 1 }884                continueSpans()885            }886            columnCount = max(columnCount, column)887            let isHeader = headerPossible && !row.cells.isEmpty && (row.inHead || row.cells.allSatisfy(\.header))888            if !isHeader { headerPossible = false }889            out.append(TableRow(cells: cells, isHeader: isHeader))890        }891        if truncated { warnings.add(.dropped, "Large tables", "Cells beyond \(FormatLimits.maxTableColumns) columns or \(FormatLimits.maxTableCells) cells were dropped.") }892        guard columnCount > 0 else { return nil }893        for r in out.indices {894            var width = out[r].cells.reduce(0) { $0 + $1.colSpan }895            while width < columnCount { out[r].cells.append(TableCell()); width += 1 }896        }897        // Rows spanned past the end of the table: a restart with nothing below it is a plain cell.898        if let last = out.indices.last {899            for c in out[last].cells.indices where out[last].cells[c].vMerge == .restart { out[last].cells[c].vMerge = .none }900        }901        return Table(columnWidths: Array(repeating: 468 / Double(columnCount), count: columnCount), rows: out)902    }903904    // MARK: Post-processing905906    private func resolveNotes(_ body: inout [Block], _ notes: inout [String: Note]) {907        let definitions = noteBodies.mapValues(\.paragraphs)908        let reachable = PendingNotes.reachable(from: body, definitions: definitions)909        let ids = Dictionary(uniqueKeysWithValues: reachable.map { ($0, DocID.make()) })910        var unresolved = 0911        func fix(_ p: inout Paragraph) {912            for k in p.runs.indices {913                guard case .note(let ref)? = p.runs[k].inline, let pending = PendingNotes.parse(ref) else { continue }914                if let id = ids[pending.target], let kind = noteBodies[pending.target]?.kind {915                    p.runs[k].inline = .note(NoteRef(kind: kind, id: id))916                } else {917                    // No such note (or a note that is itself unreferenced): keep the visible mark.918                    unresolved += 1919                    p.runs[k] = Run(pending.mark.isEmpty ? "*" : TextSanitizer.clean(pending.mark), props: CharProps(vertical: .superscript))920                }921            }922        }923        DocumentModel.mutateParagraphs(in: &body, fix)924        var orphans: [Paragraph] = []925        for target in noteBodies.keys.sorted() {926            guard var entry = noteBodies[target] else { continue }927            for k in entry.paragraphs.indices { fix(&entry.paragraphs[k]) }928            if let id = ids[target] { notes[id] = Note(id: id, kind: entry.kind, paragraphs: entry.paragraphs) } else { orphans += entry.paragraphs }929        }930        if unresolved > 0 { warnings.add(.approximated, "Footnotes", "Footnote references without a matching note are kept as superscript text.") }931        if !orphans.isEmpty {932            warnings.add(.approximated, "Footnotes", "Notes that no reference points to are appended as ordinary paragraphs.")933            body.append(contentsOf: orphans.map(Block.paragraph))934        }935    }936937    /// Element ids become bookmarks only when a link of the document points at them; explicit anchors are always kept.938    private func pruneBookmarks(_ body: inout [Block]) {939        var referenced: Set<String> = []940        DocumentModel.forEachParagraph(in: body) { p, _ in941            for r in p.runs { if let link = r.props.link, link.hasPrefix("#") { referenced.insert(String(link.dropFirst())) } }942        }943        let removable = optionalBookmarks.subtracting(referenced)944        guard !removable.isEmpty else { return }945        DocumentModel.mutateParagraphs(in: &body) { p in946            p.runs.removeAll { if case .bookmark(let name)? = $0.inline { return removable.contains(name) } else { return false } }947        }948    }949}950
Files main
Menu

Theme