// SPDX-License-Identifier: AGPL-3.0-or-later package convert import ( "html" "strconv" "strings" xhtml "golang.org/x/net/html" ) // Suggestions (Packages/editor/src/suggest.ts) are two marks on text: // suggestInsert on text someone proposes to add and suggestDelete on text // they propose to remove. HTML keeps them as / with their // details, so a page exported and imported again keeps its open // suggestions. Markdown, Word and PDF show the page as it stands until // someone accepts them: proposed text left out, proposed deletions kept. const ( markSuggestInsert = "suggestInsert" markSuggestDelete = "suggestDelete" ) // withoutSuggestions is the document with its open suggestions not taken: // inserted text dropped and deletion marks taken off. func withoutSuggestions(n Node) Node { if len(n.Content) == 0 { return n } out := make([]Node, 0, len(n.Content)) for _, c := range n.Content { if hasMark(c, markSuggestInsert) { continue } if hasMark(c, markSuggestDelete) { c.Marks = withoutMark(c.Marks, markSuggestDelete) } out = append(out, withoutSuggestions(c)) } n.Content = out return n } func hasMark(n Node, typ string) bool { for _, m := range n.Marks { if m.Type == typ { return true } } return false } func withoutMark(marks []Mark, typ string) []Mark { var out []Mark for _, m := range marks { if m.Type != typ { out = append(out, m) } } return out } // suggestionTags are the opening and closing tags of a suggestion mark. func suggestionTags(m Mark) (string, string) { tag, class := "ins", "dw-suggest-ins" if m.Type == markSuggestDelete { tag, class = "del", "dw-suggest-del" } open := "<" + tag + " class=\"" + class + "\" data-suggestion=\"" + html.EscapeString(m.attr("id")) + "\" data-author=\"" + html.EscapeString(m.attr("author")) + "\" data-name=\"" + html.EscapeString(m.attr("name")) + "\" data-at=\"" + suggestionTime(m) + "\">" return open, "" } // suggestionMark reads a suggestion from an or with data-suggestion. func suggestionMark(n *xhtml.Node, typ string) (Mark, bool) { id := attrOf(n, "data-suggestion") if strings.TrimSpace(id) == "" { return Mark{}, false } at, _ := strconv.ParseFloat(attrOf(n, "data-at"), 64) return Mark{Type: typ, Attrs: map[string]any{ "id": id, "author": attrOf(n, "data-author"), "name": attrOf(n, "data-name"), "at": at, }}, true } // suggestionTime is when a suggestion was made, in milliseconds, as text. func suggestionTime(m Mark) string { switch v := m.Attrs["at"].(type) { case float64: return strconv.FormatFloat(v, 'f', 0, 64) case string: if f, err := strconv.ParseFloat(v, 64); err == nil { return strconv.FormatFloat(f, 'f', 0, 64) } } return "0" }