Files
Docwell/Server/internal/convert/notion.go
T
tajniak81andClaude Opus 5.5 3102a476a6
CI / go (Server) (push) Failing after 4m1s
CI / go (Web-App) (push) Successful in 10m50s
CI / frontend (push) Failing after 6m46s
CI / desktop (ubuntu-latest) (push) Successful in 1h10m39s
CI / mobile (push) Failing after 3m2s
CI / docker (push) Successful in 35m59s
Docs / build (push) Successful in 13m26s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add databases: table, kanban and calendar views with rows as pages
Phase C of docs/AFFINE.md (ADR-13).

A database is a block whose records live in the page's Y.Doc, in
ydoc.getMap("blocks") under the block's id: columns, rows (each cell its
own map entry, so concurrent edits to one row merge) and views. Order is
a fractional position per item, so moving a row keeps edits made to it at
the same time. Database edits share the page's undo history.

- Thirteen property types: title, text, number, checkbox, select,
  multi-select, date, progress, link, attachment, member, created time
  and created by. The column menu renames, changes type (converting the
  values), sorts, filters, hides, inserts, moves, duplicates and deletes;
  columns resize and drag.
- Table view: keyboard navigation, range selection, typing to edit,
  copy and paste with spreadsheets (pasting adds rows as needed), row
  dragging, bulk delete, grouping.
- Views in tabs, each with its own filters (all/any), sorts, grouping
  and visible properties; kanban grouped by select, multi-select,
  checkbox or member with cards dragged between columns; calendar by a
  date property with records dragged between days.
- A record opens beside the page with its properties and a body of its
  own (a Y.XmlFragment in the row, edited by a second editor).
- /database, Ctrl+G or "Group as database" turns a list into a database;
  CSV export and import; a copied, pasted or duplicated database gets
  its own copy of the records.

Server: yrs writes each database's records into its node as attrs.data
when it turns a document into JSON, adds them to the search text, and
writes them back on imports, restores and templates. Markdown, HTML,
PDF and Word exports show a database as a table of its first view's
columns. Notion database CSVs import as database blocks with guessed
types. Share links and history previews show databases read-only.

Strings are translated into all five languages, the user guide covers
databases, and the mobile editor bundle is rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:06:18 +01:00

436 lines
12 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"crypto/rand"
"encoding/csv"
"encoding/hex"
"errors"
"fmt"
"net/url"
"path"
"regexp"
"sort"
"strconv"
"strings"
"unicode/utf8"
)
// NotionPage is one page of a Notion export. Parent is the index of its
// parent page in the list ReadNotion returns, or -1 at the top. Links to
// other pages of the export use PageRef as their URL, files AssetRef.
type NotionPage struct {
Title string
Parent int
Doc Node
}
// PageRef is the placeholder URL of the n-th page of an import.
func PageRef(n int) string { return "page:" + strconv.Itoa(n) }
// Limits of one Notion export.
const (
maxNotionPages = 2000
maxNotionEntries = 20000
maxNotionFile = 50 << 20
maxNotionTotal = 512 << 20
maxNotionInner = 200 << 20
)
// ErrNotNotion is returned for an archive without Notion pages in it.
var ErrNotNotion = errors.New("the archive holds no Markdown, HTML or CSV pages")
// notionID is the id Notion appends to every exported file and folder name.
var notionID = regexp.MustCompile(`\s+([0-9a-f]{32})$`)
// notionURLID finds a page id in a notion.so / notion.site link.
var notionURLID = regexp.MustCompile(`([0-9a-f]{32})(?:$|[?#])`)
// ReadNotion reads a Notion workspace or page export ("Markdown & CSV" or
// "HTML"), including exports split into several zip files inside one.
// Pages come parents first. Databases become a page listing their rows,
// with the row pages under it.
func ReadNotion(data []byte) ([]NotionPage, []Asset, error) {
n := &notionReader{files: map[string]*zip.File{}, assetAt: map[string]string{}}
if err := n.open(data, true); err != nil {
return nil, nil, err
}
// Page files and their place in the tree.
type src struct {
file string
key string // the path without its extension, which is also its folder
depth int
}
var srcs []src
for name := range n.files {
ext := strings.ToLower(path.Ext(name))
if ext != ".md" && ext != ".html" && ext != ".htm" && ext != ".csv" {
continue
}
if ext == ".csv" && strings.HasSuffix(strings.TrimSuffix(name, path.Ext(name)), "_all") {
continue // Newer exports add a "_all" copy of every database.
}
srcs = append(srcs, src{file: name, key: strings.TrimSuffix(name, path.Ext(name)), depth: strings.Count(name, "/")})
}
if len(srcs) == 0 {
return nil, nil, ErrNotNotion
}
if len(srcs) > maxNotionPages {
return nil, nil, fmt.Errorf("the export has more than %d pages", maxNotionPages)
}
sort.Slice(srcs, func(i, j int) bool {
if srcs[i].depth != srcs[j].depth {
return srcs[i].depth < srcs[j].depth
}
return srcs[i].file < srcs[j].file
})
n.pageAt = map[string]int{}
n.pageByID = map[string]int{}
byKey := map[string]int{}
for i, s := range srcs {
n.pageAt[s.file] = i
byKey[s.key] = i
if m := notionID.FindStringSubmatch(path.Base(s.key)); m != nil {
n.pageByID[m[1]] = i
}
}
pages := make([]NotionPage, len(srcs))
for i, s := range srcs {
parent := -1
for dir := path.Dir(s.file); dir != "." && dir != "/"; dir = path.Dir(dir) {
if p, ok := byKey[dir]; ok {
parent = p
break
}
}
data, err := n.read(n.files[s.file])
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", s.file, err)
}
if !utf8.Valid(data) {
return nil, nil, fmt.Errorf("%s is not UTF-8 text", s.file)
}
opts := ImportOptions{Resolve: func(u string) (string, bool) { return n.resolve(path.Dir(s.file), u) }}
var doc Node
switch strings.ToLower(path.Ext(s.file)) {
case ".md":
doc, err = FromMarkdownWith(notionAsides(string(bytes.TrimPrefix(data, []byte(utf8BOM)))), opts)
case ".csv":
doc, err = notionTable(data)
default:
doc, err = FromHTMLWith(string(data), opts)
}
if err != nil {
return nil, nil, fmt.Errorf("%s could not be read: %w", s.file, err)
}
if n.err != nil {
return nil, nil, n.err
}
title, body := Title(doc)
if strings.TrimSpace(title) == "" {
title = notionName(path.Base(s.key))
}
if len(body.Content) == 0 {
body.Content = []Node{{Type: "paragraph"}}
}
pages[i] = NotionPage{Title: strings.TrimSpace(title), Parent: parent, Doc: body}
}
return pages, n.assets, nil
}
// notionName is a file or folder name without Notion's id.
func notionName(name string) string {
name = strings.TrimSpace(notionID.ReplaceAllString(name, ""))
if name == "" {
return "Untitled"
}
return name
}
type notionReader struct {
files map[string]*zip.File
entries int
total int64 // bytes the archives say they hold
used int64 // bytes read so far
pageAt map[string]int // file path -> page index
pageByID map[string]int
assets []Asset
assetAt map[string]string // file path -> asset ref
err error
}
// open adds an archive's files; with nested, zip files inside it (the parts
// of a large export) are opened too.
func (n *notionReader) open(data []byte, nested bool) error {
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return fmt.Errorf("not a zip file: %w", err)
}
for _, f := range zr.File {
if f.FileInfo().IsDir() {
continue
}
n.entries++
if n.entries > maxNotionEntries {
return ErrTooLarge
}
if f.UncompressedSize64 > maxNotionTotal {
return ErrTooLarge
}
n.total += int64(f.UncompressedSize64)
if n.total > maxNotionTotal {
return ErrTooLarge
}
name := path.Clean(strings.TrimPrefix(strings.ReplaceAll(f.Name, "\\", "/"), "/"))
if name == "." || strings.HasPrefix(name, "../") || strings.HasPrefix(path.Base(name), ".") || strings.HasPrefix(name, "__MACOSX/") {
continue
}
if nested && strings.EqualFold(path.Ext(name), ".zip") {
inner, err := readZipFile(f, min(maxNotionInner, maxNotionTotal-n.used))
n.used += int64(len(inner))
if err != nil {
return err
}
if err := n.open(inner, false); err != nil {
return err
}
continue
}
n.files[name] = f
}
return nil
}
// read unpacks one file, keeping the export as a whole under its limit.
func (n *notionReader) read(f *zip.File) ([]byte, error) {
data, err := readZipFile(f, min(maxNotionFile, maxNotionTotal-n.used))
n.used += int64(len(data))
return data, err
}
// resolve maps a link or image URL in the page file under dir.
func (n *notionReader) resolve(dir, raw string) (string, bool) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil {
return "", true
}
if u.Scheme != "" || u.Host != "" {
if strings.HasSuffix(u.Host, "notion.so") || strings.HasSuffix(u.Host, "notion.site") {
if m := notionURLID.FindStringSubmatch(strings.ReplaceAll(u.Path, "-", "")); m != nil {
if i, ok := n.pageByID[m[1]]; ok {
return PageRef(i), true
}
}
}
return "", false
}
if u.Path == "" {
return "", false // An anchor in the same page.
}
p := path.Clean(path.Join(dir, u.Path))
if i, ok := n.pageAt[p]; ok {
return PageRef(i), true
}
if ref, ok := n.assetAt[p]; ok {
return ref, true
}
f, ok := n.files[p]
if !ok {
return "", true // A file the export left out.
}
data, err := n.read(f)
if err != nil {
if n.err == nil {
n.err = fmt.Errorf("%s: %w", p, err)
}
return "", true
}
ref := AssetRef(len(n.assets))
n.assets = append(n.assets, Asset{Ref: ref, Name: path.Base(p), Data: data})
n.assetAt[p] = ref
return ref, true
}
// notionTable turns a database's CSV into a database block (ADR-13): the
// header names the columns, the first column is the title, and the other
// columns get a type guessed from their values.
func notionTable(data []byte) (Node, error) {
r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(data, []byte(utf8BOM))))
r.FieldsPerRecord = -1
r.LazyQuotes = true
rows, err := r.ReadAll()
if err != nil {
return Node{}, err
}
doc := Node{Type: "doc"}
if len(rows) == 0 || len(rows[0]) == 0 {
return doc, nil
}
head, body := rows[0], rows[1:]
field := func(row []string, i int) string {
if i < len(row) {
return strings.TrimSpace(row[i])
}
return ""
}
type column struct {
id, name, typ string
options []map[string]any
byName map[string]string
}
colors := []string{"red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
cols := make([]*column, len(head))
for i, name := range head {
values := make([]string, 0, len(body))
for _, row := range body {
values = append(values, field(row, i))
}
typ := "title"
if i > 0 {
typ = guessColumnType(values)
}
if name = strings.TrimSpace(name); name == "" {
name = strconv.Itoa(i + 1)
}
cols[i] = &column{id: shortID(), name: name, typ: typ, byName: map[string]string{}}
}
var outRows []any
for n, row := range body {
cells := map[string]any{}
for i, c := range cols {
v := field(row, i)
if v == "" {
continue
}
switch c.typ {
case "number":
f, _ := strconv.ParseFloat(strings.ReplaceAll(v, ",", "."), 64)
cells[c.id] = f
case "checkbox":
if isYes(v) {
cells[c.id] = true
}
case "date":
cells[c.id] = v[:10]
case "select":
id, ok := c.byName[strings.ToLower(v)]
if !ok {
id = shortID()
c.byName[strings.ToLower(v)] = id
c.options = append(c.options, map[string]any{"id": id, "name": v, "color": colors[len(c.options)%len(colors)]})
}
cells[c.id] = id
default:
cells[c.id] = v
}
}
outRows = append(outRows, map[string]any{"id": shortID(), "createdAt": float64(n), "cells": cells})
}
columns := make([]any, len(cols))
for i, c := range cols {
col := map[string]any{"id": c.id, "name": c.name, "type": c.typ}
if c.typ == "select" {
opts := make([]any, len(c.options))
for j, o := range c.options {
opts[j] = o
}
col["options"] = opts
}
columns[i] = col
}
view := map[string]any{
"id": shortID(), "name": "Table", "type": "table", "hidden": []any{}, "filters": []any{},
"filterMode": "and", "sorts": []any{}, "widths": map[string]any{},
}
db := map[string]any{"title": "", "columns": columns, "rows": outRows, "views": []any{view}}
doc.Content = []Node{{Type: "database", Attrs: map[string]any{"id": shortID(), "data": db}}}
return doc, nil
}
var isoDate = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}`)
func isYes(v string) bool {
switch strings.ToLower(v) {
case "yes", "true", "1", "x", "✓":
return true
}
return false
}
// guessColumnType is the column type for these values, like guessType in
// Packages/editor/src/database/csv.ts.
func guessColumnType(values []string) string {
var filled []string
for _, v := range values {
if v != "" {
filled = append(filled, v)
}
}
if len(filled) == 0 {
return "text"
}
all := func(ok func(string) bool) bool {
for _, v := range filled {
if !ok(v) {
return false
}
}
return true
}
switch {
case all(func(v string) bool {
_, err := strconv.ParseFloat(strings.ReplaceAll(v, ",", "."), 64)
return err == nil
}):
return "number"
case all(isoDate.MatchString):
return "date"
case all(func(v string) bool {
l := strings.ToLower(v)
return l == "yes" || l == "no" || l == "true" || l == "false"
}):
return "checkbox"
}
distinct := map[string]bool{}
for _, v := range filled {
distinct[strings.ToLower(v)] = true
}
short := all(func(v string) bool { return len([]rune(v)) <= 40 })
if len(filled) >= 4 && short && float64(len(distinct)) <= max(2, float64(len(filled))/3) {
return "select"
}
return "text"
}
// shortID is a random id for a database's columns, rows and views.
func shortID() string {
var b [5]byte
_, _ = rand.Read(b[:])
return hex.EncodeToString(b[:])
}
// 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"