// 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 //
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