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/<id>#b-<block>. Opening one jumps to the block and flashes it.
- Markdown, HTML and PDF exports handle the new blocks; HTML import reads
<details> 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
135b4640b2
commit
40d515d15b
74 files changed
+4249
-119
No files matched your search
@@ -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/<repository owner>/<name>, 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 }}
|
||||
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// 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);
|
||||
},
|
||||
);
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 <version, e.g. 1.2.3>");
|
||||
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",
|
||||
/(<key>CFBundleShortVersionString<\/key>\s*<string>)[^<]*(<\/string>)/,
|
||||
`$1${version}$2`,
|
||||
],
|
||||
["darwin/Info.plist", /(<key>CFBundleVersion<\/key>\s*<string>)[^<]*(<\/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`);
|
||||
@@ -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"}}'
|
||||
|
||||
+13
-2
@@ -23,7 +23,11 @@ var deepLinkRoutes = []string{"p", "s"}
|
||||
|
||||
var recordID = regexp.MustCompile(`^[A-Za-z0-9]{1,32}$`)
|
||||
|
||||
// routeFromDeepLink turns docwell://p/<id> into the app route /p/<id>.
|
||||
// blockFragment is a link to one block of a page: docwell://p/<id>#b-<block>.
|
||||
var blockFragment = regexp.MustCompile(`^b-[a-z0-9]{6,16}$`)
|
||||
|
||||
// routeFromDeepLink turns docwell://p/<id> into the app route /p/<id>
|
||||
// (keeping a #b-<block> 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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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";
|
||||
@@ -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<Server> = {}) {
|
||||
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<Server>);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<Settings> = {}) {
|
||||
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<Settings>);
|
||||
}
|
||||
}
|
||||
|
||||
// Private type creation functions
|
||||
const $$createType0 = Server.createFrom;
|
||||
const $$createType1 = $Create.Array($$createType0);
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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<void> {
|
||||
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<string> {
|
||||
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<void> {
|
||||
return $Call.ByID(2986285700, serverID, token);
|
||||
}
|
||||
@@ -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<TokenStore> {
|
||||
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/<id>#b-<block>.
|
||||
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);
|
||||
+5
-1
@@ -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
|
||||
|
||||
@@ -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=
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
+182
-23
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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<Page>(`/api/v1/spaces/${encodeURIComponent(id)}/pages`, input),
|
||||
trash: (id: string) => request<TrashedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/trash`),
|
||||
archive: (id: string) => request<ArchivedPage[]>("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<Page>(`/api/v1/pages/${encodeURIComponent(id)}/move`, { parent, index }),
|
||||
trash: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}`),
|
||||
restore: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
|
||||
archive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/archive`),
|
||||
unarchive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/unarchive`),
|
||||
/** A web page's title, description and picture, read by docwell-server. */
|
||||
preview: (url: string) => request<LinkPreview>("GET", `/api/v1/link-preview${query({ url })}`),
|
||||
setFavorite: (id: string, on: boolean) =>
|
||||
request<void>(on ? "PUT" : "DELETE", `/api/v1/pages/${encodeURIComponent(id)}/favorite`),
|
||||
attachments: (id: string) => request<Attachment[]>("GET", `/api/v1/pages/${encodeURIComponent(id)}/attachments`),
|
||||
|
||||
Vendored
+240
-1
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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-<id>" 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/<id>". */
|
||||
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;
|
||||
|
||||
@@ -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<BlockLinkOptions>({
|
||||
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 =
|
||||
'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.07 0l3-3a5 5 0 0 0-7.07-7.07l-1.5 1.5"/><path d="M14 11a5 5 0 0 0-7.07 0l-3 3a5 5 0 0 0 7.07 7.07l1.5-1.5"/></svg>';
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ReturnType> {
|
||||
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<LinkPreview>;
|
||||
}
|
||||
|
||||
// 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<string> {
|
||||
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<string, unknown>) => ({ [`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<string, unknown>) => {
|
||||
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,
|
||||
};
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -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-<id>"
|
||||
* 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/<id>" 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(
|
||||
|
||||
@@ -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";
|
||||
@@ -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",
|
||||
},
|
||||
};
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
];
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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<String, dynamic>))
|
||||
.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<PageRef> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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'),
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
|
||||
@@ -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"`
|
||||
|
||||
@@ -15,18 +15,30 @@ type Options struct {
|
||||
// FileURL rewrites attachment paths (/api/v1/files/<id>) so exported
|
||||
// files link to the server; nil keeps them as they are.
|
||||
FileURL func(path string) string
|
||||
// PageURL rewrites links to pages (/p/<id>, 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, "<span class=\"mention\">@%s</span>", html.EscapeString(mentionLabel(n)))
|
||||
case "tableOfContents":
|
||||
// Nothing to keep: readers of the file see the headings themselves.
|
||||
case "details":
|
||||
b.WriteString("<details>\n")
|
||||
for _, c := range n.Content {
|
||||
if c.Type == "detailsSummary" {
|
||||
b.WriteString("<summary>")
|
||||
for _, t := range c.Content {
|
||||
writeHTML(b, t, o)
|
||||
}
|
||||
b.WriteString("</summary>\n")
|
||||
} else {
|
||||
writeHTML(b, c, o)
|
||||
}
|
||||
}
|
||||
b.WriteString("</details>\n")
|
||||
case "embed", "linkCard":
|
||||
href := n.attr("url")
|
||||
if !safeURL.MatchString(href) {
|
||||
return
|
||||
}
|
||||
title := n.attr("title")
|
||||
if title == "" {
|
||||
title = href
|
||||
}
|
||||
fmt.Fprintf(b, "<p><a href=\"%s\">%s</a>", html.EscapeString(href), html.EscapeString(title))
|
||||
if d := n.attr("description"); d != "" {
|
||||
fmt.Fprintf(b, "<br>%s", html.EscapeString(d))
|
||||
}
|
||||
b.WriteString("</p>\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 <details> 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("<details>\n<summary>"+html.EscapeString(summary)+"</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("</details>", 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)
|
||||
|
||||
@@ -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{"<details>\n<summary>More</summary>\n\nHidden\n\n</details>", "[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{"<details>\n<summary>More</summary>\n<p>Hidden</p>\n</details>", `<a href="https://example.com/a">Example</a><br>About it`, `<a href="../abc123.md#b-x1y2z3w4">see</a>`} {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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("<!doctype html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>" + t + "</title>\n</head>\n<body>\n<h1>" + t + "</h1>\n")
|
||||
depth := -1
|
||||
for _, p := range e.pages {
|
||||
for ; depth < p.depth; depth++ {
|
||||
b.WriteString("<ul>\n")
|
||||
}
|
||||
for ; depth > p.depth; depth-- {
|
||||
b.WriteString("</ul>\n")
|
||||
}
|
||||
fmt.Fprintf(&b, "<li><a href=\"%s\">%s</a></li>\n", html.EscapeString(relPath("index.html", p.path)), html.EscapeString(untitled(p.rec.Title)))
|
||||
}
|
||||
for ; depth >= 0; depth-- {
|
||||
b.WriteString("</ul>\n")
|
||||
}
|
||||
b.WriteString("</body>\n</html>\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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ type api struct {
|
||||
files *auth.FileTokens
|
||||
instance InstanceService
|
||||
collab CollabHub
|
||||
previews LinkPreviewer
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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])) + "…"
|
||||
}
|
||||
@@ -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 := `<!doctype html><html><head>
|
||||
<title> Fallback title </title>
|
||||
<meta property="og:title" content="Docwell & friends">
|
||||
<meta name="description" content="Plain description">
|
||||
<meta property="og:site_name" content="Example Blog">
|
||||
<meta property="og:image" content="/img/cover.png">
|
||||
</head><body><meta property="og:title" content="ignored"></body></html>`
|
||||
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(`<title>Only a title</title><meta property="og:image" content="javascript:alert(1)">`))
|
||||
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(`<title>secret</title>`))
|
||||
}))
|
||||
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(`<head><meta property="og:title" content="Hello"></head>`))
|
||||
}))
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
@@ -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"));
|
||||
|
||||
|
||||
@@ -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<PageVersion[] | null>(null);
|
||||
const selected = ref<PageVersion | null>(null);
|
||||
const preview = ref<JSONContent | null>(null);
|
||||
const busy = ref(false);
|
||||
const view = ref<"preview" | "changes">("preview");
|
||||
const against = ref<"previous" | "current">("previous");
|
||||
const base = ref<JSONContent | null | undefined>(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<JSONContent> {
|
||||
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<DiffRow[] | null>(() => {
|
||||
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<DiffRow["change"], string> = {
|
||||
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";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -76,7 +134,7 @@ const when = (s: string) =>
|
||||
{{ $t("page.history.empty") }}
|
||||
</p>
|
||||
<div v-else-if="versions" class="mt-3 grid gap-4 sm:grid-cols-[14rem_1fr]">
|
||||
<ul class="flex max-h-80 flex-col gap-1 overflow-y-auto" role="listbox" :aria-label="$t('page.history.title')">
|
||||
<ul class="flex max-h-96 flex-col gap-1 overflow-y-auto" role="listbox" :aria-label="$t('page.history.title')">
|
||||
<li v-for="v in versions" :key="v.id">
|
||||
<button
|
||||
type="button"
|
||||
@@ -96,14 +154,83 @@ const when = (s: string) =>
|
||||
<div class="min-w-0">
|
||||
<p v-if="!selected" class="text-ui-md text-ink-muted">{{ $t("page.history.pick") }}</p>
|
||||
<template v-else>
|
||||
<div class="max-h-80 overflow-y-auto rounded-sm border border-line px-4 py-3">
|
||||
<DocwellEditor
|
||||
v-if="preview"
|
||||
:key="selected.id"
|
||||
:content="preview"
|
||||
:editable="false"
|
||||
data-testid="version-preview"
|
||||
/>
|
||||
<div class="mb-2 flex flex-wrap items-center gap-1" role="tablist">
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:class="tab"
|
||||
:aria-selected="view === 'preview'"
|
||||
data-testid="history-preview"
|
||||
@click="view = 'preview'"
|
||||
>
|
||||
{{ $t("page.history.preview") }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
:class="tab"
|
||||
:aria-selected="view === 'changes'"
|
||||
data-testid="history-changes"
|
||||
@click="view = 'changes'"
|
||||
>
|
||||
{{ $t("page.history.changes") }}
|
||||
</button>
|
||||
<label v-if="view === 'changes'" class="ml-auto flex items-center gap-1 text-ui-sm text-ink-muted">
|
||||
{{ $t("page.history.compareWith") }}
|
||||
<select v-model="against" class="rounded-sm border border-line bg-surface px-1 py-0.5 text-ink">
|
||||
<option value="previous">{{ $t("page.history.previousVersion") }}</option>
|
||||
<option value="current">{{ $t("page.history.currentPage") }}</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="max-h-96 overflow-y-auto rounded-sm border border-line px-4 py-3">
|
||||
<template v-if="view === 'preview'">
|
||||
<DocwellEditor
|
||||
v-if="preview"
|
||||
:key="selected.id"
|
||||
:content="preview"
|
||||
:editable="false"
|
||||
data-testid="version-preview"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="rows && stats">
|
||||
<p class="mb-2 text-ui-sm text-ink-muted" data-testid="diff-summary">
|
||||
<template v-if="against === 'previous' && base === null">{{
|
||||
$t("page.history.firstVersion")
|
||||
}}</template>
|
||||
<template v-else-if="!changedRows.length">{{ $t("page.history.noChanges") }}</template>
|
||||
<template v-else>{{ $t("page.history.stats", stats) }}</template>
|
||||
</p>
|
||||
<ol class="flex flex-col gap-1 text-ui-md" data-testid="version-diff">
|
||||
<li
|
||||
v-for="(r, i) in rows"
|
||||
:key="i"
|
||||
class="rounded-xs px-2 py-0.5 whitespace-pre-wrap"
|
||||
:class="[
|
||||
rowClass[r.change],
|
||||
{
|
||||
'font-semibold': r.line.kind.startsWith('h'),
|
||||
'font-mono text-code': r.line.kind === 'codeBlock',
|
||||
},
|
||||
]"
|
||||
>
|
||||
<span class="sr-only">{{ $t(`page.history.change.${r.change}`) }}:</span>
|
||||
<template v-if="r.change === 'changed'">
|
||||
<span
|
||||
v-for="(part, j) in r.parts"
|
||||
:key="j"
|
||||
:class="{
|
||||
'rounded-xs bg-success-soft text-success': part.change === 'added',
|
||||
'rounded-xs bg-danger-soft text-danger line-through': part.change === 'removed',
|
||||
}"
|
||||
>{{ part.text }}</span
|
||||
>
|
||||
</template>
|
||||
<template v-else>{{ r.line.text || "…" }}</template>
|
||||
</li>
|
||||
</ol>
|
||||
</template>
|
||||
</div>
|
||||
<DwButton
|
||||
v-if="canRestore"
|
||||
|
||||
@@ -20,6 +20,8 @@ const EVENTS: Exclude<WebhookEvent, "*">[] = [
|
||||
"page.trashed",
|
||||
"page.restored",
|
||||
"page.deleted",
|
||||
"page.archived",
|
||||
"page.unarchived",
|
||||
"comment.created",
|
||||
"comment.resolved",
|
||||
"space.created",
|
||||
|
||||
@@ -24,6 +24,9 @@ const blocks = [
|
||||
"drawio",
|
||||
"excalidraw",
|
||||
"pageLink",
|
||||
"toggle",
|
||||
"embed",
|
||||
"linkCard",
|
||||
];
|
||||
const blockWords = [
|
||||
"edit",
|
||||
@@ -40,6 +43,13 @@ const blockWords = [
|
||||
"loadFailed",
|
||||
"toc",
|
||||
"tocEmpty",
|
||||
"expand",
|
||||
"collapse",
|
||||
"embed",
|
||||
"embedUrl",
|
||||
"embedInvalid",
|
||||
"linkUrl",
|
||||
"copyBlockLink",
|
||||
] as const;
|
||||
|
||||
/** The editor's menu and button words in the app's language. */
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { AppCommand } from "../platform";
|
||||
|
||||
// Commands from the host's menus, handed to whichever view handles them.
|
||||
const handlers = new Set<(c: AppCommand) => void>();
|
||||
|
||||
export function sendCommand(c: AppCommand) {
|
||||
for (const h of handlers) h(c);
|
||||
}
|
||||
|
||||
/** Calls handler for each command until the returned function is called. */
|
||||
export function onCommand(handler: (c: AppCommand) => void): () => void {
|
||||
handlers.add(handler);
|
||||
return () => handlers.delete(handler);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { diffDocs, diffStats, diffWords, linesOf } from "./diff";
|
||||
|
||||
const p = (text: string) => ({ type: "paragraph", content: text ? [{ type: "text", text }] : [] });
|
||||
const h = (level: number, text: string) => ({ type: "heading", attrs: { level }, content: [{ type: "text", text }] });
|
||||
const doc = (...content: object[]) => ({ type: "doc", content });
|
||||
|
||||
describe("linesOf", () => {
|
||||
it("lists blocks in order, list items and atoms included", () => {
|
||||
const lines = linesOf(
|
||||
doc(
|
||||
h(1, "Title"),
|
||||
p(""),
|
||||
{
|
||||
type: "bulletList",
|
||||
content: [
|
||||
{ type: "listItem", content: [p("one")] },
|
||||
{ type: "listItem", content: [p("two")] },
|
||||
],
|
||||
},
|
||||
{ type: "image", attrs: { src: "/api/v1/files/x", alt: "Logo" } },
|
||||
),
|
||||
);
|
||||
expect(lines).toEqual([
|
||||
{ kind: "h1", text: "Title" },
|
||||
{ kind: "paragraph", text: "one" },
|
||||
{ kind: "paragraph", text: "two" },
|
||||
{ kind: "image", text: "🖼 Logo" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("diffWords", () => {
|
||||
it("marks changed words and keeps the text", () => {
|
||||
const parts = diffWords("the quick fox", "the slow fox");
|
||||
expect(parts).toEqual([
|
||||
{ text: "the ", change: "same" },
|
||||
{ text: "quick", change: "removed" },
|
||||
{ text: "slow", change: "added" },
|
||||
{ text: " fox", change: "same" },
|
||||
]);
|
||||
expect(
|
||||
parts
|
||||
.filter((x) => x.change !== "removed")
|
||||
.map((x) => x.text)
|
||||
.join(""),
|
||||
).toBe("the slow fox");
|
||||
});
|
||||
});
|
||||
|
||||
describe("diffDocs", () => {
|
||||
it("finds added, removed and edited blocks", () => {
|
||||
const rows = diffDocs(
|
||||
doc(h(1, "Plan"), p("Ship the editor on Monday"), p("Old note")),
|
||||
doc(h(1, "Plan"), p("Ship the editor on Friday"), p("Brand new idea")),
|
||||
);
|
||||
expect(rows.map((r) => r.change)).toEqual(["same", "changed", "removed", "added"]);
|
||||
expect(diffStats(rows)).toEqual({ added: 1, removed: 1, changed: 1 });
|
||||
});
|
||||
|
||||
it("treats a missing document as empty", () => {
|
||||
expect(diffDocs(null, doc(p("Hello"))).map((r) => r.change)).toEqual(["added"]);
|
||||
expect(diffDocs(doc(p("Hello")), doc(p("Hello")))).toEqual([
|
||||
{ change: "same", line: { kind: "paragraph", text: "Hello" } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { JSONContent } from "@docwell/editor";
|
||||
|
||||
/** One line of a page as the diff sees it: a block's text with its kind. */
|
||||
export interface Line {
|
||||
kind: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** A run of words in a changed line. */
|
||||
export interface Part {
|
||||
text: string;
|
||||
change: "same" | "added" | "removed";
|
||||
}
|
||||
|
||||
export type DiffRow =
|
||||
| { change: "same" | "added" | "removed"; line: Line }
|
||||
/** A line that was edited: the old and new text, word by word. */
|
||||
| { change: "changed"; line: Line; parts: Part[] };
|
||||
|
||||
const textOf = (n: JSONContent): string =>
|
||||
n.type === "text"
|
||||
? (n.text ?? "")
|
||||
: n.type === "hardBreak"
|
||||
? "\n"
|
||||
: n.type === "mention"
|
||||
? `@${String(n.attrs?.label ?? "")}`
|
||||
: n.type === "inlineMath"
|
||||
? `$${String(n.attrs?.latex ?? "")}$`
|
||||
: (n.content ?? []).map(textOf).join("");
|
||||
|
||||
// Blocks without text still show up, so adding or removing one is visible.
|
||||
const atoms: Record<string, (a: Record<string, unknown>) => string> = {
|
||||
image: (a) => `🖼 ${String(a.alt || a.src || "")}`,
|
||||
fileAttachment: (a) => `📎 ${String(a.name ?? "")}`,
|
||||
mermaid: (a) => String(a.code ?? ""),
|
||||
blockMath: (a) => `$$${String(a.latex ?? "")}$$`,
|
||||
embed: (a) => `▶ ${String(a.url ?? "")}`,
|
||||
linkCard: (a) => `🔗 ${String(a.title || a.url || "")}`,
|
||||
drawio: () => "Draw.io",
|
||||
excalidraw: () => "Excalidraw",
|
||||
tableOfContents: () => "≡",
|
||||
horizontalRule: () => "———",
|
||||
};
|
||||
|
||||
/** The page's blocks in reading order, one line each (list items one per item). */
|
||||
export function linesOf(doc: JSONContent | null | undefined): Line[] {
|
||||
const out: Line[] = [];
|
||||
const walk = (n: JSONContent) => {
|
||||
const type = n.type ?? "";
|
||||
const atom = atoms[type];
|
||||
if (atom) {
|
||||
out.push({ kind: type, text: atom(n.attrs ?? {}) });
|
||||
return;
|
||||
}
|
||||
if (["paragraph", "heading", "codeBlock", "detailsSummary"].includes(type)) {
|
||||
const kind = type === "heading" ? `h${Number(n.attrs?.level) || 1}` : type;
|
||||
// Empty paragraphs are spacing, not content.
|
||||
const text = textOf(n);
|
||||
if (text.trim() || type !== "paragraph") out.push({ kind, text });
|
||||
return;
|
||||
}
|
||||
for (const c of n.content ?? []) walk(c);
|
||||
};
|
||||
if (doc) walk(doc);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Longest common subsequence alignment of a and b by eq, as edit steps. */
|
||||
function align<T>(a: T[], b: T[], eq: (x: T, y: T) => boolean): ("same" | "removed" | "added")[] {
|
||||
const n = a.length;
|
||||
const m = b.length;
|
||||
// Pages are a few hundred lines at most; a full table is fine.
|
||||
const dp: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0));
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
for (let j = m - 1; j >= 0; j--) {
|
||||
dp[i]![j] = eq(a[i]!, b[j]!) ? dp[i + 1]![j + 1]! + 1 : Math.max(dp[i + 1]![j]!, dp[i]![j + 1]!);
|
||||
}
|
||||
}
|
||||
const steps: ("same" | "removed" | "added")[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < n || j < m) {
|
||||
if (i < n && j < m && eq(a[i]!, b[j]!)) {
|
||||
steps.push("same");
|
||||
i++;
|
||||
j++;
|
||||
} else if (j < m && (i >= n || dp[i]![j + 1]! > dp[i + 1]![j]!)) {
|
||||
steps.push("added");
|
||||
j++;
|
||||
} else {
|
||||
steps.push("removed");
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
/** Words and the spaces between them, so joining the parts gives the text back. */
|
||||
const words = (s: string) => s.match(/\s+|[^\s]+/g) ?? [];
|
||||
|
||||
/** The word-level changes from a to b. */
|
||||
export function diffWords(a: string, b: string): Part[] {
|
||||
const wa = words(a);
|
||||
const wb = words(b);
|
||||
const parts: Part[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
for (const step of align(wa, wb, (x, y) => x === y)) {
|
||||
const text = step === "added" ? wb[j++]! : step === "removed" ? wa[i++]! : (j++, wa[i++]!);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last?.change === step) last.text += text;
|
||||
else parts.push({ text, change: step });
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/** How alike two lines are, from 0 to 1, by the words they share. */
|
||||
function similarity(a: string, b: string): number {
|
||||
const parts = diffWords(a, b);
|
||||
const same = parts.filter((p) => p.change === "same").reduce((n, p) => n + p.text.trim().length, 0);
|
||||
const total = Math.max(a.replace(/\s/g, "").length, b.replace(/\s/g, "").length, 1);
|
||||
return same / total;
|
||||
}
|
||||
|
||||
/**
|
||||
* The changes from the old document to the new one, block by block. A block
|
||||
* removed right where a similar one was added counts as edited, and shows
|
||||
* which words changed.
|
||||
*/
|
||||
export function diffDocs(older: JSONContent | null | undefined, newer: JSONContent | null | undefined): DiffRow[] {
|
||||
const a = linesOf(older);
|
||||
const b = linesOf(newer);
|
||||
const rows: DiffRow[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
for (const step of align(a, b, (x, y) => x.kind === y.kind && x.text === y.text)) {
|
||||
if (step === "same") {
|
||||
rows.push({ change: "same", line: b[j++]! });
|
||||
i++;
|
||||
} else if (step === "removed") rows.push({ change: "removed", line: a[i++]! });
|
||||
else rows.push({ change: "added", line: b[j++]! });
|
||||
}
|
||||
// Pair each run of removals with the additions that follow it.
|
||||
const out: DiffRow[] = [];
|
||||
for (let k = 0; k < rows.length;) {
|
||||
if (rows[k]!.change !== "removed") {
|
||||
out.push(rows[k++]!);
|
||||
continue;
|
||||
}
|
||||
const removed: DiffRow[] = [];
|
||||
while (k < rows.length && rows[k]!.change === "removed") removed.push(rows[k++]!);
|
||||
const added: DiffRow[] = [];
|
||||
while (k < rows.length && rows[k]!.change === "added") added.push(rows[k++]!);
|
||||
const pairs = Math.min(removed.length, added.length);
|
||||
for (let p = 0; p < pairs; p++) {
|
||||
const was = removed[p]!.line;
|
||||
const now = added[p]!.line;
|
||||
if (was.kind === now.kind && similarity(was.text, now.text) >= 0.4) {
|
||||
out.push({ change: "changed", line: now, parts: diffWords(was.text, now.text) });
|
||||
} else {
|
||||
out.push(removed[p]!, added[p]!);
|
||||
}
|
||||
}
|
||||
out.push(...removed.slice(pairs), ...added.slice(pairs));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Counts of added, removed and edited blocks. */
|
||||
export function diffStats(rows: DiffRow[]) {
|
||||
return {
|
||||
added: rows.filter((r) => r.change === "added").length,
|
||||
removed: rows.filter((r) => r.change === "removed").length,
|
||||
changed: rows.filter((r) => r.change === "changed").length,
|
||||
};
|
||||
}
|
||||
@@ -24,7 +24,8 @@
|
||||
"collapseSidebar": "Collapse sidebar",
|
||||
"expandSidebar": "Expand sidebar",
|
||||
"resize": "Resize sidebar",
|
||||
"switchWorkspace": "Switch workspace"
|
||||
"switchWorkspace": "Switch workspace",
|
||||
"archive": "Archive"
|
||||
},
|
||||
"home": {
|
||||
"untitled": "Untitled",
|
||||
@@ -221,7 +222,11 @@
|
||||
"import": "Import",
|
||||
"importing": "Importing…",
|
||||
"importHint": "Markdown, HTML, Word (.docx) or a Notion export (.zip)",
|
||||
"sharedWithYou": "Shared with you"
|
||||
"sharedWithYou": "Shared with you",
|
||||
"export": "Export space",
|
||||
"exporting": "Exporting…",
|
||||
"exportMarkdown": "Export as Markdown (zip)",
|
||||
"exportHtml": "Export as HTML (zip)"
|
||||
},
|
||||
"page": {
|
||||
"title": "Page title",
|
||||
@@ -253,6 +258,20 @@
|
||||
"labels": {
|
||||
"before-restore": "Before a restore",
|
||||
"before-replace": "Before a replace"
|
||||
},
|
||||
"preview": "Version",
|
||||
"changes": "Changes",
|
||||
"compareWith": "Compare with",
|
||||
"previousVersion": "the version before",
|
||||
"currentPage": "the page now",
|
||||
"firstVersion": "This is the first version: everything in it is new.",
|
||||
"noChanges": "No changes.",
|
||||
"stats": "{added} added · {removed} removed · {changed} edited",
|
||||
"change": {
|
||||
"same": "Unchanged",
|
||||
"added": "Added",
|
||||
"removed": "Removed",
|
||||
"changed": "Edited"
|
||||
}
|
||||
},
|
||||
"notFound": "This page does not exist or you don't have access to it.",
|
||||
@@ -263,7 +282,12 @@
|
||||
"exportMarkdown": "Export as Markdown",
|
||||
"exportHtml": "Export as HTML",
|
||||
"exportPdf": "Export as PDF",
|
||||
"backlinks": "Linked from {n} page | Linked from {n} pages"
|
||||
"backlinks": "Linked from {n} page | Linked from {n} pages",
|
||||
"archive": "Archive",
|
||||
"unarchive": "Unarchive",
|
||||
"archived": "This page is archived. It is read-only until someone unarchives it.",
|
||||
"parentArchived": "A page above this one is archived, so this page is read-only.",
|
||||
"linkCopied": "Link copied"
|
||||
},
|
||||
"trash": {
|
||||
"hint": "Pages inside a trashed page come back when you restore it.",
|
||||
@@ -412,6 +436,18 @@
|
||||
"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": {
|
||||
@@ -439,7 +475,14 @@
|
||||
"emptyExcalidraw": "Empty drawing. Click to sketch.",
|
||||
"loadFailed": "The editor could not be loaded.",
|
||||
"toc": "Contents",
|
||||
"tocEmpty": "Add headings to the page to fill the table of 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"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
@@ -551,5 +594,29 @@
|
||||
"attempts": "{n} attempts",
|
||||
"noDeliveries": "Nothing sent yet.",
|
||||
"none": "No webhooks yet."
|
||||
},
|
||||
"archive": {
|
||||
"hint": "Archived pages are out of the page tree but stay readable and searchable. Pages inside an archived page come back with it.",
|
||||
"empty": "Nothing is archived.",
|
||||
"archivedAt": "Archived {date}"
|
||||
},
|
||||
"servers": {
|
||||
"title": "Servers",
|
||||
"subtitle": "The Docwell servers this app signs in to. Each one keeps its own sign-in.",
|
||||
"desktopOnly": "Servers are chosen in the Docwell desktop app. In a browser, open the server's own address.",
|
||||
"current": "Current",
|
||||
"switch": "Switch",
|
||||
"rename": "Rename",
|
||||
"remove": "Remove",
|
||||
"confirmRemove": "Remove {name}? You are signed out of it on this computer.",
|
||||
"add": "Add a server",
|
||||
"url": "Server address",
|
||||
"name": "Name",
|
||||
"nameHint": "Optional, e.g. Work. Defaults to the address.",
|
||||
"addHint": "The app switches to the new server; sign in there with that server's account.",
|
||||
"addAndSwitch": "Add and switch",
|
||||
"change": "Change server",
|
||||
"manage": "Manage servers",
|
||||
"signedInTo": "Signed in to {url}"
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,8 @@
|
||||
"collapseSidebar": "Zwiń pasek boczny",
|
||||
"expandSidebar": "Rozwiń pasek boczny",
|
||||
"resize": "Zmień szerokość paska bocznego",
|
||||
"switchWorkspace": "Przełącz obszar roboczy"
|
||||
"switchWorkspace": "Przełącz obszar roboczy",
|
||||
"archive": "Archiwum"
|
||||
},
|
||||
"home": {
|
||||
"untitled": "Bez tytułu",
|
||||
@@ -221,7 +222,11 @@
|
||||
"import": "Importuj",
|
||||
"importing": "Importowanie…",
|
||||
"importHint": "Markdown, HTML, Word (.docx) lub eksport z Notion (.zip)",
|
||||
"sharedWithYou": "Udostępnione Tobie"
|
||||
"sharedWithYou": "Udostępnione Tobie",
|
||||
"export": "Eksportuj przestrzeń",
|
||||
"exporting": "Eksportowanie…",
|
||||
"exportMarkdown": "Eksportuj jako Markdown (zip)",
|
||||
"exportHtml": "Eksportuj jako HTML (zip)"
|
||||
},
|
||||
"page": {
|
||||
"title": "Tytuł strony",
|
||||
@@ -253,6 +258,20 @@
|
||||
"labels": {
|
||||
"before-restore": "Przed przywróceniem",
|
||||
"before-replace": "Przed zastąpieniem"
|
||||
},
|
||||
"preview": "Wersja",
|
||||
"changes": "Zmiany",
|
||||
"compareWith": "Porównaj z",
|
||||
"previousVersion": "poprzednią wersją",
|
||||
"currentPage": "obecną stroną",
|
||||
"firstVersion": "To pierwsza wersja: cała jej treść jest nowa.",
|
||||
"noChanges": "Brak zmian.",
|
||||
"stats": "dodane: {added} · usunięte: {removed} · zmienione: {changed}",
|
||||
"change": {
|
||||
"same": "Bez zmian",
|
||||
"added": "Dodane",
|
||||
"removed": "Usunięte",
|
||||
"changed": "Zmienione"
|
||||
}
|
||||
},
|
||||
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu.",
|
||||
@@ -263,7 +282,12 @@
|
||||
"exportMarkdown": "Eksportuj jako Markdown",
|
||||
"exportHtml": "Eksportuj jako HTML",
|
||||
"exportPdf": "Eksportuj jako PDF",
|
||||
"backlinks": "Linkuje tu {n} strona | Linkują tu {n} strony | Linkuje tu {n} stron"
|
||||
"backlinks": "Linkuje tu {n} strona | Linkują tu {n} strony | Linkuje tu {n} stron",
|
||||
"archive": "Archiwizuj",
|
||||
"unarchive": "Przywróć z archiwum",
|
||||
"archived": "Ta strona jest zarchiwizowana. Jest tylko do odczytu, dopóki ktoś jej nie przywróci.",
|
||||
"parentArchived": "Strona nadrzędna jest zarchiwizowana, więc ta strona jest tylko do odczytu.",
|
||||
"linkCopied": "Skopiowano link"
|
||||
},
|
||||
"trash": {
|
||||
"hint": "Strony wewnątrz przywróconej strony wracają razem z nią.",
|
||||
@@ -412,6 +436,18 @@
|
||||
"pageLink": {
|
||||
"label": "Link do strony",
|
||||
"description": "Połącz z inną stroną (lub wpisz [[)"
|
||||
},
|
||||
"toggle": {
|
||||
"label": "Rozwijana sekcja",
|
||||
"description": "Nagłówek, który ukrywa bloki pod sobą"
|
||||
},
|
||||
"embed": {
|
||||
"label": "Osadzenie",
|
||||
"description": "Film, projekt lub dokument z YouTube, Figmy i innych"
|
||||
},
|
||||
"linkCard": {
|
||||
"label": "Karta linku",
|
||||
"description": "Link z tytułem i obrazkiem strony"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
@@ -439,7 +475,14 @@
|
||||
"emptyExcalidraw": "Pusty rysunek. Kliknij, aby szkicować.",
|
||||
"loadFailed": "Nie udało się wczytać edytora.",
|
||||
"toc": "Spis treści",
|
||||
"tocEmpty": "Dodaj nagłówki do strony, aby wypełnić spis treści."
|
||||
"tocEmpty": "Dodaj nagłówki do strony, aby wypełnić spis treści.",
|
||||
"expand": "Pokaż zawartość",
|
||||
"collapse": "Ukryj zawartość",
|
||||
"embed": "Osadzona treść",
|
||||
"embedUrl": "Adres filmu, projektu lub dokumentu",
|
||||
"embedInvalid": "Tego adresu nie da się osadzić.",
|
||||
"linkUrl": "Adres strony do podlinkowania",
|
||||
"copyBlockLink": "Kopiuj link do tego bloku"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
@@ -551,5 +594,29 @@
|
||||
"attempts": "prób: {n}",
|
||||
"noDeliveries": "Nic jeszcze nie wysłano.",
|
||||
"none": "Brak webhooków."
|
||||
},
|
||||
"archive": {
|
||||
"hint": "Zarchiwizowane strony nie są w drzewie stron, ale można je czytać i wyszukiwać. Strony wewnątrz zarchiwizowanej strony wracają razem z nią.",
|
||||
"empty": "Archiwum jest puste.",
|
||||
"archivedAt": "Zarchiwizowano {date}"
|
||||
},
|
||||
"servers": {
|
||||
"title": "Serwery",
|
||||
"subtitle": "Serwery Docwell, do których loguje się ta aplikacja. Każdy ma osobne logowanie.",
|
||||
"desktopOnly": "Serwery wybiera się w aplikacji Docwell na komputer. W przeglądarce otwórz adres danego serwera.",
|
||||
"current": "Bieżący",
|
||||
"switch": "Przełącz",
|
||||
"rename": "Zmień nazwę",
|
||||
"remove": "Usuń",
|
||||
"confirmRemove": "Usunąć {name}? Zostaniesz z niego wylogowany na tym komputerze.",
|
||||
"add": "Dodaj serwer",
|
||||
"url": "Adres serwera",
|
||||
"name": "Nazwa",
|
||||
"nameHint": "Opcjonalnie, np. Praca. Domyślnie adres.",
|
||||
"addHint": "Aplikacja przełączy się na nowy serwer; zaloguj się tam kontem z tego serwera.",
|
||||
"addAndSwitch": "Dodaj i przełącz",
|
||||
"change": "Zmień serwer",
|
||||
"manage": "Zarządzaj serwerami",
|
||||
"signedInTo": "Zalogowano do {url}"
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,35 @@ export interface RuntimeConfig {
|
||||
drawioUrl?: string;
|
||||
}
|
||||
|
||||
/** Keeps the session token. The browser uses localStorage; the desktop app the system keychain. */
|
||||
export interface TokenStore {
|
||||
get(): string | null;
|
||||
set(token: string | null): void;
|
||||
}
|
||||
|
||||
/** A docwell-server the desktop app can sign in to. */
|
||||
export interface ServerEntry {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The desktop app's saved servers. Adding one or switching reloads the
|
||||
* window, which then talks to the newly active server with its own session.
|
||||
*/
|
||||
export interface ServerHost {
|
||||
list(): Promise<{ servers: ServerEntry[]; active: string }>;
|
||||
add(name: string, url: string): Promise<void>;
|
||||
rename(id: string, name: string): Promise<void>;
|
||||
/** Forgets a server and signs out of it. */
|
||||
remove(id: string): Promise<void>;
|
||||
switchTo(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Menu commands a host can send: the native menu bar on the desktop. */
|
||||
export type AppCommand = "new-page" | "search" | "toggle-sidebar";
|
||||
|
||||
/**
|
||||
* Differences between hosts that run this app: browser (docwell-web),
|
||||
* Desktop-App (Wails) and the Phone-App editor WebView.
|
||||
@@ -21,6 +50,14 @@ export interface Platform {
|
||||
loadConfig(): Promise<RuntimeConfig>;
|
||||
/** Calls open with an app route (e.g. "/p/abc") when the OS opens a docwell:// link. */
|
||||
onOpenRoute?(open: (route: string) => void): void;
|
||||
/** The address to share for an app route, e.g. a copied link to a block. */
|
||||
pageUrl(route: string): string;
|
||||
/** Where the session token is kept; without it, localStorage. */
|
||||
tokenStore?(): Promise<TokenStore>;
|
||||
/** Calls run with each command from the host's own menus. */
|
||||
onCommand?(run: (command: AppCommand) => void): void;
|
||||
/** The servers to choose from (desktop only). */
|
||||
servers?: ServerHost;
|
||||
}
|
||||
|
||||
export const webPlatform: Platform = {
|
||||
@@ -34,6 +71,7 @@ export const webPlatform: Platform = {
|
||||
}
|
||||
return (await res.json()) as RuntimeConfig;
|
||||
},
|
||||
pageUrl: (route) => location.origin + route,
|
||||
};
|
||||
|
||||
export const platformKey: InjectionKey<Platform> = Symbol("platform");
|
||||
|
||||
@@ -28,6 +28,12 @@ export function createDocwellRouter(platform: Platform) {
|
||||
{ path: "p/:id", name: "page", component: () => import("./views/page/PageView.vue"), props: true },
|
||||
{ path: "s/:id", name: "space", component: () => import("./views/space/SpaceView.vue"), props: true },
|
||||
{ path: "s/:id/trash", name: "trash", component: () => import("./views/space/TrashView.vue"), props: true },
|
||||
{
|
||||
path: "s/:id/archive",
|
||||
name: "archive",
|
||||
component: () => import("./views/space/ArchiveView.vue"),
|
||||
props: true,
|
||||
},
|
||||
{ path: "notifications", name: "notifications", component: () => import("./views/NotificationsView.vue") },
|
||||
],
|
||||
},
|
||||
@@ -48,6 +54,13 @@ export function createDocwellRouter(platform: Platform) {
|
||||
name: "account",
|
||||
component: () => import("./views/settings/AccountView.vue"),
|
||||
},
|
||||
{
|
||||
path: "/settings/servers",
|
||||
name: "servers",
|
||||
component: () => import("./views/settings/ServersView.vue"),
|
||||
// Signed out too: the sign-in page links here to pick a server.
|
||||
meta: { public: true },
|
||||
},
|
||||
{
|
||||
path: "/settings/organization",
|
||||
name: "organization",
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { ApiError, type AuthMethods } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { DwButton, DwCallout, DwIcon } from "@docwell/ui";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import AuthCard from "../../components/AuthCard.vue";
|
||||
import FormField from "../../components/FormField.vue";
|
||||
import { useFormErrors } from "../../composables/useFormErrors";
|
||||
import { usePlatform } from "../../platform";
|
||||
import { usePlatform, useRuntimeConfig } from "../../platform";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
|
||||
const api = useApi();
|
||||
@@ -16,6 +16,7 @@ const auth = useAuthStore();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const platform = usePlatform();
|
||||
const config = useRuntimeConfig();
|
||||
const errors = useFormErrors();
|
||||
|
||||
const email = ref("");
|
||||
@@ -117,6 +118,12 @@ function startOver() {
|
||||
<template>
|
||||
<AuthCard :title="$t('auth.login.title')">
|
||||
<form v-if="step === 'password'" class="space-y-4" @submit.prevent="submitPassword">
|
||||
<!-- The desktop app can sign in to several servers; show which one this is. -->
|
||||
<p v-if="platform.servers" class="flex items-center gap-2 text-ui-sm text-ink-muted" data-testid="login-server">
|
||||
<DwIcon name="server" :size="14" />
|
||||
<span class="min-w-0 truncate">{{ config.apiUrl }}</span>
|
||||
<RouterLink :to="{ name: 'servers' }" class="dw-link ml-auto shrink-0">{{ $t("servers.change") }}</RouterLink>
|
||||
</p>
|
||||
<FormField
|
||||
v-model="email"
|
||||
:label="$t('auth.email')"
|
||||
|
||||
@@ -6,6 +6,9 @@ import {
|
||||
DocwellEditor,
|
||||
encodeAnchor,
|
||||
insertFiles,
|
||||
linkedBlock,
|
||||
pagePath,
|
||||
scrollToBlock,
|
||||
setCommentMarks,
|
||||
userColor,
|
||||
type CommentAnchor,
|
||||
@@ -22,7 +25,7 @@ import ShareDialog from "../../components/ShareDialog.vue";
|
||||
import { useEditorLabels, useMentions, usePageLinks } from "../../composables/useEditorHosts";
|
||||
import { useFileHost } from "../../composables/useFiles";
|
||||
import { saveBlob } from "../../lib/download";
|
||||
import { useRuntimeConfig } from "../../platform";
|
||||
import { usePlatform, useRuntimeConfig } from "../../platform";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
import { useFavoritesStore } from "../../stores/favorites";
|
||||
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
|
||||
@@ -39,6 +42,7 @@ const route = useRoute();
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const config = useRuntimeConfig();
|
||||
const platform = usePlatform();
|
||||
const token = useToken();
|
||||
|
||||
const page = ref<Page | null>(null);
|
||||
@@ -50,6 +54,42 @@ const shareOpen = ref(false);
|
||||
const labels = useEditorLabels();
|
||||
const mentions = useMentions(() => page.value?.workspace);
|
||||
const pageLinks = usePageLinks(() => page.value?.workspace);
|
||||
// Link cards: docwell-server reads the linked page's title and picture.
|
||||
const linkHost = { preview: (url: string) => api.pages.preview(url) };
|
||||
|
||||
// Links to one block: "#b-<id>" after the page's address. The margin button
|
||||
// copies one; opening one scrolls to the block once the text has loaded.
|
||||
const copied = ref(false);
|
||||
let copiedTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const blockLink = (hash: string) => platform.pageUrl(pagePath(page.value?.id ?? props.id) + hash);
|
||||
function blockLinkCopied() {
|
||||
copied.value = true;
|
||||
clearTimeout(copiedTimer);
|
||||
copiedTimer = setTimeout(() => (copied.value = false), 2000);
|
||||
}
|
||||
let scrolledTo = "";
|
||||
function scrollToHash() {
|
||||
const editor = editorRef.value?.editor;
|
||||
const id = linkedBlock(route.hash);
|
||||
const key = `${props.id}${id}`;
|
||||
if (!editor || !id || scrolledTo === key) return;
|
||||
// The shared document fills the editor just after it is created, and node
|
||||
// views draw a moment later: try again as it changes, for a few seconds.
|
||||
const attempt = () =>
|
||||
setTimeout(() => {
|
||||
if (scrolledTo !== key && scrollToBlock(editor, id)) {
|
||||
scrolledTo = key;
|
||||
stop();
|
||||
}
|
||||
}, 50);
|
||||
const stop = () => {
|
||||
editor.off("transaction", attempt);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
const timer = setTimeout(stop, 5000);
|
||||
editor.on("transaction", attempt);
|
||||
attempt();
|
||||
}
|
||||
|
||||
// Inline comments: listed in a side panel, their text lit in the editor.
|
||||
const commentsOpen = ref(false);
|
||||
@@ -173,6 +213,7 @@ async function attachPicked() {
|
||||
// Redraw comment highlights when the list, the active one or the editor changes.
|
||||
watch([comments, activeComment, () => editorRef.value?.editor], drawComments);
|
||||
watch(() => editorRef.value?.editor, trackEmpty);
|
||||
watch([() => route.hash, () => editorRef.value?.editor], scrollToHash);
|
||||
|
||||
// The page body is a shared Yjs document; edits sync live and the server saves them.
|
||||
const provider = shallowRef<CollabProvider | null>(null);
|
||||
@@ -220,7 +261,9 @@ function closeDoc() {
|
||||
p?.destroy();
|
||||
}
|
||||
|
||||
const editable = computed(() => !!page.value && !page.value.inTrash && spaceAtLeast(page.value.role, "editor"));
|
||||
const canEdit = computed(() => !!page.value && !page.value.inTrash && spaceAtLeast(page.value.role, "editor"));
|
||||
// Archived pages stay readable but are not edited until they come back.
|
||||
const editable = computed(() => canEdit.value && !page.value!.archived);
|
||||
const children = computed(() => (page.value ? spaces.childrenOf(page.value.space, page.value.id) : []));
|
||||
// Space, then the page's ancestors, then the page itself (not a link).
|
||||
const crumbs = computed(() => {
|
||||
@@ -349,6 +392,7 @@ const menu = computed<MenuItem[]>(() => [
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(editable.value ? [{ label: t("page.archive"), icon: "archive" as const, onSelect: () => archive() }] : []),
|
||||
{ label: t("page.exportMarkdown"), icon: "download", onSelect: () => exportAs("markdown") },
|
||||
{ label: t("page.exportHtml"), icon: "download", onSelect: () => exportAs("html") },
|
||||
{ label: t("page.exportPdf"), icon: "download", onSelect: () => exportAs("pdf") },
|
||||
@@ -366,6 +410,20 @@ const trash = () =>
|
||||
await load(props.id);
|
||||
});
|
||||
|
||||
const archive = () =>
|
||||
run(async () => {
|
||||
const p = await api.pages.archive(page.value!.id);
|
||||
await spaces.loadTree(p.space);
|
||||
await load(props.id);
|
||||
});
|
||||
|
||||
const unarchive = () =>
|
||||
run(async () => {
|
||||
const p = await api.pages.unarchive(page.value!.id);
|
||||
await spaces.loadTree(p.space);
|
||||
await load(props.id);
|
||||
});
|
||||
|
||||
const restore = () =>
|
||||
run(async () => {
|
||||
await api.pages.restore(page.value!.id);
|
||||
@@ -478,6 +536,20 @@ const purge = () =>
|
||||
</template>
|
||||
</DwCallout>
|
||||
|
||||
<DwCallout
|
||||
v-else-if="page.archived"
|
||||
tone="info"
|
||||
size="ui"
|
||||
class="mb-4 items-center"
|
||||
role="status"
|
||||
data-testid="archived-note"
|
||||
>
|
||||
{{ page.archivedAt ? $t("page.archived") : $t("page.parentArchived") }}
|
||||
<template v-if="page.archivedAt && canEdit" #actions>
|
||||
<DwButton size="sm" icon="restore" :disabled="busy" @click="unarchive">{{ $t("page.unarchive") }}</DwButton>
|
||||
</template>
|
||||
</DwCallout>
|
||||
|
||||
<input
|
||||
v-model="title"
|
||||
:readonly="!editable"
|
||||
@@ -511,6 +583,8 @@ const purge = () =>
|
||||
:files="files.host"
|
||||
:mentions="mentions"
|
||||
:pages="pageLinks"
|
||||
:links="linkHost"
|
||||
:block-link="blockLink"
|
||||
:drawio-url="config.drawioUrl"
|
||||
:labels="labels"
|
||||
:can-comment="canComment"
|
||||
@@ -520,6 +594,7 @@ const purge = () =>
|
||||
class="mt-4"
|
||||
data-testid="page-editor"
|
||||
@navigate="router.push($event)"
|
||||
@block-link-copied="blockLinkCopied"
|
||||
@error="emit('error', $event)"
|
||||
@comment="startComment"
|
||||
@comment-select="selectComment"
|
||||
@@ -565,6 +640,14 @@ const purge = () =>
|
||||
</section>
|
||||
</template>
|
||||
</article>
|
||||
<p
|
||||
v-if="copied"
|
||||
role="status"
|
||||
class="fixed bottom-6 left-1/2 z-40 -translate-x-1/2 rounded-md bg-ink px-3 py-1.5 text-ui-sm text-surface shadow-menu"
|
||||
data-testid="link-copied"
|
||||
>
|
||||
{{ $t("page.linkCopied") }}
|
||||
</p>
|
||||
<!-- Beside the text on wide screens; a sheet over the bottom on narrow ones. -->
|
||||
<PageComments
|
||||
v-if="page && commentsOpen"
|
||||
|
||||
@@ -8,12 +8,15 @@ import { useApi } from "../../api";
|
||||
import FormField from "../../components/FormField.vue";
|
||||
import PageShell from "../../components/PageShell.vue";
|
||||
import { useFormErrors } from "../../composables/useFormErrors";
|
||||
import { usePlatform, useRuntimeConfig } from "../../platform";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
|
||||
// The signed-in person's own security: two-step sign-in with an
|
||||
// authenticator app, and personal API tokens.
|
||||
const api = useApi();
|
||||
const auth = useAuthStore();
|
||||
const platform = usePlatform();
|
||||
const config = useRuntimeConfig();
|
||||
const { locale } = useI18n();
|
||||
const errors = useFormErrors();
|
||||
const busy = ref(false);
|
||||
@@ -105,6 +108,15 @@ const when = (s: string) =>
|
||||
<PageShell :title="$t('account.title')" :subtitle="auth.user?.email">
|
||||
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
|
||||
|
||||
<!-- The desktop app: which server this account is on, and the others. -->
|
||||
<section v-if="platform.servers" class="dw-card flex flex-wrap items-center gap-3" data-testid="servers-section">
|
||||
<div class="min-w-0 flex-1">
|
||||
<h2 class="text-ui-lg">{{ $t("servers.title") }}</h2>
|
||||
<p class="mt-1 truncate text-ui-sm text-ink-muted">{{ $t("servers.signedInTo", { url: config.apiUrl }) }}</p>
|
||||
</div>
|
||||
<RouterLink :to="{ name: 'servers' }" class="dw-link">{{ $t("servers.manage") }}</RouterLink>
|
||||
</section>
|
||||
|
||||
<!-- Two-step sign-in -->
|
||||
<section v-if="totp" class="space-y-4 dw-card" data-testid="totp-section">
|
||||
<div>
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import { DwBadge, DwButton, DwCallout, DwIcon } from "@docwell/ui";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import FormField from "../../components/FormField.vue";
|
||||
import PageShell from "../../components/PageShell.vue";
|
||||
import { usePlatform, type ServerEntry } from "../../platform";
|
||||
|
||||
// The desktop app's servers. Each keeps its own sign-in (in the system
|
||||
// keychain); switching reloads the window onto the chosen server.
|
||||
const platform = usePlatform();
|
||||
const host = platform.servers;
|
||||
const { t } = useI18n();
|
||||
|
||||
const servers = ref<ServerEntry[]>([]);
|
||||
const active = ref("");
|
||||
const name = ref("");
|
||||
const url = ref("https://");
|
||||
const error = ref("");
|
||||
const busy = ref(false);
|
||||
const editing = ref("");
|
||||
const editName = ref("");
|
||||
|
||||
async function load() {
|
||||
if (!host) return;
|
||||
const s = await host.list();
|
||||
servers.value = s.servers;
|
||||
active.value = s.active;
|
||||
}
|
||||
onMounted(load);
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
busy.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await action();
|
||||
await load();
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const add = () => run(() => host!.add(name.value, url.value));
|
||||
const switchTo = (s: ServerEntry) => run(() => host!.switchTo(s.id));
|
||||
function remove(s: ServerEntry) {
|
||||
if (!confirm(t("servers.confirmRemove", { name: s.name }))) return;
|
||||
run(() => host!.remove(s.id));
|
||||
}
|
||||
function startRename(s: ServerEntry) {
|
||||
editing.value = s.id;
|
||||
editName.value = s.name;
|
||||
}
|
||||
const rename = () =>
|
||||
run(async () => {
|
||||
await host!.rename(editing.value, editName.value);
|
||||
editing.value = "";
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PageShell :title="$t('servers.title')" :subtitle="$t('servers.subtitle')">
|
||||
<DwCallout v-if="!host" tone="info" size="ui">{{ $t("servers.desktopOnly") }}</DwCallout>
|
||||
<template v-else>
|
||||
<DwCallout v-if="error" tone="danger" size="ui">{{ error }}</DwCallout>
|
||||
|
||||
<ul class="dw-card divide-y divide-line !p-0" data-testid="server-list">
|
||||
<li v-for="s in servers" :key="s.id" class="flex flex-wrap items-center gap-3 px-4 py-3">
|
||||
<DwIcon name="server" :size="18" class="text-ink-muted" />
|
||||
<form v-if="editing === s.id" class="flex min-w-0 flex-1 gap-2" @submit.prevent="rename">
|
||||
<input
|
||||
v-model="editName"
|
||||
class="min-w-0 flex-1 rounded-sm border border-line bg-surface px-2 py-1 text-ui-md"
|
||||
:aria-label="$t('servers.name')"
|
||||
maxlength="80"
|
||||
/>
|
||||
<DwButton type="submit" size="sm" :disabled="busy || !editName.trim()">{{ $t("common.save") }}</DwButton>
|
||||
</form>
|
||||
<span v-else class="min-w-0 flex-1">
|
||||
<span class="block truncate font-semibold">{{ s.name }}</span>
|
||||
<span class="block truncate text-ui-sm text-ink-muted">{{ s.url }}</span>
|
||||
</span>
|
||||
<DwBadge v-if="s.id === active" tone="accent">{{ $t("servers.current") }}</DwBadge>
|
||||
<span class="flex gap-1">
|
||||
<DwButton v-if="s.id !== active" size="sm" :disabled="busy" @click="switchTo(s)">
|
||||
{{ $t("servers.switch") }}
|
||||
</DwButton>
|
||||
<DwButton v-if="editing !== s.id" size="sm" variant="ghost" :disabled="busy" @click="startRename(s)">
|
||||
{{ $t("servers.rename") }}
|
||||
</DwButton>
|
||||
<DwButton
|
||||
v-if="servers.length > 1"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
class="!text-danger"
|
||||
:disabled="busy"
|
||||
@click="remove(s)"
|
||||
>
|
||||
{{ $t("servers.remove") }}
|
||||
</DwButton>
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<form class="space-y-4 dw-card" @submit.prevent="add">
|
||||
<h2 class="text-ui-lg">{{ $t("servers.add") }}</h2>
|
||||
<FormField v-model="url" :label="$t('servers.url')" type="url" required />
|
||||
<FormField v-model="name" :label="$t('servers.name')" :hint="$t('servers.nameHint')" />
|
||||
<p class="text-ui-sm text-ink-muted">{{ $t("servers.addHint") }}</p>
|
||||
<DwButton type="submit" variant="primary" :disabled="busy || !/^https?:\/\/.+/.test(url.trim())">
|
||||
{{ $t("servers.addAndSwitch") }}
|
||||
</DwButton>
|
||||
</form>
|
||||
</template>
|
||||
</PageShell>
|
||||
</template>
|
||||
@@ -0,0 +1,86 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { ArchivedPage, Space } from "@docwell/api-client";
|
||||
import { DwBreadcrumbs, DwButton, DwCallout, DwIcon } from "@docwell/ui";
|
||||
import { ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../../api";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
|
||||
|
||||
// Archived pages: out of the page tree, still readable, back with one click.
|
||||
const props = defineProps<{ id: string }>();
|
||||
const emit = defineEmits<{ error: [err: unknown] }>();
|
||||
const api = useApi();
|
||||
const spaces = useSpacesStore();
|
||||
const { locale } = useI18n();
|
||||
|
||||
const space = ref<Space | null>(null);
|
||||
const items = ref<ArchivedPage[]>([]);
|
||||
const notFound = ref(false);
|
||||
const busy = ref(false);
|
||||
|
||||
async function load() {
|
||||
spaces.active = { space: props.id, page: "" };
|
||||
notFound.value = false;
|
||||
try {
|
||||
[space.value, items.value] = await Promise.all([api.spaces.get(props.id), api.spaces.archive(props.id)]);
|
||||
} catch {
|
||||
space.value = null;
|
||||
notFound.value = true;
|
||||
}
|
||||
}
|
||||
watch(() => props.id, load, { immediate: true });
|
||||
|
||||
async function unarchive(p: ArchivedPage) {
|
||||
busy.value = true;
|
||||
try {
|
||||
await api.pages.unarchive(p.id);
|
||||
await Promise.all([load(), spaces.loadTree(props.id)]);
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// 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" });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport v-if="space" defer to="#app-header">
|
||||
<DwBreadcrumbs
|
||||
:items="[
|
||||
{ label: space.name, to: { name: 'space', params: { id: space.id } } },
|
||||
{ label: $t('sidebar.archive') },
|
||||
]"
|
||||
:label="$t('page.breadcrumbs')"
|
||||
/>
|
||||
</Teleport>
|
||||
|
||||
<article class="mx-auto max-w-doc px-4 pt-6 pb-16 sm:px-16 sm:pt-10">
|
||||
<DwCallout v-if="notFound" tone="info" size="ui">{{ $t("space.notFound") }}</DwCallout>
|
||||
<template v-if="space">
|
||||
<h1 class="font-serif text-doc-h1">{{ $t("sidebar.archive") }}</h1>
|
||||
<p class="mt-2 text-ui-md text-ink-muted">{{ $t("archive.hint") }}</p>
|
||||
|
||||
<PageList v-if="items.length" :items="items" class="mt-8" data-testid="archive-list">
|
||||
<template #meta="{ item }">{{ $t("archive.archivedAt", { date: when(item.archivedAt) }) }}</template>
|
||||
<template v-if="spaceAtLeast(space.role, 'editor')" #actions="{ item }">
|
||||
<DwButton size="sm" icon="restore" :disabled="busy" @click="unarchive(item)">
|
||||
{{ $t("page.unarchive") }}
|
||||
</DwButton>
|
||||
</template>
|
||||
</PageList>
|
||||
<div
|
||||
v-else
|
||||
class="mt-8 flex items-center gap-3 rounded-md border border-dashed border-line px-4 py-6 text-ink-muted"
|
||||
>
|
||||
<DwIcon name="drop" :size="20" class="text-spring" />
|
||||
{{ $t("archive.empty") }}
|
||||
</div>
|
||||
</template>
|
||||
</article>
|
||||
</template>
|
||||
@@ -1,11 +1,13 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { Space } from "@docwell/api-client";
|
||||
import { DwBadge, DwBreadcrumbs, DwButton, DwCallout, DwIcon } from "@docwell/ui";
|
||||
import { DwBadge, DwBreadcrumbs, DwButton, DwCallout, DwIcon, DwMenu, type MenuItem } from "@docwell/ui";
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import { saveBlob } from "../../lib/download";
|
||||
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
|
||||
|
||||
const props = defineProps<{ id: string }>();
|
||||
@@ -13,6 +15,7 @@ const emit = defineEmits<{ error: [err: unknown] }>();
|
||||
const api = useApi();
|
||||
const spaces = useSpacesStore();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
|
||||
const space = ref<Space | null>(null);
|
||||
const notFound = ref(false);
|
||||
@@ -56,6 +59,24 @@ async function importPicked() {
|
||||
}
|
||||
}
|
||||
|
||||
// The whole space as a zip: one file per page, folders for subpages.
|
||||
const exporting = ref(false);
|
||||
async function exportSpace(format: "markdown" | "html") {
|
||||
exporting.value = true;
|
||||
try {
|
||||
const { blob, filename } = await api.spaces.export(props.id, format);
|
||||
saveBlob(blob, filename);
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
} finally {
|
||||
exporting.value = false;
|
||||
}
|
||||
}
|
||||
const exportMenu = computed<MenuItem[]>(() => [
|
||||
{ label: t("space.exportMarkdown"), icon: "download", onSelect: () => exportSpace("markdown") },
|
||||
{ label: t("space.exportHtml"), icon: "download", onSelect: () => exportSpace("html") },
|
||||
]);
|
||||
|
||||
async function newPage() {
|
||||
try {
|
||||
const page = await spaces.createPage(props.id);
|
||||
@@ -69,6 +90,9 @@ async function newPage() {
|
||||
<template>
|
||||
<Teleport v-if="space" defer to="#app-header">
|
||||
<DwBreadcrumbs :items="[{ label: space.name }]" :label="$t('page.breadcrumbs')" class="min-w-0 flex-1" />
|
||||
<RouterLink :to="{ name: 'archive', params: { id: space.id } }" :class="headerLink">
|
||||
<DwIcon name="archive" :size="16" /><span class="sr-only sm:not-sr-only">{{ $t("sidebar.archive") }}</span>
|
||||
</RouterLink>
|
||||
<RouterLink :to="{ name: 'trash', params: { id: space.id } }" :class="headerLink">
|
||||
<DwIcon name="trash" :size="16" />{{ $t("sidebar.trash") }}
|
||||
</RouterLink>
|
||||
@@ -91,29 +115,37 @@ async function newPage() {
|
||||
|
||||
<div class="mt-10 flex items-center justify-between gap-2">
|
||||
<h2 class="dw-label">{{ $t("space.pages") }}</h2>
|
||||
<div v-if="spaceAtLeast(space.role, 'editor')" class="flex gap-1">
|
||||
<input
|
||||
ref="picker"
|
||||
type="file"
|
||||
multiple
|
||||
accept=".md,.markdown,.txt,.html,.htm,.docx,.zip,text/markdown,text/html"
|
||||
class="hidden"
|
||||
data-testid="import-input"
|
||||
@change="importPicked"
|
||||
<div class="flex gap-1">
|
||||
<DwMenu
|
||||
:items="exportMenu"
|
||||
:label="$t(exporting ? 'space.exporting' : 'space.export')"
|
||||
icon="download"
|
||||
data-testid="space-export"
|
||||
/>
|
||||
<DwButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="upload"
|
||||
:disabled="importing"
|
||||
:title="$t('space.importHint')"
|
||||
@click="picker?.click()"
|
||||
>
|
||||
{{ $t(importing ? "space.importing" : "space.import") }}
|
||||
</DwButton>
|
||||
<DwButton variant="ghost" size="sm" icon="plus" @click="newPage">
|
||||
{{ $t("app.newPage") }}
|
||||
</DwButton>
|
||||
<template v-if="spaceAtLeast(space.role, 'editor')">
|
||||
<input
|
||||
ref="picker"
|
||||
type="file"
|
||||
multiple
|
||||
accept=".md,.markdown,.txt,.html,.htm,.docx,.zip,text/markdown,text/html"
|
||||
class="hidden"
|
||||
data-testid="import-input"
|
||||
@change="importPicked"
|
||||
/>
|
||||
<DwButton
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
icon="upload"
|
||||
:disabled="importing"
|
||||
:title="$t('space.importHint')"
|
||||
@click="picker?.click()"
|
||||
>
|
||||
{{ $t(importing ? "space.importing" : "space.import") }}
|
||||
</DwButton>
|
||||
<DwButton variant="ghost" size="sm" icon="plus" @click="newPage">
|
||||
{{ $t("app.newPage") }}
|
||||
</DwButton>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<PageList v-if="pages.length" :items="pages" class="mt-2" />
|
||||
|
||||
+114
-2
@@ -854,6 +854,44 @@ paths:
|
||||
application/json:
|
||||
schema: { type: array, items: { $ref: "#/components/schemas/TrashedPage" } }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/spaces/{id}/archive:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: listArchive
|
||||
tags: [pages]
|
||||
summary: Archived pages, newest first (pages inside an archived page come back with it)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: array, items: { $ref: "#/components/schemas/ArchivedPage" } }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/spaces/{id}/export:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: exportSpace
|
||||
tags: [pages]
|
||||
summary: 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.
|
||||
security: [{ bearer: [] }]
|
||||
parameters:
|
||||
- { name: format, in: query, schema: { type: string, enum: [markdown, html], default: markdown } }
|
||||
responses:
|
||||
"200":
|
||||
description: The zip, streamed as it is built
|
||||
content:
|
||||
application/zip:
|
||||
schema: { type: string, format: binary }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
@@ -1030,6 +1068,61 @@ paths:
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/archive:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: archivePage
|
||||
tags: [pages]
|
||||
summary: >-
|
||||
Archive a page with its subtree (editor). Archived pages leave the page tree and
|
||||
become read-only, but stay readable, searchable and linkable.
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Page" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/unarchive:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: unarchivePage
|
||||
tags: [pages]
|
||||
summary: Put an archived page back in the tree (editor); it goes to the top level if its parent is gone or archived
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/Page" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/link-preview:
|
||||
get:
|
||||
operationId: previewLink
|
||||
tags: [pages]
|
||||
summary: 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.
|
||||
security: [{ bearer: [] }]
|
||||
parameters:
|
||||
- { name: url, in: query, required: true, schema: { type: string, maxLength: 2000 } }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/LinkPreview" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/pages/{id}/restore:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
@@ -2626,7 +2719,7 @@ components:
|
||||
Page:
|
||||
type: object
|
||||
required:
|
||||
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, ancestors, role, restricted, isTemplate, favorite]
|
||||
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite]
|
||||
properties:
|
||||
id: { type: string }
|
||||
workspace: { type: string }
|
||||
@@ -2638,6 +2731,8 @@ components:
|
||||
updated: { type: string }
|
||||
deletedAt: { type: string, description: When the page itself was trashed; empty otherwise }
|
||||
inTrash: { type: boolean, description: The page or one of its ancestors is in the trash }
|
||||
archivedAt: { type: string, description: When the page itself was archived; empty otherwise }
|
||||
archived: { type: boolean, description: The page or one of its ancestors is archived (read-only) }
|
||||
ancestors: { type: array, items: { $ref: "#/components/schemas/PageRef" }, description: Root first; pages the caller cannot open are left out }
|
||||
role: { $ref: "#/components/schemas/SpaceRole", description: The caller's role on this page }
|
||||
restricted: { type: boolean, description: The page or one of its ancestors is restricted }
|
||||
@@ -2712,6 +2807,23 @@ components:
|
||||
title: { type: string }
|
||||
icon: { type: string }
|
||||
deletedAt: { type: string }
|
||||
ArchivedPage:
|
||||
type: object
|
||||
required: [id, title, icon, archivedAt]
|
||||
properties:
|
||||
id: { type: string }
|
||||
title: { type: string }
|
||||
icon: { type: string }
|
||||
archivedAt: { type: string }
|
||||
LinkPreview:
|
||||
type: object
|
||||
required: [url, title, description, image, site]
|
||||
properties:
|
||||
url: { type: string }
|
||||
title: { type: string }
|
||||
description: { type: string }
|
||||
image: { type: string, description: Address of the page's picture on its own site; empty when it has none }
|
||||
site: { type: string }
|
||||
Session:
|
||||
type: object
|
||||
required: [token, user]
|
||||
@@ -2908,7 +3020,7 @@ components:
|
||||
page: { type: integer }
|
||||
WebhookEvent:
|
||||
type: string
|
||||
enum: ["*", page.created, page.updated, page.moved, page.trashed, page.restored, page.deleted, comment.created, comment.resolved, space.created, space.deleted]
|
||||
enum: ["*", 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:
|
||||
type: object
|
||||
required: [id, name, url, events, active, created]
|
||||
|
||||
Generated
+30
@@ -3477,6 +3477,21 @@
|
||||
"@tiptap/y-tiptap": "^3.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-details": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-details/-/extension-details-3.32.2.tgz",
|
||||
"integrity": "sha512-CqGZ7l9lhKZ+lAEzKGiiyThv2wqkrOM043Mn4vHBfCG3UUxENyg5KVwoeoziUIiPwffrAHxlilHdGzm4g6kdOQ==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.32.2",
|
||||
"@tiptap/extension-text-style": "3.32.2",
|
||||
"@tiptap/pm": "3.32.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-document": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-document/-/extension-document-3.32.2.tgz",
|
||||
@@ -3737,6 +3752,20 @@
|
||||
"@tiptap/core": "3.32.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-text-style": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-text-style/-/extension-text-style-3.32.2.tgz",
|
||||
"integrity": "sha512-7VHyvO8V7xCOj4BY56gqCylZXF972dtk+ngIIXT19nhBXYuQZKXGrN11xPrfMip/1nGsMWov9PZB2HleYJnXGQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/ueberdosis"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tiptap/core": "3.32.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@tiptap/extension-underline": {
|
||||
"version": "3.32.2",
|
||||
"resolved": "https://registry.npmjs.org/@tiptap/extension-underline/-/extension-underline-3.32.2.tgz",
|
||||
@@ -11181,6 +11210,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",
|
||||
|
||||
Reference in new issue
Block a user