From 40d515d15b817149bcfcb521787183113783e8de Mon Sep 17 00:00:00 2001
From: tajniak81 <13187254+tajniak81@users.noreply.github.com>
Date: Sun, 1 Nov 2026 14:14:14 +0100
Subject: [PATCH] Add toggles, embeds, link cards, block links, archive,
version diff, space export and desktop 1.0
Editor:
- Toggles (Tiptap Details). Open state is per reader, not saved.
- Embeds for YouTube, Vimeo, Loom, Figma, CodePen, Spotify, Google Docs
and Maps, in sandboxed frames. Other addresses become link cards.
- Link cards with title, description and picture read by docwell-server
(GET /link-preview). The fetcher refuses private, loopback, link-local
and CGNAT addresses after DNS resolution, redirects included.
- Block links: a margin button gives a block a short id and copies
/p/#b-. Opening one jumps to the block and flashes it.
- Markdown, HTML and PDF exports handle the new blocks; HTML import reads
as a toggle.
Pages and spaces:
- History gets a Changes view: block and word diff against the previous
version or the page as it is now.
- Archive: archived pages leave the tree and become read-only but stay
readable; a space's Archive lists them with Unarchive. New migration
(pages.archived_at) and page.archived / page.unarchived webhook events.
- Full space export (GET /spaces/{id}/export): a zip of Markdown or HTML
files with subpages in folders, an index, and attachments under _files/.
Links between exported pages and to attachments become relative paths.
Desktop 1.0:
- Several servers, each with its own sign-in; old settings files carry over.
- Session tokens in the system keychain (go-keyring), moved out of
localStorage on first start.
- Native menu bar (File, Edit, View, Window, Help) with a Server submenu.
- docwell:// links may point at a block.
- Release workflow builds Windows NSIS, macOS DMG and Linux deb, rpm and
AppImage installers and attaches them to the release;
build/set-version.mjs stamps the version into their metadata.
Not yet run: the release workflow, the desktop menus by eye, and macOS or
Linux builds.
Co-Authored-By: Claude Opus 5.5
---
.github/workflows/release.yml | 81 +++-
Database/pb_migrations/1763200000_archive.js | 19 +
Desktop-App/build/darwin/Taskfile.yml | 2 +-
Desktop-App/build/linux/Taskfile.yml | 2 +-
Desktop-App/build/set-version.mjs | 45 +++
Desktop-App/build/windows/Taskfile.yml | 2 +-
Desktop-App/deeplink.go | 15 +-
Desktop-App/deeplink_test.go | 15 +-
.../bindings/docwell/desktop/index.ts | 5 +-
.../bindings/docwell/desktop/models.ts | 60 ++-
.../docwell/desktop/settingsservice.ts | 44 ++-
.../bindings/docwell/desktop/tokenservice.ts | 36 ++
Desktop-App/frontend/src/main.ts | 83 +++-
Desktop-App/go.mod | 6 +-
Desktop-App/go.sum | 6 +
Desktop-App/keychain.go | 75 ++++
Desktop-App/keychain_test.go | 61 +++
Desktop-App/main.go | 15 +-
Desktop-App/menu.go | 132 +++++++
Desktop-App/settings.go | 205 ++++++++--
Desktop-App/settings_test.go | 34 ++
Packages/api-client/src/index.ts | 10 +
Packages/api-client/src/schema.d.ts | 241 ++++++++++-
Packages/editor-bridge/src/bridge.test.ts | 2 +-
Packages/editor/package.json | 1 +
Packages/editor/src/DocwellEditor.vue | 12 +
Packages/editor/src/blocklinks.ts | 228 +++++++++++
Packages/editor/src/editor.css | 167 ++++++++
Packages/editor/src/embeds.ts | 374 ++++++++++++++++++
Packages/editor/src/extensions.ts | 18 +-
Packages/editor/src/index.ts | 2 +
Packages/editor/src/labels.ts | 17 +
Packages/editor/src/slash.ts | 13 +
Packages/editor/src/toggle.ts | 25 ++
Packages/ui/src/icons.ts | 4 +
Phone-App/lib/api/generated/models.dart | 82 ++++
Server/cmd/docwell-server/main.go | 2 +
Server/internal/api/api.gen.go | 76 +++-
Server/internal/convert/export.go | 78 +++-
Server/internal/convert/export_test.go | 40 ++
Server/internal/convert/import.go | 14 +
Server/internal/convert/pdf.go | 19 +
Server/internal/directory/content.go | 10 +-
Server/internal/directory/pages.go | 152 ++++++-
Server/internal/directory/spaceexport.go | 281 +++++++++++++
Server/internal/directory/spaceexport_test.go | 35 ++
Server/internal/httpapi/auth.go | 1 +
Server/internal/httpapi/links.go | 15 +
Server/internal/httpapi/router.go | 5 +
Server/internal/httpapi/spaces.go | 15 +
Server/internal/httpapi/transfer.go | 16 +
Server/internal/unfurl/unfurl.go | 205 ++++++++++
Server/internal/unfurl/unfurl_test.go | 82 ++++
Server/internal/webhooks/webhooks.go | 1 +
Web-App/frontend/src/app.ts | 6 +-
Web-App/frontend/src/components/AppLayout.vue | 9 +
.../frontend/src/components/PageHistory.vue | 153 ++++++-
.../src/components/WorkspaceWebhooks.vue | 2 +
.../src/composables/useEditorHosts.ts | 10 +
Web-App/frontend/src/lib/commands.ts | 16 +
Web-App/frontend/src/lib/diff.test.ts | 69 ++++
Web-App/frontend/src/lib/diff.ts | 178 +++++++++
Web-App/frontend/src/locales/en.json | 75 +++-
Web-App/frontend/src/locales/pl.json | 75 +++-
Web-App/frontend/src/platform.ts | 38 ++
Web-App/frontend/src/router.ts | 13 +
Web-App/frontend/src/views/auth/LoginView.vue | 11 +-
Web-App/frontend/src/views/page/PageView.vue | 87 +++-
.../src/views/settings/AccountView.vue | 12 +
.../src/views/settings/ServersView.vue | 118 ++++++
.../frontend/src/views/space/ArchiveView.vue | 86 ++++
.../frontend/src/views/space/SpaceView.vue | 78 ++--
api/openapi.yaml | 116 +++++-
package-lock.json | 30 ++
74 files changed, 4249 insertions(+), 119 deletions(-)
create mode 100644 Database/pb_migrations/1763200000_archive.js
create mode 100644 Desktop-App/build/set-version.mjs
create mode 100644 Desktop-App/frontend/bindings/docwell/desktop/tokenservice.ts
create mode 100644 Desktop-App/keychain.go
create mode 100644 Desktop-App/keychain_test.go
create mode 100644 Desktop-App/menu.go
create mode 100644 Packages/editor/src/blocklinks.ts
create mode 100644 Packages/editor/src/embeds.ts
create mode 100644 Packages/editor/src/toggle.ts
create mode 100644 Server/internal/directory/spaceexport.go
create mode 100644 Server/internal/directory/spaceexport_test.go
create mode 100644 Server/internal/unfurl/unfurl.go
create mode 100644 Server/internal/unfurl/unfurl_test.go
create mode 100644 Web-App/frontend/src/lib/commands.ts
create mode 100644 Web-App/frontend/src/lib/diff.test.ts
create mode 100644 Web-App/frontend/src/lib/diff.ts
create mode 100644 Web-App/frontend/src/views/settings/ServersView.vue
create mode 100644 Web-App/frontend/src/views/space/ArchiveView.vue
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 48a235e..f86b4ab 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,6 +1,8 @@
-# Publishes the Docker images for a release: push a tag like v0.1.0.
+# Publishes a release: push a tag like v0.1.0.
# Images go to ghcr.io//, for linux/amd64 and
# linux/arm64, tagged with the version (0.1.0, 0.1) and latest.
+# Desktop installers (Windows NSIS, macOS DMG, Linux deb, rpm and AppImage)
+# are attached to the GitHub release for the tag.
name: Release
@@ -77,3 +79,80 @@ jobs:
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=${{ matrix.name }}
cache-to: type=gha,mode=max,scope=${{ matrix.name }}
+
+ desktop:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - os: windows-latest
+ task: windows:package
+ files: Desktop-App/bin/*-installer.exe
+ - os: macos-latest
+ task: darwin:package:dmg
+ files: Desktop-App/bin/*.dmg
+ - os: ubuntu-latest
+ task: linux:create:deb linux:create:rpm linux:create:appimage
+ files: |
+ Desktop-App/bin/*.deb
+ Desktop-App/bin/*.rpm
+ Desktop-App/bin/*.AppImage
+ runs-on: ${{ matrix.os }}
+ permissions:
+ contents: write
+ defaults:
+ run:
+ shell: bash
+ env:
+ GOWORK: "off"
+ steps:
+ - uses: actions/checkout@v5
+ - uses: actions/setup-go@v6
+ with:
+ go-version: "1.26"
+ - uses: actions/setup-node@v5
+ with:
+ node-version: 24
+ cache: npm
+
+ - name: Version
+ id: version
+ run: |
+ v="${{ inputs.version || github.ref_name }}"
+ echo "value=${v#v}" >> "$GITHUB_OUTPUT"
+
+ - name: Linux packaging dependencies
+ if: runner.os == 'Linux'
+ run: sudo apt-get update && sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev libfuse2 rpm
+ - name: NSIS
+ if: runner.os == 'Windows'
+ run: choco install nsis -y --no-progress && echo "C:/Program Files (x86)/NSIS" >> "$GITHUB_PATH"
+ - name: Wails CLI
+ run: go install github.com/wailsapp/wails/v3/cmd/wails3@v3.0.0
+
+ - run: npm ci
+ - name: Stamp the version
+ working-directory: Desktop-App
+ run: node build/set-version.mjs "${{ steps.version.outputs.value }}"
+
+ # The update feed and its ed25519 public key are repository variables;
+ # without them the build never updates itself (see updates.go).
+ - name: Package
+ working-directory: Desktop-App
+ run: |
+ flags="-X main.version=${{ steps.version.outputs.value }}"
+ flags="$flags -X main.docsURL=https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/"
+ if [ -n "${{ vars.DESKTOP_UPDATE_MANIFEST_URL }}" ]; then
+ flags="$flags -X main.updateManifestURL=${{ vars.DESKTOP_UPDATE_MANIFEST_URL }} -X main.updatePublicKey=${{ vars.DESKTOP_UPDATE_PUBLIC_KEY }}"
+ fi
+ wails3 task ${{ matrix.task }} EXTRA_LDFLAGS="$flags"
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: desktop-${{ runner.os }}
+ path: ${{ matrix.files }}
+ - name: Attach to the release
+ if: github.event_name == 'push'
+ uses: softprops/action-gh-release@v2
+ with:
+ files: ${{ matrix.files }}
diff --git a/Database/pb_migrations/1763200000_archive.js b/Database/pb_migrations/1763200000_archive.js
new file mode 100644
index 0000000..00ee581
--- /dev/null
+++ b/Database/pb_migrations/1763200000_archive.js
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+///
+
+// pages.archived_at: an archived page and its subtree leave the page tree but
+// stay readable until someone unarchives them (see directory/pages.go).
+
+migrate(
+ (app) => {
+ const pages = app.findCollectionByNameOrId("pages");
+ pages.fields.add(new DateField({ name: "archived_at" }));
+ app.save(pages);
+ },
+ (app) => {
+ const pages = app.findCollectionByNameOrId("pages");
+ pages.fields.removeByName("archived_at");
+ app.save(pages);
+ },
+);
diff --git a/Desktop-App/build/darwin/Taskfile.yml b/Desktop-App/build/darwin/Taskfile.yml
index e3ee1ee..5808a8b 100644
--- a/Desktop-App/build/darwin/Taskfile.yml
+++ b/Desktop-App/build/darwin/Taskfile.yml
@@ -43,7 +43,7 @@ tasks:
cmds:
- '{{if eq .OBFUSCATED "true"}}garble {{.GARBLE_ARGS}} build{{else}}go build{{end}} {{.BUILD_FLAGS}} -o "{{.OUTPUT}}"'
vars:
- BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s"{{end}}'
+ BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s {{.EXTRA_LDFLAGS}}"{{end}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
env:
diff --git a/Desktop-App/build/linux/Taskfile.yml b/Desktop-App/build/linux/Taskfile.yml
index 496ee95..bce1b0e 100644
--- a/Desktop-App/build/linux/Taskfile.yml
+++ b/Desktop-App/build/linux/Taskfile.yml
@@ -59,7 +59,7 @@ tasks:
cmds:
- '{{if eq .OBFUSCATED "true"}}garble {{.GARBLE_ARGS}} build{{else}}go build{{end}} {{.BUILD_FLAGS}} -o {{.OUTPUT}}'
vars:
- BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s"{{end}}'
+ BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s {{.EXTRA_LDFLAGS}}"{{end}}'
DEFAULT_OUTPUT: '{{.BIN_DIR}}/{{.APP_NAME}}'
OUTPUT: '{{ .OUTPUT | default .DEFAULT_OUTPUT }}'
env:
diff --git a/Desktop-App/build/set-version.mjs b/Desktop-App/build/set-version.mjs
new file mode 100644
index 0000000..03ac05a
--- /dev/null
+++ b/Desktop-App/build/set-version.mjs
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// Stamps a release version into the installers' metadata before packaging:
+// node build/set-version.mjs 1.2.3
+// (Windows file info and NSIS, the macOS Info.plist, the Linux packages and
+// build/config.yml). The binary's own version comes from -ldflags main.version.
+
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const version = process.argv[2]?.replace(/^v/, "");
+if (!version || !/^\d+\.\d+\.\d+([-.+][0-9A-Za-z.-]+)?$/.test(version)) {
+ console.error("usage: node build/set-version.mjs ");
+ process.exit(1);
+}
+// Windows file versions are four numbers; pre-release suffixes are left out.
+const numeric = version.match(/^\d+\.\d+\.\d+/)[0];
+
+const dir = dirname(fileURLToPath(import.meta.url));
+const edits = [
+ ["config.yml", /(version: )"[^"]*"( # The application version)/, `$1"${version}"$2`],
+ ["windows/info.json", /("file_version": )"[^"]*"/, `$1"${numeric}"`],
+ ["windows/info.json", /("ProductVersion": )"[^"]*"/, `$1"${version}"`],
+ ["windows/nsis/wails_tools.nsh", /(!define INFO_PRODUCTVERSION )"[^"]*"/, `$1"${numeric}"`],
+ ["linux/nfpm/nfpm.yaml", /^version: "[^"]*"/m, `version: "${version}"`],
+ [
+ "darwin/Info.plist",
+ /(CFBundleShortVersionString<\/key>\s*)[^<]*(<\/string>)/,
+ `$1${version}$2`,
+ ],
+ ["darwin/Info.plist", /(CFBundleVersion<\/key>\s*)[^<]*(<\/string>)/, `$1${numeric}$2`],
+];
+
+for (const [file, pattern, replacement] of edits) {
+ const path = join(dir, file);
+ const before = readFileSync(path, "utf8");
+ const after = before.replace(pattern, replacement);
+ if (after === before && !before.match(pattern)) {
+ console.error(`${file}: version field not found`);
+ process.exit(1);
+ }
+ writeFileSync(path, after);
+}
+console.log(`version ${version} set`);
diff --git a/Desktop-App/build/windows/Taskfile.yml b/Desktop-App/build/windows/Taskfile.yml
index c2f0b5a..b2aec40 100644
--- a/Desktop-App/build/windows/Taskfile.yml
+++ b/Desktop-App/build/windows/Taskfile.yml
@@ -57,7 +57,7 @@ tasks:
- cmd: rm -f *.syso
platforms: [linux, darwin]
vars:
- BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s -H windowsgui"{{end}}'
+ BUILD_FLAGS: '{{if eq .DEV "true"}}{{if or .EXTRA_TAGS (eq .OBFUSCATED "true")}}-tags {{if eq .OBFUSCATED "true"}}wails_obfuscated{{if .EXTRA_TAGS}},{{end}}{{end}}{{.EXTRA_TAGS}} {{end}}-buildvcs=false -gcflags=all="-l"{{else}}-tags production{{if eq .OBFUSCATED "true"}},wails_obfuscated{{end}}{{if .EXTRA_TAGS}},{{.EXTRA_TAGS}}{{end}} -trimpath -buildvcs=false -ldflags="-w -s {{.EXTRA_LDFLAGS}} -H windowsgui"{{end}}'
env:
GOOS: windows
CGO_ENABLED: '{{.CGO_ENABLED | default "0"}}'
diff --git a/Desktop-App/deeplink.go b/Desktop-App/deeplink.go
index 2009596..1a5df2a 100644
--- a/Desktop-App/deeplink.go
+++ b/Desktop-App/deeplink.go
@@ -23,7 +23,11 @@ var deepLinkRoutes = []string{"p", "s"}
var recordID = regexp.MustCompile(`^[A-Za-z0-9]{1,32}$`)
-// routeFromDeepLink turns docwell://p/ into the app route /p/.
+// blockFragment is a link to one block of a page: docwell://p/#b-.
+var blockFragment = regexp.MustCompile(`^b-[a-z0-9]{6,16}$`)
+
+// routeFromDeepLink turns docwell://p/ into the app route /p/
+// (keeping a #b- fragment that points at one block).
// Anything else is refused: links come from other apps and web pages, so
// they may only navigate, never change settings such as the server address.
func routeFromDeepLink(raw string) (string, error) {
@@ -38,7 +42,14 @@ func routeFromDeepLink(raw string) (string, error) {
if len(parts) != 2 || !slices.Contains(deepLinkRoutes, parts[0]) || !recordID.MatchString(parts[1]) {
return "", errors.New("unsupported docwell:// link")
}
- return "/" + parts[0] + "/" + parts[1], nil
+ route := "/" + parts[0] + "/" + parts[1]
+ if u.Fragment != "" {
+ if parts[0] != "p" || !blockFragment.MatchString(u.Fragment) {
+ return "", errors.New("unsupported docwell:// link")
+ }
+ route += "#" + u.Fragment
+ }
+ return route, nil
}
// deepLinkFromArgs finds a docwell:// link among command-line arguments,
diff --git a/Desktop-App/deeplink_test.go b/Desktop-App/deeplink_test.go
index b9f3994..4101ff3 100644
--- a/Desktop-App/deeplink_test.go
+++ b/Desktop-App/deeplink_test.go
@@ -6,12 +6,13 @@ import "testing"
func TestRouteFromDeepLink(t *testing.T) {
ok := map[string]string{
- "docwell://": "/",
- "docwell://p/abc123": "/p/abc123",
- "docwell://p/abc123/": "/p/abc123",
- "DOCWELL://s/space01": "/s/space01",
- "docwell:///p/abc123": "/p/abc123",
- " docwell://p/abc123\n ": "/p/abc123",
+ "docwell://": "/",
+ "docwell://p/abc123": "/p/abc123",
+ "docwell://p/abc123/": "/p/abc123",
+ "DOCWELL://s/space01": "/s/space01",
+ "docwell:///p/abc123": "/p/abc123",
+ "docwell://p/abc123#b-x1y2z3w4": "/p/abc123#b-x1y2z3w4",
+ " docwell://p/abc123\n ": "/p/abc123",
}
for in, want := range ok {
got, err := routeFromDeepLink(in)
@@ -28,6 +29,8 @@ func TestRouteFromDeepLink(t *testing.T) {
"docwell://p/",
"docwell://p/a%2Fb",
"docwell://p/javascript:alert(1)",
+ "docwell://s/space01#b-x1y2z3w4",
+ "docwell://p/abc123#settings",
"not a url",
}
for _, in := range bad {
diff --git a/Desktop-App/frontend/bindings/docwell/desktop/index.ts b/Desktop-App/frontend/bindings/docwell/desktop/index.ts
index 40d90fe..43988be 100644
--- a/Desktop-App/frontend/bindings/docwell/desktop/index.ts
+++ b/Desktop-App/frontend/bindings/docwell/desktop/index.ts
@@ -3,11 +3,14 @@
import * as LinkService from "./linkservice.js";
import * as SettingsService from "./settingsservice.js";
+import * as TokenService from "./tokenservice.js";
export {
LinkService,
- SettingsService
+ SettingsService,
+ TokenService
};
export {
+ Server,
Settings
} from "./models.js";
diff --git a/Desktop-App/frontend/bindings/docwell/desktop/models.ts b/Desktop-App/frontend/bindings/docwell/desktop/models.ts
index 36bbb95..fec2628 100644
--- a/Desktop-App/frontend/bindings/docwell/desktop/models.ts
+++ b/Desktop-App/frontend/bindings/docwell/desktop/models.ts
@@ -6,13 +6,63 @@
import { Create as $Create } from "@wailsio/runtime";
/**
- * Settings are stored per user in the OS config directory.
+ * Server is one docwell-server the app can sign in to.
+ */
+export class Server {
+ "id": string;
+ "name": string;
+ "url": string;
+
+ /** Creates a new Server instance. */
+ constructor($$source: Partial = {}) {
+ if (!("id" in $$source)) {
+ this["id"] = "";
+ }
+ if (!("name" in $$source)) {
+ this["name"] = "";
+ }
+ if (!("url" in $$source)) {
+ this["url"] = "";
+ }
+
+ Object.assign(this, $$source);
+ }
+
+ /**
+ * Creates a new Server instance from a string or object.
+ */
+ static createFrom($$source: any = {}): Server {
+ let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+ return new Server($$parsedSource as Partial);
+ }
+}
+
+/**
+ * Settings are stored per user in the OS config directory. Sign-in tokens
+ * are not: they live in the system keychain (see keychain.go).
*/
export class Settings {
+ "servers": Server[];
+
+ /**
+ * Active is the id of the server the window shows.
+ */
+ "active": string;
+
+ /**
+ * ServerURL is the active server's address (and, in files written by
+ * older versions, the only server).
+ */
"serverUrl": string;
/** Creates a new Settings instance. */
constructor($$source: Partial = {}) {
+ if (!("servers" in $$source)) {
+ this["servers"] = [];
+ }
+ if (!("active" in $$source)) {
+ this["active"] = "";
+ }
if (!("serverUrl" in $$source)) {
this["serverUrl"] = "";
}
@@ -24,7 +74,15 @@ export class Settings {
* Creates a new Settings instance from a string or object.
*/
static createFrom($$source: any = {}): Settings {
+ const $$createField0_0 = $$createType1;
let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+ if ("servers" in $$parsedSource) {
+ $$parsedSource["servers"] = $$createField0_0($$parsedSource["servers"]);
+ }
return new Settings($$parsedSource as Partial);
}
}
+
+// Private type creation functions
+const $$createType0 = Server.createFrom;
+const $$createType1 = $Create.Array($$createType0);
diff --git a/Desktop-App/frontend/bindings/docwell/desktop/settingsservice.ts b/Desktop-App/frontend/bindings/docwell/desktop/settingsservice.ts
index 2d2598b..94b462c 100644
--- a/Desktop-App/frontend/bindings/docwell/desktop/settingsservice.ts
+++ b/Desktop-App/frontend/bindings/docwell/desktop/settingsservice.ts
@@ -15,7 +15,17 @@ import { Call as $Call, CancellablePromise as $CancellablePromise, Create as $Cr
import * as $models from "./models.js";
/**
- * Get returns the saved settings, or defaults when none are saved.
+ * AddServer saves a server and makes it the active one. A server that is
+ * already in the list (same address) is made active instead of added twice.
+ */
+export function AddServer(name: string, rawURL: string): $CancellablePromise<$models.Settings> {
+ return $Call.ByID(496664188, name, rawURL).then(($result: any) => {
+ return $$createType0($result);
+ });
+}
+
+/**
+ * Get returns the saved settings, or one local server when none are saved.
*/
export function Get(): $CancellablePromise<$models.Settings> {
return $Call.ByID(710695688).then(($result: any) => {
@@ -24,7 +34,37 @@ export function Get(): $CancellablePromise<$models.Settings> {
}
/**
- * SetServerURL validates and saves the docwell-server address.
+ * RemoveServer forgets a server. The caller signs out of it first (its
+ * token is in the keychain). The last server cannot be removed.
+ */
+export function RemoveServer(id: string): $CancellablePromise<$models.Settings> {
+ return $Call.ByID(625188463, id).then(($result: any) => {
+ return $$createType0($result);
+ });
+}
+
+/**
+ * RenameServer changes how a server is listed.
+ */
+export function RenameServer(id: string, name: string): $CancellablePromise<$models.Settings> {
+ return $Call.ByID(3720849849, id, name).then(($result: any) => {
+ return $$createType0($result);
+ });
+}
+
+/**
+ * SetActive switches the window to another saved server; the frontend
+ * reloads afterwards.
+ */
+export function SetActive(id: string): $CancellablePromise<$models.Settings> {
+ return $Call.ByID(373454614, id).then(($result: any) => {
+ return $$createType0($result);
+ });
+}
+
+/**
+ * SetServerURL changes the active server's address (settings from the
+ * first desktop builds had only this).
*/
export function SetServerURL(raw: string): $CancellablePromise<$models.Settings> {
return $Call.ByID(2491318192, raw).then(($result: any) => {
diff --git a/Desktop-App/frontend/bindings/docwell/desktop/tokenservice.ts b/Desktop-App/frontend/bindings/docwell/desktop/tokenservice.ts
new file mode 100644
index 0000000..d948d59
--- /dev/null
+++ b/Desktop-App/frontend/bindings/docwell/desktop/tokenservice.ts
@@ -0,0 +1,36 @@
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+/**
+ * TokenService keeps each server's sign-in token in the system keychain,
+ * so it is not stored in a plain file or the web view's storage. It is
+ * bound to the frontend.
+ * @module
+ */
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore: Unused imports
+import { Call as $Call, CancellablePromise as $CancellablePromise, Create as $Create } from "@wailsio/runtime";
+
+/**
+ * Delete removes a server's token. Deleting a missing token is not an error.
+ */
+export function Delete(serverID: string): $CancellablePromise {
+ return $Call.ByID(1749246119, serverID);
+}
+
+/**
+ * Get returns the token saved for a server, or "" when there is none. An
+ * error means the keychain can't be used (e.g. no Secret Service on a
+ * Linux desktop); the frontend then keeps the session in memory only.
+ */
+export function Get(serverID: string): $CancellablePromise {
+ return $Call.ByID(806072600, serverID);
+}
+
+/**
+ * Set saves a server's token; an empty token deletes it (signing out).
+ */
+export function Set(serverID: string, token: string): $CancellablePromise {
+ return $Call.ByID(2986285700, serverID, token);
+}
diff --git a/Desktop-App/frontend/src/main.ts b/Desktop-App/frontend/src/main.ts
index 18262c5..68649fe 100644
--- a/Desktop-App/frontend/src/main.ts
+++ b/Desktop-App/frontend/src/main.ts
@@ -1,26 +1,101 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import "@docwell/web-app/style.css";
-import { createDocwellApp, type Platform } from "@docwell/web-app/app";
+import { createDocwellApp, type AppCommand, type Platform, type TokenStore } from "@docwell/web-app/app";
import { Events } from "@wailsio/runtime";
-import { LinkService, SettingsService } from "../bindings/docwell/desktop";
+import { LinkService, SettingsService, TokenService } from "../bindings/docwell/desktop";
/** Emitted by deeplink.go with an app route when the OS opens a docwell:// link. */
const OPEN_ROUTE_EVENT = "docwell:open-route";
+/** Emitted by menu.go with a command from the native menu bar. */
+const COMMAND_EVENT = "docwell:command";
-// The desktop app runs the same UI as Web-App; config loading and deep links differ.
+/** Where the first desktop builds kept the token, before the keychain. */
+const LEGACY_TOKEN_KEY = "docwell.token";
+
+let activeServer = "";
+
+/**
+ * The active server's token, read from the system keychain once at start-up
+ * and written back on every change. When the keychain can't be used (a Linux
+ * desktop without a Secret Service), the session lasts until the app closes.
+ */
+async function keychainTokens(): Promise {
+ let token: string | null = null;
+ let keychain = true;
+ try {
+ token = (await TokenService.Get(activeServer)) || null;
+ } catch (e) {
+ keychain = false;
+ console.warn("keychain unavailable; the session will not be remembered", e);
+ }
+ // Move a token saved by an older version out of the web view's storage.
+ try {
+ const legacy = localStorage.getItem(LEGACY_TOKEN_KEY);
+ if (legacy) {
+ localStorage.removeItem(LEGACY_TOKEN_KEY);
+ if (!token && keychain) {
+ token = legacy;
+ await TokenService.Set(activeServer, legacy);
+ }
+ }
+ } catch {
+ // no storage: nothing to move
+ }
+ return {
+ get: () => token,
+ set(next) {
+ token = next;
+ if (keychain) {
+ TokenService.Set(activeServer, next ?? "").catch((e: unknown) => console.warn("keychain write failed", e));
+ }
+ },
+ };
+}
+
+// The desktop app runs the same UI as Web-App; config, sessions, menus and
+// deep links come from the Go side.
const desktopPlatform: Platform = {
kind: "desktop",
async loadConfig() {
const settings = await SettingsService.Get();
+ activeServer = settings.active;
const ws = settings.serverUrl.replace(/^http/, "ws");
return { apiUrl: settings.serverUrl, collabUrl: `${ws}/collab`, version: "desktop" };
},
+ tokenStore: keychainTokens,
+ // Shared links open the desktop app: docwell://p/#b-.
+ pageUrl: (route) => `docwell:/${route}`,
onOpenRoute(open) {
Events.On(OPEN_ROUTE_EVENT, (e) => open(String(e.data)));
// The link the app was launched with arrived before this listener.
void LinkService.TakePending().then((route) => route && open(route));
},
+ onCommand(run) {
+ Events.On(COMMAND_EVENT, (e) => run(String(e.data) as AppCommand));
+ },
+ servers: {
+ async list() {
+ const s = await SettingsService.Get();
+ return { servers: s.servers ?? [], active: s.active };
+ },
+ async add(name, url) {
+ await SettingsService.AddServer(name, url);
+ location.reload();
+ },
+ async rename(id, name) {
+ await SettingsService.RenameServer(id, name);
+ },
+ async remove(id) {
+ // The Go side also deletes the server's token from the keychain.
+ await SettingsService.RemoveServer(id);
+ if (id === activeServer) location.reload();
+ },
+ async switchTo(id) {
+ await SettingsService.SetActive(id);
+ location.reload();
+ },
+ },
};
-createDocwellApp(desktopPlatform);
+void createDocwellApp(desktopPlatform);
diff --git a/Desktop-App/go.mod b/Desktop-App/go.mod
index 3a9dbd8..b6d513e 100644
--- a/Desktop-App/go.mod
+++ b/Desktop-App/go.mod
@@ -2,11 +2,15 @@ module docwell/desktop
go 1.26.0
-require github.com/wailsapp/wails/v3 v3.0.0
+require (
+ github.com/wailsapp/wails/v3 v3.0.0
+ github.com/zalando/go-keyring v0.2.8
+)
require (
github.com/adrg/xdg v0.5.3 // indirect
github.com/coder/websocket v1.8.14 // indirect
+ github.com/danieljoos/wincred v1.2.3 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/godbus/dbus/v5 v5.2.2 // indirect
github.com/mattn/go-colorable v0.1.14 // indirect
diff --git a/Desktop-App/go.sum b/Desktop-App/go.sum
index f78f386..43aad4c 100644
--- a/Desktop-App/go.sum
+++ b/Desktop-App/go.sum
@@ -2,6 +2,8 @@ github.com/adrg/xdg v0.5.3 h1:xRnxJXne7+oWDatRhR1JLnvuccuIeCoBu2rtuLqQB78=
github.com/adrg/xdg v0.5.3/go.mod h1:nlTsY+NNiCBGCK2tpm09vRqfVzrc2fLmXGpBLF0zlTQ=
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
+github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
+github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e h1:Lf/gRkoycfOBPa42vU2bbgPurFong6zXeFtPoxholzU=
@@ -20,10 +22,14 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
+github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/wailsapp/wails/v3 v3.0.0 h1:lBe89kFu23bVz1dc1H9v0srkHQgWsy7BAKpH4sLQuDw=
github.com/wailsapp/wails/v3 v3.0.0/go.mod h1:U3p3/QfSer2XxXM3XWhwis9O7LvvuNKN/AcGoEFD+K8=
+github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
+github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
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/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
diff --git a/Desktop-App/keychain.go b/Desktop-App/keychain.go
new file mode 100644
index 0000000..5fefdb7
--- /dev/null
+++ b/Desktop-App/keychain.go
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package main
+
+import (
+ "errors"
+ "log/slog"
+
+ "github.com/zalando/go-keyring"
+)
+
+// keychainService names Docwell's entries in the system keychain (Windows
+// Credential Manager, macOS Keychain, the Secret Service on Linux).
+const keychainService = "Docwell"
+
+// TokenService keeps each server's sign-in token in the system keychain,
+// so it is not stored in a plain file or the web view's storage. It is
+// bound to the frontend.
+type TokenService struct {
+ store tokenStore
+}
+
+// tokenStore is the keychain; tests swap it for a map.
+type tokenStore interface {
+ Get(service, user string) (string, error)
+ Set(service, user, password string) error
+ Delete(service, user string) error
+}
+
+type systemKeychain struct{}
+
+func (systemKeychain) Get(service, user string) (string, error) { return keyring.Get(service, user) }
+func (systemKeychain) Set(service, user, password string) error {
+ return keyring.Set(service, user, password)
+}
+func (systemKeychain) Delete(service, user string) error { return keyring.Delete(service, user) }
+
+func NewTokenService() *TokenService { return &TokenService{store: systemKeychain{}} }
+
+func tokenKey(serverID string) string { return "server:" + serverID }
+
+// Get returns the token saved for a server, or "" when there is none. An
+// error means the keychain can't be used (e.g. no Secret Service on a
+// Linux desktop); the frontend then keeps the session in memory only.
+func (t *TokenService) Get(serverID string) (string, error) {
+ tok, err := t.store.Get(keychainService, tokenKey(serverID))
+ if errors.Is(err, keyring.ErrNotFound) {
+ return "", nil
+ }
+ return tok, err
+}
+
+// Set saves a server's token; an empty token deletes it (signing out).
+func (t *TokenService) Set(serverID, token string) error {
+ if token == "" {
+ return t.Delete(serverID)
+ }
+ return t.store.Set(keychainService, tokenKey(serverID), token)
+}
+
+// Delete removes a server's token. Deleting a missing token is not an error.
+func (t *TokenService) Delete(serverID string) error {
+ err := t.store.Delete(keychainService, tokenKey(serverID))
+ if errors.Is(err, keyring.ErrNotFound) {
+ return nil
+ }
+ return err
+}
+
+// forget deletes a removed server's token, logging rather than failing.
+func (t *TokenService) forget(serverID string) {
+ if err := t.Delete(serverID); err != nil {
+ slog.Warn("could not delete token from keychain", "server", serverID, "err", err)
+ }
+}
diff --git a/Desktop-App/keychain_test.go b/Desktop-App/keychain_test.go
new file mode 100644
index 0000000..72eedbb
--- /dev/null
+++ b/Desktop-App/keychain_test.go
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package main
+
+import (
+ "testing"
+
+ "github.com/zalando/go-keyring"
+)
+
+type memKeychain map[string]string
+
+func (m memKeychain) Get(service, user string) (string, error) {
+ v, ok := m[service+"/"+user]
+ if !ok {
+ return "", keyring.ErrNotFound
+ }
+ return v, nil
+}
+
+func (m memKeychain) Set(service, user, password string) error {
+ m[service+"/"+user] = password
+ return nil
+}
+
+func (m memKeychain) Delete(service, user string) error {
+ if _, ok := m[service+"/"+user]; !ok {
+ return keyring.ErrNotFound
+ }
+ delete(m, service+"/"+user)
+ return nil
+}
+
+func TestTokens(t *testing.T) {
+ store := memKeychain{}
+ tokens := &TokenService{store: store}
+ if tok, err := tokens.Get("a"); tok != "" || err != nil {
+ t.Fatalf("empty keychain gave %q, %v", tok, err)
+ }
+ _ = tokens.Set("a", "secret-a")
+ _ = tokens.Set("b", "secret-b")
+ if tok, _ := tokens.Get("a"); tok != "secret-a" {
+ t.Fatalf("got %q", tok)
+ }
+ // Servers keep separate sessions; signing out of one leaves the other.
+ if err := tokens.Set("a", ""); err != nil {
+ t.Fatal(err)
+ }
+ if tok, _ := tokens.Get("a"); tok != "" {
+ t.Fatalf("signed out but got %q", tok)
+ }
+ if tok, _ := tokens.Get("b"); tok != "secret-b" {
+ t.Fatalf("other server lost its token: %q", tok)
+ }
+ if err := tokens.Delete("missing"); err != nil {
+ t.Fatal(err)
+ }
+ if store["Docwell/server:b"] != "secret-b" {
+ t.Fatalf("unexpected keychain layout: %v", store)
+ }
+}
diff --git a/Desktop-App/main.go b/Desktop-App/main.go
index 79df2ab..9647412 100644
--- a/Desktop-App/main.go
+++ b/Desktop-App/main.go
@@ -21,6 +21,7 @@ func main() {
log.Fatal(err)
}
+ tokens := NewTokenService()
links := &LinkService{}
updates, updatesOn, err := updateConfig(updateManifestURL, updatePublicKey)
if err != nil {
@@ -32,6 +33,7 @@ func main() {
Description: "Docwell desktop app",
Services: []application.Service{
application.NewService(settings),
+ application.NewService(tokens),
application.NewService(links),
},
// A docwell:// link starts a second process on Windows and Linux; it
@@ -63,8 +65,9 @@ func main() {
Backdrop: application.MacBackdropTranslucent,
TitleBar: application.MacTitleBarHiddenInset,
},
- BackgroundColour: application.NewRGB(255, 255, 255),
- URL: "/",
+ BackgroundColour: application.NewRGB(255, 255, 255),
+ URL: "/",
+ UseApplicationMenu: true,
})
links.setEmitter(func(route string) {
@@ -83,6 +86,14 @@ func main() {
}
}
newTray(app, win, updatesOn)
+ menu := newAppMenu(app, win, settings, updatesOn)
+ settings.changed = func(_ Settings, removed []string) {
+ // The Server menu lists the saved servers.
+ application.InvokeSync(menu.build)
+ for _, id := range removed {
+ tokens.forget(id)
+ }
+ }
if err := app.Run(); err != nil {
log.Fatal(err)
diff --git a/Desktop-App/menu.go b/Desktop-App/menu.go
new file mode 100644
index 0000000..a2e211d
--- /dev/null
+++ b/Desktop-App/menu.go
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package main
+
+import (
+ "context"
+ "log/slog"
+ "runtime"
+
+ "github.com/wailsapp/wails/v3/pkg/application"
+)
+
+// commandEvent carries a menu command to the frontend: "new-page", "search"
+// or "toggle-sidebar".
+const commandEvent = "docwell:command"
+
+// docsURL is where Help → Documentation goes; release builds set it with
+// -ldflags "-X main.docsURL=…". Without it the item is left out.
+var docsURL = ""
+
+// appMenu builds the native menu bar: File, Edit, View, Window and Help,
+// plus the app menu on macOS. Commands that act on the page are sent to the
+// frontend; switching servers saves the choice and reloads the window.
+type appMenu struct {
+ app *application.App
+ win *application.WebviewWindow
+ settings *SettingsService
+ updates bool
+ menu *application.Menu
+}
+
+func newAppMenu(app *application.App, win *application.WebviewWindow, settings *SettingsService, updates bool) *appMenu {
+ m := &appMenu{app: app, win: win, settings: settings, updates: updates, menu: app.NewMenu()}
+ m.build()
+ app.Menu.Set(m.menu)
+ return m
+}
+
+func (m *appMenu) command(name string) func(*application.Context) {
+ return func(*application.Context) {
+ showWindow(m.win)
+ m.app.Event.Emit(commandEvent, name)
+ }
+}
+
+func (m *appMenu) route(route string) func(*application.Context) {
+ return func(*application.Context) {
+ showWindow(m.win)
+ m.app.Event.Emit(openRouteEvent, route)
+ }
+}
+
+// build fills the menu; it runs again when the server list changes.
+func (m *appMenu) build() {
+ menu := m.menu
+ menu.Clear()
+ if runtime.GOOS == "darwin" {
+ menu.AddRole(application.AppMenu)
+ }
+
+ file := menu.AddSubmenu("File")
+ file.Add("New Page").SetAccelerator("CmdOrCtrl+N").OnClick(m.command("new-page"))
+ // Search (Ctrl+K) and the sidebar (Ctrl+/) have shortcuts in the page
+ // itself; an accelerator here as well would run them twice.
+ file.Add("Search…").OnClick(m.command("search"))
+ file.AddSeparator()
+ servers := file.AddSubmenu("Server")
+ if s, err := m.settings.Get(); err == nil {
+ for _, sv := range s.Servers {
+ id := sv.ID
+ servers.AddRadio(sv.Name, sv.ID == s.Active).OnClick(func(*application.Context) { m.switchTo(id) })
+ }
+ }
+ servers.AddSeparator()
+ servers.Add("Add or Manage Servers…").OnClick(m.route("/settings/servers"))
+ file.Add("Account Settings…").SetAccelerator("CmdOrCtrl+,").OnClick(m.route("/settings/account"))
+ file.AddSeparator()
+ if runtime.GOOS == "darwin" {
+ file.AddRole(application.CloseWindow)
+ } else {
+ file.AddRole(application.Quit)
+ }
+
+ menu.AddRole(application.EditMenu)
+
+ view := menu.AddSubmenu("View")
+ view.Add("Toggle Sidebar").OnClick(m.command("toggle-sidebar"))
+ view.AddSeparator()
+ view.AddRole(application.Reload)
+ view.AddSeparator()
+ view.AddRole(application.ResetZoom)
+ view.AddRole(application.ZoomIn)
+ view.AddRole(application.ZoomOut)
+ view.AddSeparator()
+ view.AddRole(application.ToggleFullscreen)
+
+ menu.AddRole(application.WindowMenu)
+
+ help := menu.AddSubmenu("Help")
+ if docsURL != "" {
+ help.Add("Docwell Documentation").OnClick(func(*application.Context) {
+ if err := m.app.Browser.OpenURL(docsURL); err != nil {
+ slog.Warn("could not open the documentation", "err", err)
+ }
+ })
+ }
+ if m.updates {
+ help.Add("Check for Updates…").OnClick(func(*application.Context) {
+ go func() {
+ if err := m.app.Updater.CheckAndInstall(context.Background()); err != nil {
+ slog.Warn("update check failed", "err", err)
+ }
+ }()
+ })
+ }
+ if runtime.GOOS != "darwin" {
+ help.AddSeparator()
+ help.AddRole(application.About)
+ }
+ menu.Update()
+}
+
+// switchTo makes another saved server active and reloads the window, which
+// then loads that server's settings and keychain token.
+func (m *appMenu) switchTo(id string) {
+ if _, err := m.settings.SetActive(id); err != nil {
+ slog.Warn("could not switch server", "server", id, "err", err)
+ return
+ }
+ showWindow(m.win)
+ m.win.Reload()
+}
diff --git a/Desktop-App/settings.go b/Desktop-App/settings.go
index 6d381dd..e9a3e2d 100644
--- a/Desktop-App/settings.go
+++ b/Desktop-App/settings.go
@@ -3,6 +3,8 @@
package main
import (
+ "crypto/rand"
+ "encoding/hex"
"encoding/json"
"errors"
"net/url"
@@ -12,8 +14,21 @@ import (
"sync"
)
-// Settings are stored per user in the OS config directory.
+// Server is one docwell-server the app can sign in to.
+type Server struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+}
+
+// Settings are stored per user in the OS config directory. Sign-in tokens
+// are not: they live in the system keychain (see keychain.go).
type Settings struct {
+ Servers []Server `json:"servers"`
+ // Active is the id of the server the window shows.
+ Active string `json:"active"`
+ // ServerURL is the active server's address (and, in files written by
+ // older versions, the only server).
ServerURL string `json:"serverUrl"`
}
@@ -21,6 +36,10 @@ type Settings struct {
type SettingsService struct {
path string
mu sync.Mutex
+ // changed is called after the server list or the active server changes,
+ // with the ids of removed servers, e.g. to rebuild the menu and delete
+ // their tokens.
+ changed func(s Settings, removed []string)
}
func NewSettingsService() (*SettingsService, error) {
@@ -33,37 +52,177 @@ func NewSettingsService() (*SettingsService, error) {
const defaultServerURL = "http://localhost:8080"
-// Get returns the saved settings, or defaults when none are saved.
+// Get returns the saved settings, or one local server when none are saved.
func (s *SettingsService) Get() (Settings, error) {
s.mu.Lock()
defer s.mu.Unlock()
- out := Settings{ServerURL: defaultServerURL}
- data, err := os.ReadFile(s.path)
- if errors.Is(err, os.ErrNotExist) {
- return out, nil
- }
- if err != nil {
- return out, err
- }
- if err := json.Unmarshal(data, &out); err != nil {
- return Settings{ServerURL: defaultServerURL}, err
- }
- return out, nil
+ return s.load()
}
-// SetServerURL validates and saves the docwell-server address.
-func (s *SettingsService) SetServerURL(raw string) (Settings, error) {
- u, err := url.Parse(strings.TrimSpace(raw))
- if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
- return Settings{}, errors.New("server URL must be an http(s) address")
+func (s *SettingsService) load() (Settings, error) {
+ var out Settings
+ data, err := os.ReadFile(s.path)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return normalize(out), err
}
- settings := Settings{ServerURL: strings.TrimRight(u.String(), "/")}
+ if err == nil {
+ if err := json.Unmarshal(data, &out); err != nil {
+ return normalize(Settings{}), err
+ }
+ }
+ return normalize(out), nil
+}
- s.mu.Lock()
- defer s.mu.Unlock()
+// normalize fills in what older or empty files lack: a server for a lone
+// serverUrl, a default server, an active one, and ServerURL.
+func normalize(s Settings) Settings {
+ if len(s.Servers) == 0 {
+ u := s.ServerURL
+ if u == "" {
+ u = defaultServerURL
+ }
+ s.Servers = []Server{{ID: "default", Name: hostName(u), URL: u}}
+ }
+ if s.server(s.Active) == nil {
+ s.Active = s.Servers[0].ID
+ }
+ s.ServerURL = s.server(s.Active).URL
+ return s
+}
+
+func (s Settings) server(id string) *Server {
+ for i := range s.Servers {
+ if s.Servers[i].ID == id {
+ return &s.Servers[i]
+ }
+ }
+ return nil
+}
+
+func (s *SettingsService) save(settings Settings, removed ...string) (Settings, error) {
+ settings = normalize(settings)
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
return Settings{}, err
}
data, _ := json.MarshalIndent(settings, "", " ")
- return settings, os.WriteFile(s.path, data, 0o600)
+ if err := os.WriteFile(s.path, data, 0o600); err != nil {
+ return Settings{}, err
+ }
+ if s.changed != nil {
+ go s.changed(settings, removed)
+ }
+ return settings, nil
+}
+
+// cleanServerURL validates a docwell-server address.
+func cleanServerURL(raw string) (string, error) {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return "", errors.New("server URL must be an http(s) address")
+ }
+ u.RawQuery, u.Fragment = "", ""
+ return strings.TrimRight(u.String(), "/"), nil
+}
+
+func hostName(raw string) string {
+ if u, err := url.Parse(raw); err == nil && u.Host != "" {
+ return u.Host
+ }
+ return raw
+}
+
+func newServerID() string {
+ b := make([]byte, 6)
+ _, _ = rand.Read(b)
+ return hex.EncodeToString(b)
+}
+
+// AddServer saves a server and makes it the active one. A server that is
+// already in the list (same address) is made active instead of added twice.
+func (s *SettingsService) AddServer(name, rawURL string) (Settings, error) {
+ u, err := cleanServerURL(rawURL)
+ if err != nil {
+ return Settings{}, err
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ settings, _ := s.load()
+ for _, sv := range settings.Servers {
+ if strings.EqualFold(sv.URL, u) {
+ settings.Active = sv.ID
+ return s.save(settings)
+ }
+ }
+ name = strings.TrimSpace(name)
+ if name == "" {
+ name = hostName(u)
+ }
+ if len(name) > 80 {
+ name = name[:80]
+ }
+ sv := Server{ID: newServerID(), Name: name, URL: u}
+ settings.Servers = append(settings.Servers, sv)
+ settings.Active = sv.ID
+ return s.save(settings)
+}
+
+// RenameServer changes how a server is listed.
+func (s *SettingsService) RenameServer(id, name string) (Settings, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ settings, _ := s.load()
+ sv := settings.server(id)
+ if sv == nil {
+ return Settings{}, errors.New("no such server")
+ }
+ if name = strings.TrimSpace(name); name != "" {
+ sv.Name = name
+ }
+ return s.save(settings)
+}
+
+// RemoveServer forgets a server. The caller signs out of it first (its
+// token is in the keychain). The last server cannot be removed.
+func (s *SettingsService) RemoveServer(id string) (Settings, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ settings, _ := s.load()
+ if len(settings.Servers) <= 1 {
+ return Settings{}, errors.New("keep at least one server")
+ }
+ kept := settings.Servers[:0]
+ for _, sv := range settings.Servers {
+ if sv.ID != id {
+ kept = append(kept, sv)
+ }
+ }
+ settings.Servers = kept
+ return s.save(settings, id)
+}
+
+// SetActive switches the window to another saved server; the frontend
+// reloads afterwards.
+func (s *SettingsService) SetActive(id string) (Settings, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ settings, _ := s.load()
+ if settings.server(id) == nil {
+ return Settings{}, errors.New("no such server")
+ }
+ settings.Active = id
+ return s.save(settings)
+}
+
+// SetServerURL changes the active server's address (settings from the
+// first desktop builds had only this).
+func (s *SettingsService) SetServerURL(raw string) (Settings, error) {
+ u, err := cleanServerURL(raw)
+ if err != nil {
+ return Settings{}, err
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ settings, _ := s.load()
+ settings.server(settings.Active).URL = u
+ return s.save(settings)
}
diff --git a/Desktop-App/settings_test.go b/Desktop-App/settings_test.go
index 44efbc9..be8d346 100644
--- a/Desktop-App/settings_test.go
+++ b/Desktop-App/settings_test.go
@@ -3,6 +3,7 @@
package main
import (
+ "os"
"path/filepath"
"testing"
)
@@ -32,3 +33,36 @@ func TestSettingsRejectsBadURL(t *testing.T) {
}
}
}
+
+func TestServers(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "settings.json")
+ // A file from the first desktop builds: one address, no list.
+ if err := os.WriteFile(path, []byte(`{"serverUrl":"https://old.example.test"}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s := &SettingsService{path: path}
+ got, _ := s.Get()
+ if len(got.Servers) != 1 || got.ServerURL != "https://old.example.test" || got.Servers[0].Name != "old.example.test" {
+ t.Fatalf("migrated = %+v", got)
+ }
+
+ got, err := s.AddServer("Work", "https://work.example.test/")
+ if err != nil || len(got.Servers) != 2 || got.ServerURL != "https://work.example.test" {
+ t.Fatalf("added = %+v, %v", got, err)
+ }
+ work := got.Active
+ // The same address again switches to it instead of adding a copy.
+ got, _ = s.AddServer("", "https://OLD.example.test")
+ if len(got.Servers) != 2 || got.ServerURL != "https://old.example.test" {
+ t.Fatalf("re-added = %+v", got)
+ }
+ if got, _ = s.SetActive(work); got.ServerURL != "https://work.example.test" {
+ t.Fatalf("switched = %+v", got)
+ }
+ if got, _ = s.RemoveServer(work); len(got.Servers) != 1 || got.ServerURL != "https://old.example.test" {
+ t.Fatalf("removed = %+v", got)
+ }
+ if _, err := s.RemoveServer(got.Active); err == nil {
+ t.Fatal("removed the last server")
+ }
+}
diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts
index d580b8c..b82fbe9 100644
--- a/Packages/api-client/src/index.ts
+++ b/Packages/api-client/src/index.ts
@@ -27,6 +27,8 @@ export type PageNode = Schemas["PageNode"];
export type PageRef = Schemas["PageRef"];
export type Page = Schemas["Page"];
export type TrashedPage = Schemas["TrashedPage"];
+export type ArchivedPage = Schemas["ArchivedPage"];
+export type LinkPreview = Schemas["LinkPreview"];
export type PageContent = Schemas["PageContent"];
export type PageVersion = Schemas["PageVersion"];
export type PublicSettings = Schemas["PublicSettings"];
@@ -379,6 +381,10 @@ export function createClient(opts: ClientOptions) {
createPage: (id: string, input: { parent?: string; title?: string; index?: number } = {}) =>
post(`/api/v1/spaces/${encodeURIComponent(id)}/pages`, input),
trash: (id: string) => request("GET", `/api/v1/spaces/${encodeURIComponent(id)}/trash`),
+ archive: (id: string) => request("GET", `/api/v1/spaces/${encodeURIComponent(id)}/archive`),
+ /** The whole space as a zip of Markdown or HTML files. */
+ export: (id: string, format: "markdown" | "html") =>
+ download(`/api/v1/spaces/${encodeURIComponent(id)}/export${query({ format })}`),
/** Creates a page per Markdown or HTML file, under parent ("" = top level). */
import: (id: string, files: File[], parent = "") => {
const form = new FormData();
@@ -409,6 +415,10 @@ export function createClient(opts: ClientOptions) {
post(`/api/v1/pages/${encodeURIComponent(id)}/move`, { parent, index }),
trash: (id: string) => request("DELETE", `/api/v1/pages/${encodeURIComponent(id)}`),
restore: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
+ archive: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/archive`),
+ unarchive: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/unarchive`),
+ /** A web page's title, description and picture, read by docwell-server. */
+ preview: (url: string) => request("GET", `/api/v1/link-preview${query({ url })}`),
setFavorite: (id: string, on: boolean) =>
request(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`),
attachments: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/attachments`),
diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts
index fe13ec9..09904c6 100644
--- a/Packages/api-client/src/schema.d.ts
+++ b/Packages/api-client/src/schema.d.ts
@@ -690,6 +690,47 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/v1/spaces/{id}/archive": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ /** Archived pages, newest first (pages inside an archived page come back with it) */
+ get: operations["listArchive"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/spaces/{id}/export": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ /**
+ * Download the whole space as a zip of Markdown or HTML files
+ * @description One file per page the caller can open (archived pages included, trashed ones not), subpages in a folder named like their parent, an index file, and the pages' attachments under _files/. Links between exported pages and to attachments are relative, so the folder works offline; links to other pages point at DOCWELL_PUBLIC_URL.
+ */
+ get: operations["exportSpace"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/pages/{id}": {
parameters: {
query?: never;
@@ -809,6 +850,64 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/v1/pages/{id}/archive": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Archive a page with its subtree (editor). Archived pages leave the page tree and become read-only, but stay readable, searchable and linkable. */
+ post: operations["archivePage"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/pages/{id}/unarchive": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Put an archived page back in the tree (editor); it goes to the top level if its parent is gone or archived */
+ post: operations["unarchivePage"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/v1/link-preview": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * A web page's title, description and picture, for link cards
+ * @description docwell-server fetches the page itself (public addresses only: private, loopback and link-local ones are refused, redirects included). A page that can't be read still gets a preview with its address and site name.
+ */
+ get: operations["previewLink"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/pages/{id}/restore": {
parameters: {
query?: never;
@@ -2200,6 +2299,10 @@ export interface components {
deletedAt: string;
/** @description The page or one of its ancestors is in the trash */
inTrash: boolean;
+ /** @description When the page itself was archived; empty otherwise */
+ archivedAt: string;
+ /** @description The page or one of its ancestors is archived (read-only) */
+ archived: boolean;
/** @description Root first; pages the caller cannot open are left out */
ancestors: components["schemas"]["PageRef"][];
/** @description The caller's role on this page */
@@ -2277,6 +2380,20 @@ export interface components {
icon: string;
deletedAt: string;
};
+ ArchivedPage: {
+ id: string;
+ title: string;
+ icon: string;
+ archivedAt: string;
+ };
+ LinkPreview: {
+ url: string;
+ title: string;
+ description: string;
+ /** @description Address of the page's picture on its own site; empty when it has none */
+ image: string;
+ site: string;
+ };
Session: {
token: string;
user: components["schemas"]["User"];
@@ -2443,7 +2560,7 @@ export interface components {
page: number;
};
/** @enum {string} */
- WebhookEvent: "*" | "page.created" | "page.updated" | "page.moved" | "page.trashed" | "page.restored" | "page.deleted" | "comment.created" | "comment.resolved" | "space.created" | "space.deleted";
+ WebhookEvent: "*" | "page.created" | "page.updated" | "page.moved" | "page.trashed" | "page.restored" | "page.deleted" | "page.archived" | "page.unarchived" | "comment.created" | "comment.resolved" | "space.created" | "space.deleted";
Webhook: {
id: string;
name: string;
@@ -4001,6 +4118,55 @@ export interface operations {
404: components["responses"]["Error"];
};
};
+ listArchive: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ArchivedPage"][];
+ };
+ };
+ 404: components["responses"]["Error"];
+ };
+ };
+ exportSpace: {
+ parameters: {
+ query?: {
+ format?: "markdown" | "html";
+ };
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The zip, streamed as it is built */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/zip": string;
+ };
+ };
+ 400: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
getPage: {
parameters: {
query?: never;
@@ -4247,6 +4413,79 @@ export interface operations {
404: components["responses"]["Error"];
};
};
+ archivePage: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Page"];
+ };
+ };
+ 400: components["responses"]["Error"];
+ 403: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
+ unarchivePage: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ id: string;
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["Page"];
+ };
+ };
+ 403: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
+ previewLink: {
+ parameters: {
+ query: {
+ url: string;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description OK */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["LinkPreview"];
+ };
+ };
+ 400: components["responses"]["Error"];
+ 404: components["responses"]["Error"];
+ };
+ };
restorePage: {
parameters: {
query?: never;
diff --git a/Packages/editor-bridge/src/bridge.test.ts b/Packages/editor-bridge/src/bridge.test.ts
index 5192d19..ddbacac 100644
--- a/Packages/editor-bridge/src/bridge.test.ts
+++ b/Packages/editor-bridge/src/bridge.test.ts
@@ -30,7 +30,7 @@ describe("EditorBridge", () => {
const { bridge, sent, el } = setup();
bridge.receive(JSON.stringify({ type: "setContent", content: doc }));
expect(el.textContent).toContain("Hello");
- expect(bridge.content).toEqual(doc);
+ expect(bridge.content).toMatchObject(doc);
expect(sent.some((m) => m.type === "change")).toBe(false);
});
diff --git a/Packages/editor/package.json b/Packages/editor/package.json
index ce501b7..e6b728f 100644
--- a/Packages/editor/package.json
+++ b/Packages/editor/package.json
@@ -19,6 +19,7 @@
"@tiptap/extension-bubble-menu": "^3.32.2",
"@tiptap/extension-collaboration": "^3.32.2",
"@tiptap/extension-collaboration-caret": "^3.32.2",
+ "@tiptap/extension-details": "^3.32.2",
"@tiptap/extension-image": "^3.32.2",
"@tiptap/extension-mathematics": "^3.32.2",
"@tiptap/extension-mention": "^3.32.2",
diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue
index fc68bf6..61fbd33 100644
--- a/Packages/editor/src/DocwellEditor.vue
+++ b/Packages/editor/src/DocwellEditor.vue
@@ -6,6 +6,7 @@ import { BubbleMenu } from "@tiptap/vue-3/menus";
import { DwIcon, type IconName } from "@docwell/ui";
import { computed, onBeforeUnmount, watch } from "vue";
import { docwellExtensions, type CollabUser } from "./extensions";
+import type { LinkHost } from "./embeds";
import type { FileHost } from "./files";
import { englishLabels, type EditorLabels } from "./labels";
import type { MentionHost } from "./mention";
@@ -24,6 +25,10 @@ const props = withDefaults(
mentions?: MentionHost;
/** Finds pages for "[[" links. */
pages?: PageHost;
+ /** Fetches previews for link cards. */
+ links?: LinkHost;
+ /** The full address of a link to a block, from its "#b-" fragment; enables "copy link". */
+ blockLink?: (hash: string) => string;
/** The Draw.io embed address (default https://embed.diagrams.net). */
drawioUrl?: string;
labels?: EditorLabels;
@@ -42,6 +47,8 @@ const emit = defineEmits<{
"comment-select": [id: string];
/** A link to a page was followed, e.g. "/p/". */
navigate: [path: string];
+ /** A link to a block was copied. */
+ "block-link-copied": [url: string];
}>();
const labels = computed(() => props.labels ?? englishLabels);
@@ -55,6 +62,9 @@ const editor = useEditor({
files: props.files,
mentions: props.mentions,
pages: props.pages,
+ links: props.links,
+ blockLink: props.blockLink,
+ onBlockLinkCopied: (url) => emit("block-link-copied", url),
drawioUrl: props.drawioUrl,
// The heavy editors load on first use; the mobile bridge leaves them out.
loadMermaid: () => import("mermaid").then((m) => m.default),
@@ -129,6 +139,8 @@ function shouldShow({ editor: e, from, to }: { editor: Editor; from: number; to:
"blockMath",
"inlineMath",
"tableOfContents",
+ "embed",
+ "linkCard",
];
if (from === to || blocks.some((b) => e.isActive(b))) return false;
return e.isEditable || props.canComment;
diff --git a/Packages/editor/src/blocklinks.ts b/Packages/editor/src/blocklinks.ts
new file mode 100644
index 0000000..f6f6232
--- /dev/null
+++ b/Packages/editor/src/blocklinks.ts
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import { Extension, type Editor } from "@tiptap/core";
+import type { Node as PMNode } from "@tiptap/pm/model";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
+import type { EditorView } from "@tiptap/pm/view";
+import type { EditorLabels } from "./labels";
+
+/** Blocks a link can point at. */
+const linkable = [
+ "paragraph",
+ "heading",
+ "blockquote",
+ "codeBlock",
+ "bulletList",
+ "orderedList",
+ "details",
+ "image",
+ "embed",
+ "linkCard",
+ "mermaid",
+ "blockMath",
+ "drawio",
+ "excalidraw",
+ "fileAttachment",
+];
+
+const BLOCK_ID = /^[a-z0-9]{6,16}$/;
+
+/** The block id in a link's #fragment ("#b-abc123"), or "". */
+export function linkedBlock(hash: string): string {
+ const id = /^#?b-([a-z0-9]{6,16})$/.exec(hash)?.[1];
+ return id ?? "";
+}
+
+/** The #fragment of a link to block id. */
+export const blockHash = (id: string) => `#b-${id}`;
+
+function newBlockId(): string {
+ const bytes = crypto.getRandomValues(new Uint8Array(8));
+ return [...bytes].map((b) => (b % 36).toString(36)).join("");
+}
+
+function findBlock(doc: PMNode, id: string): number {
+ let found = -1;
+ doc.descendants((node, pos) => {
+ if (found >= 0) return false;
+ if (node.attrs.blockId === id) found = pos;
+ return true;
+ });
+ return found;
+}
+
+/**
+ * Scrolls the block with id into view and flashes it. Returns false when the
+ * page has no such block (it was deleted, or the link is from an old copy).
+ */
+export function scrollToBlock(editor: Editor, id: string): boolean {
+ const pos = findBlock(editor.state.doc, id);
+ if (pos < 0) return false;
+ const dom = editor.view.nodeDOM(pos);
+ if (!(dom instanceof HTMLElement)) return false;
+ dom.scrollIntoView({ block: "center" });
+ // An animation, not a class: ProseMirror redraws nodes whose attributes change.
+ const flash = getComputedStyle(dom).getPropertyValue("--color-selection").trim() || "rgba(47,125,109,.25)";
+ dom.animate?.([{ backgroundColor: flash }, { backgroundColor: "transparent" }], { duration: 2000, easing: "ease-out" });
+ return true;
+}
+
+export interface BlockLinkOptions {
+ labels: EditorLabels | null;
+ /** The full address of a link to the block; without it blocks can't be linked. */
+ link?: (hash: string) => string;
+ /** Called after a link was copied, e.g. to show "Link copied". */
+ onCopied?: (url: string) => void;
+}
+
+/**
+ * Links to single blocks. A block gets a short id the first time someone
+ * copies a link to it, from the button beside it in the margin. Readers can
+ * copy links to blocks that already have one.
+ */
+export const BlockLinks = Extension.create({
+ name: "blockLinks",
+
+ addOptions() {
+ return { labels: null, link: undefined, onCopied: undefined };
+ },
+
+ addGlobalAttributes() {
+ return [
+ {
+ types: linkable,
+ attributes: {
+ blockId: {
+ default: null,
+ // Pressing Enter must not give the new block the same id.
+ keepOnSplit: false,
+ parseHTML: (el) => {
+ const id = el.getAttribute("data-block-id");
+ return id && BLOCK_ID.test(id) ? id : null;
+ },
+ renderHTML: (attrs) => (attrs.blockId ? { "data-block-id": attrs.blockId } : {}),
+ },
+ },
+ },
+ ];
+ },
+
+ addProseMirrorPlugins() {
+ const { link, onCopied } = this.options;
+ const labels = this.options.labels!;
+ if (!link) return [];
+ return [
+ new Plugin({
+ key: new PluginKey("blockLinks"),
+ view: (view) => new BlockHandle(view, labels.blocks.copyBlockLink, link, onCopied),
+ }),
+ ];
+ },
+});
+
+/** The "copy link" button that follows the pointer from block to block. */
+class BlockHandle {
+ private button = document.createElement("button");
+ private pos = -1;
+
+ constructor(
+ private view: EditorView,
+ label: string,
+ private link: (hash: string) => string,
+ private onCopied?: (url: string) => void,
+ ) {
+ const b = this.button;
+ b.type = "button";
+ b.className = "dw-block-handle";
+ b.setAttribute("aria-label", label);
+ b.title = label;
+ b.contentEditable = "false";
+ // A chain-link glyph; the editor package draws no icons of its own.
+ b.innerHTML =
+ '';
+ b.hidden = true;
+ b.addEventListener("mousedown", (e) => e.preventDefault());
+ b.addEventListener("click", () => void this.copy());
+ b.addEventListener("mouseleave", this.leave);
+ view.dom.addEventListener("mousemove", this.move);
+ view.dom.addEventListener("mouseleave", this.leave);
+ }
+
+ /** The element around the editor, which the button sits in. Hosts may move the editor after creating it. */
+ private get host(): HTMLElement | null {
+ const host = this.view.dom.parentElement;
+ if (host && this.button.parentElement !== host) {
+ host.classList.add("dw-block-host");
+ host.append(this.button);
+ }
+ return host;
+ }
+
+ private hide = () => {
+ this.button.hidden = true;
+ this.pos = -1;
+ };
+
+ // Moving from the text onto the button keeps it.
+ private leave = (e: MouseEvent) => {
+ const to = e.relatedTarget as Node | null;
+ if (to && (this.button.contains(to) || this.view.dom.contains(to))) return;
+ this.hide();
+ };
+
+ private move = (e: MouseEvent) => {
+ // The top-level block under the pointer.
+ let el = e.target as HTMLElement | null;
+ while (el && el.parentElement !== this.view.dom) el = el.parentElement;
+ const host = this.host;
+ if (!el || !host) return this.hide();
+ let pos: number;
+ try {
+ pos = this.view.posAtDOM(el, 0);
+ } catch {
+ return this.hide();
+ }
+ const $pos = this.view.state.doc.resolve(Math.min(pos, this.view.state.doc.content.size));
+ const start = $pos.depth >= 1 ? $pos.before(1) : pos;
+ const node = this.view.state.doc.nodeAt(start);
+ // Readers can only copy links that exist; only editors can add an id.
+ if (!node || !linkable.includes(node.type.name) || (!node.attrs.blockId && !this.view.editable)) {
+ return this.hide();
+ }
+ this.pos = start;
+ const box = el.getBoundingClientRect();
+ const hostBox = host.getBoundingClientRect();
+ this.button.style.top = `${box.top - hostBox.top + Math.min(box.height / 2, 14) - 11}px`;
+ this.button.hidden = false;
+ };
+
+ private async copy() {
+ const node = this.pos >= 0 ? this.view.state.doc.nodeAt(this.pos) : null;
+ if (!node) return;
+ let id = node.attrs.blockId as string | null;
+ if (!id) {
+ if (!this.view.editable) return;
+ id = newBlockId();
+ this.view.dispatch(this.view.state.tr.setNodeAttribute(this.pos, "blockId", id));
+ }
+ const url = this.link(blockHash(id));
+ try {
+ await navigator.clipboard.writeText(url);
+ this.onCopied?.(url);
+ } catch {
+ window.prompt("", url);
+ }
+ }
+
+ update() {
+ // Positions move as people type; the next pointer move finds the block again.
+ if (this.pos >= this.view.state.doc.content.size) this.hide();
+ }
+
+ destroy() {
+ this.button.parentElement?.classList.remove("dw-block-host");
+ this.button.remove();
+ this.view.dom.removeEventListener("mousemove", this.move);
+ this.view.dom.removeEventListener("mouseleave", this.leave);
+ }
+}
diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css
index f42854f..81f0a2d 100644
--- a/Packages/editor/src/editor.css
+++ b/Packages/editor/src/editor.css
@@ -405,6 +405,173 @@
color: var(--color-ink-faint);
}
+/* ---- Toggles ---- */
+.dw-prose .dw-toggle {
+ display: flex;
+ gap: 4px;
+ align-items: flex-start;
+}
+.dw-prose .dw-toggle > button {
+ flex: none;
+ display: grid;
+ place-items: center;
+ width: 24px;
+ height: calc(var(--text-doc-body--line-height) * 1em);
+ border: none;
+ border-radius: var(--radius-xs);
+ background: none;
+ color: var(--color-ink-muted);
+ cursor: pointer;
+}
+.dw-prose .dw-toggle > button:hover {
+ background: var(--color-surface-hover);
+ color: var(--color-ink);
+}
+.dw-prose .dw-toggle > button::before {
+ content: "";
+ width: 0;
+ height: 0;
+ border-top: 5px solid transparent;
+ border-bottom: 5px solid transparent;
+ border-left: 7px solid currentColor;
+ transition: transform 0.12s ease;
+}
+.dw-prose .dw-toggle.is-open > button::before {
+ transform: rotate(90deg);
+}
+.dw-prose .dw-toggle > div {
+ flex: 1;
+ min-width: 0;
+}
+.dw-prose .dw-toggle summary {
+ display: block;
+ list-style: none;
+ font-weight: 600;
+}
+.dw-prose .dw-toggle summary::-webkit-details-marker {
+ display: none;
+}
+.dw-prose .dw-toggle [data-type="detailsContent"] > * + * {
+ margin-top: 8px;
+}
+.dw-prose .dw-toggle [data-type="detailsContent"] {
+ margin-top: 4px;
+}
+.dw-prose .dw-toggle [data-type="detailsContent"][hidden] {
+ display: none;
+}
+
+/* ---- Embeds and link cards ---- */
+.dw-prose .dw-embed {
+ margin: 0;
+}
+.dw-prose .dw-embed__frame {
+ display: block;
+ width: 100%;
+ aspect-ratio: 16 / 9;
+ border: 1px solid var(--color-line);
+ border-radius: var(--radius-md);
+ background: var(--color-surface-sunken);
+}
+.dw-prose .dw-embed[data-ratio="audio"] .dw-embed__frame {
+ aspect-ratio: auto;
+ height: 152px;
+}
+.dw-prose .dw-embed[data-ratio="tall"] .dw-embed__frame {
+ aspect-ratio: 4 / 5;
+ max-height: 80vh;
+}
+.dw-prose .dw-embed__caption {
+ margin-top: 4px;
+ font-family: var(--font-sans);
+ font-size: var(--text-ui-sm);
+ color: var(--color-ink-muted);
+}
+.dw-prose .dw-embed__caption a {
+ color: inherit;
+}
+.dw-prose .dw-linkcard {
+ display: flex;
+ align-items: stretch;
+ gap: 12px;
+ overflow: hidden;
+ border: 1px solid var(--color-line);
+ border-radius: var(--radius-md);
+ color: var(--color-ink);
+ text-decoration: none;
+ font-family: var(--font-sans);
+}
+.dw-prose .dw-linkcard:hover {
+ background: var(--color-surface-hover);
+}
+.dw-prose .dw-linkcard__text {
+ display: flex;
+ flex: 1;
+ min-width: 0;
+ flex-direction: column;
+ gap: 2px;
+ padding: 10px 14px;
+}
+.dw-prose .dw-linkcard__title {
+ font-size: var(--text-ui-md);
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.dw-prose .dw-linkcard__desc {
+ font-size: var(--text-ui-sm);
+ color: var(--color-ink-muted);
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+.dw-prose .dw-linkcard__site {
+ font-size: var(--text-ui-xs);
+ color: var(--color-ink-faint);
+}
+.dw-prose .dw-linkcard__image {
+ flex: none;
+ width: 30%;
+ max-width: 200px;
+ max-height: 120px;
+ object-fit: cover;
+}
+.dw-prose .ProseMirror-selectednode:is(.dw-embed, .dw-linkcard) {
+ outline: 2px solid var(--color-focus-ring);
+ outline-offset: 2px;
+ border-radius: var(--radius-md);
+}
+
+/* ---- Block links ---- */
+.dw-block-host {
+ position: relative;
+}
+.dw-block-handle {
+ position: absolute;
+ left: -30px;
+ display: grid;
+ place-items: center;
+ width: 22px;
+ height: 22px;
+ border: none;
+ border-radius: var(--radius-xs);
+ background: none;
+ color: var(--color-ink-faint);
+ cursor: pointer;
+}
+.dw-block-handle:hover {
+ background: var(--color-surface-hover);
+ color: var(--color-ink);
+}
+/* Phones have no margin to spare and no hover. */
+@media (max-width: 640px), (hover: none) {
+ .dw-block-handle {
+ display: none;
+ }
+}
+
/* ---- The floating source editor (math, Mermaid) ---- */
.dw-source {
position: absolute;
diff --git a/Packages/editor/src/embeds.ts b/Packages/editor/src/embeds.ts
new file mode 100644
index 0000000..2b69957
--- /dev/null
+++ b/Packages/editor/src/embeds.ts
@@ -0,0 +1,374 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import { Node, mergeAttributes, type Editor } from "@tiptap/core";
+import type { EditorLabels } from "./labels";
+import { editSource } from "./source";
+
+declare module "@tiptap/core" {
+ interface Commands {
+ embeds: {
+ insertEmbed: (url: string) => ReturnType;
+ insertLinkCard: (card: LinkPreview) => ReturnType;
+ };
+ }
+}
+
+/** What a link card shows. Stored in the document, so readers fetch nothing. */
+export interface LinkPreview {
+ url: string;
+ title?: string;
+ description?: string;
+ image?: string;
+ site?: string;
+}
+
+/**
+ * Fetches a page's title, description and picture for a link card. Pages on
+ * other sites can't be read from the browser, so hosts ask docwell-server.
+ */
+export interface LinkHost {
+ preview(url: string): Promise;
+}
+
+// Each provider turns a page address into its player address. Only these
+// sites are framed; any other address becomes a link card instead.
+const providers: { pattern: RegExp; src: (m: RegExpExecArray, url: URL) => string; ratio?: string }[] = [
+ {
+ pattern: /^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,
+ src: (m) => `https://www.youtube-nocookie.com/embed/${m[1]}`,
+ },
+ { pattern: /^https:\/\/youtu\.be\/([\w-]{11})/, src: (m) => `https://www.youtube-nocookie.com/embed/${m[1]}` },
+ {
+ pattern: /^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,
+ src: (m) => `https://player.vimeo.com/video/${m[1]}`,
+ },
+ {
+ pattern: /^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,
+ src: (m) => `https://www.loom.com/embed/${m[1]}`,
+ },
+ {
+ pattern: /^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,
+ src: (_m, url) => `https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(url.href)}`,
+ },
+ {
+ pattern: /^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,
+ src: (m) => `https://codepen.io/${m[1]}/embed/${m[2]}?default-tab=result`,
+ },
+ {
+ pattern: /^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,
+ src: (m) => `https://open.spotify.com/embed/${m[1]}/${m[2]}`,
+ ratio: "audio",
+ },
+ {
+ pattern: /^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,
+ src: (m) => `https://docs.google.com/${m[1]}/d/${m[2]}/preview`,
+ ratio: "tall",
+ },
+ { pattern: /^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/, src: (_m, url) => url.href },
+];
+
+/** The player address for a page on a supported site, or null. */
+export function embedSource(raw: string): { src: string; ratio: string } | null {
+ let url: URL;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ return null;
+ }
+ for (const p of providers) {
+ const m = p.pattern.exec(url.href);
+ if (m) return { src: p.src(m, url), ratio: p.ratio ?? "video" };
+ }
+ return null;
+}
+
+/** An http(s) address, or "" for anything else (javascript:, data:, typos). */
+export function webUrl(raw: string): string {
+ try {
+ const url = new URL(raw.trim());
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : "";
+ } catch {
+ return "";
+ }
+}
+
+const hostOf = (url: string) => {
+ try {
+ return new URL(url).hostname.replace(/^www\./, "");
+ } catch {
+ return url;
+ }
+};
+
+/** Asks for an address under anchor and resolves with it ("" when cancelled). */
+function askUrl(editor: Editor, labels: EditorLabels, label: string): Promise {
+ const { node } = editor.view.domAtPos(editor.state.selection.from);
+ const el = node instanceof HTMLElement ? node : (node.parentElement ?? editor.view.dom);
+ return new Promise((resolve) => {
+ const l = labels.blocks;
+ editSource({
+ anchor: el,
+ value: "https://",
+ label,
+ labels: { done: l.done, cancel: l.cancel, remove: l.remove },
+ onSave: (v) => resolve(webUrl(v)),
+ onCancel: () => resolve(""),
+ });
+ });
+}
+
+/** "/embed": asks for an address and frames it, or makes a card when the site can't be framed. */
+export async function promptEmbed(
+ editor: Editor,
+ labels: EditorLabels,
+ links?: LinkHost,
+ onError?: (e: unknown) => void,
+) {
+ const url = await askUrl(editor, labels, labels.blocks.embedUrl);
+ if (!url) return;
+ if (embedSource(url)) editor.chain().focus().insertEmbed(url).run();
+ else await insertCard(editor, url, links, onError);
+}
+
+/** "/bookmark": asks for an address and inserts a link card for it. */
+export async function promptLinkCard(
+ editor: Editor,
+ labels: EditorLabels,
+ links?: LinkHost,
+ onError?: (e: unknown) => void,
+) {
+ const url = await askUrl(editor, labels, labels.blocks.linkUrl);
+ if (url) await insertCard(editor, url, links, onError);
+}
+
+async function insertCard(editor: Editor, url: string, links?: LinkHost, onError?: (e: unknown) => void) {
+ let card: LinkPreview = { url };
+ if (links) {
+ try {
+ card = { ...(await links.preview(url)), url };
+ } catch (e) {
+ // A card with just the address is still useful.
+ onError?.(e);
+ }
+ }
+ editor.chain().focus().insertLinkCard(card).run();
+}
+
+/**
+ * A video, design or document from a supported site, shown in a sandboxed
+ * frame. Only the page address is stored; each client works out the player.
+ */
+export const Embed = Node.create<{ labels: EditorLabels | null }>({
+ name: "embed",
+ group: "block",
+ atom: true,
+ draggable: true,
+
+ addOptions() {
+ return { labels: null };
+ },
+
+ addAttributes() {
+ return {
+ url: {
+ default: "",
+ parseHTML: (el) => el.getAttribute("data-url") ?? "",
+ renderHTML: (attrs) => ({ "data-url": attrs.url }),
+ },
+ };
+ },
+
+ parseHTML() {
+ return [{ tag: "div[data-type='embed']" }];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ const url = webUrl(String(node.attrs.url));
+ return ["div", mergeAttributes(HTMLAttributes, { "data-type": "embed" }), ["a", { href: url }, url]];
+ },
+
+ addCommands() {
+ return {
+ insertEmbed:
+ (url) =>
+ ({ commands }) =>
+ commands.insertContent({ type: this.name, attrs: { url } }),
+ };
+ },
+
+ addNodeView() {
+ return ({ node }) => {
+ const labels = this.options.labels!.blocks;
+ const dom = document.createElement("figure");
+ dom.className = "dw-embed";
+ dom.setAttribute("data-type", "embed");
+ dom.contentEditable = "false";
+ const draw = (raw: string) => {
+ const url = webUrl(raw);
+ const source = embedSource(url);
+ dom.replaceChildren();
+ if (!source) {
+ // Not framable (any more): keep the address as a link.
+ const a = document.createElement("a");
+ a.href = url;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer";
+ a.textContent = url || labels.embedInvalid;
+ dom.append(a);
+ return;
+ }
+ dom.dataset.ratio = source.ratio;
+ const frame = document.createElement("iframe");
+ frame.className = "dw-embed__frame";
+ frame.src = source.src;
+ frame.title = `${labels.embed}: ${hostOf(url)}`;
+ frame.loading = "lazy";
+ frame.allow = "fullscreen; picture-in-picture; encrypted-media; clipboard-write";
+ frame.referrerPolicy = "strict-origin-when-cross-origin";
+ // The players need scripts and their own origin; nothing else.
+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-popups allow-presentation");
+ const caption = document.createElement("figcaption");
+ caption.className = "dw-embed__caption";
+ const a = document.createElement("a");
+ a.href = url;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer";
+ a.textContent = hostOf(url);
+ caption.append(a);
+ dom.append(frame, caption);
+ };
+ let current = String(node.attrs.url);
+ draw(current);
+ return {
+ dom,
+ update: (n) => {
+ if (n.type.name !== "embed") return false;
+ if (n.attrs.url !== current) draw((current = String(n.attrs.url)));
+ return true;
+ },
+ ignoreMutation: () => true,
+ stopEvent: (e) => e.target instanceof Element && !!e.target.closest("a"),
+ };
+ };
+ },
+});
+
+/** A link shown as a card with the page's title, description and picture. */
+export const LinkCard = Node.create<{ labels: EditorLabels | null }>({
+ name: "linkCard",
+ group: "block",
+ atom: true,
+ draggable: true,
+
+ addOptions() {
+ return { labels: null };
+ },
+
+ addAttributes() {
+ const attr = (name: string) => ({
+ default: "",
+ parseHTML: (el: HTMLElement) => el.getAttribute(`data-${name}`) ?? "",
+ renderHTML: (attrs: Record) => ({ [`data-${name}`]: attrs[name] }),
+ });
+ return {
+ url: attr("url"),
+ title: attr("title"),
+ description: attr("description"),
+ image: attr("image"),
+ site: attr("site"),
+ };
+ },
+
+ parseHTML() {
+ return [{ tag: "div[data-type='link-card']" }];
+ },
+
+ renderHTML({ node, HTMLAttributes }) {
+ const url = webUrl(String(node.attrs.url));
+ return [
+ "div",
+ mergeAttributes(HTMLAttributes, { "data-type": "link-card" }),
+ ["a", { href: url }, String(node.attrs.title || url)],
+ ];
+ },
+
+ addCommands() {
+ return {
+ insertLinkCard:
+ (card) =>
+ ({ commands }) =>
+ commands.insertContent({
+ type: this.name,
+ attrs: {
+ url: card.url,
+ title: card.title ?? "",
+ description: card.description ?? "",
+ image: card.image ?? "",
+ site: card.site ?? "",
+ },
+ }),
+ };
+ },
+
+ addNodeView() {
+ return ({ node }) => {
+ const dom = document.createElement("a");
+ dom.className = "dw-linkcard";
+ dom.setAttribute("data-type", "link-card");
+ dom.contentEditable = "false";
+ dom.target = "_blank";
+ dom.rel = "noopener noreferrer";
+ const draw = (attrs: Record) => {
+ const url = webUrl(String(attrs.url));
+ dom.href = url;
+ dom.replaceChildren();
+ const text = document.createElement("span");
+ text.className = "dw-linkcard__text";
+ const title = document.createElement("span");
+ title.className = "dw-linkcard__title";
+ title.textContent = String(attrs.title || "") || hostOf(url);
+ text.append(title);
+ if (attrs.description) {
+ const desc = document.createElement("span");
+ desc.className = "dw-linkcard__desc";
+ desc.textContent = String(attrs.description);
+ text.append(desc);
+ }
+ const site = document.createElement("span");
+ site.className = "dw-linkcard__site";
+ site.textContent = String(attrs.site || "") || hostOf(url);
+ text.append(site);
+ dom.append(text);
+ const image = webUrl(String(attrs.image || ""));
+ if (image.startsWith("https:")) {
+ const img = document.createElement("img");
+ img.className = "dw-linkcard__image";
+ img.src = image;
+ img.alt = "";
+ img.loading = "lazy";
+ // Other sites don't learn which page their picture is shown on.
+ img.referrerPolicy = "no-referrer";
+ img.onerror = () => img.remove();
+ dom.append(img);
+ }
+ };
+ let current = node;
+ draw(node.attrs);
+ // Editing places the caret; following the link needs Ctrl/Cmd, as with text links.
+ dom.addEventListener("click", (e) => {
+ const view = this.editor.view;
+ if (view.editable && !(e.ctrlKey || e.metaKey)) e.preventDefault();
+ });
+ return {
+ dom,
+ update: (n) => {
+ if (n.type.name !== "linkCard") return false;
+ if (n.attrs !== current.attrs) draw(n.attrs);
+ current = n;
+ return true;
+ },
+ ignoreMutation: () => true,
+ };
+ };
+ },
+});
diff --git a/Packages/editor/src/extensions.ts b/Packages/editor/src/extensions.ts
index a277d22..2939252 100644
--- a/Packages/editor/src/extensions.ts
+++ b/Packages/editor/src/extensions.ts
@@ -5,8 +5,10 @@ import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCaret from "@tiptap/extension-collaboration-caret";
import { Placeholder } from "@tiptap/extensions";
import StarterKit from "@tiptap/starter-kit";
+import { BlockLinks } from "./blocklinks";
import { CommentHighlights } from "./comments";
import { DrawioBlock, ExcalidrawBlock, type ExcalidrawLoader } from "./diagrams";
+import { Embed, LinkCard, type LinkHost } from "./embeds";
import { DocwellImage, FileAttachment, FileDrop, type FileHost } from "./files";
import { englishLabels, type EditorLabels } from "./labels";
import { docwellMath } from "./math";
@@ -16,6 +18,7 @@ import { PageLinks, type PageHost } from "./pagelinks";
import { SlashMenu, slashCommands } from "./slash";
import type { CollabProvider } from "./provider";
import { TableOfContents } from "./toc";
+import { docwellToggles } from "./toggle";
export interface CollabUser {
name: string;
@@ -32,6 +35,15 @@ export interface ExtensionOptions {
mentions?: MentionHost;
/** Finds pages for "[[" links. */
pages?: PageHost;
+ /** Fetches previews for link cards; without it cards show the address only. */
+ links?: LinkHost;
+ /**
+ * The full address of a link to a block of this page, from its "#b-"
+ * fragment. Without it the margin has no "copy link" button.
+ */
+ blockLink?: (hash: string) => string;
+ /** Called after a block link was copied. */
+ onBlockLinkCopied?: (url: string) => void;
/** Opens an app route, e.g. "/p/" when a page link is followed. */
onNavigate?: (path: string) => void;
/** The Draw.io embed address (default https://embed.diagrams.net). */
@@ -81,7 +93,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
SlashMenu.configure({
- commands: slashCommands(labels, opts.files, opts.onError, opts.pages, !!opts.loadExcalidraw),
+ commands: slashCommands(labels, opts.files, opts.onError, opts.pages, !!opts.loadExcalidraw, opts.links),
labels,
}),
CommentHighlights.configure({ onSelect: opts.onCommentSelect }),
@@ -91,6 +103,10 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
DrawioBlock.configure(diagrams),
ExcalidrawBlock.configure(diagrams),
PageLinks.configure({ host: opts.pages, labels, onNavigate: opts.onNavigate }),
+ ...docwellToggles(labels),
+ Embed.configure({ labels }),
+ LinkCard.configure({ labels }),
+ BlockLinks.configure({ labels, link: opts.blockLink, onCopied: opts.onBlockLinkCopied }),
];
if (opts.collab) {
list.push(
diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts
index 73b3a5e..ddbac01 100644
--- a/Packages/editor/src/index.ts
+++ b/Packages/editor/src/index.ts
@@ -11,3 +11,5 @@ export { insertFiles, type FileHost, type UploadedFile } from "./files";
export { CollabProvider, type CollabProviderOptions, type CollabStatus } from "./provider";
export { linkedPage, pagePath, type PageHost, type PageRef as LinkablePage } from "./pagelinks";
export { headingsOf, type Heading } from "./toc";
+export { blockHash, linkedBlock, scrollToBlock } from "./blocklinks";
+export { embedSource, type LinkHost, type LinkPreview } from "./embeds";
diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts
index c83573a..39d6384 100644
--- a/Packages/editor/src/labels.ts
+++ b/Packages/editor/src/labels.ts
@@ -38,6 +38,13 @@ export interface EditorLabels {
loadFailed: string;
toc: string;
tocEmpty: string;
+ expand: string;
+ collapse: string;
+ embed: string;
+ embedUrl: string;
+ embedInvalid: string;
+ linkUrl: string;
+ copyBlockLink: string;
};
}
@@ -63,6 +70,9 @@ export const englishLabels: EditorLabels = {
excalidraw: { label: "Excalidraw drawing", description: "Sketch by hand" },
toc: { label: "Table of contents", description: "The page's headings, kept up to date" },
pageLink: { label: "Link to page", description: "Link another page (or type [[)" },
+ toggle: { label: "Toggle", description: "A heading that hides the blocks under it" },
+ embed: { label: "Embed", description: "A video, design or document from YouTube, Figma and more" },
+ linkCard: { label: "Link card", description: "A link with its page's title and picture" },
},
format: {
bold: "Bold",
@@ -92,5 +102,12 @@ export const englishLabels: EditorLabels = {
loadFailed: "The editor could not be loaded.",
toc: "Contents",
tocEmpty: "Add headings to the page to fill the table of contents.",
+ expand: "Show contents",
+ collapse: "Hide contents",
+ embed: "Embedded content",
+ embedUrl: "Address of the video, design or document",
+ embedInvalid: "This address can't be embedded.",
+ linkUrl: "Address of the page to link",
+ copyBlockLink: "Copy link to this block",
},
};
diff --git a/Packages/editor/src/slash.ts b/Packages/editor/src/slash.ts
index 95d4bb9..04d9b23 100644
--- a/Packages/editor/src/slash.ts
+++ b/Packages/editor/src/slash.ts
@@ -4,6 +4,7 @@ import { Extension, type Editor, type Range } from "@tiptap/core";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import type { IconName } from "@docwell/ui/icons";
+import { promptEmbed, promptLinkCard, type LinkHost } from "./embeds";
import { insertFiles, type FileHost } from "./files";
import type { PageHost } from "./pagelinks";
import type { EditorLabels } from "./labels";
@@ -39,6 +40,7 @@ export function slashCommands(
onError?: (e: unknown) => void,
pages?: PageHost,
excalidraw = false,
+ links?: LinkHost,
): SlashCommand[] {
const block = (
id: string,
@@ -72,6 +74,9 @@ export function slashCommands(
block("code", "code", ["codeblock", "```", "snippet"], (e, r) =>
e.chain().focus().deleteRange(r).toggleCodeBlock().run(),
),
+ block("toggle", "chevron-right", ["details", "collapse", "expand", "fold", ">"], (e, r) =>
+ e.chain().focus().deleteRange(r).setDetails().run(),
+ ),
block("divider", "divider", ["hr", "rule", "line", "---"], (e, r) =>
e.chain().focus().deleteRange(r).setHorizontalRule().run(),
),
@@ -87,6 +92,14 @@ export function slashCommands(
block("mermaid", "diagram", ["diagram", "flowchart", "chart", "sequence", "graph"], (e, r) =>
e.chain().focus().deleteRange(r).insertMermaid().run(),
),
+ block("embed", "video", ["video", "youtube", "vimeo", "figma", "loom", "iframe", "map"], (e, r) => {
+ e.chain().focus().deleteRange(r).run();
+ void promptEmbed(e, l, links, onError);
+ }),
+ block("linkCard", "link", ["bookmark", "preview", "card", "url", "web"], (e, r) => {
+ e.chain().focus().deleteRange(r).run();
+ void promptLinkCard(e, l, links, onError);
+ }),
];
if (pages) {
list.push(
diff --git a/Packages/editor/src/toggle.ts b/Packages/editor/src/toggle.ts
new file mode 100644
index 0000000..111a3b4
--- /dev/null
+++ b/Packages/editor/src/toggle.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import { Details, DetailsContent, DetailsSummary } from "@tiptap/extension-details";
+import type { AnyExtension } from "@tiptap/core";
+import type { EditorLabels } from "./labels";
+
+/**
+ * Toggle blocks: a summary line that hides or shows the blocks under it.
+ * Whether a toggle is open is not saved, so one reader opening it does not
+ * open it for everyone editing the page.
+ */
+export function docwellToggles(labels: EditorLabels): AnyExtension[] {
+ return [
+ Details.configure({
+ persist: false,
+ HTMLAttributes: { class: "dw-toggle" },
+ renderToggleButton: ({ element, isOpen }) => {
+ element.setAttribute("aria-label", isOpen ? labels.blocks.collapse : labels.blocks.expand);
+ element.setAttribute("aria-expanded", String(isOpen));
+ },
+ }),
+ DetailsSummary,
+ DetailsContent,
+ ];
+}
diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts
index bcef9bc..91228d9 100644
--- a/Packages/ui/src/icons.ts
+++ b/Packages/ui/src/icons.ts
@@ -83,6 +83,10 @@ export const iconPaths = {
pencil: ["M15 5l4 4L8 20H4v-4z"],
sigma: ["M18 6V4H6l6 8l-6 8h12v-2"],
diagram: ["M4 4h6v5H4z", "M14 15h6v5h-6z", "M7 9v4a2 2 0 0 0 2 2h5"],
+ // Phase 2: embeds, archive, servers.
+ video: ["M4 6h11v12H4z", "M15 10l5-3v10l-5-3"],
+ archive: ["M4 5h16v4H4z", "M5 9v10h14V9", "M10 13h4"],
+ server: ["M4 4h16v6H4z", "M4 14h16v6H4z", "M8 7h.01", "M8 17h.01"],
users: [
"M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z",
"M3 20a6 6 0 0 1 12 0",
diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart
index 6b51ed5..57f34bd 100644
--- a/Phone-App/lib/api/generated/models.dart
+++ b/Phone-App/lib/api/generated/models.dart
@@ -662,6 +662,8 @@ class Page {
required this.updated,
required this.deletedAt,
required this.inTrash,
+ required this.archivedAt,
+ required this.archived,
required this.ancestors,
required this.role,
required this.restricted,
@@ -680,6 +682,8 @@ class Page {
updated: json['updated'] as String,
deletedAt: json['deletedAt'] as String,
inTrash: json['inTrash'] as bool,
+ archivedAt: json['archivedAt'] as String,
+ archived: json['archived'] as bool,
ancestors: (json['ancestors'] as List)
.map((e) => PageRef.fromJson(e as Map))
.toList(),
@@ -711,6 +715,12 @@ class Page {
/// The page or one of its ancestors is in the trash
final bool inTrash;
+ /// When the page itself was archived; empty otherwise
+ final String archivedAt;
+
+ /// The page or one of its ancestors is archived (read-only)
+ final bool archived;
+
/// Root first; pages the caller cannot open are left out
final List ancestors;
@@ -737,6 +747,8 @@ class Page {
'updated': updated,
'deletedAt': deletedAt,
'inTrash': inTrash,
+ 'archivedAt': archivedAt,
+ 'archived': archived,
'ancestors': ancestors.map((e) => e.toJson()).toList(),
'role': role.toJson(),
'restricted': restricted,
@@ -1036,6 +1048,74 @@ class TrashedPage {
};
}
+class ArchivedPage {
+ const ArchivedPage({
+ required this.id,
+ required this.title,
+ required this.icon,
+ required this.archivedAt,
+ });
+
+ factory ArchivedPage.fromJson(Map json) => ArchivedPage(
+ id: json['id'] as String,
+ title: json['title'] as String,
+ icon: json['icon'] as String,
+ archivedAt: json['archivedAt'] as String,
+ );
+
+ final String id;
+
+ final String title;
+
+ final String icon;
+
+ final String archivedAt;
+
+ Map toJson() => {
+ 'id': id,
+ 'title': title,
+ 'icon': icon,
+ 'archivedAt': archivedAt,
+ };
+}
+
+class LinkPreview {
+ const LinkPreview({
+ required this.url,
+ required this.title,
+ required this.description,
+ required this.image,
+ required this.site,
+ });
+
+ factory LinkPreview.fromJson(Map json) => LinkPreview(
+ url: json['url'] as String,
+ title: json['title'] as String,
+ description: json['description'] as String,
+ image: json['image'] as String,
+ site: json['site'] as String,
+ );
+
+ final String url;
+
+ final String title;
+
+ final String description;
+
+ /// Address of the page's picture on its own site; empty when it has none
+ final String image;
+
+ final String site;
+
+ Map toJson() => {
+ 'url': url,
+ 'title': title,
+ 'description': description,
+ 'image': image,
+ 'site': site,
+ };
+}
+
class Session {
const Session({required this.token, required this.user});
@@ -1844,6 +1924,8 @@ enum WebhookEvent {
pageTrashed('page.trashed'),
pageRestored('page.restored'),
pageDeleted('page.deleted'),
+ pageArchived('page.archived'),
+ pageUnarchived('page.unarchived'),
commentCreated('comment.created'),
commentResolved('comment.resolved'),
spaceCreated('space.created'),
diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go
index fecdd53..c66ac41 100644
--- a/Server/cmd/docwell-server/main.go
+++ b/Server/cmd/docwell-server/main.go
@@ -29,6 +29,7 @@ import (
"docwell/server/internal/search"
"docwell/server/internal/settings"
"docwell/server/internal/store/pocketbase"
+ "docwell/server/internal/unfurl"
"docwell/server/internal/webhooks"
"docwell/server/internal/ycrdt"
)
@@ -137,6 +138,7 @@ func run(log *slog.Logger) error {
Instance: instance.New(db, Version, hub, index, reg),
Collab: hub,
Audit: auditLog,
+ Previews: unfurl.New(),
Admin: admin.Handler("/admin"),
Log: log,
}),
diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go
index a44f73e..6f5d318 100644
--- a/Server/internal/api/api.gen.go
+++ b/Server/internal/api/api.gen.go
@@ -389,11 +389,13 @@ const (
Asterisk WebhookEvent = "*"
CommentCreated WebhookEvent = "comment.created"
CommentResolved WebhookEvent = "comment.resolved"
+ PageArchived WebhookEvent = "page.archived"
PageCreated WebhookEvent = "page.created"
PageDeleted WebhookEvent = "page.deleted"
PageMoved WebhookEvent = "page.moved"
PageRestored WebhookEvent = "page.restored"
PageTrashed WebhookEvent = "page.trashed"
+ PageUnarchived WebhookEvent = "page.unarchived"
PageUpdated WebhookEvent = "page.updated"
SpaceCreated WebhookEvent = "space.created"
SpaceDeleted WebhookEvent = "space.deleted"
@@ -408,6 +410,8 @@ func (e WebhookEvent) Valid() bool {
return true
case CommentResolved:
return true
+ case PageArchived:
+ return true
case PageCreated:
return true
case PageDeleted:
@@ -418,6 +422,8 @@ func (e WebhookEvent) Valid() bool {
return true
case PageTrashed:
return true
+ case PageUnarchived:
+ return true
case PageUpdated:
return true
case SpaceCreated:
@@ -473,19 +479,37 @@ func (e CreateApiTokenJSONBodyScope) Valid() bool {
// Defines values for ExportPageParamsFormat.
const (
- Html ExportPageParamsFormat = "html"
- Markdown ExportPageParamsFormat = "markdown"
- Pdf ExportPageParamsFormat = "pdf"
+ ExportPageParamsFormatHtml ExportPageParamsFormat = "html"
+ ExportPageParamsFormatMarkdown ExportPageParamsFormat = "markdown"
+ ExportPageParamsFormatPdf ExportPageParamsFormat = "pdf"
)
// Valid indicates whether the value is a known member of the ExportPageParamsFormat enum.
func (e ExportPageParamsFormat) Valid() bool {
switch e {
- case Html:
+ case ExportPageParamsFormatHtml:
return true
- case Markdown:
+ case ExportPageParamsFormatMarkdown:
return true
- case Pdf:
+ case ExportPageParamsFormatPdf:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for ExportSpaceParamsFormat.
+const (
+ ExportSpaceParamsFormatHtml ExportSpaceParamsFormat = "html"
+ ExportSpaceParamsFormatMarkdown ExportSpaceParamsFormat = "markdown"
+)
+
+// Valid indicates whether the value is a known member of the ExportSpaceParamsFormat enum.
+func (e ExportSpaceParamsFormat) Valid() bool {
+ switch e {
+ case ExportSpaceParamsFormatHtml:
+ return true
+ case ExportSpaceParamsFormatMarkdown:
return true
default:
return false
@@ -560,6 +584,14 @@ type ApiToken struct {
// ApiTokenScope defines model for ApiToken.Scope.
type ApiTokenScope string
+// ArchivedPage defines model for ArchivedPage.
+type ArchivedPage struct {
+ ArchivedAt string `json:"archivedAt"`
+ Icon string `json:"icon"`
+ Id string `json:"id"`
+ Title string `json:"title"`
+}
+
// Attachment defines model for Attachment.
type Attachment struct {
Created string `json:"created"`
@@ -819,6 +851,17 @@ type Job struct {
Runs int `json:"runs"`
}
+// LinkPreview defines model for LinkPreview.
+type LinkPreview struct {
+ Description string `json:"description"`
+
+ // Image Address of the page's picture on its own site; empty when it has none
+ Image string `json:"image"`
+ Site string `json:"site"`
+ Title string `json:"title"`
+ Url string `json:"url"`
+}
+
// LoginRequest defines model for LoginRequest.
type LoginRequest struct {
Email openapi_types.Email `json:"email"`
@@ -941,7 +984,13 @@ type Organization struct {
type Page struct {
// Ancestors Root first; pages the caller cannot open are left out
Ancestors []PageRef `json:"ancestors"`
- Created string `json:"created"`
+
+ // Archived The page or one of its ancestors is archived (read-only)
+ Archived bool `json:"archived"`
+
+ // ArchivedAt When the page itself was archived; empty otherwise
+ ArchivedAt string `json:"archivedAt"`
+ Created string `json:"created"`
// DeletedAt When the page itself was trashed; empty otherwise
DeletedAt string `json:"deletedAt"`
@@ -1533,6 +1582,11 @@ type ListInvitesParams struct {
Organization *string `form:"organization,omitempty" json:"organization,omitempty"`
}
+// PreviewLinkParams defines parameters for PreviewLink.
+type PreviewLinkParams struct {
+ Url string `form:"url" json:"url"`
+}
+
// CreateApiTokenJSONBody defines parameters for CreateApiToken.
type CreateApiTokenJSONBody struct {
// ExpiresDays 0 never expires
@@ -1664,6 +1718,14 @@ type UpdateSpaceJSONBody struct {
Visibility *SpaceVisibility `json:"visibility,omitempty"`
}
+// ExportSpaceParams defines parameters for ExportSpace.
+type ExportSpaceParams struct {
+ Format *ExportSpaceParamsFormat `form:"format,omitempty" json:"format,omitempty"`
+}
+
+// ExportSpaceParamsFormat defines parameters for ExportSpace.
+type ExportSpaceParamsFormat string
+
// SetSpaceGroupJSONBody defines parameters for SetSpaceGroup.
type SetSpaceGroupJSONBody struct {
Group string `json:"group"`
diff --git a/Server/internal/convert/export.go b/Server/internal/convert/export.go
index 00962f6..78381af 100644
--- a/Server/internal/convert/export.go
+++ b/Server/internal/convert/export.go
@@ -15,18 +15,30 @@ type Options struct {
// FileURL rewrites attachment paths (/api/v1/files/) so exported
// files link to the server; nil keeps them as they are.
FileURL func(path string) string
+ // PageURL rewrites links to pages (/p/, with an optional #fragment
+ // for a block), e.g. to files in a space export; nil keeps them.
+ PageURL func(id, fragment string) string
}
+var pageLink = regexp.MustCompile(`^/p/([A-Za-z0-9_-]+)/?(#[\w-]*)?$`)
+
+// file rewrites the server's own paths: attachments and links to pages.
func (o Options) file(path string) string {
if o.FileURL != nil && strings.HasPrefix(path, "/api/v1/files/") {
return o.FileURL(path)
}
+ if o.PageURL != nil {
+ if m := pageLink.FindStringSubmatch(path); m != nil {
+ return o.PageURL(m[1], m[2])
+ }
+ }
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:|/|#)`)
+// safeURL keeps links to the web, mail, the server's own paths, anchors and
+// relative files (a space export); anything with another scheme
+// (javascript:, data:, ...) is dropped.
+var safeURL = regexp.MustCompile(`^(?i)(https?://|mailto:|/|#|\.{0,2}/|[^:/?#]+(?:[/?#]|$))`)
// ---- HTML ------------------------------------------------------------------
@@ -104,6 +116,34 @@ func writeHTML(b *strings.Builder, n Node, o Options) {
fmt.Fprintf(b, "@%s", html.EscapeString(mentionLabel(n)))
case "tableOfContents":
// Nothing to keep: readers of the file see the headings themselves.
+ case "details":
+ b.WriteString("\n")
+ for _, c := range n.Content {
+ if c.Type == "detailsSummary" {
+ b.WriteString("")
+ for _, t := range c.Content {
+ writeHTML(b, t, o)
+ }
+ b.WriteString("
\n")
+ } else {
+ writeHTML(b, c, o)
+ }
+ }
+ b.WriteString(" \n")
+ case "embed", "linkCard":
+ href := n.attr("url")
+ if !safeURL.MatchString(href) {
+ return
+ }
+ title := n.attr("title")
+ if title == "" {
+ title = href
+ }
+ fmt.Fprintf(b, "%s", html.EscapeString(href), html.EscapeString(title))
+ if d := n.attr("description"); d != "" {
+ fmt.Fprintf(b, "
%s", html.EscapeString(d))
+ }
+ b.WriteString("
\n")
default:
tag, ok := htmlBlock[n.Type]
if !ok {
@@ -249,6 +289,38 @@ func (w *mdWriter) block(n Node, first, rest string) {
w.lines(")+")", first, rest)
}
case "tableOfContents":
+ case "details":
+ // GitHub and most Markdown viewers show as a toggle.
+ summary := ""
+ var body []Node
+ for _, c := range n.Content {
+ if c.Type == "detailsSummary" {
+ summary = PlainText(c)
+ } else {
+ body = append(body, c.Content...)
+ }
+ }
+ w.lines("\n"+html.EscapeString(summary)+"
", first, rest)
+ if len(body) > 0 {
+ w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
+ w.blocks(body, rest, rest)
+ }
+ w.b.WriteString(strings.TrimRight(rest, " ") + "\n")
+ w.lines(" ", rest, rest)
+ case "embed", "linkCard":
+ href := n.attr("url")
+ if !safeURL.MatchString(href) {
+ return
+ }
+ title := n.attr("title")
+ if title == "" {
+ title = href
+ }
+ line := "[" + escapeMD(title) + "](" + mdURL(href) + ")"
+ if d := n.attr("description"); d != "" {
+ line += " — " + escapeMD(d)
+ }
+ w.lines(line, first, rest)
default:
if len(n.Content) > 0 {
w.blocks(n.Content, first, rest)
diff --git a/Server/internal/convert/export_test.go b/Server/internal/convert/export_test.go
index 84c976d..9d2784a 100644
--- a/Server/internal/convert/export_test.go
+++ b/Server/internal/convert/export_test.go
@@ -40,3 +40,43 @@ func TestRichBlocks(t *testing.T) {
t.Fatalf("mermaid did not round-trip: %+v", back.Content[0])
}
}
+
+func TestTogglesEmbedsAndPageLinks(t *testing.T) {
+ doc, err := Parse([]byte(`{"type":"doc","content":[
+ {"type":"details","content":[
+ {"type":"detailsSummary","content":[{"type":"text","text":"More"}]},
+ {"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"Hidden"}]}]}]},
+ {"type":"embed","attrs":{"url":"https://youtu.be/dQw4w9WgXcQ"}},
+ {"type":"linkCard","attrs":{"url":"https://example.com/a","title":"Example","description":"About it"}},
+ {"type":"linkCard","attrs":{"url":"javascript:alert(1)","title":"Bad"}},
+ {"type":"paragraph","content":[{"type":"text","text":"see","marks":[{"type":"link","attrs":{"href":"/p/abc123#b-x1y2z3w4"}}]}]}]}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ o := Options{PageURL: func(id, frag string) string { return "../" + id + ".md" + frag }}
+ md := Markdown(doc, o)
+ for _, want := range []string{"\nMore
\n\nHidden\n\n ", "[https://youtu.be/dQw4w9WgXcQ](https://youtu.be/dQw4w9WgXcQ)",
+ "[Example](https://example.com/a) — About it", "[see](../abc123.md#b-x1y2z3w4)"} {
+ if !strings.Contains(md, want) {
+ t.Errorf("markdown lacks %q:\n%s", want, md)
+ }
+ }
+ h := HTML(doc, o)
+ for _, want := range []string{"\nMore
\nHidden
\n ", `Example
About it`, `see`} {
+ if !strings.Contains(h, want) {
+ t.Errorf("html lacks %q:\n%s", want, h)
+ }
+ }
+ if strings.Contains(md+h, "javascript:") {
+ t.Errorf("unsafe link kept:\n%s\n%s", md, h)
+ }
+
+ back, err := FromHTML(h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ d := back.Content[0]
+ if d.Type != "details" || PlainText(d.Content[0]) != "More" || PlainText(d.Content[1]) != "Hidden" {
+ t.Fatalf("details did not round-trip: %+v", d)
+ }
+}
diff --git a/Server/internal/convert/import.go b/Server/internal/convert/import.go
index b93917e..6d0fc2e 100644
--- a/Server/internal/convert/import.go
+++ b/Server/internal/convert/import.go
@@ -218,6 +218,20 @@ func (r *reader) block(n *html.Node) []Node {
code.Content = []Node{{Type: "text", Text: text}}
}
return []Node{code}
+ case atom.Details:
+ summary := Node{Type: "detailsSummary"}
+ var body []Node
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ if c.Type == html.ElementNode && c.DataAtom == atom.Summary && summary.Content == nil {
+ summary.Content = trimInline(r.inlineChildren(c, nil))
+ continue
+ }
+ body = append(body, r.block(c)...)
+ }
+ if len(body) == 0 {
+ body = []Node{{Type: "paragraph"}}
+ }
+ return []Node{{Type: "details", Content: []Node{summary, {Type: "detailsContent", Content: body}}}}
case atom.Hr:
return []Node{{Type: "horizontalRule"}}
case atom.Img:
diff --git a/Server/internal/convert/pdf.go b/Server/internal/convert/pdf.go
index 14521c8..de857ee 100644
--- a/Server/internal/convert/pdf.go
+++ b/Server/internal/convert/pdf.go
@@ -255,6 +255,25 @@ func (w *pdfWriter) block(n Node, indent, gap float64) {
w.f.Ln(gap)
case "tableOfContents":
// PDF readers list the headings as bookmarks.
+ case "detailsSummary":
+ // Toggles are drawn open: the summary in bold, then what it hides.
+ w.at(indent)
+ w.inline(n.Content, "B", pdfBody)
+ w.f.Ln(pdfLine)
+ w.f.Ln(pdfTightGap)
+ case "embed", "linkCard":
+ title := n.attr("title")
+ if title == "" {
+ title = n.attr("url")
+ }
+ w.note(title, n.attr("url"), indent)
+ if d := n.attr("description"); d != "" {
+ w.at(indent)
+ w.f.SetFont("go", "", 10)
+ w.f.SetTextColor(120, 120, 120)
+ w.f.MultiCell(w.width-indent, pdfLine, pdfText(d), "", "L", false)
+ }
+ w.f.Ln(gap)
default:
for _, c := range n.Content {
w.block(c, indent, gap)
diff --git a/Server/internal/directory/content.go b/Server/internal/directory/content.go
index 0bb0f4b..d2584cd 100644
--- a/Server/internal/directory/content.go
+++ b/Server/internal/directory/content.go
@@ -76,13 +76,13 @@ func (s *Service) SavePageContent(ctx context.Context, c access.Caller, id strin
}
// CollabAccess reports whether c may open the page's live document and
-// whether their edits are accepted (editor, page not in the trash).
+// whether their edits are accepted (editor, page not in the trash or archived).
func (s *Service) CollabAccess(ctx context.Context, c access.Caller, id string) (canWrite bool, err error) {
page, err := s.GetPage(ctx, c, id)
if err != nil {
return false, err
}
- return !page.InTrash && access.EditPages(page.Role) == nil, nil
+ return !page.InTrash && !page.Archived && access.EditPages(page.Role) == nil, nil
}
// ListVersions lists a page's history, newest first (viewer).
@@ -135,7 +135,8 @@ func (s *Service) versionContent(ctx context.Context, page, versionID string) (j
return doc, err
}
-// editablePage loads a page the caller may edit and that is not in the trash.
+// editablePage loads a page the caller may edit and that is not in the
+// trash or archived.
func (s *Service) editablePage(ctx context.Context, c access.Caller, id string) (pageRecord, error) {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
@@ -147,6 +148,9 @@ func (s *Service) editablePage(ctx context.Context, c access.Caller, id string)
if p.DeletedAt != "" {
return p, apperr.Invalid("restore the page from the trash first")
}
+ if s.isArchived(ctx, p) {
+ return p, apperr.Invalid("unarchive the page first")
+ }
return p, nil
}
diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go
index e9cc203..44cc8d5 100644
--- a/Server/internal/directory/pages.go
+++ b/Server/internal/directory/pages.go
@@ -20,9 +20,11 @@ import (
// siblings by pages.position (see position.go). Trashing sets deleted_at on
// one page; its subtree is hidden with it and comes back when it is restored.
// Purging deletes the record, and PocketBase cascades to the subtree.
+// Archiving sets archived_at: the page and its subtree leave the page tree
+// but stay readable (and read-only) until someone unarchives them.
// pageFields skips the large content columns.
-const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,created,updated"
+const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,created,updated"
type pageRecord struct {
ID string `json:"id"`
@@ -37,6 +39,7 @@ type pageRecord struct {
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
+ ArchivedAt string `json:"archived_at"`
Created string `json:"created"`
Updated string `json:"updated"`
}
@@ -75,9 +78,13 @@ type Page struct {
Updated string `json:"updated"`
DeletedAt string `json:"deletedAt"`
// InTrash is true when the page or one of its ancestors is in the trash.
- InTrash bool `json:"inTrash"`
- Ancestors []PageRef `json:"ancestors"`
- Role string `json:"role"`
+ InTrash bool `json:"inTrash"`
+ // ArchivedAt is when the page itself was archived; Archived is true when
+ // it or one of its ancestors is.
+ ArchivedAt string `json:"archivedAt"`
+ Archived bool `json:"archived"`
+ Ancestors []PageRef `json:"ancestors"`
+ Role string `json:"role"`
// Restricted is true when the page or an ancestor is restricted.
Restricted bool `json:"restricted"`
// IsTemplate marks a page offered as a template for new pages.
@@ -93,6 +100,13 @@ type TrashedPage struct {
DeletedAt string `json:"deletedAt"`
}
+type ArchivedPage struct {
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Icon string `json:"icon"`
+ ArchivedAt string `json:"archivedAt"`
+}
+
func (s *Service) getPage(ctx context.Context, id string) (pageRecord, error) {
if !validID(id) {
return pageRecord{}, apperr.NotFound("page not found")
@@ -161,6 +175,21 @@ func (t tree) live(id string) bool {
return true
}
+// archived reports whether a page or one of its ancestors is archived.
+func (t tree) archived(id string) bool {
+ for depth := 0; id != "" && depth < 1000; depth++ {
+ p, ok := t.byID[id]
+ if !ok {
+ return false
+ }
+ if p.ArchivedAt != "" {
+ return true
+ }
+ id = p.Parent
+ }
+ return false
+}
+
// within reports whether page id is ancestor or the page itself.
func (t tree) within(id, ancestor string) bool {
for depth := 0; id != "" && depth < 1000; depth++ {
@@ -186,7 +215,8 @@ func (t tree) restrictedBelow(id, ancestor string) bool {
// ListPages returns the space's live pages c can open, siblings in order;
// clients build the tree. A visible page under hidden ones hangs from its
-// nearest visible ancestor (the top level when there is none).
+// nearest visible ancestor (the top level when there is none). Archived
+// pages and their subtrees are left out.
func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string) ([]PageNode, error) {
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
@@ -200,6 +230,9 @@ func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string
var walk func(parent, shownParent string)
walk = func(parent, shownParent string) {
for _, p := range t.children[parent] {
+ if p.ArchivedAt != "" {
+ continue
+ }
under := shownParent
if rules.role(p.ID) != "" {
n := p.node()
@@ -223,6 +256,7 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page
page := Page{
ID: p.ID, Workspace: p.Workspace, Space: p.Space, Parent: p.Parent, Title: p.Title, Icon: p.Icon,
Created: p.Created, Updated: p.Updated, DeletedAt: p.DeletedAt, InTrash: p.DeletedAt != "",
+ ArchivedAt: p.ArchivedAt, Archived: p.ArchivedAt != "",
Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, IsTemplate: p.IsTemplate,
Favorite: s.isFavorite(ctx, c.ID, p.ID),
}
@@ -233,6 +267,7 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page
break
}
page.InTrash = page.InTrash || anc.DeletedAt != ""
+ page.Archived = page.Archived || anc.ArchivedAt != ""
page.Restricted = page.Restricted || anc.Restricted
// Breadcrumbs leave out pages the caller cannot open.
if rules.role(anc.ID) != "" {
@@ -300,6 +335,9 @@ func checkParent(t tree, parent, moving string) error {
if _, ok := t.byID[parent]; !ok || !t.live(parent) {
return apperr.InvalidFields(map[string]string{"parent": "Parent page not found in this space."})
}
+ if t.archived(parent) {
+ return apperr.InvalidFields(map[string]string{"parent": "Unarchive the parent page first."})
+ }
if moving != "" && t.within(parent, moving) {
return apperr.InvalidFields(map[string]string{"parent": "A page cannot be moved inside itself."})
}
@@ -379,6 +417,9 @@ func (s *Service) UpdatePage(ctx context.Context, c access.Caller, id string, in
if p.DeletedAt != "" {
return Page{}, apperr.Invalid("restore the page from the trash first")
}
+ if s.isArchived(ctx, p) {
+ return Page{}, apperr.Invalid("unarchive the page first")
+ }
patch := map[string]any{"last_editor": c.ID}
if in.Title != nil {
title, err := cleanTitle(*in.Title)
@@ -432,6 +473,9 @@ func (s *Service) MovePage(ctx context.Context, c access.Caller, id string, in M
if !t.live(p.ID) {
return Page{}, apperr.Invalid("restore the page from the trash first")
}
+ if t.archived(p.ID) {
+ return Page{}, apperr.Invalid("unarchive the page first")
+ }
if err := checkParent(t, in.Parent, p.ID); err != nil {
return Page{}, err
}
@@ -534,6 +578,104 @@ func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string
return out, nil
}
+// isArchived reports whether p or one of its ancestors is archived.
+func (s *Service) isArchived(ctx context.Context, p pageRecord) bool {
+ for depth := 0; depth < 100; depth++ {
+ if p.ArchivedAt != "" {
+ return true
+ }
+ if p.Parent == "" {
+ return false
+ }
+ var err error
+ if p, err = s.getPage(ctx, p.Parent); err != nil {
+ return false
+ }
+ }
+ return false
+}
+
+// ArchivePage takes a page and its subtree out of the page tree (editor).
+// They stay readable and come back with UnarchivePage. Idempotent.
+func (s *Service) ArchivePage(ctx context.Context, c access.Caller, id string) (Page, error) {
+ p, a, err := s.pageFor(ctx, c, id)
+ if err != nil {
+ return Page{}, err
+ }
+ if err := access.EditPages(a.role); err != nil {
+ return Page{}, err
+ }
+ if p.DeletedAt != "" {
+ return Page{}, apperr.Invalid("restore the page from the trash first")
+ }
+ if p.ArchivedAt == "" {
+ if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
+ "archived_at": pbTime(time.Now()), "last_editor": c.ID,
+ }); err != nil {
+ return Page{}, mapPB(err, "page not found")
+ }
+ // Open editors reconnect read-only.
+ s.docs.Kick(p.ID)
+ s.emitPage(ctx, "page.archived", p, c.ID, nil)
+ }
+ return s.GetPage(ctx, c, p.ID)
+}
+
+// UnarchivePage puts an archived page back in the tree (editor). If its
+// parent is gone, trashed or archived, it goes to the end of the top level.
+func (s *Service) UnarchivePage(ctx context.Context, c access.Caller, id string) (Page, error) {
+ p, a, err := s.pageFor(ctx, c, id)
+ if err != nil {
+ return Page{}, err
+ }
+ if err := access.EditPages(a.role); err != nil {
+ return Page{}, err
+ }
+ if p.ArchivedAt == "" {
+ return s.GetPage(ctx, c, p.ID)
+ }
+ t, err := s.loadTree(ctx, a.space.ID)
+ if err != nil {
+ return Page{}, err
+ }
+ patch := map[string]any{"archived_at": "", "last_editor": c.ID}
+ if p.Parent != "" && (!t.live(p.Parent) || t.archived(p.Parent)) {
+ pos, renumber := placement(t.children[""], len(t.children[""]))
+ if err := s.renumber(ctx, renumber); err != nil {
+ return Page{}, err
+ }
+ patch["parent"], patch["position"] = "", pos
+ }
+ if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch); err != nil {
+ return Page{}, mapPB(err, "page not found")
+ }
+ s.docs.Kick(p.ID)
+ s.emitPage(ctx, "page.unarchived", p, c.ID, nil)
+ return s.GetPage(ctx, c, p.ID)
+}
+
+// ListArchive lists a space's archived pages c can open, newest first.
+// Pages under an archived page are not listed separately, and archived
+// pages in the trash are listed in the trash instead.
+func (s *Service) ListArchive(ctx context.Context, c access.Caller, spaceID string) ([]ArchivedPage, error) {
+ a, rules, err := s.spaceRules(ctx, c, spaceID)
+ if err != nil {
+ return nil, err
+ }
+ t, err := s.loadTree(ctx, a.space.ID)
+ if err != nil {
+ return nil, err
+ }
+ out := []ArchivedPage{}
+ for _, p := range t.byID {
+ if p.ArchivedAt != "" && t.live(p.ID) && !t.archived(p.Parent) && rules.role(p.ID) != "" {
+ out = append(out, ArchivedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, ArchivedAt: p.ArchivedAt})
+ }
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].ArchivedAt > out[j].ArchivedAt })
+ return out, nil
+}
+
// PurgePage permanently deletes a trashed page and its subtree (space admin).
func (s *Service) PurgePage(ctx context.Context, c access.Caller, id string) error {
p, a, err := s.pageFor(ctx, c, id)
diff --git a/Server/internal/directory/spaceexport.go b/Server/internal/directory/spaceexport.go
new file mode 100644
index 0000000..485bd02
--- /dev/null
+++ b/Server/internal/directory/spaceexport.go
@@ -0,0 +1,281 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package directory
+
+import (
+ "archive/zip"
+ "context"
+ "fmt"
+ "html"
+ "io"
+ "log/slog"
+ "net/url"
+ "strings"
+ "time"
+
+ "docwell/server/internal/access"
+ "docwell/server/internal/apperr"
+ "docwell/server/internal/convert"
+ "docwell/server/internal/store/pocketbase"
+)
+
+// ---- Space export ----------------------------------------------------------
+//
+// A space exports as one zip: a file per page, with a page's subpages in a
+// folder next to it, an index, and every attachment of those pages under
+// _files/. Links between exported pages and to attachments become relative
+// paths, so the folder reads on its own (in a file browser, a Markdown
+// viewer or a static site). Archived pages are included; trashed ones are not.
+
+// SpaceExport is a prepared export: everything is checked and listed, and
+// WriteTo produces the zip. Errors before WriteTo still become a normal
+// error response.
+type SpaceExport struct {
+ Filename string
+ s *Service
+ format string
+ title string
+ pages []exportedPage
+ byID map[string]*exportedPage
+ files []exportedFile
+ fileByID map[string]string
+}
+
+type exportedPage struct {
+ rec pageRecord
+ path string // file inside the zip, e.g. "Guides/Setup.md"
+ depth int
+}
+
+type exportedFile struct {
+ rec attachmentRecord
+ path string
+}
+
+// PrepareSpaceExport lists what an export of the space holds: the live pages
+// c can open, as markdown ("markdown") or HTML ("html") files (viewer).
+func (s *Service) PrepareSpaceExport(ctx context.Context, c access.Caller, spaceID, format string) (*SpaceExport, error) {
+ ext := map[string]string{"markdown": ".md", "md": ".md", "": ".md", "html": ".html"}[format]
+ if ext == "" {
+ return nil, apperr.InvalidFields(map[string]string{"format": "Format must be markdown or html."})
+ }
+ a, rules, err := s.spaceRules(ctx, c, spaceID)
+ if err != nil {
+ return nil, err
+ }
+ t, err := s.loadTree(ctx, a.space.ID)
+ if err != nil {
+ return nil, err
+ }
+ e := &SpaceExport{
+ Filename: exportName(a.space.Name, ".zip"), s: s, format: ext, title: a.space.Name,
+ byID: map[string]*exportedPage{}, fileByID: map[string]string{},
+ }
+ // Siblings need different names; "index" and "_files" are taken at the top.
+ taken := map[string]map[string]bool{"": {"index": true, "_files": true}}
+ var walk func(parent, dir, shownParent string, depth int)
+ walk = func(parent, dir, shownParent string, depth int) {
+ for _, p := range t.children[parent] {
+ under, underDir, d := shownParent, dir, depth
+ if rules.role(p.ID) != "" {
+ name := uniqueName(taken, dir, exportBase(p.Title))
+ path := name + ext
+ if dir != "" {
+ path = dir + "/" + path
+ }
+ e.pages = append(e.pages, exportedPage{rec: p, path: path, depth: depth})
+ under, d = p.ID, depth+1
+ underDir = strings.TrimSuffix(path, ext)
+ }
+ walk(p.ID, underDir, under, d)
+ }
+ }
+ walk("", "", "", 0)
+ for i := range e.pages {
+ e.byID[e.pages[i].rec.ID] = &e.pages[i]
+ }
+
+ if len(e.pages) > 0 {
+ atts, err := listAll[attachmentRecord](ctx, s, "attachments", pocketbase.ListOptions{
+ Filter: fmt.Sprintf("workspace = '%s'", a.space.Workspace),
+ })
+ if err != nil {
+ return nil, err
+ }
+ names := map[string]map[string]bool{}
+ for _, f := range atts {
+ if e.byID[f.Page] == nil {
+ continue
+ }
+ path := "_files/" + uniqueName(names, "", cleanFilename(f.Name))
+ e.files = append(e.files, exportedFile{rec: f, path: path})
+ e.fileByID[f.ID] = path
+ }
+ }
+ return e, nil
+}
+
+// exportBase is a page's file name without the extension.
+func exportBase(title string) string { return strings.TrimSuffix(exportName(title, ".x"), ".x") }
+
+// uniqueName returns name, or "name (2)", "name (3)", … when dir already has it.
+func uniqueName(taken map[string]map[string]bool, dir, name string) string {
+ if taken[dir] == nil {
+ taken[dir] = map[string]bool{}
+ }
+ out := name
+ for i := 2; taken[dir][strings.ToLower(out)]; i++ {
+ out = fmt.Sprintf("%s (%d)", name, i)
+ }
+ taken[dir][strings.ToLower(out)] = true
+ return out
+}
+
+// relPath is the link from file from to file to, both slash paths from the
+// zip's root, with each part escaped for use in a link.
+func relPath(from, to string) string {
+ fromDir := strings.Split(from, "/")
+ fromDir = fromDir[:len(fromDir)-1]
+ parts := strings.Split(to, "/")
+ common := 0
+ for common < len(fromDir) && common < len(parts)-1 && fromDir[common] == parts[common] {
+ common++
+ }
+ var out []string
+ for range fromDir[common:] {
+ out = append(out, "..")
+ }
+ for _, p := range parts[common:] {
+ out = append(out, url.PathEscape(p))
+ }
+ return strings.Join(out, "/")
+}
+
+// WriteTo writes the zip. A page or file that fails to load is replaced by a
+// note in the zip, so one broken attachment does not lose the whole export.
+func (e *SpaceExport) WriteTo(ctx context.Context, w io.Writer) error {
+ z := zip.NewWriter(w)
+ if err := e.writeIndex(z); err != nil {
+ return err
+ }
+ for _, p := range e.pages {
+ body, err := e.render(ctx, p)
+ if err != nil {
+ slog.Warn("space export: page skipped", "page", p.rec.ID, "err", err)
+ body = []byte(fmt.Sprintf("This page could not be exported: %v\n", err))
+ }
+ if err := writeZipFile(z, p.path, modTime(p.rec.Updated), body); err != nil {
+ return err
+ }
+ }
+ for _, f := range e.files {
+ if err := e.copyFile(ctx, z, f); err != nil {
+ return err
+ }
+ }
+ return z.Close()
+}
+
+func (e *SpaceExport) render(ctx context.Context, p exportedPage) ([]byte, error) {
+ raw, err := e.s.docs.Content(ctx, p.rec.ID)
+ if err != nil {
+ return nil, err
+ }
+ doc, err := convert.Parse(raw)
+ if err != nil {
+ return nil, err
+ }
+ opts := convert.Options{
+ FileURL: func(path string) string {
+ id := strings.TrimPrefix(strings.SplitN(path, "?", 2)[0], FileURL(""))
+ if to, ok := e.fileByID[id]; ok {
+ return relPath(p.path, to)
+ }
+ return e.s.publicURL + path
+ },
+ PageURL: func(id, fragment string) string {
+ if to, ok := e.byID[id]; ok {
+ return relPath(p.path, to.path) + fragment
+ }
+ // A page outside the export (another space, or hidden): the server.
+ return e.s.publicURL + "/p/" + id + fragment
+ },
+ }
+ if e.format == ".html" {
+ return []byte(convert.HTMLPage(p.rec.Title, doc, opts)), nil
+ }
+ return []byte(convert.MarkdownPage(p.rec.Title, doc, opts)), nil
+}
+
+// writeIndex lists every page as a nested list, in tree order.
+func (e *SpaceExport) writeIndex(z *zip.Writer) error {
+ var b strings.Builder
+ untitled := func(t string) string {
+ if strings.TrimSpace(t) == "" {
+ return "Untitled"
+ }
+ return t
+ }
+ if e.format == ".html" {
+ t := html.EscapeString(e.title)
+ b.WriteString("\n\n\n\n" + t + "\n\n\n" + t + "
\n")
+ depth := -1
+ for _, p := range e.pages {
+ for ; depth < p.depth; depth++ {
+ b.WriteString("\n")
+ }
+ for ; depth > p.depth; depth-- {
+ b.WriteString("
\n")
+ }
+ fmt.Fprintf(&b, "%s\n", html.EscapeString(relPath("index.html", p.path)), html.EscapeString(untitled(p.rec.Title)))
+ }
+ for ; depth >= 0; depth-- {
+ b.WriteString("\n")
+ }
+ b.WriteString("\n\n")
+ return writeZipFile(z, "index.html", time.Now(), []byte(b.String()))
+ }
+ b.WriteString("# " + e.title + "\n\n")
+ for _, p := range e.pages {
+ fmt.Fprintf(&b, "%s- [%s](%s)\n", strings.Repeat(" ", p.depth), mdLinkText(untitled(p.rec.Title)), relPath("index.md", p.path))
+ }
+ return writeZipFile(z, "index.md", time.Now(), []byte(b.String()))
+}
+
+func mdLinkText(s string) string {
+ return strings.NewReplacer(`\`, `\\`, "[", `\[`, "]", `\]`).Replace(s)
+}
+
+func (e *SpaceExport) copyFile(ctx context.Context, z *zip.Writer, f exportedFile) error {
+ file, err := e.s.openFile(ctx, f.rec, nil)
+ if err != nil {
+ slog.Warn("space export: file skipped", "file", f.rec.ID, "err", err)
+ return nil
+ }
+ defer func() { _ = file.Body.Close() }()
+ // Most attachments (images, PDFs, archives) are compressed already.
+ out, err := z.CreateHeader(&zip.FileHeader{Name: f.path, Method: zip.Store, Modified: modTime(f.rec.Created)})
+ if err != nil {
+ return err
+ }
+ _, err = io.Copy(out, file.Body)
+ return err
+}
+
+func writeZipFile(z *zip.Writer, name string, mod time.Time, body []byte) error {
+ w, err := z.CreateHeader(&zip.FileHeader{Name: name, Method: zip.Deflate, Modified: mod})
+ if err != nil {
+ return err
+ }
+ _, err = w.Write(body)
+ return err
+}
+
+// modTime reads a PocketBase date; a bad one is "now".
+func modTime(s string) time.Time {
+ t, err := time.Parse("2006-01-02 15:04:05.000Z", s)
+ if err != nil {
+ return time.Now()
+ }
+ return t
+}
diff --git a/Server/internal/directory/spaceexport_test.go b/Server/internal/directory/spaceexport_test.go
new file mode 100644
index 0000000..81d1698
--- /dev/null
+++ b/Server/internal/directory/spaceexport_test.go
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package directory
+
+import "testing"
+
+func TestRelPath(t *testing.T) {
+ for _, c := range []struct{ from, to, want string }{
+ {"A.md", "B.md", "B.md"},
+ {"A.md", "A/B.md", "A/B.md"},
+ {"A/B.md", "A.md", "../A.md"},
+ {"A/B/C.md", "A/D.md", "../D.md"},
+ {"Guides/Set up.md", "_files/a b.png", "../_files/a%20b.png"},
+ {"index.md", "X/Y.md", "X/Y.md"},
+ } {
+ if got := relPath(c.from, c.to); got != c.want {
+ t.Errorf("relPath(%q, %q) = %q, want %q", c.from, c.to, got, c.want)
+ }
+ }
+}
+
+func TestUniqueName(t *testing.T) {
+ taken := map[string]map[string]bool{"": {"index": true}}
+ for _, want := range []string{"Notes", "Notes (2)", "Notes (3)"} {
+ if got := uniqueName(taken, "", "Notes"); got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+ }
+ if got := uniqueName(taken, "", "Index"); got != "Index (2)" {
+ t.Errorf("index not reserved: %q", got)
+ }
+ if got := uniqueName(taken, "Notes", "Notes"); got != "Notes" {
+ t.Errorf("folders share names: %q", got)
+ }
+}
diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go
index d2c1ea2..d18f45d 100644
--- a/Server/internal/httpapi/auth.go
+++ b/Server/internal/httpapi/auth.go
@@ -66,6 +66,7 @@ type api struct {
files *auth.FileTokens
instance InstanceService
collab CollabHub
+ previews LinkPreviewer
log *slog.Logger
}
diff --git a/Server/internal/httpapi/links.go b/Server/internal/httpapi/links.go
index cc1cecf..69000ea 100644
--- a/Server/internal/httpapi/links.go
+++ b/Server/internal/httpapi/links.go
@@ -7,9 +7,16 @@ import (
"net/http"
"docwell/server/internal/access"
+ "docwell/server/internal/apperr"
"docwell/server/internal/directory"
+ "docwell/server/internal/unfurl"
)
+// LinkPreviewer reads a web page's title and picture for link cards.
+type LinkPreviewer interface {
+ Preview(ctx context.Context, url string) (unfurl.Preview, error)
+}
+
// LinkService is the part of directory.Service for backlinks and templates.
type LinkService interface {
Backlinks(ctx context.Context, c access.Caller, pageID string) ([]directory.PageItem, error)
@@ -18,6 +25,14 @@ type LinkService interface {
}
func (a *api) linkRoutes(mux *routeMux) {
+ mux.HandleFunc("GET /api/v1/link-preview", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ if a.previews == nil {
+ a.respond(w, nil, apperr.NotFound("link previews are off"))
+ return
+ }
+ p, err := a.previews.Preview(r.Context(), r.URL.Query().Get("url"))
+ a.respond(w, p, err)
+ }))
mux.HandleFunc("GET /api/v1/pages/{id}/backlinks", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
list, err := a.dir.Backlinks(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, list, err)
diff --git a/Server/internal/httpapi/router.go b/Server/internal/httpapi/router.go
index 641c0b7..a9fc858 100644
--- a/Server/internal/httpapi/router.go
+++ b/Server/internal/httpapi/router.go
@@ -34,6 +34,8 @@ type Deps struct {
MaxUpload int64
// Collab serves /collab; nil disables live editing.
Collab CollabHub
+ // Previews reads pages for link cards; nil turns link previews off.
+ Previews LinkPreviewer
// Audit records changes and serves the audit log; nil turns both off.
Audit AuditService
Admin http.Handler
@@ -66,6 +68,9 @@ func newMux(d Deps) *routeMux {
if d.Audit != nil {
a.audit = d.Audit
}
+ if d.Previews != nil {
+ a.previews = d.Previews
+ }
a.routes(mux)
a.fileRoutes(mux, max(d.MaxUpload, 1<<20))
a.collabRoute(mux, d.CORSOrigins)
diff --git a/Server/internal/httpapi/spaces.go b/Server/internal/httpapi/spaces.go
index 8d15c95..2fcd6cd 100644
--- a/Server/internal/httpapi/spaces.go
+++ b/Server/internal/httpapi/spaces.go
@@ -37,6 +37,9 @@ type SpaceService interface {
RestorePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
ListTrash(ctx context.Context, c access.Caller, spaceID string) ([]directory.TrashedPage, error)
PurgePage(ctx context.Context, c access.Caller, id string) error
+ ArchivePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
+ UnarchivePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
+ ListArchive(ctx context.Context, c access.Caller, spaceID string) ([]directory.ArchivedPage, error)
}
func (a *api) spaceRoutes(mux *routeMux) {
@@ -101,10 +104,22 @@ func (a *api) spaceRoutes(mux *routeMux) {
pages, err := a.dir.ListTrash(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, pages, err)
}))
+ mux.HandleFunc("GET /api/v1/spaces/{id}/archive", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ pages, err := a.dir.ListArchive(r.Context(), caller(r), r.PathValue("id"))
+ a.respond(w, pages, err)
+ }))
mux.HandleFunc("GET /api/v1/pages/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
p, err := a.dir.GetPage(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, p, err)
}))
+ mux.HandleFunc("POST /api/v1/pages/{id}/archive", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ p, err := a.dir.ArchivePage(r.Context(), caller(r), r.PathValue("id"))
+ a.respond(w, p, err)
+ }))
+ mux.HandleFunc("POST /api/v1/pages/{id}/unarchive", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ p, err := a.dir.UnarchivePage(r.Context(), caller(r), r.PathValue("id"))
+ a.respond(w, p, err)
+ }))
mux.HandleFunc("PATCH /api/v1/pages/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.UpdatePageInput
if !a.decode(w, r, &in) {
diff --git a/Server/internal/httpapi/transfer.go b/Server/internal/httpapi/transfer.go
index 9420e5b..9381691 100644
--- a/Server/internal/httpapi/transfer.go
+++ b/Server/internal/httpapi/transfer.go
@@ -17,6 +17,7 @@ import (
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)
+ PrepareSpaceExport(ctx context.Context, c access.Caller, spaceID, format string) (*directory.SpaceExport, error)
}
// maxImportRequest caps one import request: up to 20 files, each within its
@@ -38,6 +39,21 @@ func (a *api) transferRoutes(mux *routeMux) {
h.Set("X-Content-Type-Options", "nosniff")
_, _ = w.Write(e.Body)
}))
+ mux.HandleFunc("GET /api/v1/spaces/{id}/export", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
+ e, err := a.dir.PrepareSpaceExport(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", "application/zip")
+ h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": e.Filename}))
+ h.Set("X-Content-Type-Options", "nosniff")
+ // The zip streams as it is built; a failure half-way can only cut it short.
+ if err := e.WriteTo(r.Context(), w); err != nil {
+ a.log.Warn("space export failed", "space", r.PathValue("id"), "err", err)
+ }
+ }))
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(32 << 20); err != nil { // Larger uploads spill to temporary files.
diff --git a/Server/internal/unfurl/unfurl.go b/Server/internal/unfurl/unfurl.go
new file mode 100644
index 0000000..02d65ab
--- /dev/null
+++ b/Server/internal/unfurl/unfurl.go
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+// Package unfurl reads a web page's title, description and picture for link
+// cards in the editor. Any signed-in user can make the server fetch an
+// address and read the answer, so it only goes to public addresses.
+package unfurl
+
+import (
+ "context"
+ "errors"
+ "io"
+ "mime"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "syscall"
+ "time"
+ "unicode/utf8"
+
+ "golang.org/x/net/html"
+ "golang.org/x/net/html/atom"
+
+ "docwell/server/internal/apperr"
+)
+
+// Preview is what a link card shows.
+type Preview struct {
+ URL string `json:"url"`
+ Title string `json:"title"`
+ Description string `json:"description"`
+ Image string `json:"image"`
+ Site string `json:"site"`
+}
+
+// maxBody caps how much of a page is read; the tags are in its head.
+const maxBody = 1 << 20
+
+type Fetcher struct {
+ client *http.Client
+}
+
+// New returns a fetcher that refuses private, loopback and link-local
+// addresses after DNS resolution, redirects included.
+func New() *Fetcher {
+ dialer := &net.Dialer{Timeout: 5 * time.Second, Control: guard}
+ return &Fetcher{client: &http.Client{
+ Timeout: 8 * time.Second,
+ Transport: &http.Transport{DialContext: dialer.DialContext, Proxy: nil, MaxResponseHeaderBytes: 64 << 10},
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 3 {
+ return errors.New("too many redirects")
+ }
+ if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
+ return errors.New("redirect to a non-web address")
+ }
+ return nil
+ },
+ }}
+}
+
+// NewWithClient uses client as is (tests point it at a local server).
+func NewWithClient(client *http.Client) *Fetcher { return &Fetcher{client: client} }
+
+var errBlocked = errors.New("address not allowed")
+
+// cgnat is the shared address space (100.64.0.0/10) carriers and some cloud
+// networks use internally.
+var cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
+
+func guard(_, address string, _ syscall.RawConn) error {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return err
+ }
+ ip := net.ParseIP(host)
+ if ip == nil || !Public(ip) {
+ return errBlocked
+ }
+ return nil
+}
+
+// Public reports whether ip is on the public internet.
+func Public(ip net.IP) bool {
+ return !(ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
+ ip.IsUnspecified() || ip.IsMulticast() || ip.IsInterfaceLocalMulticast() || cgnat.Contains(ip))
+}
+
+// Preview fetches raw and reads its preview. Pages that are not HTML, or
+// can't be reached, still get a preview with the address and site name.
+func (f *Fetcher) Preview(ctx context.Context, raw string) (Preview, error) {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || len(raw) > 2000 {
+ return Preview{}, apperr.InvalidFields(map[string]string{"url": "Enter a web address (http or https)."})
+ }
+ u.Fragment = ""
+ out := Preview{URL: u.String(), Site: siteName(u)}
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
+ if err != nil {
+ return out, nil
+ }
+ req.Header.Set("Accept", "text/html,application/xhtml+xml")
+ req.Header.Set("User-Agent", "DocwellLinkPreview/1.0 (+https://docwell.app)")
+ res, err := f.client.Do(req)
+ if err != nil {
+ return out, nil
+ }
+ defer func() { _ = res.Body.Close() }()
+ ct, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type"))
+ if res.StatusCode >= 300 || (ct != "text/html" && ct != "application/xhtml+xml") {
+ return out, nil
+ }
+ p := Parse(res.Request.URL, io.LimitReader(res.Body, maxBody))
+ p.URL = out.URL
+ if p.Site == "" {
+ p.Site = out.Site
+ }
+ return p, nil
+}
+
+func siteName(u *url.URL) string { return strings.TrimPrefix(u.Hostname(), "www.") }
+
+// Parse reads the preview from a page's head; base resolves relative image
+// addresses.
+func Parse(base *url.URL, r io.Reader) Preview {
+ var p Preview
+ var title strings.Builder
+ meta := map[string]string{}
+ z := html.NewTokenizer(r)
+ inTitle := false
+ for {
+ switch z.Next() {
+ case html.ErrorToken:
+ return finish(base, p, title.String(), meta)
+ case html.StartTagToken, html.SelfClosingTagToken:
+ name, hasAttr := z.TagName()
+ switch atom.Lookup(name) {
+ case atom.Title:
+ inTitle = true
+ case atom.Meta:
+ var key, content string
+ for hasAttr {
+ var k, v []byte
+ k, v, hasAttr = z.TagAttr()
+ switch string(k) {
+ case "property", "name":
+ key = strings.ToLower(string(v))
+ case "content":
+ content = string(v)
+ }
+ }
+ if key != "" && meta[key] == "" {
+ meta[key] = content
+ }
+ case atom.Body:
+ // Everything a preview needs is in the head.
+ return finish(base, p, title.String(), meta)
+ }
+ case html.TextToken:
+ if inTitle {
+ title.Write(z.Text())
+ }
+ case html.EndTagToken:
+ name, _ := z.TagName()
+ switch atom.Lookup(name) {
+ case atom.Title:
+ inTitle = false
+ case atom.Head:
+ return finish(base, p, title.String(), meta)
+ }
+ }
+ }
+}
+
+func finish(base *url.URL, p Preview, title string, meta map[string]string) Preview {
+ first := func(keys ...string) string {
+ for _, k := range keys {
+ if v := strings.TrimSpace(meta[k]); v != "" {
+ return v
+ }
+ }
+ return ""
+ }
+ p.Title = clip(first("og:title", "twitter:title"), 300)
+ if p.Title == "" {
+ p.Title = clip(strings.TrimSpace(title), 300)
+ }
+ p.Description = clip(first("og:description", "twitter:description", "description"), 500)
+ p.Site = clip(first("og:site_name", "application-name"), 100)
+ if img := first("og:image:secure_url", "og:image", "twitter:image", "twitter:image:src"); img != "" && base != nil {
+ if u, err := base.Parse(img); err == nil && (u.Scheme == "https" || u.Scheme == "http") && len(u.String()) <= 2000 {
+ p.Image = u.String()
+ }
+ }
+ return p
+}
+
+// clip collapses whitespace and cuts s to n runes.
+func clip(s string, n int) string {
+ s = strings.Join(strings.Fields(s), " ")
+ if utf8.RuneCountInString(s) <= n {
+ return s
+ }
+ return strings.TrimSpace(string([]rune(s)[:n-1])) + "…"
+}
diff --git a/Server/internal/unfurl/unfurl_test.go b/Server/internal/unfurl/unfurl_test.go
new file mode 100644
index 0000000..a1da918
--- /dev/null
+++ b/Server/internal/unfurl/unfurl_test.go
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package unfurl
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestParse(t *testing.T) {
+ base, _ := url.Parse("https://example.com/blog/post")
+ page := `
+ Fallback title
+
+
+
+
+`
+ p := Parse(base, strings.NewReader(page))
+ if p.Title != "Docwell & friends" || p.Description != "Plain description" || p.Site != "Example Blog" {
+ t.Fatalf("got %+v", p)
+ }
+ if p.Image != "https://example.com/img/cover.png" {
+ t.Fatalf("image = %q", p.Image)
+ }
+
+ p = Parse(base, strings.NewReader(`Only a title`))
+ if p.Title != "Only a title" || p.Image != "" {
+ t.Fatalf("got %+v", p)
+ }
+}
+
+func TestPublic(t *testing.T) {
+ for _, s := range []string{"127.0.0.1", "10.1.2.3", "192.168.1.1", "172.16.0.1", "169.254.169.254", "100.64.0.1", "::1", "fd00::1", "0.0.0.0"} {
+ if Public(net.ParseIP(s)) {
+ t.Errorf("%s counted as public", s)
+ }
+ }
+ for _, s := range []string{"1.1.1.1", "93.184.216.34", "2606:4700::1111"} {
+ if !Public(net.ParseIP(s)) {
+ t.Errorf("%s counted as private", s)
+ }
+ }
+}
+
+func TestPreviewRefusesLocalAddresses(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`secret`))
+ }))
+ defer srv.Close()
+ p, err := New().Preview(context.Background(), srv.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The fetch is refused, so the card has only the address.
+ if p.Title != "" || p.URL != srv.URL {
+ t.Fatalf("got %+v", p)
+ }
+}
+
+func TestPreviewFetches(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = w.Write([]byte(``))
+ }))
+ defer srv.Close()
+ p, err := NewWithClient(srv.Client()).Preview(context.Background(), srv.URL+"/#part")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if p.Title != "Hello" || p.URL != srv.URL+"/" || p.Site != "127.0.0.1" {
+ t.Fatalf("got %+v", p)
+ }
+ if _, err := New().Preview(context.Background(), "file:///etc/passwd"); err == nil {
+ t.Fatal("file: address accepted")
+ }
+}
diff --git a/Server/internal/webhooks/webhooks.go b/Server/internal/webhooks/webhooks.go
index 5ebf777..dd9906a 100644
--- a/Server/internal/webhooks/webhooks.go
+++ b/Server/internal/webhooks/webhooks.go
@@ -30,6 +30,7 @@ import (
// Events a webhook can subscribe to ("*" means all of them).
var Events = []string{
"page.created", "page.updated", "page.moved", "page.trashed", "page.restored", "page.deleted",
+ "page.archived", "page.unarchived",
"comment.created", "comment.resolved",
"space.created", "space.deleted",
}
diff --git a/Web-App/frontend/src/app.ts b/Web-App/frontend/src/app.ts
index 290a705..461ab8b 100644
--- a/Web-App/frontend/src/app.ts
+++ b/Web-App/frontend/src/app.ts
@@ -5,6 +5,7 @@ import { createPinia } from "pinia";
import { createApp } from "vue";
import App from "./App.vue";
import { apiKey, tokenKey } from "./api";
+import { sendCommand } from "./lib/commands";
import { createDocwellI18n } from "./i18n";
import { configKey, platformKey, type Platform } from "./platform";
import { createDocwellRouter } from "./router";
@@ -18,7 +19,7 @@ export async function createDocwellApp(platform: Platform, el: string | Element
const pinia = createPinia();
app.use(pinia);
- const tokens = createTokenStore();
+ const tokens = platform.tokenStore ? await platform.tokenStore() : createTokenStore();
const router = createDocwellRouter(platform);
const auth = useAuthStore(pinia);
const api = createClient({
@@ -44,7 +45,8 @@ export async function createDocwellApp(platform: Platform, el: string | Element
app.use(router);
app.mount(el);
platform.onOpenRoute?.((route) => void router.push(route));
+ platform.onCommand?.(sendCommand);
return app;
}
-export type { Platform, RuntimeConfig } from "./platform";
+export type { AppCommand, Platform, RuntimeConfig, ServerEntry, ServerHost, TokenStore } from "./platform";
diff --git a/Web-App/frontend/src/components/AppLayout.vue b/Web-App/frontend/src/components/AppLayout.vue
index 5a5a4aa..18fbf58 100644
--- a/Web-App/frontend/src/components/AppLayout.vue
+++ b/Web-App/frontend/src/components/AppLayout.vue
@@ -5,6 +5,7 @@ import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { clearFileToken } from "../composables/useFiles";
import { useFormErrors } from "../composables/useFormErrors";
+import { onCommand } from "../lib/commands";
import { SIDEBAR_DEFAULT, clampWidth, useSidebar } from "../composables/useSidebar";
import { useAuthStore } from "../stores/auth";
import { useFavoritesStore } from "../stores/favorites";
@@ -68,6 +69,14 @@ function onKey(e: KeyboardEvent) {
onMounted(() => document.addEventListener("keydown", onKey));
onBeforeUnmount(() => document.removeEventListener("keydown", onKey));
+// The desktop app's menu bar sends the same actions.
+const stopCommands = onCommand((c) => {
+ if (c === "search") searchOpen.value = true;
+ else if (c === "toggle-sidebar") sidebar.toggle();
+ else if (c === "new-page") void newPage();
+});
+onBeforeUnmount(stopCommands);
+
const ws = computed(() => workspaces.current);
const canCreateSpace = computed(() => atLeast(ws.value?.role, "admin"));
diff --git a/Web-App/frontend/src/components/PageHistory.vue b/Web-App/frontend/src/components/PageHistory.vue
index 5933dd0..9eaf33b 100644
--- a/Web-App/frontend/src/components/PageHistory.vue
+++ b/Web-App/frontend/src/components/PageHistory.vue
@@ -3,11 +3,13 @@
import type { Page, PageVersion } from "@docwell/api-client";
import { DocwellEditor, type JSONContent } from "@docwell/editor";
import { DwButton, DwIcon } from "@docwell/ui";
-import { ref, watch } from "vue";
+import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
+import { diffDocs, diffStats, type DiffRow } from "../lib/diff";
-// The page's saved versions, with a read-only preview and restore. Restoring
+// The page's saved versions, with a read-only preview, the changes against
+// the version before it (or the page as it is now), and restore. Restoring
// is an ordinary edit to the live document, so open editors update at once.
const props = defineProps<{ page: Page; canRestore: boolean }>();
const emit = defineEmits<{ close: []; error: [err: unknown] }>();
@@ -18,6 +20,11 @@ const versions = ref(null);
const selected = ref(null);
const preview = ref(null);
const busy = ref(false);
+const view = ref<"preview" | "changes">("preview");
+const against = ref<"previous" | "current">("previous");
+const base = ref(undefined);
+
+const empty: JSONContent = { type: "doc", content: [] };
async function load() {
selected.value = null;
@@ -30,17 +37,59 @@ async function load() {
}
watch(() => props.page.id, load, { immediate: true });
+async function versionDoc(v: PageVersion): Promise {
+ const c = await api.pages.version(props.page.id, v.id);
+ return (c.content as JSONContent | null) ?? empty;
+}
+
async function select(v: PageVersion) {
selected.value = v;
preview.value = null;
try {
- const c = await api.pages.version(props.page.id, v.id);
- if (selected.value?.id === v.id) preview.value = (c.content as JSONContent | null) ?? { type: "doc", content: [] };
+ const doc = await versionDoc(v);
+ if (selected.value?.id === v.id) preview.value = doc;
+ await loadBase();
} catch (e) {
emit("error", e);
}
}
+// The version just before the selected one (versions are newest first).
+const previous = computed(() => {
+ const list = versions.value ?? [];
+ const i = list.findIndex((v) => v.id === selected.value?.id);
+ return i >= 0 ? (list[i + 1] ?? null) : null;
+});
+
+/** Loads what the selected version is compared with; null means "nothing before it". */
+async function loadBase() {
+ const v = selected.value;
+ if (!v || view.value !== "changes") return;
+ base.value = undefined;
+ try {
+ let doc: JSONContent | null;
+ if (against.value === "current") {
+ const c = await api.pages.content(props.page.id);
+ doc = (c.content as JSONContent | null) ?? empty;
+ } else {
+ doc = previous.value ? await versionDoc(previous.value) : null;
+ }
+ if (selected.value?.id === v.id) base.value = doc;
+ } catch (e) {
+ emit("error", e);
+ }
+}
+watch([view, against], loadBase);
+
+// Against the previous version: what this version changed. Against the
+// page now: what changed since this version.
+const rows = computed(() => {
+ if (!preview.value || base.value === undefined) return null;
+ return against.value === "current" ? diffDocs(preview.value, base.value) : diffDocs(base.value, preview.value);
+});
+const stats = computed(() => (rows.value ? diffStats(rows.value) : null));
+const changedRows = computed(() => rows.value?.filter((r) => r.change !== "same") ?? []);
+
async function restore() {
const v = selected.value;
if (!v || !confirm(t("page.history.confirmRestore", { date: when(v.created) }))) return;
@@ -62,6 +111,15 @@ const labelText = (label: string) =>
// PocketBase dates look like "2026-10-30 21:05:00.000Z".
const when = (s: string) =>
new Date(s.replace(" ", "T")).toLocaleString(locale.value, { dateStyle: "medium", timeStyle: "short" });
+
+const rowClass: Record = {
+ same: "text-ink-muted",
+ added: "bg-success-soft border-l-2 border-success",
+ removed: "bg-danger-soft border-l-2 border-danger line-through decoration-danger/60",
+ changed: "border-l-2 border-warning",
+};
+const tab =
+ "rounded-sm px-2 py-1 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink aria-selected:bg-surface-hover aria-selected:text-ink";
@@ -76,7 +134,7 @@ const when = (s: string) =>
{{ $t("page.history.empty") }}
-
+
-