// 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" ) // ImportOptions adjust how an import reads links and images. type ImportOptions struct { // Resolve, when set, sees every link and image URL first (relative ones // included). ok means the result is used as it is ("" drops the link or // image); otherwise the URL goes through the usual safety check. Resolve func(url string) (out string, ok bool) } // FromMarkdown reads CommonMark with GitHub's additions: strikethrough, // autolinks, task lists, tables and alerts ("> [!NOTE]", read as callouts). // Raw HTML in the Markdown is dropped. func FromMarkdown(md string) (Node, error) { return FromMarkdownWith(md, ImportOptions{}) } // FromMarkdownWith is FromMarkdown with options. func FromMarkdownWith(md string, o ImportOptions) (Node, error) { var buf bytes.Buffer gm := goldmark.New(goldmark.WithExtensions(extension.Strikethrough, extension.Linkify, extension.TaskList, extension.Table)) if err := gm.Convert([]byte(md), &buf); err != nil { return Node{}, err } return FromHTMLWith(buf.String(), o) } // 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) { return FromHTMLWith(src, ImportOptions{}) } // FromHTMLWith is FromHTML with options. func FromHTMLWith(src string, o ImportOptions) (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{o: o} 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{ o ImportOptions } // url applies the resolver and the safety check; "" means drop. func (r *reader) url(u string) string { if r.o.Resolve != nil { if out, ok := r.o.Resolve(u); ok { return out } } if safeURL.MatchString(u) { return u } return "" } // lonelyImage is the image a link holds and nothing else besides blank text // (how Notion and many sites wrap images), or nil. func lonelyImage(n *html.Node) *html.Node { var img *html.Node for c := n.FirstChild; c != nil; c = c.NextSibling { switch { case c.Type == html.TextNode && strings.TrimSpace(c.Data) == "": case c.Type == html.ElementNode && c.DataAtom == atom.Img && img == nil: img = c default: return nil } } return img } 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 && c.DataAtom == atom.A { if img := lonelyImage(c); img != nil { flush() out = append(out, r.block(img)...) 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: 4, atom.H5: 5, atom.H6: 6} func hasClass(n *html.Node, class string) bool { return strings.Contains(" "+attrOf(n, "class")+" ", " "+class+" ") } // aligned sets the alignment n's style asks for on the text blocks of out. func aligned(n *html.Node, out []Node) []Node { m := cssAlign.FindStringSubmatch(attrOf(n, "style")) if m == nil { return out } for i := range out { if out[i].Type == "paragraph" || out[i].Type == "heading" { out[i].Attrs = cloneAttrs(out[i].Attrs) out[i].Attrs["textAlign"] = strings.ToLower(m[1]) } } return out } // checkbox is a list item's leading checkbox: an // (Markdown task lists, Docwell's HTML) or Notion's
, // directly in the item or in its first paragraph. func checkbox(li *html.Node) (found, checked bool) { if v := attrOf(li, "data-checked"); attrOf(li, "data-type") == "taskItem" { return true, v == "true" } for c := li.FirstChild; c != nil; c = c.NextSibling { switch { case c.Type == html.TextNode && strings.TrimSpace(c.Data) == "": continue case c.Type != html.ElementNode: return false, false case c.DataAtom == atom.Input && strings.EqualFold(attrOf(c, "type"), "checkbox"): _, on := attrValue(c, "checked") return true, on case c.DataAtom == atom.Div && hasClass(c, "checkbox"): return true, hasClass(c, "checkbox-on") case c.DataAtom == atom.P || c.DataAtom == atom.Label: return checkbox(c) } return false, false } return false, false } func attrValue(n *html.Node, key string) (string, bool) { for _, a := range n.Attr { if a.Key == key { return a.Val, true } } return "", false } 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 aligned(n, 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 aligned(n, []Node{h}) case atom.Div: if cols, ok := r.readColumns(n); ok { return cols } case atom.Aside: if attrOf(n, "data-type") == "callout" { body := n for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.ElementNode && hasClass(c, "callout-body") { body = c } } return []Node{newCallout(attrOf(n, "data-emoji"), attrOf(n, "data-color"), r.blocks(body))} } case atom.Figure: // Notion:

💡
text
if hasClass(n, "callout") { emoji := "" var body []Node for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type != html.ElementNode { continue } if emoji == "" && body == nil && strings.TrimSpace(textOf(c)) != "" && len([]rune(strings.TrimSpace(textOf(c)))) <= 4 { emoji = strings.TrimSpace(textOf(c)) continue } body = append(body, r.block(c)...) } return []Node{newCallout(emoji, "", body)} } case atom.Table: return r.table(n) 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)} } tasks := attrOf(n, "data-type") == "taskList" || hasClass(n, "to-do-list") for c := n.FirstChild; c != nil && !tasks && n.DataAtom == atom.Ul; c = c.NextSibling { if c.Type == html.ElementNode { tasks, _ = checkbox(c) } } if tasks { list = Node{Type: "taskList"} } for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type != html.ElementNode { continue } item := r.listItem(c) if tasks { _, checked := checkbox(c) item.Type = "taskItem" item.Attrs = map[string]any{"checked": checked} } list.Content = append(list.Content, item) } 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 c, ok := alertCallout(content); ok { return []Node{c} } 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] } } text := strings.TrimSuffix(textOf(n), "\n") if code.Attrs["language"] == "mermaid" || strings.Contains(" "+attrOf(n, "class")+" ", " mermaid ") { return []Node{{Type: "mermaid", Attrs: map[string]any{"code": text}}} } if text != "" { code.Content = []Node{{Type: "text", Text: text}} } return []Node{code} case atom.Details: summary := Node{Type: "detailsSummary"} var body []Node for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type == html.ElementNode && c.DataAtom == atom.Summary && summary.Content == nil { summary.Content = trimInline(r.inlineChildren(c, nil)) continue } body = append(body, r.block(c)...) } if len(body) == 0 { body = []Node{{Type: "paragraph"}} } return []Node{{Type: "details", Content: []Node{summary, {Type: "detailsContent", Content: body}}}} case atom.Hr: return []Node{{Type: "horizontalRule"}} case atom.Img: src := r.url(attrOf(n, "src")) if src == "" { return nil } return []Node{{Type: "image", Attrs: map[string]any{"src": src, "alt": attrOf(n, "alt"), "title": nil}}} } // Containers (div, section, table, ...) contribute their children. return r.blocks(n) } // alertCallout turns a quote that starts with a GitHub alert marker // ("[!NOTE]") into a callout of that kind. func alertCallout(content []Node) (Node, bool) { if len(content) == 0 || content[0].Type != "paragraph" || len(content[0].Content) == 0 || content[0].Content[0].Type != "text" { return Node{}, false } first := content[0].Content[0] m := alertMarker.FindStringSubmatch(first.Text) if m == nil { return Node{}, false } a := alertNamed(m[1]) p := content[0] p.Content = append([]Node{}, p.Content...) p.Content[0].Text = first.Text[len(m[0]):] if p.Content[0].Text == "" { p.Content = p.Content[1:] } // A line break after the marker is not part of the text. if len(p.Content) > 0 && p.Content[0].Type == "hardBreak" { p.Content = p.Content[1:] } body := append([]Node{p}, content[1:]...) if len(p.Content) == 0 { body = content[1:] } emoji, body := liftEmoji(body) if emoji == "" { emoji = a.emoji } return newCallout(emoji, a.color, body), true } // table reads an HTML table: the rows of its head, bodies and foot in // order, header cells as tableHeader. Every cell holds at least a paragraph. func (r *reader) table(n *html.Node) []Node { t := Node{Type: "table"} var rows func(*html.Node) rows = func(n *html.Node) { for c := n.FirstChild; c != nil; c = c.NextSibling { if c.Type != html.ElementNode { continue } switch c.DataAtom { case atom.Thead, atom.Tbody, atom.Tfoot: rows(c) case atom.Tr: row := Node{Type: "tableRow"} for cell := c.FirstChild; cell != nil; cell = cell.NextSibling { if cell.Type != html.ElementNode || (cell.DataAtom != atom.Td && cell.DataAtom != atom.Th) { continue } kind := "tableCell" if cell.DataAtom == atom.Th { kind = "tableHeader" } attrs := map[string]any{"colspan": float64(1), "rowspan": float64(1), "colwidth": nil} for _, span := range []string{"colspan", "rowspan"} { if v, err := strconv.Atoi(attrOf(cell, span)); err == nil && v > 1 && v < 1000 { attrs[span] = float64(v) } } content := aligned(cell, r.blocks(cell)) if len(content) == 0 { content = []Node{{Type: "paragraph"}} } row.Content = append(row.Content, Node{Type: kind, Attrs: attrs, Content: content}) } if len(row.Content) > 0 { t.Content = append(t.Content, row) } } } } rows(n) if len(t.Content) == 0 { return nil } return []Node{t} } 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.Del: if m, ok := suggestionMark(n, markSuggestDelete); ok { marks = add(m) } else { marks = add(mark{Type: "strike"}) } case atom.Ins: if m, ok := suggestionMark(n, markSuggestInsert); ok { marks = add(m) } else { marks = add(mark{Type: "underline"}) } case atom.S, atom.Strike: marks = add(mark{Type: "strike"}) case atom.U: marks = add(mark{Type: "underline"}) case atom.Code, atom.Kbd, atom.Samp: marks = add(mark{Type: "code"}) case atom.Mark: c := attrOf(n, "data-color") if !isPaletteColor(c) { c = "yellow" } marks = add(mark{Type: "highlight", Attrs: map[string]any{"color": c}}) case atom.Span, atom.Font: if c := attrOf(n, "data-color"); isPaletteColor(c) { marks = add(mark{Type: "textColor", Attrs: map[string]any{"color": c}}) } // The emoji Docwell's HTML shows in a callout is in its data-emoji too. if hasClass(n, "callout-emoji") { return nil } case atom.A: if href := r.url(attrOf(n, "href")); 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

in // ) 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() }