Add spaces, the page tree and the Docwell design system

Spaces and pages:
- Spaces inside workspaces, open or private, with admin/editor/commenter/viewer
  roles that cascade from the workspace role (rules in internal/access)
- Page tree per space with fractional position keys, move with cycle checks,
  trash that hides whole subtrees, restore and permanent delete
- OpenAPI, TypeScript client, and web app sidebar tree with drag-and-drop,
  page, space, trash and space settings views (EN + PL)

Design system:
- Tokens, type scale, radii and shadows from the design kit in
  @docwell/ui/theme.css; Inter, Source Serif 4 and JetBrains Mono bundled
- Vue ports of Button, TextField, Badge, Callout, Icon, Breadcrumbs,
  SlashMenu and PageTreeItem, plus Logo; favicons and web manifest
- Web app and admin panel restyled on the new tokens, in light and dark

Also: fix the Vite dev server crashing on /config.json, and stop tracking
the local Design/ and docs/ folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 11:14:31 +01:00
1 parent 4cb313aa95
commit a96c6ad3ce
92 files changed
+5055 -892

No files matched your search

+4
View File
@@ -30,3 +30,7 @@ pb_data/
# Go
coverage.out
# Local design kit and planning docs (not part of the build)
/Design/
/docs/
-5
View File
@@ -1,5 +0,0 @@
# Design
Logos, icons, mockups and other design assets for Docwell.
The UI design tokens (colors, fonts, dark mode) live in code at `Packages/ui/src/theme.css`. Keep that file and the assets here in sync.
+42
View File
@@ -16,6 +16,17 @@ export type Workspace = Schemas["Workspace"];
export type WorkspaceMember = Schemas["WorkspaceMember"];
export type CreateUserRequest = Schemas["CreateUserRequest"];
export type UpdateUserRequest = Schemas["UpdateUserRequest"];
export type SpaceRole = Schemas["SpaceRole"];
export type SpaceDefaultRole = Schemas["SpaceDefaultRole"];
export type SpaceVisibility = Schemas["SpaceVisibility"];
export type Space = Schemas["Space"];
export type SpaceMember = Schemas["SpaceMember"];
export type PageNode = Schemas["PageNode"];
export type PageRef = Schemas["PageRef"];
export type Page = Schemas["Page"];
export type TrashedPage = Schemas["TrashedPage"];
export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility };
export type UpdateSpaceRequest = Partial<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
/** Admins manage their own organization; superadmins manage everything. */
export function isManager(user: Pick<User, "role"> | null | undefined): boolean {
@@ -127,6 +138,37 @@ export function createClient(opts: ClientOptions) {
request<WorkspaceMember>("PUT", `/api/v1/workspaces/${encodeURIComponent(id)}/members`, { email, role }),
removeMember: (id: string, userId: string) =>
request<void>("DELETE", `/api/v1/workspaces/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`),
spaces: (id: string) => request<Space[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/spaces`),
createSpace: (id: string, input: CreateSpaceRequest) =>
post<Space>(`/api/v1/workspaces/${encodeURIComponent(id)}/spaces`, input),
},
spaces: {
get: (id: string) => request<Space>("GET", `/api/v1/spaces/${encodeURIComponent(id)}`),
update: (id: string, patch: UpdateSpaceRequest) =>
request<Space>("PATCH", `/api/v1/spaces/${encodeURIComponent(id)}`, patch),
remove: (id: string) => request<void>("DELETE", `/api/v1/spaces/${encodeURIComponent(id)}`),
members: (id: string) => request<SpaceMember[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/members`),
setMember: (id: string, email: string, role: SpaceRole) =>
request<SpaceMember>("PUT", `/api/v1/spaces/${encodeURIComponent(id)}/members`, { email, role }),
removeMember: (id: string, userId: string) =>
request<void>("DELETE", `/api/v1/spaces/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`),
pages: (id: string) => request<PageNode[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/pages`),
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`),
},
pages: {
get: (id: string) => request<Page>("GET", `/api/v1/pages/${encodeURIComponent(id)}`),
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. */
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)}`),
restore: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
purge: (id: string) => request<void>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}?permanent=true`),
},
};
}
+684
View File
@@ -399,6 +399,185 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/spaces": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** Spaces of a workspace the caller can open, with their effective space role */
get: operations["listSpaces"];
put?: never;
/** Create a space (workspace admin or above) */
post: operations["createSpace"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** One space with the caller's space role */
get: operations["getSpace"];
put?: never;
post?: never;
/** Delete a space with all of its pages (workspace admin or above) */
delete: operations["deleteSpace"];
options?: never;
head?: never;
/** Change a space's settings (space admin); only the fields sent change */
patch: operations["updateSpace"];
trace?: never;
};
"/api/v1/spaces/{id}/members": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** Explicit space members (workspace admins manage every space without being listed) */
get: operations["listSpaceMembers"];
/** Add a workspace member to the space or change their role (space admin) */
put: operations["setSpaceMember"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}/members/{userId}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
userId: string;
};
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/** Remove a space member (space admin; anyone may leave) */
delete: operations["removeSpaceMember"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}/pages": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The space's live page tree as a flat list in depth-first order, siblings sorted by position. Pages in the trash, and everything under them, are left out. */
get: operations["listPages"];
put?: never;
/** Create a page (editor) */
post: operations["createPage"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}/trash": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** Trashed pages, newest first (pages inside a trashed page come back with it) */
get: operations["listTrash"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** One page with its breadcrumbs and the caller's space role */
get: operations["getPage"];
put?: never;
post?: never;
/** Move a page and its subtree to the trash (editor). With permanent=true, delete a page that is already in the trash for good (space admin). */
delete: operations["deletePage"];
options?: never;
head?: never;
/** Rename a page or change its icon (editor) */
patch: operations["updatePage"];
trace?: never;
};
"/api/v1/pages/{id}/move": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
/** Move a page with its subtree within its space (editor) */
post: operations["movePage"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/restore": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
/** Take a page out of the trash (editor); it goes to the top level if its parent is gone */
post: operations["restorePage"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -485,6 +664,76 @@ export interface components {
};
role: components["schemas"]["WorkspaceRole"];
};
/** @enum {string} */
SpaceRole: "admin" | "editor" | "commenter" | "viewer";
/**
* @description Role that workspace members (not guests) get in an open space without an explicit role.
* @enum {string}
*/
SpaceDefaultRole: "editor" | "commenter" | "viewer";
/**
* @description open - every workspace member gets the default role; private - explicit members only.
* @enum {string}
*/
SpaceVisibility: "open" | "private";
Space: {
id: string;
workspace: string;
name: string;
slug: string;
icon: string;
description: string;
visibility: components["schemas"]["SpaceVisibility"];
defaultRole: components["schemas"]["SpaceDefaultRole"];
role: components["schemas"]["SpaceRole"];
created: string;
};
SpaceMember: {
user: {
id: string;
email: string;
name: string;
};
role: components["schemas"]["SpaceRole"];
};
PageNode: {
id: string;
/** @description Parent page id; empty at the top level */
parent: string;
title: string;
icon: string;
/** @description Fractional sort key among siblings */
position: string;
updated: string;
};
PageRef: {
id: string;
title: string;
icon: string;
};
Page: {
id: string;
workspace: string;
space: string;
parent: string;
title: string;
icon: string;
created: string;
updated: string;
/** @description When the page itself was trashed; empty otherwise */
deletedAt: string;
/** @description The page or one of its ancestors is in the trash */
inTrash: boolean;
/** @description Root first */
ancestors: components["schemas"]["PageRef"][];
role: components["schemas"]["SpaceRole"];
};
TrashedPage: {
id: string;
title: string;
icon: string;
deletedAt: string;
};
Session: {
token: string;
user: components["schemas"]["User"];
@@ -1238,4 +1487,439 @@ export interface operations {
404: components["responses"]["Error"];
};
};
listSpaces: {
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"]["Space"][];
};
};
404: components["responses"]["Error"];
};
};
createSpace: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
name: string;
description?: string;
icon?: string;
visibility?: components["schemas"]["SpaceVisibility"];
};
};
};
responses: {
/** @description Created */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Space"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
getSpace: {
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"]["Space"];
};
};
404: components["responses"]["Error"];
};
};
deleteSpace: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Deleted */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
updateSpace: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
name?: string;
description?: string;
icon?: string;
visibility?: components["schemas"]["SpaceVisibility"];
defaultRole?: components["schemas"]["SpaceDefaultRole"];
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Space"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
listSpaceMembers: {
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"]["SpaceMember"][];
};
};
404: components["responses"]["Error"];
};
};
setSpaceMember: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** Format: email */
email: string;
role: components["schemas"]["SpaceRole"];
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["SpaceMember"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
removeSpaceMember: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
userId: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Removed */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
listPages: {
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"]["PageNode"][];
};
};
404: components["responses"]["Error"];
};
};
createPage: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description Parent page id; empty or missing for the top level */
parent?: string;
title?: string;
/** @description Position among the parent's children; missing appends */
index?: number;
};
};
};
responses: {
/** @description Created */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Page"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
listTrash: {
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"]["TrashedPage"][];
};
};
404: components["responses"]["Error"];
};
};
getPage: {
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"];
};
};
404: components["responses"]["Error"];
};
};
deletePage: {
parameters: {
query?: {
permanent?: boolean;
};
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Deleted */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
updatePage: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
title?: string;
icon?: string;
};
};
};
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"];
};
};
movePage: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description New parent page id; empty for the top level */
parent?: string;
/** @description Position among the new parent's other children */
index: number;
};
};
};
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"];
};
};
restorePage: {
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"];
};
};
}
+28 -13
View File
@@ -1,25 +1,40 @@
/* Base document styles for the Docwell editor. Uses tokens from @docwell/ui/theme.css. */
/* Document styles for the Docwell editor, from the design system's Document
type scale. Uses tokens from @docwell/ui/theme.css. */
.dw-prose {
outline: none;
line-height: 1.7;
font-family: var(--font-sans);
font-size: var(--text-doc-body);
line-height: var(--text-doc-body--line-height);
color: var(--color-ink);
min-height: 12rem;
}
.dw-prose > * + * { margin-top: 0.75em; }
.dw-prose h1 { font-size: 2rem; font-weight: 700; line-height: 1.25; margin-top: 1.5em; }
.dw-prose h2 { font-size: 1.5rem; font-weight: 650; line-height: 1.3; margin-top: 1.4em; }
.dw-prose h3 { font-size: 1.2rem; font-weight: 600; margin-top: 1.2em; }
/* Paragraph blocks sit space-2 apart; a heading gets space-5 above it. */
.dw-prose > * + * { margin-top: 8px; }
.dw-prose > :is(h1, h2, h3) { margin-top: 20px; }
.dw-prose h1 { font-family: var(--font-serif); font-size: var(--text-doc-h1); line-height: var(--text-doc-h1--line-height); font-weight: 600; }
.dw-prose h2 { font-family: var(--font-serif); font-size: var(--text-doc-h2); line-height: var(--text-doc-h2--line-height); font-weight: 600; }
.dw-prose h3 { font-size: var(--text-doc-h3); line-height: var(--text-doc-h3--line-height); font-weight: 600; }
.dw-prose ul { list-style: disc; padding-left: 1.5rem; }
.dw-prose ol { list-style: decimal; padding-left: 1.5rem; }
.dw-prose a { color: var(--color-brand-600); text-decoration: underline; }
.dw-prose blockquote { border-left: 3px solid var(--color-border); padding-left: 1rem; color: var(--color-fg-muted); }
.dw-prose code { font-family: var(--font-mono); font-size: 0.875em; background: var(--color-surface-muted); padding: 0.1em 0.3em; border-radius: 4px; }
.dw-prose pre { font-family: var(--font-mono); background: var(--color-surface-muted); padding: 0.75rem 1rem; border-radius: 6px; overflow-x: auto; }
.dw-prose pre code { background: none; padding: 0; }
.dw-prose hr { border: none; border-top: 1px solid var(--color-border); margin: 1.5em 0; }
.dw-prose a { color: var(--color-accent); text-decoration: underline; text-underline-offset: 2px; }
.dw-prose blockquote { border-left: 3px solid var(--color-line); padding-left: 1rem; color: var(--color-ink-muted); }
.dw-prose code { font-family: var(--font-mono); font-size: 0.9em; background: var(--color-code-bg); padding: 0.1em 0.3em; border-radius: var(--radius-xs); }
.dw-prose pre {
font-family: var(--font-mono);
font-size: var(--text-code);
line-height: var(--text-code--line-height);
background: var(--color-code-bg);
padding: 12px 16px;
border-radius: var(--radius-md);
overflow-x: auto;
}
.dw-prose pre code { background: none; padding: 0; font-size: inherit; }
.dw-prose hr { border: none; border-top: 1px solid var(--color-line); margin: 24px 0; }
.dw-prose ::selection { background: var(--color-selection); }
.dw-prose p.is-editor-empty:first-child::before {
content: attr(data-placeholder);
color: var(--color-fg-muted);
color: var(--color-ink-faint);
float: left;
height: 0;
pointer-events: none;
+5
View File
@@ -3,3 +3,8 @@ declare module "*.vue" {
const component: DefineComponent<object, object, unknown>;
export default component;
}
declare module "*.svg" {
const url: string;
export default url;
}
+5
View File
@@ -11,5 +11,10 @@
},
"peerDependencies": {
"vue": "^3.5.0"
},
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/source-serif-4": "^5.3.1"
}
}
+22
View File
@@ -0,0 +1,22 @@
<script setup lang="ts">
// A one- or two-word status. The word carries the meaning, never the color alone.
withDefaults(defineProps<{ tone?: "neutral" | "accent" | "success" | "warning" | "danger" | "info" }>(), {
tone: "neutral",
});
</script>
<template>
<span
class="inline-flex h-5 items-center rounded-xs px-1.5 text-ui-xs whitespace-nowrap"
:class="{
'bg-surface-hover text-ink-muted': tone === 'neutral',
'bg-accent-soft text-accent': tone === 'accent',
'bg-success-soft text-success': tone === 'success',
'bg-warning-soft text-warning': tone === 'warning',
'bg-danger-soft text-danger': tone === 'danger',
'bg-info-soft text-info': tone === 'info',
}"
>
<slot />
</span>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts" generic="Target">
import { computed } from "vue";
// The path from the root to the current page, root first. The last item is the
// current page and is not a link. More than four items collapse the middle into "…".
const props = defineProps<{ items: { label: string; to?: Target }[]; label?: string }>();
const shown = computed(() => {
const items = props.items;
if (items.length <= 4) return items;
return [items[0]!, { label: "…" }, ...items.slice(-2)];
});
</script>
<template>
<nav :aria-label="label ?? 'Breadcrumb'">
<ol class="flex flex-wrap items-center gap-1 text-ui-sm">
<li v-for="(it, i) in shown" :key="i" class="inline-flex min-w-0 items-center gap-1 text-ink-muted">
<span v-if="i === shown.length - 1" aria-current="page" class="max-w-64 truncate px-1 py-0.5 font-medium text-ink">
{{ it.label }}
</span>
<RouterLink
v-else-if="it.to"
:to="it.to"
class="max-w-48 truncate rounded-xs px-1 py-0.5 hover:bg-surface-hover hover:text-ink"
>
{{ it.label }}
</RouterLink>
<span v-else class="px-1 py-0.5">{{ it.label }}</span>
<span v-if="i < shown.length - 1" class="text-ink-faint" aria-hidden="true">/</span>
</li>
</ol>
</nav>
</template>
+28 -10
View File
@@ -1,20 +1,38 @@
<script setup lang="ts">
withDefaults(defineProps<{ variant?: "primary" | "secondary" | "ghost"; type?: "button" | "submit" }>(), {
variant: "primary",
type: "button",
});
import DwIcon from "./DwIcon.vue";
import type { IconName } from "./icons";
// One primary button per view, for the thing the view is for. Secondary is the
// default; ghost is for toolbars, headers and rows; danger only confirms
// something that cannot be undone. With an icon and no label it renders square:
// pass aria-label.
withDefaults(
defineProps<{
variant?: "primary" | "secondary" | "ghost" | "danger";
size?: "sm" | "md";
icon?: IconName;
type?: "button" | "submit";
}>(),
{ variant: "secondary", size: "md", type: "button" },
);
</script>
<template>
<button
:type="type"
class="inline-flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 disabled:opacity-50"
:class="{
'bg-brand-600 text-white hover:bg-brand-700': variant === 'primary',
'border border-border bg-surface hover:bg-surface-muted': variant === 'secondary',
'hover:bg-surface-muted': variant === 'ghost',
}"
class="inline-flex shrink-0 cursor-pointer items-center justify-center rounded-sm border font-semibold whitespace-nowrap transition-colors duration-[120ms] disabled:cursor-not-allowed disabled:opacity-50"
:class="[
size === 'sm' ? 'h-control-sm gap-1 text-ui-sm' : 'h-control-md gap-2 text-ui-md',
icon && !$slots.default ? (size === 'sm' ? 'w-control-sm' : 'w-control-md') : size === 'sm' ? 'px-2' : 'px-3',
{
'border-transparent bg-primary text-on-primary enabled:hover:bg-primary-hover': variant === 'primary',
'border-line-strong bg-surface-raised text-ink enabled:hover:bg-surface-hover': variant === 'secondary',
'border-transparent bg-transparent text-ink-muted enabled:hover:bg-surface-hover enabled:hover:text-ink': variant === 'ghost',
'border-transparent bg-danger text-on-danger': variant === 'danger',
},
]"
>
<DwIcon v-if="icon" :name="icon" :size="size === 'sm' ? 16 : 18" />
<slot />
</button>
</template>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { computed } from "vue";
import DwIcon from "./DwIcon.vue";
import type { IconName } from "./icons";
// A tinted panel for a note, tip, warning or error. note uses the drop glyph.
const props = withDefaults(
defineProps<{ tone?: "note" | "info" | "success" | "warning" | "danger"; title?: string; icon?: IconName; size?: "doc" | "ui" }>(),
{ tone: "note", size: "doc" },
);
const defaultIcon = { note: "drop", info: "info", success: "check", warning: "alert", danger: "error" } as const;
const iconName = computed<IconName>(() => props.icon ?? defaultIcon[props.tone]);
</script>
<template>
<div
class="flex gap-3 rounded-md text-ink"
:class="[
size === 'doc' ? 'p-4 text-doc-body' : 'px-3 py-2 text-ui-md',
{
'bg-accent-soft': tone === 'note',
'bg-info-soft': tone === 'info',
'bg-success-soft': tone === 'success',
'bg-warning-soft': tone === 'warning',
'bg-danger-soft': tone === 'danger',
},
]"
:role="tone === 'danger' ? 'alert' : 'note'"
>
<DwIcon
:name="iconName"
:size="size === 'doc' ? 20 : 18"
:class="[
size === 'doc' ? 'mt-[3px]' : 'mt-px',
{
'text-accent': tone === 'note',
'text-info': tone === 'info',
'text-success': tone === 'success',
'text-warning': tone === 'warning',
'text-danger': tone === 'danger',
},
]"
/>
<div class="min-w-0 flex-1">
<p v-if="title" class="font-semibold">{{ title }}</p>
<slot />
</div>
<slot name="actions" />
</div>
</template>
+28
View File
@@ -0,0 +1,28 @@
<script setup lang="ts">
import { computed } from "vue";
import { iconPaths, type IconName } from "./icons";
// 16 in tree rows and small buttons, 18 in buttons, 20 in callouts and menus.
const props = withDefaults(defineProps<{ name: IconName; size?: number; label?: string }>(), { size: 18 });
const paths = computed(() => iconPaths[props.name] ?? iconPaths.page);
</script>
<template>
<svg
class="block shrink-0"
:width="size"
:height="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.75"
stroke-linecap="round"
stroke-linejoin="round"
focusable="false"
:role="label ? 'img' : undefined"
:aria-label="label"
:aria-hidden="label ? undefined : 'true'"
>
<path v-for="d in paths" :key="d" :d="d" />
</svg>
</template>
+29
View File
@@ -0,0 +1,29 @@
<script setup lang="ts">
import horizontal from "./assets/docwell-horizontal.svg";
import horizontalReversed from "./assets/docwell-horizontal-reversed.svg";
import symbolReversed from "./assets/docwell-symbol-reversed.svg";
import symbolSmall from "./assets/docwell-symbol-small.svg";
// The Docwell logo, never recolored or retyped. horizontal goes in headers
// (min 96px wide); symbol stands alone where the name is already shown. Dark
// themes get the -reversed artwork, and so does any dark ground such as the
// Ink Well brand panel (reversed). Size it with a height class.
withDefaults(defineProps<{ variant?: "horizontal" | "symbol"; reversed?: boolean }>(), { variant: "horizontal" });
</script>
<template>
<span class="inline-flex shrink-0" role="img" aria-label="Docwell">
<img
v-if="!reversed"
:src="variant === 'horizontal' ? horizontal : symbolSmall"
alt=""
class="h-full w-auto dark:hidden"
/>
<img
:src="variant === 'horizontal' ? horizontalReversed : symbolReversed"
alt=""
class="h-full w-auto"
:class="{ 'hidden dark:block': !reversed }"
/>
</span>
</template>
+44
View File
@@ -0,0 +1,44 @@
<script setup lang="ts">
import DwIcon from "./DwIcon.vue";
import type { IconName } from "./icons";
export interface SlashMenuItem {
label: string;
description?: string;
icon?: IconName;
shortcut?: string;
}
// The block inserter the editor opens on "/". The editor owns the keyboard
// (Up/Down move activeIndex, Enter selects, Escape closes); items select on
// mousedown so the editor keeps focus.
withDefaults(defineProps<{ items: SlashMenuItem[]; activeIndex?: number; query?: string; label?: string }>(), {
activeIndex: 0,
label: "Insert block",
});
const emit = defineEmits<{ select: [item: SlashMenuItem, index: number] }>();
</script>
<template>
<div class="w-80 max-w-full rounded-md border border-line bg-surface-raised p-1 shadow-menu" role="listbox" :aria-label="label">
<div v-if="query != null" class="px-2 pt-2 pb-1 font-mono text-ui-xs text-ink-muted">/{{ query }}</div>
<div
v-for="(it, i) in items"
:key="it.label"
role="option"
:aria-selected="i === activeIndex"
class="flex cursor-pointer items-center gap-3 rounded-sm px-2 py-1.5"
:class="{ 'bg-surface-hover': i === activeIndex }"
@mousedown.prevent="emit('select', it, i)"
>
<span class="grid size-9 shrink-0 place-items-center rounded-sm border border-line bg-surface text-ink-muted">
<DwIcon :name="it.icon ?? 'text'" :size="18" />
</span>
<span class="flex min-w-0 flex-1 flex-col">
<span class="text-ui-md font-medium text-ink">{{ it.label }}</span>
<span v-if="it.description" class="truncate text-ui-xs font-normal text-ink-muted">{{ it.description }}</span>
</span>
<kbd v-if="it.shortcut" class="font-mono text-[11px] leading-4 text-ink-muted">{{ it.shortcut }}</kbd>
</div>
</div>
</template>
+27
View File
@@ -0,0 +1,27 @@
<script setup lang="ts">
import { useId } from "vue";
// A labelled single-line input for settings, dialogs and sign-in. The label is
// the accessible name; placeholders are examples only. error replaces hint.
defineOptions({ inheritAttrs: false });
const props = defineProps<{ label: string; hint?: string; error?: string; id?: string }>();
const model = defineModel<string>({ default: "" });
const id = props.id ?? useId();
</script>
<template>
<div class="flex min-w-0 flex-col gap-1.5" :class="$attrs.class">
<label :for="id" class="text-ui-sm font-semibold text-ink">{{ label }}</label>
<input
:id="id"
v-model="model"
v-bind="{ ...$attrs, class: undefined }"
class="dw-input"
:aria-invalid="error ? 'true' : undefined"
:aria-describedby="error || hint ? `${id}-note` : undefined"
/>
<p v-if="error || hint" :id="`${id}-note`" class="text-ui-sm" :class="error ? 'text-danger' : 'text-ink-muted'">
{{ error || hint }}
</p>
</div>
</template>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import DwIcon from "./DwIcon.vue";
import type { IconName } from "./icons";
// One row of the sidebar page tree (the design system's PageTreeItem), nested
// 16px per depth on surface-sunken. The default slot is the row's main control
// (usually a link holding the title); the actions slot shows on hover and focus.
withDefaults(
defineProps<{
title?: string;
depth?: number;
icon?: IconName;
hasChildren?: boolean;
expanded?: boolean;
active?: boolean;
toggleLabel?: string;
}>(),
{ depth: 0, icon: "page" },
);
const emit = defineEmits<{ toggle: [] }>();
</script>
<template>
<div
role="treeitem"
:aria-selected="active"
:aria-expanded="hasChildren ? expanded : undefined"
class="group flex h-control-sm items-center gap-1 rounded-sm pr-1 text-ui-md transition-colors duration-[120ms]"
:class="active ? 'bg-accent-soft font-semibold text-accent' : 'text-ink-muted hover:bg-surface-hover hover:text-ink'"
:style="{ paddingLeft: `${8 + depth * 16}px` }"
>
<button
type="button"
tabindex="-1"
class="grid size-5 shrink-0 cursor-pointer place-items-center rounded-xs hover:bg-line"
:class="{ invisible: !hasChildren }"
:aria-label="toggleLabel"
@click.stop="emit('toggle')"
>
<DwIcon :name="expanded ? 'chevron-down' : 'chevron-right'" :size="14" />
</button>
<DwIcon :name="icon" :size="16" />
<span class="min-w-0 flex-1 truncate" :title="title">
<slot>{{ title }}</slot>
</span>
<span v-if="$slots.actions" class="hidden shrink-0 items-center group-focus-within:flex group-hover:flex">
<slot name="actions" />
</span>
</div>
</template>
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 846 256" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYToxMjkxYmUzNS04ZTZiLTQ3NWYtODUyMC00MzE5NzY5YzRmZDMAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaB0vu8jKFEIl9kYI2+2bnS4AAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDplNjk0NmNjNy1kNTczLTQ3ZTUtYTdhMy00YzM3ZmU3MWNiYTdscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNoZlZ5WXKM2cYlRDwW0zLYDgAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3JlZGllbnQudjNkaGFzaFggG45DhAjj7dGQNBfCV4+xY3rWJP8+Nx+XKQJ2yLn7q36kZmFjdGlvbngdY29tLmFudGhyb3BpYy5jbGF1ZGUucHJvdmlkZWRqcGFyYW1ldGVyc6F4H2NvbS5hbnRocm9waWMub3JpZ2luLWNvbmZpZGVuY2VndW5rbm93bmtkZXNjcmlwdGlvbnhmQ2xhdWRlIHByb3ZpZGVkIHRo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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTowYTRkZTE3Ni03OTlkLTRlMmItOGE0Zi1hZDMzNjFjNjkwNGYAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaKpB55Fq4I3f8+UTsP+ajRwAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDoyYjEzNzAzZi1mYzY1LTQ5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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated

After

Width:  |  Height:  |  Size: 7.9 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYTo3MTZiMjFmNi00MzgzLTQ5ODUtODJkYS03OTliOGU3MDY1MDcAAAADl2p1bWIAAAApanVtZGMyYXMAEQAQgAAAqgA4m3EDYzJwYS5hc3NlcnRpb25zAAAAALxqdW1iAAAARGp1bWRjYm9yABEAEIAAAKoAOJtxE2MycGEuaW5ncmVkaWVudC52MwAAAAAYYzJzaH8uDVnuMtisHFskP66nqqUAAABwY2JvcqNpZGM6Zm9ybWF0bWltYWdlL3N2Zyt4bWxqaW5zdGFuY2VJRHgseG1wOmlpZDo0YTYyYTY1NS0zZTQ5LTQxNDQtOGNiYS03MmVjODJhYjdmOTJscmVsYXRpb25zaGlwaHBhcmVudE9mAAAB4mp1bWIAAABBanVtZGNib3IAEQAQgAAAqgA4m3ETYzJwYS5hY3Rpb25zLnYyAAAAABhjMnNo624VnIttOWgoCKddQc1Q3gAAAZljYm9yomdhY3Rpb25zgqJmYWN0aW9ua2MycGEub3BlbmVkanBhcmFtZXRlcnOha2luZ3JlZGllbnRzgaJjdXJseC1zZWxmI2p1bWJmPWMycGEuYXNzZXJ0aW9ucy9jMnBhLmluZ3Jl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KiB

+37
View File
@@ -0,0 +1,37 @@
/**
* Docwell's own outline icons: a 24-unit grid, 1.75 stroke, round caps and
* joins, drawn in currentColor. The first group is the design system's set
* (Design/docwell-all/3-design-system); the rest extend it on the same grid.
*/
export const iconPaths = {
page: ["M6 3h8l4 4v14H6z", "M14 3v4h4", "M9 12h6", "M9 16h6"],
"chevron-right": ["M10 6l6 6-6 6"],
"chevron-down": ["M6 10l6 6 6-6"],
plus: ["M12 5v14", "M5 12h14"],
search: ["M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z", "M16.5 16.5L20 20"],
more: ["M6 12h.01", "M12 12h.01", "M18 12h.01"],
drop: ["M12 4h7v7a7 7 0 1 1-7-7z"],
info: ["M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M12 11v5", "M12 8h.01"],
check: ["M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M8 12.5l2.5 2.5L16 9.5"],
alert: ["M12 4l9 16H3z", "M12 10v4", "M12 17h.01"],
error: ["M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M9 9l6 6", "M15 9l-6 6"],
text: ["M5 6h14", "M12 6v13"],
heading: ["M6 5v14", "M18 5v14", "M6 12h12"],
list: ["M9 6h11", "M9 12h11", "M9 18h11", "M4.5 6h.01", "M4.5 12h.01", "M4.5 18h.01"],
todo: ["M4 4h7v7H4z", "M5.5 7.5l1.5 1.5 2.5-2.5", "M14 7h6", "M4 14h7v7H4z", "M14 17h6"],
code: ["M9 7l-5 5 5 5", "M15 7l5 5-5 5"],
quote: ["M6 6v12", "M10 8h9", "M10 12h9", "M10 16h6"],
image: ["M4 5h16v14H4z", "M4 16l5-5 4 4 2-2 5 5", "M15.5 8.5h.01"],
table: ["M4 5h16v14H4z", "M4 10h16", "M4 15h16", "M10 5v14"],
// Extensions for the app shell.
lock: ["M6 11h12v9H6z", "M8.5 11V8a3.5 3.5 0 0 1 7 0v3"],
trash: ["M4 7h16", "M10 4h4", "M6 7l1 13h10l1-13", "M10 11v6", "M14 11v6"],
settings: ["M4 7h9", "M17 7h3", "M15 5v4", "M4 17h3", "M11 17h9", "M9 15v4"],
menu: ["M4 7h16", "M4 12h16", "M4 17h16"],
close: ["M6 6l12 12", "M18 6L6 18"],
open: ["M8 16L16 8", "M9 8h7v7"],
restore: ["M4.5 13a7.5 7.5 0 1 0 2.2-6.3", "M5 4v4h4"],
"sign-out": ["M14 4h5v16h-5", "M10 8l-4 4 4 4", "M6 12h9"],
} as const;
export type IconName = keyof typeof iconPaths;
+9
View File
@@ -1,2 +1,11 @@
export { default as DwBadge } from "./DwBadge.vue";
export { default as DwBreadcrumbs } from "./DwBreadcrumbs.vue";
export { default as DwButton } from "./DwButton.vue";
export { default as DwCallout } from "./DwCallout.vue";
export { default as DwIcon } from "./DwIcon.vue";
export { default as DwLogo } from "./DwLogo.vue";
export { default as DwSlashMenu, type SlashMenuItem } from "./DwSlashMenu.vue";
export { default as DwTextField } from "./DwTextField.vue";
export { default as DwTreeItem } from "./DwTreeItem.vue";
export { iconPaths, type IconName } from "./icons";
export { useTheme, type ThemeMode } from "./theme";
+214 -25
View File
@@ -1,43 +1,232 @@
/* Shared Docwell design tokens for Tailwind CSS v4.
Import after `@import "tailwindcss";` in each app's main stylesheet. */
/* Docwell design system for Tailwind CSS v4: the tokens from
Design/docwell-all/3-design-system/source/tokens.json, plus the component
classes. Import after `@import "tailwindcss";` in each app's main stylesheet.
Keep this file in sync with that tokens.json. */
/* Fonts are bundled (no third-party requests): Docwell is self-hosted and
the desktop app works offline. All three are SIL Open Font License. */
@import "@fontsource-variable/inter/wght.css";
@import "@fontsource-variable/source-serif-4/opsz.css";
@import "@fontsource-variable/jetbrains-mono/wght.css";
@source "./";
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, monospace;
--color-brand-50: oklch(0.97 0.02 250);
--color-brand-100: oklch(0.93 0.04 250);
--color-brand-500: oklch(0.58 0.17 255);
--color-brand-600: oklch(0.52 0.18 258);
--color-brand-700: oklch(0.45 0.16 260);
--font-sans: "Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
--font-serif: "Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;
--font-mono: "JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;
/* Colors: utilities like bg-surface-sunken, text-ink-muted, border-line. */
--color-surface: var(--dw-surface);
--color-surface-muted: var(--dw-surface-muted);
--color-border: var(--dw-border);
--color-fg: var(--dw-fg);
--color-fg-muted: var(--dw-fg-muted);
--color-surface-sunken: var(--dw-surface-sunken);
--color-surface-raised: var(--dw-surface-raised);
--color-surface-hover: var(--dw-surface-hover);
--color-line: var(--dw-line);
--color-line-strong: var(--dw-line-strong);
--color-ink: var(--dw-ink);
--color-ink-muted: var(--dw-ink-muted);
--color-ink-faint: var(--dw-ink-faint);
--color-well: #12403c;
--color-spring: var(--dw-spring);
--color-primary: var(--dw-primary);
--color-primary-hover: var(--dw-primary-hover);
--color-on-primary: var(--dw-on-primary);
--color-accent: var(--dw-accent);
--color-accent-soft: var(--dw-accent-soft);
--color-selection: var(--dw-selection);
--color-focus-ring: var(--dw-focus-ring);
--color-success: var(--dw-success);
--color-success-soft: var(--dw-success-soft);
--color-warning: var(--dw-warning);
--color-warning-soft: var(--dw-warning-soft);
--color-danger: var(--dw-danger);
--color-danger-soft: var(--dw-danger-soft);
--color-on-danger: var(--dw-on-danger);
--color-info: var(--dw-info);
--color-info-soft: var(--dw-info-soft);
--color-code-bg: var(--dw-code-bg);
/* Interface text styles: text-ui-xs … text-ui-lg. */
--text-ui-xs: 12px;
--text-ui-xs--line-height: 16px;
--text-ui-xs--letter-spacing: 0.01em;
--text-ui-xs--font-weight: 500;
--text-ui-sm: 13px;
--text-ui-sm--line-height: 18px;
--text-ui-md: 14px;
--text-ui-md--line-height: 20px;
--text-ui-lg: 16px;
--text-ui-lg--line-height: 24px;
--text-ui-lg--font-weight: 600;
/* Document text styles: text-doc-title … text-doc-caption. */
--text-doc-title: 40px;
--text-doc-title--line-height: 48px;
--text-doc-title--letter-spacing: -0.01em;
--text-doc-title--font-weight: 600;
--text-doc-h1: 30px;
--text-doc-h1--line-height: 38px;
--text-doc-h1--font-weight: 600;
--text-doc-h2: 24px;
--text-doc-h2--line-height: 32px;
--text-doc-h2--font-weight: 600;
--text-doc-h3: 18px;
--text-doc-h3--line-height: 28px;
--text-doc-h3--font-weight: 600;
--text-doc-body: 16px;
--text-doc-body--line-height: 27px;
--text-doc-body-serif: 18px;
--text-doc-body-serif--line-height: 30px;
--text-doc-caption: 13px;
--text-doc-caption--line-height: 20px;
--text-code: 14px;
--text-code--line-height: 22px;
/* Radii: rounded-xs (badges) · sm (buttons, inputs, rows) · md (cards, menus) · lg (dialogs). */
--radius-xs: 4px;
--radius-sm: 6px;
--radius-md: 10px;
--radius-lg: 16px;
/* Floating layers only; everything else is separated by borders. */
--shadow-menu: var(--dw-shadow-menu);
--shadow-dialog: var(--dw-shadow-dialog);
/* Sizes: max-w-doc, w-sidebar, h-control-md … (spacing is Tailwind's 4px scale). */
--container-doc: 720px;
--container-doc-wide: 1040px;
--spacing-sidebar: 264px;
--spacing-control-sm: 28px;
--spacing-control-md: 34px;
}
:root {
--dw-surface: oklch(1 0 0);
--dw-surface-muted: oklch(0.975 0.003 250);
--dw-border: oklch(0.91 0.005 250);
--dw-fg: oklch(0.22 0.01 250);
--dw-fg-muted: oklch(0.5 0.01 250);
--dw-surface: #ffffff;
--dw-surface-sunken: #f4f7f6;
--dw-surface-raised: #ffffff;
--dw-surface-hover: #e9efed;
--dw-line: #dce4e1;
--dw-line-strong: #7f918c;
--dw-ink: #13201e;
--dw-ink-muted: #55645f;
--dw-ink-faint: #677672;
--dw-spring: #16a37c;
--dw-primary: #12403c;
--dw-primary-hover: #1b5853;
--dw-on-primary: #ffffff;
--dw-accent: #0e7a5c;
--dw-accent-soft: #e1f3ec;
--dw-selection: #c4eadb;
--dw-focus-ring: #0e8a68;
--dw-success: #1d6f47;
--dw-success-soft: #e2f3e8;
--dw-warning: #7f5300;
--dw-warning-soft: #fdf2dc;
--dw-danger: #b0302a;
--dw-danger-soft: #fbe8e6;
--dw-on-danger: #ffffff;
--dw-info: #2c5aa8;
--dw-info-soft: #e7eefb;
--dw-code-bg: #f1f5f4;
--dw-shadow-menu: 0 1px 2px rgba(11, 42, 39, 0.06), 0 8px 24px rgba(11, 42, 39, 0.12);
--dw-shadow-dialog: 0 2px 6px rgba(11, 42, 39, 0.08), 0 24px 64px rgba(11, 42, 39, 0.18);
color-scheme: light;
}
/* Dark is a full theme, not an inversion. */
.dark {
--dw-surface: oklch(0.19 0.006 250);
--dw-surface-muted: oklch(0.23 0.007 250);
--dw-border: oklch(0.32 0.008 250);
--dw-fg: oklch(0.94 0.004 250);
--dw-fg-muted: oklch(0.68 0.008 250);
--dw-surface: #0f1716;
--dw-surface-sunken: #0b1211;
--dw-surface-raised: #18221f;
--dw-surface-hover: #202c29;
--dw-line: #2a3735;
--dw-line-strong: #5d706b;
--dw-ink: #e8efed;
--dw-ink-muted: #a3b3ae;
--dw-ink-faint: #8a9b96;
--dw-spring: #2bc495;
--dw-primary: #2bc495;
--dw-primary-hover: #4fd3aa;
--dw-on-primary: #06291f;
--dw-accent: #5fd8b1;
--dw-accent-soft: #14332d;
--dw-selection: #1f4d43;
--dw-focus-ring: #5fd8b1;
--dw-success: #6fd39c;
--dw-success-soft: #11301f;
--dw-warning: #f2bc55;
--dw-warning-soft: #33260a;
--dw-danger: #ff9289;
--dw-danger-soft: #3a1614;
--dw-on-danger: #2a0807;
--dw-info: #93b8ff;
--dw-info-soft: #162440;
--dw-code-bg: #141e1c;
--dw-shadow-menu: 0 1px 2px rgba(0, 0, 0, 0.5), 0 8px 24px rgba(0, 0, 0, 0.55);
--dw-shadow-dialog: 0 2px 6px rgba(0, 0, 0, 0.5), 0 24px 64px rgba(0, 0, 0, 0.6);
color-scheme: dark;
}
html {
@apply bg-surface;
}
body {
@apply bg-surface text-fg font-sans antialiased;
@apply bg-surface text-ui-md text-ink font-sans antialiased;
}
::selection {
@apply bg-selection;
}
/* Keyboard focus: 2px focus-ring outline, 2px offset, on every interactive element. */
:where(a, button, [role="button"], [role="treeitem"], summary, select, input[type="checkbox"], input[type="radio"]):focus-visible {
outline: 2px solid var(--dw-focus-ring);
outline-offset: 2px;
}
/* Text inputs draw focus at 0 offset and turn their border focus-ring. */
:where(input:not([type="checkbox"], [type="radio"]), textarea, select).dw-input:focus-visible {
outline: 2px solid var(--dw-focus-ring);
outline-offset: 0;
border-color: var(--dw-focus-ring);
}
@layer components {
/* Inputs and selects (the TextField look), for places that use a bare control. */
.dw-input {
@apply h-control-md min-w-0 rounded-sm border border-line-strong bg-surface px-3 text-ui-md text-ink placeholder:text-ink-faint;
}
textarea.dw-input {
@apply h-auto py-2;
}
.dw-input[aria-invalid="true"] {
@apply border-danger;
}
/* Cards: separated by a line, never a shadow. */
.dw-card {
@apply rounded-md border border-line bg-surface-raised p-6;
}
/* Uppercase section labels (sidebar groups, settings sections). */
.dw-label {
@apply text-ui-xs uppercase text-ink-muted;
}
.dw-link {
@apply text-accent underline-offset-2 hover:underline;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
transition: none !important;
animation: none !important;
}
}
+3 -4
View File
@@ -2,9 +2,6 @@
An open-source, self-hostable knowledge base and collaborative document editor. It is wiki-first like Docmost and Outline, and will grow Notion-style databases later.
- [docs/FEATURES.md](docs/FEATURES.md): feature inventory of the reference apps, with Docwell priorities
- [docs/PLAN.md](docs/PLAN.md): architecture, decisions (ADRs) and roadmap
> Status: **Phase 0 scaffold.** All services build and run, but no product features exist yet.
## Components
@@ -49,7 +46,7 @@ Accounts live in PocketBase's built-in `users` auth collection. PocketBase store
- the first account becomes the superadmin
- disabled accounts (`status = disabled`) can't sign in
Tokens are sent as `Authorization: Bearer <token>`. Email codes (OTP), MFA and OAuth2 providers are switched on in PocketBase's `users` collection settings; the web app already handles codes and MFA. See ADR-6 in [docs/PLAN.md](docs/PLAN.md).
Tokens are sent as `Authorization: Bearer <token>`. Email codes (OTP), MFA and OAuth2 providers are switched on in PocketBase's `users` collection settings; the web app already handles codes and MFA.
## Organizations and rights
@@ -63,6 +60,8 @@ Docwell uses the same model as DriverVault. Every user belongs to at most one **
Workspaces belong to an organization, and rights cascade into them: superadmins and org admins are owners of every workspace in their scope, and everyone else gets their workspace role (`owner` > `admin` > `member` > `guest`). Nobody can grant a role above their own, change someone ranked above them, or change their own role.
Inside a workspace, pages live in **spaces**. Workspace owners and admins administer every space. In an **open** space every workspace member (not guests) gets the space's default role (`editor`, `commenter` or `viewer`); a **private** space is visible only to the people added to it. Space roles rank `admin` > `editor` > `commenter` > `viewer`: editors create, rename, move and trash pages, and space admins manage members and empty the trash. Pages form a tree per space, ordered by fractional position keys, and trashing a page hides its whole subtree until it is restored.
A user without an organization can create one from the web app and becomes its admin. Org admins and superadmins manage users and organizations in the admin panel; workspace members are managed in the web app. The rules live in [Server/internal/access](Server/internal/access/access.go).
## Development
+4
View File
@@ -3,6 +3,10 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="theme-color" content="#12403C" />
<title>Docwell Admin</title>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQ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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated

After

Width:  |  Height:  |  Size: 8.0 KiB

+15 -12
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { useTheme } from "@docwell/ui";
import { DwBadge, DwButton, DwLogo, useTheme } from "@docwell/ui";
import { useRouter } from "vue-router";
import { computed } from "vue";
import { currentUser, isSuperadmin, signOut } from "./session";
@@ -32,29 +32,32 @@ function logout() {
<template>
<RouterView v-if="!currentUser" />
<div v-else class="flex min-h-dvh flex-col md:flex-row">
<aside class="flex flex-col border-b border-border bg-surface-muted md:w-56 md:border-r md:border-b-0">
<div class="px-4 py-3 font-semibold">Docwell Admin</div>
<nav class="flex gap-1 overflow-x-auto px-2 pb-2 text-sm md:flex-1 md:flex-col">
<aside class="flex flex-col border-b border-line bg-surface-sunken md:w-56 md:border-r md:border-b-0">
<div class="flex h-12 items-center gap-2 px-4">
<DwLogo class="h-6" />
<DwBadge tone="accent">Admin</DwBadge>
</div>
<nav class="flex gap-px overflow-x-auto px-2 pb-2 md:flex-1 md:flex-col">
<RouterLink
v-for="item in nav"
:key="item.to"
:to="item.to"
class="rounded-md px-3 py-1.5 whitespace-nowrap hover:bg-surface"
exact-active-class="bg-surface font-medium"
class="flex h-control-sm items-center rounded-sm px-3 whitespace-nowrap text-ink-muted hover:bg-surface-hover hover:text-ink"
exact-active-class="!bg-accent-soft font-semibold !text-accent"
>
{{ item.label }}
</RouterLink>
</nav>
<div class="hidden border-t border-border p-3 text-sm md:block">
<div class="truncate font-medium">{{ currentUser.name }}</div>
<div class="truncate text-xs text-fg-muted">{{ currentUser.email }}</div>
<div class="mt-1 text-xs text-fg-muted" data-testid="role">
<div class="hidden border-t border-line p-3 md:block">
<div class="truncate font-medium text-ink">{{ currentUser.name }}</div>
<div class="truncate text-ui-sm text-ink-muted">{{ currentUser.email }}</div>
<div class="mt-1 text-ui-sm text-ink-muted" data-testid="role">
{{ isSuperadmin ? "Superadmin" : `Admin · ${currentUser.organizationName || "no organization"}` }}
</div>
<button class="mt-2 text-xs text-fg-muted hover:text-fg" @click="logout">Sign out</button>
<DwButton variant="ghost" size="sm" icon="sign-out" class="mt-2 -ml-2" @click="logout">Sign out</DwButton>
</div>
</aside>
<main class="flex-1 p-4 sm:p-8">
<main class="min-w-0 flex-1 bg-surface p-4 sm:p-8">
<RouterView />
</main>
</div>
+16 -16
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ApiError } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwBadge, DwButton, DwCallout, DwLogo, DwTextField } from "@docwell/ui";
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { signIn } from "../session";
@@ -35,20 +35,20 @@ async function submit() {
</script>
<template>
<div class="grid min-h-dvh place-items-center bg-surface-muted px-4">
<form class="w-full max-w-sm space-y-4 rounded-xl border border-border bg-surface p-6 shadow-sm" @submit.prevent="submit">
<h1 class="text-xl font-semibold">Docwell Admin</h1>
<p class="text-sm text-fg-muted">Sign in with an organization admin or superadmin account.</p>
<label class="block space-y-1 text-sm">
<span class="font-medium">Email</span>
<input v-model="email" type="email" autocomplete="email" required class="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-brand-500" />
</label>
<label class="block space-y-1 text-sm">
<span class="font-medium">Password</span>
<input v-model="password" type="password" autocomplete="current-password" required class="w-full rounded-md border border-border bg-surface px-3 py-2 outline-none focus:border-brand-500" />
</label>
<p v-if="error" role="alert" class="text-sm text-red-600">{{ error }}</p>
<DwButton type="submit" class="w-full justify-center" :disabled="busy">Sign in</DwButton>
</form>
<div class="grid min-h-dvh place-items-center bg-surface-sunken px-4">
<div class="w-full max-w-sm">
<div class="mb-8 flex items-center justify-center gap-2">
<DwLogo class="h-8" />
<DwBadge tone="accent">Admin</DwBadge>
</div>
<form class="space-y-4 dw-card" @submit.prevent="submit">
<h1 class="text-ui-lg">Sign in to the admin panel</h1>
<p class="text-ink-muted">Use an organization admin or superadmin account.</p>
<DwTextField v-model="email" label="Email" type="email" autocomplete="email" required />
<DwTextField v-model="password" label="Password" type="password" autocomplete="current-password" required />
<DwCallout v-if="error" tone="danger" size="ui">{{ error }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full" :disabled="busy">Sign in</DwButton>
</form>
</div>
</div>
</template>
+17 -17
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import type { Organization } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { api, currentUser, errorMessage, isSuperadmin, reloadUser } from "../session";
@@ -79,8 +79,8 @@ async function remove(o: Organization) {
<template>
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-xl font-semibold">{{ isSuperadmin ? "Organizations" : "Organization" }}</h1>
<p class="text-sm text-fg-muted">
<h1 class="text-2xl font-semibold tracking-tight">{{ isSuperadmin ? "Organizations" : "Organization" }}</h1>
<p class="mt-1 text-ink-muted">
{{
isSuperadmin
? "Every organization on this server. Admins of an organization manage only their own."
@@ -88,38 +88,38 @@ async function remove(o: Organization) {
}}
</p>
</div>
<DwButton v-if="isSuperadmin" @click="startNew">New organization</DwButton>
<DwButton v-if="isSuperadmin" variant="primary" @click="startNew">New organization</DwButton>
</div>
<p v-if="error" role="alert" class="mt-4 rounded-md bg-red-500/10 px-3 py-2 text-sm text-red-600">{{ error }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<form v-if="editing" class="mt-4 flex flex-wrap items-end gap-2 rounded-lg border border-border bg-surface-muted p-4" @submit.prevent="save">
<label class="flex-1 space-y-1 text-sm">
<span>Name</span>
<form v-if="editing" class="mt-4 flex flex-wrap items-end gap-2 dw-card !p-4" @submit.prevent="save">
<label class="flex flex-1 flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Name</span>
<input
v-model="draft"
required
maxlength="120"
class="w-full rounded-md border border-border bg-surface px-3 py-1.5 outline-none focus:border-brand-500"
class="dw-input w-full"
/>
</label>
<DwButton type="submit" :disabled="busy || !draft.trim()">{{ editing === "new" ? "Create" : "Save" }}</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy || !draft.trim()">{{ editing === "new" ? "Create" : "Save" }}</DwButton>
<DwButton variant="ghost" :disabled="busy" @click="editing = null">Cancel</DwButton>
</form>
<p v-if="!orgs.length && !error" class="mt-6 text-sm text-fg-muted">No organizations yet.</p>
<ul v-else class="mt-6 divide-y divide-border rounded-lg border border-border">
<p v-if="!orgs.length && !error" class="mt-6 text-ui-md text-ink-muted">No organizations yet.</p>
<ul v-else class="mt-6 divide-y divide-line rounded-md border border-line bg-surface-raised">
<li v-for="o in orgs" :key="o.id" class="flex flex-wrap items-center justify-between gap-3 px-4 py-3">
<div class="min-w-0">
<p class="truncate font-medium">{{ o.name }}</p>
<p class="text-xs text-fg-muted">
<p class="truncate font-medium text-ink">{{ o.name }}</p>
<p class="text-ui-sm text-ink-muted">
{{ o.members }} {{ o.members === 1 ? "member" : "members" }} · {{ o.workspaces }}
{{ o.workspaces === 1 ? "workspace" : "workspaces" }}
</p>
</div>
<div class="flex shrink-0 gap-3 text-sm">
<button class="text-brand-600 hover:underline" @click="startEdit(o)">Rename</button>
<button class="text-red-600 hover:underline" :disabled="busy" @click="remove(o)">Delete</button>
<div class="flex shrink-0 gap-1">
<DwButton variant="ghost" size="sm" @click="startEdit(o)">Rename</DwButton>
<DwButton variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="remove(o)">Delete</DwButton>
</div>
</li>
</ul>
+13 -12
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { ApiError, type Status, type Version } from "@docwell/api-client";
import { DwCallout } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { api } from "../session";
@@ -27,25 +28,25 @@ onMounted(async () => {
</script>
<template>
<h1 class="text-xl font-semibold">Overview</h1>
<p v-if="error" class="mt-4 text-sm text-red-600">{{ error }}</p>
<h1 class="text-2xl font-semibold tracking-tight">Overview</h1>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<div class="mt-6 grid gap-4 sm:grid-cols-3">
<div class="rounded-lg border border-border p-4">
<div class="text-xs text-fg-muted">Server version</div>
<div class="mt-1 text-lg font-medium">{{ version?.version ?? "…" }}</div>
<div class="rounded-md border border-line bg-surface-raised p-4">
<div class="text-ui-sm text-ink-muted">Server version</div>
<div class="mt-1 text-ui-lg">{{ version?.version ?? "…" }}</div>
</div>
<div class="rounded-lg border border-border p-4">
<div class="text-xs text-fg-muted">Database</div>
<div class="rounded-md border border-line bg-surface-raised p-4">
<div class="text-ui-sm text-ink-muted">Database</div>
<div
class="mt-1 text-lg font-medium"
:class="readiness?.status === 'ok' ? 'text-emerald-600' : readiness ? 'text-red-600' : ''"
class="mt-1 text-ui-lg"
:class="readiness?.status === 'ok' ? 'text-success' : readiness ? 'text-danger' : ''"
>
{{ readiness ? (readiness.status === "ok" ? "Connected" : "Unavailable") : "…" }}
</div>
</div>
<RouterLink to="/users" class="rounded-lg border border-border p-4 hover:bg-surface-muted">
<div class="text-xs text-fg-muted">Users</div>
<div class="mt-1 text-lg font-medium" data-testid="user-count">{{ userCount ?? "…" }}</div>
<RouterLink to="/users" class="rounded-md border border-line bg-surface-raised p-4 transition-colors duration-[120ms] hover:border-line-strong">
<div class="text-ui-sm text-ink-muted">Users</div>
<div class="mt-1 text-ui-lg" data-testid="user-count">{{ userCount ?? "…" }}</div>
</RouterLink>
</div>
</template>
+2 -2
View File
@@ -1,4 +1,4 @@
<template>
<h1 class="text-xl font-semibold">{{ $route.meta.title }}</h1>
<p class="mt-2 text-sm text-fg-muted">Not built yet. See docs/PLAN.md, section 8.</p>
<h1 class="text-2xl font-semibold tracking-tight">{{ $route.meta.title }}</h1>
<p class="mt-2 text-ui-md text-ink-muted">Not built yet. See docs/PLAN.md, section 8.</p>
</template>
+44 -45
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import type { Organization, Role, User, UserList } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwBadge, DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { api, currentUser, errorMessage, isSuperadmin } from "../session";
@@ -113,75 +113,74 @@ async function remove(u: User) {
}
}
const inputClass = "w-full rounded-md border border-border bg-surface px-3 py-1.5 text-sm outline-none focus:border-brand-500";
</script>
<template>
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 class="text-xl font-semibold">Users</h1>
<p class="text-sm text-fg-muted">
<h1 class="text-2xl font-semibold tracking-tight">Users</h1>
<p class="mt-1 text-ink-muted">
{{ isSuperadmin ? "Everyone on this server." : `Members of ${currentUser?.organizationName}.` }}
</p>
</div>
<DwButton @click="startNew">New user</DwButton>
<DwButton variant="primary" @click="startNew">New user</DwButton>
</div>
<div class="mt-4 flex flex-wrap gap-2">
<input v-model="search" type="search" placeholder="Search name or email" aria-label="Search users" :class="[inputClass, 'sm:w-64']" />
<select v-if="isSuperadmin" v-model="orgFilter" aria-label="Filter by organization" :class="[inputClass, 'sm:w-56']">
<input v-model="search" type="search" placeholder="Search name or email" aria-label="Search users" class="dw-input sm:w-64" />
<select v-if="isSuperadmin" v-model="orgFilter" aria-label="Filter by organization" class="dw-input sm:w-56">
<option value="">All organizations</option>
<option value="none">No organization</option>
<option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
</div>
<p v-if="error" role="alert" class="mt-4 rounded-md bg-red-500/10 px-3 py-2 text-sm text-red-600">{{ error }}</p>
<DwCallout v-if="error" tone="danger" size="ui" class="mt-4">{{ error }}</DwCallout>
<form v-if="editing" class="mt-4 grid gap-3 rounded-lg border border-border bg-surface-muted p-4 sm:grid-cols-2" @submit.prevent="save">
<h2 class="font-medium sm:col-span-2">{{ editing === "new" ? "New user" : `Edit ${editing.email}` }}</h2>
<label class="space-y-1 text-sm">
<span>Name</span>
<input v-model="form.name" required :class="inputClass" />
<form v-if="editing" class="mt-4 grid gap-3 dw-card !p-4 sm:grid-cols-2" @submit.prevent="save">
<h2 class="text-ui-lg sm:col-span-2">{{ editing === "new" ? "New user" : `Edit ${editing.email}` }}</h2>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Name</span>
<input v-model="form.name" required class="dw-input" />
</label>
<label class="space-y-1 text-sm">
<span>Email</span>
<input v-model="form.email" type="email" required :class="inputClass" />
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Email</span>
<input v-model="form.email" type="email" required class="dw-input" />
</label>
<label class="space-y-1 text-sm">
<span>{{ editing === "new" ? "Password" : "New password (optional)" }}</span>
<input v-model="form.password" type="password" autocomplete="new-password" :required="editing === 'new'" minlength="8" :class="inputClass" />
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ editing === "new" ? "Password" : "New password (optional)" }}</span>
<input v-model="form.password" type="password" autocomplete="new-password" :required="editing === 'new'" minlength="8" class="dw-input" />
</label>
<label class="space-y-1 text-sm">
<span>Role</span>
<select v-model="form.role" :disabled="isSelf" :class="inputClass">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Role</span>
<select v-model="form.role" :disabled="isSelf" class="dw-input">
<option v-for="r in roles" :key="r" :value="r">{{ roleLabel[r] }}</option>
</select>
<span v-if="isSelf" class="text-xs text-fg-muted">You cannot change your own role.</span>
<span v-if="isSelf" class="text-ui-sm text-ink-muted">You cannot change your own role.</span>
</label>
<label v-if="isSuperadmin" class="space-y-1 text-sm">
<span>Organization</span>
<select v-model="form.organization" :class="inputClass">
<label v-if="isSuperadmin" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Organization</span>
<select v-model="form.organization" class="dw-input">
<option value="">No organization</option>
<option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
</label>
<label v-if="editing !== 'new'" class="space-y-1 text-sm">
<span>Status</span>
<select v-model="form.status" :disabled="isSelf" :class="inputClass">
<label v-if="editing !== 'new'" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">Status</span>
<select v-model="form.status" :disabled="isSelf" class="dw-input">
<option value="active">Active</option>
<option value="disabled">Disabled</option>
</select>
</label>
<div class="flex gap-2 sm:col-span-2">
<DwButton type="submit" :disabled="busy">{{ editing === "new" ? "Create user" : "Save" }}</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy">{{ editing === "new" ? "Create user" : "Save" }}</DwButton>
<DwButton variant="ghost" :disabled="busy" @click="editing = null">Cancel</DwButton>
</div>
</form>
<div class="mt-6 overflow-x-auto rounded-lg border border-border">
<table class="w-full text-left text-sm">
<thead class="bg-surface-muted text-xs text-fg-muted">
<div class="mt-6 overflow-x-auto rounded-md border border-line bg-surface-raised">
<table class="w-full text-left text-ui-md">
<thead class="bg-surface-sunken text-ui-xs uppercase text-ink-muted">
<tr>
<th class="px-4 py-2 font-medium">Name</th>
<th class="px-4 py-2 font-medium">Email</th>
@@ -192,33 +191,33 @@ const inputClass = "w-full rounded-md border border-border bg-surface px-3 py-1.
</tr>
</thead>
<tbody>
<tr v-for="u in list?.items" :key="u.id" class="border-t border-border">
<tr v-for="u in list?.items" :key="u.id" class="border-t border-line">
<td class="px-4 py-2 font-medium">{{ u.name }}</td>
<td class="px-4 py-2">{{ u.email }}</td>
<td class="px-4 py-2">{{ roleLabel[u.role] }}</td>
<td v-if="isSuperadmin" class="px-4 py-2">{{ u.organizationName || "—" }}</td>
<td class="px-4 py-2 capitalize">{{ u.status }}</td>
<td class="px-4 py-2">
<DwBadge :tone="u.status === 'active' ? 'success' : u.status === 'disabled' ? 'danger' : 'neutral'" class="capitalize">{{ u.status }}</DwBadge>
</td>
<td class="px-4 py-2 text-right whitespace-nowrap">
<template v-if="canEdit(u)">
<button class="text-brand-600 hover:underline" @click="startEdit(u)">Edit</button>
<button v-if="u.id !== currentUser?.id" class="ml-3 text-red-600 hover:underline" :disabled="busy" @click="remove(u)">
<DwButton variant="ghost" size="sm" @click="startEdit(u)">Edit</DwButton>
<DwButton v-if="u.id !== currentUser?.id" variant="ghost" size="sm" class="!text-danger" :disabled="busy" @click="remove(u)">
Delete
</button>
</DwButton>
</template>
</td>
</tr>
<tr v-if="list && list.items.length === 0">
<td :colspan="isSuperadmin ? 6 : 5" class="px-4 py-6 text-center text-fg-muted">No users found.</td>
<td :colspan="isSuperadmin ? 6 : 5" class="px-4 py-6 text-center text-ink-muted">No users found.</td>
</tr>
</tbody>
</table>
</div>
<div v-if="list && list.totalItems > perPage" class="mt-4 flex items-center gap-3 text-sm">
<button class="rounded border border-border px-2 py-1 disabled:opacity-40" :disabled="page <= 1" @click="page--">Previous</button>
<span class="text-fg-muted">Page {{ page }} of {{ Math.ceil(list.totalItems / perPage) }}</span>
<button class="rounded border border-border px-2 py-1 disabled:opacity-40" :disabled="page * perPage >= list.totalItems" @click="page++">
Next
</button>
<div v-if="list && list.totalItems > perPage" class="mt-4 flex items-center gap-3 text-ui-md">
<DwButton size="sm" :disabled="page <= 1" @click="page--">Previous</DwButton>
<span class="text-ink-muted">Page {{ page }} of {{ Math.ceil(list.totalItems / perPage) }}</span>
<DwButton size="sm" :disabled="page * perPage >= list.totalItems" @click="page++">Next</DwButton>
</div>
</template>
+122
View File
@@ -0,0 +1,122 @@
package access
import "docwell/server/internal/apperr"
// ---- Spaces and pages ------------------------------------------------------
//
// Space rights cascade from the workspace role:
//
// workspace owner/admin admin of every space in the workspace
// member explicit space role, else the space's default role in open spaces
// guest explicit space role only (guests never see open spaces by default)
//
// Space roles: admin > editor > commenter > viewer. Pages inherit their space's rights.
// Space roles stored in space_members.role.
const (
SpaceAdmin = "admin"
SpaceEditor = "editor"
SpaceCommenter = "commenter"
SpaceViewer = "viewer"
)
// Space visibilities stored in spaces.visibility.
const (
SpaceOpen = "open"
SpacePrivate = "private"
)
var spaceRank = map[string]int{SpaceViewer: 1, SpaceCommenter: 2, SpaceEditor: 3, SpaceAdmin: 4}
// ValidSpaceRole reports whether role is a space role.
func ValidSpaceRole(role string) bool { return spaceRank[role] > 0 }
// ValidDefaultRole reports whether role can be an open space's default role.
func ValidDefaultRole(role string) bool { return ValidSpaceRole(role) && role != SpaceAdmin }
// SpaceAtLeast reports whether space role has is at or above need.
func SpaceAtLeast(has, need string) bool { return has != "" && spaceRank[has] >= spaceRank[need] }
// SpaceRole is the effective role in a space for someone with workspace role
// wsRole (already resolved by WorkspaceRole) and explicit space role
// memberRole ("" when not a space member). "" = no access.
func SpaceRole(wsRole, visibility, defaultRole, memberRole string) string {
switch {
case wsRole == "":
return ""
case AtLeast(wsRole, WorkspaceAdmin):
return SpaceAdmin
case ValidSpaceRole(memberRole):
return memberRole
case visibility == SpaceOpen && wsRole != WorkspaceGuest:
if ValidDefaultRole(defaultRole) {
return defaultRole
}
return SpaceEditor
}
return ""
}
// CreateSpace and DeleteSpace need workspace admin: spaces are the workspace's structure.
func CreateSpace(wsRole string) error {
if !AtLeast(wsRole, WorkspaceAdmin) {
return apperr.Forbidden("workspace admin role required")
}
return nil
}
func DeleteSpace(wsRole string) error { return CreateSpace(wsRole) }
// ManageSpace (settings and members) needs space admin.
func ManageSpace(spaceRole string) error {
if !SpaceAtLeast(spaceRole, SpaceAdmin) {
return apperr.Forbidden("space admin role required")
}
return nil
}
// ViewSpace needs any access; a space someone cannot see does not exist for them.
func ViewSpace(spaceRole string) error {
if spaceRole == "" {
return apperr.NotFound("space not found")
}
return nil
}
// EditPages (create, rename, move, trash, restore) needs editor.
func EditPages(spaceRole string) error {
if err := ViewSpace(spaceRole); err != nil {
return err
}
if !SpaceAtLeast(spaceRole, SpaceEditor) {
return apperr.Forbidden("editor role required")
}
return nil
}
// PurgePage (permanent delete from the trash) needs space admin.
func PurgePage(spaceRole string) error {
if err := ViewSpace(spaceRole); err != nil {
return err
}
return ManageSpace(spaceRole)
}
// SetSpaceMember checks granting role to someone whose workspace role is
// targetWsRole. The target must be able to open the workspace; workspace
// admins are already space admins everywhere, so they are not listed.
func SetSpaceMember(actorRole, targetWsRole, role string) error {
if !ValidSpaceRole(role) {
return apperr.Invalid("role must be admin, editor, commenter or viewer")
}
if err := ManageSpace(actorRole); err != nil {
return err
}
if targetWsRole == "" {
return apperr.Invalid("that user is not a member of this workspace")
}
if AtLeast(targetWsRole, WorkspaceAdmin) {
return apperr.Invalid("workspace admins already manage every space")
}
return nil
}
+81
View File
@@ -0,0 +1,81 @@
package access
import (
"testing"
"docwell/server/internal/apperr"
)
const notFound = apperr.KindNotFound
func TestSpaceRoleCascade(t *testing.T) {
cases := []struct {
name string
ws, visibility, def, member string
want string
}{
{"no workspace access", "", SpaceOpen, SpaceEditor, SpaceAdmin, ""},
{"workspace owner", WorkspaceOwner, SpacePrivate, "", "", SpaceAdmin},
{"workspace admin beats explicit role", WorkspaceAdmin, SpacePrivate, "", SpaceViewer, SpaceAdmin},
{"member, open space default", WorkspaceMember, SpaceOpen, SpaceCommenter, "", SpaceCommenter},
{"member, open space, no default", WorkspaceMember, SpaceOpen, "", "", SpaceEditor},
{"member, admin default is ignored", WorkspaceMember, SpaceOpen, SpaceAdmin, "", SpaceEditor},
{"member, explicit beats default", WorkspaceMember, SpaceOpen, SpaceEditor, SpaceViewer, SpaceViewer},
{"member, private space", WorkspaceMember, SpacePrivate, SpaceEditor, "", ""},
{"member, private space, explicit", WorkspaceMember, SpacePrivate, "", SpaceAdmin, SpaceAdmin},
{"guest, open space", WorkspaceGuest, SpaceOpen, SpaceEditor, "", ""},
{"guest, explicit", WorkspaceGuest, SpaceOpen, "", SpaceViewer, SpaceViewer},
}
for _, c := range cases {
if got := SpaceRole(c.ws, c.visibility, c.def, c.member); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestSpaceActions(t *testing.T) {
cases := []struct {
name string
err error
want apperr.Kind
}{
{"member cannot create space", CreateSpace(WorkspaceMember), forbidden},
{"admin creates space", CreateSpace(WorkspaceAdmin), ok},
{"owner deletes space", DeleteSpace(WorkspaceOwner), ok},
{"editor cannot manage space", ManageSpace(SpaceEditor), forbidden},
{"space admin manages", ManageSpace(SpaceAdmin), ok},
{"no access hides space", ViewSpace(""), notFound},
{"viewer sees space", ViewSpace(SpaceViewer), ok},
{"commenter cannot edit pages", EditPages(SpaceCommenter), forbidden},
{"editor edits pages", EditPages(SpaceEditor), ok},
{"no access hides pages", EditPages(""), notFound},
{"editor cannot purge", PurgePage(SpaceEditor), forbidden},
{"admin purges", PurgePage(SpaceAdmin), ok},
}
for _, c := range cases {
if got := kind(c.err); got != c.want {
t.Errorf("%s: got kind %v, want %v (%v)", c.name, got, c.want, c.err)
}
}
}
func TestSetSpaceMember(t *testing.T) {
cases := []struct {
name string
actor, targetWs, role string
want apperr.Kind
}{
{"admin adds member as editor", SpaceAdmin, WorkspaceMember, SpaceEditor, ok},
{"admin adds guest as viewer", SpaceAdmin, WorkspaceGuest, SpaceViewer, ok},
{"admin grants admin", SpaceAdmin, WorkspaceMember, SpaceAdmin, ok},
{"editor cannot add", SpaceEditor, WorkspaceMember, SpaceViewer, forbidden},
{"unknown role", SpaceAdmin, WorkspaceMember, "owner", invalid},
{"outsider", SpaceAdmin, "", SpaceViewer, invalid},
{"workspace admin needs no entry", SpaceAdmin, WorkspaceAdmin, SpaceViewer, invalid},
}
for _, c := range cases {
if got := kind(SetSpaceMember(c.actor, c.targetWs, c.role)); got != c.want {
t.Errorf("%s: got kind %v, want %v", c.name, got, c.want)
}
}
}
+25 -8
View File
@@ -1,6 +1,7 @@
// Package directory manages users, organizations, workspaces and workspace
// members in PocketBase. Every action asks the access package first; this
// package only loads the facts those rules need and applies the result.
// Package directory manages users, organizations, workspaces, spaces, pages
// and their memberships in PocketBase. Every action asks the access package
// first; this package only loads the facts those rules need and applies the
// result.
package directory
import (
@@ -664,7 +665,7 @@ func (s *Service) CreateWorkspace(ctx context.Context, c access.Caller, in Creat
return Workspace{}, err
}
base := slugify(name)
base := slugify(name, "workspace")
for i := 1; i <= 50; i++ {
slug := base
if i > 1 {
@@ -691,13 +692,13 @@ func (s *Service) CreateWorkspace(ctx context.Context, c access.Caller, in Creat
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
func slugify(name string) string {
func slugify(name, fallback string) string {
s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(name), "-"), "-")
if len(s) > 48 {
s = strings.TrimRight(s[:48], "-")
}
if s == "" {
return "workspace"
return fallback
}
return s
}
@@ -827,10 +828,19 @@ func (s *Service) RemoveMember(ctx context.Context, c access.Caller, wsID, userI
if err := access.RemoveMember(c.ID, actorRole, userID, current.Role); err != nil {
return err
}
return mapPB(s.pb.Delete(ctx, "workspace_members", current.ID), "member not found")
if err := s.pb.Delete(ctx, "workspace_members", current.ID); err != nil {
return mapPB(err, "member not found")
}
// Space roles mean nothing without the workspace; drop them (best effort).
if spaceMembers, err := s.userSpaceMemberships(ctx, userID, ws.ID); err == nil {
for _, m := range spaceMembers {
_ = s.pb.Delete(ctx, "space_members", m.ID)
}
}
return nil
}
// dropMemberships removes all of a user's workspace memberships (best effort).
// dropMemberships removes all of a user's workspace and space memberships (best effort).
func (s *Service) dropMemberships(ctx context.Context, userID string) {
res, err := pocketbase.List[memberRecord](ctx, s.pb, "workspace_members", pocketbase.ListOptions{
PerPage: 500, Filter: fmt.Sprintf("user = '%s'", userID),
@@ -841,4 +851,11 @@ func (s *Service) dropMemberships(ctx context.Context, userID string) {
for _, m := range res.Items {
_ = s.pb.Delete(ctx, "workspace_members", m.ID)
}
spaceMembers, err := s.userSpaceMemberships(ctx, userID, "")
if err != nil {
return
}
for _, m := range spaceMembers {
_ = s.pb.Delete(ctx, "space_members", m.ID)
}
}
+496
View File
@@ -0,0 +1,496 @@
package directory
import (
"context"
"fmt"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Pages -----------------------------------------------------------------
//
// Pages form a tree per space (pages.parent, "" = top level), ordered among
// 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.
// pageFields skips the large content columns.
const pageFields = "id,workspace,space,parent,title,icon,position,creator,last_editor,deleted_at,created,updated"
type pageRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Position string `json:"position"`
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
Created string `json:"created"`
Updated string `json:"updated"`
}
// PageNode is one entry of a space's page tree.
type PageNode struct {
ID string `json:"id"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Position string `json:"position"`
Updated string `json:"updated"`
}
func (r pageRecord) node() PageNode {
return PageNode{ID: r.ID, Parent: r.Parent, Title: r.Title, Icon: r.Icon, Position: r.Position, Updated: r.Updated}
}
type PageRef struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
}
// Page is one page with its breadcrumb trail and the caller's space role.
type Page struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Parent string `json:"parent"`
Title string `json:"title"`
Icon string `json:"icon"`
Created string `json:"created"`
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"`
}
type TrashedPage struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
DeletedAt string `json:"deletedAt"`
}
func (s *Service) getPage(ctx context.Context, id string) (pageRecord, error) {
if !validID(id) {
return pageRecord{}, apperr.NotFound("page not found")
}
res, err := pocketbase.List[pageRecord](ctx, s.pb, "pages", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("id = '%s'", id), Fields: pageFields,
})
if err != nil {
return pageRecord{}, err
}
if len(res.Items) == 0 {
return pageRecord{}, apperr.NotFound("page not found")
}
return res.Items[0], nil
}
// pageFor loads a page and c's access to its space.
func (s *Service) pageFor(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, error) {
p, err := s.getPage(ctx, id)
if err != nil {
return p, spaceAccess{}, err
}
a, err := s.spaceFor(ctx, c, p.Space)
if err != nil {
return p, a, apperr.NotFound("page not found")
}
return p, a, nil
}
// tree is every page of one space, live or trashed.
type tree struct {
byID map[string]pageRecord
children map[string][]pageRecord // parent id ("" = top level) → live children in order
}
func (s *Service) loadTree(ctx context.Context, spaceID string) (tree, error) {
all, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s'", spaceID), Fields: pageFields,
})
if err != nil {
return tree{}, err
}
t := tree{byID: make(map[string]pageRecord, len(all)), children: map[string][]pageRecord{}}
for _, p := range all {
t.byID[p.ID] = p
}
for _, p := range all {
if p.DeletedAt == "" {
t.children[p.Parent] = append(t.children[p.Parent], p)
}
}
for _, list := range t.children {
sort.Slice(list, func(i, j int) bool {
if list[i].Position != list[j].Position {
return list[i].Position < list[j].Position
}
return list[i].ID < list[j].ID
})
}
return t, nil
}
// live reports whether a page and all of its ancestors are out of the trash.
func (t tree) live(id string) bool {
for depth := 0; id != "" && depth < 1000; depth++ {
p, ok := t.byID[id]
if !ok || p.DeletedAt != "" {
return false
}
id = p.Parent
}
return true
}
// 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++ {
if id == ancestor {
return true
}
id = t.byID[id].Parent
}
return false
}
// ListPages returns a space's live pages, siblings in order; clients build the tree.
func (s *Service) ListPages(ctx context.Context, c access.Caller, spaceID string) ([]PageNode, error) {
a, err := s.spaceFor(ctx, c, spaceID)
if err != nil {
return nil, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return nil, err
}
out := []PageNode{}
var walk func(parent string)
walk = func(parent string) {
for _, p := range t.children[parent] {
out = append(out, p.node())
walk(p.ID)
}
}
walk("")
return out, nil
}
// GetPage returns a page with its breadcrumbs.
func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page, error) {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return Page{}, err
}
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 != "",
Ancestors: []PageRef{}, Role: a.role,
}
parent := p.Parent
for depth := 0; parent != "" && depth < 100; depth++ {
anc, err := s.getPage(ctx, parent)
if err != nil {
break
}
page.InTrash = page.InTrash || anc.DeletedAt != ""
page.Ancestors = append([]PageRef{{ID: anc.ID, Title: anc.Title, Icon: anc.Icon}}, page.Ancestors...)
parent = anc.Parent
}
return page, nil
}
// placement computes the position for a page at index among siblings (which
// must not contain the page itself). When keys get too long it renumbers the
// siblings and returns the updates to apply first.
func placement(siblings []pageRecord, index int) (string, map[string]string) {
index = min(max(index, 0), len(siblings))
before, after := "", ""
if index > 0 {
before = siblings[index-1].Position
}
if index < len(siblings) {
after = siblings[index].Position
}
if before < after || after == "" {
if key := keyBetween(before, after); len(key) <= maxKeyLen {
return key, nil
}
}
keys := evenKeys(len(siblings) + 1)
renumber := map[string]string{}
for i, sib := range siblings {
k := keys[i]
if i >= index {
k = keys[i+1]
}
if sib.Position != k {
renumber[sib.ID] = k
}
}
return keys[index], renumber
}
func (s *Service) renumber(ctx context.Context, updates map[string]string) error {
for id, pos := range updates {
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", id, map[string]any{"position": pos}); err != nil {
return mapPB(err, "page not found")
}
}
return nil
}
func cleanTitle(title string) (string, error) {
title = strings.TrimSpace(title)
if len(title) > 500 {
return "", apperr.InvalidFields(map[string]string{"title": "Title is too long (max 500)."})
}
return title, nil
}
// checkParent validates a new parent ("" = top level) inside t; moving (the
// page being moved, "" when creating) may not go under itself.
func checkParent(t tree, parent, moving string) error {
if parent == "" {
return nil
}
if _, ok := t.byID[parent]; !ok || !t.live(parent) {
return apperr.InvalidFields(map[string]string{"parent": "Parent page not found in this space."})
}
if moving != "" && t.within(parent, moving) {
return apperr.InvalidFields(map[string]string{"parent": "A page cannot be moved inside itself."})
}
return nil
}
type CreatePageInput struct {
Parent string `json:"parent"`
Title string `json:"title"`
// Index among the parent's children; nil appends at the end.
Index *int `json:"index"`
}
// CreatePage adds a page to a space (editor).
func (s *Service) CreatePage(ctx context.Context, c access.Caller, spaceID string, in CreatePageInput) (Page, error) {
a, err := s.spaceFor(ctx, c, spaceID)
if err != nil {
return Page{}, err
}
if err := access.EditPages(a.role); err != nil {
return Page{}, err
}
title, err := cleanTitle(in.Title)
if err != nil {
return Page{}, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
if err := checkParent(t, in.Parent, ""); err != nil {
return Page{}, err
}
siblings := t.children[in.Parent]
index := len(siblings)
if in.Index != nil {
index = *in.Index
}
pos, renumber := placement(siblings, index)
if err := s.renumber(ctx, renumber); err != nil {
return Page{}, err
}
body := map[string]any{
"workspace": a.space.Workspace, "space": a.space.ID, "title": title, "position": pos,
"creator": c.ID, "last_editor": c.ID,
}
if in.Parent != "" {
body["parent"] = in.Parent
}
rec, err := pocketbase.Create[pageRecord](ctx, s.pb, "pages", body)
if err != nil {
return Page{}, mapPB(err, "page not found")
}
return s.GetPage(ctx, c, rec.ID)
}
type UpdatePageInput struct {
Title *string `json:"title"`
Icon *string `json:"icon"`
}
// UpdatePage renames a page or changes its icon (editor).
func (s *Service) UpdatePage(ctx context.Context, c access.Caller, id string, in UpdatePageInput) (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")
}
patch := map[string]any{"last_editor": c.ID}
if in.Title != nil {
title, err := cleanTitle(*in.Title)
if err != nil {
return Page{}, err
}
patch["title"] = title
}
if in.Icon != nil {
icon := strings.TrimSpace(*in.Icon)
if len(icon) > 32 {
return Page{}, apperr.InvalidFields(map[string]string{"icon": "Icon is too long."})
}
patch["icon"] = icon
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch); err != nil {
return Page{}, mapPB(err, "page not found")
}
return s.GetPage(ctx, c, p.ID)
}
type MovePageInput struct {
// Parent is the new parent ("" = top level of the space).
Parent string `json:"parent"`
// Index among the new parent's other children.
Index int `json:"index"`
}
// MovePage moves a page (with its subtree) within its space (editor).
func (s *Service) MovePage(ctx context.Context, c access.Caller, id string, in MovePageInput) (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
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
if !t.live(p.ID) {
return Page{}, apperr.Invalid("restore the page from the trash first")
}
if err := checkParent(t, in.Parent, p.ID); err != nil {
return Page{}, err
}
siblings := make([]pageRecord, 0, len(t.children[in.Parent]))
for _, sib := range t.children[in.Parent] {
if sib.ID != p.ID {
siblings = append(siblings, sib)
}
}
pos, renumber := placement(siblings, in.Index)
if err := s.renumber(ctx, renumber); err != nil {
return Page{}, err
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"parent": in.Parent, "position": pos,
}); err != nil {
return Page{}, mapPB(err, "page not found")
}
return s.GetPage(ctx, c, p.ID)
}
// pbTime formats t the way PocketBase stores dates.
func pbTime(t time.Time) string { return t.UTC().Format("2006-01-02 15:04:05.000Z") }
// TrashPage moves a page and its subtree to the trash (editor). Idempotent.
func (s *Service) TrashPage(ctx context.Context, c access.Caller, id string) error {
p, a, err := s.pageFor(ctx, c, id)
if err != nil {
return err
}
if err := access.EditPages(a.role); err != nil {
return err
}
if p.DeletedAt != "" {
return nil
}
_, err = pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"deleted_at": pbTime(time.Now()), "last_editor": c.ID,
})
return mapPB(err, "page not found")
}
// RestorePage takes a page out of the trash (editor). If its parent is gone or
// still trashed, it goes to the end of the top level.
func (s *Service) RestorePage(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 s.GetPage(ctx, c, p.ID)
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
patch := map[string]any{"deleted_at": "", "last_editor": c.ID}
if p.Parent != "" && !t.live(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")
}
return s.GetPage(ctx, c, p.ID)
}
// ListTrash lists a space's trashed pages, newest first. Pages inside a
// trashed page are not listed separately: they come back with it.
func (s *Service) ListTrash(ctx context.Context, c access.Caller, spaceID string) ([]TrashedPage, error) {
a, err := s.spaceFor(ctx, c, spaceID)
if err != nil {
return nil, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return nil, err
}
out := []TrashedPage{}
for _, p := range t.byID {
if p.DeletedAt != "" && t.live(p.Parent) {
out = append(out, TrashedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, DeletedAt: p.DeletedAt})
}
}
sort.Slice(out, func(i, j int) bool { return out[i].DeletedAt > out[j].DeletedAt })
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)
if err != nil {
return err
}
if err := access.PurgePage(a.role); err != nil {
return err
}
if p.DeletedAt == "" {
return apperr.Invalid("move the page to the trash first")
}
return mapPB(s.pb.Delete(ctx, "pages", p.ID), "page not found")
}
+79
View File
@@ -0,0 +1,79 @@
package directory
import "strings"
// Sibling pages are ordered by a fractional index: a string key that sorts
// byte-wise (SQLite's default collation), so moving a page rewrites only that
// page. Keys use base-62 digits and never end in the zero digit, which leaves
// room for a key below any other.
const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// maxKeyLen is when to renumber siblings instead of growing keys further
// (pages.position allows 128 characters).
const maxKeyLen = 64
// keyBetween returns a key that sorts strictly between a and b. "" means no
// bound: keyBetween("", "") is the first key of an empty list.
func keyBetween(a, b string) string {
if b != "" {
n := 0
for n < len(b) && digitAt(a, n) == b[n] {
n++
}
if n > 0 {
return b[:n] + keyBetween(a[min(n, len(a)):], b[n:])
}
}
da := 0
if a != "" {
da = strings.IndexByte(digits, a[0])
}
db := len(digits)
if b != "" {
db = strings.IndexByte(digits, b[0])
}
if db-da > 1 {
return string(digits[(da+db+1)/2])
}
if len(b) > 1 {
return b[:1]
}
rest := ""
if a != "" {
rest = a[1:]
}
return string(digits[da]) + keyBetween(rest, "")
}
// digitAt is a's n-th byte, or the zero digit past its end.
func digitAt(a string, n int) byte {
if n < len(a) {
return a[n]
}
return digits[0]
}
// evenKeys returns n ascending keys spread evenly, all the same short length.
func evenKeys(n int) []string {
width, space := 1, len(digits)
for space < 2*(n+1) {
width++
space *= len(digits)
}
step := space / (n + 1)
keys := make([]string, n)
for i := range keys {
v := (i + 1) * step
b := make([]byte, width)
for j := width - 1; j >= 0; j-- {
b[j] = digits[v%len(digits)]
v /= len(digits)
}
// step >= 2, so bumping a trailing zero digit keeps keys distinct and ordered.
if b[width-1] == digits[0] {
b[width-1] = digits[1]
}
keys[i] = string(b)
}
return keys
}
+110
View File
@@ -0,0 +1,110 @@
package directory
import (
"fmt"
"math/rand/v2"
"slices"
"strings"
"testing"
)
func checkBetween(t *testing.T, a, b string) string {
t.Helper()
k := keyBetween(a, b)
if k <= a || (b != "" && k >= b) || strings.HasSuffix(k, "0") {
t.Fatalf("keyBetween(%q, %q) = %q", a, b, k)
}
return k
}
func TestKeyBetween(t *testing.T) {
first := checkBetween(t, "", "")
checkBetween(t, "", first)
checkBetween(t, first, "")
checkBetween(t, "V", "W")
checkBetween(t, "V", "V1")
checkBetween(t, "z", "")
checkBetween(t, "", "01")
checkBetween(t, "Vz", "W")
}
// TestKeyBetweenRandom inserts at random spots and checks the list stays sorted.
func TestKeyBetweenRandom(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
keys := []string{}
for range 5000 {
i := r.IntN(len(keys) + 1)
a, b := "", ""
if i > 0 {
a = keys[i-1]
}
if i < len(keys) {
b = keys[i]
}
keys = slices.Insert(keys, i, checkBetween(t, a, b))
}
if !slices.IsSorted(keys) {
t.Fatal("keys are not sorted")
}
}
// TestAppendGrowth: appending is the common case; keys must grow slowly.
func TestAppendGrowth(t *testing.T) {
last := ""
for range 300 {
last = checkBetween(t, last, "")
}
if len(last) > maxKeyLen {
t.Fatalf("300 appends made a %d-character key", len(last))
}
}
func TestEvenKeys(t *testing.T) {
for _, n := range []int{0, 1, 2, 30, 31, 61, 62, 1000, 5000} {
keys := evenKeys(n)
if len(keys) != n || !slices.IsSorted(keys) || len(slices.Compact(slices.Clone(keys))) != n {
t.Fatalf("evenKeys(%d) is not %d distinct sorted keys", n, n)
}
for _, k := range keys {
if strings.HasSuffix(k, "0") {
t.Fatalf("evenKeys(%d) produced %q", n, k)
}
}
if n > 1 {
checkBetween(t, keys[0], keys[1])
}
}
}
func recs(keys ...string) []pageRecord {
out := make([]pageRecord, len(keys))
for i, k := range keys {
out[i] = pageRecord{ID: fmt.Sprint("p", i), Position: k}
}
return out
}
func TestPlacement(t *testing.T) {
sib := recs("A", "M", "Z")
for index, want := range map[int][2]string{0: {"", "A"}, 1: {"A", "M"}, 3: {"Z", ""}, 99: {"Z", ""}, -5: {"", "A"}} {
key, renumber := placement(sib, index)
if key <= want[0] || (want[1] != "" && key >= want[1]) || renumber != nil {
t.Errorf("index %d: key %q, renumber %v", index, key, renumber)
}
}
// Keys at the length limit force a renumber that keeps the order.
long := strings.Repeat("z", maxKeyLen)
sib = recs("V", long)
key, renumber := placement(sib, 2)
if len(renumber) == 0 {
t.Fatal("expected a renumber")
}
order := []string{renumber["p0"], renumber["p1"], key}
if renumber["p0"] == "" {
order[0] = "V"
}
if !slices.IsSorted(order) || len(key) > 2 {
t.Fatalf("renumbered order %v", order)
}
}
+374
View File
@@ -0,0 +1,374 @@
package directory
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Spaces ----------------------------------------------------------------
type Space struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Slug string `json:"slug"`
Icon string `json:"icon"`
Description string `json:"description"`
Visibility string `json:"visibility"`
DefaultRole string `json:"defaultRole"`
// Role is the caller's effective space role after the cascade.
Role string `json:"role"`
Created string `json:"created"`
}
type spaceRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Slug string `json:"slug"`
Icon string `json:"icon"`
Description string `json:"description"`
Visibility string `json:"visibility"`
DefaultRole string `json:"default_role"`
Created string `json:"created"`
}
func (r spaceRecord) view(role string) Space {
def := r.DefaultRole
if !access.ValidDefaultRole(def) {
def = access.SpaceEditor
}
return Space{
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Slug: r.Slug, Icon: r.Icon, Description: r.Description,
Visibility: r.Visibility, DefaultRole: def, Role: role, Created: r.Created,
}
}
type spaceMemberRecord struct {
ID string `json:"id"`
Space string `json:"space"`
PrincipalID string `json:"principal_id"`
Role string `json:"role"`
}
// listAll pages through a whole collection query (PocketBase caps a page at 1000 records).
func listAll[T any](ctx context.Context, s *Service, collection string, opts pocketbase.ListOptions) ([]T, error) {
opts.PerPage = 1000
var out []T
for page := 1; ; page++ {
opts.Page = page
res, err := pocketbase.List[T](ctx, s.pb, collection, opts)
if err != nil {
return nil, err
}
out = append(out, res.Items...)
if page >= res.TotalPages || len(res.Items) == 0 {
return out, nil
}
}
}
// userSpaceMemberships lists a user's space memberships, in one workspace or ("" ) all.
func (s *Service) userSpaceMemberships(ctx context.Context, userID, wsID string) ([]spaceMemberRecord, error) {
filter := fmt.Sprintf("principal_type = 'user' && principal_id = '%s'", userID)
if wsID != "" {
filter += fmt.Sprintf(" && space.workspace = '%s'", wsID)
}
return listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{Filter: filter})
}
func (s *Service) spaceMembership(ctx context.Context, spaceID, userID string) (spaceMemberRecord, error) {
res, err := pocketbase.List[spaceMemberRecord](ctx, s.pb, "space_members", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("space = '%s' && principal_type = 'user' && principal_id = '%s'", spaceID, userID),
})
if err != nil || len(res.Items) == 0 {
return spaceMemberRecord{}, err
}
return res.Items[0], nil
}
// spaceAccess is a space with the caller's workspace and space roles.
type spaceAccess struct {
space spaceRecord
ws workspaceRecord
wsRole string
role string
}
// spaceFor loads a space with c's roles. A space c cannot open is reported as
// not found, like a workspace.
func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
if !validID(id) {
return spaceAccess{}, apperr.NotFound("space not found")
}
sp, err := pocketbase.Get[spaceRecord](ctx, s.pb, "spaces", id)
if err != nil {
return spaceAccess{}, mapPB(err, "space not found")
}
ws, err := s.getWorkspace(ctx, sp.Workspace)
if err != nil {
return spaceAccess{}, err
}
wsRole, err := s.effective(ctx, c, ws)
if err != nil {
return spaceAccess{}, err
}
var member spaceMemberRecord
if wsRole != "" && !access.AtLeast(wsRole, access.WorkspaceAdmin) {
if member, err = s.spaceMembership(ctx, sp.ID, c.ID); err != nil {
return spaceAccess{}, err
}
}
a := spaceAccess{space: sp, ws: ws, wsRole: wsRole, role: access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, member.Role)}
if err := access.ViewSpace(a.role); err != nil {
return spaceAccess{}, err
}
return a, nil
}
// ListSpaces lists the spaces of a workspace that c can open.
func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]Space, error) {
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return nil, err
}
spaces, err := listAll[spaceRecord](ctx, s, "spaces", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", ws.ID), Sort: "name",
})
if err != nil {
return nil, err
}
explicit := map[string]string{}
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
mine, err := s.userSpaceMemberships(ctx, c.ID, ws.ID)
if err != nil {
return nil, err
}
for _, m := range mine {
explicit[m.Space] = m.Role
}
}
out := []Space{}
for _, sp := range spaces {
if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" {
out = append(out, sp.view(role))
}
}
sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
return out, nil
}
// GetSpace returns one space with c's role.
func (s *Service) GetSpace(ctx context.Context, c access.Caller, id string) (Space, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return Space{}, err
}
return a.space.view(a.role), nil
}
type CreateSpaceInput struct {
Name string `json:"name"`
Description string `json:"description"`
Icon string `json:"icon"`
Visibility string `json:"visibility"`
}
// CreateSpace creates a space in a workspace (workspace admin or above).
func (s *Service) CreateSpace(ctx context.Context, c access.Caller, wsID string, in CreateSpaceInput) (Space, error) {
name, err := cleanName(in.Name, "Space")
if err != nil {
return Space{}, err
}
visibility := in.Visibility
if visibility == "" {
visibility = access.SpaceOpen
}
if visibility != access.SpaceOpen && visibility != access.SpacePrivate {
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
}
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return Space{}, err
}
if err := access.CreateSpace(wsRole); err != nil {
return Space{}, err
}
base := slugify(name, "space")
for i := 1; i <= 50; i++ {
slug := base
if i > 1 {
slug = fmt.Sprintf("%s-%d", base, i)
}
rec, err := pocketbase.Create[spaceRecord](ctx, s.pb, "spaces", map[string]any{
"workspace": ws.ID, "name": name, "slug": slug, "icon": strings.TrimSpace(in.Icon),
"description": strings.TrimSpace(in.Description), "visibility": visibility, "default_role": access.SpaceEditor,
})
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Data["slug"].Code == "validation_not_unique" {
continue
}
if err != nil {
return Space{}, mapPB(err, "space not found")
}
return rec.view(access.SpaceAdmin), nil
}
return Space{}, apperr.Conflict("could not find a free space address; try another name")
}
// UpdateSpaceInput changes only the fields that are set.
type UpdateSpaceInput struct {
Name *string `json:"name"`
Description *string `json:"description"`
Icon *string `json:"icon"`
Visibility *string `json:"visibility"`
DefaultRole *string `json:"defaultRole"`
}
// UpdateSpace changes a space's settings (space admin).
func (s *Service) UpdateSpace(ctx context.Context, c access.Caller, id string, in UpdateSpaceInput) (Space, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return Space{}, err
}
if err := access.ManageSpace(a.role); err != nil {
return Space{}, err
}
patch := map[string]any{}
if in.Name != nil {
name, err := cleanName(*in.Name, "Space")
if err != nil {
return Space{}, err
}
patch["name"] = name
}
if in.Description != nil {
patch["description"] = strings.TrimSpace(*in.Description)
}
if in.Icon != nil {
patch["icon"] = strings.TrimSpace(*in.Icon)
}
if in.Visibility != nil {
if *in.Visibility != access.SpaceOpen && *in.Visibility != access.SpacePrivate {
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
}
patch["visibility"] = *in.Visibility
}
if in.DefaultRole != nil {
if !access.ValidDefaultRole(*in.DefaultRole) {
return Space{}, apperr.InvalidFields(map[string]string{"defaultRole": "Default role must be editor, commenter or viewer."})
}
patch["default_role"] = *in.DefaultRole
}
if len(patch) == 0 {
return a.space.view(a.role), nil
}
rec, err := pocketbase.Update[spaceRecord](ctx, s.pb, "spaces", a.space.ID, patch)
if err != nil {
return Space{}, mapPB(err, "space not found")
}
return rec.view(a.role), nil
}
// DeleteSpace deletes a space with all of its pages (workspace admin).
func (s *Service) DeleteSpace(ctx context.Context, c access.Caller, id string) error {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return err
}
if err := access.DeleteSpace(a.wsRole); err != nil {
return err
}
return mapPB(s.pb.Delete(ctx, "spaces", a.space.ID), "space not found")
}
// ListSpaceMembers lists a space's explicit members (any space role may look).
// Workspace admins manage every space without being listed.
func (s *Service) ListSpaceMembers(ctx context.Context, c access.Caller, id string) ([]Member, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return nil, err
}
members, err := listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s' && principal_type = 'user'", a.space.ID),
})
if err != nil {
return nil, err
}
out := make([]Member, 0, len(members))
for _, m := range members {
u, err := s.getUser(ctx, m.PrincipalID)
if err != nil {
continue // a deleted user's leftover row
}
out = append(out, Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: m.Role})
}
sort.Slice(out, func(i, j int) bool { return out[i].User.Email < out[j].User.Email })
return out, nil
}
// SetSpaceMember adds a workspace member (by email) to a space or changes their role (space admin).
func (s *Service) SetSpaceMember(ctx context.Context, c access.Caller, id, email, role string) (Member, error) {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return Member{}, err
}
if err := access.ManageSpace(a.role); err != nil {
return Member{}, err
}
u, err := s.findUserByEmail(ctx, email)
if err != nil {
return Member{}, err
}
targetWsRole, err := s.effective(ctx, u.Caller(), a.ws)
if err != nil {
return Member{}, err
}
if err := access.SetSpaceMember(a.role, targetWsRole, role); err != nil {
return Member{}, err
}
current, err := s.spaceMembership(ctx, a.space.ID, u.ID)
if err != nil {
return Member{}, err
}
if current.ID != "" {
_, err = pocketbase.Update[spaceMemberRecord](ctx, s.pb, "space_members", current.ID, map[string]any{"role": role})
} else {
_, err = pocketbase.Create[spaceMemberRecord](ctx, s.pb, "space_members", map[string]any{
"space": a.space.ID, "principal_type": "user", "principal_id": u.ID, "role": role,
})
}
if err != nil {
return Member{}, mapPB(err, "space not found")
}
return Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: role}, nil
}
// RemoveSpaceMember removes a space membership (idempotent). Anyone may leave;
// removing others needs space admin.
func (s *Service) RemoveSpaceMember(ctx context.Context, c access.Caller, id, userID string) error {
a, err := s.spaceFor(ctx, c, id)
if err != nil {
return err
}
if userID != c.ID {
if err := access.ManageSpace(a.role); err != nil {
return err
}
}
if !validID(userID) {
return apperr.NotFound("member not found")
}
current, err := s.spaceMembership(ctx, a.space.ID, userID)
if err != nil || current.ID == "" {
return err
}
return mapPB(s.pb.Delete(ctx, "space_members", current.ID), "member not found")
}
+1
View File
@@ -136,6 +136,7 @@ func (a *api) routes(mux *http.ServeMux) {
})
a.directoryRoutes(mux)
a.spaceRoutes(mux)
}
func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool {
+3 -1
View File
@@ -91,10 +91,12 @@ func authRouter() http.Handler {
DB: fakeDB{},
Auth: fakeAuth{},
Directory: fakeDir{seen: &lastCaller},
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
Log: authRouterLog(),
})
}
func authRouterLog() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) }
func send(h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
if token != "" {
+2
View File
@@ -29,6 +29,8 @@ type DirectoryService interface {
ListMembers(ctx context.Context, c access.Caller, wsID string) ([]directory.Member, error)
SetMember(ctx context.Context, c access.Caller, wsID, email, role string) (directory.Member, error)
RemoveMember(ctx context.Context, c access.Caller, wsID, userID string) error
SpaceService
}
func caller(r *http.Request) access.Caller {
+127
View File
@@ -0,0 +1,127 @@
package httpapi
import (
"context"
"net/http"
"docwell/server/internal/access"
"docwell/server/internal/directory"
)
// SpaceService is the part of directory.Service that serves spaces and pages.
type SpaceService interface {
ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]directory.Space, error)
CreateSpace(ctx context.Context, c access.Caller, wsID string, in directory.CreateSpaceInput) (directory.Space, error)
GetSpace(ctx context.Context, c access.Caller, id string) (directory.Space, error)
UpdateSpace(ctx context.Context, c access.Caller, id string, in directory.UpdateSpaceInput) (directory.Space, error)
DeleteSpace(ctx context.Context, c access.Caller, id string) error
ListSpaceMembers(ctx context.Context, c access.Caller, id string) ([]directory.Member, error)
SetSpaceMember(ctx context.Context, c access.Caller, id, email, role string) (directory.Member, error)
RemoveSpaceMember(ctx context.Context, c access.Caller, id, userID string) error
ListPages(ctx context.Context, c access.Caller, spaceID string) ([]directory.PageNode, error)
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)
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)
ListTrash(ctx context.Context, c access.Caller, spaceID string) ([]directory.TrashedPage, error)
PurgePage(ctx context.Context, c access.Caller, id string) error
}
func (a *api) spaceRoutes(mux *http.ServeMux) {
// Spaces. Rights are resolved per space (see access.SpaceRole).
mux.HandleFunc("GET /api/v1/workspaces/{id}/spaces", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
list, err := a.dir.ListSpaces(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/workspaces/{id}/spaces", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.CreateSpaceInput
if !a.decode(w, r, &in) {
return
}
sp, err := a.dir.CreateSpace(r.Context(), caller(r), r.PathValue("id"), in)
a.respondStatus(w, http.StatusCreated, sp, err)
}))
mux.HandleFunc("GET /api/v1/spaces/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
sp, err := a.dir.GetSpace(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, sp, err)
}))
mux.HandleFunc("PATCH /api/v1/spaces/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.UpdateSpaceInput
if !a.decode(w, r, &in) {
return
}
sp, err := a.dir.UpdateSpace(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, sp, err)
}))
mux.HandleFunc("DELETE /api/v1/spaces/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.dir.DeleteSpace(r.Context(), caller(r), r.PathValue("id")))
}))
mux.HandleFunc("GET /api/v1/spaces/{id}/members", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
members, err := a.dir.ListSpaceMembers(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, members, err)
}))
mux.HandleFunc("PUT /api/v1/spaces/{id}/members", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Email, Role string }
if !a.decode(w, r, &in) {
return
}
m, err := a.dir.SetSpaceMember(r.Context(), caller(r), r.PathValue("id"), in.Email, in.Role)
a.respond(w, m, err)
}))
mux.HandleFunc("DELETE /api/v1/spaces/{id}/members/{userId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.dir.RemoveSpaceMember(r.Context(), caller(r), r.PathValue("id"), r.PathValue("userId")))
}))
// Page tree and trash.
mux.HandleFunc("GET /api/v1/spaces/{id}/pages", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
pages, err := a.dir.ListPages(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, pages, err)
}))
mux.HandleFunc("POST /api/v1/spaces/{id}/pages", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.CreatePageInput
if !a.decode(w, r, &in) {
return
}
p, err := a.dir.CreatePage(r.Context(), caller(r), r.PathValue("id"), in)
a.respondStatus(w, http.StatusCreated, p, err)
}))
mux.HandleFunc("GET /api/v1/spaces/{id}/trash", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
pages, err := a.dir.ListTrash(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("PATCH /api/v1/pages/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.UpdatePageInput
if !a.decode(w, r, &in) {
return
}
p, err := a.dir.UpdatePage(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, p, 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) {
return
}
p, err := a.dir.MovePage(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, p, err)
}))
mux.HandleFunc("POST /api/v1/pages/{id}/restore", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
p, err := a.dir.RestorePage(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, p, err)
}))
// DELETE moves to the trash; ?permanent=true purges a page that is already there.
mux.HandleFunc("DELETE /api/v1/pages/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("permanent") == "true" {
a.respondNoContent(w, a.dir.PurgePage(r.Context(), caller(r), r.PathValue("id")))
return
}
a.respondNoContent(w, a.dir.TrashPage(r.Context(), caller(r), r.PathValue("id")))
}))
}
+60
View File
@@ -0,0 +1,60 @@
package httpapi
import (
"context"
"testing"
"docwell/server/internal/access"
"docwell/server/internal/directory"
)
// pageDir records which page call the router made.
type pageDir struct {
fakeDir
calls *[]string
}
func (p pageDir) TrashPage(_ context.Context, _ access.Caller, id string) error {
*p.calls = append(*p.calls, "trash "+id)
return nil
}
func (p pageDir) PurgePage(_ context.Context, _ access.Caller, id string) error {
*p.calls = append(*p.calls, "purge "+id)
return nil
}
func (p pageDir) MovePage(_ context.Context, _ access.Caller, id string, in directory.MovePageInput) (directory.Page, error) {
*p.calls = append(*p.calls, "move "+id+" under "+in.Parent)
return directory.Page{ID: id, Parent: in.Parent}, nil
}
func TestPageRoutes(t *testing.T) {
var calls []string
h := NewRouter(Deps{
Version: "test", DB: fakeDB{}, Auth: fakeAuth{},
Directory: pageDir{fakeDir: fakeDir{seen: &lastCaller}, calls: &calls},
Log: authRouterLog(),
})
for _, req := range []struct{ method, path, body string }{
{"DELETE", "/api/v1/pages/p1", ""},
{"DELETE", "/api/v1/pages/p1?permanent=true", ""},
{"POST", "/api/v1/pages/p2/move", `{"parent":"p1","index":0}`},
} {
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"}
if len(calls) != len(want) {
t.Fatalf("calls = %v", calls)
}
for i := range want {
if calls[i] != want[i] {
t.Fatalf("calls = %v, want %v", calls, want)
}
}
if rec := send(h, "GET", "/api/v1/spaces/s1/pages", "", ""); rec.Code != 401 {
t.Fatalf("anonymous page list = %d", rec.Code)
}
}
@@ -82,6 +82,8 @@ type ListOptions struct {
Sort string
// Expand lists relations to inline, e.g. "organization" or "user,workspace".
Expand string
// Fields limits the returned fields, e.g. "id,title" (skips large columns).
Fields string
}
func (o ListOptions) values() url.Values {
@@ -101,6 +103,9 @@ func (o ListOptions) values() url.Values {
if o.Expand != "" {
v.Set("expand", o.Expand)
}
if o.Fields != "" {
v.Set("fields", o.Fields)
}
return v
}
+1 -1
View File
@@ -1,6 +1,6 @@
# Spike: yrs.wasm under wazero
Phase 0 go/no-go spike for ADR-3. Results and the decision are in [docs/adr/0003-yrs-wasm-wazero.md](../../docs/adr/0003-yrs-wasm-wazero.md).
Phase 0 go/no-go spike for ADR-3 (yrs compiled to WebAssembly under wazero). The answer was go.
This folder is outside `go.work` and the npm workspaces, so CI doesn't build it.
+4
View File
@@ -3,7 +3,11 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="theme-color" content="#12403C" />
<title>Docwell</title>
</head>
<body>
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#2f5fd0"/><path d="M10 8h7.5a7.5 7.5 0 0 1 0 15H10z" fill="none" stroke="#fff" stroke-width="3"/><path d="M10 26h12" stroke="#fff" stroke-width="3" stroke-linecap="round"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256" xmlns:c2pa="http://c2pa.org/manifest"><metadata><c2pa:manifest>AAAWgmp1bWIAAAAeanVtZGMycGEAEQAQgAAAqgA4m3EDYzJwYQAAABZcanVtYgAAAEdqdW1kYzJtYQARABCAAACqADibcQN1cm46YzJwYToyYTkxZWZl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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALine truncated

Before

Width:  |  Height:  |  Size: 281 B

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+24
View File
@@ -0,0 +1,24 @@
{
"name": "Docwell",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
},
{
"src": "/maskable-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"theme_color": "#12403C",
"background_color": "#12403C",
"display": "standalone"
}
@@ -0,0 +1,253 @@
<script setup lang="ts">
import { DwButton, DwCallout, DwIcon, DwLogo, useTheme, type ThemeMode } from "@docwell/ui";
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useFormErrors } from "../composables/useFormErrors";
import { useAuthStore } from "../stores/auth";
import { useSpacesStore } from "../stores/spaces";
import { atLeast, useWorkspacesStore } from "../stores/workspaces";
import PageTreeNode from "./PageTreeNode.vue";
import ServerStatus from "./ServerStatus.vue";
const auth = useAuthStore();
const workspaces = useWorkspacesStore();
const spaces = useSpacesStore();
const router = useRouter();
const route = useRoute();
const { mode } = useTheme();
const errors = useFormErrors();
const themes: ThemeMode[] = ["system", "light", "dark"];
const sidebarOpen = ref(false);
const error = ref("");
function showError(e: unknown) {
errors.show(e);
error.value = errors.message.value || Object.values(errors.fields.value)[0] || "";
}
onMounted(() => workspaces.load().catch(showError));
watch(
() => workspaces.current?.id,
(id) => id && spaces.load(id).catch(showError),
{ immediate: true },
);
watch(() => route.fullPath, () => (sidebarOpen.value = false));
const ws = computed(() => workspaces.current);
const canCreateSpace = computed(() => atLeast(ws.value?.role, "admin"));
// "New page" goes into the space on screen, else the first space the user can edit.
const targetSpace = computed(() =>
spaces.canEdit(spaces.active.space) ? spaces.active.space : spaces.items.find((s) => spaces.canEdit(s.id))?.id,
);
async function newPage(spaceId = targetSpace.value) {
if (!spaceId) return;
error.value = "";
try {
const page = await spaces.createPage(spaceId);
router.push({ name: "page", params: { id: page.id } });
} catch (e) {
showError(e);
}
}
function selectWorkspace(id: string) {
workspaces.select(id);
router.push({ name: "home" });
}
// Dropping a page on a space's header moves it to the end of the top level.
async function dropOnSpace(spaceId: string) {
const d = spaces.dragging;
spaces.dragging = null;
if (!d || d.spaceId !== spaceId) return;
try {
await spaces.move(spaceId, d.id, "", spaces.childrenOf(spaceId, "").filter((n) => n.id !== d.id).length);
} catch (e) {
showError(e);
}
}
const iconLink =
"grid size-control-sm shrink-0 cursor-pointer place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink";
const rowLink = "flex h-control-sm items-center gap-2 rounded-sm px-2 text-ink-muted hover:bg-surface-hover hover:text-ink";
function signOut() {
auth.logout();
router.replace({ name: "login" });
}
</script>
<template>
<div class="flex h-dvh">
<aside
class="fixed inset-y-0 left-0 z-20 flex w-sidebar flex-col border-r border-line bg-surface-sunken transition-transform duration-200 ease-out md:static md:translate-x-0"
:class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'"
>
<div class="flex h-12 shrink-0 items-center px-4">
<RouterLink to="/" class="rounded-sm" :aria-label="$t('app.name')"><DwLogo class="h-6" /></RouterLink>
</div>
<div class="space-y-2 px-3">
<div class="flex items-center gap-1">
<select
v-if="workspaces.items.length"
:value="ws?.id"
:aria-label="$t('sidebar.workspace')"
class="dw-input h-control-sm flex-1 px-2"
data-testid="workspace-select"
@change="selectWorkspace(($event.target as HTMLSelectElement).value)"
>
<option v-for="w in workspaces.items" :key="w.id" :value="w.id">{{ w.name }}</option>
</select>
<p v-else-if="workspaces.loaded" class="flex-1 px-1 text-ui-sm text-ink-muted">
{{ $t(auth.user?.organization || auth.user?.role === "superadmin" ? "sidebar.noWorkspaces" : "sidebar.noOrg") }}
</p>
<RouterLink
v-if="ws"
:to="{ name: 'workspace-settings', params: { id: ws.id } }"
:class="iconLink"
:aria-label="$t('workspace.settings')"
:title="$t('workspace.settings')"
>
<DwIcon name="settings" :size="16" />
</RouterLink>
<RouterLink
v-if="workspaces.canCreate()"
to="/workspaces/new"
:class="iconLink"
:aria-label="$t('workspace.newTitle')"
:title="$t('workspace.newTitle')"
>
<DwIcon name="plus" :size="16" />
</RouterLink>
</div>
<button
class="flex h-control-sm w-full items-center gap-2 rounded-sm border border-line bg-surface px-2 text-left text-ui-md text-ink-muted hover:bg-surface-hover"
>
<DwIcon name="search" :size="16" />
<span class="flex-1">{{ $t("app.search") }}</span>
<kbd class="font-mono text-[11px] leading-4">Ctrl K</kbd>
</button>
</div>
<nav class="mt-5 flex-1 space-y-5 overflow-y-auto px-3" data-testid="space-list">
<DwCallout v-if="error" tone="danger" size="ui">{{ error }}</DwCallout>
<template v-if="ws">
<section v-for="s in spaces.items" :key="s.id">
<div
class="group flex h-control-sm items-center gap-1 rounded-sm pl-2"
@dragover="spaces.dragging?.spaceId === s.id && $event.preventDefault()"
@drop.prevent="dropOnSpace(s.id)"
>
<button
class="dw-label flex min-w-0 flex-1 cursor-pointer items-center gap-1 text-left hover:text-ink"
:aria-expanded="spaces.spaceOpen(s.id)"
@click="spaces.toggleSpace(s.id)"
>
<span class="truncate">{{ s.icon ? `${s.icon} ` : "" }}{{ s.name }}</span>
<DwIcon v-if="s.visibility === 'private'" name="lock" :size="12" :label="$t('space.private')" />
</button>
<RouterLink
:to="{ name: 'space', params: { id: s.id } }"
:class="[iconLink, 'size-6 opacity-0 group-hover:opacity-100 focus-visible:opacity-100']"
:aria-label="$t('space.open', { name: s.name })"
:title="$t('space.open', { name: s.name })"
>
<DwIcon name="open" :size="14" />
</RouterLink>
<button
v-if="spaces.canEdit(s.id)"
:class="[iconLink, 'size-6']"
:aria-label="$t('sidebar.addPage')"
:title="$t('sidebar.addPage')"
@click="newPage(s.id)"
>
<DwIcon name="plus" :size="14" />
</button>
</div>
<template v-if="spaces.spaceOpen(s.id)">
<ul class="mt-0.5 flex flex-col gap-px" role="tree" :aria-label="s.name" data-testid="page-tree">
<PageTreeNode
v-for="n in spaces.childrenOf(s.id, '')"
:key="n.id"
:space-id="s.id"
:node="n"
:depth="0"
@error="showError"
/>
</ul>
<p v-if="spaces.trees[s.id] && !spaces.trees[s.id]!.length" class="px-2 py-1 text-ui-sm text-ink-muted">
{{ $t("space.noPages") }}
</p>
<RouterLink :to="{ name: 'trash', params: { id: s.id } }" :class="rowLink">
<DwIcon name="trash" :size="16" />
{{ $t("sidebar.trash") }}
</RouterLink>
</template>
</section>
<p v-if="spaces.loaded && !spaces.items.length" class="px-2 text-ui-sm text-ink-muted">{{ $t("sidebar.noSpaces") }}</p>
<RouterLink v-if="canCreateSpace" :to="{ name: 'new-space', params: { id: ws.id } }" :class="rowLink">
<DwIcon name="plus" :size="16" />
{{ $t("space.new") }}
</RouterLink>
</template>
</nav>
<div class="space-y-3 border-t border-line p-3">
<div v-if="auth.user" class="flex items-center gap-2">
<span
class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-ui-sm font-semibold text-on-primary"
aria-hidden="true"
>
{{ auth.user.name.slice(0, 1).toUpperCase() }}
</span>
<RouterLink to="/settings/organization" class="min-w-0 flex-1 rounded-sm">
<div class="truncate font-medium text-ink" data-testid="user-name">{{ auth.user.name }}</div>
<div class="truncate text-ui-sm text-ink-muted" data-testid="user-org">
{{ $t(`roles.${auth.user.role}`) }}{{ auth.user.organizationName ? ` · ${auth.user.organizationName}` : "" }}
</div>
</RouterLink>
<DwButton
variant="ghost"
size="sm"
icon="sign-out"
:aria-label="$t('auth.signOut')"
:title="$t('auth.signOut')"
@click="signOut"
/>
</div>
<label class="flex items-center justify-between gap-2">
<span class="text-ink-muted">{{ $t("app.theme") }}</span>
<select v-model="mode" class="dw-input h-control-sm px-2 text-ui-sm">
<option v-for="t in themes" :key="t" :value="t">{{ $t(`theme.${t}`) }}</option>
</select>
</label>
<ServerStatus />
</div>
</aside>
<div v-if="sidebarOpen" class="fixed inset-0 z-10 bg-black/40 md:hidden" @click="sidebarOpen = false" />
<main class="flex min-w-0 flex-1 flex-col bg-surface">
<header class="flex h-12 shrink-0 items-center justify-between gap-2 border-b border-line px-4">
<DwButton
class="md:hidden"
variant="ghost"
size="sm"
icon="menu"
:aria-label="$t('sidebar.menu')"
@click="sidebarOpen = true"
/>
<span class="min-w-0 flex-1" />
<DwButton v-if="targetSpace" variant="primary" icon="plus" @click="newPage()">{{ $t("app.newPage") }}</DwButton>
</header>
<div class="flex-1 overflow-y-auto">
<RouterView @error="showError" />
</div>
</main>
</div>
</template>
+18 -12
View File
@@ -1,20 +1,26 @@
<script setup lang="ts">
import { DwLogo } from "@docwell/ui";
defineProps<{ title: string }>();
</script>
<template>
<div class="grid min-h-dvh place-items-center bg-surface-muted px-4 py-10">
<div class="w-full max-w-sm">
<div class="mb-6 flex items-center justify-center gap-2 text-lg font-semibold">
<img src="/favicon.svg" alt="" class="size-6" />
{{ $t("app.name") }}
</div>
<div class="rounded-xl border border-border bg-surface p-6 shadow-sm">
<h1 class="mb-5 text-xl font-semibold">{{ title }}</h1>
<slot />
</div>
<div class="mt-4 text-center text-sm text-fg-muted">
<slot name="footer" />
<div class="grid min-h-dvh lg:grid-cols-[minmax(0,5fr)_minmax(0,7fr)]">
<!-- The sign-in screens are a brand moment: Ink Well with the reversed logo. -->
<aside class="hidden flex-col justify-between bg-well p-12 text-white lg:flex">
<DwLogo reversed class="h-10 self-start" />
<p class="max-w-sm font-serif text-doc-h2 text-white/90">{{ $t("auth.tagline") }}</p>
</aside>
<div class="grid place-items-center bg-surface-sunken px-4 py-10">
<div class="w-full max-w-sm">
<div class="mb-8 flex justify-center lg:hidden"><DwLogo class="h-8" /></div>
<div class="rounded-md border border-line bg-surface-raised p-6">
<h1 class="mb-5 text-ui-lg">{{ title }}</h1>
<slot />
</div>
<div class="mt-4 text-center text-ui-md text-ink-muted">
<slot name="footer" />
</div>
</div>
</div>
</div>
+13 -16
View File
@@ -1,22 +1,19 @@
<script setup lang="ts">
defineProps<{ label: string; type?: string; autocomplete?: string; error?: string; required?: boolean }>();
import { DwTextField } from "@docwell/ui";
defineProps<{ label: string; type?: string; autocomplete?: string; error?: string; hint?: string; required?: boolean }>();
const model = defineModel<string>({ default: "" });
const id = `f-${Math.random().toString(36).slice(2, 9)}`;
</script>
<template>
<div class="space-y-1">
<label :for="id" class="block text-sm font-medium">{{ label }}</label>
<input
:id="id"
v-model="model"
:type="type ?? 'text'"
:autocomplete="autocomplete"
:required="required"
:aria-invalid="!!error"
class="w-full rounded-md border border-border bg-surface px-3 py-2 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20"
:class="{ 'border-red-500': error }"
/>
<p v-if="error" class="text-xs text-red-600">{{ error }}</p>
</div>
<DwTextField
v-model="model"
:label="label"
:type="type ?? 'text'"
:autocomplete="autocomplete"
:required="required"
:error="error"
:hint="hint"
class="w-full"
/>
</template>
@@ -0,0 +1,25 @@
<script setup lang="ts" generic="Item extends { id: string; title: string; icon: string }">
import { DwIcon } from "@docwell/ui";
// A bordered list of pages (children of a page, a space's top level, the trash).
defineProps<{ items: Item[] }>();
</script>
<template>
<ul class="divide-y divide-line rounded-md border border-line bg-surface-raised">
<li v-for="p in items" :key="p.id" class="flex min-h-11 flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1.5">
<RouterLink
:to="{ name: 'page', params: { id: p.id } }"
class="flex min-w-0 flex-1 items-center gap-2 rounded-xs py-1 text-ink hover:text-accent"
>
<span v-if="p.icon" class="w-4 text-center">{{ p.icon }}</span>
<DwIcon v-else name="page" :size="16" class="text-ink-muted" />
<span class="min-w-0">
<span class="block truncate">{{ p.title || $t("home.untitled") }}</span>
<span v-if="$slots.meta" class="block text-ui-sm text-ink-muted"><slot name="meta" :item="p" /></span>
</span>
</RouterLink>
<span v-if="$slots.actions" class="flex shrink-0 gap-2"><slot name="actions" :item="p" /></span>
</li>
</ul>
</template>
+15 -7
View File
@@ -1,16 +1,24 @@
<script setup lang="ts">
import { DwIcon } from "@docwell/ui";
defineProps<{ title: string; subtitle?: string }>();
</script>
<template>
<div class="min-h-dvh bg-surface-muted">
<header class="flex h-12 items-center gap-3 border-b border-border bg-surface px-4">
<RouterLink to="/" class="text-sm text-fg-muted hover:text-fg">← {{ $t("common.back") }}</RouterLink>
<div class="min-h-dvh bg-surface-sunken">
<header class="flex h-12 items-center gap-3 border-b border-line bg-surface px-4">
<RouterLink
to="/"
class="inline-flex h-control-sm items-center gap-1 rounded-sm px-2 text-ui-md text-ink-muted hover:bg-surface-hover hover:text-ink"
>
<DwIcon name="chevron-right" :size="16" class="rotate-180" />
{{ $t("common.back") }}
</RouterLink>
</header>
<main class="mx-auto max-w-3xl px-4 py-8">
<h1 class="text-2xl font-semibold">{{ title }}</h1>
<p v-if="subtitle" class="mt-1 text-sm text-fg-muted">{{ subtitle }}</p>
<div class="mt-6 space-y-6">
<main class="mx-auto max-w-doc px-4 py-8 sm:px-6">
<h1 class="text-2xl font-semibold tracking-tight">{{ title }}</h1>
<p v-if="subtitle" class="mt-1 text-ui-md text-ink-muted">{{ subtitle }}</p>
<div class="mt-8 space-y-8">
<slot />
</div>
</main>
@@ -0,0 +1,128 @@
<script setup lang="ts">
import type { PageNode } from "@docwell/api-client";
import { DwButton, DwTreeItem } from "@docwell/ui";
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { dropPlacement, zoneAt, type DropZone } from "../lib/tree";
import { useSpacesStore } from "../stores/spaces";
const props = defineProps<{ spaceId: string; node: PageNode; depth: number }>();
const emit = defineEmits<{ error: [err: unknown] }>();
const spaces = useSpacesStore();
const router = useRouter();
const kids = computed(() => spaces.childrenOf(props.spaceId, props.node.id));
const open = computed(() => spaces.isExpanded(props.node.id));
const editable = computed(() => spaces.canEdit(props.spaceId));
const active = computed(() => spaces.active.page === props.node.id);
const zone = ref<DropZone | null>(null);
function onDragStart(e: DragEvent) {
spaces.dragging = { spaceId: props.spaceId, id: props.node.id };
e.dataTransfer?.setData("text/plain", props.node.id);
if (e.dataTransfer) e.dataTransfer.effectAllowed = "move";
}
// Pages move only within their space; a drop is allowed when it changes something valid.
function placement(z: DropZone) {
const d = spaces.dragging;
if (!d || d.spaceId !== props.spaceId) return null;
return dropPlacement(spaces.trees[props.spaceId] ?? [], d.id, props.node.id, z);
}
function onDragOver(e: DragEvent) {
const el = e.currentTarget as HTMLElement;
const z = zoneAt(e.offsetY, el.clientHeight);
zone.value = placement(z) ? z : null;
if (zone.value) e.preventDefault();
}
async function onDrop() {
const z = zone.value;
zone.value = null;
const d = spaces.dragging;
const to = z && placement(z);
spaces.dragging = null;
if (!d || !to) return;
try {
await spaces.move(props.spaceId, d.id, to.parent, to.index);
} catch (e) {
emit("error", e);
}
}
async function addChild() {
try {
const page = await spaces.createPage(props.spaceId, props.node.id);
router.push({ name: "page", params: { id: page.id } });
} catch (e) {
emit("error", e);
}
}
async function trash() {
try {
await spaces.trash(props.spaceId, props.node.id);
if (active.value) router.push({ name: "space", params: { id: props.spaceId } });
} catch (e) {
emit("error", e);
}
}
const dropClass = computed(() => {
switch (zone.value) {
case "before":
return "shadow-[inset_0_2px_0_var(--color-focus-ring)]";
case "after":
return "shadow-[inset_0_-2px_0_var(--color-focus-ring)]";
case "inside":
return "bg-accent-soft";
}
return "";
});
</script>
<template>
<li>
<DwTreeItem
:title="node.title || $t('home.untitled')"
:depth="depth"
:has-children="kids.length > 0"
:expanded="open"
:active="active"
:toggle-label="open ? $t('sidebar.collapse') : $t('sidebar.expand')"
:class="dropClass"
:draggable="editable"
data-testid="tree-row"
@toggle="spaces.setExpanded(node.id, !open)"
@dragstart="onDragStart"
@dragend="spaces.dragging = null"
@dragover="onDragOver"
@dragleave="zone = null"
@drop.prevent="onDrop"
>
<RouterLink
:to="{ name: 'page', params: { id: node.id } }"
class="block truncate rounded-xs"
:class="active ? 'text-accent' : 'text-inherit'"
:aria-current="active ? 'page' : undefined"
>
<span v-if="node.icon" class="mr-1">{{ node.icon }}</span>{{ node.title || $t("home.untitled") }}
</RouterLink>
<template v-if="editable" #actions>
<DwButton variant="ghost" size="sm" icon="plus" class="!size-6" :aria-label="$t('sidebar.addSubpage')" :title="$t('sidebar.addSubpage')" @click="addChild" />
<DwButton variant="ghost" size="sm" icon="trash" class="!size-6" :aria-label="$t('page.moveToTrash')" :title="$t('page.moveToTrash')" @click="trash" />
</template>
</DwTreeItem>
<ul v-if="open && kids.length" role="group" class="mt-px flex flex-col gap-px">
<PageTreeNode
v-for="k in kids"
:key="k.id"
:space-id="spaceId"
:node="k"
:depth="depth + 1"
@error="emit('error', $event)"
/>
</ul>
</li>
</template>
@@ -16,10 +16,10 @@ onMounted(async () => {
</script>
<template>
<div class="flex items-center gap-2 text-xs text-fg-muted" data-testid="server-status">
<div class="flex items-center gap-2 text-ui-sm text-ink-muted" data-testid="server-status">
<span
class="size-2 rounded-full"
:class="failed ? 'bg-red-500' : version ? 'bg-emerald-500' : 'bg-fg-muted/40'"
:class="failed ? 'bg-danger' : version ? 'bg-success' : 'bg-ink-faint'"
aria-hidden="true"
/>
<span v-if="version">{{ $t("home.serverOnline", { version }) }}</span>
+9
View File
@@ -11,5 +11,14 @@ export function createDocwellI18n() {
locale: (supportedLocales as readonly string[]).includes(preferred) ? preferred : "en",
fallbackLocale: "en",
messages: { en, pl },
pluralRules: {
// Polish: 1 strona, 2-4 strony (but 12-14 stron), otherwise stron.
pl: (n: number) => {
if (n === 1) return 0;
const ones = n % 10;
const tens = n % 100;
return ones >= 2 && ones <= 4 && (tens < 12 || tens > 14) ? 1 : 2;
},
},
});
}
+50
View File
@@ -0,0 +1,50 @@
import type { PageNode } from "@docwell/api-client";
import { describe, expect, it } from "vitest";
import { applyMove, childrenByParent, dropPlacement, isWithin, zoneAt } from "./tree";
const node = (id: string, parent = ""): PageNode => ({ id, parent, title: id, icon: "", position: "", updated: "" });
// a
// a1
// a1x
// a2
// b
const nodes = [node("a"), node("a1", "a"), node("a1x", "a1"), node("a2", "a"), node("b")];
describe("page tree helpers", () => {
it("groups children by parent in order", () => {
const children = childrenByParent(nodes);
expect(children.get("")!.map((n) => n.id)).toEqual(["a", "b"]);
expect(children.get("a")!.map((n) => n.id)).toEqual(["a1", "a2"]);
});
it("knows subtrees", () => {
expect(isWithin(nodes, "a1x", "a")).toBe(true);
expect(isWithin(nodes, "a", "a")).toBe(true);
expect(isWithin(nodes, "b", "a")).toBe(false);
});
it("splits a row into drop zones", () => {
expect(zoneAt(2, 40)).toBe("before");
expect(zoneAt(20, 40)).toBe("inside");
expect(zoneAt(38, 40)).toBe("after");
});
it("computes move arguments for drops", () => {
expect(dropPlacement(nodes, "b", "a", "before")).toEqual({ parent: "", index: 0 });
expect(dropPlacement(nodes, "b", "a1", "after")).toEqual({ parent: "a", index: 1 });
expect(dropPlacement(nodes, "b", "a1", "inside")).toEqual({ parent: "a1", index: 1 });
// Moving down among the same siblings: the index excludes the page itself.
expect(dropPlacement(nodes, "a1", "a2", "after")).toEqual({ parent: "a", index: 1 });
});
it("refuses drops onto itself or its own subtree", () => {
expect(dropPlacement(nodes, "a", "a", "inside")).toBeNull();
expect(dropPlacement(nodes, "a", "a1x", "after")).toBeNull();
});
it("applies a move with the subtree attached", () => {
const moved = applyMove(nodes, "a1", "b", 0);
expect(moved.map((n) => `${n.id}<${n.parent}`)).toEqual(["a<", "a2<a", "b<", "a1<b", "a1x<a1"]);
});
});
+75
View File
@@ -0,0 +1,75 @@
import type { PageNode } from "@docwell/api-client";
/** Children of each page ("" = top level), in the order the server sent them. */
export function childrenByParent(nodes: PageNode[]): Map<string, PageNode[]> {
const map = new Map<string, PageNode[]>();
for (const n of nodes) {
const list = map.get(n.parent);
if (list) list.push(n);
else map.set(n.parent, [n]);
}
return map;
}
/** Whether page id is ancestor itself or lies somewhere under it. */
export function isWithin(nodes: PageNode[], id: string, ancestor: string): boolean {
const parentOf = new Map(nodes.map((n) => [n.id, n.parent]));
for (let cur: string | undefined = id, depth = 0; cur && depth < 1000; cur = parentOf.get(cur), depth++) {
if (cur === ancestor) return true;
}
return false;
}
export type DropZone = "before" | "inside" | "after";
/** The zone of a row the pointer is over: top quarter, middle, bottom quarter. */
export function zoneAt(offsetY: number, height: number): DropZone {
if (offsetY < height / 4) return "before";
if (offsetY > (height * 3) / 4) return "after";
return "inside";
}
/**
* Where dropping page dragged onto target (in zone) moves it, as the server's
* move arguments: a parent ("" = top level) and an index among the parent's
* other children. Null when the drop is not allowed (onto itself or into its
* own subtree).
*/
export function dropPlacement(
nodes: PageNode[],
dragged: string,
target: string,
zone: DropZone,
): { parent: string; index: number } | null {
if (dragged === target || isWithin(nodes, target, dragged)) return null;
const children = childrenByParent(nodes);
const node = nodes.find((n) => n.id === target);
if (!node) return null;
if (zone === "inside") {
const others = (children.get(target) ?? []).filter((n) => n.id !== dragged);
return { parent: target, index: others.length };
}
const siblings = (children.get(node.parent) ?? []).filter((n) => n.id !== dragged);
const at = siblings.findIndex((n) => n.id === target);
return { parent: node.parent, index: zone === "before" ? at : at + 1 };
}
/** Applies a move locally (optimistic update) and returns the new flat list in tree order. */
export function applyMove(nodes: PageNode[], id: string, parent: string, index: number): PageNode[] {
const moving = nodes.find((n) => n.id === id);
if (!moving) return nodes;
const children = childrenByParent(nodes.filter((n) => n.id !== id));
const siblings = children.get(parent) ?? [];
siblings.splice(Math.min(Math.max(index, 0), siblings.length), 0, { ...moving, parent });
children.set(parent, siblings);
// The moved page's own children are still listed under its id, so its subtree follows it.
const out: PageNode[] = [];
const walk = (p: string) => {
for (const n of children.get(p) ?? []) {
out.push(n);
walk(n.id);
}
};
walk("");
return out;
}
+72 -7
View File
@@ -3,14 +3,23 @@
"name": "Docwell",
"search": "Search",
"newPage": "New page",
"settings": "Settings"
"settings": "Settings",
"theme": "Theme"
},
"sidebar": {
"favorites": "Favorites",
"trash": "Trash",
"workspaces": "Workspaces",
"noWorkspaces": "No workspaces yet.",
"noOrg": "Join or create an organization to get workspaces."
"noOrg": "Join or create an organization to get workspaces.",
"workspace": "Workspace",
"spaces": "Spaces",
"noSpaces": "No spaces yet.",
"addPage": "Add a page",
"addSubpage": "Add a page inside",
"expand": "Expand",
"collapse": "Collapse",
"menu": "Menu"
},
"home": {
"untitled": "Untitled",
@@ -36,8 +45,8 @@
"forgot": "Forgot password?",
"emailCode": "Email me a sign-in code",
"code": "Code",
"codeHint": "We sent a sign-in code to {email}.",
"mfaHint": "Your account needs a second step. We sent a code to {email}.",
"codeHint": "A sign-in code is on its way to {email}.",
"mfaHint": "Your account needs a second step. A code is on its way to {email}.",
"noAccount": "No account yet?"
},
"signup": {
@@ -48,7 +57,7 @@
},
"forgot": {
"title": "Reset password",
"hint": "Enter your email and we will send you a link to choose a new password.",
"hint": "Enter your email to get a link for choosing a new password.",
"submit": "Send reset link",
"sent": "If an account exists for {email}, a reset link is on its way."
},
@@ -61,7 +70,8 @@
"verify": {
"title": "Verify email",
"done": "Your email address is verified."
}
},
"tagline": "Write it once, find it forever."
},
"errors": {
"invalid_credentials": "Wrong email or password.",
@@ -73,7 +83,7 @@
"invalid_token": "This link is invalid or has expired.",
"mfa_required": "A second sign-in step is required.",
"network": "Can't reach the server. Check your connection.",
"unknown": "Something went wrong. Please try again.",
"unknown": "The server could not finish this request. Reload the page and try again.",
"conflict": "That conflicts with existing data.",
"not_found": "Not found.",
"invalid": "That request is not valid."
@@ -136,5 +146,60 @@
"member": "Member",
"guest": "Guest"
}
},
"space": {
"new": "New space",
"newHint": "Spaces group pages, for example per team or project.",
"name": "Space name",
"description": "Description",
"visibility": "Who can open it",
"open": "Open {name}",
"openHint": "Every workspace member can open it, with the role below.",
"private": "Private",
"privateHint": "Only workspace admins and the people you add can open it.",
"create": "Create space",
"settings": "Space settings",
"openPages": "Open the space's pages",
"yourRole": "Your role: {role}",
"defaultRole": "Role for workspace members",
"defaultRoleHint": "Guests never get it; add them as members instead.",
"members": "Members",
"membersHint": "Workspace admins manage every space without being listed here.",
"noMembers": "No members yet.",
"notFound": "This space does not exist or you don't have access to it.",
"delete": "Delete space",
"deleteHint": "Deletes all of its pages, including the trash. This cannot be undone.",
"confirmDelete": "Delete {name} with all of its pages?",
"pages": "Pages",
"noPages": "No pages yet.",
"pageCount": "{n} page | {n} pages",
"none": "You don't have access to any space here yet.",
"noneAdmin": "Create the first space to start writing pages.",
"roles": {
"admin": "Admin",
"editor": "Editor",
"commenter": "Commenter",
"viewer": "Viewer"
}
},
"page": {
"title": "Page title",
"breadcrumbs": "Breadcrumbs",
"subpages": "Pages inside",
"noSubpages": "No pages inside yet.",
"moveToTrash": "Move to trash",
"inTrash": "This page is in the trash.",
"parentInTrash": "A page above this one is in the trash.",
"restore": "Restore",
"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.",
"notFound": "This page does not exist or you don't have access to it."
},
"trash": {
"hint": "Pages inside a trashed page come back when you restore it.",
"empty": "The trash is empty.",
"deletedAt": "Deleted {date}"
}
}
+72 -7
View File
@@ -3,14 +3,23 @@
"name": "Docwell",
"search": "Szukaj",
"newPage": "Nowa strona",
"settings": "Ustawienia"
"settings": "Ustawienia",
"theme": "Motyw"
},
"sidebar": {
"favorites": "Ulubione",
"trash": "Kosz",
"workspaces": "Obszary robocze",
"noWorkspaces": "Brak obszarów roboczych.",
"noOrg": "Dołącz do organizacji lub ją utwórz, aby mieć obszary robocze."
"noOrg": "Dołącz do organizacji lub ją utwórz, aby mieć obszary robocze.",
"workspace": "Obszar roboczy",
"spaces": "Przestrzenie",
"noSpaces": "Brak przestrzeni.",
"addPage": "Dodaj stronę",
"addSubpage": "Dodaj stronę wewnątrz",
"expand": "Rozwiń",
"collapse": "Zwiń",
"menu": "Menu"
},
"home": {
"untitled": "Bez tytułu",
@@ -36,8 +45,8 @@
"forgot": "Nie pamiętasz hasła?",
"emailCode": "Wyślij mi kod logowania",
"code": "Kod",
"codeHint": "Wysłaliśmy kod logowania na {email}.",
"mfaHint": "Twoje konto wymaga drugiego kroku. Wysłaliśmy kod na {email}.",
"codeHint": "Kod logowania jest w drodze na {email}.",
"mfaHint": "Twoje konto wymaga drugiego kroku. Kod jest w drodze na {email}.",
"noAccount": "Nie masz konta?"
},
"signup": {
@@ -48,7 +57,7 @@
},
"forgot": {
"title": "Resetuj hasło",
"hint": "Podaj swój e-mail, a wyślemy link do ustawienia nowego hasła.",
"hint": "Podaj swój e-mail, aby otrzymać link do ustawienia nowego hasła.",
"submit": "Wyślij link",
"sent": "Jeśli konto {email} istnieje, link do resetu jest w drodze."
},
@@ -61,7 +70,8 @@
"verify": {
"title": "Weryfikacja e-maila",
"done": "Twój adres e-mail został zweryfikowany."
}
},
"tagline": "Zapisz raz, znajdź zawsze."
},
"errors": {
"invalid_credentials": "Nieprawidłowy e-mail lub hasło.",
@@ -73,7 +83,7 @@
"invalid_token": "Ten link jest nieprawidłowy lub wygasł.",
"mfa_required": "Wymagany jest drugi krok logowania.",
"network": "Brak połączenia z serwerem.",
"unknown": "Coś poszło nie tak. Spróbuj ponownie.",
"unknown": "Serwer nie dokończył tego żądania. Odśwież stronę i spróbuj ponownie.",
"conflict": "To koliduje z istniejącymi danymi.",
"not_found": "Nie znaleziono.",
"invalid": "Nieprawidłowe żądanie."
@@ -136,5 +146,60 @@
"member": "Członek",
"guest": "Gość"
}
},
"space": {
"new": "Nowa przestrzeń",
"newHint": "Przestrzenie grupują strony, na przykład według zespołu lub projektu.",
"name": "Nazwa przestrzeni",
"description": "Opis",
"visibility": "Kto może ją otworzyć",
"open": "Otwórz {name}",
"openHint": "Każdy członek obszaru roboczego może ją otworzyć, z rolą poniżej.",
"private": "Prywatna",
"privateHint": "Tylko administratorzy obszaru roboczego i dodane osoby mogą ją otworzyć.",
"create": "Utwórz przestrzeń",
"settings": "Ustawienia przestrzeni",
"openPages": "Otwórz strony przestrzeni",
"yourRole": "Twoja rola: {role}",
"defaultRole": "Rola członków obszaru roboczego",
"defaultRoleHint": "Goście jej nie dostają; dodaj ich jako członków.",
"members": "Członkowie",
"membersHint": "Administratorzy obszaru roboczego zarządzają każdą przestrzenią, nie będąc tu wymienieni.",
"noMembers": "Brak członków.",
"notFound": "Ta przestrzeń nie istnieje lub nie masz do niej dostępu.",
"delete": "Usuń przestrzeń",
"deleteHint": "Usuwa wszystkie jej strony, także z kosza. Tego nie można cofnąć.",
"confirmDelete": "Usunąć {name} ze wszystkimi stronami?",
"pages": "Strony",
"noPages": "Brak stron.",
"pageCount": "{n} strona | {n} strony | {n} stron",
"none": "Nie masz jeszcze dostępu do żadnej przestrzeni.",
"noneAdmin": "Utwórz pierwszą przestrzeń, aby zacząć pisać strony.",
"roles": {
"admin": "Administrator",
"editor": "Edytor",
"commenter": "Komentujący",
"viewer": "Czytelnik"
}
},
"page": {
"title": "Tytuł strony",
"breadcrumbs": "Ścieżka",
"subpages": "Strony wewnątrz",
"noSubpages": "Brak stron wewnątrz.",
"moveToTrash": "Przenieś do kosza",
"inTrash": "Ta strona jest w koszu.",
"parentInTrash": "Strona nadrzędna jest w koszu.",
"restore": "Przywróć",
"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.",
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu."
},
"trash": {
"hint": "Strony wewnątrz przywróconej strony wracają razem z nią.",
"empty": "Kosz jest pusty.",
"deletedAt": "Usunięto {date}"
}
}
+3 -2
View File
@@ -21,8 +21,9 @@ export const webPlatform: Platform = {
kind: "web",
async loadConfig() {
const res = await fetch("/config.json", { cache: "no-cache" });
if (!res.ok) {
// Vite dev server: no docwell-web in front, use the dev proxy.
if (!res.ok || !res.headers.get("content-type")?.includes("json")) {
// Vite dev server: no docwell-web in front (its SPA fallback answers with
// index.html), so use the dev proxy.
return { apiUrl: "", collabUrl: "", version: "dev" };
}
return (await res.json()) as RuntimeConfig;
+23 -1
View File
@@ -17,7 +17,29 @@ export function createDocwellRouter(platform: Platform) {
// where path-based history does not work.
history: platform.kind === "web" ? createWebHistory() : createMemoryHistory(),
routes: [
{ path: "/", name: "home", component: () => import("./views/HomeView.vue") },
// The sidebar layout: spaces and page trees around the main view.
{
path: "/",
component: () => import("./components/AppLayout.vue"),
children: [
{ path: "", name: "home", component: () => import("./views/HomeView.vue") },
{ 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/settings",
name: "space-settings",
component: () => import("./views/space/SpaceSettingsView.vue"),
props: true,
},
{
path: "/w/:id/spaces/new",
name: "new-space",
component: () => import("./views/space/NewSpaceView.vue"),
props: true,
},
{
path: "/settings/organization",
name: "organization",
+152
View File
@@ -0,0 +1,152 @@
import type { PageNode, Space, SpaceRole } from "@docwell/api-client";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useApi } from "../api";
import { applyMove, childrenByParent } from "../lib/tree";
const rank: Record<SpaceRole, number> = { viewer: 1, commenter: 2, editor: 3, admin: 4 };
/** Whether space role has is at least need (mirrors the server's ranking). */
export function spaceAtLeast(has: SpaceRole | "" | undefined, need: SpaceRole): boolean {
return !!has && rank[has] >= rank[need];
}
const expandedKey = "docwell.expanded";
function rememberedExpanded(): Set<string> {
try {
return new Set(JSON.parse(localStorage.getItem(expandedKey) ?? "[]") as string[]);
} catch {
return new Set();
}
}
/** Spaces of the sidebar's workspace and their page trees. */
export const useSpacesStore = defineStore("spaces", () => {
const api = useApi();
const workspaceId = ref("");
const items = ref<Space[]>([]);
const loaded = ref(false);
/** Each space's live pages, flat in tree order. */
const trees = ref<Record<string, PageNode[]>>({});
/** Expanded page ids, plus "collapsed:<space id>" for spaces folded away (spaces start open). */
const expanded = ref(rememberedExpanded());
/** The page being dragged in the sidebar, if any. */
const dragging = ref<{ spaceId: string; id: string } | null>(null);
/** The space and page the main view shows, for highlighting and "New page". */
const active = ref({ space: "", page: "" });
const children = computed(() => {
const out: Record<string, Map<string, PageNode[]>> = {};
for (const [id, nodes] of Object.entries(trees.value)) out[id] = childrenByParent(nodes);
return out;
});
async function load(wsId: string) {
if (workspaceId.value !== wsId) {
workspaceId.value = wsId;
items.value = [];
trees.value = {};
loaded.value = false;
}
items.value = await api.workspaces.spaces(wsId);
loaded.value = true;
await Promise.all(items.value.map((s) => loadTree(s.id)));
}
async function loadTree(spaceId: string) {
trees.value[spaceId] = await api.spaces.pages(spaceId);
}
function space(id: string): Space | undefined {
return items.value.find((s) => s.id === id);
}
function childrenOf(spaceId: string, parent: string): PageNode[] {
return children.value[spaceId]?.get(parent) ?? [];
}
function canEdit(spaceId: string): boolean {
return spaceAtLeast(space(spaceId)?.role, "editor");
}
function persistExpanded() {
try {
localStorage.setItem(expandedKey, JSON.stringify([...expanded.value]));
} catch {
// per-browser convenience only
}
}
function isExpanded(id: string) {
return expanded.value.has(id);
}
function setExpanded(id: string, open: boolean) {
if (open === expanded.value.has(id)) return;
if (open) expanded.value.add(id);
else expanded.value.delete(id);
persistExpanded();
}
const spaceOpen = (id: string) => !expanded.value.has(`collapsed:${id}`);
const toggleSpace = (id: string) => setExpanded(`collapsed:${id}`, spaceOpen(id));
/** Opens every ancestor of a page so it is visible in the sidebar. */
function reveal(spaceId: string, pageId: string) {
const parentOf = new Map((trees.value[spaceId] ?? []).map((n) => [n.id, n.parent]));
for (let p = parentOf.get(pageId); p; p = parentOf.get(p)) setExpanded(p, true);
}
async function createPage(spaceId: string, parent = "") {
const page = await api.spaces.createPage(spaceId, { parent });
if (parent) setExpanded(parent, true);
await loadTree(spaceId);
return page;
}
/** Moves a page optimistically, then reloads the tree from the server either way. */
async function move(spaceId: string, id: string, parent: string, index: number) {
trees.value[spaceId] = applyMove(trees.value[spaceId] ?? [], id, parent, index);
if (parent) setExpanded(parent, true);
try {
await api.pages.move(id, parent, index);
} finally {
await loadTree(spaceId);
}
}
/** Mirrors a title change into the sidebar without a reload. */
function setTitle(spaceId: string, id: string, title: string) {
const node = trees.value[spaceId]?.find((n) => n.id === id);
if (node) node.title = title;
}
async function trash(spaceId: string, id: string) {
await api.pages.trash(id);
await loadTree(spaceId);
}
return {
workspaceId,
dragging,
active,
items,
loaded,
trees,
load,
loadTree,
space,
childrenOf,
canEdit,
isExpanded,
setExpanded,
spaceOpen,
toggleSpace,
reveal,
createPage,
move,
setTitle,
trash,
};
});
+25 -2
View File
@@ -1,6 +1,6 @@
import type { Workspace, WorkspaceRole } from "@docwell/api-client";
import { defineStore } from "pinia";
import { ref } from "vue";
import { computed, ref } from "vue";
import { useApi } from "../api";
import { useAuthStore } from "./auth";
@@ -16,22 +16,45 @@ export function grantableRoles(actor: WorkspaceRole): WorkspaceRole[] {
return (["owner", "admin", "member", "guest"] as WorkspaceRole[]).filter((r) => rank[r] <= rank[actor]);
}
const currentKey = "docwell.workspace";
function remembered(): string {
try {
return localStorage.getItem(currentKey) ?? "";
} catch {
return "";
}
}
export const useWorkspacesStore = defineStore("workspaces", () => {
const api = useApi();
const auth = useAuthStore();
const items = ref<Workspace[]>([]);
const loaded = ref(false);
const currentId = ref(remembered());
/** The workspace shown in the sidebar: the remembered one, else the first. */
const current = computed(() => items.value.find((w) => w.id === currentId.value) ?? items.value[0] ?? null);
async function load() {
items.value = await api.workspaces.list();
loaded.value = true;
}
function select(id: string) {
currentId.value = id;
try {
localStorage.setItem(currentKey, id);
} catch {
// per-browser convenience only
}
}
/** Org admins (in their organization) and superadmins create workspaces. */
function canCreate(): boolean {
const u = auth.user;
return !!u && (u.role === "superadmin" || (u.role === "admin" && !!u.organization));
}
return { items, loaded, load, canCreate };
return { items, loaded, current, load, select, canCreate };
});
+49 -108
View File
@@ -1,121 +1,62 @@
<script setup lang="ts">
import { DocwellEditor } from "@docwell/editor";
import { DwButton, useTheme, type ThemeMode } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import ServerStatus from "../components/ServerStatus.vue";
import { DwBadge, DwCallout, DwIcon } from "@docwell/ui";
import { computed, onMounted } from "vue";
import { useAuthStore } from "../stores/auth";
import { useWorkspacesStore } from "../stores/workspaces";
import { useSpacesStore } from "../stores/spaces";
import { atLeast, useWorkspacesStore } from "../stores/workspaces";
const auth = useAuthStore();
const workspaces = useWorkspacesStore();
onMounted(() => workspaces.load().catch(() => {}));
const router = useRouter();
const { mode } = useTheme();
function signOut() {
auth.logout();
router.replace({ name: "login" });
}
const themes: ThemeMode[] = ["system", "light", "dark"];
const sidebarOpen = ref(false);
const title = ref("");
const spaces = useSpacesStore();
const ws = computed(() => workspaces.current);
onMounted(() => (spaces.active = { space: "", page: "" }));
</script>
<template>
<div class="flex h-dvh">
<aside
class="fixed inset-y-0 left-0 z-20 flex w-64 flex-col border-r border-border bg-surface-muted transition-transform md:static md:translate-x-0"
:class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'"
>
<div class="flex h-12 items-center gap-2 px-4 font-semibold">
<img src="/favicon.svg" alt="" class="size-5" />
{{ $t("app.name") }}
</div>
<div class="px-3">
<button
class="w-full rounded-md border border-border bg-surface px-3 py-1.5 text-left text-sm text-fg-muted hover:bg-surface-muted"
<article class="mx-auto max-w-doc-wide px-4 pt-8 pb-16 sm:px-16 sm:pt-12">
<div class="flex items-center gap-3">
<DwIcon name="drop" :size="28" class="text-spring" />
<h1 class="font-serif text-doc-h1">{{ ws?.name ?? $t("app.name") }}</h1>
</div>
<p v-if="ws" class="mt-2 text-ui-md text-ink-muted">
{{ $t("workspace.yourRole", { role: $t(`workspace.roles.${ws.role}`), org: ws.organizationName }) }}
</p>
<DwCallout v-else-if="workspaces.loaded" class="mt-6" size="ui">
{{ $t(auth.user?.organization || auth.user?.role === "superadmin" ? "sidebar.noWorkspaces" : "sidebar.noOrg") }}
</DwCallout>
<template v-if="ws">
<div class="mt-10 flex items-center justify-between gap-2">
<h2 class="dw-label">{{ $t("sidebar.spaces") }}</h2>
<RouterLink
v-if="atLeast(ws.role, 'admin')"
:to="{ name: 'new-space', params: { id: ws.id } }"
class="inline-flex h-control-sm items-center gap-1 rounded-sm px-2 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
>
{{ $t("app.search") }} <kbd class="float-right text-xs">Ctrl K</kbd>
</button>
<DwIcon name="plus" :size="16" />{{ $t("space.new") }}
</RouterLink>
</div>
<nav class="mt-4 flex-1 space-y-4 overflow-y-auto px-3 text-sm">
<section>
<h2 class="px-2 text-xs font-medium uppercase tracking-wide text-fg-muted">{{ $t("sidebar.favorites") }}</h2>
</section>
<section>
<div class="flex items-center justify-between px-2">
<h2 class="text-xs font-medium uppercase tracking-wide text-fg-muted">{{ $t("sidebar.workspaces") }}</h2>
<RouterLink
v-if="workspaces.canCreate()"
to="/workspaces/new"
class="text-fg-muted hover:text-fg"
:aria-label="$t('workspace.newTitle')"
:title="$t('workspace.newTitle')"
>
+
</RouterLink>
</div>
<ul class="mt-1 space-y-0.5" data-testid="workspace-list">
<li v-for="w in workspaces.items" :key="w.id">
<RouterLink
:to="{ name: 'workspace-settings', params: { id: w.id } }"
class="flex items-center justify-between gap-2 rounded-md px-2 py-1 hover:bg-surface"
>
<span class="truncate">{{ w.name }}</span>
<span class="shrink-0 text-xs text-fg-muted">{{ $t(`workspace.roles.${w.role}`) }}</span>
</RouterLink>
</li>
<li v-if="workspaces.loaded && !workspaces.items.length" class="px-2 py-1 text-xs text-fg-muted">
{{ $t(auth.user?.organization || auth.user?.role === "superadmin" ? "sidebar.noWorkspaces" : "sidebar.noOrg") }}
</li>
</ul>
</section>
</nav>
<div class="space-y-3 border-t border-border p-3">
<div v-if="auth.user" class="flex items-center gap-2">
<span
class="grid size-7 shrink-0 place-items-center rounded-full bg-brand-600 text-xs font-semibold text-white"
aria-hidden="true"
<ul class="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3" data-testid="space-cards">
<li v-for="s in spaces.items" :key="s.id">
<RouterLink
:to="{ name: 'space', params: { id: s.id } }"
class="flex h-full flex-col rounded-md border border-line bg-surface-raised p-4 transition-colors duration-[120ms] hover:border-line-strong"
>
{{ auth.user.name.slice(0, 1).toUpperCase() }}
</span>
<RouterLink to="/settings/organization" class="min-w-0 flex-1 text-sm hover:opacity-80">
<div class="truncate font-medium" data-testid="user-name">{{ auth.user.name }}</div>
<div class="truncate text-xs text-fg-muted" data-testid="user-org">
{{ $t(`roles.${auth.user.role}`) }}{{ auth.user.organizationName ? ` · ${auth.user.organizationName}` : "" }}
</div>
<span class="flex items-center gap-2 text-ui-lg text-ink">
<span class="truncate">{{ s.icon ? `${s.icon} ` : "" }}{{ s.name }}</span>
</span>
<span v-if="s.description" class="mt-1 line-clamp-2 text-ui-md text-ink-muted">{{ s.description }}</span>
<span class="mt-auto flex flex-wrap items-center gap-2 pt-3 text-ui-sm text-ink-muted">
{{ $t("space.pageCount", { n: spaces.trees[s.id]?.length ?? 0 }, spaces.trees[s.id]?.length ?? 0) }}
<DwBadge v-if="s.visibility === 'private'">{{ $t("space.private") }}</DwBadge>
<DwBadge tone="accent">{{ $t(`space.roles.${s.role}`) }}</DwBadge>
</span>
</RouterLink>
<button class="text-xs text-fg-muted hover:text-fg" @click="signOut">{{ $t("auth.signOut") }}</button>
</div>
<label class="flex items-center justify-between text-sm">
<span class="text-fg-muted">{{ $t("app.settings") }}</span>
<select v-model="mode" class="rounded border border-border bg-surface px-1 py-0.5 text-xs">
<option v-for="t in themes" :key="t" :value="t">{{ $t(`theme.${t}`) }}</option>
</select>
</label>
<ServerStatus />
</div>
</aside>
<div v-if="sidebarOpen" class="fixed inset-0 z-10 bg-black/30 md:hidden" @click="sidebarOpen = false" />
<main class="flex min-w-0 flex-1 flex-col">
<header class="flex h-12 items-center justify-between border-b border-border px-4">
<button class="md:hidden" aria-label="Menu" @click="sidebarOpen = true">☰</button>
<span class="truncate text-sm text-fg-muted">{{ title || $t("home.untitled") }}</span>
<DwButton>{{ $t("app.newPage") }}</DwButton>
</header>
<div class="flex-1 overflow-y-auto">
<article class="mx-auto max-w-3xl px-4 py-10 sm:px-8">
<input
v-model="title"
:placeholder="$t('home.untitled')"
class="mb-4 w-full bg-transparent text-4xl font-bold outline-none placeholder:text-fg-muted/50"
/>
<DocwellEditor />
</article>
</div>
</main>
</div>
</li>
</ul>
<DwCallout v-if="spaces.loaded && !spaces.items.length" class="mt-3" size="ui">
{{ atLeast(ws.role, "admin") ? $t("space.noneAdmin") : $t("space.none") }}
</DwCallout>
</template>
</article>
</template>
+1 -1
View File
@@ -2,7 +2,7 @@
<div class="grid h-dvh place-items-center text-center">
<div>
<h1 class="text-2xl font-semibold">{{ $t("notFound.title") }}</h1>
<RouterLink to="/" class="mt-4 inline-block text-brand-600 underline">{{ $t("notFound.back") }}</RouterLink>
<RouterLink to="/" class="mt-4 inline-block text-accent underline">{{ $t("notFound.back") }}</RouterLink>
</div>
</div>
</template>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { ref } from "vue";
import { useApi } from "../../api";
import AuthCard from "../../components/AuthCard.vue";
@@ -28,15 +28,15 @@ async function submit() {
<template>
<AuthCard :title="$t('auth.forgot.title')">
<p v-if="sent" role="status" class="text-sm">{{ $t("auth.forgot.sent", { email }) }}</p>
<p v-if="sent" role="status" class="text-ui-md">{{ $t("auth.forgot.sent", { email }) }}</p>
<form v-else class="space-y-4" @submit.prevent="submit">
<p class="text-sm text-fg-muted">{{ $t("auth.forgot.hint") }}</p>
<p class="text-ui-md text-ink-muted">{{ $t("auth.forgot.hint") }}</p>
<FormField v-model="email" :label="$t('auth.email')" type="email" autocomplete="email" required :error="errors.fields.value.email" />
<p v-if="errors.message.value" role="alert" class="text-sm text-red-600">{{ errors.message.value }}</p>
<DwButton type="submit" class="w-full justify-center" :disabled="busy">{{ $t("auth.forgot.submit") }}</DwButton>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full justify-center" :disabled="busy">{{ $t("auth.forgot.submit") }}</DwButton>
</form>
<template #footer>
<RouterLink to="/login" class="text-brand-600 hover:underline">{{ $t("auth.backToLogin") }}</RouterLink>
<RouterLink to="/login" class="dw-link">{{ $t("auth.backToLogin") }}</RouterLink>
</template>
</AuthCard>
</template>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { ApiError, type AuthMethods } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useApi } from "../../api";
@@ -88,26 +88,26 @@ async function submitCode() {
<form v-if="step === 'password'" class="space-y-4" @submit.prevent="submitPassword">
<FormField v-model="email" :label="$t('auth.email')" type="email" autocomplete="email" required :error="errors.fields.value.identity" />
<FormField v-model="password" :label="$t('auth.password')" type="password" autocomplete="current-password" required />
<div class="text-right text-sm">
<RouterLink to="/forgot-password" class="text-brand-600 hover:underline">{{ $t("auth.login.forgot") }}</RouterLink>
<div class="text-right text-ui-md">
<RouterLink to="/forgot-password" class="dw-link">{{ $t("auth.login.forgot") }}</RouterLink>
</div>
<p v-if="errors.message.value" role="alert" class="text-sm text-red-600">{{ errors.message.value }}</p>
<DwButton type="submit" class="w-full justify-center" :disabled="busy">{{ $t("auth.login.submit") }}</DwButton>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full justify-center" :disabled="busy">{{ $t("auth.login.submit") }}</DwButton>
<DwButton v-if="methods?.otp" variant="secondary" class="w-full justify-center" :disabled="busy || !email" @click="useEmailCode">
{{ $t("auth.login.emailCode") }}
</DwButton>
</form>
<form v-else class="space-y-4" @submit.prevent="submitCode">
<p class="text-sm text-fg-muted">{{ $t(mfaId ? "auth.login.mfaHint" : "auth.login.codeHint", { email }) }}</p>
<p class="text-ui-md text-ink-muted">{{ $t(mfaId ? "auth.login.mfaHint" : "auth.login.codeHint", { email }) }}</p>
<FormField v-model="code" :label="$t('auth.login.code')" autocomplete="one-time-code" required />
<p v-if="errors.message.value" role="alert" class="text-sm text-red-600">{{ errors.message.value }}</p>
<DwButton type="submit" class="w-full justify-center" :disabled="busy">{{ $t("auth.login.submit") }}</DwButton>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full justify-center" :disabled="busy">{{ $t("auth.login.submit") }}</DwButton>
</form>
<template v-if="methods?.signup !== false" #footer>
{{ $t("auth.login.noAccount") }}
<RouterLink to="/signup" class="text-brand-600 hover:underline">{{ $t("auth.signup.title") }}</RouterLink>
<RouterLink to="/signup" class="dw-link">{{ $t("auth.signup.title") }}</RouterLink>
</template>
</AuthCard>
</template>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { ref } from "vue";
import { useRoute } from "vue-router";
import { useApi } from "../../api";
@@ -31,8 +31,8 @@ async function submit() {
<template>
<AuthCard :title="$t('auth.reset.title')">
<p v-if="done" role="status" class="text-sm">{{ $t("auth.reset.done") }}</p>
<p v-else-if="!token" role="alert" class="text-sm text-red-600">{{ $t("errors.invalid_token") }}</p>
<p v-if="done" role="status" class="text-ui-md">{{ $t("auth.reset.done") }}</p>
<p v-else-if="!token" role="alert" class="text-ui-md text-danger">{{ $t("errors.invalid_token") }}</p>
<form v-else class="space-y-4" @submit.prevent="submit">
<FormField
v-model="password"
@@ -42,11 +42,11 @@ async function submit() {
required
:error="errors.fields.value.password"
/>
<p v-if="errors.message.value" role="alert" class="text-sm text-red-600">{{ errors.message.value }}</p>
<DwButton type="submit" class="w-full justify-center" :disabled="busy">{{ $t("auth.reset.submit") }}</DwButton>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full justify-center" :disabled="busy">{{ $t("auth.reset.submit") }}</DwButton>
</form>
<template #footer>
<RouterLink to="/login" class="text-brand-600 hover:underline">{{ $t("auth.backToLogin") }}</RouterLink>
<RouterLink to="/login" class="dw-link">{{ $t("auth.backToLogin") }}</RouterLink>
</template>
</AuthCard>
</template>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { ref } from "vue";
import { useRouter } from "vue-router";
import AuthCard from "../../components/AuthCard.vue";
@@ -43,13 +43,13 @@ async function submit() {
required
:error="errors.fields.value.password"
/>
<p class="text-xs text-fg-muted">{{ $t("auth.signup.passwordHint") }}</p>
<p v-if="errors.message.value" role="alert" class="text-sm text-red-600">{{ errors.message.value }}</p>
<DwButton type="submit" class="w-full justify-center" :disabled="busy">{{ $t("auth.signup.submit") }}</DwButton>
<p class="text-ui-sm text-ink-muted">{{ $t("auth.signup.passwordHint") }}</p>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" class="w-full justify-center" :disabled="busy">{{ $t("auth.signup.submit") }}</DwButton>
</form>
<template #footer>
{{ $t("auth.signup.haveAccount") }}
<RouterLink to="/login" class="text-brand-600 hover:underline">{{ $t("auth.login.title") }}</RouterLink>
<RouterLink to="/login" class="dw-link">{{ $t("auth.login.title") }}</RouterLink>
</template>
</AuthCard>
</template>
@@ -22,11 +22,11 @@ onMounted(async () => {
<template>
<AuthCard :title="$t('auth.verify.title')">
<p v-if="state === 'working'" class="text-sm text-fg-muted">…</p>
<p v-else-if="state === 'done'" role="status" class="text-sm">{{ $t("auth.verify.done") }}</p>
<p v-else role="alert" class="text-sm text-red-600">{{ $t("errors.invalid_token") }}</p>
<p v-if="state === 'working'" class="text-ui-md text-ink-muted">…</p>
<p v-else-if="state === 'done'" role="status" class="text-ui-md">{{ $t("auth.verify.done") }}</p>
<p v-else role="alert" class="text-ui-md text-danger">{{ $t("errors.invalid_token") }}</p>
<template #footer>
<RouterLink to="/" class="text-brand-600 hover:underline">{{ $t("auth.continue") }}</RouterLink>
<RouterLink to="/" class="dw-link">{{ $t("auth.continue") }}</RouterLink>
</template>
</AuthCard>
</template>
@@ -0,0 +1,172 @@
<script setup lang="ts">
import type { Page } from "@docwell/api-client";
import { DwBreadcrumbs, DwButton, DwCallout } from "@docwell/ui";
import { computed, onBeforeUnmount, 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 { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
import { useWorkspacesStore } from "../../stores/workspaces";
const props = defineProps<{ id: string }>();
const emit = defineEmits<{ error: [err: unknown] }>();
const api = useApi();
const spaces = useSpacesStore();
const workspaces = useWorkspacesStore();
const router = useRouter();
const { t } = useI18n();
const page = ref<Page | null>(null);
const notFound = ref(false);
const title = ref("");
const busy = ref(false);
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) : []));
// Space, then the page's ancestors, then the page itself (not a link).
const crumbs = computed(() => {
const p = page.value;
if (!p) return [];
const untitled = t("home.untitled");
return [
{ label: spaces.space(p.space)?.name ?? "…", to: { name: "space", params: { id: p.space } } },
...p.ancestors.map((a) => ({ label: a.title || untitled, to: { name: "page", params: { id: a.id } } })),
{ label: title.value.trim() || untitled },
];
});
async function load(id: string) {
notFound.value = false;
try {
const p = await api.pages.get(id);
page.value = p;
title.value = p.title;
spaces.active = { space: p.space, page: p.id };
// A link from another workspace switches the sidebar to it.
if (workspaces.current && p.workspace !== workspaces.current.id) workspaces.select(p.workspace);
spaces.reveal(p.space, p.id);
} catch {
page.value = null;
notFound.value = true;
}
}
// Titles save after a short pause in typing, and right away on blur or when leaving.
let timer: ReturnType<typeof setTimeout> | undefined;
async function saveTitle() {
clearTimeout(timer);
const p = page.value;
if (!p || !editable.value || title.value.trim() === p.title) return;
try {
const saved = await api.pages.update(p.id, { title: title.value });
if (page.value?.id === saved.id) page.value = { ...page.value, title: saved.title, updated: saved.updated };
spaces.setTitle(saved.space, saved.id, saved.title);
} catch (e) {
emit("error", e);
}
}
function onTitleInput() {
clearTimeout(timer);
if (page.value) spaces.setTitle(page.value.space, page.value.id, title.value.trim());
timer = setTimeout(saveTitle, 600);
}
watch(
() => props.id,
async (id, old) => {
if (old) await saveTitle();
await load(id);
},
{ immediate: true },
);
onBeforeUnmount(saveTitle);
async function run(action: () => Promise<unknown>) {
busy.value = true;
try {
await action();
} catch (e) {
emit("error", e);
} finally {
busy.value = false;
}
}
const addChild = () =>
run(async () => {
const child = await spaces.createPage(page.value!.space, page.value!.id);
router.push({ name: "page", params: { id: child.id } });
});
const trash = () =>
run(async () => {
await spaces.trash(page.value!.space, page.value!.id);
await load(props.id);
});
const restore = () =>
run(async () => {
await api.pages.restore(page.value!.id);
await spaces.loadTree(page.value!.space);
await load(props.id);
});
const purge = () =>
run(async () => {
const p = page.value!;
if (!confirm(t("page.confirmPurge", { title: p.title || t("home.untitled") }))) return;
await api.pages.purge(p.id);
router.replace({ name: "trash", params: { id: p.space } });
});
</script>
<template>
<article class="mx-auto max-w-doc px-4 pt-8 pb-16 sm:px-16 sm:pt-12">
<DwCallout v-if="notFound" tone="info" size="ui">{{ $t("page.notFound") }}</DwCallout>
<template v-if="page">
<DwBreadcrumbs :items="crumbs" :label="$t('page.breadcrumbs')" />
<DwCallout v-if="page.inTrash" tone="warning" size="ui" class="mt-4 items-center" role="status">
{{ page.deletedAt ? $t("page.inTrash") : $t("page.parentInTrash") }}
<template v-if="page.deletedAt && spaceAtLeast(page.role, 'editor')" #actions>
<span class="flex shrink-0 flex-wrap gap-2">
<DwButton size="sm" icon="restore" :disabled="busy" @click="restore">{{ $t("page.restore") }}</DwButton>
<DwButton v-if="spaceAtLeast(page.role, 'admin')" size="sm" variant="danger" :disabled="busy" @click="purge">
{{ $t("page.deleteForever") }}
</DwButton>
</span>
</template>
</DwCallout>
<input
v-model="title"
:readonly="!editable"
:placeholder="$t('home.untitled')"
:aria-label="$t('page.title')"
maxlength="500"
class="mt-6 w-full rounded-xs bg-transparent font-serif text-doc-title text-ink outline-none placeholder:text-ink-faint"
data-testid="page-title"
@input="onTitleInput"
@blur="saveTitle"
@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>
<DwCallout class="mt-8" size="ui">{{ $t("page.editorSoon") }}</DwCallout>
<!-- A trashed page's children are hidden with it; they come back on restore. -->
<section v-if="!page.inTrash" class="mt-10">
<div class="flex flex-wrap items-center justify-between gap-2">
<h2 class="dw-label">{{ $t("page.subpages") }}</h2>
<div v-if="editable" class="flex gap-1">
<DwButton variant="ghost" size="sm" icon="plus" :disabled="busy" @click="addChild">{{ $t("sidebar.addSubpage") }}</DwButton>
<DwButton variant="ghost" size="sm" icon="trash" :disabled="busy" @click="trash">{{ $t("page.moveToTrash") }}</DwButton>
</div>
</div>
<PageList v-if="children.length" :items="children" class="mt-2" />
<p v-else class="mt-2 text-ui-md text-ink-muted">{{ $t("page.noSubpages") }}</p>
</section>
</template>
</article>
</template>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import type { Organization } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../../api";
@@ -64,35 +64,33 @@ function remove() {
<template>
<PageShell :title="$t('org.title')" :subtitle="$t(`org.subtitle.${role === 'superadmin' ? 'superadmin' : hasOrg ? role : 'none'}`)">
<p v-if="errors.message.value" role="alert" class="rounded-md bg-red-500/10 px-3 py-2 text-sm text-red-600">
{{ errors.message.value }}
</p>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<section v-if="role === 'superadmin'" class="rounded-xl border border-border bg-surface p-6">
<a :href="adminUrl" class="text-brand-600 hover:underline">{{ $t("org.openAdmin") }}</a>
<section v-if="role === 'superadmin'" class="dw-card">
<a :href="adminUrl" class="dw-link">{{ $t("org.openAdmin") }}</a>
</section>
<form v-else-if="!hasOrg" class="space-y-4 rounded-xl border border-border bg-surface p-6" @submit.prevent="create">
<form v-else-if="!hasOrg" class="space-y-4 dw-card" @submit.prevent="create">
<FormField v-model="name" :label="$t('org.name')" required :error="errors.fields.value.name" />
<p class="text-xs text-fg-muted">{{ $t("org.createHint") }}</p>
<DwButton type="submit" :disabled="busy || !name.trim()">{{ $t("org.create") }}</DwButton>
<p class="text-ui-sm text-ink-muted">{{ $t("org.createHint") }}</p>
<DwButton type="submit" variant="primary" :disabled="busy || !name.trim()">{{ $t("org.create") }}</DwButton>
</form>
<section v-else-if="role === 'admin' && org" class="space-y-4 rounded-xl border border-border bg-surface p-6">
<section v-else-if="role === 'admin' && org" class="space-y-4 dw-card">
<form class="space-y-4" @submit.prevent="rename">
<FormField v-model="name" :label="$t('org.name')" required :error="errors.fields.value.name" />
<p class="text-xs text-fg-muted">{{ $t("org.counts", { members: org.members, workspaces: org.workspaces }) }}</p>
<DwButton type="submit" :disabled="busy || !name.trim() || name.trim() === org.name">{{ $t("common.save") }}</DwButton>
<p class="text-ui-sm text-ink-muted">{{ $t("org.counts", { members: org.members, workspaces: org.workspaces }) }}</p>
<DwButton type="submit" variant="primary" :disabled="busy || !name.trim() || name.trim() === org.name">{{ $t("common.save") }}</DwButton>
</form>
<div class="border-t border-border pt-4">
<h2 class="text-sm font-medium">{{ $t("org.dangerTitle") }}</h2>
<p class="mt-1 text-xs text-fg-muted">{{ $t("org.deleteHint") }}</p>
<DwButton variant="secondary" class="mt-3 !text-red-600" :disabled="busy" @click="remove">{{ $t("org.delete") }}</DwButton>
<div class="border-t border-line pt-4">
<h2 class="text-ui-lg">{{ $t("org.dangerTitle") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("org.deleteHint") }}</p>
<DwButton variant="secondary" class="mt-3 !text-danger" :disabled="busy" @click="remove">{{ $t("org.delete") }}</DwButton>
</div>
</section>
<section v-else class="rounded-xl border border-border bg-surface p-6">
<p class="text-sm">{{ $t("org.memberOf", { name: auth.user?.organizationName }) }}</p>
<section v-else class="dw-card">
<p class="text-ui-md">{{ $t("org.memberOf", { name: auth.user?.organizationName }) }}</p>
</section>
</PageShell>
</template>
@@ -0,0 +1,69 @@
<script setup lang="ts">
import type { SpaceVisibility } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useApi } from "../../api";
import FormField from "../../components/FormField.vue";
import PageShell from "../../components/PageShell.vue";
import { useFormErrors } from "../../composables/useFormErrors";
import { useSpacesStore } from "../../stores/spaces";
const props = defineProps<{ id: string }>();
const api = useApi();
const spaces = useSpacesStore();
const router = useRouter();
const errors = useFormErrors();
const name = ref("");
const description = ref("");
const visibility = ref<SpaceVisibility>("open");
const busy = ref(false);
async function submit() {
busy.value = true;
errors.reset();
try {
const space = await api.workspaces.createSpace(props.id, {
name: name.value,
description: description.value,
visibility: visibility.value,
});
await spaces.load(props.id);
router.replace({ name: "space", params: { id: space.id } });
} catch (e) {
errors.show(e);
} finally {
busy.value = false;
}
}
</script>
<template>
<PageShell :title="$t('space.new')" :subtitle="$t('space.newHint')">
<form class="space-y-4 dw-card" @submit.prevent="submit">
<FormField v-model="name" :label="$t('space.name')" required :error="errors.fields.value.name" />
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("space.description") }}</span>
<textarea
v-model="description"
rows="2"
maxlength="1000"
class="dw-input w-full"
/>
</label>
<fieldset class="space-y-2 text-ui-md">
<legend class="text-ui-sm font-semibold">{{ $t("space.visibility") }}</legend>
<label v-for="v in ['open', 'private'] as const" :key="v" class="flex items-start gap-2">
<input v-model="visibility" type="radio" name="visibility" :value="v" class="mt-1 accent-primary" />
<span>
<span class="font-medium">{{ $t(`space.${v}`) }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t(`space.${v}Hint`) }}</span>
</span>
</label>
</fieldset>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" :disabled="busy || !name.trim()">{{ $t("space.create") }}</DwButton>
</form>
</PageShell>
</template>
@@ -0,0 +1,205 @@
<script setup lang="ts">
import type { Space, SpaceDefaultRole, SpaceMember, SpaceRole, SpaceVisibility } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { useApi } from "../../api";
import PageShell from "../../components/PageShell.vue";
import { useFormErrors } from "../../composables/useFormErrors";
import { useAuthStore } from "../../stores/auth";
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
import { atLeast, useWorkspacesStore } from "../../stores/workspaces";
const props = defineProps<{ id: string }>();
const api = useApi();
const auth = useAuthStore();
const spaces = useSpacesStore();
const workspaces = useWorkspacesStore();
const router = useRouter();
const { t } = useI18n();
const errors = useFormErrors();
const space = ref<Space | null>(null);
const members = ref<SpaceMember[]>([]);
const notFound = ref(false);
const busy = ref(false);
const form = ref({ name: "", description: "", visibility: "open" as SpaceVisibility, defaultRole: "editor" as SpaceDefaultRole });
const email = ref("");
const newRole = ref<SpaceRole>("editor");
const roles: SpaceRole[] = ["admin", "editor", "commenter", "viewer"];
const defaultRoles: SpaceDefaultRole[] = ["editor", "commenter", "viewer"];
const canManage = computed(() => spaceAtLeast(space.value?.role, "admin"));
// Deleting a space is for workspace admins, not just space admins.
const canDelete = computed(() => {
if (!workspaces.loaded) return false;
return atLeast(workspaces.items.find((w) => w.id === space.value?.workspace)?.role, "admin");
});
const dirty = computed(
() =>
!!space.value &&
(form.value.name.trim() !== space.value.name ||
form.value.description.trim() !== space.value.description ||
form.value.visibility !== space.value.visibility ||
form.value.defaultRole !== space.value.defaultRole),
);
async function load() {
try {
if (!workspaces.loaded) await workspaces.load();
const s = await api.spaces.get(props.id);
space.value = s;
form.value = { name: s.name, description: s.description, visibility: s.visibility, defaultRole: s.defaultRole };
members.value = await api.spaces.members(props.id);
} catch {
notFound.value = !space.value;
}
}
onMounted(load);
async function run(action: () => Promise<unknown>) {
busy.value = true;
errors.reset();
try {
await action();
await load();
if (space.value) await spaces.load(space.value.workspace);
} catch (e) {
errors.show(e);
} finally {
busy.value = false;
}
}
const save = () => run(() => api.spaces.update(props.id, { ...form.value }));
const setRole = (m: SpaceMember, role: SpaceRole) => run(() => api.spaces.setMember(props.id, m.user.email, role));
const removeMember = (m: SpaceMember) => run(() => api.spaces.removeMember(props.id, m.user.id));
async function addMember() {
await run(() => api.spaces.setMember(props.id, email.value, newRole.value));
if (!errors.message.value && !Object.keys(errors.fields.value).length) email.value = "";
}
async function removeSpace() {
const s = space.value;
if (!s || !confirm(t("space.confirmDelete", { name: s.name }))) return;
busy.value = true;
errors.reset();
try {
await api.spaces.remove(s.id);
await spaces.load(s.workspace);
router.replace({ name: "home" });
} catch (e) {
errors.show(e);
} finally {
busy.value = false;
}
}
</script>
<template>
<PageShell
:title="space?.name ?? $t('space.settings')"
:subtitle="space ? $t('space.yourRole', { role: $t(`space.roles.${space.role}`) }) : undefined"
>
<p v-if="notFound" class="text-ui-md text-ink-muted">{{ $t("space.notFound") }}</p>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<template v-if="space">
<RouterLink :to="{ name: 'space', params: { id: space.id } }" class="text-ui-md text-accent hover:underline">
{{ $t("space.openPages") }}
</RouterLink>
<form v-if="canManage" class="space-y-4 dw-card" @submit.prevent="save">
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("space.name") }}</span>
<input v-model="form.name" required maxlength="120" class="dw-input w-full" />
<span v-if="errors.fields.value.name" class="text-ui-sm text-danger">{{ errors.fields.value.name }}</span>
</label>
<label class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("space.description") }}</span>
<textarea v-model="form.description" rows="2" maxlength="1000" class="dw-input w-full" />
</label>
<fieldset class="space-y-2 text-ui-md">
<legend class="text-ui-sm font-semibold">{{ $t("space.visibility") }}</legend>
<label v-for="v in ['open', 'private'] as const" :key="v" class="flex items-start gap-2">
<input v-model="form.visibility" type="radio" name="visibility" :value="v" class="mt-1 accent-primary" />
<span>
<span class="font-medium">{{ $t(`space.${v}`) }}</span>
<span class="block text-ui-sm text-ink-muted">{{ $t(`space.${v}Hint`) }}</span>
</span>
</label>
</fieldset>
<label v-if="form.visibility === 'open'" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("space.defaultRole") }}</span>
<select v-model="form.defaultRole" class="dw-input">
<option v-for="r in defaultRoles" :key="r" :value="r">{{ $t(`space.roles.${r}`) }}</option>
</select>
<span class="block text-ui-sm text-ink-muted">{{ $t("space.defaultRoleHint") }}</span>
</label>
<DwButton type="submit" variant="primary" :disabled="busy || !form.name.trim() || !dirty">{{ $t("common.save") }}</DwButton>
</form>
<section class="dw-card">
<h2 class="text-ui-lg">{{ $t("space.members") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("space.membersHint") }}</p>
<form v-if="canManage" class="mt-4 flex flex-wrap gap-2" @submit.prevent="addMember">
<input
v-model="email"
type="email"
required
:placeholder="$t('auth.email')"
:aria-label="$t('auth.email')"
class="dw-input min-w-48 flex-1"
/>
<select v-model="newRole" :aria-label="$t('workspace.role')" class="dw-input">
<option v-for="r in roles" :key="r" :value="r">{{ $t(`space.roles.${r}`) }}</option>
</select>
<DwButton type="submit" :disabled="busy || !email">{{ $t("workspace.add") }}</DwButton>
</form>
<p v-if="errors.fields.value.email" class="mt-1 text-ui-sm text-danger">{{ errors.fields.value.email }}</p>
<ul class="mt-4 divide-y divide-line">
<li v-for="m in members" :key="m.user.id" class="flex flex-wrap items-center justify-between gap-2 py-2" data-testid="space-member">
<div class="min-w-0">
<p class="truncate text-ui-md font-medium">{{ m.user.name }}</p>
<p class="truncate text-ui-sm text-ink-muted">{{ m.user.email }}</p>
</div>
<div class="flex items-center gap-3 text-ui-md">
<select
v-if="canManage"
:value="m.role"
:aria-label="$t('workspace.role')"
class="dw-input"
:disabled="busy"
@change="setRole(m, ($event.target as HTMLSelectElement).value as SpaceRole)"
>
<option v-for="r in roles" :key="r" :value="r">{{ $t(`space.roles.${r}`) }}</option>
</select>
<span v-else class="text-ink-muted">{{ $t(`space.roles.${m.role}`) }}</span>
<button
v-if="canManage || m.user.id === auth.user?.id"
class="text-danger hover:underline"
:disabled="busy"
@click="removeMember(m)"
>
{{ m.user.id === auth.user?.id ? $t("workspace.leave") : $t("workspace.remove") }}
</button>
</div>
</li>
<li v-if="!members.length" class="py-2 text-ui-md text-ink-muted">{{ $t("space.noMembers") }}</li>
</ul>
</section>
<section v-if="canDelete" class="dw-card">
<h2 class="text-ui-lg">{{ $t("org.dangerTitle") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("space.deleteHint") }}</p>
<DwButton variant="secondary" class="mt-3 !text-danger" :disabled="busy" @click="removeSpace">
{{ $t("space.delete") }}
</DwButton>
</section>
</template>
</PageShell>
</template>
@@ -0,0 +1,85 @@
<script setup lang="ts">
import type { Space } from "@docwell/api-client";
import { DwBadge, DwButton, DwCallout, DwIcon } from "@docwell/ui";
import { computed, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useApi } from "../../api";
import PageList from "../../components/PageList.vue";
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
const props = defineProps<{ id: string }>();
const emit = defineEmits<{ error: [err: unknown] }>();
const api = useApi();
const spaces = useSpacesStore();
const router = useRouter();
const space = ref<Space | null>(null);
const notFound = ref(false);
const pages = computed(() => spaces.childrenOf(props.id, ""));
watch(
() => props.id,
async (id) => {
spaces.active = { space: id, page: "" };
notFound.value = false;
try {
space.value = await api.spaces.get(id);
if (!spaces.trees[id]) await spaces.loadTree(id);
} catch {
space.value = null;
notFound.value = true;
}
},
{ immediate: true },
);
const headerLink =
"inline-flex h-control-sm items-center gap-1 rounded-sm px-2 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink";
async function newPage() {
try {
const page = await spaces.createPage(props.id);
router.push({ name: "page", params: { id: page.id } });
} catch (e) {
emit("error", e);
}
}
</script>
<template>
<article class="mx-auto max-w-doc px-4 pt-8 pb-16 sm:px-16 sm:pt-12">
<DwCallout v-if="notFound" tone="info" size="ui">{{ $t("space.notFound") }}</DwCallout>
<template v-if="space">
<div class="flex flex-wrap items-start justify-between gap-4">
<div class="min-w-0">
<h1 class="font-serif text-doc-h1">{{ space.icon ? `${space.icon} ` : "" }}{{ space.name }}</h1>
<p v-if="space.description" class="mt-2 text-doc-body text-ink-muted">{{ space.description }}</p>
<p class="mt-3 flex flex-wrap items-center gap-2">
<DwBadge v-if="space.visibility === 'private'">{{ $t("space.private") }}</DwBadge>
<DwBadge tone="accent">{{ $t(`space.roles.${space.role}`) }}</DwBadge>
</p>
</div>
<div class="flex gap-1">
<RouterLink :to="{ name: 'trash', params: { id: space.id } }" :class="headerLink">
<DwIcon name="trash" :size="16" />{{ $t("sidebar.trash") }}
</RouterLink>
<RouterLink :to="{ name: 'space-settings', params: { id: space.id } }" :class="headerLink">
<DwIcon name="settings" :size="16" />{{ $t("space.settings") }}
</RouterLink>
</div>
</div>
<div class="mt-10 flex items-center justify-between gap-2">
<h2 class="dw-label">{{ $t("space.pages") }}</h2>
<DwButton v-if="spaceAtLeast(space.role, 'editor')" variant="ghost" size="sm" icon="plus" @click="newPage">
{{ $t("app.newPage") }}
</DwButton>
</div>
<PageList v-if="pages.length" :items="pages" class="mt-2" />
<div v-else class="mt-2 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("space.noPages") }}
</div>
</template>
</article>
</template>
@@ -0,0 +1,82 @@
<script setup lang="ts">
import type { Space, TrashedPage } 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";
const props = defineProps<{ id: string }>();
const emit = defineEmits<{ error: [err: unknown] }>();
const api = useApi();
const spaces = useSpacesStore();
const { t, locale } = useI18n();
const space = ref<Space | null>(null);
const items = ref<TrashedPage[]>([]);
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.trash(props.id)]);
} catch {
space.value = null;
notFound.value = true;
}
}
watch(() => props.id, load, { immediate: true });
async function run(action: () => Promise<unknown>) {
busy.value = true;
try {
await action();
await Promise.all([load(), spaces.loadTree(props.id)]);
} catch (e) {
emit("error", e);
} finally {
busy.value = false;
}
}
const restore = (p: TrashedPage) => run(() => api.pages.restore(p.id));
function purge(p: TrashedPage) {
if (!confirm(t("page.confirmPurge", { title: p.title || t("home.untitled") }))) return;
run(() => api.pages.purge(p.id));
}
// 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>
<article class="mx-auto max-w-doc px-4 pt-8 pb-16 sm:px-16 sm:pt-12">
<DwCallout v-if="notFound" tone="info" size="ui">{{ $t("space.notFound") }}</DwCallout>
<template v-if="space">
<DwBreadcrumbs
:items="[{ label: space.name, to: { name: 'space', params: { id: space.id } } }, { label: $t('sidebar.trash') }]"
:label="$t('page.breadcrumbs')"
/>
<h1 class="mt-6 font-serif text-doc-h1">{{ $t("sidebar.trash") }}</h1>
<p class="mt-2 text-ui-md text-ink-muted">{{ $t("trash.hint") }}</p>
<PageList v-if="items.length" :items="items" class="mt-8" data-testid="trash-list">
<template #meta="{ item }">{{ $t("trash.deletedAt", { date: when(item.deletedAt) }) }}</template>
<template v-if="spaceAtLeast(space.role, 'editor')" #actions="{ item }">
<DwButton size="sm" icon="restore" :disabled="busy" @click="restore(item)">{{ $t("page.restore") }}</DwButton>
<DwButton v-if="spaceAtLeast(space.role, 'admin')" size="sm" variant="danger" :disabled="busy" @click="purge(item)">
{{ $t("page.deleteForever") }}
</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("trash.empty") }}
</div>
</template>
</article>
</template>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import type { Organization } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { useApi } from "../../api";
@@ -47,17 +47,17 @@ async function submit() {
<template>
<PageShell :title="$t('workspace.newTitle')" :subtitle="$t('workspace.newHint')">
<form class="space-y-4 rounded-xl border border-border bg-surface p-6" @submit.prevent="submit">
<form class="space-y-4 dw-card" @submit.prevent="submit">
<FormField v-model="name" :label="$t('workspace.name')" required :error="errors.fields.value.name" />
<label v-if="isSuperadmin" class="block space-y-1 text-sm">
<span class="font-medium">{{ $t("workspace.organization") }}</span>
<select v-model="organization" required class="w-full rounded-md border border-border bg-surface px-3 py-2">
<label v-if="isSuperadmin" class="flex flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("workspace.organization") }}</span>
<select v-model="organization" required class="dw-input w-full">
<option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
<span v-if="!orgs.length" class="text-xs text-fg-muted">{{ $t("workspace.noOrgs") }}</span>
<span v-if="!orgs.length" class="text-ui-sm text-ink-muted">{{ $t("workspace.noOrgs") }}</span>
</label>
<p v-if="errors.message.value" role="alert" class="text-sm text-red-600">{{ errors.message.value }}</p>
<DwButton type="submit" :disabled="busy || !name.trim() || (isSuperadmin && !organization)">
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<DwButton type="submit" variant="primary" :disabled="busy || !name.trim() || (isSuperadmin && !organization)">
{{ $t("workspace.create") }}
</DwButton>
</form>
@@ -1,6 +1,6 @@
<script setup lang="ts">
import type { Workspace, WorkspaceMember, WorkspaceRole } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { DwButton, DwCallout } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
@@ -85,7 +85,6 @@ async function removeWorkspace() {
}
}
const inputClass = "rounded-md border border-border bg-surface px-3 py-1.5 text-sm outline-none focus:border-brand-500";
</script>
<template>
@@ -93,23 +92,21 @@ const inputClass = "rounded-md border border-border bg-surface px-3 py-1.5 text-
:title="ws?.name ?? $t('workspace.settings')"
:subtitle="ws ? $t('workspace.yourRole', { role: $t(`workspace.roles.${ws.role}`), org: ws.organizationName }) : undefined"
>
<p v-if="notFound" class="text-sm text-fg-muted">{{ $t("workspace.notFound") }}</p>
<p v-if="errors.message.value" role="alert" class="rounded-md bg-red-500/10 px-3 py-2 text-sm text-red-600">
{{ errors.message.value }}
</p>
<p v-if="notFound" class="text-ui-md text-ink-muted">{{ $t("workspace.notFound") }}</p>
<DwCallout v-if="errors.message.value" tone="danger" size="ui">{{ errors.message.value }}</DwCallout>
<template v-if="ws">
<form v-if="canManage" class="flex flex-wrap items-end gap-2 rounded-xl border border-border bg-surface p-6" @submit.prevent="rename">
<label class="min-w-48 flex-1 space-y-1 text-sm">
<span class="font-medium">{{ $t("workspace.name") }}</span>
<input v-model="name" required maxlength="120" :class="[inputClass, 'w-full']" />
<form v-if="canManage" class="flex flex-wrap items-end gap-2 dw-card" @submit.prevent="rename">
<label class="flex min-w-48 flex-1 flex-col gap-1.5">
<span class="text-ui-sm font-semibold">{{ $t("workspace.name") }}</span>
<input v-model="name" required maxlength="120" class="dw-input w-full" />
</label>
<DwButton type="submit" :disabled="busy || !name.trim() || name.trim() === ws.name">{{ $t("common.save") }}</DwButton>
<DwButton type="submit" variant="primary" :disabled="busy || !name.trim() || name.trim() === ws.name">{{ $t("common.save") }}</DwButton>
</form>
<section class="rounded-xl border border-border bg-surface p-6">
<h2 class="font-medium">{{ $t("workspace.members") }}</h2>
<p class="mt-1 text-xs text-fg-muted">{{ $t("workspace.cascadeHint") }}</p>
<section class="dw-card">
<h2 class="text-ui-lg">{{ $t("workspace.members") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("workspace.cascadeHint") }}</p>
<form v-if="canManage" class="mt-4 flex flex-wrap gap-2" @submit.prevent="addMember">
<input
@@ -118,35 +115,35 @@ const inputClass = "rounded-md border border-border bg-surface px-3 py-1.5 text-
required
:placeholder="$t('auth.email')"
:aria-label="$t('auth.email')"
:class="[inputClass, 'min-w-48 flex-1']"
class="dw-input min-w-48 flex-1"
/>
<select v-model="newRole" :aria-label="$t('workspace.role')" :class="inputClass">
<select v-model="newRole" :aria-label="$t('workspace.role')" class="dw-input">
<option v-for="r in roles" :key="r" :value="r">{{ $t(`workspace.roles.${r}`) }}</option>
</select>
<DwButton type="submit" :disabled="busy || !email">{{ $t("workspace.add") }}</DwButton>
</form>
<ul class="mt-4 divide-y divide-border">
<ul class="mt-4 divide-y divide-line">
<li v-for="m in members" :key="m.user.id" class="flex flex-wrap items-center justify-between gap-2 py-2" data-testid="member">
<div class="min-w-0">
<p class="truncate text-sm font-medium">{{ m.user.name }}</p>
<p class="truncate text-xs text-fg-muted">{{ m.user.email }}</p>
<p class="truncate text-ui-md font-medium">{{ m.user.name }}</p>
<p class="truncate text-ui-sm text-ink-muted">{{ m.user.email }}</p>
</div>
<div class="flex items-center gap-3 text-sm">
<div class="flex items-center gap-3 text-ui-md">
<select
v-if="canChange(m)"
:value="m.role"
:aria-label="$t('workspace.role')"
:class="inputClass"
class="dw-input"
:disabled="busy"
@change="setRole(m, ($event.target as HTMLSelectElement).value as WorkspaceRole)"
>
<option v-for="r in roles" :key="r" :value="r">{{ $t(`workspace.roles.${r}`) }}</option>
</select>
<span v-else class="text-fg-muted">{{ $t(`workspace.roles.${m.role}`) }}</span>
<span v-else class="text-ink-muted">{{ $t(`workspace.roles.${m.role}`) }}</span>
<button
v-if="canChange(m) || m.user.id === auth.user?.id"
class="text-red-600 hover:underline"
class="text-danger hover:underline"
:disabled="busy"
@click="removeMember(m)"
>
@@ -154,14 +151,14 @@ const inputClass = "rounded-md border border-border bg-surface px-3 py-1.5 text-
</button>
</div>
</li>
<li v-if="!members.length" class="py-2 text-sm text-fg-muted">{{ $t("workspace.noMembers") }}</li>
<li v-if="!members.length" class="py-2 text-ui-md text-ink-muted">{{ $t("workspace.noMembers") }}</li>
</ul>
</section>
<section v-if="atLeast(myRole, 'owner')" class="rounded-xl border border-border bg-surface p-6">
<h2 class="text-sm font-medium">{{ $t("org.dangerTitle") }}</h2>
<p class="mt-1 text-xs text-fg-muted">{{ $t("workspace.deleteHint") }}</p>
<DwButton variant="secondary" class="mt-3 !text-red-600" :disabled="busy" @click="removeWorkspace">
<section v-if="atLeast(myRole, 'owner')" class="dw-card">
<h2 class="text-ui-lg">{{ $t("org.dangerTitle") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("workspace.deleteHint") }}</p>
<DwButton variant="secondary" class="mt-3 !text-danger" :disabled="busy" @click="removeWorkspace">
{{ $t("workspace.delete") }}
</DwButton>
</section>
+372
View File
@@ -460,6 +460,300 @@ paths:
"204": { description: Removed }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/spaces:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listSpaces
tags: [spaces]
summary: Spaces of a workspace the caller can open, with their effective space role
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Space" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createSpace
tags: [spaces]
summary: Create a space (workspace admin or above)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [name]
properties:
name: { type: string, maxLength: 120 }
description: { type: string, maxLength: 1000 }
icon: { type: string, maxLength: 32 }
visibility: { $ref: "#/components/schemas/SpaceVisibility" }
responses:
"201":
description: Created
content:
application/json:
schema: { $ref: "#/components/schemas/Space" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getSpace
tags: [spaces]
summary: One space with the caller's space role
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Space" }
"404": { $ref: "#/components/responses/Error" }
patch:
operationId: updateSpace
tags: [spaces]
summary: Change a space's settings (space admin); only the fields sent change
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
name: { type: string, maxLength: 120 }
description: { type: string, maxLength: 1000 }
icon: { type: string, maxLength: 32 }
visibility: { $ref: "#/components/schemas/SpaceVisibility" }
defaultRole: { $ref: "#/components/schemas/SpaceDefaultRole" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Space" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteSpace
tags: [spaces]
summary: Delete a space with all of its pages (workspace admin or above)
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/members:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listSpaceMembers
tags: [spaces]
summary: Explicit space members (workspace admins manage every space without being listed)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/SpaceMember" } }
"404": { $ref: "#/components/responses/Error" }
put:
operationId: setSpaceMember
tags: [spaces]
summary: Add a workspace member to the space or change their role (space admin)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [email, role]
properties:
email: { type: string, format: email }
role: { $ref: "#/components/schemas/SpaceRole" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/SpaceMember" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/members/{userId}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
- { name: userId, in: path, required: true, schema: { type: string } }
delete:
operationId: removeSpaceMember
tags: [spaces]
summary: Remove a space member (space admin; anyone may leave)
security: [{ bearer: [] }]
responses:
"204": { description: Removed }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/pages:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listPages
tags: [pages]
summary: >-
The space's live page tree as a flat list in depth-first order, siblings
sorted by position. Pages in the trash, and everything under them, are left out.
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/PageNode" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createPage
tags: [pages]
summary: Create a page (editor)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
parent: { type: string, description: Parent page id; empty or missing for the top level }
title: { type: string, maxLength: 500 }
index: { type: integer, minimum: 0, description: Position among the parent's children; missing appends }
responses:
"201":
description: Created
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/spaces/{id}/trash:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listTrash
tags: [pages]
summary: Trashed pages, newest first (pages inside a trashed page come back with it)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/TrashedPage" } }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getPage
tags: [pages]
summary: One page with its breadcrumbs and the caller's space role
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Page" }
"404": { $ref: "#/components/responses/Error" }
patch:
operationId: updatePage
tags: [pages]
summary: Rename a page or change its icon (editor)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
title: { type: string, maxLength: 500 }
icon: { type: string, maxLength: 32 }
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" }
delete:
operationId: deletePage
tags: [pages]
summary: >-
Move a page and its subtree to the trash (editor). With permanent=true,
delete a page that is already in the trash for good (space admin).
security: [{ bearer: [] }]
parameters:
- { name: permanent, in: query, schema: { type: boolean } }
responses:
"204": { description: Deleted }
"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 } }
post:
operationId: movePage
tags: [pages]
summary: Move a page with its subtree within its space (editor)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [index]
properties:
parent: { type: string, description: New parent page id; empty for the top level }
index: { type: integer, minimum: 0, description: Position among the new parent's other children }
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}/restore:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: restorePage
tags: [pages]
summary: Take a page out of the trash (editor); it goes to the top level if its parent is gone
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Page" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
components:
securitySchemes:
bearer:
@@ -572,6 +866,84 @@ components:
email: { type: string }
name: { type: string }
role: { $ref: "#/components/schemas/WorkspaceRole" }
SpaceRole:
type: string
enum: [admin, editor, commenter, viewer]
SpaceDefaultRole:
type: string
enum: [editor, commenter, viewer]
description: Role that workspace members (not guests) get in an open space without an explicit role.
SpaceVisibility:
type: string
enum: [open, private]
description: open - every workspace member gets the default role; private - explicit members only.
Space:
type: object
required: [id, workspace, name, slug, icon, description, visibility, defaultRole, role, created]
properties:
id: { type: string }
workspace: { type: string }
name: { type: string }
slug: { type: string }
icon: { type: string }
description: { type: string }
visibility: { $ref: "#/components/schemas/SpaceVisibility" }
defaultRole: { $ref: "#/components/schemas/SpaceDefaultRole" }
role: { $ref: "#/components/schemas/SpaceRole" }
created: { type: string }
SpaceMember:
type: object
required: [user, role]
properties:
user:
type: object
required: [id, email, name]
properties:
id: { type: string }
email: { type: string }
name: { type: string }
role: { $ref: "#/components/schemas/SpaceRole" }
PageNode:
type: object
required: [id, parent, title, icon, position, updated]
properties:
id: { type: string }
parent: { type: string, description: Parent page id; empty at the top level }
title: { type: string }
icon: { type: string }
position: { type: string, description: Fractional sort key among siblings }
updated: { type: string }
PageRef:
type: object
required: [id, title, icon]
properties:
id: { type: string }
title: { type: string }
icon: { type: string }
Page:
type: object
required: [id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, ancestors, role]
properties:
id: { type: string }
workspace: { type: string }
space: { type: string }
parent: { type: string }
title: { type: string }
icon: { type: string }
created: { type: string }
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 }
ancestors: { type: array, items: { $ref: "#/components/schemas/PageRef" }, description: Root first }
role: { $ref: "#/components/schemas/SpaceRole" }
TrashedPage:
type: object
required: [id, title, icon, deletedAt]
properties:
id: { type: string }
title: { type: string }
icon: { type: string }
deletedAt: { type: string }
Session:
type: object
required: [token, user]
-181
View File
@@ -1,181 +0,0 @@
# Docwell — Competitive Feature Inventory
Research date: 2026-10-30. Sources: product sites and GitHub READMEs of the five reference apps, plus prior product knowledge. Notion is closed source; the other four are open source.
## 1. Reference apps at a glance
| | Docmost | Outline | AppFlowy | AFFiNE | Notion |
|---|---|---|---|---|---|
| Repo | `docmost/docmost` | `outline/outline` | `AppFlowy-IO/AppFlowy` (+ `AppFlowy-Cloud`) | `toeverything/AFFiNE` (+ `blocksuite`) | closed |
| Stars (Oct 2026) | ~22k | ~41k | ~78k | ~74k | — |
| License | AGPL-3.0 core + separate EE license (`ee/` dirs) | BSL 1.1 (converts to Apache 2.0 after a delay) | AGPL-3.0 | MIT (Community Edition) | proprietary |
| Frontend | React + Mantine, Vite | React + MobX + styled-components | Flutter (desktop + mobile), Next.js web | React + Jotai, Vite | React |
| Backend | NestJS (TypeScript), PostgreSQL, Redis | Node.js/Koa (TypeScript), PostgreSQL (Sequelize), Redis | Rust (Actix) — Postgres, Redis, S3/MinIO, GoTrue auth | NestJS + Rust via napi-rs, PostgreSQL, Redis | — |
| Editor | Tiptap (ProseMirror) | ProseMirror (custom) | appflowy_editor (Flutter) | BlockSuite (custom, Lit web components) | custom block editor |
| Realtime/CRDT | Yjs + Hocuspocus | Yjs (y-prosemirror) | Rust Yrs ("collab" crate) | Yjs on web, y-octo (Rust Yjs port) natively | operational model, proprietary |
| Desktop | — (web/PWA) | — (web; unofficial wrappers) | Flutter native | Electron | Electron |
| Mobile | responsive web | responsive web | Flutter native | native apps | native |
| Local-first / offline | no | no | yes | yes | partial (offline pages) |
| Monorepo tooling | pnpm + Nx | yarn | Cargo + Flutter | yarn + Cargo | — |
**What this tells us:** the open-source wikis (Docmost, Outline) all use **ProseMirror/Tiptap + Yjs** and a server-authoritative model. The "Notion alternatives" (AppFlowy, AFFiNE) are **local-first** apps with their own CRDT engines and native clients. Docwell starts with the first model and adds the second step by step.
## 2. Feature inventory
Columns show which reference app has each feature: **D**ocmost, **O**utline, **A**ppFlowy, a**F**FiNE, **N**otion. The **Docwell** column gives our priority: **M** = MVP, **1** = v1.0, **2** = v2.x, **X** = out of scope or later.
### 2.1 Editor and content blocks
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Rich text (bold/italic/underline/strike/code/highlight/color) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Headings, lists (bullet/numbered/todo), quotes, dividers | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Slash command menu (`/`) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Markdown shortcuts (`#`, `-`, `[]`, `` ``` ``) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Floating / bubble formatting toolbar | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Drag handle to move blocks | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Code blocks with syntax highlighting | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Tables (resizable, merge cells) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Callouts / info panels | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Toggle / collapsible blocks | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Columns / multi-column layout | – | – | ✓ | ✓ | ✓ | 2 |
| Images (upload, paste, resize, caption) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| File attachments, video, audio | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Math / LaTeX (inline + block) | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Mermaid diagrams | ✓ | ✓ | – | – | ✓ | 1 |
| Draw.io / Excalidraw diagrams | ✓ | – | – | – | – | 1 |
| Embeds (YouTube, Figma, Loom, Miro, Airtable, Google Docs…) | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Link previews / bookmark cards | – | ✓ | ✓ | ✓ | ✓ | 1 |
| @mentions (users, pages, dates) | ✓ | ✓ | ✓ | ✓ | ✓ | M (users/pages), 1 (dates/reminders) |
| Emoji picker, page icon and cover | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Table of contents block | – | ✓ | ✓ | – | ✓ | 1 |
| Synced / transcluded blocks | – | – | – | ✓ | ✓ | 2 |
| Block links (deep link to a block) | – | ✓ | ✓ | ✓ | ✓ | 1 |
| Find and replace in page | ✓ | ✓ | ✓ | – | ✓ | 1 |
| Page width toggle, font choice | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Whiteboard / edgeless canvas | – | – | – | ✓ | – | X (Excalidraw embed covers it) |
| Slides / presentation mode | – | – | – | ✓ | – | X |
### 2.2 Organization and navigation
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Workspaces (tenant) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Spaces / collections / teamspaces | ✓ | ✓ | ✓ | – | ✓ | M |
| Nested page tree, drag-and-drop reorder | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Favorites / starred | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Recently viewed / edited | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Breadcrumbs | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Backlinks ("linked from") | – | ✓ | – | ✓ | ✓ | 1 |
| Tags | – | – | – | ✓ | – | 2 |
| Templates (workspace and space level) | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Trash with restore | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Archive | – | ✓ | – | – | ✓ | 1 |
| Command palette / quick switcher (Ctrl+K) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Journals / daily notes | – | – | – | ✓ | – | 2 |
| Pinned docs on space home | – | ✓ | – | – | – | 1 |
### 2.3 Collaboration
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Real-time co-editing (CRDT) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Live cursors and presence avatars | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Inline comments on selections | ✓ | ✓ | ✓ | – | ✓ | M |
| Threads, resolve, reactions | ✓ | ✓ | ✓ | – | ✓ | 1 |
| Page history and version restore | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Version diff view | – | ✓ | – | – | – | 1 |
| Notifications (in-app + email) | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Watch / subscribe to page | – | ✓ | – | – | ✓ | 1 |
| Suggesting mode (tracked changes) | – | – | – | – | ✓ | 2 |
| Page analytics (views, who viewed) | – | ✓ | – | – | ✓ | 2 |
| Verified pages / expiry reminders | – | – | – | – | ✓ | 2 |
### 2.4 Databases (Notion-style structured data)
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Inline + full-page databases | – | – | ✓ | ✓ | ✓ | 2 |
| Views: table/grid | – | – | ✓ | ✓ | ✓ | 2 |
| Views: board / kanban | – | – | ✓ | ✓ | ✓ | 2 |
| Views: calendar | – | – | ✓ | – | ✓ | 2 |
| Views: gallery, list, timeline/Gantt, chart | – | – | partial | – | ✓ | X / later |
| Property types (text, number, select, multi-select, date, person, checkbox, URL, files) | – | – | ✓ | ✓ | ✓ | 2 |
| Relations, rollups, formulas | – | – | partial | – | ✓ | X / later |
| Filters, sorts, grouping | – | – | ✓ | ✓ | ✓ | 2 |
| Row opens as a full page | – | – | ✓ | ✓ | ✓ | 2 |
| Forms that write to a database | – | – | – | – | ✓ | X |
| Automations / buttons | – | – | – | – | ✓ | X |
### 2.5 Search and AI
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Full-text search across workspace | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Search filters (space, author, date) | ✓ | ✓ | – | – | ✓ | 1 |
| Search in attachments (PDF/DOCX text) | EE | – | – | – | ✓ | 2 |
| AI writing assistant (rewrite, summarize, translate) | EE | ✓ | ✓ | ✓ | ✓ | 2 |
| AI Q&A over the workspace (RAG with citations) | EE | ✓ | ✓ | ✓ | ✓ | 2 |
| Bring-your-own model / local LLM (Ollama) | – | – | ✓ | – | – | 2 |
| AI agents / automations | – | – | – | – | ✓ | X |
### 2.6 Sharing, permissions, security
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Roles: owner / admin / member / guest | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| User groups | ✓ | ✓ | – | – | ✓ | M |
| Space-level permissions | ✓ | ✓ | ✓ | – | ✓ | M |
| Page-level permissions / restrictions | EE | ✓ | – | – | ✓ | 1 |
| Public share links (read-only) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Publish as public site / custom domain | – | ✓ | ✓ | ✓ | ✓ | 2 |
| Guest / external collaborators | – | ✓ | ✓ | ✓ | ✓ | 1 |
| Email + password, magic link | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| OAuth (Google, GitHub, Microsoft) | – | ✓ | ✓ | ✓ | ✓ | 1 |
| OIDC / SAML SSO | EE | ✓ | ✓ | – | ✓ | 1 (OIDC), 2 (SAML) |
| LDAP | EE | – | – | – | – | 2 |
| MFA (TOTP) | EE | – | – | – | ✓ | 1 |
| SCIM provisioning | – | – | – | – | ✓ | 2 |
| Audit log | EE | ✓ | – | – | ✓ | 1 |
| Domain allow-list for signups | ✓ | ✓ | – | – | ✓ | M |
### 2.7 Import, export, integrations, API
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Import Markdown / HTML | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Import Notion export (zip) | ✓ | ✓ | ✓ | ✓ | – | 1 |
| Import Confluence | EE | ✓ | – | – | ✓ | 2 |
| Import DOCX | ✓ | ✓ | – | – | ✓ | 1 |
| Export Markdown / HTML | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Export PDF | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Export whole space / workspace (zip) | ✓ | ✓ | ✓ | ✓ | ✓ | 1 |
| Public REST API + API tokens | EE | ✓ | ✓ | – | ✓ | 1 |
| Webhooks | – | ✓ | – | – | ✓ | 1 |
| Slack integration (unfurl, notifications, search) | – | ✓ | – | – | ✓ | 2 |
| GitHub / Linear / Figma unfurls | – | ✓ | – | – | ✓ | 2 |
| MCP server (AI-agent access to docs) | – | ✓ | – | – | ✓ | 2 |
| Plugin / extension system | – | ✓ (internal) | ✓ | planned | – | 2 |
### 2.8 Platform and UX
| Feature | D | O | A | F | N | Docwell |
|---|---|---|---|---|---|---|
| Dark mode | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| i18n (10+ languages) | ✓ | ✓ | ✓ | ✓ | ✓ | M (framework + EN/PL), 1 (more) |
| Responsive web / PWA | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Native desktop app | – | – | ✓ | ✓ | ✓ | 1 (Wails) |
| Native mobile apps | – | – | ✓ | ✓ | ✓ | 1 (Flutter) |
| Offline editing + sync | – | – | ✓ | ✓ | partial | 2 (desktop first) |
| Keyboard shortcuts and help sheet | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Self-host via Docker / docker-compose | ✓ | ✓ | ✓ | ✓ | – | M |
| Admin panel (users, settings, usage, license) | ✓ | ✓ | ✓ | ✓ | ✓ | M |
| Storage backends: local disk / S3 | ✓ | ✓ | ✓ | ✓ | – | M |
| Email (SMTP) configuration | ✓ | ✓ | ✓ | ✓ | – | M |
## 3. Where Docwell can stand out
1. **Single-binary simplicity.** Go server + PocketBase (SQLite) needs no Postgres, Redis or Node. You can self-host it on a $5 VPS or a Raspberry Pi. None of the five competitors offers this.
2. **Truly native clients for every platform from day one**: web, Wails desktop (small binaries, ~15 MB vs Electron's ~150 MB) and Flutter mobile.
3. **Wiki-first, databases second.** Ship the Docmost/Outline feature set first, because that is where users switch. Add AppFlowy/Notion-style databases in v2.
4. **Open core without crippled security.** Docmost and Outline put SSO, MFA or page permissions behind paid tiers. Docwell can include OIDC, MFA and page permissions in the open-source core.
-225
View File
@@ -1,225 +0,0 @@
# Docwell — Architecture and Build Plan
Companion to [FEATURES.md](FEATURES.md), which defines the feature priorities (MVP / v1 / v2) used below.
## 1. Product statement
Docwell is an open-source, self-hostable knowledge base and collaborative document editor. It is wiki-first like Docmost and Outline, and grows into Notion-style databases later, like AppFlowy and AFFiNE. It ships as three standalone services plus native desktop and mobile clients.
## 2. System architecture
```
┌──────────────────────┐ ┌───────────────────┐ ┌───────────────────┐
Clients │ Web App (browser) │ │ Desktop (Wails) │ │ Mobile (Flutter) │
└──────────┬───────────┘ └─────────┬─────────┘ └─────────┬─────────┘
│ HTTPS: REST + WebSocket (all clients use the same API)
─────────────────────────┼──────────────────────────────────────────────────────────
Standalone ┌──────────▼───────────┐ ┌────────────────────────────────────────┐
services │ docwell-web (Go) │ │ docwell-server (Go) │
│ • serves Vue SPA │──▶│ • REST API /api/v1 │
│ • runtime config │ │ • WebSocket collab /collab (Yjs relay) │
│ • optional /api proxy│ │ • auth, permissions, search index │
└──────────────────────┘ │ • jobs: import/export, email, webhooks │
│ • Admin panel (Vue SPA) /admin │
└──────────────────┬─────────────────────┘
│ private network only
┌──────────────────▼─────────────────────┐
│ docwell-db (PocketBase) │
│ • SQLite + collections + migrations │
│ • file storage (local or S3) │
│ • realtime SSE (server subscribes) │
└────────────────────────────────────────┘
```
### 2.1 Responsibilities
| Service | Owns | Does NOT do |
|---|---|---|
| **docwell-db** (PocketBase, unmodified official binary + `pb_migrations/` + optional `pb_hooks/`) | Persistence, schema migrations, file blobs, backups, low-level realtime events | Business rules. Its collection API rules allow **only the server's superuser token**, so it is never exposed publicly. |
| **docwell-server** (Go) | Single public API, authentication and sessions, authorization (workspace/space/page ACLs), Yjs collaboration relay and persistence, search index, background jobs, email, webhooks, API tokens. Hosts the **admin panel** (embedded Vue build). | Rendering the end-user UI |
| **docwell-web** (Go) | Serves the end-user Vue SPA (embedded via `embed.FS`), injects runtime config (`/config.json` with API URL, branding, enabled auth providers), sets security headers and caching, can optionally reverse-proxy `/api` + `/collab` for single-origin deployments | Business logic. It is a thin delivery service, so the SPA can also be hosted on any CDN. |
**Why the server is the only gateway to PocketBase:** permission rules in a wiki depend on space membership, group membership and page-level overrides. Those rules are awkward to express as PocketBase API-rule strings, and splitting auth logic across two places is a security risk. Keeping PocketBase private also lets us swap it for Postgres later behind a Go `Store` interface.
### 2.2 Key technical decisions (ADR summaries)
| # | Decision | Rationale / alternatives |
|---|---|---|
| ADR-1 | **Editor = Tiptap 2/3 (ProseMirror) for web and desktop**, with `@tiptap/vue-3` | This is the stack Docmost uses and close to what Outline uses. It has a large extension ecosystem (tables, math, mentions, collaboration) and is MIT licensed. |
| ADR-2 | **CRDT = Yjs** (`y-prosemirror`, `y-indexeddb`, Awareness for cursors) | Industry standard, and both Docmost and Outline use it. |
| ADR-3 | **The Go server relays the y-websocket / Hocuspocus-compatible protocol** and stores incremental updates. Compaction (merging updates into a snapshot, and extracting plain text and JSON for search and exports) runs **Yrs compiled to WASM inside Go via `wazero`**, so there is no cgo and no Node sidecar. | There is no mature pure-Go Yjs port. Options considered: (a) a Node Hocuspocus sidecar, which breaks the "Go only" goal; (b) cgo + yffi, which complicates cross-compiling; (c) client-side compaction, which you can't trust. **(d) wazero + yrs.wasm** was chosen — **spike passed** ([ADR-3](adr/0003-yrs-wasm-wazero.md)): output matches y-prosemirror, steady-state compaction takes milliseconds, WebAssembly costs ≤2× native. Compact incrementally (snapshot + new updates); never `merge_updates` on long logs, which is quadratic. |
| ADR-4 | **Mobile editor = the same Tiptap editor bundle running inside a Flutter WebView** (`webview_flutter` or `flutter_inappwebview`), bridged over JS channels. Navigation, lists, search, settings and comments are native Flutter. | Writing a second rich-text engine in Dart with identical schema and Yjs semantics is months of work and a constant source of divergence. AppFlowy built its own Flutter editor, but its data model is native to that editor. Revisit a native Dart editor in v2+. |
| ADR-5 | **Search = Bleve** (pure Go, embedded in the server) with an optional **Meilisearch** adapter | PocketBase does not expose SQLite FTS5 through its API. Bleve keeps the "no extra service" promise. The search code sits behind an interface so you can swap the backend. |
| ADR-6 | **Authentication = PocketBase's built-in `users` auth collection** — **decided**. PocketBase stores the credentials and issues the tokens, and also handles password, OTP email codes, MFA, OAuth2, verification and password-reset emails (via its own SMTP settings). PocketBase stays private: clients call `/api/v1/auth/*` on docwell-server, which forwards to PocketBase. The server checks bearer tokens through a small hook route (`pb_hooks/docwell.pb.js`, cached 30 s) and adds Docwell's rules: signup policy and domain allow-list, `status = disabled` blocks sign-in (PocketBase `authRule`), and the first account becomes the superadmin (see ADR-12). **Authorization** (workspace, space and page permissions) stays in docwell-server. | Less security-critical code to write and maintain, and auth features (MFA, OTP, OAuth2) come out of the box. Trade-offs: tokens are PocketBase JWTs, so sign-out is client-side (to revoke every session, rotate the user's `tokenKey`), and swapping PocketBase for Postgres later would need a token migration plan. |
| ADR-7 | **Frontend monorepo with shared packages** (npm workspaces): `@docwell/editor`, `@docwell/ui`, `@docwell/api-client` (generated from OpenAPI), `@docwell/i18n` | Web app, admin panel, desktop app and mobile WebView all reuse the same editor and UI kit. |
| ADR-8 | **API contract = OpenAPI 3.1 written first** → Go server stubs (`oapi-codegen`) + TS client (`openapi-typescript`) + Dart client (`openapi-generator`) | Keeps four clients in sync. |
| ADR-9 | **Background jobs = in-process worker pool** with a PocketBase `jobs` collection as a durable queue (no Redis) | Fits a single-node deployment. For multi-node later, add NATS or Redis behind an interface. |
| ADR-10 | **License = AGPL-3.0** for the whole repository (services, apps and packages) — **decided** | Same license as Docmost and AppFlowy. Anyone who runs a modified Docwell as a hosted service must publish their changes. |
| ADR-11 | **Desktop = Wails v3** — **decided** | v3 adds multi-window support, a system tray, a better bindings generator and a cleaner app/service API than v2. Pin an exact v3 version and upgrade on purpose. |
| ADR-12 | **Organizations above workspaces, with cascading rights (same model as DriverVault)** — **decided**. Each user belongs to at most one organization (`users.organization`) and has an instance role (`users.role`): `superadmin` manages everything, `admin` manages only their own organization, `user` is a plain member. Workspaces belong to an organization. Rights cascade: a superadmin owns every workspace, an org admin owns every workspace of their organization, and anyone else gets their explicit workspace role (owner > admin > member > guest), and only while they belong to that organization. Nobody grants a role above their own, acts on someone ranked above them, or changes their own role. A user without an organization can create one and becomes its admin; an admin can delete their organization only as its last member (with no workspaces left) and is demoted to user. All rules live in `Server/internal/access` as pure, tested functions. | Same mental model as DriverVault, so both products behave alike. One organization per user keeps permission checks simple (one role, one tenant); multi-organization membership can come later through a join table without changing the rule functions. |
### 2.3 Scaling note (PocketBase = SQLite)
SQLite in WAL mode can handle a few thousand active users on a single node, and that covers the self-host market. The limits to know about: one writer at a time, and a single node, because the collab relay keeps doc rooms in memory. Mitigations: batch Yjs update writes (debounce 1–2 s per doc), store large blobs as files, keep the `Store` interface DB-agnostic, and plan a "Postgres store" plus a "Redis/NATS pub-sub for collab rooms" for horizontal scale in v2+.
## 3. Repository layout (monorepo)
Scaffolded in Phase 0. Folders marked *(planned)* do not exist yet.
```
Docwell/
├── api/openapi.yaml # API contract (source of truth for all clients)
├── Database/ # docwell-db: official PocketBase + pb_migrations/ + pb_hooks/
├── Server/ # docwell-server (Go module docwell/server)
│ ├── cmd/docwell-server/
│ ├── internal/
│ │ ├── httpapi/ # router (net/http ServeMux), CORS, logging, handlers
│ │ ├── config/
│ │ ├── store/pocketbase # superuser REST client
│ │ ├── admin/ # embeds the admin SPA build (dist/)
│ │ └── auth, acl, collab, ycrdt, search, jobs, importer, exporter, mail (planned)
│ └── admin/ # admin panel: Vue 3 + Vite + Tailwind (@docwell/admin)
├── Web-App/ # docwell-web (Go module docwell/web)
│ ├── cmd/docwell-web/
│ ├── internal/spa/ # embeds the web app build, /config.json, optional proxy
│ └── frontend/ # end-user app: Vue 3 + Vite + Tailwind (@docwell/web-app)
├── Desktop-App/ # Wails v3 (Go module docwell/desktop)
│ └── frontend/ # thin host that mounts @docwell/web-app with a desktop platform
├── Phone-App/ # Flutter (android + ios)
├── Packages/
│ ├── editor/ # @docwell/editor – Tiptap schema + Vue component
│ ├── ui/ # @docwell/ui – Tailwind theme tokens + components
│ ├── api-client/ # @docwell/api-client – TS client, types generated from api/
│ └── editor-bridge/, i18n/ (planned)
├── Docker/ # docker-compose: db + server + web as separate services
├── Docker-AIO/ # single all-in-one image (PocketBase + server + web)
├── Design/ # design assets
├── docs/
├── go.work # Go workspace: Server, Web-App, Desktop-App
└── package.json # npm workspaces
```
## 4. Tech stack details
| Layer | Choice |
|---|---|
| Go | Go 1.26, stdlib `net/http` router (method + wildcard patterns), `nhooyr.io/websocket` (now `coder/websocket`), `slog`, `koanf` config, `oapi-codegen`, `wazero`, `bleve/v2`, `go-oidc`, `pquerna/otp`, `testify` + `testcontainers-go` (spins up PocketBase) |
| PocketBase | Official binary pinned to a version, used standalone, with JS migrations. The server talks to it through a thin typed REST client and authenticates with a superuser token |
| Vue (web, admin, desktop) | Vue 3.5 + `<script setup>` TS, Vite, Pinia, Vue Router, VueUse, TanStack Query (vue), Tailwind CSS 4, Reka UI (headless), `vue-i18n`, Lucide icons |
| Editor | Tiptap + extensions: StarterKit, Collaboration, CollaborationCaret, Table, TaskList, Mention, Placeholder, CodeBlockLowlight, Image, Mathematics (KaTeX), plus custom: Callout, Embed, Mermaid, Drawio, Excalidraw, Toggle, PageLink, Attachment |
| Desktop | Wails v3 (Go backend + embedded webview; Go services bound to the frontend through generated TS bindings). Uses the `apps/web` UI with a desktop adapter: native menus, tray, deep links `docwell://`, OS keychain token storage, auto-update, multi-server accounts. v2: local SQLite cache + offline Yjs |
| Mobile | Flutter 3.x, Riverpod, go_router, dio + generated Dart client, `flutter_secure_storage`, `flutter_inappwebview` editor host, push via FCM/APNs (server sends through ntfy/Gotify or direct FCM) |
| CI/CD | GitHub Actions: lint/test per package, build multi-arch Docker images (GHCR), Wails builds (win/mac/linux), Flutter builds (apk/ipa), release-please, Renovate |
| Quality | golangci-lint, ESLint + Prettier, Vitest, Playwright E2E, `flutter test`, k6 load test on the collab relay |
## 5. Data model (PocketBase collections)
| Collection | Key fields |
|---|---|
| `organizations` | name (unique, case-insensitive), settings(json: middle layer of the settings cascade instance → organization → user) |
| `workspaces` | organization (required), name, slug, logo(file), settings(json) |
| `users` (PocketBase **auth** collection) | built-in: email, password, tokenKey, verified, name, avatar; Docwell fields: role (user/admin/superadmin), organization (non-cascading), status (active/invited/disabled), locale, theme, last_seen |
| `workspace_members` | workspace, user, role (owner/admin/member/guest) |
| `groups`, `group_members` | workspace, name / group, user |
| `spaces` | workspace, name, slug, icon, description, visibility (open/private), default_permission |
| `space_members` | space, principal_type (user/group), principal_id, role (admin/editor/commenter/viewer) |
| `pages` | workspace, space, parent (self-ref), position (fractional index string), title, icon, cover(file), creator, last_editor, is_template, archived_at, deleted_at, content_json (latest JSON snapshot), content_text (plain text), word_count |
| `page_permissions` | page, principal_type, principal_id, role, inherit(bool) |
| `page_ydoc` | page, state (file/bytes: compacted Yjs state), state_vector, updated_at |
| `page_yupdates` | page, update (bytes), client_id, created — compacted and pruned periodically |
| `page_versions` | page, snapshot (Yjs state), content_json, author(s), created, label |
| `comments` | page, thread_root, parent, author, body_json, anchor (Yjs relative position), resolved_at, reactions(json) |
| `attachments` | workspace, page, file, mime, size, uploader |
| `favorites`, `page_views` | user, page / user, page, viewed_at |
| `share_links` | page, token, include_children, expires_at, password_hash, allow_search_index |
| `notifications` | user, type, payload(json), read_at |
| `page_watchers` | page, user |
| `api_tokens` | user, name, token_hash, scopes, last_used, expires_at |
| `webhooks`, `webhook_deliveries` | workspace, url, secret, events[] / status, response |
| `audit_log` | workspace, actor, action, target, ip, ua, meta(json) |
| `jobs` | type, payload, status, attempts, run_at, error |
| v2: `databases`, `db_properties`, `db_rows`, `db_views` | (rows are pages; property values stored as json per row) |
## 6. Collaboration flow
1. The client opens `wss://server/collab?page=<id>` with its session token. The server checks ACLs: viewers get read-only, commenters can only touch comment marks.
2. The server loads the room (in-memory), runs the Yjs sync step 1/2 using `page_ydoc.state` + pending `page_yupdates`, and starts relaying updates and awareness to peers.
3. Incoming updates are appended to an in-memory buffer and flushed to `page_yupdates` every ~1 s (or 50 updates).
4. A compaction job (wazero/yrs) runs on idle (30 s with no edits) or on room close. It merges updates into `page_ydoc.state`, derives `content_json` + `content_text`, updates the search index and backlinks, and creates a `page_versions` entry on a time/size heuristic (e.g. every 10 min of activity, or when the last editor leaves).
5. Comments anchor to Yjs relative positions, so they survive concurrent edits.
## 7. Delivery roadmap
Time estimates assume ~2 full-time developers. Scale them for your team.
### Phase 0 — Foundations (2–3 weeks)
- Monorepo, CI, lint/test scaffolding, license, CONTRIBUTING, Code of Conduct.
- `api/openapi.yaml` v0 (auth, workspaces, spaces, pages), with codegen wired up for Go, TS and Dart.
- docwell-db Docker image + first migrations. Typed Go PocketBase client + `Store` interface.
- **Spikes (go/no-go):** (1) yrs.wasm under wazero: merge updates, extract JSON, benchmark. (2) Tiptap editor in a Flutter WebView with a JS bridge on iOS + Android. (3) Wails v3 app embedding `apps/web`, with tray, deep link and auto-update checked on Windows, macOS and Linux.
- docker-compose that brings up all three services.
### Phase 1 — MVP wiki (8–10 weeks) → release `0.1`
- **Server:** auth (email+password, magic link, invites, domain allow-list), workspaces, members, groups, spaces + space permissions, page tree CRUD + move/reorder, trash, favorites, recents, attachments (local/S3 via PocketBase), Markdown/HTML import + export, Bleve search, SMTP mail, public share links.
- **Collab:** WebSocket relay, persistence, compaction, presence/cursors, page history list + restore.
- **Web app:** login/onboarding, sidebar tree (drag-and-drop), editor with the MVP block set, slash menu, bubble menu, mentions, inline comments (basic), search + Ctrl+K palette, share dialog, trash, settings, dark mode, i18n (EN + PL), responsive layout.
- **Admin panel:** dashboard (users, pages, storage), user management (invite, disable, role, reset), workspace settings (branding, signup rules, auth), SMTP + storage config, PocketBase backup trigger/download, job queue viewer, system health/version.
- **Deploy:** multi-arch images, `docker compose up` quick start, docs site.
### Phase 2 — v1.0 "team ready" (8–10 weeks)
- Page-level permissions, guests, groups in sharing dialog.
- Comment threads, resolve, reactions. Notifications (in-app + email digest). Page watching.
- Version diff view, templates, archive, backlinks, TOC, toggles, math, Mermaid, Draw.io, Excalidraw, embeds, link cards, block links.
- OAuth (Google, GitHub, Microsoft), generic OIDC, TOTP MFA, audit log, API tokens + public REST API, webhooks.
- Notion zip import, DOCX import, PDF export, full space export.
- **Desktop app (Wails) 1.0:** multi-server login, native menus, deep links, keychain, auto-update; Windows/macOS/Linux installers.
- **Mobile app (Flutter) 1.0:** login, workspace/space/page browsing, search, read + edit (WebView editor), comments, notifications (push), share sheet ("save to Docwell"), offline read cache.
### Phase 3 — v2 "Notion-class" (12+ weeks, iterative)
- Databases: inline + full-page, table/board/calendar views, core property types, filters/sorts/grouping, rows as pages.
- AI: provider-agnostic (OpenAI-compatible API, Anthropic, Ollama). Writing assistant in editor. Workspace Q&A with RAG (embeddings stored in SQLite via `sqlite-vec` or in the search backend) and citations. MCP server endpoint for agents.
- Offline-first desktop (local SQLite + y-indexeddb sync queue), then mobile.
- Publish as a public site with a custom domain. SAML, LDAP, SCIM. Confluence import. Slack/GitHub integrations. Plugin API (editor extensions + server webhooks).
- Scale-out option: Postgres `Store` and NATS for collab room fan-out.
## 8. Admin panel scope (docwell-server `/admin`)
| Area | Functions |
|---|---|
| Overview | Active users, pages, storage used, collab rooms online, job queue depth, version + update check |
| Users | List/search, invite, change role, disable, force logout, reset MFA, impersonate (audited) |
| Workspaces | Create/edit, branding (logo, colors, name), default language |
| Authentication | Enable/disable email login, magic link, OAuth providers, OIDC config, domain allow-list, session lifetime, MFA enforcement |
| Storage | Local vs S3 (passes through to PocketBase settings), quotas, orphaned file cleanup |
| Email | SMTP config + test send, templates |
| Search | Reindex, backend selection (Bleve/Meilisearch) |
| Security | Audit log viewer/export, API tokens overview, webhooks |
| Maintenance | Backups (PocketBase snapshot create/download/restore), jobs viewer/retry, logs tail, feature flags |
| AI (v2) | Provider keys, models, usage limits |
## 9. Testing strategy
- **Go:** unit tests per package. Integration tests run against a real PocketBase container (testcontainers). Collab convergence tests drive N simulated Yjs clients doing random edits through the relay and assert identical final state. Fuzz-test the protocol parser.
- **Frontend:** Vitest for stores/composables/editor extensions. Playwright E2E for core journeys (signup → create space → co-edit in two browsers → comment → share link).
- **Mobile:** widget tests and integration tests against the docker-compose stack.
- **Load:** k6 with 500 concurrent editors across 50 rooms. Target p95 update fan-out under 100 ms on a 2 vCPU node.
- **Security:** authz matrix tests (every endpoint × every role), gosec, dependency scanning, CSP + sanitization of pasted HTML.
## 10. Risks and mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| yrs.wasm under wazero is slow or has gaps | Compaction/search extraction blocked | Phase 0 spike. Fallbacks: cgo + yffi, or optional Node sidecar for compaction only |
| WebView editor feels non-native on mobile | Poor mobile UX | Native toolbar above the keyboard in Flutter, tuned scrolling/keyboard insets, prefetch the editor bundle. Native read-only renderer for fast viewing |
| SQLite write contention | Lag at higher scale | Batched writes, WAL, files outside the DB, `Store` interface ready for Postgres |
| PocketBase is pre-1.0 with breaking changes | Upgrade pain | Pin the version, keep usage to the documented REST API + migrations, wrap it in our client, run an upgrade test in CI |
| Wails v3 APIs still changing between releases | Desktop app breaks on upgrade | Pin the exact version, keep Wails-specific code in a thin adapter layer in `apps/desktop`, and run desktop builds in CI on every upgrade |
| Scope creep toward "full Notion" | Never ships | Strict MVP/v1/v2 gates from FEATURES.md. Databases only after v1.0 |
| Four clients drifting apart | Bugs, duplicated work | OpenAPI-first codegen, shared editor package, shared i18n catalog |
## 11. Immediate next steps
1. ~~Confirm the license and the Wails version~~ — decided: AGPL-3.0 for everything, Wails v3. Add the official AGPL-3.0 `LICENSE` text and SPDX headers (`AGPL-3.0-only` or `-or-later`) during scaffolding.
2. Scaffold the monorepo (Phase 0 layout above) and docker-compose with the three services.
3. Run the three Phase 0 spikes and record the results as ADRs in `docs/adr/`. Done: yrs.wasm under wazero ([ADR-3](adr/0003-yrs-wasm-wazero.md), go). Still to do: Tiptap in a Flutter WebView, Wails v3 tray/deep link/auto-update.
4. Write `api/openapi.yaml` v0 and the first PocketBase migrations.
-65
View File
@@ -1,65 +0,0 @@
# ADR-3: Yjs compaction with yrs compiled to WebAssembly, run by wazero
- Status: **accepted** (Phase 0 spike passed, 2026-10-30)
- Spike code: [`Spikes/yrs-wasm/`](../../Spikes/yrs-wasm/README.md)
## Context
The Go server relays Yjs updates between editors and stores them. It also has to read the documents itself: compact the update log into a snapshot, extract ProseMirror JSON for exports and plain text for search, and answer sync step 2 (send a peer what its state vector is missing). There is no mature pure-Go Yjs port. We wanted to avoid a Node sidecar and cgo, so the plan was to compile yrs (the Rust port of Yjs) to WebAssembly and run it in-process with wazero. This spike decides go or no-go.
## What was built
- `rust/`: a ~250-line wrapper around yrs 0.28 compiled to `wasm32-wasip1` (577 KiB). It exports `compact`, `merge`, `state_vector`, `diff`, `to_json` and `to_text` through a tiny pointer-and-length ABI.
- `go/`: a wazero host (`yrs.go`) that embeds the module, plus tests and benchmarks.
- `fixtures/`: generates realistic edit logs with real Yjs (keystroke-by-keystroke typing with headings, lists, bold and links, backspaces and edits to earlier blocks, and three clients editing concurrently). y-prosemirror's `yXmlFragmentToProsemirrorJSON` supplies the expected output. `verify.mjs` checks that Yjs loads what yrs wrote and times Yjs as a baseline.
| Fixture | Updates | Log size | Snapshot | Notes |
|---|---:|---:|---:|---|
| small | 2,277 | 56 KB | 5 KB | ~2k characters |
| medium | 30,804 | 785 KB | 66 KB | ~30k characters, a long page |
| large | 255,566 | 6.8 MB | 553 KB | ~250k characters, a book-length page |
| concurrent | 19,999 | 697 KB | 597 KB | 3 clients, random sync order |
## Results
**Correctness: all pass.**
- yrs JSON matches y-prosemirror exactly on every fixture. This holds whether yrs reads the raw log, a merged update, a compacted snapshot, or a snapshot rebuilt in batches of 500 updates (the server's real pattern).
- Yjs loads every yrs snapshot and produces identical JSON. Snapshots are the same size as Yjs's own but not byte-identical, because encoding order differs. That doesn't matter.
- Sync step 2 (`diff` against a client's state vector) brings a half-synced client to the same document.
- Malformed updates return an error message, and the instance keeps working afterwards.
- 8 goroutines, each with its own instance of one compiled module, run concurrently without problems.
**Speed** (AMD Threadripper 2950X, Go 1.26, wazero 1.12 compiler mode):
| Operation | small | medium | large | concurrent |
|---|---:|---:|---:|---:|
| Compact the full log (one-off) | 4.4 ms | 71 ms | 2.7 s | 80 ms |
| **Compact snapshot + 200 new updates (steady state)** | **0.6 ms** | **2.9 ms** | **23 ms** | **47 ms** |
| JSON from snapshot (export, indexing) | 0.3 ms | 3.5 ms | 33 ms | 42 ms |
| Plain text from snapshot (search) | 0.25 ms | 2.6 ms | 23 ms | 39 ms |
| `merge_updates_v1` on the full log | 67 ms | **13.2 s** | not run | **5.7 s** |
Baselines for the same machine and fixtures:
- Native yrs (no WebAssembly) compacts in 2.7 / 38 / 2,500 / 49 ms and builds JSON in 0.27 / 2.9 / 32 / 32 ms. WebAssembly costs 1.0–1.9×, and the large case is limited by yrs itself.
- Yjs in Node compacts in 20 / 103 / 1,468 / 166 ms, so yrs is in the same range. Its `mergeUpdates` is quadratic too (21.7 s on medium).
**Startup and memory:**
- Compiling the module takes ~350 ms, once per process. Each instance takes 0.5 ms and 1.1 MiB to create.
- Memory grows with the largest document an instance has loaded: 17 MiB after medium, 55 MiB after large. WebAssembly memory never shrinks.
## Decision
**Go.** Keep ADR-3 as planned: yrs.wasm under wazero, with no cgo and no Node sidecar. The rules below come from the spike.
1. **Compact incrementally; never use `merge` on long logs.** `merge_updates_v1` (and Yjs's `mergeUpdates`) is quadratic in the number of updates. The compaction job loads the latest snapshot plus the pending updates, applies them to a document and re-encodes it (`Compact`). That keeps the steady-state cost to milliseconds even for very long pages. Run it after N updates or T seconds of idle time per document.
2. **One instance per worker, with a pool.** Instances aren't safe for concurrent use. Compile once at startup. Retire an instance when its memory passes a limit (start at 64 MiB) and **after any error that came from a trap**, because the module is built with `panic = "abort"`.
3. **Reuse the startup cost.** Turn on wazero's file compilation cache so restarts skip most of the 350 ms compile.
4. **Text offsets are UTF-16, as in Yjs.** When an edit splits a surrogate pair (an emoji), Yjs keeps the broken half or replaces it with U+FFFD, and yrs keeps the character whole. ProseMirror never splits a surrogate pair, so real editors don't hit this. Our own code must never produce such edits either: no server-side text edits at raw offsets.
5. **Build:** pin `yrs` (0.28.x) and build the module in CI and the Docker images with the `wasm32-wasip1` target, then embed it with `go:embed`. Don't commit the binary. yrs is MIT licensed, which is compatible with AGPL-3.0.
6. **Platforms:** wazero's compiler covers amd64 and arm64, which are the published image architectures. Other architectures fall back to wazero's interpreter, which is much slower; that's acceptable for hobby use but not supported.
## Not covered (follow up in Phase 1)
- Tiptap extensions beyond StarterKit, links and headings (tables, mentions, images). The JSON conversion is generic over element names and attributes, so they should work, but test them against the real editor schema.
- Subdocuments, and the awareness protocol (cursors). The awareness protocol is relayed without decoding, so it doesn't need yrs.
- Long-running memory behaviour under a real workload, and the pool's retirement threshold.
+32
View File
@@ -348,6 +348,33 @@
"integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==",
"license": "MIT"
},
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
"integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/jetbrains-mono": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/jetbrains-mono/-/jetbrains-mono-5.3.0.tgz",
"integrity": "sha512-F32xpS2NsGYoQi2ADSkKTgpJj7ozajsGgDJ8woTnqjmIB+dxDIqImjl4pXZVEExu8UFZ2ndhmX18EBS/hdz3Lw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/source-serif-4": {
"version": "5.3.1",
"resolved": "https://registry.npmjs.org/@fontsource-variable/source-serif-4/-/source-serif-4-5.3.1.tgz",
"integrity": "sha512-4Rtay22SC4lMvw11r/+9kxANB6P3M0X8s1NudBC2v0J1KU2y3DcMoNcT3lBoZ/CqLirzf+StlO6UlJilyrvaUg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@intlify/core-base": {
"version": "11.4.16",
"resolved": "https://registry.npmjs.org/@intlify/core-base/-/core-base-11.4.16.tgz",
@@ -4463,6 +4490,11 @@
"name": "@docwell/ui",
"version": "0.0.1",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@fontsource-variable/inter": "^5.3.0",
"@fontsource-variable/jetbrains-mono": "^5.3.0",
"@fontsource-variable/source-serif-4": "^5.3.1"
},
"peerDependencies": {
"vue": "^3.5.0"
}