// SPDX-License-Identifier: AGPL-3.0-or-later package convert import ( "encoding/json" "strconv" ) // numberFootnotes returns a copy of doc in which each footnote carries its // number (attr "n") in reading order, and the footnotes' texts (see // footnoteContent) in that order. Exports show the number in the text and // list the notes at the end, as the editor does. func numberFootnotes(doc Node) (Node, [][]Node) { var notes [][]Node var walk func(n Node) Node walk = func(n Node) Node { if n.Type == "footnote" { notes = append(notes, footnoteContent(n)) attrs := make(map[string]any, len(n.Attrs)+1) for k, v := range n.Attrs { attrs[k] = v } attrs["n"] = float64(len(notes)) n.Attrs = attrs return n } if len(n.Content) > 0 { content := make([]Node, len(n.Content)) for i, c := range n.Content { content[i] = walk(c) } n.Content = content } return n } return walk(doc), notes } // footnoteContent is a footnote's text as inline nodes: its formatted text // (attr "content": text runs with marks, and line breaks), or its plain text // (attr "text") as one run for notes without. func footnoteContent(n Node) []Node { if raw, ok := n.Attrs["content"].([]any); ok && len(raw) > 0 { var nodes []Node if b, err := json.Marshal(raw); err == nil && json.Unmarshal(b, &nodes) == nil { kept := nodes[:0] for _, c := range nodes { if (c.Type == "text" && c.Text != "") || c.Type == "hardBreak" { c.Content = nil kept = append(kept, c) } } if len(kept) > 0 { return kept } } } if t := n.attr("text"); t != "" { return []Node{{Type: "text", Text: t}} } return nil } // oneLine turns a note's line breaks into spaces, for formats where a note // must stay on one line. func oneLine(nodes []Node) []Node { out := make([]Node, len(nodes)) for i, n := range nodes { if n.Type == "hardBreak" { n = Node{Type: "text", Text: " "} } out[i] = n } return out } // footnoteNumber is a numbered footnote's number as text ("1"), or "*". func footnoteNumber(n Node) string { if v := n.intAttr("n", 0); v > 0 { return strconv.Itoa(v) } return "*" } // statusText is a status badge's words. func statusText(n Node) string { if t := n.attr("text"); t != "" { return t } return "Status" } // statusColor is a status badge's palette colour, grey when it has none. func statusColor(n Node) string { if c := n.attr("color"); isPaletteColor(c) { return c } return "gray" } // tabTitle is a tab's name, or "Tab " for one without. func tabTitle(n Node, i int) string { if t := n.attr("title"); t != "" { return t } return "Tab " + strconv.Itoa(i+1) }