Files
Docwell/Server/internal/convert/export.go
T
tajniak81andClaude Opus 5.5 e441880f2f
CI / desktop (ubuntu-latest) (push) Successful in 1h15m48s
CI / mobile (push) Failing after 3m6s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 10m21s
CI / go (Server) (push) Failing after 19m16s
CI / go (Web-App) (push) Successful in 10m27s
CI / frontend (push) Failing after 7m25s
CI / docker (push) Successful in 46m48s
Add the block types Docmost has and Docwell lacked
The slash menu gains Video, Audio, Page break, Footnote, Tabs, Status,
Emoji, Subpages, Synced block and a fifth column size:
- Video and audio upload a file that plays on the page.
- Page breaks show as a labelled line and start a new page in print,
  Word and PDF.
- Footnotes are numbered in reading order and listed at the end of the
  page. Their notes hold bold, italic, code and links, with a plain copy
  kept for search.
- Tabs hold blocks on several named tabs; which one shows is each
  reader's own choice.
- Status badges are coloured words in the text.
- Typing ":" and a word picks an emoji, from the list the page icon
  picker uses, now kept in the editor package.
- Subpages lists the page's child pages, read afresh from the page tree.
- A synced block is a synced page that shows one block of another page,
  made from a copied block link.

Exports (HTML, Markdown, Word, PDF) and search handle every new block.
Page and space exports list a page's subpages. Labels are translated in
all five languages.

The phone toolbar gets Tabs, Footnote, Status, Emoji, Subpages and Page
break, and the app answers the editor's request for the page's
subpages. The bridge protocol goes to version 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:37:32 +01:00

671 lines
19 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"fmt"
"html"
"regexp"
"slices"
"strconv"
"strings"
)
// Options adjust exported links.
type Options struct {
// FileURL rewrites attachment paths (/api/v1/files/<id>) so exported
// files link to the server; nil keeps them as they are.
FileURL func(path string) string
// PageURL rewrites links to pages (/p/<id>, with an optional #fragment
// for a block), e.g. to files in a space export; nil keeps them.
PageURL func(id, fragment string) string
// Subpages are the exported page's child pages, in order, for its
// subpages blocks; without them those blocks are left out.
Subpages []PageLink
}
// PageLink is a page a subpages block lists.
type PageLink struct {
ID string
Title string
Icon string
}
// label is the page's icon and title as a link shows them.
func (p PageLink) label() string {
t := p.Title
if t == "" {
t = "Untitled"
}
if p.Icon != "" {
return p.Icon + " " + t
}
return t
}
var pageLink = regexp.MustCompile(`^/p/([A-Za-z0-9_-]+)/?(#[\w-]*)?$`)
// file rewrites the server's own paths: attachments and links to pages.
func (o Options) file(path string) string {
if o.FileURL != nil && strings.HasPrefix(path, "/api/v1/files/") {
return o.FileURL(path)
}
if o.PageURL != nil {
if m := pageLink.FindStringSubmatch(path); m != nil {
return o.PageURL(m[1], m[2])
}
}
return path
}
// safeURL keeps links to the web, mail, the server's own paths, anchors and
// relative files (a space export); anything with another scheme
// (javascript:, data:, ...) is dropped.
var safeURL = regexp.MustCompile(`^(?i)(https?://|mailto:|/|#|\.{0,2}/|[^:/?#]+(?:[/?#]|$))`)
// ---- HTML ------------------------------------------------------------------
// HTML renders the document's body as HTML.
func HTML(doc Node, o Options) string {
doc, notes := numberFootnotes(expandDatabases(doc))
var b strings.Builder
for _, n := range doc.Content {
writeHTML(&b, n, o)
}
if len(notes) > 0 {
b.WriteString("<section class=\"footnotes\">\n<hr>\n<ol>\n")
for i, note := range notes {
fmt.Fprintf(&b, "<li id=\"fn-%d\">", i+1)
for _, n := range note {
writeHTML(&b, n, o)
}
fmt.Fprintf(&b, " <a href=\"#fnref-%d\">↩</a></li>\n", i+1)
}
b.WriteString("</ol>\n</section>\n")
}
return b.String()
}
// HTMLPage renders a standalone HTML file with a title.
func HTMLPage(title string, doc Node, o Options) string {
t := html.EscapeString(title)
return "<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>" + t + "</title>\n</head>\n<body>\n" +
"<h1>" + t + "</h1>\n" + HTML(doc, o) + "</body>\n</html>\n"
}
var htmlBlock = map[string]string{
"blockquote": "blockquote", "bulletList": "ul", "orderedList": "ol", "listItem": "li",
}
func writeHTML(b *strings.Builder, n Node, o Options) {
children := func() {
for _, c := range n.Content {
writeHTML(b, c, o)
}
}
switch n.Type {
case "text":
writeHTMLText(b, n, o)
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
fmt.Fprintf(b, "<h%d%s>", level, htmlAlign(n))
children()
fmt.Fprintf(b, "</h%d>\n", level)
case "paragraph":
fmt.Fprintf(b, "<p%s>", htmlAlign(n))
children()
b.WriteString("</p>\n")
case "taskList":
b.WriteString("<ul data-type=\"taskList\">\n")
children()
b.WriteString("</ul>\n")
case "taskItem":
checked := n.Attrs["checked"] == true
box := ""
if checked {
box = " checked"
}
fmt.Fprintf(b, "<li data-type=\"taskItem\" data-checked=\"%t\"><input type=\"checkbox\" disabled%s> ", checked, box)
children()
b.WriteString("</li>\n")
case "callout":
emoji, color := calloutParts(n)
fmt.Fprintf(b, "<aside data-type=\"callout\" data-emoji=\"%s\" data-color=\"%s\" style=\"background:%s\">"+
"<span class=\"callout-emoji\">%s</span><div class=\"callout-body\">\n",
html.EscapeString(emoji), color, paletteBackground[color], html.EscapeString(emoji))
children()
b.WriteString("</div></aside>\n")
case "columns":
writeHTMLColumns(b, n, o)
case "table":
b.WriteString("<table>\n<tbody>\n")
children()
b.WriteString("</tbody>\n</table>\n")
case "tableRow":
b.WriteString("<tr>")
children()
b.WriteString("</tr>\n")
case "tableCell", "tableHeader":
tag := "td"
if n.Type == "tableHeader" {
tag = "th"
}
b.WriteString("<" + tag)
for _, span := range []string{"colspan", "rowspan"} {
if v := n.intAttr(span, 1); v > 1 {
fmt.Fprintf(b, " %s=\"%d\"", span, v)
}
}
b.WriteString(">")
children()
b.WriteString("</" + tag + ">")
case "orderedList":
if start := n.intAttr("start", 1); start != 1 {
fmt.Fprintf(b, "<ol start=\"%d\">\n", start)
} else {
b.WriteString("<ol>\n")
}
children()
b.WriteString("</ol>\n")
case "codeBlock":
lang := n.attr("language")
if lang != "" {
fmt.Fprintf(b, "<pre><code class=\"language-%s\">", html.EscapeString(lang))
} else {
b.WriteString("<pre><code>")
}
b.WriteString(html.EscapeString(PlainText(n)))
b.WriteString("</code></pre>\n")
case "horizontalRule":
b.WriteString("<hr>\n")
case "pageBreak":
b.WriteString("<div data-type=\"pageBreak\" style=\"break-after:page\"></div>\n")
case "status":
c := n.attr("color")
if !isPaletteColor(c) {
c = "gray"
}
fmt.Fprintf(b, "<span data-type=\"status\" data-color=\"%s\" style=\"background:%s;color:%s;padding:0 6px;border-radius:4px;font-size:.8em;font-weight:600\">%s</span>",
c, paletteBackground[c], paletteText[c], html.EscapeString(statusText(n)))
case "footnote":
num := footnoteNumber(n)
fmt.Fprintf(b, "<sup data-type=\"footnote\" data-text=\"%s\" id=\"fnref-%s\"><a href=\"#fn-%s\">[%s]</a></sup>",
html.EscapeString(n.attr("text")), num, num, num)
case "tabs":
// Every tab is shown, its name as a heading over its content.
b.WriteString("<div data-type=\"tabs\">\n")
for i, tab := range n.Content {
fmt.Fprintf(b, "<div data-type=\"tab\" data-title=\"%s\">\n<h4>%s</h4>\n",
html.EscapeString(tab.attr("title")), html.EscapeString(tabTitle(tab, i)))
for _, c := range tab.Content {
writeHTML(b, c, o)
}
b.WriteString("</div>\n")
}
b.WriteString("</div>\n")
case "video", "audio":
src := o.file(n.attr("src"))
if !safeURL.MatchString(src) {
return
}
fmt.Fprintf(b, "<%s src=\"%s\" controls preload=\"metadata\" data-name=\"%s\"></%s>\n",
n.Type, html.EscapeString(src), html.EscapeString(n.attr("name")), n.Type)
case "subpages":
if len(o.Subpages) == 0 {
return
}
b.WriteString("<ul data-type=\"subpages\">\n")
for _, p := range o.Subpages {
fmt.Fprintf(b, "<li><a href=\"%s\">%s</a></li>\n", html.EscapeString(o.file("/p/"+p.ID)), html.EscapeString(p.label()))
}
b.WriteString("</ul>\n")
case "hardBreak":
b.WriteString("<br>")
case "image":
fmt.Fprintf(b, "<img src=\"%s\" alt=\"%s\">\n", html.EscapeString(o.file(n.attr("src"))), html.EscapeString(n.attr("alt")))
case "fileAttachment":
fmt.Fprintf(b, "<p><a href=\"%s\">%s</a></p>\n", html.EscapeString(o.file(n.attr("url"))), html.EscapeString(n.attr("name")))
case "mermaid":
// Mermaid's own script draws <pre class="mermaid"> when a page loads it.
fmt.Fprintf(b, "<pre class=\"mermaid\">%s</pre>\n", html.EscapeString(n.attr("code")))
case "blockMath":
fmt.Fprintf(b, "<div class=\"math math-display\">\\[%s\\]</div>\n", html.EscapeString(n.attr("latex")))
case "inlineMath":
fmt.Fprintf(b, "<span class=\"math math-inline\">\\(%s\\)</span>", html.EscapeString(n.attr("latex")))
case "drawio", "excalidraw":
if src := n.attr("src"); src != "" {
fmt.Fprintf(b, "<figure><img src=\"%s\" alt=\"%s\"></figure>\n", html.EscapeString(o.file(src)), html.EscapeString(n.Type))
}
case "mention":
fmt.Fprintf(b, "<span class=\"mention\">@%s</span>", html.EscapeString(mentionLabel(n)))
case "dateMention":
d := html.EscapeString(n.attr("date"))
fmt.Fprintf(b, "<time datetime=\"%s\">%s</time>", d, d)
case "tableOfContents":
// Nothing to keep: readers of the file see the headings themselves.
case "details":
b.WriteString("<details>\n")
for _, c := range n.Content {
if c.Type == "detailsSummary" {
b.WriteString("<summary>")
for _, t := range c.Content {
writeHTML(b, t, o)
}
b.WriteString("</summary>\n")
} else {
writeHTML(b, c, o)
}
}
b.WriteString("</details>\n")
case "embed", "linkCard", "syncedPage":
href, title := n.card()
href = o.file(href)
if !safeURL.MatchString(href) {
return
}
fmt.Fprintf(b, "<p><a href=\"%s\">%s</a>", html.EscapeString(href), html.EscapeString(title))
if d := n.attr("description"); d != "" {
fmt.Fprintf(b, "<br>%s", html.EscapeString(d))
}
b.WriteString("</p>\n")
default:
tag, ok := htmlBlock[n.Type]
if !ok {
// Unknown block types still keep their text.
children()
return
}
fmt.Fprintf(b, "<%s>", tag)
if tag == "ul" || tag == "ol" {
b.WriteString("\n")
}
children()
fmt.Fprintf(b, "</%s>\n", tag)
}
}
// htmlAlign is the style attribute of an aligned paragraph or heading.
func htmlAlign(n Node) string {
if a := alignOf(n); a != "" {
return " style=\"text-align:" + a + "\""
}
return ""
}
func writeHTMLText(b *strings.Builder, n Node, o Options) {
var open, close []string
for _, m := range n.Marks {
switch m.Type {
case "bold":
open, close = append(open, "<strong>"), append([]string{"</strong>"}, close...)
case "italic":
open, close = append(open, "<em>"), append([]string{"</em>"}, close...)
case "strike":
open, close = append(open, "<s>"), append([]string{"</s>"}, close...)
case "underline":
open, close = append(open, "<u>"), append([]string{"</u>"}, close...)
case "code":
open, close = append(open, "<code>"), append([]string{"</code>"}, close...)
case "textColor":
if c := m.attr("color"); isPaletteColor(c) {
open = append(open, "<span data-color=\""+c+"\" style=\"color:"+paletteText[c]+"\">")
close = append([]string{"</span>"}, close...)
}
case "highlight":
c := m.attr("color")
if !isPaletteColor(c) {
c = "yellow"
}
open = append(open, "<mark data-color=\""+c+"\" style=\"background:"+paletteBackground[c]+"\">")
close = append([]string{"</mark>"}, close...)
case markSuggestInsert, markSuggestDelete:
op, cl := suggestionTags(m)
open, close = append(open, op), append([]string{cl}, close...)
case "link":
if href := o.file(m.attr("href")); safeURL.MatchString(href) {
open, close = append(open, "<a href=\""+html.EscapeString(href)+"\">"), append([]string{"</a>"}, close...)
}
}
}
b.WriteString(strings.Join(open, ""))
b.WriteString(html.EscapeString(n.Text))
b.WriteString(strings.Join(close, ""))
}
// ---- Markdown --------------------------------------------------------------
// Markdown renders the document as CommonMark (with ~~strikethrough~~).
func Markdown(doc Node, o Options) string {
doc, notes := numberFootnotes(withoutSuggestions(expandDatabases(doc)))
w := &mdWriter{o: o}
w.blocks(doc.Content, "", "")
out := strings.TrimRight(w.b.String(), "\n") + "\n"
if len(notes) > 0 {
// Footnote definitions, as GitHub and most Markdown tools read them.
out += "\n"
for i, note := range notes {
out += "[^" + strconv.Itoa(i+1) + "]: " + strings.ReplaceAll(w.inline(oneLine(note)), "\n", " ") + "\n"
}
}
return out
}
// MarkdownPage is Markdown with the title as a leading heading.
func MarkdownPage(title string, doc Node, o Options) string {
body := Markdown(doc, o)
if strings.TrimSpace(title) == "" {
return body
}
return "# " + escapeMD(title) + "\n\n" + body
}
type mdWriter struct {
b strings.Builder
o Options
}
// blocks writes block nodes; first prefixes the first line (a list marker),
// rest the following lines (indentation or "> ").
func (w *mdWriter) blocks(nodes []Node, first, rest string) {
for i, n := range nodes {
p := rest
if i == 0 {
p = first
}
if i > 0 {
w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
}
w.block(n, p, rest)
}
}
func (w *mdWriter) lines(text, first, rest string) {
for i, line := range strings.Split(text, "\n") {
if i == 0 {
w.b.WriteString(first)
} else {
w.b.WriteString(rest)
}
w.b.WriteString(line)
w.b.WriteString("\n")
}
}
func (w *mdWriter) block(n Node, first, rest string) {
switch n.Type {
case "paragraph":
w.lines(w.inline(n.Content), first, rest)
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
w.lines(strings.Repeat("#", level)+" "+w.inline(n.Content), first, rest)
case "blockquote":
w.blocks(n.Content, first+"> ", rest+"> ")
case "bulletList":
for i, item := range n.Content {
p := rest
if i == 0 {
p = first
}
w.blocks(item.Content, p+"- ", rest+" ")
}
case "taskList":
// GitHub's task lists, which FromMarkdown reads back.
for i, item := range n.Content {
p := rest
if i == 0 {
p = first
}
box := "[ ] "
if item.Attrs["checked"] == true {
box = "[x] "
}
if len(item.Content) == 0 || item.Content[0].Type != "paragraph" {
item.Content = append([]Node{{Type: "paragraph"}}, item.Content...)
}
w.blocks(item.Content, p+"- "+box, rest+" ")
}
case "callout":
// A GitHub alert; the emoji goes first in the text unless it is the alert's own.
emoji, color := calloutParts(n)
a := alertFor(color)
body := n.Content
if emoji != a.emoji && len(body) > 0 && body[0].Type == "paragraph" {
p := body[0]
p.Content = append([]Node{{Type: "text", Text: emoji + " "}}, p.Content...)
body = append([]Node{p}, body[1:]...)
}
w.lines("[!"+a.name+"]", first+"> ", rest+"> ")
w.blocks(body, rest+"> ", rest+"> ")
case "table":
w.table(n, first, rest)
case "orderedList":
start := n.intAttr("start", 1)
for i, item := range n.Content {
p := rest
if i == 0 {
p = first
}
marker := strconv.Itoa(start+i) + ". "
w.blocks(item.Content, p+marker, rest+strings.Repeat(" ", len(marker)))
}
case "codeBlock":
text := PlainText(n)
fence := "```"
for strings.Contains(text, fence) {
fence += "`"
}
w.lines(fence+n.attr("language")+"\n"+text+"\n"+fence, first, rest)
case "horizontalRule":
w.lines("---", first, rest)
case "pageBreak":
// Markdown has no page break; tools that print Markdown read this HTML.
w.lines("<div style=\"break-after: page\"></div>", first, rest)
case "tabs":
for i, tab := range n.Content {
p := rest
if i == 0 {
p = first
} else {
w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
}
w.lines("**"+escapeMD(tabTitle(tab, i))+"**", p, rest)
if len(tab.Content) > 0 {
w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
w.blocks(tab.Content, rest, rest)
}
}
case "video", "audio":
src := w.o.file(n.attr("src"))
if !safeURL.MatchString(src) {
return
}
name := n.attr("name")
if name == "" {
name = n.Type
}
w.lines("["+escapeMD(name)+"]("+mdURL(src)+")", first, rest)
case "subpages":
for i, p := range w.o.Subpages {
pre := rest
if i == 0 {
pre = first
}
w.lines("- ["+escapeMD(p.label())+"]("+mdURL(w.o.file("/p/"+p.ID))+")", pre, rest)
}
case "image":
w.lines("!["+escapeMD(n.attr("alt"))+"]("+mdURL(w.o.file(n.attr("src")))+")", first, rest)
case "fileAttachment":
w.lines("["+escapeMD(n.attr("name"))+"]("+mdURL(w.o.file(n.attr("url")))+")", first, rest)
case "mermaid":
code := n.attr("code")
fence := "```"
for strings.Contains(code, fence) {
fence += "`"
}
w.lines(fence+"mermaid\n"+code+"\n"+fence, first, rest)
case "blockMath":
w.lines("$$\n"+n.attr("latex")+"\n$$", first, rest)
case "drawio", "excalidraw":
if src := n.attr("src"); src != "" {
w.lines("![]("+mdURL(w.o.file(src))+")", first, rest)
}
case "tableOfContents":
case "details":
// GitHub and most Markdown viewers show <details> as a toggle.
summary := ""
var body []Node
for _, c := range n.Content {
if c.Type == "detailsSummary" {
summary = PlainText(c)
} else {
body = append(body, c.Content...)
}
}
w.lines("<details>\n<summary>"+html.EscapeString(summary)+"</summary>", first, rest)
if len(body) > 0 {
w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
w.blocks(body, rest, rest)
}
w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
w.lines("</details>", rest, rest)
case "embed", "linkCard", "syncedPage":
href, title := n.card()
href = w.o.file(href)
if !safeURL.MatchString(href) {
return
}
line := "[" + escapeMD(title) + "](" + mdURL(href) + ")"
if d := n.attr("description"); d != "" {
line += " — " + escapeMD(d)
}
w.lines(line, first, rest)
default:
if len(n.Content) > 0 {
w.blocks(n.Content, first, rest)
}
}
}
// table writes a GitHub table. Its first row is the header, as Markdown
// tables need one; cells keep their text on one line.
func (w *mdWriter) table(n Node, first, rest string) {
cols := 0
for _, row := range n.Content {
cols = max(cols, len(row.Content))
}
if cols == 0 {
return
}
line := func(cells []string) string {
for len(cells) < cols {
cells = append(cells, "")
}
return "| " + strings.Join(cells, " | ") + " |"
}
for i, row := range n.Content {
var cells []string
for _, c := range row.Content {
cells = append(cells, w.cellText(c))
}
p := rest
if i == 0 {
p = first
}
w.lines(line(cells), p, rest)
if i == 0 {
w.lines(line(slices.Repeat([]string{"---"}, cols)), rest, rest)
}
}
}
func (w *mdWriter) inline(nodes []Node) string {
var b strings.Builder
for _, n := range nodes {
switch n.Type {
case "hardBreak":
b.WriteString("\\\n")
case "text":
b.WriteString(w.text(n))
case "inlineMath":
b.WriteString("$" + n.attr("latex") + "$")
case "mention":
b.WriteString("@" + escapeMD(mentionLabel(n)))
case "dateMention":
b.WriteString(escapeMD(n.attr("date")))
case "status":
b.WriteString("`" + strings.ReplaceAll(statusText(n), "`", "'") + "`")
case "footnote":
b.WriteString("[^" + footnoteNumber(n) + "]")
default:
b.WriteString(w.inline(n.Content))
}
}
return b.String()
}
func (w *mdWriter) text(n Node) string {
code := false
for _, m := range n.Marks {
if m.Type == "code" {
code = true
}
}
s := n.Text
if code {
tick := "`"
for strings.Contains(s, tick) {
tick += "`"
}
pad := ""
if strings.HasPrefix(s, "`") || strings.HasSuffix(s, "`") {
pad = " "
}
s = tick + pad + s + pad + tick
} else {
s = escapeMD(s)
}
// Emphasis cannot start or end with spaces; keep them outside the markers.
core := strings.TrimSpace(s)
lead := s[:strings.Index(s, core)]
trail := s[len(lead)+len(core):]
if core == "" {
return s
}
for _, m := range n.Marks {
switch m.Type {
case "bold":
core = "**" + core + "**"
case "italic":
core = "*" + core + "*"
case "strike":
core = "~~" + core + "~~"
case "link":
if href := w.o.file(m.attr("href")); safeURL.MatchString(href) {
core = "[" + core + "](" + mdURL(href) + ")"
}
}
}
return lead + core + trail
}
var mdSpecial = strings.NewReplacer(
`\`, `\\`, "`", "\\`", "*", `\*`, "_", `\_`, "[", `\[`, "]", `\]`, "<", `\<`, ">", `\>`, "#", `\#`, "~", `\~`, "|", `\|`,
)
func escapeMD(s string) string { return mdSpecial.Replace(s) }
func mdURL(u string) string {
if strings.ContainsAny(u, " ()<>") {
return "<" + strings.NewReplacer("<", "%3C", ">", "%3E").Replace(u) + ">"
}
return u
}
// mentionLabel is the name a mention shows ("someone" when it has none).
func mentionLabel(n Node) string {
if l := n.attr("label"); l != "" {
return l
}
return "someone"
}