Add real-time collaboration with page history
Pages are now shared Yjs documents. docwell-server relays the y-websocket protocol at /collab (token sent as the first message), flushes updates to page_yupdates every second, and compacts them into page_ydoc with yrs compiled to WebAssembly under wazero (ADR-3) after 30 s idle or when the last editor leaves. Compaction refreshes content_json/content_text and records page_versions; versions can be listed, previewed and restored. The editor connects through a small y-protocols provider with carets and presence. Pages saved before this change are seeded from content_json. The yrs module lives in Server/ycrdt-wasm and is built by go generate, CI and the Dockerfiles rather than committed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
abf55a426b
commit
5e1dcf4291
45 files changed
+3480
-213
No files matched your search
@@ -2,7 +2,13 @@ import type { DocwellClient } from "@docwell/api-client";
|
||||
import { inject, type InjectionKey } from "vue";
|
||||
|
||||
export const apiKey: InjectionKey<DocwellClient> = Symbol("api");
|
||||
/** Reads the current session token (for the collab WebSocket, which cannot use the client). */
|
||||
export const tokenKey: InjectionKey<() => string | null> = Symbol("token");
|
||||
|
||||
export function useApi(): DocwellClient {
|
||||
return inject(apiKey)!;
|
||||
}
|
||||
|
||||
export function useToken(): () => string | null {
|
||||
return inject(tokenKey)!;
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { createClient, createTokenStore } from "@docwell/api-client";
|
||||
import { createPinia } from "pinia";
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import { apiKey } from "./api";
|
||||
import { apiKey, tokenKey } from "./api";
|
||||
import { createDocwellI18n } from "./i18n";
|
||||
import { configKey, platformKey, type Platform } from "./platform";
|
||||
import { createDocwellRouter } from "./router";
|
||||
@@ -37,6 +37,7 @@ export async function createDocwellApp(platform: Platform, el: string | Element
|
||||
app.provide(platformKey, platform);
|
||||
app.provide(configKey, config);
|
||||
app.provide(apiKey, api);
|
||||
app.provide(tokenKey, tokens.get);
|
||||
app.use(createDocwellI18n());
|
||||
app.use(router);
|
||||
app.mount(el);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
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 { useI18n } from "vue-i18n";
|
||||
import { useApi } from "../api";
|
||||
|
||||
// The page's saved versions, with a read-only preview 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] }>();
|
||||
const api = useApi();
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
const versions = ref<PageVersion[] | null>(null);
|
||||
const selected = ref<PageVersion | null>(null);
|
||||
const preview = ref<JSONContent | null>(null);
|
||||
const busy = ref(false);
|
||||
|
||||
async function load() {
|
||||
selected.value = null;
|
||||
preview.value = null;
|
||||
try {
|
||||
versions.value = await api.pages.versions(props.page.id);
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
watch(() => props.page.id, load, { immediate: true });
|
||||
|
||||
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: [] };
|
||||
} catch (e) {
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function restore() {
|
||||
const v = selected.value;
|
||||
if (!v || !confirm(t("page.history.confirmRestore", { date: when(v.created) }))) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await api.pages.restoreVersion(props.page.id, v.id);
|
||||
emit("close");
|
||||
} 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>
|
||||
<section class="rounded-md border border-line p-4" data-testid="page-history" :aria-label="$t('page.history.title')">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<h2 class="dw-label">{{ $t("page.history.title") }}</h2>
|
||||
<DwButton variant="ghost" size="sm" @click="emit('close')">{{ $t("page.history.close") }}</DwButton>
|
||||
</div>
|
||||
|
||||
<p v-if="versions && !versions.length" class="mt-3 flex items-center gap-2 text-ui-md text-ink-muted">
|
||||
<DwIcon name="drop" :size="18" class="text-spring" />
|
||||
{{ $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')">
|
||||
<li v-for="v in versions" :key="v.id">
|
||||
<button
|
||||
type="button"
|
||||
role="option"
|
||||
:aria-selected="selected?.id === v.id"
|
||||
class="w-full rounded-sm px-2 py-1.5 text-left text-ui-md hover:bg-surface-hover"
|
||||
:class="{ 'bg-surface-hover font-semibold': selected?.id === v.id }"
|
||||
@click="select(v)"
|
||||
>
|
||||
<span class="block">{{ when(v.created) }}</span>
|
||||
<span v-if="v.author" class="block text-ui-sm text-ink-muted">{{ v.author }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<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>
|
||||
<DwButton v-if="canRestore" class="mt-3" size="sm" icon="restore" :disabled="busy || !preview" @click="restore">
|
||||
{{ $t("page.history.restore") }}
|
||||
</DwButton>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -195,10 +195,20 @@
|
||||
"confirmPurge": "Delete \"{title}\" and every page inside it for good?",
|
||||
"readOnly": "You can read this page but not change it.",
|
||||
"placeholder": "Start writing…",
|
||||
"save": {
|
||||
"saving": "Saving…",
|
||||
"saved": "Saved",
|
||||
"failed": "Couldn't save. Your changes will be retried."
|
||||
"someone": "Someone",
|
||||
"collab": {
|
||||
"connecting": "Connecting…",
|
||||
"offline": "Offline. Your changes will sync when the connection is back.",
|
||||
"denied": "This page can't be opened for editing. Try signing in again.",
|
||||
"alsoHere": "Also here:"
|
||||
},
|
||||
"history": {
|
||||
"title": "History",
|
||||
"close": "Close",
|
||||
"empty": "No versions yet. One is saved every few minutes while people edit.",
|
||||
"pick": "Pick a version to see it.",
|
||||
"restore": "Restore this version",
|
||||
"confirmRestore": "Replace the page with the version from {date}? The current text stays in the history."
|
||||
},
|
||||
"notFound": "This page does not exist or you don't have access to it."
|
||||
},
|
||||
|
||||
@@ -195,10 +195,20 @@
|
||||
"confirmPurge": "Usunąć na zawsze „{title}” i wszystkie strony wewnątrz?",
|
||||
"readOnly": "Możesz czytać tę stronę, ale nie możesz jej zmieniać.",
|
||||
"placeholder": "Zacznij pisać…",
|
||||
"save": {
|
||||
"saving": "Zapisywanie…",
|
||||
"saved": "Zapisano",
|
||||
"failed": "Nie udało się zapisać. Zmiany zostaną zapisane ponownie."
|
||||
"someone": "Ktoś",
|
||||
"collab": {
|
||||
"connecting": "Łączenie…",
|
||||
"offline": "Brak połączenia. Zmiany zsynchronizują się po jego przywróceniu.",
|
||||
"denied": "Nie można otworzyć tej strony do edycji. Spróbuj zalogować się ponownie.",
|
||||
"alsoHere": "Na stronie są też:"
|
||||
},
|
||||
"history": {
|
||||
"title": "Historia",
|
||||
"close": "Zamknij",
|
||||
"empty": "Brak wersji. Nowa wersja zapisuje się co kilka minut podczas edycji.",
|
||||
"pick": "Wybierz wersję, aby ją zobaczyć.",
|
||||
"restore": "Przywróć tę wersję",
|
||||
"confirmRestore": "Zastąpić stronę wersją z {date}? Obecny tekst zostanie w historii."
|
||||
},
|
||||
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu."
|
||||
},
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import type { Page } from "@docwell/api-client";
|
||||
import { DocwellEditor, type JSONContent } from "@docwell/editor";
|
||||
import { CollabProvider, DocwellEditor, userColor } from "@docwell/editor";
|
||||
import { DwBreadcrumbs, DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { computed, onBeforeUnmount, ref, shallowRef, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { useApi } from "../../api";
|
||||
import { useApi, useToken } from "../../api";
|
||||
import PageHistory from "../../components/PageHistory.vue";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import { useRuntimeConfig } from "../../platform";
|
||||
import { useAuthStore } from "../../stores/auth";
|
||||
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
|
||||
import { useWorkspacesStore } from "../../stores/workspaces";
|
||||
|
||||
@@ -17,14 +20,51 @@ const spaces = useSpacesStore();
|
||||
const workspaces = useWorkspacesStore();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
const config = useRuntimeConfig();
|
||||
const token = useToken();
|
||||
|
||||
const page = ref<Page | null>(null);
|
||||
const notFound = ref(false);
|
||||
const title = ref("");
|
||||
const busy = ref(false);
|
||||
// undefined until loaded; null for a page that was never edited.
|
||||
const content = ref<JSONContent | null | undefined>(undefined);
|
||||
const saveState = ref<"idle" | "saving" | "saved" | "failed">("idle");
|
||||
const historyOpen = ref(false);
|
||||
|
||||
// The page body is a shared Yjs document; edits sync live and the server saves them.
|
||||
const provider = shallowRef<CollabProvider | null>(null);
|
||||
const collabStatus = ref<CollabProvider["status"]>("connecting");
|
||||
const synced = ref(false);
|
||||
const others = ref<{ name: string; color: string }[]>([]);
|
||||
const me = computed(() => ({
|
||||
name: auth.user?.name || auth.user?.email || t("page.someone"),
|
||||
color: userColor(auth.user?.id ?? ""),
|
||||
}));
|
||||
|
||||
function collabUrl() {
|
||||
if (config.collabUrl) return config.collabUrl;
|
||||
return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/collab`;
|
||||
}
|
||||
|
||||
function openDoc(id: string) {
|
||||
closeDoc();
|
||||
const p = new CollabProvider({ url: collabUrl(), page: id, token });
|
||||
const refresh = () => {
|
||||
collabStatus.value = p.status;
|
||||
synced.value = p.synced;
|
||||
others.value = [...p.awareness.getStates()]
|
||||
.filter(([client, s]) => client !== p.doc.clientID && s.user)
|
||||
.map(([, s]) => s.user as { name: string; color: string });
|
||||
};
|
||||
p.onChange(refresh);
|
||||
p.awareness.on("change", refresh);
|
||||
refresh();
|
||||
provider.value = p;
|
||||
}
|
||||
|
||||
function closeDoc() {
|
||||
provider.value?.destroy();
|
||||
provider.value = null;
|
||||
}
|
||||
|
||||
const editable = computed(() => !!page.value && !page.value.inTrash && spaceAtLeast(page.value.role, "editor"));
|
||||
const children = computed(() => (page.value ? spaces.childrenOf(page.value.space, page.value.id) : []));
|
||||
@@ -42,12 +82,10 @@ const crumbs = computed(() => {
|
||||
|
||||
async function load(id: string) {
|
||||
notFound.value = false;
|
||||
content.value = undefined;
|
||||
saveState.value = "idle";
|
||||
try {
|
||||
const [p, c] = await Promise.all([api.pages.get(id), api.pages.content(id)]);
|
||||
const p = await api.pages.get(id);
|
||||
page.value = p;
|
||||
content.value = (c.content as JSONContent | null) ?? null;
|
||||
if (!provider.value) openDoc(id);
|
||||
title.value = p.title;
|
||||
spaces.active = { space: p.space, page: p.id };
|
||||
// A link from another workspace switches the sidebar to it.
|
||||
@@ -56,6 +94,7 @@ async function load(id: string) {
|
||||
} catch {
|
||||
page.value = null;
|
||||
notFound.value = true;
|
||||
closeDoc();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,51 +118,21 @@ function onTitleInput() {
|
||||
timer = setTimeout(saveTitle, 600);
|
||||
}
|
||||
|
||||
// Content saves the same way, a little later, until the collab relay replaces it.
|
||||
let pending: { id: string; doc: JSONContent } | null = null;
|
||||
let contentTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
async function saveContent() {
|
||||
clearTimeout(contentTimer);
|
||||
const next = pending;
|
||||
if (!next) return;
|
||||
pending = null;
|
||||
saveState.value = "saving";
|
||||
try {
|
||||
await api.pages.saveContent(next.id, next.doc);
|
||||
if (!pending && page.value?.id === next.id) saveState.value = "saved";
|
||||
} catch (e) {
|
||||
// Keep the edit so the next change or blur retries it.
|
||||
pending ??= next;
|
||||
if (page.value?.id === next.id) saveState.value = "failed";
|
||||
emit("error", e);
|
||||
}
|
||||
}
|
||||
function onContentUpdate(doc: JSONContent) {
|
||||
if (!page.value || !editable.value) return;
|
||||
pending = { id: page.value.id, doc };
|
||||
saveState.value = "saving";
|
||||
clearTimeout(contentTimer);
|
||||
contentTimer = setTimeout(saveContent, 1000);
|
||||
}
|
||||
function warnUnsaved(e: BeforeUnloadEvent) {
|
||||
if (!pending) return;
|
||||
saveContent();
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.id,
|
||||
async (id, old) => {
|
||||
if (old) await Promise.all([saveTitle(), saveContent()]);
|
||||
if (old) {
|
||||
await saveTitle();
|
||||
closeDoc();
|
||||
historyOpen.value = false;
|
||||
}
|
||||
await load(id);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
window.addEventListener("beforeunload", warnUnsaved);
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener("beforeunload", warnUnsaved);
|
||||
saveTitle();
|
||||
saveContent();
|
||||
closeDoc();
|
||||
});
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
@@ -196,20 +205,33 @@ const purge = () =>
|
||||
@keydown.enter.prevent="($event.target as HTMLInputElement).blur()"
|
||||
/>
|
||||
<p v-if="!spaceAtLeast(page.role, 'editor')" class="mt-2 text-ui-sm text-ink-muted">{{ $t("page.readOnly") }}</p>
|
||||
<p v-else-if="saveState !== 'idle'" class="mt-2 text-ui-sm" :class="saveState === 'failed' ? 'text-danger' : 'text-ink-muted'" role="status" data-testid="save-state">
|
||||
{{ $t(`page.save.${saveState}`) }}
|
||||
</p>
|
||||
|
||||
<div class="mt-3 flex min-h-6 flex-wrap items-center justify-between gap-2 text-ui-sm text-ink-muted">
|
||||
<p role="status" data-testid="collab-status" :class="{ 'text-danger': collabStatus === 'denied' }">
|
||||
<template v-if="collabStatus === 'denied'">{{ $t("page.collab.denied") }}</template>
|
||||
<template v-else-if="collabStatus === 'offline'">{{ $t("page.collab.offline") }}</template>
|
||||
<template v-else-if="!synced">{{ $t("page.collab.connecting") }}</template>
|
||||
<template v-else-if="others.length">
|
||||
{{ $t("page.collab.alsoHere") }}
|
||||
<span v-for="o in others" :key="o.name + o.color" class="ml-1 font-semibold" :style="{ color: o.color }">{{ o.name }}</span>
|
||||
</template>
|
||||
</p>
|
||||
<DwButton variant="ghost" size="sm" icon="restore" data-testid="history-toggle" @click="historyOpen = !historyOpen">
|
||||
{{ $t("page.history.title") }}
|
||||
</DwButton>
|
||||
</div>
|
||||
|
||||
<PageHistory v-if="historyOpen" :page="page" :can-restore="editable" class="mt-4" @close="historyOpen = false" @error="emit('error', $event)" />
|
||||
|
||||
<DocwellEditor
|
||||
v-if="content !== undefined"
|
||||
v-if="provider && synced"
|
||||
:key="page.id"
|
||||
:content="content ?? undefined"
|
||||
:provider="provider"
|
||||
:user="me"
|
||||
:editable="editable"
|
||||
:placeholder="editable ? $t('page.placeholder') : ''"
|
||||
class="mt-6"
|
||||
class="mt-4"
|
||||
data-testid="page-editor"
|
||||
@update="onContentUpdate"
|
||||
@blur="saveContent"
|
||||
/>
|
||||
|
||||
<!-- A trashed page's children are hidden with it; they come back on restore. -->
|
||||
|
||||
Reference in new issue
Block a user