Files
Docwell/Server/internal/convert/docx.go
T
tajniak81andClaude Opus 5.5 d28f1e02db 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>
2026-11-14 12:20:08 +01:00

766 lines
19 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"path"
"regexp"
"strconv"
"strings"
)
// Asset is a file an imported document refers to. The document uses Ref as
// the file's URL until the importer has stored it and calls RewriteURLs.
type Asset struct {
Ref string
Name string
Data []byte
}
// AssetRef is the placeholder URL of the n-th asset of an import.
func AssetRef(n int) string { return "asset:" + strconv.Itoa(n) }
// RewriteURLs replaces image sources, file and diagram URLs and link targets
// through fn, which returns the new URL (or "" to drop a link mark, or an
// image or file block).
func RewriteURLs(n Node, fn func(string) string) Node {
switch n.Type {
case "image", "drawio", "excalidraw":
if src := n.attr("src"); src != "" {
n.Attrs = cloneAttrs(n.Attrs)
n.Attrs["src"] = fn(src)
}
case "fileAttachment":
if u := n.attr("url"); u != "" {
n.Attrs = cloneAttrs(n.Attrs)
n.Attrs["url"] = fn(u)
}
}
if len(n.Marks) > 0 {
marks := make([]Mark, 0, len(n.Marks))
for _, m := range n.Marks {
if m.Type == "link" {
href := fn(m.attr("href"))
if href == "" {
continue
}
m.Attrs = cloneAttrs(m.Attrs)
m.Attrs["href"] = href
}
marks = append(marks, m)
}
n.Marks = marks
}
if len(n.Content) > 0 {
kids := make([]Node, 0, len(n.Content))
for _, c := range n.Content {
c = RewriteURLs(c, fn)
if (c.Type == "image" && c.attr("src") == "") || (c.Type == "fileAttachment" && c.attr("url") == "") {
continue
}
kids = append(kids, c)
}
n.Content = kids
}
return n
}
func cloneAttrs(a map[string]any) map[string]any {
out := make(map[string]any, len(a)+1)
for k, v := range a {
out[k] = v
}
return out
}
// ---- Zip limits ------------------------------------------------------------
// ErrTooLarge is returned when an archive unpacks to more than its limits.
var ErrTooLarge = errors.New("the archive is too large")
// readZipFile reads one archive entry, failing past limit bytes, so a small
// archive cannot unpack into an unbounded amount of memory.
func readZipFile(f *zip.File, limit int64) ([]byte, error) {
if limit < 0 || f.UncompressedSize64 > uint64(limit) {
return nil, ErrTooLarge
}
rc, err := f.Open()
if err != nil {
return nil, err
}
defer func() { _ = rc.Close() }()
data, err := io.ReadAll(io.LimitReader(rc, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, ErrTooLarge
}
return data, nil
}
// ---- A small XML tree ------------------------------------------------------
// xnode is an XML element with attributes keyed by local name.
type xnode struct {
name string
attrs map[string]string
kids []*xnode
text string
}
func parseXML(data []byte) (*xnode, error) {
d := xml.NewDecoder(bytes.NewReader(data))
d.Strict = false
root := &xnode{}
stack := []*xnode{root}
for {
tok, err := d.Token()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, err
}
top := stack[len(stack)-1]
switch t := tok.(type) {
case xml.StartElement:
n := &xnode{name: t.Name.Local, attrs: map[string]string{}}
for _, a := range t.Attr {
n.attrs[a.Name.Local] = a.Value
}
top.kids = append(top.kids, n)
stack = append(stack, n)
case xml.EndElement:
if len(stack) > 1 {
stack = stack[:len(stack)-1]
}
case xml.CharData:
top.text += string(t)
}
}
return root, nil
}
func (n *xnode) child(name string) *xnode {
if n == nil {
return nil
}
for _, k := range n.kids {
if k.name == name {
return k
}
}
return nil
}
func (n *xnode) val(name string) string {
if c := n.child(name); c != nil {
return c.attrs["val"]
}
return ""
}
// on tells whether a toggle property (<w:b/>, <w:i w:val="0"/>) is set.
func (n *xnode) on(name string) bool {
c := n.child(name)
if c == nil {
return false
}
v, ok := c.attrs["val"]
return !ok || (v != "0" && v != "false" && v != "none")
}
func (n *xnode) find(name string) *xnode {
if n == nil {
return nil
}
if n.name == name {
return n
}
for _, k := range n.kids {
if f := k.find(name); f != nil {
return f
}
}
return nil
}
// ---- DOCX ------------------------------------------------------------------
// 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, 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 {
return Node{}, nil, fmt.Errorf("not a Word file: %w", err)
}
files := map[string]*zip.File{}
for _, f := range zr.File {
files[strings.TrimPrefix(f.Name, "/")] = f
}
part := func(name string) (*xnode, error) {
f := files[name]
if f == nil {
return nil, nil
}
b, err := readZipFile(f, maxDocxPart)
if err != nil {
return nil, err
}
return parseXML(b)
}
body, err := part("word/document.xml")
if err != nil {
return Node{}, nil, err
}
if body == nil {
return Node{}, nil, errors.New("not a Word file: word/document.xml is missing")
}
d := &docxReader{files: files, rels: map[string]rel{}, styles: map[string]docxStyle{}, numFmt: map[string]bool{}}
if x, err := part("word/_rels/document.xml.rels"); err == nil && x != nil {
for _, r := range x.find("Relationships").kids {
d.rels[r.attrs["Id"]] = rel{target: r.attrs["Target"], external: r.attrs["TargetMode"] == "External"}
}
}
if x, err := part("word/styles.xml"); err == nil && x != nil {
d.readStyles(x)
}
if x, err := part("word/numbering.xml"); err == nil && x != nil {
d.readNumbering(x)
}
b := body.find("body")
if b == nil {
return Node{}, nil, errors.New("not a Word file: the document has no body")
}
doc := Node{Type: "doc", Content: d.blocks(b.kids)}
if d.err != nil {
return Node{}, nil, d.err
}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
}
return doc, d.assets, nil
}
type rel struct {
target string
external bool
}
type docxStyle struct {
name string
basedOn string
outline int // heading level from w:outlineLvl, 0 when none
numID string
}
type docxReader struct {
files map[string]*zip.File
rels map[string]rel
styles map[string]docxStyle
// numFmt is true for an ordered list level, keyed "numId/ilvl".
numFmt map[string]bool
assets []Asset
images map[string]string // zip path -> asset ref
err error
}
func (d *docxReader) readStyles(x *xnode) {
root := x.find("styles")
if root == nil {
return
}
for _, s := range root.kids {
if s.name != "style" || s.attrs["type"] != "paragraph" {
continue
}
st := docxStyle{name: strings.ToLower(s.val("name")), basedOn: s.val("basedOn")}
if ppr := s.child("pPr"); ppr != nil {
if v, err := strconv.Atoi(ppr.val("outlineLvl")); err == nil && v < 9 {
st.outline = v + 1
}
if np := ppr.child("numPr"); np != nil {
st.numID = np.val("numId")
}
}
d.styles[s.attrs["styleId"]] = st
}
}
func (d *docxReader) readNumbering(x *xnode) {
root := x.find("numbering")
if root == nil {
return
}
abstract := map[string]map[string]bool{}
for _, a := range root.kids {
if a.name != "abstractNum" {
continue
}
levels := map[string]bool{}
for _, l := range a.kids {
if l.name == "lvl" {
f := l.val("numFmt")
levels[l.attrs["ilvl"]] = f != "" && f != "bullet" && f != "none"
}
}
abstract[a.attrs["abstractNumId"]] = levels
}
for _, n := range root.kids {
if n.name != "num" {
continue
}
for lvl, ordered := range abstract[n.val("abstractNumId")] {
d.numFmt[n.attrs["numId"]+"/"+lvl] = ordered
}
}
}
// style resolves a paragraph style through basedOn, with a depth guard
// against style loops.
func (d *docxReader) style(id string) (name string, outline int, numID string) {
for i := 0; id != "" && i < 10; i++ {
st, ok := d.styles[id]
if !ok {
break
}
if name == "" {
name = st.name
}
if outline == 0 {
outline = st.outline
}
if numID == "" {
numID = st.numID
}
id = st.basedOn
}
if name == "" {
name = strings.ToLower(id)
}
return name, outline, numID
}
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
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
blocks []Node // images and other blocks lifted out of the paragraph
}
func (d *docxReader) blocks(nodes []*xnode) []Node {
var out []Node
var list []para
var code []string
flushList := func() {
for len(list) > 0 {
var l Node
l, list = buildList(list, list[0].level)
out = append(out, l)
}
}
flushCode := func() {
if code != nil {
c := Node{Type: "codeBlock", Attrs: map[string]any{"language": nil}}
if t := strings.Join(code, "\n"); t != "" {
c.Content = []Node{{Type: "text", Text: t}}
}
out = append(out, c)
code = nil
}
}
for _, n := range nodes {
switch n.name {
case "p":
p := d.paragraph(n)
if p.kind != "list" {
flushList()
}
if p.kind != "code" {
flushCode()
}
switch p.kind {
case "list":
list = append(list, p)
case "code":
code = append(code, p.text)
case "heading":
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 "quote":
if inl := trimInline(p.inline); len(inl) > 0 {
q := Node{Type: "paragraph", Content: inl}
if l := len(out) - 1; l >= 0 && out[l].Type == "blockquote" {
out[l].Content = append(out[l].Content, q)
} else {
out = append(out, Node{Type: "blockquote", Content: []Node{q}})
}
}
default:
if inl := trimInline(p.inline); len(inl) > 0 {
out = append(out, withAlign(Node{Type: "paragraph", Content: inl}, p.align))
}
}
out = append(out, p.blocks...)
case "tbl":
flushList()
flushCode()
out = append(out, d.table(n)...)
case "sdt":
flushList()
flushCode()
out = append(out, d.blocks(n.child("sdtContent").kidsOrNil())...)
}
}
flushList()
flushCode()
return out
}
func (n *xnode) kidsOrNil() []*xnode {
if n == nil {
return nil
}
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 {
tbl := Node{Type: "table"}
for _, tr := range t.kids {
if tr.name != "tr" {
continue
}
kind := "tableCell"
if tr.child("trPr").on("tblHeader") {
kind = "tableHeader"
}
row := Node{Type: "tableRow"}
for _, tc := range tr.kids {
if tc.name != "tc" {
continue
}
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)
}
content := d.blocks(tc.kids)
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 {
tbl.Content = append(tbl.Content, row)
}
}
if len(tbl.Content) == 0 {
return nil
}
return []Node{tbl}
}
func (d *docxReader) paragraph(p *xnode) para {
ppr := p.child("pPr")
name, outline, styleNum := d.style(ppr.val("pStyle"))
out := para{kind: "paragraph"}
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
case headingStyle.MatchString(name):
lvl, _ := strconv.Atoi(headingStyle.FindStringSubmatch(name)[1])
out.kind, out.level = "heading", lvl
case outline > 0:
out.kind, out.level = "heading", outline
case name == "subtitle":
out.kind, out.level = "heading", 2
case strings.Contains(name, "quote"):
out.kind = "quote"
case strings.Contains(name, "code") || strings.Contains(name, "preformatted") || name == "source":
out.kind = "code"
}
numID, ilvl := styleNum, "0"
if np := ppr.child("numPr"); np != nil {
if v := np.val("numId"); v != "" {
numID = v
}
if v := np.val("ilvl"); v != "" {
ilvl = v
}
}
if numID != "" && numID != "0" && out.kind == "paragraph" {
out.kind = "list"
out.level, _ = strconv.Atoi(ilvl)
ordered, known := d.numFmt[numID+"/"+ilvl]
if !known {
ordered = strings.Contains(name, "number")
}
out.ordered = ordered
}
r := &runReader{d: d}
r.children(p.kids, nil)
out.inline, out.blocks = r.inline, r.blocks
if out.kind == "code" {
out.text = PlainText(Node{Content: r.inline})
}
return out
}
// buildList nests list paragraphs by depth, starting a new list where the
// kind (bulleted or numbered) changes.
func buildList(items []para, level int) (Node, []para) {
list := newList(items[0].ordered)
for len(items) > 0 {
it := items[0]
if it.level < level {
break
}
if it.level == level {
if it.ordered != (list.Type == "orderedList") {
break
}
p := Node{Type: "paragraph", Content: trimInline(it.inline)}
item := Node{Type: "listItem", Content: append([]Node{p}, it.blocks...)}
list.Content = append(list.Content, item)
items = items[1:]
continue
}
var sub Node
sub, items = buildList(items, it.level)
if len(list.Content) == 0 {
list.Content = []Node{{Type: "listItem", Content: []Node{{Type: "paragraph"}}}}
}
last := &list.Content[len(list.Content)-1]
last.Content = append(last.Content, sub)
}
return list, items
}
func newList(ordered bool) Node {
if ordered {
return Node{Type: "orderedList", Attrs: map[string]any{"start": float64(1)}}
}
return Node{Type: "bulletList"}
}
// runReader collects a paragraph's runs, following hyperlinks (both
// <w:hyperlink> and HYPERLINK fields) and lifting images out as blocks.
type runReader struct {
d *docxReader
inline []Node
blocks []Node
// A complex field: instr gathers the instruction, link is its target
// once the field's result starts.
inField bool
instr string
link string
}
var hyperlinkField = regexp.MustCompile(`^\s*HYPERLINK\s+"([^"]+)"`)
var monoFont = regexp.MustCompile(`(?i)courier|consolas|mono|menlo|monaco`)
func (r *runReader) children(nodes []*xnode, marks []Mark) {
for _, n := range nodes {
switch n.name {
case "r":
r.run(n, marks)
case "hyperlink":
m := marks
if rl, ok := r.d.rels[n.attrs["id"]]; ok && rl.external && safeURL.MatchString(rl.target) {
m = withLink(marks, rl.target)
}
r.children(n.kids, m)
case "fldSimple":
m := marks
if f := hyperlinkField.FindStringSubmatch(n.attrs["instr"]); f != nil && safeURL.MatchString(f[1]) {
m = withLink(marks, f[1])
}
r.children(n.kids, m)
case "smartTag", "customXml", "ins", "sdt", "sdtContent":
r.children(n.kids, marks)
}
}
}
// 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,
}})
}
func (r *runReader) run(n *xnode, marks []Mark) {
rpr := n.child("rPr")
add := func(t string) {
for _, m := range marks {
if m.Type == t {
return
}
}
marks = append(append([]Mark(nil), marks...), Mark{Type: t})
}
if rpr != nil {
if rpr.on("b") {
add("bold")
}
if rpr.on("i") {
add("italic")
}
if u := rpr.child("u"); u != nil && u.attrs["val"] != "none" && u.attrs["val"] != "0" {
add("underline")
}
if rpr.on("strike") || rpr.on("dstrike") {
add("strike")
}
if f := rpr.child("rFonts"); f != nil && monoFont.MatchString(f.attrs["ascii"]) {
add("code")
}
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)
}
for _, c := range n.kids {
switch c.name {
case "fldChar":
switch c.attrs["fldCharType"] {
case "begin":
r.inField, r.instr, r.link = true, "", ""
case "separate":
if f := hyperlinkField.FindStringSubmatch(r.instr); f != nil && safeURL.MatchString(f[1]) {
r.link = f[1]
}
r.inField = false
case "end":
r.inField, r.link = false, ""
}
case "instrText":
if r.inField {
r.instr += c.text
}
case "t":
if !r.inField && c.text != "" {
r.inline = append(r.inline, Node{Type: "text", Text: c.text, Marks: marks})
}
case "tab":
r.inline = append(r.inline, Node{Type: "text", Text: " ", Marks: marks})
case "br", "cr":
if c.attrs["type"] != "page" && c.attrs["type"] != "column" {
r.inline = append(r.inline, Node{Type: "hardBreak"})
}
case "drawing", "pict":
r.image(c)
}
}
}
func (r *runReader) image(n *xnode) {
id := ""
if blip := n.find("blip"); blip != nil {
id = blip.attrs["embed"]
} else if im := n.find("imagedata"); im != nil {
id = im.attrs["id"]
}
rl, ok := r.d.rels[id]
if !ok || rl.external {
return
}
alt := ""
if dp := n.find("docPr"); dp != nil {
alt = dp.attrs["descr"]
}
ref := r.d.asset(path.Clean(path.Join("word", rl.target)))
if ref == "" {
return
}
r.blocks = append(r.blocks, Node{Type: "image", Attrs: map[string]any{"src": ref, "alt": alt, "title": nil}})
}
// asset adds a file from the archive (once) and returns its ref, or "".
func (d *docxReader) asset(name string) string {
if ref, ok := d.images[name]; ok {
return ref
}
f := d.files[strings.TrimPrefix(name, "/")]
if f == nil {
return ""
}
data, err := readZipFile(f, maxDocxPart)
if err != nil {
if d.err == nil && errors.Is(err, ErrTooLarge) {
d.err = err
}
return ""
}
if d.images == nil {
d.images = map[string]string{}
}
ref := AssetRef(len(d.assets))
d.assets = append(d.assets, Asset{Ref: ref, Name: path.Base(name), Data: data})
d.images[name] = ref
return ref
}