Add Word export, column dragging and the rest of editor parity
CI / go (Server) (push) Failing after 8m51s
CI / go (Web-App) (push) Successful in 11m46s
CI / mobile (push) Failing after 3m44s
CI / docker (push) Successful in 54m15s
Docs / build (push) Successful in 12m28s
Docs / deploy (push) Skipped
CI / frontend (push) Failing after 7m47s
CI / desktop (ubuntu-latest) (push) Successful in 1h27m22s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s

Word export: pages download as .docx from the page menu and from
GET /pages/{id}/export?format=docx. The file keeps headings, alignment,
lists, to-dos, quotes, callouts, code, tables with a repeating header
row, text formatting, colours, highlights, links and the page's images.
Word import now reads callouts, to-dos and shaded highlights, so a page
exported to Word imports back as it was. The user guide says how to move
pages to Notion, whose Import reads Word and Markdown files.

Editor:
- Columns move like rows: a grip on the column's top edge drags it, and
  the table toolbar and Ctrl+Alt+Left/Right move it from the keyboard.
  Row and column moving share tablemove.ts.
- Ctrl+Shift+C copies a link to the block the cursor is in.
- Headings 4 to 6 sit under "Other headings" in the slash menu; a search
  still finds them directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-14 13:01:06 +01:00
1 parent d28f1e02db
commit 3dea2bb2f4
28 files changed
+1630 -432

No files matched your search

+3
View File
@@ -503,6 +503,7 @@ func (e CreateApiTokenJSONBodyScope) Valid() bool {
// Defines values for ExportPageParamsFormat.
const (
ExportPageParamsFormatDocx ExportPageParamsFormat = "docx"
ExportPageParamsFormatHtml ExportPageParamsFormat = "html"
ExportPageParamsFormatMarkdown ExportPageParamsFormat = "markdown"
ExportPageParamsFormatPdf ExportPageParamsFormat = "pdf"
@@ -511,6 +512,8 @@ const (
// Valid indicates whether the value is a known member of the ExportPageParamsFormat enum.
func (e ExportPageParamsFormat) Valid() bool {
switch e {
case ExportPageParamsFormatDocx:
return true
case ExportPageParamsFormatHtml:
return true
case ExportPageParamsFormatMarkdown:
+94
View File
@@ -3,7 +3,11 @@
package convert
import (
"archive/zip"
"bytes"
"encoding/xml"
"errors"
"io"
"strings"
"testing"
)
@@ -151,3 +155,93 @@ func TestNearestPalette(t *testing.T) {
}
}
}
func TestDOCXRoundTrip(t *testing.T) {
src := mustParse(t, phaseA)
data, err := DOCX("Blocks", src, DOCXOptions{})
if err != nil {
t.Fatal(err)
}
doc, _, err := FromDOCX(data)
if err != nil {
t.Fatal(err)
}
title, body := Title(doc)
if title != "Blocks" {
t.Errorf("title = %q", title)
}
if got, want := Markdown(body, Options{}), Markdown(src, Options{}); got != want {
t.Errorf("word round trip:\n%s\nwant\n%s", got, want)
}
j := asJSON(t, body)
for _, want := range []string{
`"textAlign":"right"`, `"textAlign":"center"`,
`{"type":"textColor","attrs":{"color":"red"}}`, `{"type":"highlight","attrs":{"color":"green"}}`,
`{"type":"callout","attrs":{"color":"red","emoji":"🔥"}`, `"type":"tableHeader"`,
} {
if !strings.Contains(j, want) {
t.Errorf("word import lacks %s:\n%s", want, j)
}
}
}
func TestDOCXListsCodeLinksAndImages(t *testing.T) {
src := mustParse(t, sample)
data, err := DOCX("", src, DOCXOptions{
Options: Options{FileURL: func(p string) string { return "https://api.docwell.test" + p }},
Image: func(string) ([]byte, error) { return pngOf(t, 4, 2), nil },
})
if err != nil {
t.Fatal(err)
}
doc, assets, err := FromDOCX(data)
if err != nil {
t.Fatal(err)
}
md := Markdown(doc, Options{})
for _, want := range []string{
`## Plan & \<scope\>`,
"[a link](https://docwell.test/x)",
"- one\n\n 1. nested\n- two",
"```\nx := 1 < 2\n```",
"> quoted",
"![diagram](asset:0)",
} {
if !strings.Contains(md, want) {
t.Errorf("markdown lacks %q:\n%s", want, md)
}
}
if strings.Contains(md, "javascript:") {
t.Error("unsafe link kept")
}
if len(assets) != 1 {
t.Errorf("assets = %d", len(assets))
}
}
func TestDOCXIsWellFormed(t *testing.T) {
data, err := DOCX("A & <b>", mustParse(t, phaseA), DOCXOptions{})
if err != nil {
t.Fatal(err)
}
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
for _, f := range zr.File {
if !strings.HasSuffix(f.Name, ".xml") && !strings.HasSuffix(f.Name, ".rels") {
continue
}
rc, _ := f.Open()
d := xml.NewDecoder(rc)
for {
if _, err := d.Token(); err != nil {
if !errors.Is(err, io.EOF) {
t.Errorf("%s: %v", f.Name, err)
}
break
}
}
_ = rc.Close()
}
}
+72 -1
View File
@@ -357,9 +357,11 @@ var headingStyle = regexp.MustCompile(`^heading\s*([1-9])$`)
// para is a Word paragraph after its style is known.
type para struct {
kind string // paragraph, heading, quote, code, list
kind string // paragraph, heading, quote, code, list, callout, task
level int // heading level, or list depth
align string // "center" or "right", or "" for the default
color string // a callout's palette colour
checked bool // a ticked to-do
ordered bool
inline []Node
text string // code paragraphs keep their plain text
@@ -406,6 +408,22 @@ func (d *docxReader) blocks(nodes []*xnode) []Node {
if inl := trimInline(p.inline); len(inl) > 0 {
out = append(out, withAlign(Node{Type: "heading", Attrs: map[string]any{"level": float64(min(p.level, 6))}, Content: inl}, p.align))
}
case "callout":
// Paragraphs in the Callout style with the same shading are one callout.
q := Node{Type: "paragraph", Content: trimInline(p.inline)}
if l := len(out) - 1; l >= 0 && out[l].Type == "callout" && out[l].attr("color") == p.color {
out[l].Content = append(out[l].Content, q)
} else {
emoji, body := liftEmoji([]Node{q})
out = append(out, newCallout(emoji, p.color, body))
}
case "task":
item := Node{Type: "taskItem", Attrs: map[string]any{"checked": p.checked}, Content: []Node{{Type: "paragraph", Content: trimInline(p.inline)}}}
if l := len(out) - 1; l >= 0 && out[l].Type == "taskList" {
out[l].Content = append(out[l].Content, item)
} else {
out = append(out, Node{Type: "taskList", Content: []Node{item}})
}
case "quote":
if inl := trimInline(p.inline); len(inl) > 0 {
q := Node{Type: "paragraph", Content: inl}
@@ -512,6 +530,9 @@ func (d *docxReader) paragraph(p *xnode) para {
out.kind, out.level = "heading", outline
case name == "subtitle":
out.kind, out.level = "heading", 2
case name == "callout":
out.kind = "callout"
out.color = paletteNamed(paletteBackground, ppr.child("shd").attrValue("fill"))
case strings.Contains(name, "quote"):
out.kind = "quote"
case strings.Contains(name, "code") || strings.Contains(name, "preformatted") || name == "source":
@@ -541,6 +562,12 @@ func (d *docxReader) paragraph(p *xnode) para {
if out.kind == "code" {
out.text = PlainText(Node{Content: r.inline})
}
// A paragraph starting with a ballot box is a to-do (how DOCX writes them).
if out.kind == "paragraph" || out.kind == "list" {
if checked, rest, ok := ballot(out.inline); ok {
out.kind, out.checked, out.inline = "task", checked, rest
}
}
return out
}
@@ -621,6 +648,46 @@ func (r *runReader) children(nodes []*xnode, marks []Mark) {
}
}
// paletteNamed is the palette colour whose value in table is hex ("rrggbb"), or "".
func paletteNamed(table map[string]string, hex string) string {
for name, v := range table {
if strings.EqualFold(strings.TrimPrefix(v, "#"), hex) {
return name
}
}
return ""
}
func (n *xnode) attrValue(key string) string {
if n == nil {
return ""
}
return n.attrs[key]
}
// ballot takes a leading "☐ " or "☒ " off a paragraph and tells whether it was ticked.
func ballot(inline []Node) (checked bool, rest []Node, ok bool) {
i := 0
for i < len(inline) && inline[i].Type == "text" && strings.TrimSpace(inline[i].Text) == "" {
i++
}
if i == len(inline) || inline[i].Type != "text" {
return false, inline, false
}
t := strings.TrimLeft(inline[i].Text, " ")
for box, on := range map[string]bool{"☐": false, "☒": true, "☑": true} {
if after, found := strings.CutPrefix(t, box); found {
rest = append([]Node{}, inline[i:]...)
rest[0].Text = strings.TrimLeft(after, "  ")
if rest[0].Text == "" {
rest = rest[1:]
}
return on, rest, true
}
}
return false, inline, false
}
// wordHighlight maps Word's highlight colours to the palette.
var wordHighlight = map[string]string{
"yellow": "yellow", "darkYellow": "yellow", "green": "green", "darkGreen": "green", "cyan": "teal",
@@ -679,6 +746,10 @@ func (r *runReader) run(n *xnode, marks []Mark) {
if c, ok := wordHighlight[rpr.val("highlight")]; ok {
marks = withMark(marks, Mark{Type: "highlight", Attrs: map[string]any{"color": c}})
}
// Shading in a palette colour is a highlight too (how DOCX writes them).
if c := paletteNamed(paletteBackground, rpr.child("shd").attrValue("fill")); c != "" {
marks = withMark(marks, Mark{Type: "highlight", Attrs: map[string]any{"color": c}})
}
}
if r.link != "" {
marks = withLink(marks, r.link)
+685
View File
@@ -0,0 +1,685 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"fmt"
"strconv"
"strings"
"time"
)
// DOCXOptions adjust a Word export.
type DOCXOptions struct {
Options
// BaseURL makes server paths (/p/<id>, attachments) absolute links.
BaseURL string
// Image loads an image by its document URL; nil, or an error, leaves a
// link to the image in its place.
Image func(src string) ([]byte, error)
}
// DOCX renders a page as a Word document with the title on top. Headings,
// lists, to-dos, quotes, callouts, code, tables, alignment, text colours and
// highlights, links and images are kept in a form FromDOCX reads back.
// Diagrams and embeds become links, formulas their LaTeX.
func DOCX(title string, doc Node, o DOCXOptions) ([]byte, error) {
w := &docxWriter{o: o}
if strings.TrimSpace(title) != "" {
w.para(paraProps{style: "Title"}, func() { w.text(title, runProps{}) })
}
w.blocks(doc.Content, blockCtx{})
return w.pack(title)
}
// ---- Package ---------------------------------------------------------------
const (
docxTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
`<Default Extension="xml" ContentType="application/xml"/>` +
`<Default Extension="png" ContentType="image/png"/>` +
`<Default Extension="jpeg" ContentType="image/jpeg"/>` +
`<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>` +
`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>` +
`<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>` +
`<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>` +
`</Types>`
docxRootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>` +
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>` +
`</Relationships>`
relStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
relNumbering = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"
relLink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
relImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
)
func (w *docxWriter) pack(title string) ([]byte, error) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
put := func(name, body string) error {
f, err := z.Create(name)
if err == nil {
_, err = f.Write([]byte(body))
}
return err
}
rels := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="` + relStyles + `" Target="styles.xml"/>` +
`<Relationship Id="rId2" Type="` + relNumbering + `" Target="numbering.xml"/>`
for _, r := range w.rels {
mode := ""
if r.external {
mode = ` TargetMode="External"`
}
rels += `<Relationship Id="` + r.id + `" Type="` + r.typ + `" Target="` + xmlText(r.target) + `"` + mode + `/>`
}
rels += `</Relationships>`
document := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` +
`xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` +
`xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` +
`xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ` +
`xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><w:body>` +
w.b.String() +
`<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>` +
`<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>` +
`</w:sectPr></w:body></w:document>`
core := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ` +
`xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ` +
`xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">` +
`<dc:title>` + xmlText(title) + `</dc:title><dc:creator>Docwell</dc:creator>` +
`<dcterms:created xsi:type="dcterms:W3CDTF">` + time.Now().UTC().Format(time.RFC3339) + `</dcterms:created>` +
`</cp:coreProperties>`
for _, p := range []struct{ name, body string }{
{"[Content_Types].xml", docxTypes}, {"_rels/.rels", docxRootRels}, {"docProps/core.xml", core},
{"word/document.xml", document}, {"word/_rels/document.xml.rels", rels},
{"word/styles.xml", docxStyles}, {"word/numbering.xml", w.numbering()},
} {
if err := put(p.name, p.body); err != nil {
return nil, err
}
}
for _, m := range w.media {
f, err := z.Create("word/media/" + m.name)
if err != nil {
return nil, err
}
if _, err := f.Write(m.data); err != nil {
return nil, err
}
}
if err := z.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// The styles FromDOCX recognises by name: headings, Title, Quote, Code and
// Callout, plus the Hyperlink character style and a bordered table style.
var docxStyles = func() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
`<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Calibri" w:cs="Calibri"/>` +
`<w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US"/></w:rPr></w:rPrDefault>` +
`<w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` +
`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>` +
`<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:spacing w:after="240"/></w:pPr><w:rPr><w:b/><w:sz w:val="48"/></w:rPr></w:style>`)
sizes := []int{36, 30, 26, 24, 22, 20}
for i, sz := range sizes {
fmt.Fprintf(&b, `<w:style w:type="paragraph" w:styleId="Heading%d"><w:name w:val="heading %d"/><w:basedOn w:val="Normal"/>`+
`<w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="80"/><w:outlineLvl w:val="%d"/></w:pPr>`+
`<w:rPr><w:b/><w:sz w:val="%d"/></w:rPr></w:style>`, i+1, i+1, i, sz)
}
b.WriteString(`<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="C8C8C8"/></w:pBdr><w:ind w:left="284"/></w:pPr>` +
`<w:rPr><w:color w:val="5F5F5F"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:shd w:val="clear" w:color="auto" w:fill="F4F4F1"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>` +
`<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/><w:sz w:val="19"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Callout"><w:name w:val="Callout"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:ind w:left="170" w:right="170"/></w:pPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="TableHeading"><w:name w:val="Table Heading"/><w:basedOn w:val="Normal"/>` +
`<w:rPr><w:b/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:spacing w:after="40"/></w:pPr></w:style>` +
`<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>` +
`<w:rPr><w:color w:val="2F6FBF"/><w:u w:val="single"/></w:rPr></w:style>` +
`<w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:tblPr><w:tblBorders>` +
`<w:top w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:left w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`<w:bottom w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:right w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`<w:insideH w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`</w:tblBorders><w:tblCellMar><w:left w:w="100" w:type="dxa"/><w:right w:w="100" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>` +
`</w:styles>`)
return b.String()
}()
// numbering lists a bulleted and a numbered pattern, and one list instance
// per list in the document so each numbered list counts from its own start.
func (w *docxWriter) numbering() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
bullets := []string{"•", "◦", "▪"}
for abs, ordered := range []bool{false, true} {
fmt.Fprintf(&b, `<w:abstractNum w:abstractNumId="%d"><w:multiLevelType w:val="hybridMultilevel"/>`, abs+1)
for lvl := range 9 {
if ordered {
fmt.Fprintf(&b, `<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%%%d."/>`, lvl, lvl+1)
} else {
fmt.Fprintf(&b, `<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="%s"/>`, lvl, bullets[lvl%3])
}
fmt.Fprintf(&b, `<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="%d" w:hanging="360"/></w:pPr></w:lvl>`, 720+lvl*360)
}
b.WriteString(`</w:abstractNum>`)
}
for i, n := range w.nums {
abs := 1
if n.ordered {
abs = 2
}
fmt.Fprintf(&b, `<w:num w:numId="%d"><w:abstractNumId w:val="%d"/>`, i+1, abs)
if n.ordered && n.start != 1 {
fmt.Fprintf(&b, `<w:lvlOverride w:ilvl="%d"><w:startOverride w:val="%d"/></w:lvlOverride>`, n.level, n.start)
}
b.WriteString(`</w:num>`)
}
b.WriteString(`</w:numbering>`)
return b.String()
}
// ---- Document --------------------------------------------------------------
type docxRel struct {
id, typ, target string
external bool
}
type docxNum struct {
ordered bool
level int
start int
}
type docxWriter struct {
o DOCXOptions
b strings.Builder
rels []docxRel
media []struct {
name string
data []byte
}
nums []docxNum
images int
}
// blockCtx is what surrounds a block: a quote, a callout, list depth.
type blockCtx struct {
quote bool
callout string // the callout's colour, "" outside one
depth int // list nesting, for indentation
}
type paraProps struct {
style string
align string
numID int
ilvl int
indent int // left indent in twips
shading string // background "rrggbb"
border string // left border colour "rrggbb"
rule bool // a horizontal line under the paragraph
}
type runProps struct {
bold, italic, underline, strike, code bool
color, shade, href string
}
func (w *docxWriter) rel(typ, target string, external bool) string {
id := "rId" + strconv.Itoa(len(w.rels)+3)
w.rels = append(w.rels, docxRel{id: id, typ: typ, target: target, external: external})
return id
}
// link makes a document URL something Word can open, or "".
func (w *docxWriter) link(href string) string {
href = w.o.file(href)
if strings.HasPrefix(href, "/") && !strings.HasPrefix(href, "//") {
if w.o.BaseURL == "" {
return ""
}
href = strings.TrimRight(w.o.BaseURL, "/") + href
}
if !safeURL.MatchString(href) || strings.HasPrefix(href, "#") {
return ""
}
return href
}
func (w *docxWriter) para(p paraProps, content func()) {
w.b.WriteString("<w:p><w:pPr>")
if p.style != "" {
w.b.WriteString(`<w:pStyle w:val="` + p.style + `"/>`)
}
if p.numID > 0 {
fmt.Fprintf(&w.b, `<w:numPr><w:ilvl w:val="%d"/><w:numId w:val="%d"/></w:numPr>`, p.ilvl, p.numID)
}
if p.border != "" || p.rule {
w.b.WriteString("<w:pBdr>")
if p.border != "" {
w.b.WriteString(`<w:left w:val="single" w:sz="24" w:space="8" w:color="` + p.border + `"/>`)
}
if p.rule {
w.b.WriteString(`<w:bottom w:val="single" w:sz="6" w:space="1" w:color="D2D2D2"/>`)
}
w.b.WriteString("</w:pBdr>")
}
if p.shading != "" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + p.shading + `"/>`)
}
if p.indent > 0 {
fmt.Fprintf(&w.b, `<w:ind w:left="%d"/>`, p.indent)
}
if p.align != "" {
w.b.WriteString(`<w:jc w:val="` + p.align + `"/>`)
}
w.b.WriteString("</w:pPr>")
if content != nil {
content()
}
w.b.WriteString("</w:p>")
}
// textPara is the paragraph style a text block gets where it is.
func (w *docxWriter) textPara(ctx blockCtx) paraProps {
switch {
case ctx.callout != "":
bg := strings.TrimPrefix(paletteBackground[ctx.callout], "#")
fg := strings.TrimPrefix(paletteText[ctx.callout], "#")
return paraProps{style: "Callout", shading: bg, border: fg}
case ctx.quote:
return paraProps{style: "Quote"}
case ctx.depth > 0:
return paraProps{indent: 720 + (ctx.depth-1)*360}
}
return paraProps{}
}
func (w *docxWriter) blocks(nodes []Node, ctx blockCtx) {
for _, n := range nodes {
w.block(n, ctx)
}
}
func (w *docxWriter) block(n Node, ctx blockCtx) {
switch n.Type {
case "paragraph":
p := w.textPara(ctx)
p.align = docxAlign(n)
w.para(p, func() { w.inline(n.Content, runProps{}) })
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
w.para(paraProps{style: "Heading" + strconv.Itoa(level), align: docxAlign(n)}, func() { w.inline(n.Content, runProps{}) })
case "bulletList", "orderedList":
w.list(n, ctx)
case "taskList":
// FromDOCX reads paragraphs starting with a ballot box back as to-dos.
for _, item := range n.Content {
box := "☐ "
if item.Attrs["checked"] == true {
box = "☒ "
}
for i, c := range item.Content {
if i == 0 && c.Type == "paragraph" {
p := paraProps{style: "ListParagraph", indent: 360 + ctx.depth*360}
w.para(p, func() {
w.text(box, runProps{})
w.inline(c.Content, runProps{})
})
continue
}
w.block(c, blockCtx{depth: ctx.depth + 1})
}
}
case "blockquote":
ctx.quote = true
w.blocks(n.Content, ctx)
case "callout":
emoji, color := calloutParts(n)
ctx.callout = color
body := n.Content
// The emoji leads the first paragraph, where FromDOCX lifts it off again.
if len(body) > 0 && body[0].Type == "paragraph" {
first := body[0]
first.Content = append([]Node{{Type: "text", Text: emoji + " "}}, first.Content...)
body = append([]Node{first}, body[1:]...)
} else {
body = append([]Node{{Type: "paragraph", Content: []Node{{Type: "text", Text: emoji}}}}, body...)
}
w.blocks(body, ctx)
case "codeBlock":
w.code(PlainText(n))
case "mermaid":
w.code(n.attr("code"))
case "blockMath":
w.para(paraProps{align: "center"}, func() { w.text(n.attr("latex"), runProps{code: true}) })
case "horizontalRule":
w.para(paraProps{rule: true}, nil)
case "image":
w.image(n.attr("src"), n.attr("alt"))
case "drawio", "excalidraw":
label := "Draw.io diagram"
if n.Type == "excalidraw" {
label = "Excalidraw drawing"
}
w.para(paraProps{}, func() { w.text(label, runProps{italic: true, href: w.link(n.attr("src"))}) })
case "fileAttachment":
w.para(paraProps{}, func() { w.text(n.attr("name"), runProps{href: w.link(n.attr("url"))}) })
case "embed", "linkCard":
title := n.attr("title")
if title == "" {
title = n.attr("url")
}
w.para(paraProps{}, func() {
w.text(title, runProps{href: w.link(n.attr("url"))})
if d := n.attr("description"); d != "" {
w.b.WriteString("<w:r><w:br/></w:r>")
w.text(d, runProps{color: "787878"})
}
})
case "tableOfContents":
// Word builds its own from the headings (References > Table of Contents).
case "details":
for _, c := range n.Content {
if c.Type == "detailsSummary" {
w.para(w.textPara(ctx), func() { w.inline(c.Content, runProps{bold: true}) })
} else {
w.blocks(c.Content, ctx)
}
}
case "table":
w.table(n)
default:
w.blocks(n.Content, ctx)
}
}
func docxAlign(n Node) string {
switch alignOf(n) {
case "center":
return "center"
case "right":
return "right"
}
return ""
}
// list writes a bulleted or numbered list as numbered paragraphs, nesting
// by level; more blocks in an item follow indented under it.
func (w *docxWriter) list(n Node, ctx blockCtx) {
w.nums = append(w.nums, docxNum{ordered: n.Type == "orderedList", level: ctx.depth, start: n.intAttr("start", 1)})
id := len(w.nums)
for _, item := range n.Content {
for i, c := range item.Content {
if i == 0 && c.Type == "paragraph" {
w.para(paraProps{style: "ListParagraph", numID: id, ilvl: min(ctx.depth, 8)}, func() { w.inline(c.Content, runProps{}) })
continue
}
w.block(c, blockCtx{depth: ctx.depth + 1})
}
}
}
func (w *docxWriter) code(text string) {
for _, line := range strings.Split(strings.ReplaceAll(text, "\t", " "), "\n") {
w.para(paraProps{style: "Code"}, func() { w.text(line, runProps{}) })
}
// A little room after the block.
w.para(paraProps{}, nil)
}
// table writes a bordered table across the page. A row of header cells
// repeats on every page, which is also how FromDOCX tells header rows.
func (w *docxWriter) table(n Node) {
cols := 0
for _, row := range n.Content {
width := 0
for _, c := range row.Content {
width += max(c.intAttr("colspan", 1), 1)
}
cols = max(cols, width)
}
if cols == 0 {
return
}
const total = 9026 // the text width of an A4 page with 1" margins, in twips
w.b.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="5000" w:type="pct"/>` +
`<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr><w:tblGrid>`)
for range cols {
fmt.Fprintf(&w.b, `<w:gridCol w:w="%d"/>`, total/cols)
}
w.b.WriteString("</w:tblGrid>")
for _, row := range n.Content {
header := len(row.Content) > 0
for _, c := range row.Content {
header = header && c.Type == "tableHeader"
}
w.b.WriteString("<w:tr>")
if header {
w.b.WriteString("<w:trPr><w:tblHeader/></w:trPr>")
}
for _, c := range row.Content {
span := max(c.intAttr("colspan", 1), 1)
fmt.Fprintf(&w.b, `<w:tc><w:tcPr><w:tcW w:w="%d" w:type="dxa"/>`, total/cols*span)
if span > 1 {
fmt.Fprintf(&w.b, `<w:gridSpan w:val="%d"/>`, span)
}
if c.Type == "tableHeader" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="F4F4F1"/>`)
}
w.b.WriteString("</w:tcPr>")
start := w.b.Len()
for _, b := range c.Content {
if b.Type == "paragraph" && c.Type == "tableHeader" {
w.para(paraProps{style: "TableHeading", align: docxAlign(b)}, func() { w.inline(b.Content, runProps{}) })
continue
}
w.block(b, blockCtx{})
}
if w.b.Len() == start || !strings.HasSuffix(w.b.String(), "</w:p>") {
// A cell must end with a paragraph.
w.para(paraProps{}, nil)
}
w.b.WriteString("</w:tc>")
}
w.b.WriteString("</w:tr>")
}
w.b.WriteString("</w:tbl>")
// Word joins tables that touch; a paragraph keeps the next block apart.
w.para(paraProps{}, nil)
}
func (w *docxWriter) inline(nodes []Node, base runProps) {
for _, n := range nodes {
switch n.Type {
case "text":
p := base
for _, m := range n.Marks {
switch m.Type {
case "bold":
p.bold = true
case "italic":
p.italic = true
case "underline":
p.underline = true
case "strike":
p.strike = true
case "code":
p.code = true
case "textColor":
if c, ok := paletteText[m.attr("color")]; ok {
p.color = strings.TrimPrefix(c, "#")
}
case "highlight":
c, ok := paletteBackground[m.attr("color")]
if !ok {
c = paletteBackground["yellow"]
}
p.shade = strings.TrimPrefix(c, "#")
case "link":
p.href = w.link(m.attr("href"))
}
}
w.text(n.Text, p)
case "hardBreak":
w.b.WriteString("<w:r><w:br/></w:r>")
case "inlineMath":
w.text(n.attr("latex"), runProps{code: true})
case "mention":
w.text("@"+mentionLabel(n), runProps{bold: true})
case "dateMention":
w.text(n.attr("date"), runProps{bold: true})
default:
w.inline(n.Content, base)
}
}
}
// text writes one run, inside a hyperlink when it links somewhere.
func (w *docxWriter) text(s string, p runProps) {
if s == "" {
return
}
if p.href != "" {
w.b.WriteString(`<w:hyperlink r:id="` + w.rel(relLink, p.href, true) + `" w:history="1">`)
}
w.b.WriteString("<w:r><w:rPr>")
if p.href != "" {
w.b.WriteString(`<w:rStyle w:val="Hyperlink"/>`)
}
if p.code {
w.b.WriteString(`<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>`)
}
if p.bold {
w.b.WriteString("<w:b/>")
}
if p.italic {
w.b.WriteString("<w:i/>")
}
if p.strike {
w.b.WriteString("<w:strike/>")
}
if p.color != "" {
w.b.WriteString(`<w:color w:val="` + strings.ToUpper(p.color) + `"/>`)
}
if p.underline {
w.b.WriteString(`<w:u w:val="single"/>`)
}
if p.shade != "" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + strings.ToUpper(p.shade) + `"/>`)
}
w.b.WriteString("</w:rPr>")
for i, line := range strings.Split(s, "\n") {
if i > 0 {
w.b.WriteString("<w:br/>")
}
for j, part := range strings.Split(line, "\t") {
if j > 0 {
w.b.WriteString("<w:tab/>")
}
if part != "" {
w.b.WriteString(`<w:t xml:space="preserve">` + xmlText(part) + `</w:t>`)
}
}
}
w.b.WriteString("</w:r>")
if p.href != "" {
w.b.WriteString("</w:hyperlink>")
}
}
// image embeds a picture at its size (96 pixels to the inch), shrunk to the
// page width, or links to it when it cannot be loaded.
func (w *docxWriter) image(src, alt string) {
fallback := func() {
text := "Image"
if alt != "" {
text += ": " + alt
}
w.para(paraProps{}, func() { w.text("["+text+"]", runProps{italic: true, href: w.link(src)}) })
}
if w.o.Image == nil || src == "" {
fallback()
return
}
data, err := w.o.Image(src)
if err != nil {
fallback()
return
}
kind, body, px, py, err := pdfImage(data)
if err != nil {
fallback()
return
}
const emuPerPx, maxW = 9525, 5731510 // 6.27" in EMU
cx, cy := int64(px)*emuPerPx, int64(py)*emuPerPx
if cx > maxW {
cx, cy = maxW, cy*maxW/cx
}
w.images++
ext := "png"
if kind == "JPG" {
ext = "jpeg"
}
name := "image" + strconv.Itoa(w.images) + "." + ext
w.media = append(w.media, struct {
name string
data []byte
}{name, body})
rid := w.rel(relImage, "media/"+name, false)
id := strconv.Itoa(w.images)
w.para(paraProps{}, func() {
fmt.Fprintf(&w.b, `<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">`+
`<wp:extent cx="%d" cy="%d"/><wp:docPr id="%s" name="Picture %s" descr="%s"/>`+
`<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>`+
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">`+
`<pic:pic><pic:nvPicPr><pic:cNvPr id="%s" name="%s"/><pic:cNvPicPr/></pic:nvPicPr>`+
`<pic:blipFill><a:blip r:embed="%s"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>`+
`<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="%d" cy="%d"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>`+
`</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`,
cx, cy, id, id, xmlText(alt), id, name, rid, cx, cy)
})
}
// xmlText escapes text for XML and leaves out the control characters XML
// cannot hold.
func xmlText(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r == '&':
b.WriteString("&amp;")
case r == '<':
b.WriteString("&lt;")
case r == '>':
b.WriteString("&gt;")
case r == '"':
b.WriteString("&quot;")
case r < 0x20 && r != '\t' && r != '\n' && r != '\r', r == 0xFFFE, r == 0xFFFF:
default:
b.WriteRune(r)
}
}
return b.String()
}
+17 -4
View File
@@ -60,8 +60,8 @@ func exportName(title, ext string) string {
return name + ext
}
// ExportPage renders a page as Markdown ("markdown"), HTML ("html") or PDF
// ("pdf") (viewer).
// ExportPage renders a page as Markdown ("markdown"), HTML ("html"), PDF
// ("pdf") or Word ("docx") (viewer).
func (s *Service) ExportPage(ctx context.Context, c access.Caller, id, format string) (Export, error) {
p, _, err := s.pageFor(ctx, c, id)
if err != nil {
@@ -96,11 +96,24 @@ func (s *Service) ExportPage(ctx context.Context, c access.Caller, id, format st
return Export{}, err
}
return Export{Filename: exportName(p.Title, ".pdf"), ContentType: "application/pdf", Body: body}, nil
case "docx":
body, err := convert.DOCX(p.Title, doc, convert.DOCXOptions{
Options: opts, BaseURL: s.publicURL,
Image: func(src string) ([]byte, error) { return s.pdfImage(ctx, c, src) },
})
if err != nil {
return Export{}, err
}
return Export{
Filename: exportName(p.Title, ".docx"),
ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
Body: body,
}, nil
}
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown, html or pdf."})
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown, html, pdf or docx."})
}
// pdfImage loads an attachment the caller can read for a PDF export. Images
// pdfImage loads an attachment the caller can read for a PDF or Word export. Images
// on other sites are not fetched: the server would make requests on a
// reader's behalf to wherever a document points.
func (s *Service) pdfImage(ctx context.Context, c access.Caller, src string) ([]byte, error) {