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>
326 lines
9.4 KiB
Go
326 lines
9.4 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package convert
|
|
|
|
import (
|
|
"bytes"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/yuin/goldmark"
|
|
"github.com/yuin/goldmark/extension"
|
|
"golang.org/x/net/html"
|
|
"golang.org/x/net/html/atom"
|
|
)
|
|
|
|
// FromMarkdown reads CommonMark (with GitHub's strikethrough, autolinks and
|
|
// task lists, the latter as plain lists). Raw HTML in the Markdown is dropped.
|
|
func FromMarkdown(md string) (Node, error) {
|
|
var buf bytes.Buffer
|
|
gm := goldmark.New(goldmark.WithExtensions(extension.Strikethrough, extension.Linkify, extension.TaskList))
|
|
if err := gm.Convert([]byte(md), &buf); err != nil {
|
|
return Node{}, err
|
|
}
|
|
return FromHTML(buf.String())
|
|
}
|
|
|
|
// FromHTML reads an HTML document or fragment into the Docwell schema.
|
|
// Elements the schema has no node for are unwrapped (their text is kept);
|
|
// script, style and similar elements are dropped with their content.
|
|
func FromHTML(src string) (Node, error) {
|
|
root, err := html.Parse(strings.NewReader(src))
|
|
if err != nil {
|
|
return Node{}, err
|
|
}
|
|
body := find(root, atom.Body)
|
|
if body == nil {
|
|
body = root
|
|
}
|
|
r := &reader{}
|
|
doc := Node{Type: "doc", Content: r.blocks(body)}
|
|
if len(doc.Content) == 0 {
|
|
doc.Content = []Node{{Type: "paragraph"}}
|
|
}
|
|
return doc, nil
|
|
}
|
|
|
|
func find(n *html.Node, a atom.Atom) *html.Node {
|
|
if n.Type == html.ElementNode && n.DataAtom == a {
|
|
return n
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
if f := find(c, a); f != nil {
|
|
return f
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func attrOf(n *html.Node, key string) string {
|
|
for _, a := range n.Attr {
|
|
if a.Key == key {
|
|
return a.Val
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
var dropped = map[atom.Atom]bool{
|
|
atom.Script: true, atom.Style: true, atom.Noscript: true, atom.Template: true, atom.Iframe: true,
|
|
atom.Object: true, atom.Embed: true, atom.Head: true, atom.Title: true, atom.Svg: true, atom.Math: true,
|
|
atom.Button: true, atom.Select: true, atom.Textarea: true, atom.Input: true,
|
|
}
|
|
|
|
var blockAtoms = map[atom.Atom]bool{
|
|
atom.P: true, atom.H1: true, atom.H2: true, atom.H3: true, atom.H4: true, atom.H5: true, atom.H6: true,
|
|
atom.Ul: true, atom.Ol: true, atom.Li: true, atom.Blockquote: true, atom.Pre: true, atom.Hr: true,
|
|
atom.Div: true, atom.Section: true, atom.Article: true, atom.Main: true, atom.Header: true, atom.Footer: true,
|
|
atom.Aside: true, atom.Nav: true, atom.Figure: true, atom.Table: true, atom.Tr: true, atom.Img: true,
|
|
atom.Dl: true, atom.Dt: true, atom.Dd: true, atom.Details: true, atom.Summary: true, atom.Figcaption: true,
|
|
atom.Thead: true, atom.Tbody: true, atom.Tfoot: true, atom.Td: true, atom.Th: true,
|
|
}
|
|
|
|
type reader struct{}
|
|
|
|
type mark = Mark
|
|
|
|
// blocks reads the children of n as block nodes; loose inline content is
|
|
// gathered into paragraphs.
|
|
func (r *reader) blocks(n *html.Node) []Node {
|
|
var out []Node
|
|
var loose []Node
|
|
flush := func() {
|
|
if p := trimInline(loose); len(p) > 0 {
|
|
out = append(out, Node{Type: "paragraph", Content: p})
|
|
}
|
|
loose = nil
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
if c.Type == html.ElementNode && dropped[c.DataAtom] {
|
|
continue
|
|
}
|
|
if c.Type == html.ElementNode && blockAtoms[c.DataAtom] {
|
|
flush()
|
|
out = append(out, r.block(c)...)
|
|
continue
|
|
}
|
|
loose = append(loose, r.inline(c, nil)...)
|
|
}
|
|
flush()
|
|
return out
|
|
}
|
|
|
|
var headingLevel = map[atom.Atom]int{atom.H1: 1, atom.H2: 2, atom.H3: 3, atom.H4: 3, atom.H5: 3, atom.H6: 3}
|
|
|
|
var languageClass = regexp.MustCompile(`(?:^|\s)(?:language|lang)-([A-Za-z0-9_+#.-]{1,40})`)
|
|
|
|
func (r *reader) block(n *html.Node) []Node {
|
|
switch n.DataAtom {
|
|
case atom.P, atom.Dt, atom.Dd, atom.Summary, atom.Figcaption, atom.Td, atom.Th:
|
|
// Text becomes a paragraph; images (blocks in the schema, but inside
|
|
// <p> in Markdown output) are lifted out next to it.
|
|
return r.blocks(n)
|
|
case atom.H1, atom.H2, atom.H3, atom.H4, atom.H5, atom.H6:
|
|
h := Node{Type: "heading", Attrs: map[string]any{"level": float64(headingLevel[n.DataAtom])}}
|
|
h.Content = trimInline(r.inlineChildren(n, nil))
|
|
return []Node{h}
|
|
case atom.Ul, atom.Ol:
|
|
list := Node{Type: "bulletList"}
|
|
if n.DataAtom == atom.Ol {
|
|
list.Type = "orderedList"
|
|
start := 1
|
|
if s, err := strconv.Atoi(attrOf(n, "start")); err == nil {
|
|
start = s
|
|
}
|
|
list.Attrs = map[string]any{"start": float64(start)}
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
if c.Type != html.ElementNode {
|
|
continue
|
|
}
|
|
list.Content = append(list.Content, r.listItem(c))
|
|
}
|
|
if len(list.Content) == 0 {
|
|
return nil
|
|
}
|
|
return []Node{list}
|
|
case atom.Li:
|
|
return []Node{{Type: "bulletList", Content: []Node{r.listItem(n)}}}
|
|
case atom.Blockquote:
|
|
content := r.blocks(n)
|
|
if len(content) == 0 {
|
|
content = []Node{{Type: "paragraph"}}
|
|
}
|
|
return []Node{{Type: "blockquote", Content: content}}
|
|
case atom.Pre:
|
|
code := Node{Type: "codeBlock", Attrs: map[string]any{"language": nil}}
|
|
if c := find(n, atom.Code); c != nil {
|
|
if m := languageClass.FindStringSubmatch(attrOf(c, "class")); m != nil {
|
|
code.Attrs["language"] = m[1]
|
|
}
|
|
}
|
|
if text := strings.TrimSuffix(textOf(n), "\n"); text != "" {
|
|
code.Content = []Node{{Type: "text", Text: text}}
|
|
}
|
|
return []Node{code}
|
|
case atom.Hr:
|
|
return []Node{{Type: "horizontalRule"}}
|
|
case atom.Img:
|
|
src := attrOf(n, "src")
|
|
if !safeURL.MatchString(src) {
|
|
return nil
|
|
}
|
|
return []Node{{Type: "image", Attrs: map[string]any{"src": src, "alt": attrOf(n, "alt"), "title": nil}}}
|
|
case atom.Tr:
|
|
// Tables are not in the schema yet; each row becomes a paragraph of cells.
|
|
var cells []Node
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
if c.Type == html.ElementNode && (c.DataAtom == atom.Td || c.DataAtom == atom.Th) {
|
|
if len(cells) > 0 {
|
|
cells = append(cells, Node{Type: "text", Text: " · "})
|
|
}
|
|
cells = append(cells, trimInline(r.inlineChildren(c, nil))...)
|
|
}
|
|
}
|
|
if len(cells) == 0 {
|
|
return nil
|
|
}
|
|
return []Node{{Type: "paragraph", Content: cells}}
|
|
}
|
|
// Containers (div, section, table, ...) contribute their children.
|
|
return r.blocks(n)
|
|
}
|
|
|
|
func (r *reader) listItem(n *html.Node) Node {
|
|
item := Node{Type: "listItem", Content: r.blocks(n)}
|
|
if len(item.Content) == 0 || item.Content[0].Type != "paragraph" {
|
|
item.Content = append([]Node{{Type: "paragraph"}}, item.Content...)
|
|
}
|
|
return item
|
|
}
|
|
|
|
func (r *reader) inlineChildren(n *html.Node, marks []mark) []Node {
|
|
var out []Node
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
out = append(out, r.inline(c, marks)...)
|
|
}
|
|
return out
|
|
}
|
|
|
|
var whitespace = regexp.MustCompile(`[ \t\r\n\f]+`)
|
|
|
|
func (r *reader) inline(n *html.Node, marks []mark) []Node {
|
|
switch n.Type {
|
|
case html.TextNode:
|
|
text := whitespace.ReplaceAllString(n.Data, " ")
|
|
if text == "" {
|
|
return nil
|
|
}
|
|
return []Node{{Type: "text", Text: text, Marks: append([]mark(nil), marks...)}}
|
|
case html.ElementNode:
|
|
default:
|
|
return nil
|
|
}
|
|
if dropped[n.DataAtom] {
|
|
return nil
|
|
}
|
|
add := func(m mark) []mark {
|
|
for _, have := range marks {
|
|
if have.Type == m.Type {
|
|
return marks
|
|
}
|
|
}
|
|
return append(append([]mark(nil), marks...), m)
|
|
}
|
|
switch n.DataAtom {
|
|
case atom.Br:
|
|
return []Node{{Type: "hardBreak"}}
|
|
case atom.Strong, atom.B:
|
|
marks = add(mark{Type: "bold"})
|
|
case atom.Em, atom.I:
|
|
marks = add(mark{Type: "italic"})
|
|
case atom.S, atom.Del, atom.Strike:
|
|
marks = add(mark{Type: "strike"})
|
|
case atom.U, atom.Ins:
|
|
marks = add(mark{Type: "underline"})
|
|
case atom.Code, atom.Kbd, atom.Samp:
|
|
marks = add(mark{Type: "code"})
|
|
case atom.A:
|
|
if href := attrOf(n, "href"); safeURL.MatchString(href) {
|
|
marks = add(mark{Type: "link", Attrs: map[string]any{
|
|
"href": href, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
|
|
}})
|
|
}
|
|
case atom.Img:
|
|
// An image nested in inline markup (a link, bold text) cannot be a
|
|
// block here; keep its alt text.
|
|
if alt := attrOf(n, "alt"); alt != "" {
|
|
return []Node{{Type: "text", Text: alt, Marks: append([]mark(nil), marks...)}}
|
|
}
|
|
return nil
|
|
}
|
|
// Other elements (span, and blocks inside inline content such as <p> in
|
|
// <a>) keep their text inline.
|
|
return r.inlineChildren(n, marks)
|
|
}
|
|
|
|
// trimInline drops whitespace at the edges of a paragraph and merges runs
|
|
// with equal marks.
|
|
func trimInline(nodes []Node) []Node {
|
|
for len(nodes) > 0 && nodes[0].Type == "text" && strings.TrimSpace(nodes[0].Text) == "" {
|
|
nodes = nodes[1:]
|
|
}
|
|
for len(nodes) > 0 && nodes[len(nodes)-1].Type == "text" && strings.TrimSpace(nodes[len(nodes)-1].Text) == "" {
|
|
nodes = nodes[:len(nodes)-1]
|
|
}
|
|
if len(nodes) == 0 {
|
|
return nil
|
|
}
|
|
if nodes[0].Type == "text" {
|
|
nodes[0].Text = strings.TrimLeft(nodes[0].Text, " ")
|
|
}
|
|
if last := len(nodes) - 1; nodes[last].Type == "text" {
|
|
nodes[last].Text = strings.TrimRight(nodes[last].Text, " ")
|
|
}
|
|
var out []Node
|
|
for _, n := range nodes {
|
|
if l := len(out) - 1; l >= 0 && n.Type == "text" && out[l].Type == "text" && sameMarks(out[l].Marks, n.Marks) {
|
|
out[l].Text += n.Text
|
|
continue
|
|
}
|
|
if n.Type == "text" && n.Text == "" {
|
|
continue
|
|
}
|
|
out = append(out, n)
|
|
}
|
|
return out
|
|
}
|
|
|
|
func sameMarks(a, b []mark) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
for i := range a {
|
|
if a[i].Type != b[i].Type || (a[i].Type == "link" && a[i].attr("href") != b[i].attr("href")) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func textOf(n *html.Node) string {
|
|
if n.Type == html.TextNode {
|
|
return n.Data
|
|
}
|
|
var b strings.Builder
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
if c.Type == html.ElementNode && c.DataAtom == atom.Br {
|
|
b.WriteString("\n")
|
|
continue
|
|
}
|
|
b.WriteString(textOf(c))
|
|
}
|
|
return b.String()
|
|
}
|