Add search filters, space pins, find and replace and page layout

- Search can be narrowed by space, author and last change; the index
  records a mapping version and rebuilds when it changes.
- Editors can pin up to 12 pages to a space's home.
- Find and replace in the editor (Ctrl+F), with match case.
- Pages can be set to full width and a serif or mono font.
- Tailwind now scans the editor package, so its classes are generated.
- Fix golangci-lint findings, including push device names that were
  saved before being trimmed and capped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-02 14:35:18 +01:00
1 parent 1f580ca6f8
commit f20e5f96f9
41 files changed
+1634 -109

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// pages.pinned_at: pages pinned to their space's home, for everyone who can
// open them, in the order they were pinned (see directory/pins.go).
migrate(
(app) => {
const pages = app.findCollectionByNameOrId("pages");
pages.fields.add(new DateField({ name: "pinned_at" }));
app.save(pages);
},
(app) => {
const pages = app.findCollectionByNameOrId("pages");
pages.fields.removeByName("pinned_at");
app.save(pages);
},
);
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// How a page is laid out for everyone who reads it: full width instead of the
// reading column, and the body font ("" is the default sans).
migrate(
(app) => {
const pages = app.findCollectionByNameOrId("pages");
pages.fields.add(new BoolField({ name: "full_width" }));
pages.fields.add(new SelectField({ name: "font", maxSelect: 1, values: ["serif", "mono"] }));
app.save(pages);
},
(app) => {
const pages = app.findCollectionByNameOrId("pages");
pages.fields.removeByName("full_width");
pages.fields.removeByName("font");
app.save(pages);
},
);
+17 -4
View File
@@ -28,6 +28,8 @@ export type PageRef = Schemas["PageRef"];
export type Page = Schemas["Page"];
export type TrashedPage = Schemas["TrashedPage"];
export type ArchivedPage = Schemas["ArchivedPage"];
export type PinnedPage = Schemas["PinnedPage"];
export type PageFont = Schemas["PageFont"];
export type LinkPreview = Schemas["LinkPreview"];
export type PageContent = Schemas["PageContent"];
export type PageVersion = Schemas["PageVersion"];
@@ -341,8 +343,11 @@ export function createClient(opts: ClientOptions) {
groups: (id: string) => request<Group[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/groups`),
people: (id: string, q: string, limit?: number) =>
request<MemberUser[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/people${query({ q, limit })}`),
search: (id: string, q: string, limit?: number) =>
request<SearchResult>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/search${query({ q, limit })}`),
search: (id: string, q: string, limit?: number, filter: SearchFilter = {}) =>
request<SearchResult>(
"GET",
`/api/v1/workspaces/${encodeURIComponent(id)}/search${query({ q, limit, ...filter })}`,
),
favorites: (id: string) => request<PageItem[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/favorites`),
templates: (id: string) => request<Template[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/templates`),
recent: (id: string, limit?: number) =>
@@ -382,6 +387,7 @@ export function createClient(opts: ClientOptions) {
post<Page>(`/api/v1/spaces/${encodeURIComponent(id)}/pages`, input),
trash: (id: string) => request<TrashedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/trash`),
archive: (id: string) => request<ArchivedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/archive`),
pinned: (id: string) => request<PinnedPage[]>("GET", `/api/v1/spaces/${encodeURIComponent(id)}/pinned`),
/** The whole space as a zip of Markdown or HTML files. */
export: (id: string, format: "markdown" | "html") =>
download(`/api/v1/spaces/${encodeURIComponent(id)}/export${query({ format })}`),
@@ -396,8 +402,10 @@ export function createClient(opts: ClientOptions) {
pages: {
get: (id: string) => request<Page>("GET", `/api/v1/pages/${encodeURIComponent(id)}`),
update: (id: string, patch: { title?: string; icon?: string; isTemplate?: boolean }) =>
request<Page>("PATCH", `/api/v1/pages/${encodeURIComponent(id)}`, patch),
update: (
id: string,
patch: { title?: string; icon?: string; isTemplate?: boolean; fullWidth?: boolean; font?: PageFont },
) => request<Page>("PATCH", `/api/v1/pages/${encodeURIComponent(id)}`, patch),
/** Moves a page under parent ("" = top level) at index among its other children. */
content: (id: string) => request<PageContent>("GET", `/api/v1/pages/${encodeURIComponent(id)}/content`),
/** Replaces the page's document; content is Tiptap JSON with type "doc". */
@@ -417,6 +425,8 @@ export function createClient(opts: ClientOptions) {
restore: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/restore`),
archive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/archive`),
unarchive: (id: string) => post<Page>(`/api/v1/pages/${encodeURIComponent(id)}/unarchive`),
pin: (id: string) => request<Page>("PUT", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
unpin: (id: string) => request<Page>("DELETE", `/api/v1/pages/${encodeURIComponent(id)}/pin`),
/** A web page's title, description and picture, read by docwell-server. */
preview: (url: string) => request<LinkPreview>("GET", `/api/v1/link-preview${query({ url })}`),
setFavorite: (id: string, on: boolean) =>
@@ -483,6 +493,9 @@ export function createClient(opts: ClientOptions) {
};
}
/** Optional narrowing for workspaces.search; dates are RFC 3339 times or YYYY-MM-DD days. */
export type SearchFilter = { space?: string; author?: string; updatedAfter?: string; updatedBefore?: string };
function query(params: Record<string, string | number | undefined>): string {
const qs = new URLSearchParams();
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== "") qs.set(k, String(v));
+145 -2
View File
@@ -749,6 +749,28 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}/pinned": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/**
* Pages pinned to the space's home, in the order they were pinned
* @description Pinned pages in the trash or the archive are left out until they are restored.
*/
get: operations["listPinned"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/spaces/{id}/export": {
parameters: {
query?: never;
@@ -788,7 +810,7 @@ export interface paths {
delete: operations["deletePage"];
options?: never;
head?: never;
/** Rename a page, change its icon, or make it a template (editor) */
/** Rename a page, change its icon or layout, or make it a template (editor) */
patch: operations["updatePage"];
trace?: never;
};
@@ -1334,6 +1356,26 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/pin": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
/** Pin the page to its space's home for everyone (editor; at most 12 per space) */
put: operations["pinPage"];
post?: never;
/** Take the page off its space's home (editor) */
delete: operations["unpinPage"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/pages/{id}/visit": {
parameters: {
query?: never;
@@ -1445,7 +1487,7 @@ export interface paths {
};
/**
* Full-text search of page titles and text, in the spaces the caller can open
* @description Trashed pages are not found. The index catches up with edits within a few seconds.
* @description Trashed pages are not found. The index catches up with edits within a few seconds. The filters narrow the results; with an empty q and at least one filter, the matching pages are listed, most recently changed first. A space the caller cannot open finds nothing.
*/
get: operations["searchPages"];
put?: never;
@@ -2353,7 +2395,17 @@ export interface components {
isTemplate: boolean;
/** @description In the caller's favorites */
favorite: boolean;
/** @description When the page was pinned to its space's home; empty if not */
pinnedAt: string;
/** @description Shown across the whole window instead of the reading column */
fullWidth: boolean;
font: components["schemas"]["PageFont"];
};
/**
* @description The body font for everyone reading the page; empty is the default sans
* @enum {string}
*/
PageFont: "" | "serif" | "mono";
/** @enum {string} */
PageGrantRole: "editor" | "commenter" | "viewer";
/**
@@ -2440,6 +2492,13 @@ export interface components {
icon: string;
archivedAt: string;
};
PinnedPage: {
id: string;
title: string;
icon: string;
updated: string;
pinnedAt: string;
};
LinkPreview: {
url: string;
title: string;
@@ -4271,6 +4330,29 @@ export interface operations {
404: components["responses"]["Error"];
};
};
listPinned: {
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"]["PinnedPage"][];
};
};
404: components["responses"]["Error"];
};
};
exportSpace: {
parameters: {
query?: {
@@ -4361,6 +4443,9 @@ export interface operations {
icon?: string;
/** @description Offer the page as a template for new pages */
isTemplate?: boolean;
/** @description Use the whole window instead of the reading column */
fullWidth?: boolean;
font?: components["schemas"]["PageFont"];
};
};
};
@@ -5265,6 +5350,55 @@ export interface operations {
404: components["responses"]["Error"];
};
};
pinPage: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Page"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
unpinPage: {
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"];
};
};
recordPageVisit: {
parameters: {
query?: never;
@@ -5419,6 +5553,14 @@ export interface operations {
query: {
q: string;
limit?: number;
/** @description Only pages in this space */
space?: string;
/** @description Only pages this user created or last edited */
author?: string;
/** @description Only pages changed at or after this time (RFC 3339) or day (YYYY-MM-DD) */
updatedAfter?: string;
/** @description Only pages changed at or before this time (RFC 3339) or the end of this day (YYYY-MM-DD) */
updatedBefore?: string;
};
header?: never;
path: {
@@ -5437,6 +5579,7 @@ export interface operations {
"application/json": components["schemas"]["SearchResult"];
};
};
400: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
+6 -1
View File
@@ -11,6 +11,9 @@
"./provider": "./src/provider.ts",
"./editor.css": "./src/editor.css"
},
"scripts": {
"test": "vitest run"
},
"dependencies": {
"@docwell/ui": "*",
"@excalidraw/excalidraw": "^0.18.1",
@@ -42,6 +45,8 @@
},
"devDependencies": {
"@types/react": "^18.3.31",
"@types/react-dom": "^18.3.7"
"@types/react-dom": "^18.3.7",
"jsdom": "^30.1.3",
"vitest": "^5.0.5"
}
}
+156 -3
View File
@@ -4,8 +4,9 @@ import type { Editor, JSONContent } from "@tiptap/core";
import { EditorContent, useEditor } from "@tiptap/vue-3";
import { BubbleMenu } from "@tiptap/vue-3/menus";
import { DwIcon, type IconName } from "@docwell/ui";
import { computed, onBeforeUnmount, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { docwellExtensions, type CollabUser } from "./extensions";
import { findKey } from "./find";
import type { LinkHost } from "./embeds";
import type { FileHost } from "./files";
import { englishLabels, type EditorLabels } from "./labels";
@@ -76,6 +77,10 @@ const editor = useEditor({
}),
editorProps: { attributes: { class: "dw-prose" } },
onUpdate: ({ editor }) => emit("update", editor.getJSON()),
onTransaction: ({ editor }) => {
const f = findKey.getState(editor.state);
found.value = { current: f?.current ?? -1, total: f?.matches.length ?? 0 };
},
onBlur: () => emit("blur"),
});
@@ -146,11 +151,159 @@ function shouldShow({ editor: e, from, to }: { editor: Editor; from: number; to:
return e.isEditable || props.canComment;
}
defineExpose({ editor });
// Find and replace (Ctrl+F / Cmd+F while editing, or openFind from the host).
const finding = ref(false);
const findText = ref("");
const replaceText = ref("");
const matchCase = ref(false);
const findInput = ref<HTMLInputElement | null>(null);
const found = ref({ current: -1, total: 0 });
const findCount = computed(() =>
found.value.total
? labels.value.find.count
.replace("{current}", String(found.value.current + 1))
.replace("{total}", String(found.value.total))
: findText.value
? labels.value.find.none
: "",
);
async function openFind() {
const e = editor.value;
if (!e) return;
const { from, to } = e.state.selection;
const picked = e.state.doc.textBetween(from, to, "\n");
if (picked && !picked.includes("\n") && picked.length <= 200) findText.value = picked;
finding.value = true;
await nextTick();
findInput.value?.focus();
findInput.value?.select();
e.commands.setFind(findText.value, matchCase.value);
}
function closeFind() {
finding.value = false;
editor.value?.chain().clearFind().focus().run();
}
watch([findText, matchCase], ([text, mc]) => {
if (finding.value) editor.value?.commands.setFind(text, mc);
});
function onFindKey(e: KeyboardEvent) {
if (e.key === "Enter") {
e.preventDefault();
editor.value?.commands.findStep(e.shiftKey ? -1 : 1);
} else if (e.key === "Escape") {
e.preventDefault();
closeFind();
}
}
function onKeydown(e: KeyboardEvent) {
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "f") {
e.preventDefault();
void openFind();
}
}
defineExpose({ editor, openFind });
</script>
<template>
<div>
<div @keydown="onKeydown">
<!-- A zero-height sticky row, so the floating bar does not push the text down. -->
<div v-if="finding && editor" class="sticky top-2 z-20 h-0">
<div
class="dw-find-bar absolute right-0 flex max-w-full flex-col gap-1.5 rounded-md border border-line bg-surface-raised p-2 text-ui-sm shadow-menu"
role="search"
data-testid="find-bar"
>
<div class="flex items-center gap-1">
<input
ref="findInput"
v-model="findText"
type="search"
maxlength="200"
class="dw-input h-control-sm w-48 min-w-0"
:placeholder="labels.find.find"
:aria-label="labels.find.find"
data-testid="find-input"
@keydown="onFindKey"
/>
<span class="min-w-16 px-1 text-center text-ink-muted tabular-nums" aria-live="polite">{{ findCount }}</span>
<button
type="button"
class="grid size-7 place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
:aria-label="labels.find.previous"
:title="labels.find.previous"
:disabled="!found.total"
@click="editor.commands.findStep(-1)"
>
<DwIcon name="chevron-up" :size="16" />
</button>
<button
type="button"
class="grid size-7 place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
:aria-label="labels.find.next"
:title="labels.find.next"
:disabled="!found.total"
@click="editor.commands.findStep(1)"
>
<DwIcon name="chevron-down" :size="16" />
</button>
<button
type="button"
class="grid size-7 place-items-center rounded-sm font-mono text-[12px] text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'bg-surface-hover text-ink': matchCase }"
:aria-label="labels.find.matchCase"
:title="labels.find.matchCase"
:aria-pressed="matchCase"
@click="matchCase = !matchCase"
>
Aa
</button>
<button
type="button"
class="grid size-7 place-items-center rounded-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
:aria-label="labels.find.close"
:title="labels.find.close"
@click="closeFind"
>
<DwIcon name="close" :size="16" />
</button>
</div>
<div v-if="editor.isEditable" class="flex items-center gap-1">
<input
v-model="replaceText"
type="text"
class="dw-input h-control-sm w-48 min-w-0"
:placeholder="labels.find.replace"
:aria-label="labels.find.replace"
data-testid="replace-input"
@keydown.enter.prevent="editor.commands.replaceCurrent(replaceText)"
@keydown.esc.prevent="closeFind"
/>
<button
type="button"
class="h-7 rounded-sm px-2 font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink disabled:opacity-50"
:disabled="!found.total"
@click="editor.commands.replaceCurrent(replaceText)"
>
{{ labels.find.replaceOne }}
</button>
<button
type="button"
class="h-7 rounded-sm px-2 font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink disabled:opacity-50"
:disabled="!found.total"
data-testid="replace-all"
@click="editor.commands.replaceAll(replaceText)"
>
{{ labels.find.replaceAll }}
</button>
</div>
</div>
</div>
<BubbleMenu
v-if="editor"
:editor="editor"
+23
View File
@@ -2,6 +2,9 @@
@import "katex/dist/katex.min.css";
/* Tailwind classes used by the editor's own components (menus, find bar). */
@source "./";
/* Document styles for the Docwell editor, from the design system's Document
type scale. Uses tokens from @docwell/ui/theme.css. */
@@ -632,3 +635,23 @@
.dw-source__btn--danger {
color: var(--color-danger);
}
/* Find in page: every match, and the one the bar is on. */
.dw-prose .dw-find {
background: color-mix(in srgb, var(--color-accent) 22%, transparent);
border-radius: 2px;
}
.dw-prose .dw-find-current {
background: color-mix(in srgb, var(--color-accent) 50%, transparent);
outline: 1px solid var(--color-accent);
}
/* The page's body font, chosen per page; headings follow it too. */
.dw-font-serif .dw-prose,
.dw-font-serif .dw-prose :is(h1, h2, h3) {
font-family: var(--font-serif);
}
.dw-font-mono .dw-prose,
.dw-font-mono .dw-prose :is(h1, h2, h3) {
font-family: var(--font-mono);
}
+2
View File
@@ -10,6 +10,7 @@ import { CommentHighlights } from "./comments";
import { DrawioBlock, ExcalidrawBlock, type ExcalidrawLoader } from "./diagrams";
import { Embed, LinkCard, type LinkHost } from "./embeds";
import { DocwellImage, FileAttachment, FileDrop, type FileHost } from "./files";
import { FindReplace } from "./find";
import { englishLabels, type EditorLabels } from "./labels";
import { docwellMath } from "./math";
import { docwellMention, type MentionHost } from "./mention";
@@ -107,6 +108,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
Embed.configure({ labels }),
LinkCard.configure({ labels }),
BlockLinks.configure({ labels, link: opts.blockLink, onCopied: opts.onBlockLinkCopied }),
FindReplace,
];
if (opts.collab) {
list.push(
+65
View File
@@ -0,0 +1,65 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Editor } from "@tiptap/core";
import StarterKit from "@tiptap/starter-kit";
import { afterEach, describe, expect, it } from "vitest";
import { FindReplace, findKey, findMatches } from "./find";
let editor: Editor | undefined;
afterEach(() => editor?.destroy());
function setup(html: string) {
editor = new Editor({ extensions: [StarterKit, FindReplace], content: html });
return editor;
}
const texts = (e: Editor) => findMatches(e.state.doc, "cat").map((m) => e.state.doc.textBetween(m.from, m.to));
describe("findMatches", () => {
it("ignores case unless asked, and crosses marks inside a block", () => {
const e = setup("<p>Cat and c<strong>at</strong>.</p><p>concatenate</p>");
expect(texts(e)).toEqual(["Cat", "cat", "cat"]);
expect(findMatches(e.state.doc, "Cat", true)).toHaveLength(1);
});
it("does not run from one block into the next", () => {
const e = setup("<p>ca</p><p>t</p>");
expect(findMatches(e.state.doc, "cat")).toEqual([]);
});
});
describe("FindReplace", () => {
it("steps through matches and wraps around", () => {
const e = setup("<p>one cat, two cat, three cat</p>");
e.commands.setFind("cat");
const state = () => findKey.getState(e.state)!;
expect(state().matches).toHaveLength(3);
expect(state().current).toBe(0);
e.commands.findStep(-1);
expect(state().current).toBe(2);
e.commands.findStep(1);
expect(state().current).toBe(0);
});
it("replaces one match, then all, as ordinary edits", () => {
const e = setup("<p>cat cat cat</p>");
e.commands.setFind("cat");
e.commands.replaceCurrent("dog");
expect(e.getText()).toBe("dog cat cat");
expect(findKey.getState(e.state)!.matches).toHaveLength(2);
e.commands.replaceAll("cow");
expect(e.getText()).toBe("dog cow cow");
expect(findKey.getState(e.state)!.matches).toHaveLength(0);
e.commands.undo();
expect(e.getText()).toBe("dog cat cat");
});
it("searches again after other edits and clears", () => {
const e = setup("<p>cat</p>");
e.commands.setFind("cat");
e.commands.insertContentAt(e.state.doc.content.size, "<p>another cat</p>");
expect(findKey.getState(e.state)!.matches).toHaveLength(2);
e.commands.clearFind();
expect(findKey.getState(e.state)!.term).toBe("");
});
});
+189
View File
@@ -0,0 +1,189 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension } from "@tiptap/core";
import type { Node as PMNode } from "@tiptap/pm/model";
import { Plugin, PluginKey, TextSelection, type Transaction } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
export type FindMatch = { from: number; to: number };
export type FindState = {
term: string;
caseSensitive: boolean;
matches: FindMatch[];
/** Index of the current match, -1 when there is none. */
current: number;
};
export const findKey = new PluginKey<FindState>("dwFind");
// Inline nodes that are not text (mentions, math, page links) count as one
// character no search can match, so a match never runs across them.
const OBJECT = "";
/**
* Every occurrence of term in the document's text, in document order. A match
* stays inside one text block but may cross marks (bold in the middle of a
* word still matches).
*/
export function findMatches(doc: PMNode, term: string, caseSensitive = false): FindMatch[] {
if (!term) return [];
const needle = caseSensitive ? term : term.toLowerCase();
const out: FindMatch[] = [];
doc.descendants((block, blockPos) => {
if (!block.isTextblock) return true;
let text = "";
// Document position of each character of text.
const at: number[] = [];
block.forEach((child, offset) => {
const start = blockPos + 1 + offset;
if (child.isText) {
const s = child.text ?? "";
for (let i = 0; i < s.length; i++) at.push(start + i);
text += s;
} else {
at.push(start);
text += OBJECT;
}
});
const hay = caseSensitive ? text : text.toLowerCase();
for (let i = hay.indexOf(needle); i !== -1; i = hay.indexOf(needle, i + needle.length)) {
out.push({ from: at[i]!, to: at[i + needle.length - 1]! + 1 });
}
return false;
});
return out;
}
function compute(doc: PMNode, term: string, caseSensitive: boolean, near: number): FindState {
const matches = findMatches(doc, term, caseSensitive);
let current = matches.findIndex((m) => m.from >= near);
if (current === -1) current = matches.length ? 0 : -1;
return { term, caseSensitive, matches, current };
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
find: {
/** Starts or changes a search; the current match is the first one after the selection. */
setFind: (term: string, caseSensitive?: boolean) => ReturnType;
/** Moves to the next (1) or previous (-1) match and scrolls it into view. */
findStep: (dir: 1 | -1) => ReturnType;
/** Replaces the current match and moves on to the next one. */
replaceCurrent: (text: string) => ReturnType;
replaceAll: (text: string) => ReturnType;
clearFind: () => ReturnType;
};
}
}
type Meta = { term: string; caseSensitive: boolean; near: number } | { current: number } | { clear: true };
function select(tr: Transaction, m: FindMatch | undefined) {
if (m) tr.setSelection(TextSelection.create(tr.doc, m.from, m.to)).scrollIntoView();
return tr;
}
/**
* Find and replace in the page. Matches are highlighted with decorations, so
* searching changes nothing in the shared document; replacing is an ordinary
* edit that collaborators see and undo can take back.
*/
export const FindReplace = Extension.create({
name: "findReplace",
addCommands() {
return {
setFind:
(term, caseSensitive = false) =>
({ state, tr, dispatch }) => {
const next = compute(state.doc, term, caseSensitive, state.selection.from);
tr.setMeta(findKey, { term, caseSensitive, near: state.selection.from } satisfies Meta);
if (dispatch) dispatch(select(tr, next.matches[next.current]));
return true;
},
findStep:
(dir) =>
({ state, tr, dispatch }) => {
const f = findKey.getState(state);
if (!f?.matches.length) return false;
const current = (f.current + dir + f.matches.length) % f.matches.length;
tr.setMeta(findKey, { current } satisfies Meta);
if (dispatch) dispatch(select(tr, f.matches[current]));
return true;
},
replaceCurrent:
(text) =>
({ state, tr, dispatch }) => {
const f = findKey.getState(state);
const m = f?.matches[f.current];
if (!f || !m) return false;
if (dispatch) {
tr.insertText(text, m.from, m.to);
// Carry on from just after the replacement.
tr.setMeta(findKey, {
term: f.term,
caseSensitive: f.caseSensitive,
near: m.from + text.length,
} satisfies Meta);
const after = compute(tr.doc, f.term, f.caseSensitive, m.from + text.length);
dispatch(select(tr, after.matches[after.current]));
}
return true;
},
replaceAll:
(text) =>
({ state, tr, dispatch }) => {
const f = findKey.getState(state);
if (!f?.matches.length) return false;
if (dispatch) {
// Back to front, so earlier positions stay valid.
for (const m of [...f.matches].reverse()) tr.insertText(text, m.from, m.to);
tr.setMeta(findKey, { term: f.term, caseSensitive: f.caseSensitive, near: 0 } satisfies Meta);
dispatch(tr);
}
return true;
},
clearFind:
() =>
({ tr, dispatch }) => {
if (dispatch) dispatch(tr.setMeta(findKey, { clear: true } satisfies Meta));
return true;
},
};
},
addProseMirrorPlugins() {
const empty: FindState = { term: "", caseSensitive: false, matches: [], current: -1 };
return [
new Plugin<FindState>({
key: findKey,
state: {
init: () => empty,
apply(tr, prev, _old, state) {
const meta = tr.getMeta(findKey) as Meta | undefined;
if (meta && "clear" in meta) return empty;
if (meta && "term" in meta) return compute(state.doc, meta.term, meta.caseSensitive, meta.near);
if (meta && "current" in meta) return { ...prev, current: meta.current };
if (!prev.term || !tr.docChanged) return prev;
// Someone edited (maybe a collaborator): search again, staying near the current match.
const near = prev.matches[prev.current]?.from ?? 0;
return compute(state.doc, prev.term, prev.caseSensitive, tr.mapping.map(near));
},
},
props: {
decorations(state) {
const f = findKey.getState(state);
if (!f?.matches.length) return null;
return DecorationSet.create(
state.doc,
f.matches.map((m, i) =>
Decoration.inline(m.from, m.to, { class: i === f.current ? "dw-find dw-find-current" : "dw-find" }),
),
);
},
},
}),
];
},
});
+1
View File
@@ -11,5 +11,6 @@ export { insertFiles, type FileHost, type UploadedFile } from "./files";
export { CollabProvider, type CollabProviderOptions, type CollabStatus } from "./provider";
export { linkedPage, pagePath, type PageHost, type PageRef as LinkablePage } from "./pagelinks";
export { headingsOf, type Heading } from "./toc";
export { findMatches, type FindMatch } from "./find";
export { blockHash, linkedBlock, scrollToBlock } from "./blocklinks";
export { embedSource, type LinkHost, type LinkPreview } from "./embeds";
+25
View File
@@ -46,6 +46,19 @@ export interface EditorLabels {
linkUrl: string;
copyBlockLink: string;
};
/** The find and replace bar. count has {current} and {total} in it. */
find: {
find: string;
replace: string;
previous: string;
next: string;
replaceOne: string;
replaceAll: string;
matchCase: string;
close: string;
count: string;
none: string;
};
}
export const englishLabels: EditorLabels = {
@@ -110,4 +123,16 @@ export const englishLabels: EditorLabels = {
linkUrl: "Address of the page to link",
copyBlockLink: "Copy link to this block",
},
find: {
find: "Find in page",
replace: "Replace with",
previous: "Previous match",
next: "Next match",
replaceOne: "Replace",
replaceAll: "Replace all",
matchCase: "Match case",
close: "Close",
count: "{current} of {total}",
none: "No matches",
},
};
+7
View File
@@ -0,0 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { defineConfig } from "vitest/config";
export default defineConfig({
test: { environment: "jsdom" },
});
+4
View File
@@ -9,6 +9,7 @@ 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"],
"chevron-up": ["M6 14l6-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"],
@@ -86,6 +87,9 @@ export const iconPaths = {
// Phase 2: embeds, archive, servers.
video: ["M4 6h11v12H4z", "M15 10l5-3v10l-5-3"],
archive: ["M4 5h16v4H4z", "M5 9v10h14V9", "M10 13h4"],
pin: ["M9 4h6", "M10 4v6l-3 4h10l-3-4V4", "M12 14v6"],
width: ["M3 12h18", "M7 8l-4 4 4 4", "M17 8l4 4-4 4"],
type: ["M5 7V5h14v2", "M12 5v14", "M9 19h6"],
server: ["M4 4h16v6H4z", "M4 14h16v6H4z", "M8 7h.01", "M8 17h.01"],
users: [
"M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z",
+70
View File
@@ -669,6 +669,9 @@ class Page {
required this.restricted,
required this.isTemplate,
required this.favorite,
required this.pinnedAt,
required this.fullWidth,
required this.font,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
@@ -691,6 +694,9 @@ class Page {
restricted: json['restricted'] as bool,
isTemplate: json['isTemplate'] as bool,
favorite: json['favorite'] as bool,
pinnedAt: json['pinnedAt'] as String,
fullWidth: json['fullWidth'] as bool,
font: PageFont.fromJson(json['font'] as String),
);
final String id;
@@ -736,6 +742,14 @@ class Page {
/// In the caller's favorites
final bool favorite;
/// When the page was pinned to its space's home; empty if not
final String pinnedAt;
/// Shown across the whole window instead of the reading column
final bool fullWidth;
final PageFont font;
Map<String, dynamic> toJson() => {
'id': id,
'workspace': workspace,
@@ -754,9 +768,29 @@ class Page {
'restricted': restricted,
'isTemplate': isTemplate,
'favorite': favorite,
'pinnedAt': pinnedAt,
'fullWidth': fullWidth,
'font': font.toJson(),
};
}
/// The body font for everyone reading the page; empty is the default sans
enum PageFont {
none(''),
serif('serif'),
mono('mono');
const PageFont(this.value);
final String value;
static PageFont fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown PageFont', value),
);
String toJson() => value;
}
enum PageGrantRole {
editor('editor'),
commenter('commenter'),
@@ -1131,6 +1165,42 @@ class ArchivedPage {
};
}
class PinnedPage {
const PinnedPage({
required this.id,
required this.title,
required this.icon,
required this.updated,
required this.pinnedAt,
});
factory PinnedPage.fromJson(Map<String, dynamic> json) => PinnedPage(
id: json['id'] as String,
title: json['title'] as String,
icon: json['icon'] as String,
updated: json['updated'] as String,
pinnedAt: json['pinnedAt'] as String,
);
final String id;
final String title;
final String icon;
final String updated;
final String pinnedAt;
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'icon': icon,
'updated': updated,
'pinnedAt': pinnedAt,
};
}
class LinkPreview {
const LinkPreview({
required this.url,
+3
View File
@@ -270,6 +270,9 @@ void main() {
'restricted': false,
'isTemplate': false,
'favorite': false,
'pinnedAt': '',
'fullWidth': false,
'font': '',
});
await tester.pumpWidget(
MaterialApp(
+63 -4
View File
@@ -153,6 +153,27 @@ func (e OAuthProviderSettingsName) Valid() bool {
}
}
// Defines values for PageFont.
const (
PageFontEmpty PageFont = ""
PageFontMono PageFont = "mono"
PageFontSerif PageFont = "serif"
)
// Valid indicates whether the value is a known member of the PageFont enum.
func (e PageFont) Valid() bool {
switch e {
case PageFontEmpty:
return true
case PageFontMono:
return true
case PageFontSerif:
return true
default:
return false
}
}
// Defines values for PageGrantType.
const (
PageGrantTypeGroup PageGrantType = "group"
@@ -996,9 +1017,15 @@ type Page struct {
DeletedAt string `json:"deletedAt"`
// Favorite In the caller's favorites
Favorite bool `json:"favorite"`
Icon string `json:"icon"`
Id string `json:"id"`
Favorite bool `json:"favorite"`
// Font The body font for everyone reading the page; empty is the default sans
Font PageFont `json:"font"`
// FullWidth Shown across the whole window instead of the reading column
FullWidth bool `json:"fullWidth"`
Icon string `json:"icon"`
Id string `json:"id"`
// InTrash The page or one of its ancestors is in the trash
InTrash bool `json:"inTrash"`
@@ -1007,6 +1034,9 @@ type Page struct {
IsTemplate bool `json:"isTemplate"`
Parent string `json:"parent"`
// PinnedAt When the page was pinned to its space's home; empty if not
PinnedAt string `json:"pinnedAt"`
// Restricted The page or one of its ancestors is restricted
Restricted bool `json:"restricted"`
@@ -1047,6 +1077,9 @@ type PageContent struct {
Updated string `json:"updated"`
}
// PageFont The body font for everyone reading the page; empty is the default sans
type PageFont string
// PageGrant defines model for PageGrant.
type PageGrant struct {
// Email Empty for groups
@@ -1121,6 +1154,15 @@ type PageVersion struct {
Label string `json:"label"`
}
// PinnedPage defines model for PinnedPage.
type PinnedPage struct {
Icon string `json:"icon"`
Id string `json:"id"`
PinnedAt string `json:"pinnedAt"`
Title string `json:"title"`
Updated string `json:"updated"`
}
// PublicSettings defines model for PublicSettings.
type PublicSettings struct {
// AccentColor #rrggbb, or empty for the default
@@ -1648,7 +1690,12 @@ type DeletePageParams struct {
// UpdatePageJSONBody defines parameters for UpdatePage.
type UpdatePageJSONBody struct {
Icon *string `json:"icon,omitempty"`
// Font The body font for everyone reading the page; empty is the default sans
Font *PageFont `json:"font,omitempty"`
// FullWidth Use the whole window instead of the reading column
FullWidth *bool `json:"fullWidth,omitempty"`
Icon *string `json:"icon,omitempty"`
// IsTemplate Offer the page as a template for new pages
IsTemplate *bool `json:"isTemplate,omitempty"`
@@ -1815,6 +1862,18 @@ type ListRecentPagesParams struct {
type SearchPagesParams struct {
Q string `form:"q" json:"q"`
Limit *int `form:"limit,omitempty" json:"limit,omitempty"`
// Space Only pages in this space
Space *string `form:"space,omitempty" json:"space,omitempty"`
// Author Only pages this user created or last edited
Author *string `form:"author,omitempty" json:"author,omitempty"`
// UpdatedAfter Only pages changed at or after this time (RFC 3339) or day (YYYY-MM-DD)
UpdatedAfter *string `form:"updatedAfter,omitempty" json:"updatedAfter,omitempty"`
// UpdatedBefore Only pages changed at or before this time (RFC 3339) or the end of this day (YYYY-MM-DD)
UpdatedBefore *string `form:"updatedBefore,omitempty" json:"updatedBefore,omitempty"`
}
// CreateSpaceJSONBody defines parameters for CreateSpace.
+2 -2
View File
@@ -87,7 +87,7 @@ var ErrTooLarge = errors.New("the archive is too large")
// readZipFile reads one archive entry, failing past limit bytes, so a small
// archive cannot unpack into an unbounded amount of memory.
func readZipFile(f *zip.File, limit int64) ([]byte, error) {
if f.UncompressedSize64 > uint64(limit) {
if limit < 0 || f.UncompressedSize64 > uint64(limit) {
return nil, ErrTooLarge
}
rc, err := f.Open()
@@ -122,7 +122,7 @@ func parseXML(data []byte) (*xnode, error) {
stack := []*xnode{root}
for {
tok, err := d.Token()
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}
if err != nil {
+3
View File
@@ -177,6 +177,9 @@ func (n *notionReader) open(data []byte, nested bool) error {
if n.entries > maxNotionEntries {
return ErrTooLarge
}
if f.UncompressedSize64 > maxNotionTotal {
return ErrTooLarge
}
n.total += int64(f.UncompressedSize64)
if n.total > maxNotionTotal {
return ErrTooLarge
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"image"
"image/color"
"image/png"
@@ -192,7 +193,7 @@ func TestReadNotion(t *testing.T) {
t.Errorf("assets = %+v", assets)
}
if _, _, err := ReadNotion(zipOf(t, map[string][]byte{"a.png": nil})); err != ErrNotNotion {
if _, _, err := ReadNotion(zipOf(t, map[string][]byte{"a.png": nil})); !errors.Is(err, ErrNotNotion) {
t.Errorf("err = %v", err)
}
}
+25 -3
View File
@@ -24,7 +24,7 @@ import (
// but stay readable (and read-only) until someone unarchives them.
// pageFields skips the large content columns.
const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,created,updated"
const pageFields = "id,workspace,space,parent,title,icon,position,restricted,is_template,creator,last_editor,deleted_at,archived_at,pinned_at,full_width,font,created,updated"
type pageRecord struct {
ID string `json:"id"`
@@ -40,6 +40,9 @@ type pageRecord struct {
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
ArchivedAt string `json:"archived_at"`
PinnedAt string `json:"pinned_at"`
FullWidth bool `json:"full_width"`
Font string `json:"font"`
Created string `json:"created"`
Updated string `json:"updated"`
}
@@ -91,6 +94,11 @@ type Page struct {
IsTemplate bool `json:"isTemplate"`
// Favorite is whether the caller has the page in their favorites.
Favorite bool `json:"favorite"`
// PinnedAt is when the page was pinned to its space's home; empty if not.
PinnedAt string `json:"pinnedAt"`
// FullWidth and Font are how the page is shown to everyone.
FullWidth bool `json:"fullWidth"`
Font string `json:"font"`
}
type TrashedPage struct {
@@ -258,7 +266,8 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page
Created: p.Created, Updated: p.Updated, DeletedAt: p.DeletedAt, InTrash: p.DeletedAt != "",
ArchivedAt: p.ArchivedAt, Archived: p.ArchivedAt != "",
Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, IsTemplate: p.IsTemplate,
Favorite: s.isFavorite(ctx, c.ID, p.ID),
Favorite: s.isFavorite(ctx, c.ID, p.ID), PinnedAt: p.PinnedAt,
FullWidth: p.FullWidth, Font: p.Font,
}
parent := p.Parent
for depth := 0; parent != "" && depth < 100; depth++ {
@@ -403,9 +412,11 @@ type UpdatePageInput struct {
Title *string `json:"title"`
Icon *string `json:"icon"`
IsTemplate *bool `json:"isTemplate"`
FullWidth *bool `json:"fullWidth"`
Font *string `json:"font"`
}
// UpdatePage renames a page or changes its icon (editor).
// UpdatePage renames a page, changes its icon or how it is shown (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 {
@@ -438,6 +449,17 @@ func (s *Service) UpdatePage(ctx context.Context, c access.Caller, id string, in
if in.IsTemplate != nil {
patch["is_template"] = *in.IsTemplate
}
if in.FullWidth != nil {
patch["full_width"] = *in.FullWidth
}
if in.Font != nil {
switch *in.Font {
case "", "serif", "mono":
patch["font"] = *in.Font
default:
return Page{}, apperr.InvalidFields(map[string]string{"font": "Font must be empty, serif or mono."})
}
}
updated, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch)
if err != nil {
return Page{}, mapPB(err, "page not found")
-14
View File
@@ -137,20 +137,6 @@ func (r pageRules) role(id string) string {
return access.PageRole(r.spaceRole, chain)
}
// restrictedAt is the page itself or its nearest restricted ancestor ("" when none).
func (r pageRules) restrictedAt(id string) string {
if len(r.restricted) == 0 {
return ""
}
for depth := 0; id != "" && depth < 1000; depth++ {
if r.restricted[id] {
return id
}
id = r.parent[id]
}
return ""
}
// pageAccess loads a page with c's rights on it: a.role is the page role.
// A page c cannot open is reported as not found.
func (s *Service) pageAccess(ctx context.Context, c access.Caller, id string) (pageRecord, spaceAccess, pageRules, error) {
+108
View File
@@ -0,0 +1,108 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"sort"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// maxPins keeps the space home short; pinning is for the few pages everyone
// should find first.
const maxPins = 12
type PinnedPage struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
Updated string `json:"updated"`
PinnedAt string `json:"pinnedAt"`
}
// PinPage pins a page to its space's home (editor).
func (s *Service) PinPage(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.PinnedAt != "" {
return s.GetPage(ctx, c, p.ID)
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return Page{}, err
}
if !t.live(p.ID) || t.archived(p.ID) {
return Page{}, apperr.Invalid("trashed and archived pages cannot be pinned")
}
if len(pinned(t)) >= maxPins {
return Page{}, apperr.Invalid("a space can have at most 12 pinned pages; unpin one first")
}
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{"pinned_at": pbTime(time.Now())}); err != nil {
return Page{}, mapPB(err, "page not found")
}
return s.GetPage(ctx, c, p.ID)
}
// UnpinPage takes a page off its space's home (editor).
func (s *Service) UnpinPage(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.PinnedAt != "" {
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{"pinned_at": ""}); err != nil {
return Page{}, mapPB(err, "page not found")
}
}
return s.GetPage(ctx, c, p.ID)
}
// ListPinned lists the pinned pages of a space that c can open, in the order
// they were pinned. Pages in the trash or the archive (themselves or through
// an ancestor) keep their pin but are not listed, so restoring brings it back.
func (s *Service) ListPinned(ctx context.Context, c access.Caller, spaceID string) ([]PinnedPage, error) {
a, rules, err := s.spaceRules(ctx, c, spaceID)
if err != nil {
return nil, err
}
t, err := s.loadTree(ctx, a.space.ID)
if err != nil {
return nil, err
}
out := []PinnedPage{}
for _, p := range pinned(t) {
if rules.role(p.ID) != "" {
out = append(out, PinnedPage{ID: p.ID, Title: p.Title, Icon: p.Icon, Updated: p.Updated, PinnedAt: p.PinnedAt})
}
}
return out, nil
}
// pinned is the space's listed pins, oldest first.
func pinned(t tree) []pageRecord {
var out []pageRecord
for _, p := range t.byID {
if p.PinnedAt != "" && t.live(p.ID) && !t.archived(p.ID) {
out = append(out, p)
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].PinnedAt != out[j].PinnedAt {
return out[i].PinnedAt < out[j].PinnedAt
}
return out[i].ID < out[j].ID
})
return out
}
+24
View File
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import "testing"
func TestPinnedSkipsTrashAndArchiveInPinOrder(t *testing.T) {
recs := []pageRecord{
{ID: "b", PinnedAt: "2026-11-02 10:00:00.000Z"},
{ID: "a", PinnedAt: "2026-11-01 10:00:00.000Z"},
{ID: "plain"},
{ID: "trashed", PinnedAt: "2026-11-01 09:00:00.000Z", DeletedAt: "2026-11-02 08:00:00.000Z"},
{ID: "box", ArchivedAt: "2026-10-01 00:00:00.000Z"},
{ID: "inBox", Parent: "box", PinnedAt: "2026-11-01 08:00:00.000Z"},
}
tr := tree{byID: map[string]pageRecord{}}
for _, p := range recs {
tr.byID[p.ID] = p
}
got := pinned(tr)
if len(got) != 2 || got[0].ID != "a" || got[1].ID != "b" {
t.Errorf("pinned = %+v", got)
}
}
+49 -3
View File
@@ -4,14 +4,17 @@ package directory
import (
"context"
"slices"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/search"
)
// Searcher is the part of search.Index this package uses.
type Searcher interface {
Query(ctx context.Context, workspace string, spaces []string, text string, limit int) ([]search.Hit, int, error)
Query(ctx context.Context, workspace string, spaces []string, text string, f search.Filter, limit int) ([]search.Hit, int, error)
}
// UseSearch enables Search.
@@ -27,12 +30,54 @@ type SearchResult struct {
Total int `json:"total"`
}
// SearchQuery is a search request. Space, Author, UpdatedAfter and
// UpdatedBefore are optional; the dates are RFC 3339 times or plain dates
// (UpdatedBefore then covers the whole day).
type SearchQuery struct {
Text string
Space string
Author string
UpdatedAfter string
UpdatedBefore string
Limit int
}
func parseSearchTime(v string, endOfDay bool) (time.Time, error) {
if v == "" {
return time.Time{}, nil
}
if t, err := time.Parse(time.RFC3339, v); err == nil {
return t, nil
}
t, err := time.Parse(time.DateOnly, v)
if err != nil {
return time.Time{}, apperr.Invalid("Dates must look like 2026-11-02 or 2026-11-02T15:04:05Z.")
}
if endOfDay {
t = t.Add(24*time.Hour - time.Millisecond)
}
return t, nil
}
// Search finds pages in a workspace, only the ones c can open.
func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (SearchResult, error) {
func (s *Service) Search(ctx context.Context, c access.Caller, wsID string, sq SearchQuery) (SearchResult, error) {
f := search.Filter{Author: sq.Author}
var err error
if f.After, err = parseSearchTime(sq.UpdatedAfter, false); err != nil {
return SearchResult{}, err
}
if f.Before, err = parseSearchTime(sq.UpdatedBefore, true); err != nil {
return SearchResult{}, err
}
spaces, err := s.ListSpaces(ctx, c, wsID)
if err != nil {
return SearchResult{}, err
}
if sq.Space != "" {
// A space the caller cannot see finds nothing rather than an error,
// so its existence does not leak.
spaces = slices.DeleteFunc(spaces, func(sp Space) bool { return sp.ID != sq.Space })
}
out := SearchResult{Items: []SearchHit{}}
if s.search == nil || len(spaces) == 0 {
return out, nil
@@ -50,6 +95,7 @@ func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string
rules[sp.ID] = r
filtered = filtered || (!r.plain() && r.spaceRole != access.SpaceAdmin)
}
limit := sq.Limit
if limit <= 0 {
limit = 20
}
@@ -59,7 +105,7 @@ func (s *Service) Search(ctx context.Context, c access.Caller, wsID, text string
if filtered {
want = limit*3 + 20
}
hits, total, err := s.search.Query(ctx, wsID, ids, text, want)
hits, total, err := s.search.Query(ctx, wsID, ids, sq.Text, f, want)
if err != nil {
return SearchResult{}, err
}
+34
View File
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"testing"
"time"
)
func TestParseSearchTime(t *testing.T) {
for _, tc := range []struct {
in string
endOfDay bool
want string
bad bool
}{
{in: "", want: "0001-01-01T00:00:00Z"},
{in: "2026-11-02", want: "2026-11-02T00:00:00Z"},
{in: "2026-11-02", endOfDay: true, want: "2026-11-02T23:59:59.999Z"},
{in: "2026-11-02T08:30:00+01:00", endOfDay: true, want: "2026-11-02T07:30:00Z"},
{in: "last week", bad: true},
} {
got, err := parseSearchTime(tc.in, tc.endOfDay)
if tc.bad {
if err == nil {
t.Errorf("%q: want an error", tc.in)
}
continue
}
if err != nil || got.UTC().Format(time.RFC3339Nano) != tc.want {
t.Errorf("%q = %v, %v; want %s", tc.in, got, err, tc.want)
}
}
}
+6 -2
View File
@@ -13,14 +13,18 @@ import (
// SearchService is the part of directory.Service that searches pages.
type SearchService interface {
Search(ctx context.Context, c access.Caller, wsID, text string, limit int) (directory.SearchResult, error)
Search(ctx context.Context, c access.Caller, wsID string, q directory.SearchQuery) (directory.SearchResult, error)
}
func (a *api) searchRoutes(mux *routeMux) {
mux.HandleFunc("GET /api/v1/workspaces/{id}/search", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
res, err := a.dir.Search(r.Context(), caller(r), r.PathValue("id"), q.Get("q"), min(max(limit, 0), 50))
res, err := a.dir.Search(r.Context(), caller(r), r.PathValue("id"), directory.SearchQuery{
Text: q.Get("q"), Space: q.Get("space"), Author: q.Get("author"),
UpdatedAfter: q.Get("updatedAfter"), UpdatedBefore: q.Get("updatedBefore"),
Limit: min(max(limit, 0), 50),
})
a.respond(w, res, err)
}))
}
+15
View File
@@ -40,6 +40,9 @@ type SpaceService interface {
ArchivePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
UnarchivePage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
ListArchive(ctx context.Context, c access.Caller, spaceID string) ([]directory.ArchivedPage, error)
PinPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
UnpinPage(ctx context.Context, c access.Caller, id string) (directory.Page, error)
ListPinned(ctx context.Context, c access.Caller, spaceID string) ([]directory.PinnedPage, error)
}
func (a *api) spaceRoutes(mux *routeMux) {
@@ -108,6 +111,18 @@ func (a *api) spaceRoutes(mux *routeMux) {
pages, err := a.dir.ListArchive(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, pages, err)
}))
mux.HandleFunc("GET /api/v1/spaces/{id}/pinned", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
pages, err := a.dir.ListPinned(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, pages, err)
}))
mux.HandleFunc("PUT /api/v1/pages/{id}/pin", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
p, err := a.dir.PinPage(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, p, err)
}))
mux.HandleFunc("DELETE /api/v1/pages/{id}/pin", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
p, err := a.dir.UnpinPage(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, p, 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)
+1 -1
View File
@@ -183,11 +183,11 @@ func (s *Service) Register(ctx context.Context, user, endpoint, p256dh, auth, na
if err := checkKeys(p256dh, auth); err != nil {
return Device{}, apperr.InvalidFields(map[string]string{"p256dh": "Send the endpoint's Web Push keys (" + err.Error() + ")."})
}
keys := map[string]any{"user": user, "name": name, "p256dh": p256dh, "auth": auth}
name = strings.TrimSpace(name)
if r := []rune(name); len(r) > 100 {
name = string(r[:100])
}
keys := map[string]any{"user": user, "name": name, "p256dh": p256dh, "auth": auth}
res, err := pocketbase.List[deviceRecord](ctx, s.pb, "push_devices", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("endpoint = '%s'", strings.ReplaceAll(endpoint, "'", "")),
})
+6 -1
View File
@@ -104,10 +104,15 @@ func encrypt(plaintext []byte, p256dh, auth string) ([]byte, error) {
// One record, so it is the last: padding delimiter 0x02.
sealed := gcm.Seal(nil, nonce, append(plaintext, 2), nil)
// An uncompressed P-256 point, the only kind ECDH hands out.
const keyLen = 65
if len(asPub) != keyLen {
return nil, errors.New("webpush: unexpected server key length")
}
header := make([]byte, 0, 16+4+1+len(asPub))
header = append(header, salt...)
header = binary.BigEndian.AppendUint32(header, recordSize)
header = append(header, byte(len(asPub)))
header = append(header, keyLen)
header = append(header, asPub...)
return append(header, sealed...), nil
}
+117 -41
View File
@@ -31,14 +31,36 @@ import (
"docwell/server/internal/store/pocketbase"
)
// doc is what the index stores per page.
// doc is what the index stores per page. Modified is Updated parsed, so
// searches can be limited to a time range.
type doc struct {
Workspace string `json:"workspace"`
Space string `json:"space"`
Title string `json:"title"`
Icon string `json:"icon"`
Text string `json:"text"`
Updated string `json:"updated"`
Workspace string `json:"workspace"`
Space string `json:"space"`
Title string `json:"title"`
Icon string `json:"icon"`
Text string `json:"text"`
Creator string `json:"creator"`
Editor string `json:"editor"`
Updated string `json:"updated"`
Modified time.Time `json:"modified"`
}
// Filter narrows a search. Zero fields do not filter.
type Filter struct {
Author string // created or last edited the page
After, Before time.Time
}
func (f Filter) empty() bool { return f.Author == "" && f.After.IsZero() && f.Before.IsZero() }
const pbTimeLayout = "2006-01-02 15:04:05.000Z"
func newDoc(p pageRow) doc {
modified, _ := time.Parse(pbTimeLayout, p.Updated)
return doc{
Workspace: p.Workspace, Space: p.Space, Title: p.Title, Icon: p.Icon, Text: p.ContentText,
Creator: p.Creator, Editor: p.LastEditor, Updated: p.Updated, Modified: modified,
}
}
// Hit is one search result. Highlights are [start, end) rune offsets of the
@@ -72,7 +94,13 @@ func (x *Index) tracked(name string, fn func() error) error {
return x.track(name, fn)
}
const checkpointKey = "checkpoint"
const (
checkpointKey = "checkpoint"
// mappingKey holds mappingVersion; an index built with another mapping is
// rebuilt on open. Bump the version whenever newMapping changes.
mappingKey = "mapping"
mappingVersion = "2"
)
func newMapping() mapping.IndexMapping {
keywordField := bleve.NewKeywordFieldMapping()
@@ -86,6 +114,9 @@ func newMapping() mapping.IndexMapping {
page := bleve.NewDocumentMapping()
page.AddFieldMappingsAt("workspace", keywordField)
page.AddFieldMappingsAt("space", keywordField)
page.AddFieldMappingsAt("creator", keywordField)
page.AddFieldMappingsAt("editor", keywordField)
page.AddFieldMappingsAt("modified", bleve.NewDateTimeFieldMapping())
page.AddFieldMappingsAt("title", text)
page.AddFieldMappingsAt("text", text)
page.AddFieldMappingsAt("icon", stored)
@@ -98,21 +129,28 @@ func newMapping() mapping.IndexMapping {
}
// Open opens the index in dir, creating it when missing. An index that cannot
// be opened (corrupt, or from an incompatible version) is rebuilt.
// be opened (corrupt, or from an incompatible version) or that was built with
// an older mapping is rebuilt.
func Open(dir string, pb *pocketbase.Client, log *slog.Logger) (*Index, error) {
path := filepath.Join(dir, "search.bleve")
idx, err := bleve.Open(path)
if err == nil {
if v, vErr := idx.GetInternal([]byte(mappingKey)); vErr != nil || string(v) != mappingVersion {
_ = idx.Close()
err = errors.New("built with an older mapping")
}
}
if errors.Is(err, bleve.ErrorIndexPathDoesNotExist) {
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, err
}
idx, err = bleve.New(path, newMapping())
idx, err = createIndex(path)
} else if err != nil {
log.Warn("search: rebuilding unreadable index", "err", err)
if rmErr := os.RemoveAll(path); rmErr != nil {
return nil, rmErr
}
idx, err = bleve.New(path, newMapping())
idx, err = createIndex(path)
}
if err != nil {
return nil, fmt.Errorf("search index %s: %w", path, err)
@@ -120,6 +158,18 @@ func Open(dir string, pb *pocketbase.Client, log *slog.Logger) (*Index, error) {
return &Index{idx: idx, pb: pb, log: log}, nil
}
func createIndex(path string) (bleve.Index, error) {
idx, err := bleve.New(path, newMapping())
if err != nil {
return nil, err
}
if err := idx.SetInternal([]byte(mappingKey), []byte(mappingVersion)); err != nil {
_ = idx.Close()
return nil, err
}
return idx, nil
}
// OpenMemory opens an in-memory index (tests).
func OpenMemory(pb *pocketbase.Client, log *slog.Logger) (*Index, error) {
idx, err := bleve.NewMemOnly(newMapping())
@@ -171,6 +221,8 @@ type pageRow struct {
Title string `json:"title"`
Icon string `json:"icon"`
ContentText string `json:"content_text"`
Creator string `json:"creator"`
LastEditor string `json:"last_editor"`
DeletedAt string `json:"deleted_at"`
Updated string `json:"updated"`
}
@@ -192,7 +244,7 @@ func (x *Index) CatchUp(ctx context.Context) error {
}
res, err := pocketbase.List[pageRow](ctx, x.pb, "pages", pocketbase.ListOptions{
PerPage: 200, Filter: filter, Sort: "updated,id",
Fields: "id,workspace,space,title,icon,content_text,deleted_at,updated",
Fields: "id,workspace,space,title,icon,content_text,creator,last_editor,deleted_at,updated",
})
if err != nil {
return err
@@ -204,9 +256,7 @@ func (x *Index) CatchUp(ctx context.Context) error {
batch.Delete(p.ID)
continue
}
if err := batch.Index(p.ID, doc{
Workspace: p.Workspace, Space: p.Space, Title: p.Title, Icon: p.Icon, Text: p.ContentText, Updated: p.Updated,
}); err != nil {
if err := batch.Index(p.ID, newDoc(p)); err != nil {
return err
}
}
@@ -286,10 +336,11 @@ func (x *Index) Rebuild(ctx context.Context) error {
}
// Query searches the pages of workspace inside spaces (the caller's visible
// spaces). An empty spaces list finds nothing.
func (x *Index) Query(ctx context.Context, workspace string, spaces []string, text string, limit int) ([]Hit, int, error) {
// spaces). An empty spaces list finds nothing. Empty text with a non-empty
// filter lists the matching pages, most recently changed first.
func (x *Index) Query(ctx context.Context, workspace string, spaces []string, text string, f Filter, limit int) ([]Hit, int, error) {
text = strings.TrimSpace(text)
if text == "" || len(spaces) == 0 {
if (text == "" && f.empty()) || len(spaces) == 0 {
return []Hit{}, 0, nil
}
if len(text) > 200 {
@@ -304,35 +355,33 @@ func (x *Index) Query(ctx context.Context, workspace string, spaces []string, te
q.SetField("space")
inSpace = append(inSpace, q)
}
// Words match in the title (worth more) or the text; the last word also
// matches as a prefix, so results appear while typing.
var match []query.Query
for field, boost := range map[string]float64{"title": 3, "text": 1} {
m := bleve.NewMatchQuery(text)
m.SetField(field)
m.SetBoost(boost)
match = append(match, m)
fuzzy := bleve.NewMatchQuery(text)
fuzzy.SetField(field)
fuzzy.SetFuzziness(1)
fuzzy.SetBoost(boost / 4)
match = append(match, fuzzy)
}
words := strings.Fields(strings.ToLower(text))
if last := words[len(words)-1]; utf8.RuneCountInString(last) >= 2 {
for field, boost := range map[string]float64{"title": 2, "text": 0.5} {
p := bleve.NewPrefixQuery(last)
p.SetField(field)
p.SetBoost(boost)
match = append(match, p)
must := []query.Query{ws, bleve.NewDisjunctionQuery(inSpace...)}
if f.Author != "" {
var by []query.Query
for _, field := range []string{"creator", "editor"} {
q := bleve.NewTermQuery(f.Author)
q.SetField(field)
by = append(by, q)
}
must = append(must, bleve.NewDisjunctionQuery(by...))
}
if !f.After.IsZero() || !f.Before.IsZero() {
inclusive := true
q := bleve.NewDateRangeInclusiveQuery(f.After, f.Before, &inclusive, &inclusive)
q.SetField("modified")
must = append(must, q)
}
if text != "" {
must = append(must, textQuery(text))
}
q := bleve.NewConjunctionQuery(ws, bleve.NewDisjunctionQuery(inSpace...), bleve.NewDisjunctionQuery(match...))
q := bleve.NewConjunctionQuery(must...)
req := bleve.NewSearchRequestOptions(q, max(1, min(limit, 50)), 0, false)
req.Fields = []string{"title", "icon", "space", "text", "updated"}
req.IncludeLocations = true
if text == "" {
req.SortBy([]string{"-modified", "_id"})
}
res, err := x.idx.SearchInContext(ctx, req)
if err != nil {
return nil, 0, err
@@ -355,6 +404,33 @@ func (x *Index) Query(ctx context.Context, workspace string, spaces []string, te
return hits, toInt(res.Total), nil
}
// textQuery matches words in the title (worth more) or the text; the last
// word also matches as a prefix, so results appear while typing.
func textQuery(text string) query.Query {
var match []query.Query
for field, boost := range map[string]float64{"title": 3, "text": 1} {
m := bleve.NewMatchQuery(text)
m.SetField(field)
m.SetBoost(boost)
match = append(match, m)
fuzzy := bleve.NewMatchQuery(text)
fuzzy.SetField(field)
fuzzy.SetFuzziness(1)
fuzzy.SetBoost(boost / 4)
match = append(match, fuzzy)
}
words := strings.Fields(strings.ToLower(text))
if last := words[len(words)-1]; utf8.RuneCountInString(last) >= 2 {
for field, boost := range map[string]float64{"title": 2, "text": 0.5} {
p := bleve.NewPrefixQuery(last)
p.SetField(field)
p.SetBoost(boost)
match = append(match, p)
}
}
return bleve.NewDisjunctionQuery(match...)
}
// toInt converts Bleve's counts and offsets, which are far below MaxInt32 in practice.
func toInt(u uint64) int {
if u > math.MaxInt32 {
+83 -5
View File
@@ -7,6 +7,7 @@ import (
"io"
"log/slog"
"testing"
"time"
)
func newIndex(t *testing.T) *Index {
@@ -32,7 +33,7 @@ func TestQueryScopesAndRanks(t *testing.T) {
put("p4", "w2", "s9", "Deployment elsewhere", "Another workspace.")
ctx := context.Background()
hits, total, err := x.Query(ctx, "w1", []string{"s1"}, "deployment", 10)
hits, total, err := x.Query(ctx, "w1", []string{"s1"}, "deployment", Filter{}, 10)
if err != nil {
t.Fatal(err)
}
@@ -49,25 +50,102 @@ func TestQueryScopesAndRanks(t *testing.T) {
}
// Typing: the last word matches as a prefix.
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "meet", 10); len(hits) != 1 || hits[0].ID != "p2" {
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "meet", Filter{}, 10); len(hits) != 1 || hits[0].ID != "p2" {
t.Errorf("prefix = %+v", hits)
}
// One wrong letter is forgiven.
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "deploymant", 10); len(hits) == 0 {
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "deploymant", Filter{}, 10); len(hits) == 0 {
t.Error("fuzzy match failed")
}
if hits, _, _ := x.Query(ctx, "w1", nil, "deployment", 10); len(hits) != 0 {
if hits, _, _ := x.Query(ctx, "w1", nil, "deployment", Filter{}, 10); len(hits) != 0 {
t.Error("no visible spaces must find nothing")
}
if err := x.Remove("p1"); err != nil {
t.Fatal(err)
}
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "guide", 10); len(hits) != 0 {
if hits, _, _ := x.Query(ctx, "w1", []string{"s1"}, "guide", Filter{}, 10); len(hits) != 0 {
t.Errorf("removed page still found: %+v", hits)
}
}
func TestQueryFilters(t *testing.T) {
x := newIndex(t)
put := func(id, creator, editor, updated, title string) {
if err := x.Put(id, newDoc(pageRow{
ID: id, Workspace: "w1", Space: "s1", Title: title, Creator: creator, LastEditor: editor, Updated: updated,
})); err != nil {
t.Fatal(err)
}
}
put("old", "ann", "ann", "2026-01-10 09:00:00.000Z", "Roadmap draft")
put("mid", "ann", "bob", "2026-06-15 12:00:00.000Z", "Roadmap review")
put("new", "cat", "cat", "2026-10-30 18:30:00.000Z", "Roadmap final")
ctx := context.Background()
ids := func(f Filter, text string) []string {
t.Helper()
hits, _, err := x.Query(ctx, "w1", []string{"s1"}, text, f, 10)
if err != nil {
t.Fatal(err)
}
var out []string
for _, h := range hits {
out = append(out, h.ID)
}
return out
}
day := func(s string) time.Time { v, _ := time.Parse(time.DateOnly, s); return v }
if got := ids(Filter{Author: "bob"}, "roadmap"); len(got) != 1 || got[0] != "mid" {
t.Errorf("last editor = %v", got)
}
if got := ids(Filter{Author: "ann"}, "roadmap"); len(got) != 2 {
t.Errorf("creator or editor = %v", got)
}
if got := ids(Filter{After: day("2026-06-01")}, "roadmap"); len(got) != 2 {
t.Errorf("after = %v", got)
}
if got := ids(Filter{After: day("2026-06-01"), Before: day("2026-07-01")}, "roadmap"); len(got) != 1 || got[0] != "mid" {
t.Errorf("range = %v", got)
}
// No words but a filter: newest first.
if got := ids(Filter{After: day("2026-01-01")}, ""); len(got) != 3 || got[0] != "new" || got[2] != "old" {
t.Errorf("filter only = %v", got)
}
if got := ids(Filter{}, ""); len(got) != 0 {
t.Errorf("nothing asked = %v", got)
}
}
func TestOpenRebuildsOldMapping(t *testing.T) {
dir := t.TempDir()
log := slog.New(slog.NewTextHandler(io.Discard, nil))
x, err := Open(dir, nil, log)
if err != nil {
t.Fatal(err)
}
if err := x.Put("p1", doc{Workspace: "w1", Space: "s1", Title: "Kept?"}); err != nil {
t.Fatal(err)
}
if err := x.idx.SetInternal([]byte(mappingKey), []byte("1")); err != nil {
t.Fatal(err)
}
_ = x.Close()
x, err = Open(dir, nil, log)
if err != nil {
t.Fatal(err)
}
defer x.Close()
if n, _ := x.Count(); n != 0 {
t.Errorf("an index with an old mapping must start over, has %d pages", n)
}
if v, _ := x.idx.GetInternal([]byte(mappingKey)); string(v) != mappingVersion {
t.Errorf("mapping version = %q", v)
}
}
func TestSnippet(t *testing.T) {
text := "Zażółć gęślą jaźń. The quick brown fox jumps over the lazy dog."
start := len("Zażółć gęślą jaźń. The quick ")
+2 -2
View File
@@ -82,8 +82,8 @@ func guard(_, address string, _ syscall.RawConn) error {
// Public reports whether ip is on the public internet.
func Public(ip net.IP) bool {
return !(ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
ip.IsUnspecified() || ip.IsMulticast() || ip.IsInterfaceLocalMulticast() || cgnat.Contains(ip))
return !ip.IsLoopback() && !ip.IsPrivate() && !ip.IsLinkLocalUnicast() && !ip.IsLinkLocalMulticast() &&
!ip.IsUnspecified() && !ip.IsMulticast() && !ip.IsInterfaceLocalMulticast() && !cgnat.Contains(ip)
}
// Preview fetches raw and reads its preview. Pages that are not HTML, or
@@ -1,18 +1,22 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { PageItem, SearchHit } from "@docwell/api-client";
import type { MemberUser, PageItem, SearchFilter, SearchHit } from "@docwell/api-client";
import { DwIcon } from "@docwell/ui";
import { computed, nextTick, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useApi } from "../api";
import { useAuthStore } from "../stores/auth";
import { useSpacesStore } from "../stores/spaces";
import { useWorkspacesStore } from "../stores/workspaces";
// The Ctrl+K palette: full-text search of the current workspace, showing the
// recently visited pages until something is typed.
// recently visited pages until something is typed or a filter is picked.
const open = defineModel<boolean>({ default: false });
const api = useApi();
const router = useRouter();
const workspaces = useWorkspacesStore();
const spaces = useSpacesStore();
const auth = useAuthStore();
const input = ref<HTMLInputElement | null>(null);
const q = ref("");
@@ -22,6 +26,23 @@ const active = ref(0);
const loading = ref(false);
const failed = ref(false);
// Filters: a space, someone who created or last edited the page, and how
// recently it changed. They stay set while the palette is reopened.
const space = ref("");
const author = ref("");
const since = ref<"" | "day" | "week" | "month" | "year">("");
const people = ref<MemberUser[]>([]);
const sinceDays = { day: 1, week: 7, month: 30, year: 365 } as const;
const filter = computed<SearchFilter>(() => ({
space: space.value || undefined,
author: author.value || undefined,
updatedAfter: since.value ? new Date(Date.now() - sinceDays[since.value] * 864e5).toISOString() : undefined,
}));
const filtered = computed(() => !!(space.value || author.value || since.value));
const searching = computed(() => !!q.value.trim() || filtered.value);
const others = computed(() => people.value.filter((p) => p.id !== auth.user?.id));
type Row = { id: string; title: string; icon: string; spaceName: string; parts: { text: string; mark: boolean }[] };
/** Splits a snippet into plain and highlighted runs (offsets count characters, not UTF-16 units). */
@@ -40,7 +61,7 @@ function parts(snippet: string, highlights: number[][]): Row["parts"] {
}
const rows = computed<Row[]>(() =>
q.value.trim()
searching.value
? hits.value.map((h) => ({ ...h, parts: parts(h.snippet, h.highlights) }))
: recent.value.map((p) => ({ ...p, parts: [] })),
);
@@ -53,18 +74,26 @@ watch(open, async (v) => {
await nextTick();
input.value?.focus();
const ws = workspaces.current;
if (ws) recent.value = await api.workspaces.recent(ws.id, 8).catch(() => []);
if (!ws) return;
if (filtered.value) run();
const [r, p] = await Promise.all([
api.workspaces.recent(ws.id, 8).catch(() => []),
api.workspaces.people(ws.id, "", 50).catch(() => []),
]);
recent.value = r;
people.value = p;
});
// Search after a short pause in typing; only the latest answer counts.
let timer: ReturnType<typeof setTimeout> | undefined;
let seq = 0;
watch(q, (text) => {
function run() {
clearTimeout(timer);
active.value = 0;
failed.value = false;
const ws = workspaces.current;
if (!text.trim() || !ws) {
const text = q.value;
if (!searching.value || !ws) {
hits.value = [];
loading.value = false;
return;
@@ -73,7 +102,7 @@ watch(q, (text) => {
timer = setTimeout(async () => {
const mine = ++seq;
try {
const res = await api.workspaces.search(ws.id, text, 20);
const res = await api.workspaces.search(ws.id, text, 20, filter.value);
if (mine === seq) hits.value = res.items;
} catch {
if (mine === seq) failed.value = true;
@@ -81,7 +110,8 @@ watch(q, (text) => {
if (mine === seq) loading.value = false;
}
}, 150);
});
}
watch([q, filter], run);
function go(row: Row | undefined) {
if (!row) return;
@@ -139,8 +169,34 @@ function onKey(e: KeyboardEvent) {
/>
<kbd class="font-mono text-[11px] text-ink-faint">Esc</kbd>
</div>
<div class="flex flex-wrap gap-2 border-b border-line px-3 py-2 text-ui-sm" data-testid="search-filters">
<select v-model="space" class="dw-filter" :class="{ on: space }" :aria-label="$t('search.space')">
<option value="">{{ $t("search.anySpace") }}</option>
<option v-for="s in spaces.items" :key="s.id" :value="s.id">{{ s.name }}</option>
</select>
<select v-model="author" class="dw-filter" :class="{ on: author }" :aria-label="$t('search.author')">
<option value="">{{ $t("search.anyone") }}</option>
<option v-if="auth.user" :value="auth.user.id">{{ $t("search.me") }}</option>
<option v-for="p in others" :key="p.id" :value="p.id">{{ p.name || p.email }}</option>
</select>
<select v-model="since" class="dw-filter" :class="{ on: since }" :aria-label="$t('search.updated')">
<option value="">{{ $t("search.anyTime") }}</option>
<option value="day">{{ $t("search.pastDay") }}</option>
<option value="week">{{ $t("search.pastWeek") }}</option>
<option value="month">{{ $t("search.pastMonth") }}</option>
<option value="year">{{ $t("search.pastYear") }}</option>
</select>
<button
v-if="filtered"
type="button"
class="ml-auto text-ink-muted hover:text-ink"
@click="((space = ''), (author = ''), (since = ''))"
>
{{ $t("search.clear") }}
</button>
</div>
<p v-if="!q.trim() && rows.length" class="px-4 pt-3 dw-label">{{ $t("home.recent") }}</p>
<p v-if="!searching && rows.length" class="px-4 pt-3 dw-label">{{ $t("home.recent") }}</p>
<ul id="search-results" role="listbox" class="max-h-[50vh] overflow-y-auto p-1">
<li
v-for="(r, i) in rows"
@@ -170,10 +226,24 @@ function onKey(e: KeyboardEvent) {
</span>
</li>
</ul>
<p v-if="q.trim() && !loading && !rows.length" class="px-4 pt-1 pb-4 text-ui-md text-ink-muted">
{{ failed ? $t("errors.unknown") : $t("search.none", { q }) }}
<p v-if="searching && !loading && !rows.length" class="px-4 pt-1 pb-4 text-ui-md text-ink-muted">
{{ failed ? $t("errors.unknown") : q.trim() ? $t("search.none", { q }) : $t("search.noneFiltered") }}
</p>
</div>
</div>
</Teleport>
</template>
<style scoped>
.dw-filter {
border-radius: var(--radius-sm, 4px);
border: 1px solid var(--color-line);
background: var(--color-surface);
padding: 2px 6px;
color: var(--color-ink-muted);
}
.dw-filter.on {
border-color: var(--color-accent);
color: var(--color-ink);
}
</style>
@@ -52,6 +52,19 @@ const blockWords = [
"copyBlockLink",
] as const;
const findWords = [
"find",
"replace",
"previous",
"next",
"replaceOne",
"replaceAll",
"matchCase",
"close",
"count",
"none",
] as const;
/** The editor's menu and button words in the app's language. */
export function useEditorLabels() {
const { t } = useI18n();
@@ -78,6 +91,10 @@ export function useEditorLabels() {
pageLinks: t("editor.pageLinks"),
noPages: t("editor.noPages"),
blocks: Object.fromEntries(blockWords.map((w) => [w, t(`editor.block.${w}`)])) as EditorLabels["blocks"],
// The editor fills in {current} and {total} itself, so they pass through.
find: Object.fromEntries(
findWords.map((w) => [w, t(`editor.find.${w}`, { current: "{current}", total: "{total}" })]),
) as EditorLabels["find"],
}));
}
+37 -1
View File
@@ -208,6 +208,7 @@
"delete": "Delete space",
"deleteHint": "Deletes all of its pages, including the trash. This cannot be undone.",
"confirmDelete": "Delete {name} with all of its pages?",
"pinned": "Pinned",
"pages": "Pages",
"noPages": "No pages yet.",
"pageCount": "{n} page | {n} pages",
@@ -283,6 +284,16 @@
"exportHtml": "Export as HTML",
"exportPdf": "Export as PDF",
"backlinks": "Linked from {n} page | Linked from {n} pages",
"find": "Find and replace",
"fullWidth": "Full width",
"standardWidth": "Standard width",
"font": {
"sans": "Default font",
"serif": "Serif font",
"mono": "Monospace font"
},
"pin": "Pin to space home",
"unpin": "Unpin from space home",
"archive": "Archive",
"unarchive": "Unarchive",
"archived": "This page is archived. It is read-only until someone unarchives it.",
@@ -319,7 +330,20 @@
},
"search": {
"placeholder": "Search pages…",
"none": "Nothing found for \"{q}\"."
"none": "Nothing found for \"{q}\".",
"noneFiltered": "No pages match these filters.",
"space": "Space",
"anySpace": "Any space",
"author": "Created or edited by",
"anyone": "Anyone",
"me": "Me",
"updated": "Last changed",
"anyTime": "Any time",
"pastDay": "Past 24 hours",
"pastWeek": "Past week",
"pastMonth": "Past month",
"pastYear": "Past year",
"clear": "Clear filters"
},
"share": {
"button": "Share",
@@ -360,6 +384,18 @@
"limitedSpace": "You see only the pages of {space} that are shared with you."
},
"editor": {
"find": {
"find": "Find in page",
"replace": "Replace with",
"previous": "Previous match",
"next": "Next match",
"replaceOne": "Replace",
"replaceAll": "Replace all",
"matchCase": "Match case",
"close": "Close",
"count": "{current} of {total}",
"none": "No matches"
},
"slashMenu": "Insert block",
"noMatches": "No matching blocks",
"mentions": "Mention someone",
+37 -1
View File
@@ -208,6 +208,7 @@
"delete": "Usuń przestrzeń",
"deleteHint": "Usuwa wszystkie jej strony, także z kosza. Tego nie można cofnąć.",
"confirmDelete": "Usunąć {name} ze wszystkimi stronami?",
"pinned": "Przypięte",
"pages": "Strony",
"noPages": "Brak stron.",
"pageCount": "{n} strona | {n} strony | {n} stron",
@@ -283,6 +284,16 @@
"exportHtml": "Eksportuj jako HTML",
"exportPdf": "Eksportuj jako PDF",
"backlinks": "Linkuje tu {n} strona | Linkują tu {n} strony | Linkuje tu {n} stron",
"find": "Znajdź i zamień",
"fullWidth": "Pełna szerokość",
"standardWidth": "Standardowa szerokość",
"font": {
"sans": "Domyślna czcionka",
"serif": "Czcionka szeryfowa",
"mono": "Czcionka o stałej szerokości"
},
"pin": "Przypnij na stronie przestrzeni",
"unpin": "Odepnij ze strony przestrzeni",
"archive": "Archiwizuj",
"unarchive": "Przywróć z archiwum",
"archived": "Ta strona jest zarchiwizowana. Jest tylko do odczytu, dopóki ktoś jej nie przywróci.",
@@ -319,7 +330,20 @@
},
"search": {
"placeholder": "Szukaj stron…",
"none": "Nic nie znaleziono dla „{q}”."
"none": "Nic nie znaleziono dla „{q}”.",
"noneFiltered": "Żadna strona nie pasuje do tych filtrów.",
"space": "Przestrzeń",
"anySpace": "Każda przestrzeń",
"author": "Utworzone lub edytowane przez",
"anyone": "Ktokolwiek",
"me": "Ja",
"updated": "Ostatnia zmiana",
"anyTime": "Kiedykolwiek",
"pastDay": "Ostatnie 24 godziny",
"pastWeek": "Ostatni tydzień",
"pastMonth": "Ostatni miesiąc",
"pastYear": "Ostatni rok",
"clear": "Wyczyść filtry"
},
"share": {
"button": "Udostępnij",
@@ -360,6 +384,18 @@
"limitedSpace": "Widzisz tylko te strony z {space}, które Ci udostępniono."
},
"editor": {
"find": {
"find": "Znajdź na stronie",
"replace": "Zamień na",
"previous": "Poprzednie wystąpienie",
"next": "Następne wystąpienie",
"replaceOne": "Zamień",
"replaceAll": "Zamień wszystko",
"matchCase": "Uwzględniaj wielkość liter",
"close": "Zamknij",
"count": "{current} z {total}",
"none": "Brak wyników"
},
"slashMenu": "Wstaw blok",
"noMatches": "Brak pasujących bloków",
"mentions": "Wspomnij kogoś",
+43 -3
View File
@@ -1,6 +1,6 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Comment, Page, PageItem, Template } from "@docwell/api-client";
import type { Comment, Page, PageFont, PageItem, Template } from "@docwell/api-client";
import {
CollabProvider,
DocwellEditor,
@@ -166,6 +166,14 @@ const toggleTemplate = () =>
if (page.value?.id === p.id) page.value = p;
});
// Layout for everyone: full width, and the body font.
const setLayout = (patch: { fullWidth?: boolean; font?: PageFont }) =>
run(async () => {
const p = await api.pages.update(page.value!.id, patch);
if (page.value?.id === p.id) page.value = p;
});
const fonts: PageFont[] = ["", "serif", "mono"];
// Watching: new comments on the page land in the inbox.
const watching = ref(false);
async function loadWatch(id: string) {
@@ -378,6 +386,7 @@ const exportAs = (format: "markdown" | "html" | "pdf") =>
});
const menu = computed<MenuItem[]>(() => [
{ label: t("page.find"), icon: "search", onSelect: () => editorRef.value?.openFind() },
{
label: t(watching.value ? "notifications.unwatch" : "notifications.watch"),
icon: watching.value ? "bell-off" : "bell",
@@ -392,7 +401,28 @@ const menu = computed<MenuItem[]>(() => [
},
]
: []),
...(editable.value ? [{ label: t("page.archive"), icon: "archive" as const, onSelect: () => archive() }] : []),
...(editable.value
? [
{
label: t(page.value?.pinnedAt ? "page.unpin" : "page.pin"),
icon: "pin" as const,
onSelect: togglePin,
},
{ label: t("page.archive"), icon: "archive" as const, onSelect: () => archive() },
{
label: t(page.value?.fullWidth ? "page.standardWidth" : "page.fullWidth"),
icon: "width" as const,
onSelect: () => setLayout({ fullWidth: !page.value?.fullWidth }),
},
...fonts
.filter((f) => f !== page.value?.font)
.map((font) => ({
label: t(`page.font.${font || "sans"}`),
icon: "type" as const,
onSelect: () => setLayout({ font }),
})),
]
: []),
{ label: t("page.exportMarkdown"), icon: "download", onSelect: () => exportAs("markdown") },
{ label: t("page.exportHtml"), icon: "download", onSelect: () => exportAs("html") },
{ label: t("page.exportPdf"), icon: "download", onSelect: () => exportAs("pdf") },
@@ -410,6 +440,12 @@ const trash = () =>
await load(props.id);
});
const togglePin = () =>
run(async () => {
const id = page.value!.id;
page.value = await (page.value!.pinnedAt ? api.pages.unpin(id) : api.pages.pin(id));
});
const archive = () =>
run(async () => {
const p = await api.pages.archive(page.value!.id);
@@ -515,7 +551,11 @@ const purge = () =>
<ShareDialog v-if="page" v-model="shareOpen" :page="page" @changed="accessChanged" />
<div class="flex min-h-full items-start">
<article class="mx-auto min-w-0 max-w-doc flex-1 px-4 pt-6 pb-16 sm:px-16 sm:pt-10">
<article
class="mx-auto min-w-0 flex-1 px-4 pt-6 pb-16 sm:px-16 sm:pt-10"
:class="[page?.fullWidth ? 'max-w-doc-wide' : 'max-w-doc', page?.font ? `dw-font-${page.font}` : '']"
data-testid="page-article"
>
<DwCallout v-if="notFound" tone="info" size="ui">{{ $t("page.notFound") }}</DwCallout>
<template v-if="page">
<DwCallout v-if="page.inTrash" tone="warning" size="ui" class="mb-4 items-center" role="status">
+43 -1
View File
@@ -1,6 +1,6 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Space } from "@docwell/api-client";
import type { PinnedPage, Space } from "@docwell/api-client";
import { DwBadge, DwBreadcrumbs, DwButton, DwCallout, DwIcon, DwMenu, type MenuItem } from "@docwell/ui";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
@@ -18,6 +18,7 @@ const router = useRouter();
const { t } = useI18n();
const space = ref<Space | null>(null);
const pinned = ref<PinnedPage[]>([]);
const notFound = ref(false);
const pages = computed(() => spaces.childrenOf(props.id, ""));
@@ -27,8 +28,10 @@ watch(
spaces.active = { space: id, page: "" };
notFound.value = false;
try {
pinned.value = [];
space.value = await api.spaces.get(id);
if (!spaces.trees[id]) await spaces.loadTree(id);
pinned.value = await api.spaces.pinned(id).catch(() => []);
} catch {
space.value = null;
notFound.value = true;
@@ -77,6 +80,15 @@ const exportMenu = computed<MenuItem[]>(() => [
{ label: t("space.exportHtml"), icon: "download", onSelect: () => exportSpace("html") },
]);
async function unpin(id: string) {
try {
await api.pages.unpin(id);
pinned.value = pinned.value.filter((p) => p.id !== id);
} catch (e) {
emit("error", e);
}
}
async function newPage() {
try {
const page = await spaces.createPage(props.id);
@@ -113,6 +125,36 @@ async function newPage() {
</p>
</div>
<section v-if="pinned.length" class="mt-10" data-testid="pinned-pages">
<h2 class="dw-label">{{ $t("space.pinned") }}</h2>
<ul class="mt-2 grid gap-2 sm:grid-cols-2">
<li
v-for="p in pinned"
:key="p.id"
class="group flex items-center gap-2 rounded-md border border-line bg-surface-raised px-3 py-2"
>
<RouterLink
:to="{ name: 'page', params: { id: p.id } }"
class="flex min-w-0 flex-1 items-center gap-2 text-ink hover:text-accent"
>
<span v-if="p.icon" class="w-5 shrink-0 text-center">{{ p.icon }}</span>
<DwIcon v-else name="page" :size="18" class="shrink-0 text-ink-muted" />
<span class="truncate font-medium">{{ p.title || $t("home.untitled") }}</span>
</RouterLink>
<button
v-if="spaceAtLeast(space.role, 'editor')"
type="button"
class="rounded-xs p-1 text-ink-faint hover:bg-surface-hover hover:text-ink sm:opacity-0 sm:group-hover:opacity-100 sm:focus-visible:opacity-100"
:title="$t('page.unpin')"
:aria-label="$t('page.unpin')"
@click="unpin(p.id)"
>
<DwIcon name="close" :size="14" />
</button>
</li>
</ul>
</section>
<div class="mt-10 flex items-center justify-between gap-2">
<h2 class="dw-label">{{ $t("space.pages") }}</h2>
<div class="flex gap-1">
+80 -2
View File
@@ -924,6 +924,22 @@ paths:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/ArchivedPage" } }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/pinned:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listPinned
tags: [pages]
summary: Pages pinned to the space's home, in the order they were pinned
description: Pinned pages in the trash or the archive are left out until they are restored.
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/PinnedPage" } }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/export:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
@@ -965,7 +981,7 @@ paths:
patch:
operationId: updatePage
tags: [pages]
summary: Rename a page, change its icon, or make it a template (editor)
summary: Rename a page, change its icon or layout, or make it a template (editor)
security: [{ bearer: [] }]
requestBody:
required: true
@@ -977,6 +993,8 @@ paths:
title: { type: string, maxLength: 500 }
icon: { type: string, maxLength: 32 }
isTemplate: { type: boolean, description: Offer the page as a template for new pages }
fullWidth: { type: boolean, description: Use the whole window instead of the reading column }
font: { $ref: "#/components/schemas/PageFont" }
responses:
"200":
description: OK
@@ -1604,6 +1622,36 @@ paths:
responses:
"204": { description: Removed }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/pin:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
put:
operationId: pinPage
tags: [pages]
summary: Pin the page to its space's home for everyone (editor; at most 12 per space)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Page" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: unpinPage
tags: [pages]
summary: Take the page off its space's home (editor)
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Page" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/visit:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
@@ -1715,16 +1763,30 @@ paths:
summary: Full-text search of page titles and text, in the spaces the caller can open
description: >-
Trashed pages are not found. The index catches up with edits within a few seconds.
The filters narrow the results; with an empty q and at least one filter, the
matching pages are listed, most recently changed first. A space the caller cannot
open finds nothing.
security: [{ bearer: [] }]
parameters:
- { name: q, in: query, required: true, schema: { type: string, maxLength: 200 } }
- { name: limit, in: query, schema: { type: integer, minimum: 1, maximum: 50 } }
- { name: space, in: query, description: Only pages in this space, schema: { type: string } }
- { name: author, in: query, description: Only pages this user created or last edited, schema: { type: string } }
- name: updatedAfter
in: query
description: Only pages changed at or after this time (RFC 3339) or day (YYYY-MM-DD)
schema: { type: string }
- name: updatedBefore
in: query
description: Only pages changed at or before this time (RFC 3339) or the end of this day (YYYY-MM-DD)
schema: { type: string }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/SearchResult" }
"400": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/pages/{id}/export:
parameters:
@@ -2774,7 +2836,7 @@ components:
Page:
type: object
required:
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite]
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite, pinnedAt, fullWidth, font]
properties:
id: { type: string }
workspace: { type: string }
@@ -2793,6 +2855,13 @@ components:
restricted: { type: boolean, description: The page or one of its ancestors is restricted }
isTemplate: { type: boolean, description: Offered as a template for new pages }
favorite: { type: boolean, description: In the caller's favorites }
pinnedAt: { type: string, description: When the page was pinned to its space's home; empty if not }
fullWidth: { type: boolean, description: Shown across the whole window instead of the reading column }
font: { $ref: "#/components/schemas/PageFont" }
PageFont:
type: string
enum: ["", serif, mono]
description: The body font for everyone reading the page; empty is the default sans
PageGrantRole: { type: string, enum: [editor, commenter, viewer] }
SpaceCallerRole:
type: string
@@ -2885,6 +2954,15 @@ components:
title: { type: string }
icon: { type: string }
archivedAt: { type: string }
PinnedPage:
type: object
required: [id, title, icon, updated, pinnedAt]
properties:
id: { type: string }
title: { type: string }
icon: { type: string }
updated: { type: string }
pinnedAt: { type: string }
LinkPreview:
type: object
required: [url, title, description, image, site]
+3 -1
View File
@@ -11230,7 +11230,9 @@
},
"devDependencies": {
"@types/react": "^18.3.31",
"@types/react-dom": "^18.3.7"
"@types/react-dom": "^18.3.7",
"jsdom": "^30.1.3",
"vitest": "^5.0.5"
},
"peerDependencies": {
"vue": "^3.5.0"