SPB Git

Repository Public

HTMLExporter.swift 27.3 KB 477 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocFormats/HTMLExporter.swift3// Description: Standalone semantic HTML5 export: embedded style sheet derived from the document styles, images as data URIs,4//              tables with spans, footnotes listed at the end, heading ids, alternative text, language, optional MathML.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112public enum HTMLExporter {13    public static func export(_ doc: DocumentModel, options: ExportOptions = ExportOptions()) -> ExportResult {14        var writer = HTMLWriter(doc, options: options)15        let html = writer.write()16        return ExportResult(data: Data(html.utf8), warnings: writer.ctx.finalWarnings(source: doc, format: .html))17    }18}1920struct HTMLWriter {21    var ctx: ExportContext22    private var doc: DocumentModel { ctx.doc }23    private var ids: [String: String] = [:]          // paragraph id → element id24    private var noteNumbers: [String: (label: String, anchor: String)] = [:]2526    init(_ source: DocumentModel, options: ExportOptions) {27        ctx = ExportContext(source, options: options)28        var slugger = Slugger()29        var bookmarkNames = Set(ctx.numbering.bookmarks.keys)30        for block in doc.body {31            guard case .paragraph(let p) = block else { continue }32            if p.style == StyleID.title || ModelIdiom.headingLevel(p, styles: doc.styles) != nil {33                if case .bookmark(let name)? = p.runs.first?.inline, !name.isEmpty {34                    ids[p.id] = name          // a leading bookmark is written as the element id35                } else {36                    var id = slugger.unique(ctx.headingNumberPrefix(p) + p.visibleText)37                    while bookmarkNames.contains(id) { id += "-h" }38                    bookmarkNames.insert(id)39                    ids[p.id] = id40                }41            } else if ctx.numbering.captions[p.id] != nil {42                ids[p.id] = "caption-" + p.id43            }44        }45        for (ref, _) in ctx.orderedNotes {46            let n = ctx.numbering.noteNumbers[ref.id] ?? 047            noteNumbers[ref.id] = (ctx.noteMark(ref), (ref.kind == .footnote ? "fn" : "en") + String(n))48        }49    }5051    private func esc(_ s: String) -> String { HTMLEntities.escapeText(s) }52    private func attr(_ s: String) -> String { HTMLEntities.escapeAttribute(s) }53    private static func number(_ v: Double) -> String {54        let r = (v * 100).rounded() / 10055        return r == r.rounded() ? String(Int(r)) : String(r)56    }57    private static func css(_ c: RGBA) -> String {58        c.a >= 0.999 ? "#" + c.hexString.lowercased() : "rgba(\(Int((c.r * 255).rounded())), \(Int((c.g * 255).rounded())), \(Int((c.b * 255).rounded())), \(number(c.a)))"59    }60    private static func family(_ name: String) -> String {61        let mono = ["SF Mono", "Menlo", "Monaco", "Courier", "Courier New", "Consolas"].contains(name)62        let serif = ["New York", "Times New Roman", "Georgia", "Charter", "Palatino", "Times"].contains(name)63        return "\"\(name.replacingOccurrences(of: "\"", with: ""))\", " + (mono ? "ui-monospace, monospace" : serif ? "ui-serif, serif" : "system-ui, sans-serif")64    }6566    // MARK: Style sheet6768    private static func declarations(char c: CharProps) -> [String] {69        var d: [String] = []70        if let f = c.fontFamily { d.append("font-family: \(family(f))") }71        if let s = c.fontSize { d.append("font-size: \(number(s))pt") }72        if let w = c.weight { d.append("font-weight: \(w)") } else if let b = c.bold { d.append("font-weight: \(b ? "bold" : "normal")") }73        if let i = c.italic { d.append("font-style: \(i ? "italic" : "normal")") }74        if let col = c.color { d.append("color: \(css(col))") }75        if let h = c.highlight { d.append("background-color: \(css(h))") }76        var decorations: [String] = []77        if c.underline == true { decorations.append("underline") }78        if c.strikethrough == true { decorations.append("line-through") }79        if !decorations.isEmpty { d.append("text-decoration: " + decorations.joined(separator: " ")) }80        else if c.underline == false, c.strikethrough != true { d.append("text-decoration: none") }81        if c.smallCaps == true { d.append("font-variant: small-caps") }82        if c.allCaps == true { d.append("text-transform: uppercase") }83        if let t = c.tracking { d.append("letter-spacing: \(number(t))pt") }84        return d85    }8687    private static func declarations(para p: ParaProps) -> [String] {88        var d: [String] = []89        if let a = p.alignment { d.append("text-align: \(a == .justified ? "justify" : a.rawValue)") }90        if let v = p.indentLeft { d.append("margin-left: \(number(v))pt") }91        if let v = p.indentRight { d.append("margin-right: \(number(v))pt") }92        if let v = p.firstLineIndent { d.append("text-indent: \(number(v))pt") }93        if let v = p.spaceBefore { d.append("margin-top: \(number(v))pt") }94        if let v = p.spaceAfter { d.append("margin-bottom: \(number(v))pt") }95        if let l = p.lineSpacing {96            switch l {97            case .multiple(let m): d.append("line-height: \(number(m * 1.2))")98            case .exact(let pt), .atLeast(let pt): d.append("line-height: \(number(pt))pt")99            }100        }101        if let s = p.shading { d.append("background-color: \(css(s))") }102        if let b = p.borderLeft { d.append("border-left: \(number(b.width))pt \(b.style.rawValue) \(css(b.color)); padding-left: 10pt") }103        if let b = p.borderTop { d.append("border-top: \(number(b.width))pt \(b.style.rawValue) \(css(b.color))") }104        if let b = p.borderBottom { d.append("border-bottom: \(number(b.width))pt \(b.style.rawValue) \(css(b.color))") }105        if let r = p.rightToLeft { d.append("direction: \(r ? "rtl" : "ltr")") }106        return d107    }108109    private static func className(_ styleID: String) -> String {110        "ps-" + String(styleID.map { $0.isASCII && ($0.isLetter || $0.isNumber) ? $0 : "-" })111    }112113    private func styleSheet() -> String {114        let styles = doc.styles115        var rules: [String] = []116        func rule(_ selector: String, _ declarations: [String]) { if !declarations.isEmpty { rules.append("\(selector) { " + declarations.joined(separator: "; ") + "; }") } }117        func chained(_ id: String) -> (CharProps, ParaProps) {118            var c = CharProps.none, p = ParaProps.none119            for s in styles.chain(id) { c.apply(s.char); p.apply(s.para) }120            return (c, p)121        }122        var bodyChar = styles.defaultChar123        var bodyPara = styles.defaultPara124        if let normal = styles.style(StyleID.normal) { bodyChar.apply(normal.char); bodyPara.apply(normal.para) }125        var body = HTMLWriter.declarations(char: bodyChar)126        if let l = bodyPara.lineSpacing, case .multiple(let m) = l { body.append("line-height: \(HTMLWriter.number(m * 1.2))") }127        body.append(contentsOf: ["max-width: \(HTMLWriter.number(doc.pageSetup.contentWidth))pt", "margin: 2em auto", "padding: 0 1em"])128        rule("body", body)129        var paragraph: [String] = []130        if let a = bodyPara.alignment, a != .left { paragraph.append("text-align: \(a == .justified ? "justify" : a.rawValue)") }131        paragraph.append("margin: \(HTMLWriter.number(bodyPara.spaceBefore ?? 0))pt 0 \(HTMLWriter.number(bodyPara.spaceAfter ?? 0))pt 0")132        rule("p", paragraph)133        func styleRule(_ selector: String, _ id: String) {134            guard styles.style(id) != nil else { return }135            let (c, p) = chained(id)136            var pp = p137            if id == StyleID.quote { pp.indentLeft = nil; pp.indentRight = nil }138            rule(selector, HTMLWriter.declarations(char: c) + HTMLWriter.declarations(para: pp))139        }140        styleRule("h1.title", StyleID.title)141        styleRule("p.subtitle", StyleID.subtitle)142        for level in 1...6 { styleRule("h\(level)", StyleID.heading(level)) }143        styleRule("blockquote p", StyleID.quote)144        rule("blockquote", ["margin: 0 28pt"])145        styleRule("pre", StyleID.code)146        rule("pre", ["white-space: pre-wrap", "padding: 8pt", "tab-size: 4"])147        rule("pre code", ["font: inherit"])148        styleRule("p.caption, caption", StyleID.caption)149        styleRule("p.abstract", StyleID.abstract)150        styleRule("section.footnotes, section.endnotes", StyleID.footnoteText)151        if let code = styles.style(StyleID.inlineCode) { rule("code", HTMLWriter.declarations(char: code.char)) }152        if let link = styles.style(StyleID.hyperlink) { rule("a", HTMLWriter.declarations(char: link.char)) }153        styleRule("td, th", StyleID.tableText)154        rule("table", ["border-collapse: collapse", "margin: 8pt 0"])155        rule("td, th", ["padding: 4pt 6pt", "vertical-align: top", "text-align: left"])156        rule("td p, th p, li p", ["margin: 0"])157        rule("img", ["max-width: 100%", "height: auto"])158        rule("nav.toc ul", ["list-style: none", "padding-left: 0"])159        for level in 2...9 { rule("nav.toc li.toc-\(level)", ["margin-left: \((level - 1) * 16)pt"]) }160        rule(".math.display", ["display: block", "text-align: center", "margin: 8pt 0"])161        rule(".page-break", ["break-after: page", "page-break-after: always"])162        // Custom paragraph styles.163        let builtIn = Set(StyleSheet.standard().styles.map(\.id))164        for style in styles.paragraphStyles where !builtIn.contains(style.id) {165            let (c, p) = chained(style.id)166            rule("." + HTMLWriter.className(style.id), HTMLWriter.declarations(char: c) + HTMLWriter.declarations(para: p))167        }168        return rules.joined(separator: "\n")169    }170171    // MARK: Inline content172173    private enum Sty: Equatable { case link(String), bold, italic, underline, strike, sub, sup, code, span(String) }174175    private mutating func inline(_ p: Paragraph, skipLeadingBookmark: Bool = false) -> String {176        var out = ""177        var open: [Sty] = []178        var sequenceIndex = 0179        func tag(_ s: Sty, opening: Bool) -> String {180            switch s {181            case .link(let url): return opening ? "<a href=\"\(attr(url))\">" : "</a>"182            case .bold: return opening ? "<strong>" : "</strong>"183            case .italic: return opening ? "<em>" : "</em>"184            case .underline: return opening ? "<u>" : "</u>"185            case .strike: return opening ? "<s>" : "</s>"186            case .sub: return opening ? "<sub>" : "</sub>"187            case .sup: return opening ? "<sup>" : "</sup>"188            case .code: return opening ? "<code>" : "</code>"189            case .span(let style): return opening ? "<span style=\"\(attr(style))\">" : "</span>"190            }191        }192        func transition(to wanted: [Sty]) {193            var keep = 0194            while keep < open.count, keep < wanted.count, open[keep] == wanted[keep] { keep += 1 }195            for s in open[keep...].reversed() { out += tag(s, opening: false) }196            for s in wanted[keep...] { out += tag(s, opening: true) }197            open = wanted198        }199        for (index, run) in p.runs.enumerated() {200            if let object = run.inline {201                var wanted: [Sty] = []202                if let link = run.props.link, !link.isEmpty, LinkPolicy.sanitize(link) != nil { wanted.append(.link(link)) }203                transition(to: wanted)204                switch object {205                case .image(let image):206                    guard let asset = doc.assets[image.asset] else {207                        ctx.warnings.add(.dropped, "Missing images", "An image has no data in the document; its alternative text was written instead.")208                        out += esc(image.altText)209                        break210                    }211                    var style = ""212                    if case .floating(_, let align, _, _) = image.placement { style = align == .center ? " style=\"display: block; margin: 0 auto\"" : " style=\"float: \(align.rawValue); margin: 0 8pt 4pt 8pt\"" }213                    out += "<img src=\"\(ImageSupport.dataURI(asset))\" alt=\"\(attr(image.altText))\" width=\"\(Int((image.width / 0.75).rounded()))\" height=\"\(Int((image.height / 0.75).rounded()))\"\(style)>"214                case .shape(let shape): out += esc(shape.text.isEmpty ? shape.altText : shape.text)215                case .equation(let e):216                    let cls = e.display ? "math display" : "math inline"217                    if let markup = ctx.options.mathML?(e.latex, e.display) {218                        out += "<span class=\"\(cls)\" data-latex=\"\(attr(e.latex))\">\(markup)</span>"219                    } else {220                        if ctx.options.mathML != nil { ctx.warnings.add(.approximated, "Equations", "Some equations could not be converted to MathML and are written as LaTeX source.") }221                        out += "<span class=\"\(cls)\" data-latex=\"\(attr(e.latex))\">\(esc(e.latex))</span>"222                    }223                case .note(let ref):224                    if let n = noteNumbers[ref.id] {225                        out += "<a href=\"#\(n.anchor)\" class=\"footnote-ref\" id=\"\(n.anchor)-ref\" role=\"doc-noteref\"><sup>\(esc(n.label))</sup></a>"226                    }227                case .citation(let c):228                    out += "<span class=\"citation\" data-cite-items=\"\(attr(CitationSyntax.render(c)))\">\(esc(ctx.citationText(c)))</span>"229                case .crossRef(let ref):230                    let text = esc(ctx.crossRefText(ref))231                    if ctx.numbering.bookmarks[ref.target] != nil { out += "<a href=\"#\(attr(ref.target))\">\(text)</a>" }232                    else if let target = ctx.crossRefTarget(ref), let id = ids[target] { out += "<a href=\"#\(attr(id))\">\(text)</a>" }233                    else { out += text }234                case .field(let f): out += esc(ctx.fieldText(f, in: p, sequenceIndex: &sequenceIndex))235                case .bookmark(let name): if !(skipLeadingBookmark && index == 0) { out += "<a id=\"\(attr(name))\"></a>" }236                }237                continue238            }239            let c = ModelIdiom.explicitChar(run, styles: doc.styles)240            var wanted: [Sty] = []241            if let link = c.link, !link.isEmpty, LinkPolicy.sanitize(link) != nil { wanted.append(.link(link)) }242            var direct = run.props243            direct.link = nil; direct.bold = nil; direct.italic = nil; direct.underline = nil; direct.strikethrough = nil; direct.vertical = nil; direct.weight = nil244            if let weight = run.props.weight, weight != 400, weight != 700 { direct.weight = weight }245            let css = HTMLWriter.declarations(char: direct)246            if !css.isEmpty { wanted.append(.span(css.joined(separator: "; "))) }247            if ModelIdiom.isBold(c) { wanted.append(.bold) }248            if c.italic == true { wanted.append(.italic) }249            if c.underline == true, c.link == nil { wanted.append(.underline) }250            if c.strikethrough == true { wanted.append(.strike) }251            if c.vertical == .subscript { wanted.append(.sub) }252            if c.vertical == .superscript { wanted.append(.sup) }253            if run.charStyle == StyleID.inlineCode { wanted.append(.code) }254            transition(to: wanted)255            var text = esc(run.text).replacingOccurrences(of: lineSeparatorCharacter, with: "<br>\n")256            if text.contains("\t") { text = text.replacingOccurrences(of: "\t", with: "<span style=\"white-space: pre\">&#9;</span>") }257            out += text258        }259        transition(to: [])260        return out261    }262263    // MARK: Blocks264265    private func directStyle(_ p: Paragraph, extra: [String] = []) -> String {266        var props = p.props267        props.outlineLevel = nil268        let d = HTMLWriter.declarations(para: props) + extra269        return d.isEmpty ? "" : " style=\"\(attr(d.joined(separator: "; ")))\""270    }271272    private mutating func paragraphHTML(_ p: Paragraph) -> String {273        if ModelIdiom.isRule(p) { return "<hr>" }274        var idAttribute = ids[p.id].map { " id=\"\(attr($0))\"" } ?? ""275        var skip = false276        if case .bookmark(let name)? = p.runs.first?.inline, !name.isEmpty { idAttribute = " id=\"\(attr(name))\""; skip = true }277        let style = directStyle(p)278        if p.style == StyleID.title { return "<h1 class=\"title\"\(idAttribute)\(style)>\(inline(p, skipLeadingBookmark: skip))</h1>" }279        if let level = ModelIdiom.headingLevel(p, styles: doc.styles) {280            let number = esc(ctx.headingNumberPrefix(p))281            let tag = "h\(min(6, level))"282            let aria = level > 6 ? " aria-level=\"\(level)\"" : ""283            return "<\(tag)\(idAttribute)\(aria)\(style)>\(number)\(inline(p, skipLeadingBookmark: skip))</\(tag)>"284        }285        if ModelIdiom.displayEquation(p) != nil, p.runs.count == 1 {286            return "<p class=\"equation\"\(idAttribute)\(style)>\(inline(p))</p>"287        }288        var cls: String?289        switch p.style {290        case StyleID.subtitle: cls = "subtitle"291        case StyleID.abstract: cls = "abstract"292        case StyleID.caption: cls = "caption"293        case StyleID.normal, StyleID.quote, StyleID.listParagraph, StyleID.tableText, StyleID.footnoteText: cls = nil294        default: cls = HTMLWriter.className(p.style)295        }296        let classAttribute = cls.map { " class=\"\($0)\"" } ?? ""297        return "<p\(classAttribute)\(idAttribute)\(style)>\(inline(p, skipLeadingBookmark: skip))</p>"298    }299300    private mutating func tableHTML(_ t: Table) -> String {301        var out = "<table>\n"302        let total = max(1, t.totalWidth)303        out += "<colgroup>" + t.columnWidths.map { "<col style=\"width: \(HTMLWriter.number($0 / total * 100))%\">" }.joined() + "</colgroup>\n"304        // Row spans: a restart cell spans the continue cells below it in the same grid column.305        func column(of cellIndex: Int, in row: TableRow) -> Int { row.cells[..<cellIndex].reduce(0) { $0 + $1.colSpan } }306        func rowHTML(_ r: Int) -> String {307            let row = t.rows[r]308            var s = "<tr>"309            for (c, cell) in row.cells.enumerated() where cell.vMerge != .continue {310                var span = 1311                if cell.vMerge == .restart {312                    let col = column(of: c, in: row)313                    var below = r + 1314                    while below < t.rows.count, let k = t.rows[below].cells.indices.first(where: { column(of: $0, in: t.rows[below]) == col }), t.rows[below].cells[k].vMerge == .continue {315                        span += 1; below += 1316                    }317                }318                let tag = row.isHeader ? "th" : "td"319                var attributes = ""320                if cell.colSpan > 1 { attributes += " colspan=\"\(cell.colSpan)\"" }321                if span > 1 { attributes += " rowspan=\"\(span)\"" }322                var css: [String] = []323                if let shading = cell.shading ?? (row.isHeader ? t.style.headerShading : nil) { css.append("background-color: \(HTMLWriter.css(shading))") }324                if cell.vAlign != .top { css.append("vertical-align: \(cell.vAlign == .center ? "middle" : "bottom")") }325                if let border = t.style.innerHorizontal ?? t.style.outerBorder { css.append("border: \(HTMLWriter.number(border.width))pt solid \(HTMLWriter.css(border.color))") }326                if !css.isEmpty { attributes += " style=\"\(attr(css.joined(separator: "; ")))\"" }327                var content = ""328                if cell.paragraphs.count == 1, let only = cell.paragraphs.first, only.list == nil, only.props.isEmpty {329                    content = inline(only)330                } else {331                    content = blocksHTML(cell.paragraphs.map(Block.paragraph))332                }333                s += "<\(tag)\(attributes)>\(content)</\(tag)>"334            }335            return s + "</tr>\n"336        }337        var r = 0338        let headerCount = t.rows.prefix { $0.isHeader }.count339        if headerCount > 0 {340            out += "<thead>\n"341            while r < headerCount { out += rowHTML(r); r += 1 }342            out += "</thead>\n"343        }344        out += "<tbody>\n"345        while r < t.rows.count { out += rowHTML(r); r += 1 }346        out += "</tbody>\n</table>"347        return out348    }349350    private mutating func blocksHTML(_ blocks: [Block]) -> String {351        var out: [String] = []352        var index = 0353        while index < blocks.count {354            let block = blocks[index]355            switch block {356            case .paragraph(let p):357                if p.list != nil, doc.list(p.list!.listID) != nil {358                    out.append(listHTML(blocks, &index))359                    continue360                }361                if p.style == StyleID.code {362                    var lines = [p]363                    while index + 1 < blocks.count, case .paragraph(let next) = blocks[index + 1], next.style == StyleID.code, next.list == nil { lines.append(next); index += 1 }364                    let code = lines.map { esc(ctx.flatText($0)).replacingOccurrences(of: lineSeparatorCharacter, with: "\n") }.joined(separator: "\n")365                    out.append("<pre><code>\(code)</code></pre>")366                } else if p.style == StyleID.quote {367                    var parts = [paragraphHTML(p)]368                    while index + 1 < blocks.count, case .paragraph(let next) = blocks[index + 1], next.style == StyleID.quote, next.list == nil { parts.append(paragraphHTML(next)); index += 1 }369                    out.append("<blockquote>\n" + parts.joined(separator: "\n") + "\n</blockquote>")370                } else if !p.isEmpty || ModelIdiom.isRule(p) {371                    out.append(paragraphHTML(p))372                }373            case .table(let t): out.append(tableHTML(t))374            case .pageBreak(let b): if b.kind == .page { out.append("<div class=\"page-break\"></div>") }375            case .sectionBreak(let s): if s.kind != .continuous { out.append("<div class=\"page-break\"></div>") }376            case .toc(let toc):377                var s = "<nav class=\"toc\" data-kind=\"\(toc.kind.rawValue)\" data-max-level=\"\(toc.maxLevel)\"" + (toc.title.map { " data-title=\"\(attr($0))\"" } ?? "") + ">\n"378                if let title = toc.title, !title.isEmpty { s += "<p class=\"toc-title\"><strong>\(esc(title))</strong></p>\n" }379                s += "<ul>\n"380                for e in ctx.entries(of: toc) {381                    let label = esc(e.text)382                    s += "<li class=\"toc-\(e.level)\">" + (ids[e.target].map { "<a href=\"#\(attr($0))\">\(label)</a>" } ?? label) + "</li>\n"383                }384                out.append(s + "</ul>\n</nav>")385            case .bibliography(let b):386                var s = "<section class=\"orix-bibliography\" role=\"doc-bibliography\"" + (b.title.map { " data-title=\"\(attr($0))\"" } ?? "") + ">\n"387                if let title = b.title, !title.isEmpty { s += "<h2>\(esc(title))</h2>\n" }388                if let entries = ctx.bibliographyParagraphs() { for e in entries { s += "<p class=\"bib-entry\">\(inline(e))</p>\n" } }389                out.append(s + "</section>")390            }391            index += 1392        }393        return out.joined(separator: "\n")394    }395396    /// Consecutive list paragraphs become nested <ul>/<ol> elements. `index` is left on the first block after the list.397    private mutating func listHTML(_ blocks: [Block], _ index: inout Int) -> String {398        var out = ""399        var open: [(tag: String, listID: String)] = []       // one entry per open level400        var itemOpen: [Bool] = []401        func closeLevel() {402            if itemOpen.removeLast() { out += "</li>\n" }403            out += "</\(open.removeLast().tag)>\n"404        }405        while index < blocks.count, case .paragraph(let p) = blocks[index] {406            if let item = p.list, let def = doc.list(item.listID), !def.levels.isEmpty {407                var level = max(0, min(def.levels.count - 1, item.level))408                level = min(level, open.count)409                // A different list at the top level ends this one.410                if level == 0, let first = open.first, first.listID != item.listID { break }411                while open.count > level + 1 { closeLevel() }412                let format = def.levels[level].format413                let ordered = format != .bullet && format != .none414                if open.count == level + 1, open[level].tag != (ordered ? "ol" : "ul") {415                    closeLevel()416                }417                if open.count == level {418                    var attributes = ""419                    if ordered {420                        if def.levels[level].start != 1 { attributes += " start=\"\(def.levels[level].start)\"" }421                        switch format {422                        case .lowerAlpha: attributes += " type=\"a\""423                        case .upperAlpha: attributes += " type=\"A\""424                        case .lowerRoman: attributes += " type=\"i\""425                        case .upperRoman: attributes += " type=\"I\""426                        default: break427                        }428                    }429                    out += "<\(ordered ? "ol" : "ul")\(attributes)>\n"430                    open.append((ordered ? "ol" : "ul", item.listID))431                    itemOpen.append(false)432                } else if itemOpen[level] {433                    out += "</li>\n"434                }435                out += "<li\(directStyle(p))>" + inline(p)436                itemOpen[level] = true437                index += 1438            } else if !open.isEmpty, p.style == StyleID.listParagraph, (p.props.indentLeft ?? 0) > 0, !p.isEmpty {439                // Continuation paragraph of the current item.440                var q = p441                q.props.indentLeft = nil442                out += "\n<p\(directStyle(q))>" + inline(q) + "</p>"443                index += 1444            } else { break }445        }446        while !open.isEmpty { closeLevel() }447        return out.trimmingCharacters(in: .newlines)448    }449450    mutating func write() -> String {451        let meta = doc.meta452        let css = styleSheet()453        let body = blocksHTML(doc.body)454        var notes = ""455        for kind in [NoteRef.Kind.footnote, .endnote] {456            let list = ctx.orderedNotes.filter { $0.ref.kind == kind }457            guard !list.isEmpty else { continue }458            notes += "\n<section class=\"\(kind == .footnote ? "footnotes" : "endnotes")\" role=\"doc-endnotes\">\n<hr>\n<ol\(kind == .endnote ? " type=\"i\"" : "")>\n"459            for (ref, note) in list {460                guard let n = noteNumbers[ref.id] else { continue }461                var content = blocksHTML(note.paragraphs.map(Block.paragraph))462                let back = " <a href=\"#\(n.anchor)-ref\" class=\"footnote-back\" role=\"doc-backlink\">↩</a>"463                if content.hasSuffix("</p>") { content = String(content.dropLast(4)) + back + "</p>" } else { content += back }464                notes += "<li id=\"\(n.anchor)\">\(content)</li>\n"465            }466            notes += "</ol>\n</section>"467        }468        let language = meta.language.isEmpty ? "en" : meta.language469        var head = "<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<meta name=\"generator\" content=\"ORIX Docs\">\n"470        head += "<title>\(esc(meta.title))</title>\n"471        if !meta.author.isEmpty { head += "<meta name=\"author\" content=\"\(attr(meta.author))\">\n" }472        if !meta.keywords.isEmpty { head += "<meta name=\"keywords\" content=\"\(attr(meta.keywords.joined(separator: ", ")))\">\n" }473        if !meta.subject.isEmpty { head += "<meta name=\"description\" content=\"\(attr(meta.subject))\">\n" }474        return "<!DOCTYPE html>\n<html lang=\"\(attr(language))\">\n<head>\n\(head)<style>\n\(css)\n</style>\n</head>\n<body>\n\(body)\(notes)\n</body>\n</html>\n"475    }476}477
Files main
Menu

Theme