// SPDX-License-Identifier: AGPL-3.0-or-later // Package convert turns page documents (Tiptap/ProseMirror JSON in the Docwell // schema, see Packages/editor) into Markdown and HTML, and Markdown and HTML // back into documents. Imports keep only what the schema knows, which also // drops scripts, styles and event handlers from pasted or uploaded HTML. package convert import "encoding/json" // Node is one ProseMirror node or text run. type Node struct { Type string `json:"type"` Attrs map[string]any `json:"attrs,omitempty"` Content []Node `json:"content,omitempty"` Text string `json:"text,omitempty"` Marks []Mark `json:"marks,omitempty"` } type Mark struct { Type string `json:"type"` Attrs map[string]any `json:"attrs,omitempty"` } // Parse reads a document; null or empty input is an empty document. func Parse(raw json.RawMessage) (Node, error) { doc := Node{Type: "doc"} if len(raw) == 0 || string(raw) == "null" { return doc, nil } err := json.Unmarshal(raw, &doc) return doc, err } func (n Node) attr(key string) string { switch v := n.Attrs[key].(type) { case string: return v case float64: return json.Number(formatNumber(v)).String() } return "" } // card is the address and title of a block that links somewhere: an embed, // a link card, or a synced page (shown as a link to the page it shows). func (n Node) card() (href, title string) { if n.Type == "syncedPage" { href = "/p/" + n.attr("page") title = n.attr("title") if icon := n.attr("icon"); icon != "" && title != "" { title = icon + " " + title } if title == "" { title = "Synced page" } return href, title } href, title = n.attr("url"), n.attr("title") if title == "" { title = href } return href, title } func (n Node) intAttr(key string, def int) int { if v, ok := n.Attrs[key].(float64); ok { return int(v) } return def } func (m Mark) attr(key string) string { if v, ok := m.Attrs[key].(string); ok { return v } return "" } func formatNumber(f float64) string { b, _ := json.Marshal(f) return string(b) } // Title takes a leading level-1 heading as the page title and returns the // document without it; title is "" when the document does not start with one. func Title(doc Node) (string, Node) { if len(doc.Content) == 0 { return "", doc } first := doc.Content[0] if first.Type != "heading" || first.intAttr("level", 1) != 1 { return "", doc } doc.Content = doc.Content[1:] return PlainText(first), doc } // PlainText is the node's text with no formatting. func PlainText(n Node) string { if n.Type == "text" { return n.Text } var s string for _, c := range n.Content { s += PlainText(c) } return s }