Files
Docwell/Server/internal/convert/export.go
T
tajniak81andClaude Opus 5.5 011833fcef Add Markdown and HTML import and export
docwell-server converts between page documents and Markdown or HTML (a
new convert package), so every client and the API get the same results.
Pages export as a download from the page menu; spaces import one page
per .md, .txt or .html file, taking a leading level-1 heading as the
title. Import keeps only what the editor schema knows, which drops
scripts, styles, event handlers and javascript: links; tables become
one paragraph per row until the editor has tables.

The UI package gains DwMenu, a small accessible action menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:04:39 +01:00

302 lines
7.8 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"fmt"
"html"
"regexp"
"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
}
func (o Options) file(path string) string {
if o.FileURL != nil && strings.HasPrefix(path, "/api/v1/files/") {
return o.FileURL(path)
}
return path
}
// safeURL keeps links to the web, mail, the server's own paths and anchors;
// anything else (javascript:, data:, ...) is dropped.
var safeURL = regexp.MustCompile(`^(?i)(https?://|mailto:|/|#)`)
// ---- HTML ------------------------------------------------------------------
// HTML renders the document's body as HTML.
func HTML(doc Node, o Options) string {
var b strings.Builder
for _, n := range doc.Content {
writeHTML(&b, n, o)
}
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{
"paragraph": "p", "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>", level)
children()
fmt.Fprintf(b, "</h%d>\n", level)
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 "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")))
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)
}
}
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 "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 {
w := &mdWriter{o: o}
w.blocks(doc.Content, "", "")
return strings.TrimRight(w.b.String(), "\n") + "\n"
}
// 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 "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 "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)
default:
if len(n.Content) > 0 {
w.blocks(n.Content, first, 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))
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
}