Add tables, to-dos, callouts and the rest of editor parity
The editor gains the blocks and formatting it lacked next to AFFiNE: - Tables with a header row, resizable columns, a toolbar to add, delete, merge and split, and rows that move by a drag grip, toolbar buttons or Ctrl+Alt+Up/Down. - To-do lists (also from "[] "), callouts with an emoji and colour, and headings down to level 6 (Ctrl+Shift+0-6 for text and headings). - Text colour and highlights from a fixed palette that follows the theme, and left, centre and right alignment. - Optional line numbers on code blocks, with a default hosts can set. - PDF attachments show their pages inline; pdf.js loads only then, and the mobile bundle leaves it out. - The selection toolbar adds underline, colour, align, inline math, make a linked page and copy block link. A grip beside each block drags it and opens a menu: turn into, move, duplicate, copy, copy link, delete. - The slash menu adds Today, Tomorrow, Yesterday, Now and New page. The web app translates the new words and makes linked pages as children of the open page. The mobile bridge gets underline, to-do, callout and table commands, so its protocol moves to version 2 and the bundle is rebuilt. docwell-server's converters learn the new nodes: Markdown writes task lists, GitHub alerts and tables and reads them back; HTML keeps colours and alignment and reads its own output back; PDF draws tables, to-dos, callouts and coloured text; Word import keeps tables, alignment, H4-H6 and colours; Notion import turns databases into tables and keeps callouts and to-dos. Imported tables and H4-H6 headings no longer collapse into paragraphs and H3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3c7403ddf9
commit
d28f1e02db
44 files changed
+4318
-338
No files matched your search
@@ -0,0 +1,230 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// The palette colours of text, highlights and callouts (Packages/editor
|
||||
// colors.ts). Documents store the name; files that need a value get the
|
||||
// light theme's.
|
||||
var paletteText = map[string]string{
|
||||
"gray": "#6b6f6d", "red": "#c0392b", "orange": "#c2571a", "yellow": "#9a7400", "green": "#3d7a1f",
|
||||
"teal": "#1f7f79", "blue": "#2f6fbf", "purple": "#7c5cc4", "pink": "#b8327a",
|
||||
}
|
||||
|
||||
var paletteBackground = map[string]string{
|
||||
"gray": "#ecece9", "red": "#fbe3df", "orange": "#fbe7d7", "yellow": "#fbf1c7", "green": "#e4f1d8",
|
||||
"teal": "#d9efec", "blue": "#dfe9f7", "purple": "#ebe4f7", "pink": "#f8e0ec",
|
||||
}
|
||||
|
||||
func isPaletteColor(c string) bool {
|
||||
_, ok := paletteText[c]
|
||||
return ok
|
||||
}
|
||||
|
||||
// rgb reads a "#rrggbb" colour.
|
||||
func rgb(hex string) (r, g, b int) {
|
||||
v, err := strconv.ParseUint(strings.TrimPrefix(hex, "#"), 16, 32)
|
||||
if err != nil || len(hex) != 7 {
|
||||
return 0, 0, 0
|
||||
}
|
||||
return int(v >> 16 & 0xff), int(v >> 8 & 0xff), int(v & 0xff)
|
||||
}
|
||||
|
||||
// nearestPalette maps a "rrggbb" colour from another program to the
|
||||
// palette colour of its hue, or "" for black, white and near-greys, which
|
||||
// stay plain text (dark greys are usually just text).
|
||||
func nearestPalette(hex string) string {
|
||||
if len(strings.TrimPrefix(hex, "#")) != 6 {
|
||||
return ""
|
||||
}
|
||||
r, g, b := rgb("#" + strings.TrimPrefix(strings.ToLower(hex), "#"))
|
||||
hi, lo := max(r, g, b), min(r, g, b)
|
||||
switch {
|
||||
case hi < 60 || lo > 235:
|
||||
return ""
|
||||
case hi-lo < 40:
|
||||
if hi > 90 && hi < 200 {
|
||||
return "gray"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
var hue float64
|
||||
d := float64(hi - lo)
|
||||
switch hi {
|
||||
case r:
|
||||
hue = 60 * float64(g-b) / d
|
||||
case g:
|
||||
hue = 60*float64(b-r)/d + 120
|
||||
default:
|
||||
hue = 60*float64(r-g)/d + 240
|
||||
}
|
||||
if hue < 0 {
|
||||
hue += 360
|
||||
}
|
||||
for _, band := range []struct {
|
||||
upTo float64
|
||||
name string
|
||||
}{{15, "red"}, {40, "orange"}, {70, "yellow"}, {160, "green"}, {200, "teal"}, {250, "blue"}, {290, "purple"}, {345, "pink"}} {
|
||||
if hue < band.upTo {
|
||||
return band.name
|
||||
}
|
||||
}
|
||||
return "red"
|
||||
}
|
||||
|
||||
// ---- Callouts --------------------------------------------------------------
|
||||
|
||||
// alert is a GitHub Markdown alert ("> [!NOTE]"), which callouts become in
|
||||
// Markdown, with the colour and emoji a callout read from one gets.
|
||||
type alert struct{ name, color, emoji string }
|
||||
|
||||
var alerts = []alert{
|
||||
{"NOTE", "blue", "💡"}, {"TIP", "green", "✅"}, {"IMPORTANT", "purple", "❗"},
|
||||
{"WARNING", "yellow", "⚠️"}, {"CAUTION", "red", "🚫"},
|
||||
}
|
||||
|
||||
// alertFor is the alert closest to a callout colour.
|
||||
func alertFor(color string) alert {
|
||||
switch color {
|
||||
case "green":
|
||||
return alerts[1]
|
||||
case "purple", "pink":
|
||||
return alerts[2]
|
||||
case "yellow", "orange":
|
||||
return alerts[3]
|
||||
case "red":
|
||||
return alerts[4]
|
||||
}
|
||||
return alerts[0]
|
||||
}
|
||||
|
||||
var alertMarker = regexp.MustCompile(`^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*`)
|
||||
|
||||
func alertNamed(name string) alert {
|
||||
for _, a := range alerts {
|
||||
if a.name == strings.ToUpper(name) {
|
||||
return a
|
||||
}
|
||||
}
|
||||
return alerts[0]
|
||||
}
|
||||
|
||||
// leadingEmoji splits an emoji, and the space after it, off the start of s.
|
||||
// emoji is "" when s does not start with one followed by a space.
|
||||
func leadingEmoji(s string) (emoji, rest string) {
|
||||
i, joined := 0, true // joined: the next rune may start the emoji, or continue it after a ZWJ
|
||||
for i < len(s) {
|
||||
r, size := utf8.DecodeRuneInString(s[i:])
|
||||
switch {
|
||||
case joined && isEmojiBase(r):
|
||||
joined = false
|
||||
case i > 0 && (r == 0xFE0F || (r >= 0x1F3FB && r <= 0x1F3FF) || r == 0x20E3 || (r >= 0x1F1E6 && r <= 0x1F1FF)):
|
||||
// Variation selectors, skin tones, keycaps and the second letter of a flag.
|
||||
case i > 0 && r == 0x200D:
|
||||
joined = true
|
||||
case i > 0 && !joined && (r == 0x20 || r == 0xA0):
|
||||
return s[:i], s[i+size:]
|
||||
default:
|
||||
return "", s
|
||||
}
|
||||
i += size
|
||||
}
|
||||
if i == 0 || joined {
|
||||
return "", s
|
||||
}
|
||||
return s, ""
|
||||
}
|
||||
|
||||
func isEmojiBase(r rune) bool {
|
||||
return r >= 0x1F000 || (r >= 0x2190 && r <= 0x2BFF) || r == 0x2705 || unicode.Is(unicode.So, r)
|
||||
}
|
||||
|
||||
// calloutParts is a callout's emoji and colour, with the defaults filled in.
|
||||
func calloutParts(n Node) (emoji, color string) {
|
||||
emoji, color = n.attr("emoji"), n.attr("color")
|
||||
if !isPaletteColor(color) {
|
||||
color = "blue"
|
||||
}
|
||||
if emoji == "" {
|
||||
emoji = "💡"
|
||||
}
|
||||
return emoji, color
|
||||
}
|
||||
|
||||
// newCallout is a callout node around body, which gets an empty paragraph
|
||||
// when it has nothing.
|
||||
func newCallout(emoji, color string, body []Node) Node {
|
||||
if emoji == "" {
|
||||
emoji = "💡"
|
||||
}
|
||||
if !isPaletteColor(color) {
|
||||
color = "blue"
|
||||
}
|
||||
if len(body) == 0 {
|
||||
body = []Node{{Type: "paragraph"}}
|
||||
}
|
||||
return Node{Type: "callout", Attrs: map[string]any{"emoji": emoji, "color": color}, Content: body}
|
||||
}
|
||||
|
||||
// liftEmoji takes an emoji off the start of the first paragraph of body, as
|
||||
// callouts imported from Markdown and Notion carry their icon there.
|
||||
func liftEmoji(body []Node) (string, []Node) {
|
||||
if len(body) == 0 || body[0].Type != "paragraph" || len(body[0].Content) == 0 || body[0].Content[0].Type != "text" {
|
||||
return "", body
|
||||
}
|
||||
emoji, rest := leadingEmoji(body[0].Content[0].Text)
|
||||
if emoji == "" {
|
||||
return "", body
|
||||
}
|
||||
p := body[0]
|
||||
p.Content = append([]Node{}, p.Content...)
|
||||
p.Content[0].Text = rest
|
||||
if rest == "" {
|
||||
p.Content = p.Content[1:]
|
||||
}
|
||||
out := append([]Node{}, body...)
|
||||
if len(p.Content) == 0 && len(out) > 1 {
|
||||
return emoji, out[1:]
|
||||
}
|
||||
out[0] = p
|
||||
return emoji, out
|
||||
}
|
||||
|
||||
// ---- Tables ----------------------------------------------------------------
|
||||
|
||||
// cellText is a table cell's content on one line, for Markdown.
|
||||
func (w *mdWriter) cellText(cell Node) string {
|
||||
var parts []string
|
||||
for _, b := range cell.Content {
|
||||
var s string
|
||||
switch b.Type {
|
||||
case "paragraph", "heading":
|
||||
s = w.inline(b.Content)
|
||||
default:
|
||||
s = escapeMD(PlainText(b))
|
||||
}
|
||||
s = strings.TrimSpace(strings.NewReplacer("\\\n", " ", "\n", " ").Replace(s))
|
||||
if s != "" {
|
||||
parts = append(parts, s)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
// alignOf is a text block's alignment when it is not the default.
|
||||
func alignOf(n Node) string {
|
||||
switch a := n.attr("textAlign"); a {
|
||||
case "center", "right":
|
||||
return a
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var cssAlign = regexp.MustCompile(`(?i)text-align\s*:\s*(center|right)`)
|
||||
@@ -0,0 +1,153 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const phaseA = `{"type":"doc","content":[
|
||||
{"type":"heading","attrs":{"level":5,"textAlign":"center"},"content":[{"type":"text","text":"Small"}]},
|
||||
{"type":"paragraph","attrs":{"textAlign":"right"},"content":[
|
||||
{"type":"text","text":"red","marks":[{"type":"textColor","attrs":{"color":"red"}}]},
|
||||
{"type":"text","text":" and "},
|
||||
{"type":"text","text":"marked","marks":[{"type":"highlight","attrs":{"color":"green"}}]}]},
|
||||
{"type":"taskList","content":[
|
||||
{"type":"taskItem","attrs":{"checked":true},"content":[{"type":"paragraph","content":[{"type":"text","text":"done"}]}]},
|
||||
{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"todo"}]}]}]},
|
||||
{"type":"callout","attrs":{"emoji":"🔥","color":"red"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Careful"}]}]},
|
||||
{"type":"callout","attrs":{"emoji":"💡","color":"blue"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Plain"}]}]},
|
||||
{"type":"table","content":[
|
||||
{"type":"tableRow","content":[
|
||||
{"type":"tableHeader","content":[{"type":"paragraph","content":[{"type":"text","text":"Name"}]}]},
|
||||
{"type":"tableHeader","content":[{"type":"paragraph","content":[{"type":"text","text":"Role"}]}]}]},
|
||||
{"type":"tableRow","content":[
|
||||
{"type":"tableCell","content":[{"type":"paragraph","content":[{"type":"text","text":"Ada | A"}]}]},
|
||||
{"type":"tableCell","attrs":{"colspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Lead"}]},{"type":"paragraph","content":[{"type":"text","text":"and more"}]}]}]}]}
|
||||
]}`
|
||||
|
||||
func TestPhaseABlocksMarkdown(t *testing.T) {
|
||||
md := Markdown(mustParse(t, phaseA), Options{})
|
||||
for _, want := range []string{
|
||||
"##### Small\n",
|
||||
"- [x] done\n- [ ] todo\n",
|
||||
"> [!CAUTION]\n> 🔥 Careful\n",
|
||||
"> [!NOTE]\n> Plain\n",
|
||||
"| Name | Role |\n| --- | --- |\n| Ada \\| A | Lead and more |\n",
|
||||
} {
|
||||
if !strings.Contains(md, want) {
|
||||
t.Errorf("markdown lacks %q:\n%s", want, md)
|
||||
}
|
||||
}
|
||||
|
||||
// And back: the same kinds of blocks come out again.
|
||||
doc, err := FromMarkdown(md)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j := asJSON(t, doc)
|
||||
for _, want := range []string{
|
||||
`"level":5`,
|
||||
`{"type":"taskItem","attrs":{"checked":true}`,
|
||||
`{"type":"callout","attrs":{"color":"red","emoji":"🔥"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Careful"}]}]}`,
|
||||
`{"type":"callout","attrs":{"color":"blue","emoji":"💡"}`,
|
||||
`"type":"tableHeader"`,
|
||||
`"text":"Ada | A"`,
|
||||
} {
|
||||
if !strings.Contains(j, want) {
|
||||
t.Errorf("import lacks %s:\n%s", want, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhaseABlocksHTML(t *testing.T) {
|
||||
h := HTML(mustParse(t, phaseA), Options{})
|
||||
for _, want := range []string{
|
||||
`<h5 style="text-align:center">Small</h5>`,
|
||||
`<p style="text-align:right"><span data-color="red" style="color:#c0392b">red</span> and <mark data-color="green"`,
|
||||
`<li data-type="taskItem" data-checked="true"><input type="checkbox" disabled checked> <p>done</p>`,
|
||||
`<aside data-type="callout" data-emoji="🔥" data-color="red"`,
|
||||
`<tr><th><p>Name</p>`,
|
||||
} {
|
||||
if !strings.Contains(h, want) {
|
||||
t.Errorf("html lacks %q:\n%s", want, h)
|
||||
}
|
||||
}
|
||||
// Docwell's own HTML reads back as the document it came from.
|
||||
doc, err := FromHTML(h)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := Markdown(doc, Options{}), Markdown(mustParse(t, phaseA), Options{}); got != want {
|
||||
t.Errorf("html round trip:\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
j := asJSON(t, doc)
|
||||
for _, want := range []string{`"textAlign":"right"`, `{"type":"textColor","attrs":{"color":"red"}}`, `{"type":"highlight","attrs":{"color":"green"}}`} {
|
||||
if !strings.Contains(j, want) {
|
||||
t.Errorf("html import lacks %s:\n%s", want, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotionCalloutsAndTodos(t *testing.T) {
|
||||
md := notionAsides("Intro\n\n<aside>\n⚠️ Mind the gap\n\n</aside>\n\nAfter\n")
|
||||
doc, err := FromMarkdown(md)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if j := asJSON(t, doc); !strings.Contains(j, `{"type":"callout","attrs":{"color":"blue","emoji":"⚠️"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Mind the gap"}]}]}`) {
|
||||
t.Errorf("aside = %s", j)
|
||||
}
|
||||
|
||||
doc, err = FromHTML(`<figure class="callout"><div style="font-size:1.5em"><span class="icon">📌</span></div><div style="width:100%"><p>Pinned</p></div></figure>` +
|
||||
`<ul class="to-do-list"><li><div class="checkbox checkbox-on"></div> <span class="to-do-children-checked">Bought milk</span></li>` +
|
||||
`<li><div class="checkbox checkbox-off"></div> <span>Eggs</span></li></ul>`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j := asJSON(t, doc)
|
||||
for _, want := range []string{
|
||||
`{"type":"callout","attrs":{"color":"blue","emoji":"📌"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pinned"}]}]}`,
|
||||
`{"type":"taskItem","attrs":{"checked":true},"content":[{"type":"paragraph","content":[{"type":"text","text":"Bought milk"}]}]}`,
|
||||
`{"type":"taskItem","attrs":{"checked":false}`,
|
||||
} {
|
||||
if !strings.Contains(j, want) {
|
||||
t.Errorf("notion html lacks %s:\n%s", want, j)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLeadingEmoji(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"💡 idea": "💡",
|
||||
"⚠️ careful": "⚠️",
|
||||
"👩💻 dev": "👩💻",
|
||||
"🇵🇱 flag": "🇵🇱",
|
||||
"plain": "",
|
||||
"💡nospace": "",
|
||||
} {
|
||||
if got, _ := leadingEmoji(in); got != want {
|
||||
t.Errorf("leadingEmoji(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPhaseABlocksPDF(t *testing.T) {
|
||||
out, err := PDF("Blocks", mustParse(t, phaseA), PDFOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.HasPrefix(out, []byte("%PDF-")) {
|
||||
t.Fatal("not a PDF")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNearestPalette(t *testing.T) {
|
||||
for in, want := range map[string]string{"FF0000": "red", "0070C0": "blue", "000000": "", "auto": "", "FFFFFF": "", "00B050": "green"} {
|
||||
if got := nearestPalette(in); got != want {
|
||||
t.Errorf("nearestPalette(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,7 @@ func TestFromHTMLSanitizes(t *testing.T) {
|
||||
if title != "Hi" {
|
||||
t.Errorf("title = %q", title)
|
||||
}
|
||||
if md := Markdown(rest, Options{}); !strings.Contains(md, "[ok](https://ok.test)") || !strings.Contains(md, "a · **b**") || !strings.Contains(md, "### deep") {
|
||||
if md := Markdown(rest, Options{}); !strings.Contains(md, "[ok](https://ok.test)") || !strings.Contains(md, "| a | **b** |\n| --- | --- |") || !strings.Contains(md, "##### deep") {
|
||||
t.Errorf("content = %s", md)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -197,9 +197,10 @@ func (n *xnode) find(name string) *xnode {
|
||||
// maxDocxPart caps one unpacked part of a Word file (the document XML, one image).
|
||||
const maxDocxPart = 50 << 20
|
||||
|
||||
// FromDOCX reads a Word document. Headings, lists, quotes, code, bold,
|
||||
// italic, underline, strikethrough, links and images are kept; tables become
|
||||
// one paragraph per row, as in HTML import. Images come back as assets.
|
||||
// FromDOCX reads a Word document. Headings, lists, quotes, code, tables,
|
||||
// alignment, bold, italic, underline, strikethrough, text colours and
|
||||
// highlights (as the nearest palette colour), links and images are kept.
|
||||
// Images come back as assets.
|
||||
func FromDOCX(data []byte) (Node, []Asset, error) {
|
||||
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
@@ -358,6 +359,7 @@ var headingStyle = regexp.MustCompile(`^heading\s*([1-9])$`)
|
||||
type para struct {
|
||||
kind string // paragraph, heading, quote, code, list
|
||||
level int // heading level, or list depth
|
||||
align string // "center" or "right", or "" for the default
|
||||
ordered bool
|
||||
inline []Node
|
||||
text string // code paragraphs keep their plain text
|
||||
@@ -402,7 +404,7 @@ func (d *docxReader) blocks(nodes []*xnode) []Node {
|
||||
code = append(code, p.text)
|
||||
case "heading":
|
||||
if inl := trimInline(p.inline); len(inl) > 0 {
|
||||
out = append(out, Node{Type: "heading", Attrs: map[string]any{"level": float64(min(p.level, 3))}, Content: inl})
|
||||
out = append(out, withAlign(Node{Type: "heading", Attrs: map[string]any{"level": float64(min(p.level, 6))}, Content: inl}, p.align))
|
||||
}
|
||||
case "quote":
|
||||
if inl := trimInline(p.inline); len(inl) > 0 {
|
||||
@@ -415,7 +417,7 @@ func (d *docxReader) blocks(nodes []*xnode) []Node {
|
||||
}
|
||||
default:
|
||||
if inl := trimInline(p.inline); len(inl) > 0 {
|
||||
out = append(out, Node{Type: "paragraph", Content: inl})
|
||||
out = append(out, withAlign(Node{Type: "paragraph", Content: inl}, p.align))
|
||||
}
|
||||
}
|
||||
out = append(out, p.blocks...)
|
||||
@@ -441,56 +443,50 @@ func (n *xnode) kidsOrNil() []*xnode {
|
||||
return n.kids
|
||||
}
|
||||
|
||||
// withAlign sets a text block's alignment when it has one.
|
||||
func withAlign(n Node, align string) Node {
|
||||
if align != "" {
|
||||
n.Attrs = cloneAttrs(n.Attrs)
|
||||
n.Attrs["textAlign"] = align
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// table reads a Word table. Rows marked to repeat as a header become header
|
||||
// cells; cells spanning columns keep their span.
|
||||
func (d *docxReader) table(t *xnode) []Node {
|
||||
var out []Node
|
||||
tbl := Node{Type: "table"}
|
||||
for _, tr := range t.kids {
|
||||
if tr.name != "tr" {
|
||||
continue
|
||||
}
|
||||
var cells []Node
|
||||
kind := "tableCell"
|
||||
if tr.child("trPr").on("tblHeader") {
|
||||
kind = "tableHeader"
|
||||
}
|
||||
row := Node{Type: "tableRow"}
|
||||
for _, tc := range tr.kids {
|
||||
if tc.name != "tc" {
|
||||
continue
|
||||
}
|
||||
var cell []Node
|
||||
for _, b := range d.blocks(tc.kids) {
|
||||
if len(cell) > 0 {
|
||||
cell = append(cell, Node{Type: "text", Text: " "})
|
||||
}
|
||||
if b.Type == "image" {
|
||||
out = append(out, b)
|
||||
continue
|
||||
}
|
||||
cell = append(cell, inlineOf(b)...)
|
||||
attrs := map[string]any{"colspan": float64(1), "rowspan": float64(1), "colwidth": nil}
|
||||
if span, err := strconv.Atoi(tc.child("tcPr").val("gridSpan")); err == nil && span > 1 && span < 1000 {
|
||||
attrs["colspan"] = float64(span)
|
||||
}
|
||||
if len(cells) > 0 {
|
||||
cells = append(cells, Node{Type: "text", Text: " · "})
|
||||
content := d.blocks(tc.kids)
|
||||
if len(content) == 0 {
|
||||
content = []Node{{Type: "paragraph"}}
|
||||
}
|
||||
cells = append(cells, cell...)
|
||||
row.Content = append(row.Content, Node{Type: kind, Attrs: attrs, Content: content})
|
||||
}
|
||||
if c := trimInline(cells); len(c) > 0 {
|
||||
out = append(out, Node{Type: "paragraph", Content: c})
|
||||
if len(row.Content) > 0 {
|
||||
tbl.Content = append(tbl.Content, row)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// inlineOf flattens a block to its inline content.
|
||||
func inlineOf(b Node) []Node {
|
||||
switch b.Type {
|
||||
case "paragraph", "heading":
|
||||
return b.Content
|
||||
case "text", "hardBreak":
|
||||
return []Node{b}
|
||||
if len(tbl.Content) == 0 {
|
||||
return nil
|
||||
}
|
||||
var out []Node
|
||||
for _, c := range b.Content {
|
||||
if len(out) > 0 && (c.Type == "paragraph" || c.Type == "listItem") {
|
||||
out = append(out, Node{Type: "text", Text: " "})
|
||||
}
|
||||
out = append(out, inlineOf(c)...)
|
||||
}
|
||||
return out
|
||||
return []Node{tbl}
|
||||
}
|
||||
|
||||
func (d *docxReader) paragraph(p *xnode) para {
|
||||
@@ -500,6 +496,12 @@ func (d *docxReader) paragraph(p *xnode) para {
|
||||
if v, err := strconv.Atoi(ppr.val("outlineLvl")); err == nil && v < 9 {
|
||||
outline = v + 1
|
||||
}
|
||||
switch ppr.val("jc") {
|
||||
case "center":
|
||||
out.align = "center"
|
||||
case "right", "end":
|
||||
out.align = "right"
|
||||
}
|
||||
switch {
|
||||
case name == "title":
|
||||
out.kind, out.level = "heading", 1
|
||||
@@ -619,6 +621,23 @@ func (r *runReader) children(nodes []*xnode, marks []Mark) {
|
||||
}
|
||||
}
|
||||
|
||||
// wordHighlight maps Word's highlight colours to the palette.
|
||||
var wordHighlight = map[string]string{
|
||||
"yellow": "yellow", "darkYellow": "yellow", "green": "green", "darkGreen": "green", "cyan": "teal",
|
||||
"darkCyan": "teal", "blue": "blue", "darkBlue": "blue", "magenta": "pink", "darkMagenta": "purple",
|
||||
"red": "red", "darkRed": "red", "lightGray": "gray", "darkGray": "gray",
|
||||
}
|
||||
|
||||
// withMark adds m unless a mark of its type is there already.
|
||||
func withMark(marks []Mark, m Mark) []Mark {
|
||||
for _, have := range marks {
|
||||
if have.Type == m.Type {
|
||||
return marks
|
||||
}
|
||||
}
|
||||
return append(append([]Mark(nil), marks...), m)
|
||||
}
|
||||
|
||||
func withLink(marks []Mark, href string) []Mark {
|
||||
return append(append([]Mark(nil), marks...), Mark{Type: "link", Attrs: map[string]any{
|
||||
"href": href, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
|
||||
@@ -654,6 +673,12 @@ func (r *runReader) run(n *xnode, marks []Mark) {
|
||||
if s := strings.ToLower(rpr.val("rStyle")); strings.Contains(s, "code") {
|
||||
add("code")
|
||||
}
|
||||
if c := nearestPalette(rpr.val("color")); c != "" {
|
||||
marks = withMark(marks, Mark{Type: "textColor", Attrs: map[string]any{"color": c}})
|
||||
}
|
||||
if c, ok := wordHighlight[rpr.val("highlight")]; ok {
|
||||
marks = withMark(marks, Mark{Type: "highlight", Attrs: map[string]any{"color": c}})
|
||||
}
|
||||
}
|
||||
if r.link != "" {
|
||||
marks = withLink(marks, r.link)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"html"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
@@ -59,7 +60,7 @@ func HTMLPage(title string, doc Node, o Options) string {
|
||||
}
|
||||
|
||||
var htmlBlock = map[string]string{
|
||||
"paragraph": "p", "blockquote": "blockquote", "bulletList": "ul", "orderedList": "ol", "listItem": "li",
|
||||
"blockquote": "blockquote", "bulletList": "ul", "orderedList": "ol", "listItem": "li",
|
||||
}
|
||||
|
||||
func writeHTML(b *strings.Builder, n Node, o Options) {
|
||||
@@ -73,9 +74,55 @@ func writeHTML(b *strings.Builder, n Node, o Options) {
|
||||
writeHTMLText(b, n, o)
|
||||
case "heading":
|
||||
level := min(max(n.intAttr("level", 1), 1), 6)
|
||||
fmt.Fprintf(b, "<h%d>", level)
|
||||
fmt.Fprintf(b, "<h%d%s>", level, htmlAlign(n))
|
||||
children()
|
||||
fmt.Fprintf(b, "</h%d>\n", level)
|
||||
case "paragraph":
|
||||
fmt.Fprintf(b, "<p%s>", htmlAlign(n))
|
||||
children()
|
||||
b.WriteString("</p>\n")
|
||||
case "taskList":
|
||||
b.WriteString("<ul data-type=\"taskList\">\n")
|
||||
children()
|
||||
b.WriteString("</ul>\n")
|
||||
case "taskItem":
|
||||
checked := n.Attrs["checked"] == true
|
||||
box := ""
|
||||
if checked {
|
||||
box = " checked"
|
||||
}
|
||||
fmt.Fprintf(b, "<li data-type=\"taskItem\" data-checked=\"%t\"><input type=\"checkbox\" disabled%s> ", checked, box)
|
||||
children()
|
||||
b.WriteString("</li>\n")
|
||||
case "callout":
|
||||
emoji, color := calloutParts(n)
|
||||
fmt.Fprintf(b, "<aside data-type=\"callout\" data-emoji=\"%s\" data-color=\"%s\" style=\"background:%s\">"+
|
||||
"<span class=\"callout-emoji\">%s</span><div class=\"callout-body\">\n",
|
||||
html.EscapeString(emoji), color, paletteBackground[color], html.EscapeString(emoji))
|
||||
children()
|
||||
b.WriteString("</div></aside>\n")
|
||||
case "table":
|
||||
b.WriteString("<table>\n<tbody>\n")
|
||||
children()
|
||||
b.WriteString("</tbody>\n</table>\n")
|
||||
case "tableRow":
|
||||
b.WriteString("<tr>")
|
||||
children()
|
||||
b.WriteString("</tr>\n")
|
||||
case "tableCell", "tableHeader":
|
||||
tag := "td"
|
||||
if n.Type == "tableHeader" {
|
||||
tag = "th"
|
||||
}
|
||||
b.WriteString("<" + tag)
|
||||
for _, span := range []string{"colspan", "rowspan"} {
|
||||
if v := n.intAttr(span, 1); v > 1 {
|
||||
fmt.Fprintf(b, " %s=\"%d\"", span, v)
|
||||
}
|
||||
}
|
||||
b.WriteString(">")
|
||||
children()
|
||||
b.WriteString("</" + tag + ">")
|
||||
case "orderedList":
|
||||
if start := n.intAttr("start", 1); start != 1 {
|
||||
fmt.Fprintf(b, "<ol start=\"%d\">\n", start)
|
||||
@@ -163,6 +210,14 @@ func writeHTML(b *strings.Builder, n Node, o Options) {
|
||||
}
|
||||
}
|
||||
|
||||
// htmlAlign is the style attribute of an aligned paragraph or heading.
|
||||
func htmlAlign(n Node) string {
|
||||
if a := alignOf(n); a != "" {
|
||||
return " style=\"text-align:" + a + "\""
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func writeHTMLText(b *strings.Builder, n Node, o Options) {
|
||||
var open, close []string
|
||||
for _, m := range n.Marks {
|
||||
@@ -177,6 +232,18 @@ func writeHTMLText(b *strings.Builder, n Node, o Options) {
|
||||
open, close = append(open, "<u>"), append([]string{"</u>"}, close...)
|
||||
case "code":
|
||||
open, close = append(open, "<code>"), append([]string{"</code>"}, close...)
|
||||
case "textColor":
|
||||
if c := m.attr("color"); isPaletteColor(c) {
|
||||
open = append(open, "<span data-color=\""+c+"\" style=\"color:"+paletteText[c]+"\">")
|
||||
close = append([]string{"</span>"}, close...)
|
||||
}
|
||||
case "highlight":
|
||||
c := m.attr("color")
|
||||
if !isPaletteColor(c) {
|
||||
c = "yellow"
|
||||
}
|
||||
open = append(open, "<mark data-color=\""+c+"\" style=\"background:"+paletteBackground[c]+"\">")
|
||||
close = append([]string{"</mark>"}, close...)
|
||||
case "link":
|
||||
if href := o.file(m.attr("href")); safeURL.MatchString(href) {
|
||||
open, close = append(open, "<a href=\""+html.EscapeString(href)+"\">"), append([]string{"</a>"}, close...)
|
||||
@@ -255,6 +322,36 @@ func (w *mdWriter) block(n Node, first, rest string) {
|
||||
}
|
||||
w.blocks(item.Content, p+"- ", rest+" ")
|
||||
}
|
||||
case "taskList":
|
||||
// GitHub's task lists, which FromMarkdown reads back.
|
||||
for i, item := range n.Content {
|
||||
p := rest
|
||||
if i == 0 {
|
||||
p = first
|
||||
}
|
||||
box := "[ ] "
|
||||
if item.Attrs["checked"] == true {
|
||||
box = "[x] "
|
||||
}
|
||||
if len(item.Content) == 0 || item.Content[0].Type != "paragraph" {
|
||||
item.Content = append([]Node{{Type: "paragraph"}}, item.Content...)
|
||||
}
|
||||
w.blocks(item.Content, p+"- "+box, rest+" ")
|
||||
}
|
||||
case "callout":
|
||||
// A GitHub alert; the emoji goes first in the text unless it is the alert's own.
|
||||
emoji, color := calloutParts(n)
|
||||
a := alertFor(color)
|
||||
body := n.Content
|
||||
if emoji != a.emoji && len(body) > 0 && body[0].Type == "paragraph" {
|
||||
p := body[0]
|
||||
p.Content = append([]Node{{Type: "text", Text: emoji + " "}}, p.Content...)
|
||||
body = append([]Node{p}, body[1:]...)
|
||||
}
|
||||
w.lines("[!"+a.name+"]", first+"> ", rest+"> ")
|
||||
w.blocks(body, rest+"> ", rest+"> ")
|
||||
case "table":
|
||||
w.table(n, first, rest)
|
||||
case "orderedList":
|
||||
start := n.intAttr("start", 1)
|
||||
for i, item := range n.Content {
|
||||
@@ -331,6 +428,38 @@ func (w *mdWriter) block(n Node, first, rest string) {
|
||||
}
|
||||
}
|
||||
|
||||
// table writes a GitHub table. Its first row is the header, as Markdown
|
||||
// tables need one; cells keep their text on one line.
|
||||
func (w *mdWriter) table(n Node, first, rest string) {
|
||||
cols := 0
|
||||
for _, row := range n.Content {
|
||||
cols = max(cols, len(row.Content))
|
||||
}
|
||||
if cols == 0 {
|
||||
return
|
||||
}
|
||||
line := func(cells []string) string {
|
||||
for len(cells) < cols {
|
||||
cells = append(cells, "")
|
||||
}
|
||||
return "| " + strings.Join(cells, " | ") + " |"
|
||||
}
|
||||
for i, row := range n.Content {
|
||||
var cells []string
|
||||
for _, c := range row.Content {
|
||||
cells = append(cells, w.cellText(c))
|
||||
}
|
||||
p := rest
|
||||
if i == 0 {
|
||||
p = first
|
||||
}
|
||||
w.lines(line(cells), p, rest)
|
||||
if i == 0 {
|
||||
w.lines(line(slices.Repeat([]string{"---"}, cols)), rest, rest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (w *mdWriter) inline(nodes []Node) string {
|
||||
var b strings.Builder
|
||||
for _, n := range nodes {
|
||||
|
||||
@@ -22,14 +22,15 @@ type ImportOptions struct {
|
||||
Resolve func(url string) (out string, ok bool)
|
||||
}
|
||||
|
||||
// FromMarkdown reads CommonMark (with GitHub's strikethrough, autolinks and
|
||||
// task lists, the latter as plain lists). Raw HTML in the Markdown is dropped.
|
||||
// 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))
|
||||
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
|
||||
}
|
||||
@@ -161,7 +162,61 @@ func (r *reader) blocks(n *html.Node) []Node {
|
||||
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 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 <input type=checkbox>
|
||||
// (Markdown task lists, Docwell's HTML) or Notion's <div class="checkbox">,
|
||||
// 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})`)
|
||||
|
||||
@@ -170,11 +225,40 @@ func (r *reader) block(n *html.Node) []Node {
|
||||
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
|
||||
// <p> in Markdown output) are lifted out next to it.
|
||||
return r.blocks(n)
|
||||
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 []Node{h}
|
||||
return aligned(n, []Node{h})
|
||||
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: <figure class="callout"><div><span class="icon">💡</span></div><div>text</div></figure>
|
||||
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 {
|
||||
@@ -185,11 +269,26 @@ func (r *reader) block(n *html.Node) []Node {
|
||||
}
|
||||
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
|
||||
}
|
||||
list.Content = append(list.Content, r.listItem(c))
|
||||
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
|
||||
@@ -199,6 +298,9 @@ func (r *reader) block(n *html.Node) []Node {
|
||||
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"}}
|
||||
}
|
||||
@@ -240,26 +342,92 @@ func (r *reader) block(n *html.Node) []Node {
|
||||
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)
|
||||
}
|
||||
|
||||
// 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" {
|
||||
@@ -314,6 +482,20 @@ func (r *reader) inline(n *html.Node, marks []mark) []Node {
|
||||
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{
|
||||
|
||||
@@ -117,7 +117,7 @@ func ReadNotion(data []byte) ([]NotionPage, []Asset, error) {
|
||||
var doc Node
|
||||
switch strings.ToLower(path.Ext(s.file)) {
|
||||
case ".md":
|
||||
doc, err = FromMarkdownWith(string(bytes.TrimPrefix(data, []byte(utf8BOM))), opts)
|
||||
doc, err = FromMarkdownWith(notionAsides(string(bytes.TrimPrefix(data, []byte(utf8BOM)))), opts)
|
||||
case ".csv":
|
||||
doc, err = notionTable(data)
|
||||
default:
|
||||
@@ -254,8 +254,7 @@ func (n *notionReader) resolve(dir, raw string) (string, bool) {
|
||||
return ref, true
|
||||
}
|
||||
|
||||
// notionTable turns a database's CSV into paragraphs, one per row, with the
|
||||
// column names in bold first.
|
||||
// notionTable turns a database's CSV into a table, its first row the header.
|
||||
func notionTable(data []byte) (Node, error) {
|
||||
r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(data, []byte(utf8BOM))))
|
||||
r.FieldsPerRecord = -1
|
||||
@@ -264,28 +263,53 @@ func notionTable(data []byte) (Node, error) {
|
||||
if err != nil {
|
||||
return Node{}, err
|
||||
}
|
||||
doc := Node{Type: "doc"}
|
||||
for i, row := range rows {
|
||||
var cells []Node
|
||||
for _, cell := range row {
|
||||
if cell = strings.TrimSpace(cell); cell == "" {
|
||||
cell = "–"
|
||||
}
|
||||
if len(cells) > 0 {
|
||||
cells = append(cells, Node{Type: "text", Text: " · "})
|
||||
}
|
||||
t := Node{Type: "text", Text: cell}
|
||||
if i == 0 {
|
||||
t.Marks = []Mark{{Type: "bold"}}
|
||||
}
|
||||
cells = append(cells, t)
|
||||
}
|
||||
if c := trimInline(cells); len(c) > 0 {
|
||||
doc.Content = append(doc.Content, Node{Type: "paragraph", Content: c})
|
||||
}
|
||||
cols := 0
|
||||
for _, row := range rows {
|
||||
cols = max(cols, len(row))
|
||||
}
|
||||
doc := Node{Type: "doc"}
|
||||
if cols == 0 {
|
||||
return doc, nil
|
||||
}
|
||||
table := Node{Type: "table"}
|
||||
for i, row := range rows {
|
||||
tr := Node{Type: "tableRow"}
|
||||
for c := range cols {
|
||||
kind := "tableCell"
|
||||
if i == 0 {
|
||||
kind = "tableHeader"
|
||||
}
|
||||
p := Node{Type: "paragraph"}
|
||||
if c < len(row) {
|
||||
if cell := strings.TrimSpace(row[c]); cell != "" {
|
||||
p.Content = []Node{{Type: "text", Text: cell}}
|
||||
}
|
||||
}
|
||||
attrs := map[string]any{"colspan": float64(1), "rowspan": float64(1), "colwidth": nil}
|
||||
tr.Content = append(tr.Content, Node{Type: kind, Attrs: attrs, Content: []Node{p}})
|
||||
}
|
||||
table.Content = append(table.Content, tr)
|
||||
}
|
||||
doc.Content = []Node{table}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
// notionAside finds the <aside> blocks Notion writes callouts as in its
|
||||
// Markdown export. Markdown readers drop raw HTML, text and all.
|
||||
var notionAside = regexp.MustCompile(`(?ms)^[ \t]*<aside>[ \t]*\n(.*?)\n?[ \t]*</aside>[ \t]*$`)
|
||||
|
||||
// notionAsides rewrites Notion's callouts as GitHub alerts, which import
|
||||
// reads as callouts (with the emoji Notion puts first in the text).
|
||||
func notionAsides(md string) string {
|
||||
return notionAside.ReplaceAllStringFunc(md, func(block string) string {
|
||||
body := strings.TrimSpace(notionAside.FindStringSubmatch(block)[1])
|
||||
lines := []string{"> [!NOTE]"}
|
||||
for _, l := range strings.Split(body, "\n") {
|
||||
lines = append(lines, strings.TrimRight("> "+l, " "))
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
})
|
||||
}
|
||||
|
||||
// utf8BOM starts some exported text files.
|
||||
const utf8BOM = "\xef\xbb\xbf"
|
||||
+137
-11
@@ -89,12 +89,14 @@ func PDF(title string, doc Node, o PDFOptions) (out []byte, err error) {
|
||||
|
||||
// Layout, in millimetres and points.
|
||||
const (
|
||||
pdfMargin = 20.0
|
||||
pdfGap = 3.0 // after a block
|
||||
pdfTightGap = 1.2 // after a block in a list item
|
||||
pdfBody = 11.0
|
||||
pdfLine = 5.6
|
||||
pdfIndent = 6.0
|
||||
pdfMargin = 20.0
|
||||
pdfGap = 3.0 // after a block
|
||||
pdfTightGap = 1.2 // after a block in a list item
|
||||
pdfBody = 11.0
|
||||
pdfLine = 5.6
|
||||
pdfIndent = 6.0
|
||||
pdfTaskIndent = 8.0
|
||||
pdfCellPad = 1.6
|
||||
)
|
||||
|
||||
type pdfWriter struct {
|
||||
@@ -155,18 +157,80 @@ func (w *pdfWriter) heading(text string, level int, size float64) {
|
||||
w.f.Ln(pdfGap)
|
||||
}
|
||||
|
||||
var pdfHeadingSize = map[int]float64{1: 18, 2: 15, 3: 13}
|
||||
var pdfHeadingSize = map[int]float64{1: 18, 2: 15, 3: 13, 4: 12, 5: 11, 6: 10}
|
||||
|
||||
func (w *pdfWriter) block(n Node, indent, gap float64) {
|
||||
switch n.Type {
|
||||
case "paragraph":
|
||||
w.at(indent)
|
||||
w.inline(n.Content, "", pdfBody)
|
||||
w.f.Ln(pdfLine)
|
||||
if a := alignOf(n); a != "" {
|
||||
// fpdf aligns whole cells only, so aligned text loses its inline formatting.
|
||||
w.f.SetFont("go", "", pdfBody)
|
||||
w.ink()
|
||||
w.f.MultiCell(w.width-indent, pdfLine, pdfText(PlainText(n)), "", strings.ToUpper(a[:1]), false)
|
||||
} else {
|
||||
w.inline(n.Content, "", pdfBody)
|
||||
w.f.Ln(pdfLine)
|
||||
}
|
||||
w.f.Ln(gap)
|
||||
case "heading":
|
||||
level := min(max(n.intAttr("level", 1), 1), 3)
|
||||
level := min(max(n.intAttr("level", 1), 1), 6)
|
||||
w.heading(PlainText(n), level, pdfHeadingSize[level])
|
||||
case "taskList":
|
||||
for i, item := range n.Content {
|
||||
marker := "[ ]"
|
||||
if item.Attrs["checked"] == true {
|
||||
marker = "[x]"
|
||||
}
|
||||
w.room(pdfLine)
|
||||
w.at(indent)
|
||||
w.f.SetFont("mono", "", pdfBody-1)
|
||||
w.ink()
|
||||
w.f.CellFormat(pdfTaskIndent, pdfLine, marker, "", 0, "L", false, 0, "")
|
||||
for j, c := range item.Content {
|
||||
g := pdfTightGap
|
||||
if j == len(item.Content)-1 && i == len(n.Content)-1 {
|
||||
g = gap
|
||||
}
|
||||
if j == 0 && c.Type == "paragraph" {
|
||||
w.f.SetLeftMargin(pdfMargin + indent + pdfTaskIndent)
|
||||
w.inline(c.Content, "", pdfBody)
|
||||
w.f.Ln(pdfLine)
|
||||
w.f.Ln(g)
|
||||
continue
|
||||
}
|
||||
if j == 0 {
|
||||
w.f.Ln(pdfLine)
|
||||
}
|
||||
w.block(c, indent+pdfTaskIndent, g)
|
||||
}
|
||||
if len(item.Content) == 0 {
|
||||
w.f.Ln(pdfLine)
|
||||
}
|
||||
}
|
||||
case "callout":
|
||||
// A quote-like bar in the callout's colour; the Go fonts have no emoji.
|
||||
_, color := calloutParts(n)
|
||||
page, top := w.f.PageNo(), w.f.GetY()
|
||||
for i, c := range n.Content {
|
||||
g := pdfTightGap
|
||||
if i == len(n.Content)-1 {
|
||||
g = 0
|
||||
}
|
||||
w.block(c, indent+pdfIndent, g)
|
||||
}
|
||||
if w.f.PageNo() != page {
|
||||
top = pdfMargin
|
||||
}
|
||||
r, g, b := rgb(paletteText[color])
|
||||
w.f.SetDrawColor(r, g, b)
|
||||
w.f.SetLineWidth(1.2)
|
||||
x := pdfMargin + indent + 1.5
|
||||
w.f.Line(x, top, x, w.f.GetY())
|
||||
w.f.Ln(gap)
|
||||
case "table":
|
||||
w.table(n, indent)
|
||||
w.f.Ln(gap)
|
||||
case "bulletList", "orderedList":
|
||||
start := n.intAttr("start", 1)
|
||||
for i, item := range n.Content {
|
||||
@@ -287,9 +351,11 @@ func (w *pdfWriter) inline(nodes []Node, style string, size float64) {
|
||||
for _, n := range nodes {
|
||||
switch n.Type {
|
||||
case "text":
|
||||
family, st, href := "go", style, ""
|
||||
family, st, href, color := "go", style, "", ""
|
||||
for _, m := range n.Marks {
|
||||
switch m.Type {
|
||||
case "textColor":
|
||||
color = paletteText[m.attr("color")]
|
||||
case "bold":
|
||||
st += "B"
|
||||
case "italic":
|
||||
@@ -317,6 +383,9 @@ func (w *pdfWriter) inline(nodes []Node, style string, size float64) {
|
||||
w.f.WriteLinkString(pdfLine, pdfText(n.Text), href)
|
||||
} else {
|
||||
w.ink()
|
||||
if color != "" {
|
||||
w.f.SetTextColor(rgb(color))
|
||||
}
|
||||
w.f.Write(pdfLine, pdfText(n.Text))
|
||||
}
|
||||
case "hardBreak":
|
||||
@@ -361,6 +430,63 @@ func pdfStyle(s string) string {
|
||||
return out
|
||||
}
|
||||
|
||||
// table draws a grid with each cell's text wrapped in its column; columns
|
||||
// share the width evenly, and header cells are bold on a grey fill. A row
|
||||
// that does not fit on the page starts a new one.
|
||||
func (w *pdfWriter) table(n Node, indent float64) {
|
||||
cols := 0
|
||||
for _, row := range n.Content {
|
||||
cols = max(cols, len(row.Content))
|
||||
}
|
||||
if cols == 0 {
|
||||
return
|
||||
}
|
||||
colW := (w.width - indent) / float64(cols)
|
||||
const lineH = 4.8
|
||||
for _, row := range n.Content {
|
||||
texts := make([][]string, cols)
|
||||
lines := 1
|
||||
for i, cell := range row.Content {
|
||||
var parts []string
|
||||
for _, b := range cell.Content {
|
||||
if t := strings.TrimSpace(PlainText(b)); t != "" {
|
||||
parts = append(parts, t)
|
||||
}
|
||||
}
|
||||
style := ""
|
||||
if cell.Type == "tableHeader" {
|
||||
style = "B"
|
||||
}
|
||||
w.f.SetFont("go", style, pdfBody-1)
|
||||
texts[i] = w.f.SplitText(pdfText(strings.Join(parts, "\n")), colW-2*pdfCellPad)
|
||||
lines = max(lines, len(texts[i]))
|
||||
}
|
||||
h := float64(lines)*lineH + 2*pdfCellPad
|
||||
w.room(h)
|
||||
y := w.f.GetY()
|
||||
for i := range cols {
|
||||
x := pdfMargin + indent + float64(i)*colW
|
||||
header := i < len(row.Content) && row.Content[i].Type == "tableHeader"
|
||||
w.f.SetDrawColor(200, 200, 200)
|
||||
w.f.SetLineWidth(0.2)
|
||||
if header {
|
||||
w.f.SetFillColor(244, 244, 241)
|
||||
w.f.Rect(x, y, colW, h, "FD")
|
||||
w.f.SetFont("go", "B", pdfBody-1)
|
||||
} else {
|
||||
w.f.Rect(x, y, colW, h, "D")
|
||||
w.f.SetFont("go", "", pdfBody-1)
|
||||
}
|
||||
w.ink()
|
||||
for j, line := range texts[i] {
|
||||
w.f.SetXY(x+pdfCellPad, y+pdfCellPad+float64(j)*lineH)
|
||||
w.f.CellFormat(colW-2*pdfCellPad, lineH, line, "", 0, "L", false, 0, "")
|
||||
}
|
||||
}
|
||||
w.f.SetXY(pdfMargin+indent, y+h)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *pdfWriter) code(text string, indent float64, label string) {
|
||||
w.at(indent)
|
||||
if label != "" {
|
||||
|
||||
@@ -117,7 +117,7 @@ func TestFromDOCX(t *testing.T) {
|
||||
"> Said someone",
|
||||
"```\nx := 1\ny := 2\n```",
|
||||
"",
|
||||
"Name · Role\n\nAda · Lead",
|
||||
"| Name | Role |\n| --- | --- |\n| Ada | Lead |",
|
||||
"Zażółć gęślą jaźń",
|
||||
} {
|
||||
if !strings.Contains(md, want) {
|
||||
@@ -183,7 +183,7 @@ func TestReadNotion(t *testing.T) {
|
||||
if j := asJSON(t, pages[child].Doc); !strings.Contains(j, `"href":"`+PageRef(root)+`"`) {
|
||||
t.Errorf("child = %s", j)
|
||||
}
|
||||
if md := Markdown(pages[db].Doc, Options{}); !strings.Contains(md, "**Name** · **Status**\n\nShip it · Done") {
|
||||
if md := Markdown(pages[db].Doc, Options{}); !strings.Contains(md, "| Name | Status |\n| --- | --- |\n| Ship it | Done |") {
|
||||
t.Errorf("database = %s", md)
|
||||
}
|
||||
if md := Markdown(pages[row].Doc, Options{}); !strings.Contains(md, "Row body\n\n") {
|
||||
|
||||
Reference in new issue
Block a user