Add Markdown and HTML import and export

docwell-server converts between page documents and Markdown or HTML (a
new convert package), so every client and the API get the same results.
Pages export as a download from the page menu; spaces import one page
per .md, .txt or .html file, taking a leading level-1 heading as the
title. Import keeps only what the editor schema knows, which drops
scripts, styles, event handlers and javascript: links; tables become
one paragraph per row until the editor has tables.

The UI package gains DwMenu, a small accessible action menu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 17:04:39 +01:00
1 parent 25e7ca19a5
commit 011833fcef
23 files changed
+1495 -26

No files matched your search

+24
View File
@@ -108,6 +108,21 @@ export function createClient(opts: ClientOptions) {
const post = <T = void>(path: string, body?: unknown) => request<T>("POST", path, body ?? {});
/** Fetches a file with the session token; the name comes from Content-Disposition. */
async function download(path: string): Promise<{ blob: Blob; filename: string }> {
const headers: Record<string, string> = {};
const token = opts.token?.();
if (token) headers.Authorization = `Bearer ${token}`;
const res = await doFetch(base + path, { headers });
if (!res.ok) {
const data = res.headers.get("content-type")?.includes("application/json") ? await res.json() : await res.text();
throw new ApiError(res.status, data);
}
const cd = res.headers.get("content-disposition") ?? "";
const m = /filename\*=UTF-8''([^;]+)/i.exec(cd) ?? /filename="?([^";]+)"?/i.exec(cd);
return { blob: await res.blob(), filename: m ? decodeURIComponent(m[1]!) : "download" };
}
/** Sends a multipart form; the browser sets the boundary header itself. */
async function upload<T>(path: string, form: FormData): Promise<T> {
const headers: Record<string, string> = { Accept: "application/json" };
@@ -245,6 +260,13 @@ export function createClient(opts: ClientOptions) {
createPage: (id: string, input: { parent?: string; title?: string; index?: number } = {}) =>
post<Page>(`/api/v1/spaces/${encodeURIComponent(id)}/pages`, input),
trash: (id: string) => request<TrashedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/trash`),
/** Creates a page per Markdown or HTML file, under parent ("" = top level). */
import: (id: string, files: File[], parent = "") => {
const form = new FormData();
for (const f of files) form.append("file", f, f.name);
if (parent) form.append("parent", parent);
return upload<Page[]>(`/api/v1/spaces/${encodeURIComponent(id)}/import`, form);
},
},
pages: {
@@ -276,6 +298,8 @@ export function createClient(opts: ClientOptions) {
form.append("file", file, name);
return upload<Attachment>(`/api/v1/pages/${encodeURIComponent(id)}/attachments`, form);
},
export: (id: string, format: "markdown" | "html") =>
download(`/api/v1/pages/${encodeURIComponent(id)}/export${query({ format })}`),
/** Records that the user opened the page, for their recent list. */
visit: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/visit`),
purge: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}?permanent=true`),
+104
View File
@@ -1163,6 +1163,50 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/export": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/**
* Download the page as Markdown or HTML
* @description Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open.
*/
get: operations["exportPage"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}/import": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Create pages from Markdown or HTML files (editor)
* @description One page per file (.md, .markdown, .txt, .html, .htm; at most 20 files, 5 MB each, 25 MB in all). A leading level-1 heading becomes the title, otherwise the file name. HTML is reduced to what the editor supports; scripts and styles are dropped.
*/
post: operations["importPages"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -3638,4 +3682,64 @@ export interface operations {
403: components["responses"]["Error"];
};
};
exportPage: {
parameters: {
query?: {
format?: "markdown" | "html";
};
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description The file */
200: {
headers: {
[name: string]: unknown;
};
content: {
"text/markdown": string;
"text/html": string;
};
};
400: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
importPages: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"multipart/form-data": {
file: string[];
/** @description Parent page id; empty for the top level */
parent?: string;
};
};
};
responses: {
/** @description The created pages */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Page"][];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
}
+109
View File
@@ -0,0 +1,109 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, useId } from "vue";
import DwButton from "./DwButton.vue";
import DwIcon from "./DwIcon.vue";
import type { IconName } from "./icons";
export interface MenuItem {
label: string;
icon?: IconName;
danger?: boolean;
disabled?: boolean;
onSelect: () => void;
}
// A button that opens a short list of actions. Arrow keys move between items,
// Escape or a click outside closes it and returns focus to the button.
const props = withDefaults(
defineProps<{ items: MenuItem[]; label: string; icon?: IconName; align?: "start" | "end" }>(),
{
icon: "more",
align: "end",
},
);
const open = ref(false);
const root = ref<HTMLElement | null>(null);
const list = ref<HTMLElement | null>(null);
const id = useId();
function onDocDown(e: PointerEvent) {
if (root.value && !root.value.contains(e.target as Node)) close(false);
}
async function toggle() {
if (open.value) return close();
open.value = true;
document.addEventListener("pointerdown", onDocDown);
await nextTick();
list.value?.querySelector<HTMLElement>("[role=menuitem]:not([disabled])")?.focus();
}
function close(refocus = true) {
open.value = false;
document.removeEventListener("pointerdown", onDocDown);
if (refocus) root.value?.querySelector<HTMLElement>("button")?.focus();
}
onBeforeUnmount(() => document.removeEventListener("pointerdown", onDocDown));
function select(item: MenuItem) {
if (item.disabled) return;
close();
item.onSelect();
}
function onKey(e: KeyboardEvent) {
const items = [...(list.value?.querySelectorAll<HTMLElement>("[role=menuitem]:not([disabled])") ?? [])];
const at = items.indexOf(document.activeElement as HTMLElement);
if (e.key === "Escape") {
e.preventDefault();
close();
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const step = e.key === "ArrowDown" ? 1 : -1;
items[(at + step + items.length) % items.length]?.focus();
}
}
</script>
<template>
<div ref="root" class="relative" @keydown="onKey">
<DwButton
variant="ghost"
size="sm"
:icon="props.icon"
:aria-label="label"
:title="label"
aria-haspopup="menu"
:aria-expanded="open"
:aria-controls="open ? id : undefined"
@click="toggle"
>
<slot />
</DwButton>
<div
v-if="open"
:id="id"
ref="list"
role="menu"
:aria-label="label"
class="absolute top-full z-40 mt-1 min-w-48 rounded-md border border-line bg-surface-raised p-1 shadow-menu"
:class="align === 'end' ? 'right-0' : 'left-0'"
>
<button
v-for="it in items"
:key="it.label"
role="menuitem"
type="button"
:disabled="it.disabled"
class="flex w-full cursor-pointer items-center gap-2 rounded-sm px-2 py-1.5 text-left text-ui-md hover:bg-surface-hover focus:bg-surface-hover focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
:class="it.danger ? 'text-danger' : 'text-ink'"
@click="select(it)"
>
<DwIcon v-if="it.icon" :name="it.icon" :size="16" class="shrink-0 text-ink-muted" />
{{ it.label }}
</button>
</div>
</div>
</template>
+1
View File
@@ -6,6 +6,7 @@ export { default as DwButton } from "./DwButton.vue";
export { default as DwCallout } from "./DwCallout.vue";
export { default as DwIcon } from "./DwIcon.vue";
export { default as DwLogo } from "./DwLogo.vue";
export { default as DwMenu, type MenuItem } from "./DwMenu.vue";
export { default as DwSlashMenu, type SlashMenuItem } from "./DwSlashMenu.vue";
export { default as DwTextField } from "./DwTextField.vue";
export { default as DwTreeItem } from "./DwTreeItem.vue";
+1
View File
@@ -76,6 +76,7 @@ func run(log *slog.Logger) error {
defer stopIndex()
go index.Run(indexCtx, 3*time.Second, 10*time.Minute)
dirSvc.UseSearch(index)
dirSvc.SetPublicURL(cfg.PublicURL)
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
b, _ := settingsSvc.Branding(ctx)
+8 -6
View File
@@ -1,12 +1,14 @@
module docwell/server
go 1.26
go 1.26.0
require (
github.com/blevesearch/bleve/v2 v2.6.1
github.com/coder/websocket v1.8.15
github.com/oapi-codegen/runtime v1.8.0
github.com/tetratelabs/wazero v1.12.0
github.com/yuin/goldmark v1.8.7
golang.org/x/net v0.62.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -50,11 +52,11 @@ require (
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
go.etcd.io/bbolt v1.4.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.38.0 // indirect
golang.org/x/sync v0.22.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.40.0 // indirect
golang.org/x/tools v0.48.0 // indirect
golang.org/x/mod v0.41.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
golang.org/x/tools v0.51.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
)
+14 -12
View File
@@ -152,6 +152,8 @@ github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U
github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk=
github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI=
github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk=
go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
@@ -160,8 +162,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
@@ -169,13 +171,13 @@ golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -190,21 +192,21 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI=
golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+37
View File
@@ -196,6 +196,24 @@ func (e WorkspaceRole) Valid() bool {
}
}
// Defines values for ExportPageParamsFormat.
const (
Html ExportPageParamsFormat = "html"
Markdown ExportPageParamsFormat = "markdown"
)
// Valid indicates whether the value is a known member of the ExportPageParamsFormat enum.
func (e ExportPageParamsFormat) Valid() bool {
switch e {
case Html:
return true
case Markdown:
return true
default:
return false
}
}
// Attachment defines model for Attachment.
type Attachment struct {
Created string `json:"created"`
@@ -758,6 +776,14 @@ type SavePageContentJSONBody struct {
Content map[string]interface{} `json:"content"`
}
// ExportPageParams defines parameters for ExportPage.
type ExportPageParams struct {
Format *ExportPageParamsFormat `form:"format,omitempty" json:"format,omitempty"`
}
// ExportPageParamsFormat defines parameters for ExportPage.
type ExportPageParamsFormat string
// MovePageJSONBody defines parameters for MovePage.
type MovePageJSONBody struct {
// Index Position among the new parent's other children
@@ -785,6 +811,14 @@ type SetSpaceGroupJSONBody struct {
Role SpaceRole `json:"role"`
}
// ImportPagesMultipartBody defines parameters for ImportPages.
type ImportPagesMultipartBody struct {
File []openapi_types.File `json:"file"`
// Parent Parent page id; empty for the top level
Parent *string `json:"parent,omitempty"`
}
// SetSpaceMemberJSONBody defines parameters for SetSpaceMember.
type SetSpaceMemberJSONBody struct {
Email openapi_types.Email `json:"email"`
@@ -912,6 +946,9 @@ type UpdateSpaceJSONRequestBody UpdateSpaceJSONBody
// SetSpaceGroupJSONRequestBody defines body for SetSpaceGroup for application/json ContentType.
type SetSpaceGroupJSONRequestBody SetSpaceGroupJSONBody
// ImportPagesMultipartRequestBody defines body for ImportPages for multipart/form-data ContentType.
type ImportPagesMultipartRequestBody ImportPagesMultipartBody
// SetSpaceMemberJSONRequestBody defines body for SetSpaceMember for application/json ContentType.
type SetSpaceMemberJSONRequestBody SetSpaceMemberJSONBody
+130
View File
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"encoding/json"
"strings"
"testing"
)
const sample = `{"type":"doc","content":[
{"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"Plan & <scope>"}]},
{"type":"paragraph","content":[
{"type":"text","text":"Ship "},
{"type":"text","text":"bold","marks":[{"type":"bold"}]},
{"type":"text","text":" and "},
{"type":"text","text":"a link","marks":[{"type":"link","attrs":{"href":"https://docwell.test/x"}}]},
{"type":"text","text":" and "},
{"type":"text","text":"bad","marks":[{"type":"link","attrs":{"href":"javascript:alert(1)"}}]},
{"type":"text","text":" *stars*"}]},
{"type":"bulletList","content":[
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"one"}]},
{"type":"orderedList","attrs":{"start":3},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"nested"}]}]}]}]},
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"two"}]}]}]},
{"type":"codeBlock","attrs":{"language":"go"},"content":[{"type":"text","text":"x := 1 < 2"}]},
{"type":"blockquote","content":[{"type":"paragraph","content":[{"type":"text","text":"quoted"}]}]},
{"type":"image","attrs":{"src":"/api/v1/files/abc","alt":"diagram"}},
{"type":"horizontalRule"}
]}`
func mustParse(t *testing.T, raw string) Node {
t.Helper()
doc, err := Parse(json.RawMessage(raw))
if err != nil {
t.Fatal(err)
}
return doc
}
var opts = Options{FileURL: func(p string) string { return "https://api.docwell.test" + p }}
func TestMarkdown(t *testing.T) {
md := MarkdownPage("Title", mustParse(t, sample), opts)
for _, want := range []string{
"# Title\n",
`## Plan & \<scope\>` + "\n",
`Ship **bold** and [a link](https://docwell.test/x) and bad \*stars\*` + "\n",
"- one\n\n 3. nested\n- two\n",
"```go\nx := 1 < 2\n```\n",
"> quoted\n",
"![diagram](https://api.docwell.test/api/v1/files/abc)\n",
"---\n",
} {
if !strings.Contains(md, want) {
t.Errorf("markdown lacks %q:\n%s", want, md)
}
}
if strings.Contains(md, "javascript:") {
t.Error("unsafe links must be dropped")
}
}
func TestHTML(t *testing.T) {
h := HTMLPage("A <b>", mustParse(t, sample), opts)
for _, want := range []string{
"<title>A &lt;b&gt;</title>",
"<h2>Plan &amp; &lt;scope&gt;</h2>",
"<strong>bold</strong>",
`<a href="https://docwell.test/x">a link</a>`,
`<ol start="3">`,
`<pre><code class="language-go">x := 1 &lt; 2</code></pre>`,
`<img src="https://api.docwell.test/api/v1/files/abc" alt="diagram">`,
} {
if !strings.Contains(h, want) {
t.Errorf("html lacks %q:\n%s", want, h)
}
}
if strings.Contains(h, "javascript:") {
t.Error("unsafe links must be dropped")
}
}
func TestMarkdownRoundTrip(t *testing.T) {
doc := mustParse(t, sample)
back, err := FromMarkdown(Markdown(doc, Options{}))
if err != nil {
t.Fatal(err)
}
if got, want := Markdown(back, Options{}), Markdown(doc, Options{}); got != want {
t.Errorf("round trip changed the document:\n--- got\n%s\n--- want\n%s", got, want)
}
}
func TestFromHTMLSanitizes(t *testing.T) {
doc, err := FromHTML(`<div onclick="x()"><h1>Hi <script>alert(1)</script></h1>
<p>Text <a href="javascript:evil()">bad</a> <a href="https://ok.test">ok</a><img src="x" onerror="alert(1)"></p>
<style>p{}</style><iframe src="https://evil.test"></iframe>
<table><tr><td>a</td><td><b>b</b></td></tr></table><h5>deep</h5></div>`)
if err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(doc)
s := string(raw)
for _, bad := range []string{"alert", "evil", "onclick", "onerror", "iframe", "p{}"} {
if strings.Contains(s, bad) {
t.Errorf("import kept %q: %s", bad, s)
}
}
title, rest := Title(doc)
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") {
t.Errorf("content = %s", md)
}
}
func TestEmpty(t *testing.T) {
doc, err := Parse(nil)
if err != nil || doc.Type != "doc" {
t.Fatal(doc, err)
}
if md := Markdown(doc, Options{}); md != "\n" {
t.Errorf("empty markdown = %q", md)
}
back, _ := FromMarkdown("")
if len(back.Content) != 1 || back.Content[0].Type != "paragraph" {
t.Errorf("empty import = %+v", back)
}
}
+301
View File
@@ -0,0 +1,301 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"fmt"
"html"
"regexp"
"strconv"
"strings"
)
// Options adjust exported links.
type Options struct {
// FileURL rewrites attachment paths (/api/v1/files/<id>) so exported
// files link to the server; nil keeps them as they are.
FileURL func(path string) string
}
func (o Options) file(path string) string {
if o.FileURL != nil && strings.HasPrefix(path, "/api/v1/files/") {
return o.FileURL(path)
}
return path
}
// safeURL keeps links to the web, mail, the server's own paths and anchors;
// anything else (javascript:, data:, ...) is dropped.
var safeURL = regexp.MustCompile(`^(?i)(https?://|mailto:|/|#)`)
// ---- HTML ------------------------------------------------------------------
// HTML renders the document's body as HTML.
func HTML(doc Node, o Options) string {
var b strings.Builder
for _, n := range doc.Content {
writeHTML(&b, n, o)
}
return b.String()
}
// HTMLPage renders a standalone HTML file with a title.
func HTMLPage(title string, doc Node, o Options) string {
t := html.EscapeString(title)
return "<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>" + t + "</title>\n</head>\n<body>\n" +
"<h1>" + t + "</h1>\n" + HTML(doc, o) + "</body>\n</html>\n"
}
var htmlBlock = map[string]string{
"paragraph": "p", "blockquote": "blockquote", "bulletList": "ul", "orderedList": "ol", "listItem": "li",
}
func writeHTML(b *strings.Builder, n Node, o Options) {
children := func() {
for _, c := range n.Content {
writeHTML(b, c, o)
}
}
switch n.Type {
case "text":
writeHTMLText(b, n, o)
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
fmt.Fprintf(b, "<h%d>", level)
children()
fmt.Fprintf(b, "</h%d>\n", level)
case "orderedList":
if start := n.intAttr("start", 1); start != 1 {
fmt.Fprintf(b, "<ol start=\"%d\">\n", start)
} else {
b.WriteString("<ol>\n")
}
children()
b.WriteString("</ol>\n")
case "codeBlock":
lang := n.attr("language")
if lang != "" {
fmt.Fprintf(b, "<pre><code class=\"language-%s\">", html.EscapeString(lang))
} else {
b.WriteString("<pre><code>")
}
b.WriteString(html.EscapeString(PlainText(n)))
b.WriteString("</code></pre>\n")
case "horizontalRule":
b.WriteString("<hr>\n")
case "hardBreak":
b.WriteString("<br>")
case "image":
fmt.Fprintf(b, "<img src=\"%s\" alt=\"%s\">\n", html.EscapeString(o.file(n.attr("src"))), html.EscapeString(n.attr("alt")))
case "fileAttachment":
fmt.Fprintf(b, "<p><a href=\"%s\">%s</a></p>\n", html.EscapeString(o.file(n.attr("url"))), html.EscapeString(n.attr("name")))
default:
tag, ok := htmlBlock[n.Type]
if !ok {
// Unknown block types still keep their text.
children()
return
}
fmt.Fprintf(b, "<%s>", tag)
if tag == "ul" || tag == "ol" {
b.WriteString("\n")
}
children()
fmt.Fprintf(b, "</%s>\n", tag)
}
}
func writeHTMLText(b *strings.Builder, n Node, o Options) {
var open, close []string
for _, m := range n.Marks {
switch m.Type {
case "bold":
open, close = append(open, "<strong>"), append([]string{"</strong>"}, close...)
case "italic":
open, close = append(open, "<em>"), append([]string{"</em>"}, close...)
case "strike":
open, close = append(open, "<s>"), append([]string{"</s>"}, close...)
case "underline":
open, close = append(open, "<u>"), append([]string{"</u>"}, close...)
case "code":
open, close = append(open, "<code>"), append([]string{"</code>"}, 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...)
}
}
}
b.WriteString(strings.Join(open, ""))
b.WriteString(html.EscapeString(n.Text))
b.WriteString(strings.Join(close, ""))
}
// ---- Markdown --------------------------------------------------------------
// Markdown renders the document as CommonMark (with ~~strikethrough~~).
func Markdown(doc Node, o Options) string {
w := &mdWriter{o: o}
w.blocks(doc.Content, "", "")
return strings.TrimRight(w.b.String(), "\n") + "\n"
}
// MarkdownPage is Markdown with the title as a leading heading.
func MarkdownPage(title string, doc Node, o Options) string {
body := Markdown(doc, o)
if strings.TrimSpace(title) == "" {
return body
}
return "# " + escapeMD(title) + "\n\n" + body
}
type mdWriter struct {
b strings.Builder
o Options
}
// blocks writes block nodes; first prefixes the first line (a list marker),
// rest the following lines (indentation or "> ").
func (w *mdWriter) blocks(nodes []Node, first, rest string) {
for i, n := range nodes {
p := rest
if i == 0 {
p = first
}
if i > 0 {
w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
}
w.block(n, p, rest)
}
}
func (w *mdWriter) lines(text, first, rest string) {
for i, line := range strings.Split(text, "\n") {
if i == 0 {
w.b.WriteString(first)
} else {
w.b.WriteString(rest)
}
w.b.WriteString(line)
w.b.WriteString("\n")
}
}
func (w *mdWriter) block(n Node, first, rest string) {
switch n.Type {
case "paragraph":
w.lines(w.inline(n.Content), first, rest)
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
w.lines(strings.Repeat("#", level)+" "+w.inline(n.Content), first, rest)
case "blockquote":
w.blocks(n.Content, first+"> ", rest+"> ")
case "bulletList":
for i, item := range n.Content {
p := rest
if i == 0 {
p = first
}
w.blocks(item.Content, p+"- ", rest+" ")
}
case "orderedList":
start := n.intAttr("start", 1)
for i, item := range n.Content {
p := rest
if i == 0 {
p = first
}
marker := strconv.Itoa(start+i) + ". "
w.blocks(item.Content, p+marker, rest+strings.Repeat(" ", len(marker)))
}
case "codeBlock":
text := PlainText(n)
fence := "```"
for strings.Contains(text, fence) {
fence += "`"
}
w.lines(fence+n.attr("language")+"\n"+text+"\n"+fence, first, rest)
case "horizontalRule":
w.lines("---", first, rest)
case "image":
w.lines("!["+escapeMD(n.attr("alt"))+"]("+mdURL(w.o.file(n.attr("src")))+")", first, rest)
case "fileAttachment":
w.lines("["+escapeMD(n.attr("name"))+"]("+mdURL(w.o.file(n.attr("url")))+")", first, rest)
default:
if len(n.Content) > 0 {
w.blocks(n.Content, first, rest)
}
}
}
func (w *mdWriter) inline(nodes []Node) string {
var b strings.Builder
for _, n := range nodes {
switch n.Type {
case "hardBreak":
b.WriteString("\\\n")
case "text":
b.WriteString(w.text(n))
default:
b.WriteString(w.inline(n.Content))
}
}
return b.String()
}
func (w *mdWriter) text(n Node) string {
code := false
for _, m := range n.Marks {
if m.Type == "code" {
code = true
}
}
s := n.Text
if code {
tick := "`"
for strings.Contains(s, tick) {
tick += "`"
}
pad := ""
if strings.HasPrefix(s, "`") || strings.HasSuffix(s, "`") {
pad = " "
}
s = tick + pad + s + pad + tick
} else {
s = escapeMD(s)
}
// Emphasis cannot start or end with spaces; keep them outside the markers.
core := strings.TrimSpace(s)
lead := s[:strings.Index(s, core)]
trail := s[len(lead)+len(core):]
if core == "" {
return s
}
for _, m := range n.Marks {
switch m.Type {
case "bold":
core = "**" + core + "**"
case "italic":
core = "*" + core + "*"
case "strike":
core = "~~" + core + "~~"
case "link":
if href := w.o.file(m.attr("href")); safeURL.MatchString(href) {
core = "[" + core + "](" + mdURL(href) + ")"
}
}
}
return lead + core + trail
}
var mdSpecial = strings.NewReplacer(
`\`, `\\`, "`", "\\`", "*", `\*`, "_", `\_`, "[", `\[`, "]", `\]`, "<", `\<`, ">", `\>`, "#", `\#`, "~", `\~`, "|", `\|`,
)
func escapeMD(s string) string { return mdSpecial.Replace(s) }
func mdURL(u string) string {
if strings.ContainsAny(u, " ()<>") {
return "<" + strings.NewReplacer("<", "%3C", ">", "%3E").Replace(u) + ">"
}
return u
}
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"bytes"
"regexp"
"strconv"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// FromMarkdown reads CommonMark (with GitHub's strikethrough, autolinks and
// task lists, the latter as plain lists). Raw HTML in the Markdown is dropped.
func FromMarkdown(md string) (Node, error) {
var buf bytes.Buffer
gm := goldmark.New(goldmark.WithExtensions(extension.Strikethrough, extension.Linkify, extension.TaskList))
if err := gm.Convert([]byte(md), &buf); err != nil {
return Node{}, err
}
return FromHTML(buf.String())
}
// FromHTML reads an HTML document or fragment into the Docwell schema.
// Elements the schema has no node for are unwrapped (their text is kept);
// script, style and similar elements are dropped with their content.
func FromHTML(src string) (Node, error) {
root, err := html.Parse(strings.NewReader(src))
if err != nil {
return Node{}, err
}
body := find(root, atom.Body)
if body == nil {
body = root
}
r := &reader{}
doc := Node{Type: "doc", Content: r.blocks(body)}
if len(doc.Content) == 0 {
doc.Content = []Node{{Type: "paragraph"}}
}
return doc, nil
}
func find(n *html.Node, a atom.Atom) *html.Node {
if n.Type == html.ElementNode && n.DataAtom == a {
return n
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if f := find(c, a); f != nil {
return f
}
}
return nil
}
func attrOf(n *html.Node, key string) string {
for _, a := range n.Attr {
if a.Key == key {
return a.Val
}
}
return ""
}
var dropped = map[atom.Atom]bool{
atom.Script: true, atom.Style: true, atom.Noscript: true, atom.Template: true, atom.Iframe: true,
atom.Object: true, atom.Embed: true, atom.Head: true, atom.Title: true, atom.Svg: true, atom.Math: true,
atom.Button: true, atom.Select: true, atom.Textarea: true, atom.Input: true,
}
var blockAtoms = map[atom.Atom]bool{
atom.P: true, atom.H1: true, atom.H2: true, atom.H3: true, atom.H4: true, atom.H5: true, atom.H6: true,
atom.Ul: true, atom.Ol: true, atom.Li: true, atom.Blockquote: true, atom.Pre: true, atom.Hr: true,
atom.Div: true, atom.Section: true, atom.Article: true, atom.Main: true, atom.Header: true, atom.Footer: true,
atom.Aside: true, atom.Nav: true, atom.Figure: true, atom.Table: true, atom.Tr: true, atom.Img: true,
atom.Dl: true, atom.Dt: true, atom.Dd: true, atom.Details: true, atom.Summary: true, atom.Figcaption: true,
atom.Thead: true, atom.Tbody: true, atom.Tfoot: true, atom.Td: true, atom.Th: true,
}
type reader struct{}
type mark = Mark
// blocks reads the children of n as block nodes; loose inline content is
// gathered into paragraphs.
func (r *reader) blocks(n *html.Node) []Node {
var out []Node
var loose []Node
flush := func() {
if p := trimInline(loose); len(p) > 0 {
out = append(out, Node{Type: "paragraph", Content: p})
}
loose = nil
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && dropped[c.DataAtom] {
continue
}
if c.Type == html.ElementNode && blockAtoms[c.DataAtom] {
flush()
out = append(out, r.block(c)...)
continue
}
loose = append(loose, r.inline(c, nil)...)
}
flush()
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 languageClass = regexp.MustCompile(`(?:^|\s)(?:language|lang)-([A-Za-z0-9_+#.-]{1,40})`)
func (r *reader) block(n *html.Node) []Node {
switch n.DataAtom {
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)
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}
case atom.Ul, atom.Ol:
list := Node{Type: "bulletList"}
if n.DataAtom == atom.Ol {
list.Type = "orderedList"
start := 1
if s, err := strconv.Atoi(attrOf(n, "start")); err == nil {
start = s
}
list.Attrs = map[string]any{"start": float64(start)}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type != html.ElementNode {
continue
}
list.Content = append(list.Content, r.listItem(c))
}
if len(list.Content) == 0 {
return nil
}
return []Node{list}
case atom.Li:
return []Node{{Type: "bulletList", Content: []Node{r.listItem(n)}}}
case atom.Blockquote:
content := r.blocks(n)
if len(content) == 0 {
content = []Node{{Type: "paragraph"}}
}
return []Node{{Type: "blockquote", Content: content}}
case atom.Pre:
code := Node{Type: "codeBlock", Attrs: map[string]any{"language": nil}}
if c := find(n, atom.Code); c != nil {
if m := languageClass.FindStringSubmatch(attrOf(c, "class")); m != nil {
code.Attrs["language"] = m[1]
}
}
if text := strings.TrimSuffix(textOf(n), "\n"); text != "" {
code.Content = []Node{{Type: "text", Text: text}}
}
return []Node{code}
case atom.Hr:
return []Node{{Type: "horizontalRule"}}
case atom.Img:
src := attrOf(n, "src")
if !safeURL.MatchString(src) {
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)
}
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" {
item.Content = append([]Node{{Type: "paragraph"}}, item.Content...)
}
return item
}
func (r *reader) inlineChildren(n *html.Node, marks []mark) []Node {
var out []Node
for c := n.FirstChild; c != nil; c = c.NextSibling {
out = append(out, r.inline(c, marks)...)
}
return out
}
var whitespace = regexp.MustCompile(`[ \t\r\n\f]+`)
func (r *reader) inline(n *html.Node, marks []mark) []Node {
switch n.Type {
case html.TextNode:
text := whitespace.ReplaceAllString(n.Data, " ")
if text == "" {
return nil
}
return []Node{{Type: "text", Text: text, Marks: append([]mark(nil), marks...)}}
case html.ElementNode:
default:
return nil
}
if dropped[n.DataAtom] {
return nil
}
add := func(m mark) []mark {
for _, have := range marks {
if have.Type == m.Type {
return marks
}
}
return append(append([]mark(nil), marks...), m)
}
switch n.DataAtom {
case atom.Br:
return []Node{{Type: "hardBreak"}}
case atom.Strong, atom.B:
marks = add(mark{Type: "bold"})
case atom.Em, atom.I:
marks = add(mark{Type: "italic"})
case atom.S, atom.Del, atom.Strike:
marks = add(mark{Type: "strike"})
case atom.U, atom.Ins:
marks = add(mark{Type: "underline"})
case atom.Code, atom.Kbd, atom.Samp:
marks = add(mark{Type: "code"})
case atom.A:
if href := attrOf(n, "href"); safeURL.MatchString(href) {
marks = add(mark{Type: "link", Attrs: map[string]any{
"href": href, "target": "_blank", "rel": "noopener noreferrer nofollow", "class": nil,
}})
}
case atom.Img:
// An image nested in inline markup (a link, bold text) cannot be a
// block here; keep its alt text.
if alt := attrOf(n, "alt"); alt != "" {
return []Node{{Type: "text", Text: alt, Marks: append([]mark(nil), marks...)}}
}
return nil
}
// Other elements (span, and blocks inside inline content such as <p> in
// <a>) keep their text inline.
return r.inlineChildren(n, marks)
}
// trimInline drops whitespace at the edges of a paragraph and merges runs
// with equal marks.
func trimInline(nodes []Node) []Node {
for len(nodes) > 0 && nodes[0].Type == "text" && strings.TrimSpace(nodes[0].Text) == "" {
nodes = nodes[1:]
}
for len(nodes) > 0 && nodes[len(nodes)-1].Type == "text" && strings.TrimSpace(nodes[len(nodes)-1].Text) == "" {
nodes = nodes[:len(nodes)-1]
}
if len(nodes) == 0 {
return nil
}
if nodes[0].Type == "text" {
nodes[0].Text = strings.TrimLeft(nodes[0].Text, " ")
}
if last := len(nodes) - 1; nodes[last].Type == "text" {
nodes[last].Text = strings.TrimRight(nodes[last].Text, " ")
}
var out []Node
for _, n := range nodes {
if l := len(out) - 1; l >= 0 && n.Type == "text" && out[l].Type == "text" && sameMarks(out[l].Marks, n.Marks) {
out[l].Text += n.Text
continue
}
if n.Type == "text" && n.Text == "" {
continue
}
out = append(out, n)
}
return out
}
func sameMarks(a, b []mark) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i].Type != b[i].Type || (a[i].Type == "link" && a[i].attr("href") != b[i].attr("href")) {
return false
}
}
return true
}
func textOf(n *html.Node) string {
if n.Type == html.TextNode {
return n.Data
}
var b strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.ElementNode && c.DataAtom == atom.Br {
b.WriteString("\n")
continue
}
b.WriteString(textOf(c))
}
return b.String()
}
+88
View File
@@ -0,0 +1,88 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// Package convert turns page documents (Tiptap/ProseMirror JSON in the Docwell
// schema, see Packages/editor) into Markdown and HTML, and Markdown and HTML
// back into documents. Imports keep only what the schema knows, which also
// drops scripts, styles and event handlers from pasted or uploaded HTML.
package convert
import "encoding/json"
// Node is one ProseMirror node or text run.
type Node struct {
Type string `json:"type"`
Attrs map[string]any `json:"attrs,omitempty"`
Content []Node `json:"content,omitempty"`
Text string `json:"text,omitempty"`
Marks []Mark `json:"marks,omitempty"`
}
type Mark struct {
Type string `json:"type"`
Attrs map[string]any `json:"attrs,omitempty"`
}
// Parse reads a document; null or empty input is an empty document.
func Parse(raw json.RawMessage) (Node, error) {
doc := Node{Type: "doc"}
if len(raw) == 0 || string(raw) == "null" {
return doc, nil
}
err := json.Unmarshal(raw, &doc)
return doc, err
}
func (n Node) attr(key string) string {
switch v := n.Attrs[key].(type) {
case string:
return v
case float64:
return json.Number(formatNumber(v)).String()
}
return ""
}
func (n Node) intAttr(key string, def int) int {
if v, ok := n.Attrs[key].(float64); ok {
return int(v)
}
return def
}
func (m Mark) attr(key string) string {
if v, ok := m.Attrs[key].(string); ok {
return v
}
return ""
}
func formatNumber(f float64) string {
b, _ := json.Marshal(f)
return string(b)
}
// Title takes a leading level-1 heading as the page title and returns the
// document without it; title is "" when the document does not start with one.
func Title(doc Node) (string, Node) {
if len(doc.Content) == 0 {
return "", doc
}
first := doc.Content[0]
if first.Type != "heading" || first.intAttr("level", 1) != 1 {
return "", doc
}
doc.Content = doc.Content[1:]
return PlainText(first), doc
}
// PlainText is the node's text with no formatting.
func PlainText(n Node) string {
if n.Type == "text" {
return n.Text
}
var s string
for _, c := range n.Content {
s += PlainText(c)
}
return s
}
+1
View File
@@ -30,6 +30,7 @@ type Service struct {
// maxUpload caps one attachment in bytes (0 = 50 MB).
maxUpload int64
search Searcher
publicURL string
}
func New(pb *pocketbase.Client, forget func(userID string), docs Docs) *Service {
+152
View File
@@ -0,0 +1,152 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"encoding/json"
"path"
"regexp"
"strings"
"unicode/utf8"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/convert"
)
// ---- Import and export -----------------------------------------------------
// maxImportBytes caps one imported file.
const maxImportBytes = 5 << 20
// SetPublicURL is docwell-server's external URL; exported files link
// attachments there.
func (s *Service) SetPublicURL(u string) { s.publicURL = strings.TrimRight(u, "/") }
// Export is a page rendered as a file.
type Export struct {
Filename string
ContentType string
Body []byte
}
var unsafeFilename = regexp.MustCompile(`[^\p{L}\p{N} ._-]+`)
func exportName(title, ext string) string {
name := strings.TrimSpace(unsafeFilename.ReplaceAllString(title, ""))
if name == "" {
name = "Untitled"
}
if utf8.RuneCountInString(name) > 100 {
name = string([]rune(name)[:100])
}
return name + ext
}
// ExportPage renders a page as Markdown ("markdown") or HTML ("html") (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 {
return Export{}, err
}
raw, err := s.docs.Content(ctx, p.ID)
if err != nil {
return Export{}, err
}
doc, err := convert.Parse(raw)
if err != nil {
return Export{}, err
}
opts := convert.Options{FileURL: func(path string) string { return s.publicURL + path }}
switch format {
case "markdown", "md", "":
return Export{
Filename: exportName(p.Title, ".md"), ContentType: "text/markdown; charset=utf-8",
Body: []byte(convert.MarkdownPage(p.Title, doc, opts)),
}, nil
case "html":
return Export{
Filename: exportName(p.Title, ".html"), ContentType: "text/html; charset=utf-8",
Body: []byte(convert.HTMLPage(p.Title, doc, opts)),
}, nil
}
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown or html."})
}
// ImportFile is one uploaded document.
type ImportFile struct {
Name string
Data []byte
}
// ImportPages creates a page per file under parent ("" = top level) (editor).
// Markdown (.md, .markdown, .txt) and HTML (.html, .htm) are understood; a
// leading level-1 heading becomes the title, otherwise the file name does.
func (s *Service) ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []ImportFile) ([]Page, error) {
a, err := s.spaceFor(ctx, c, spaceID)
if err != nil {
return nil, err
}
if err := access.EditPages(a.role); err != nil {
return nil, err
}
if len(files) == 0 {
return nil, apperr.InvalidFields(map[string]string{"file": "Choose at least one file."})
}
type parsed struct {
title string
doc convert.Node
}
var docs []parsed
for _, f := range files {
if len(f.Data) > maxImportBytes {
return nil, apperr.InvalidFields(map[string]string{"file": f.Name + " is larger than 5 MB."})
}
if !utf8.Valid(f.Data) {
return nil, apperr.InvalidFields(map[string]string{"file": f.Name + " is not UTF-8 text."})
}
ext := strings.ToLower(path.Ext(f.Name))
var doc convert.Node
switch ext {
case ".md", ".markdown", ".txt":
doc, err = convert.FromMarkdown(string(f.Data))
case ".html", ".htm":
doc, err = convert.FromHTML(string(f.Data))
default:
return nil, apperr.InvalidFields(map[string]string{"file": f.Name + ": only Markdown and HTML files can be imported."})
}
if err != nil {
return nil, apperr.InvalidFields(map[string]string{"file": f.Name + " could not be read."})
}
title, body := convert.Title(doc)
if title == "" {
title = strings.TrimSuffix(path.Base(strings.ReplaceAll(f.Name, "\\", "/")), path.Ext(f.Name))
}
if len(body.Content) == 0 {
body.Content = []convert.Node{{Type: "paragraph"}}
}
docs = append(docs, parsed{title: strings.TrimSpace(title), doc: body})
}
out := make([]Page, 0, len(docs))
for _, d := range docs {
title := d.title
if len(title) > 500 {
title = title[:500]
}
page, err := s.CreatePage(ctx, c, a.space.ID, CreatePageInput{Parent: parent, Title: title})
if err != nil {
return out, err
}
raw, err := json.Marshal(d.doc)
if err != nil {
return out, err
}
if err := s.docs.Replace(ctx, page.ID, c.ID, raw, "import"); err != nil {
return out, err
}
out = append(out, page)
}
return out, nil
}
+1
View File
@@ -149,6 +149,7 @@ func (a *api) routes(mux *routeMux) {
a.groupRoutes(mux)
a.favoriteRoutes(mux)
a.searchRoutes(mux)
a.transferRoutes(mux)
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
+1
View File
@@ -38,6 +38,7 @@ type DirectoryService interface {
FavoriteService
AttachmentService
SearchService
TransferService
}
func caller(r *http.Request) access.Caller {
+69
View File
@@ -0,0 +1,69 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"io"
"mime"
"net/http"
"strconv"
"docwell/server/internal/access"
"docwell/server/internal/directory"
)
// TransferService is the part of directory.Service that imports and exports pages.
type TransferService interface {
ExportPage(ctx context.Context, c access.Caller, id, format string) (directory.Export, error)
ImportPages(ctx context.Context, c access.Caller, spaceID, parent string, files []directory.ImportFile) ([]directory.Page, error)
}
// maxImportRequest caps one import request: each file may be 5 MB, and up to
// 20 files may come at once, but not more than 25 MB in all.
const maxImportRequest = 25 << 20
func (a *api) transferRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/pages/{id}/export", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
e, err := a.dir.ExportPage(r.Context(), caller(r), r.PathValue("id"), r.URL.Query().Get("format"))
if err != nil {
a.writeError(w, err)
return
}
h := w.Header()
h.Set("Content-Type", e.ContentType)
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": e.Filename}))
h.Set("Content-Length", strconv.Itoa(len(e.Body)))
h.Set("X-Content-Type-Options", "nosniff")
_, _ = w.Write(e.Body)
}))
mux.HandleFunc("POST /api/v1/spaces/{id}/import", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxImportRequest)
if err := r.ParseMultipartForm(maxImportRequest); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "expected multipart/form-data up to 25 MB"})
return
}
defer func() { _ = r.MultipartForm.RemoveAll() }()
var files []directory.ImportFile
for _, fh := range r.MultipartForm.File["file"] {
if len(files) == 20 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid", "message": "import at most 20 files at once"})
return
}
f, err := fh.Open()
if err != nil {
a.writeError(w, err)
return
}
data, err := io.ReadAll(io.LimitReader(f, 5<<20+1))
_ = f.Close()
if err != nil {
a.writeError(w, err)
return
}
files = append(files, directory.ImportFile{Name: fh.Filename, Data: data})
}
pages, err := a.dir.ImportPages(r.Context(), caller(r), r.PathValue("id"), r.FormValue("parent"), files)
a.respondStatus(w, http.StatusCreated, pages, err)
}))
}
+13
View File
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/** Hands a fetched file to the browser as a download. */
export function saveBlob(blob: Blob, filename: string) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
+6 -2
View File
@@ -204,7 +204,8 @@
"editor": "Editor",
"commenter": "Commenter",
"viewer": "Viewer"
}
},
"import": "Import"
},
"page": {
"title": "Page title",
@@ -241,7 +242,10 @@
"notFound": "This page does not exist or you don't have access to it.",
"favorite": "Add to favorites",
"unfavorite": "Remove from favorites",
"attach": "Attach a file or image"
"attach": "Attach a file or image",
"more": "More actions",
"exportMarkdown": "Export as Markdown",
"exportHtml": "Export as HTML"
},
"trash": {
"hint": "Pages inside a trashed page come back when you restore it.",
+6 -2
View File
@@ -204,7 +204,8 @@
"editor": "Edytor",
"commenter": "Komentujący",
"viewer": "Czytelnik"
}
},
"import": "Importuj"
},
"page": {
"title": "Tytuł strony",
@@ -241,7 +242,10 @@
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu.",
"favorite": "Dodaj do ulubionych",
"unfavorite": "Usuń z ulubionych",
"attach": "Dołącz plik lub obraz"
"attach": "Dołącz plik lub obraz",
"more": "Więcej działań",
"exportMarkdown": "Eksportuj jako Markdown",
"exportHtml": "Eksportuj jako HTML"
},
"trash": {
"hint": "Strony wewnątrz przywróconej strony wracają razem z nią.",
+16 -1
View File
@@ -2,7 +2,7 @@
<script setup lang="ts">
import type { Page } from "@docwell/api-client";
import { CollabProvider, DocwellEditor, insertFiles, userColor } from "@docwell/editor";
import { DwBreadcrumbs, DwButton, DwCallout, DwIcon } from "@docwell/ui";
import { DwBreadcrumbs, DwButton, DwCallout, DwIcon, DwMenu, type MenuItem } from "@docwell/ui";
import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
@@ -10,6 +10,7 @@ import { useApi, useToken } from "../../api";
import PageHistory from "../../components/PageHistory.vue";
import PageList from "../../components/PageList.vue";
import { useFileHost } from "../../composables/useFiles";
import { saveBlob } from "../../lib/download";
import { useRuntimeConfig } from "../../platform";
import { useAuthStore } from "../../stores/auth";
import { useFavoritesStore } from "../../stores/favorites";
@@ -188,6 +189,19 @@ const toggleFavorite = () =>
if (page.value?.id === p.id) page.value = { ...page.value, favorite: !p.favorite };
});
const exportAs = (format: "markdown" | "html") =>
run(async () => {
// Save first, so the file has the latest title.
await saveTitle();
const { blob, filename } = await api.pages.export(page.value!.id, format);
saveBlob(blob, filename);
});
const menu = computed<MenuItem[]>(() => [
{ label: t("page.exportMarkdown"), icon: "download", onSelect: () => exportAs("markdown") },
{ label: t("page.exportHtml"), icon: "download", onSelect: () => exportAs("html") },
]);
const addChild = () =>
run(async () => {
const child = await spaces.createPage(page.value!.space, page.value!.id);
@@ -270,6 +284,7 @@ const purge = () =>
>
{{ $t("page.history.title") }}
</DwButton>
<DwMenu :items="menu" :label="$t('page.more')" data-testid="page-menu" />
</Teleport>
<article class="mx-auto max-w-doc px-4 pt-6 pb-16 sm:px-16 sm:pt-10">
+36 -3
View File
@@ -37,6 +37,25 @@ watch(
const headerLink =
"inline-flex h-control-sm items-center gap-1 rounded-sm px-2 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink";
const picker = ref<HTMLInputElement | null>(null);
const importing = ref(false);
async function importPicked() {
const input = picker.value;
if (!input?.files?.length) return;
const files = [...input.files];
input.value = "";
importing.value = true;
try {
const pages = await api.spaces.import(props.id, files);
await spaces.loadTree(props.id);
if (pages.length === 1) router.push({ name: "page", params: { id: pages[0]!.id } });
} catch (e) {
emit("error", e);
} finally {
importing.value = false;
}
}
async function newPage() {
try {
const page = await spaces.createPage(props.id);
@@ -72,9 +91,23 @@ async function newPage() {
<div class="mt-10 flex items-center justify-between gap-2">
<h2 class="dw-label">{{ $t("space.pages") }}</h2>
<DwButton v-if="spaceAtLeast(space.role, 'editor')" variant="ghost" size="sm" icon="plus" @click="newPage">
{{ $t("app.newPage") }}
</DwButton>
<div v-if="spaceAtLeast(space.role, 'editor')" class="flex gap-1">
<input
ref="picker"
type="file"
multiple
accept=".md,.markdown,.txt,.html,.htm,text/markdown,text/html"
class="hidden"
data-testid="import-input"
@change="importPicked"
/>
<DwButton variant="ghost" size="sm" icon="upload" :disabled="importing" @click="picker?.click()">
{{ $t("space.import") }}
</DwButton>
<DwButton variant="ghost" size="sm" icon="plus" @click="newPage">
{{ $t("app.newPage") }}
</DwButton>
</div>
</div>
<PageList v-if="pages.length" :items="pages" class="mt-2" />
<div
+52
View File
@@ -1391,6 +1391,58 @@ paths:
responses:
"202": { description: Started }
"403": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/export:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: exportPage
tags: [pages]
summary: Download the page as Markdown or HTML
description: Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open.
security: [{ bearer: [] }]
parameters:
- { name: format, in: query, schema: { type: string, enum: [markdown, html], default: markdown } }
responses:
"200":
description: The file
content:
text/markdown:
schema: { type: string }
text/html:
schema: { type: string }
"400": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/import:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: importPages
tags: [pages]
summary: Create pages from Markdown or HTML files (editor)
description: >-
One page per file (.md, .markdown, .txt, .html, .htm; at most 20 files, 5 MB each,
25 MB in all). A leading level-1 heading becomes the title, otherwise the file name.
HTML is reduced to what the editor supports; scripts and styles are dropped.
security: [{ bearer: [] }]
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
required: [file]
properties:
file: { type: array, items: { type: string, format: binary } }
parent: { type: string, description: Parent page id; empty for the top level }
responses:
"201":
description: The created pages
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Page" } }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
components:
securitySchemes:
bearer: