Edit page content with the Docwell editor

PageView now mounts @docwell/editor and autosaves the document through
GET/PUT /api/v1/pages/{id}/content. The server stores Tiptap JSON in
pages.content_json and derives content_text and word_count itself.
Saves are last-write-wins until the collab relay replaces them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 11:24:36 +01:00
1 parent a96c6ad3ce
commit abf55a426b
13 files changed
+420 -9

No files matched your search

+5
View File
@@ -25,6 +25,7 @@ export type PageNode = Schemas["PageNode"];
export type PageRef = Schemas["PageRef"];
export type Page = Schemas["Page"];
export type TrashedPage = Schemas["TrashedPage"];
export type PageContent = Schemas["PageContent"];
export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility };
export type UpdateSpaceRequest = Partial<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
@@ -164,6 +165,10 @@ export function createClient(opts: ClientOptions) {
update: (id: string, patch: { title?: string; icon?: string }) =>
request<Page>("PATCH", `/api/v1/pages/${encodeURIComponent(id)}`, patch),
/** Moves a page under parent ("" = top level) at index among its other children. */
content: (id: string) => request<PageContent>("GET", `/api/v1/pages/${encodeURIComponent(id)}/content`),
/** Replaces the page's document; content is Tiptap JSON with type "doc". */
saveContent: (id: string, content: Record<string, unknown>) =>
request<PageContent>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/content`, { content }),
move: (id: string, parent: string, index: number) =>
post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/move`, { parent, index }),
trash: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}`),
+84
View File
@@ -540,6 +540,26 @@ export interface paths {
patch: operations["updatePage"];
trace?: never;
};
"/api/v1/pages/{id}/content": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The page's document as Tiptap JSON (null for a page that was never edited) */
get: operations["getPageContent"];
/** Replace the page's document (editor). Last write wins until the collab relay lands; the server derives the plain text and word count. */
put: operations["savePageContent"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/move": {
parameters: {
query?: never;
@@ -728,6 +748,13 @@ export interface components {
ancestors: components["schemas"]["PageRef"][];
role: components["schemas"]["SpaceRole"];
};
PageContent: {
/** @description Tiptap JSON with type "doc"; null for a page that was never edited */
content: {
[key: string]: unknown;
} | null;
updated: string;
};
TrashedPage: {
id: string;
title: string;
@@ -1864,6 +1891,63 @@ export interface operations {
404: components["responses"]["Error"];
};
};
getPageContent: {
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"]["PageContent"];
};
};
404: components["responses"]["Error"];
};
};
savePageContent: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description Tiptap JSON with type "doc" */
content: {
[key: string]: unknown;
};
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["PageContent"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
movePage: {
parameters: {
query?: never;
+2 -1
View File
@@ -7,7 +7,7 @@ import { docwellExtensions } from "./extensions";
const props = withDefaults(defineProps<{ content?: JSONContent; editable?: boolean; placeholder?: string }>(), {
editable: true,
});
const emit = defineEmits<{ update: [content: JSONContent] }>();
const emit = defineEmits<{ update: [content: JSONContent]; blur: [] }>();
const editor = useEditor({
content: props.content,
@@ -15,6 +15,7 @@ const editor = useEditor({
extensions: docwellExtensions({ placeholder: props.placeholder }),
editorProps: { attributes: { class: "dw-prose" } },
onUpdate: ({ editor }) => emit("update", editor.getJSON()),
onBlur: () => emit("blur"),
});
watch(
+1
View File
@@ -1,2 +1,3 @@
export { default as DocwellEditor } from "./DocwellEditor.vue";
export type { JSONContent } from "@tiptap/core";
export { docwellExtensions, type ExtensionOptions } from "./extensions";
+144
View File
@@ -0,0 +1,144 @@
package directory
import (
"context"
"encoding/json"
"strings"
"unicode"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Page content ------------------------------------------------------------
//
// Until the collab relay lands, a page body is saved whole as Tiptap JSON
// (pages.content_json), last write wins. The server derives content_text and
// word_count from it, so clients cannot make search text disagree with the
// document.
// maxContentBytes caps one saved document (the PocketBase field allows 20 MB).
const maxContentBytes = 8 << 20
type contentRecord struct {
ID string `json:"id"`
Space string `json:"space"`
ContentJSON json.RawMessage `json:"content_json"`
Updated string `json:"updated"`
}
// PageContent is a page's document as Tiptap JSON; Content is null for a page
// that was never edited.
type PageContent struct {
Content json.RawMessage `json:"content"`
Updated string `json:"updated"`
}
// GetPageContent returns a page's document (viewer).
func (s *Service) GetPageContent(ctx context.Context, c access.Caller, id string) (PageContent, error) {
p, _, err := s.pageFor(ctx, c, id)
if err != nil {
return PageContent{}, err
}
rec, err := pocketbase.Get[contentRecord](ctx, s.pb, "pages", p.ID)
if err != nil {
return PageContent{}, mapPB(err, "page not found")
}
return PageContent{Content: nullIfEmpty(rec.ContentJSON), Updated: rec.Updated}, nil
}
type SavePageContentInput struct {
Content json.RawMessage `json:"content"`
}
// SavePageContent replaces a page's document (editor).
func (s *Service) SavePageContent(ctx context.Context, c access.Caller, id string, in SavePageContentInput) (PageContent, error) {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return PageContent{}, err
}
if err := access.EditPages(a.role); err != nil {
return PageContent{}, err
}
if p.DeletedAt != "" {
return PageContent{}, apperr.Invalid("restore the page from the trash first")
}
if len(in.Content) > maxContentBytes {
return PageContent{}, apperr.InvalidFields(map[string]string{"content": "The page is too large to save."})
}
var doc docNode
if err := json.Unmarshal(in.Content, &doc); err != nil || doc.Type != "doc" {
return PageContent{}, apperr.InvalidFields(map[string]string{"content": "Content must be a Tiptap document."})
}
text := doc.plainText()
rec, err := pocketbase.Update[contentRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"content_json": in.Content, "content_text": text, "word_count": wordCount(text), "last_editor": c.ID,
})
if err != nil {
return PageContent{}, mapPB(err, "page not found")
}
return PageContent{Content: nullIfEmpty(rec.ContentJSON), Updated: rec.Updated}, nil
}
func nullIfEmpty(raw json.RawMessage) json.RawMessage {
if len(raw) == 0 || string(raw) == `""` {
return json.RawMessage("null")
}
return raw
}
// docNode is the part of a ProseMirror/Tiptap JSON node needed for text extraction.
type docNode struct {
Type string `json:"type"`
Text string `json:"text"`
Content []docNode `json:"content"`
}
// blockTypes end with a line break in the plain text; everything else is inline.
var blockTypes = map[string]bool{
"paragraph": true, "heading": true, "codeBlock": true, "blockquote": true,
"listItem": true, "taskItem": true, "horizontalRule": true, "tableRow": true,
}
// plainText flattens the document to text, one line per block.
func (n docNode) plainText() string {
var b strings.Builder
lineEnded := true
write := func(s string) {
if s != "" {
b.WriteString(s)
lineEnded = s[len(s)-1] == '\n'
}
}
var walk func(n docNode, depth int)
walk = func(n docNode, depth int) {
if depth > 200 {
return
}
switch n.Type {
case "text":
write(n.Text)
case "hardBreak":
write("\n")
case "tableCell", "tableHeader":
for _, c := range n.Content {
walk(c, depth+1)
}
write("\t")
return
}
for _, c := range n.Content {
walk(c, depth+1)
}
if blockTypes[n.Type] && !lineEnded {
write("\n")
}
}
walk(n, 0)
return strings.TrimSpace(b.String())
}
func wordCount(text string) int {
return len(strings.FieldsFunc(text, func(r rune) bool { return unicode.IsSpace(r) }))
}
+36
View File
@@ -0,0 +1,36 @@
package directory
import (
"encoding/json"
"testing"
)
func TestPlainText(t *testing.T) {
raw := `{"type":"doc","content":[
{"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"Release notes"}]},
{"type":"paragraph","content":[{"type":"text","text":"Fixed "},{"type":"text","marks":[{"type":"bold"}],"text":"two"},{"type":"text","text":" bugs."}]},
{"type":"bulletList","content":[
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"one"}]}]},
{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"line"},{"type":"hardBreak"},{"type":"text","text":"break"}]}]}
]},
{"type":"paragraph"}
]}`
var doc docNode
if err := json.Unmarshal([]byte(raw), &doc); err != nil {
t.Fatal(err)
}
got := doc.plainText()
want := "Release notes\nFixed two bugs.\none\nline\nbreak"
if got != want {
t.Fatalf("plainText = %q, want %q", got, want)
}
if n := wordCount(got); n != 8 {
t.Fatalf("wordCount = %d, want 8", n)
}
}
func TestPlainTextEmpty(t *testing.T) {
if got := (docNode{Type: "doc"}).plainText(); got != "" {
t.Fatalf("empty doc = %q", got)
}
}
+6 -1
View File
@@ -140,7 +140,12 @@ func (a *api) routes(mux *http.ServeMux) {
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
return a.decodeMax(w, r, v, 1<<20)
}
// decodeMax is decode with a larger body limit, for page content.
func (a *api) decodeMax(w http.ResponseWriter, r *http.Request, v any, limit int64) bool {
r.Body = http.MaxBytesReader(w, r.Body, limit)
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_json"})
return false
+14
View File
@@ -23,6 +23,8 @@ type SpaceService interface {
CreatePage(ctx context.Context, c access.Caller, spaceID string, in directory.CreatePageInput) (directory.Page, error)
GetPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
UpdatePage(ctx context.Context, c access.Caller, id string, in directory.UpdatePageInput) (directory.Page, error)
GetPageContent(ctx context.Context, c access.Caller, id string) (directory.PageContent, error)
SavePageContent(ctx context.Context, c access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error)
MovePage(ctx context.Context, c access.Caller, id string, in directory.MovePageInput) (directory.Page, error)
TrashPage(ctx context.Context, c access.Caller, id string) error
RestorePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
@@ -104,6 +106,18 @@ func (a *api) spaceRoutes(mux *http.ServeMux) {
p, err := a.dir.UpdatePage(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, p, err)
}))
mux.HandleFunc("GET /api/v1/pages/{id}/content", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
c, err := a.dir.GetPageContent(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, c, err)
}))
mux.HandleFunc("PUT /api/v1/pages/{id}/content", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.SavePageContentInput
if !a.decodeMax(w, r, &in, 10<<20) {
return
}
c, err := a.dir.SavePageContent(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, c, err)
}))
mux.HandleFunc("POST /api/v1/pages/{id}/move", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.MovePageInput
if !a.decode(w, r, &in) {
+7 -1
View File
@@ -29,6 +29,11 @@ func (p pageDir) MovePage(_ context.Context, _ access.Caller, id string, in dire
return directory.Page{ID: id, Parent: in.Parent}, nil
}
func (p pageDir) SavePageContent(_ context.Context, _ access.Caller, id string, in directory.SavePageContentInput) (directory.PageContent, error) {
*p.calls = append(*p.calls, "save "+id+" "+string(in.Content))
return directory.PageContent{Content: in.Content}, nil
}
func TestPageRoutes(t *testing.T) {
var calls []string
h := NewRouter(Deps{
@@ -40,12 +45,13 @@ func TestPageRoutes(t *testing.T) {
{"DELETE", "/api/v1/pages/p1", ""},
{"DELETE", "/api/v1/pages/p1?permanent=true", ""},
{"POST", "/api/v1/pages/p2/move", `{"parent":"p1","index":0}`},
{"PUT", "/api/v1/pages/p2/content", `{"content":{"type":"doc"}}`},
} {
if rec := send(h, req.method, req.path, "alice", req.body); rec.Code >= 300 {
t.Fatalf("%s %s = %d %s", req.method, req.path, rec.Code, rec.Body)
}
}
want := []string{"trash p1", "purge p1", "move p2 under p1"}
want := []string{"trash p1", "purge p1", "move p2 under p1", `save p2 {"type":"doc"}`}
if len(calls) != len(want) {
t.Fatalf("calls = %v", calls)
}
+6 -1
View File
@@ -194,7 +194,12 @@
"deleteForever": "Delete forever",
"confirmPurge": "Delete \"{title}\" and every page inside it for good?",
"readOnly": "You can read this page but not change it.",
"editorSoon": "Editing page content arrives with real-time collaboration.",
"placeholder": "Start writing…",
"save": {
"saving": "Saving…",
"saved": "Saved",
"failed": "Couldn't save. Your changes will be retried."
},
"notFound": "This page does not exist or you don't have access to it."
},
"trash": {
+6 -1
View File
@@ -194,7 +194,12 @@
"deleteForever": "Usuń na zawsze",
"confirmPurge": "Usunąć na zawsze „{title}” i wszystkie strony wewnątrz?",
"readOnly": "Możesz czytać tę stronę, ale nie możesz jej zmieniać.",
"editorSoon": "Edycja treści stron pojawi się razem ze współpracą w czasie rzeczywistym.",
"placeholder": "Zacznij pisać…",
"save": {
"saving": "Zapisywanie…",
"saved": "Zapisano",
"failed": "Nie udało się zapisać. Zmiany zostaną zapisane ponownie."
},
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu."
},
"trash": {
+61 -4
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import type { Page } from "@docwell/api-client";
import { DocwellEditor, type JSONContent } from "@docwell/editor";
import { DwBreadcrumbs, DwButton, DwCallout } from "@docwell/ui";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
@@ -21,6 +22,9 @@ 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 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) : []));
@@ -38,9 +42,12 @@ const crumbs = computed(() => {
async function load(id: string) {
notFound.value = false;
content.value = undefined;
saveState.value = "idle";
try {
const p = await api.pages.get(id);
const [p, c] = await Promise.all([api.pages.get(id), api.pages.content(id)]);
page.value = p;
content.value = (c.content as JSONContent | null) ?? null;
title.value = p.title;
spaces.active = { space: p.space, page: p.id };
// A link from another workspace switches the sidebar to it.
@@ -72,15 +79,52 @@ 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 saveTitle();
if (old) await Promise.all([saveTitle(), saveContent()]);
await load(id);
},
{ immediate: true },
);
onBeforeUnmount(saveTitle);
window.addEventListener("beforeunload", warnUnsaved);
onBeforeUnmount(() => {
window.removeEventListener("beforeunload", warnUnsaved);
saveTitle();
saveContent();
});
async function run(action: () => Promise<unknown>) {
busy.value = true;
@@ -152,8 +196,21 @@ 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>
<DwCallout class="mt-8" size="ui">{{ $t("page.editorSoon") }}</DwCallout>
<DocwellEditor
v-if="content !== undefined"
:key="page.id"
:content="content ?? undefined"
:editable="editable"
:placeholder="editable ? $t('page.placeholder') : ''"
class="mt-6"
data-testid="page-editor"
@update="onContentUpdate"
@blur="saveContent"
/>
<!-- A trashed page's children are hidden with it; they come back on restore. -->
<section v-if="!page.inTrash" class="mt-10">
+48
View File
@@ -711,6 +711,46 @@ paths:
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/content:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getPageContent
tags: [pages]
summary: The page's document as Tiptap JSON (null for a page that was never edited)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/PageContent" }
"404": { $ref: "#/components/responses/Error" }
put:
operationId: savePageContent
tags: [pages]
summary: >-
Replace the page's document (editor). Last write wins until the collab
relay lands; the server derives the plain text and word count.
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [content]
properties:
content: { type: object, additionalProperties: true, description: 'Tiptap JSON with type "doc"' }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/PageContent" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/move:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
@@ -936,6 +976,14 @@ components:
inTrash: { type: boolean, description: The page or one of its ancestors is in the trash }
ancestors: { type: array, items: { $ref: "#/components/schemas/PageRef" }, description: Root first }
role: { $ref: "#/components/schemas/SpaceRole" }
PageContent:
type: object
required: [content, updated]
properties:
content:
oneOf: [{ type: object, additionalProperties: true }, { type: "null" }]
description: Tiptap JSON with type "doc"; null for a page that was never edited
updated: { type: string }
TrashedPage:
type: object
required: [id, title, icon, deletedAt]