Add page properties, tags, All docs, collections and journals

Phase B (items 1-6) of docs/AFFINE.md.

Properties: workspaces define custom page properties (text, number,
checkbox, date, select, multi-select, person, link) in the new
workspace_properties collection; pages keep their values in
pages.properties, checked against each property's type. The Info panel
under the title shows tags, custom and built-in properties, following
each property's visibility; the Info side panel shows them all, with the
page's collections and the journal. Settings gains Page properties and
Tags sections.

Tags: coloured, per workspace (tags collection, pages.tags); create from
the picker, rename, recolour, merge and delete. Search filters by tag.

All docs: GET /workspaces/{id}/docs lists the pages the caller can open
with their properties, narrowed by space, tag, collection or filter
rules evaluated on the server. The view shows a list, grid or cards,
groups and orders by any property, picks the properties shown, and acts
on several pages at once (tag, move, trash, collect).

Collections (page_collections): saved rules plus pages added or taken
out by hand, private to their creator until shared with the workspace,
listed in the sidebar.

Journals: one page per person and day in a private journal space
(spaces.journal_owner) that workspace admins do not see into, made on
first use. A week strip marks days with pages, new days can start from
a template, and dates in read mode open that day's journal.

The migration and schema snapshot, OpenAPI spec and generated Go, TS and
Dart types are updated (the Dart generator learns untyped values), the
mobile editor bundle is rebuilt, the new strings are translated into all
five languages, and the user guide covers the new features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-14 16:35:42 +01:00
1 parent 3dea2bb2f4
commit ec11abd8b8
53 files changed
+9368 -63

No files matched your search

@@ -0,0 +1,111 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference path="../pb_data/types.d.ts" />
// Phase B of docs/AFFINE.md: page properties, tags, collections and journals.
//
// - workspace_properties: the custom properties every page of a workspace can
// fill in. pages.properties holds the values as { "<property id>": value }.
// - tags: coloured labels per workspace; pages.tags lists a page's tags.
// - page_collections: saved views of pages (rules plus pages added by hand),
// private to their creator or shared with the workspace.
// - Journals: one page per person and day. They live in the person's journal
// space (spaces.journal_owner); pages.journal_date is the day (YYYY-MM-DD)
// and spaces.journal_template the page new journals are filled from.
migrate(
(app) => {
const users = app.findCollectionByNameOrId("users");
const workspaces = app.findCollectionByNameOrId("workspaces");
const pages = app.findCollectionByNameOrId("pages");
const spaces = app.findCollectionByNameOrId("spaces");
app.save(
new Collection({
type: "base",
name: "workspace_properties",
fields: [
{ name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true },
{ name: "name", type: "text", required: true, max: 80 },
{
name: "type",
type: "select",
required: true,
maxSelect: 1,
values: ["text", "number", "checkbox", "date", "select", "multi_select", "member", "link"],
},
// Select and multi-select choices: [{ "id", "name", "color" }].
{ name: "options", type: "json", maxSize: 20000 },
{ name: "visibility", type: "select", maxSelect: 1, values: ["always", "hide_empty", "never"] },
{ name: "position", type: "number" },
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE INDEX idx_workspace_properties_ws ON workspace_properties (workspace, position)"],
}),
);
const tags = new Collection({
type: "base",
name: "tags",
fields: [
{ name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true },
{ name: "name", type: "text", required: true, max: 60 },
{ name: "color", type: "text", max: 20 },
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE UNIQUE INDEX idx_tags_name ON tags (workspace, name COLLATE NOCASE)"],
});
app.save(tags);
app.save(
new Collection({
type: "base",
name: "page_collections",
fields: [
{ name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true },
{ name: "creator", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: true },
{ name: "name", type: "text", required: true, max: 120 },
{ name: "icon", type: "text", max: 32 },
// { "match": "all" | "any", "rules": [{ "field", "op", "value" }] }
{ name: "filter", type: "json", maxSize: 20000 },
// Page ids added by hand, and page ids the rules match but were taken out.
{ name: "include", type: "json", maxSize: 50000 },
{ name: "exclude", type: "json", maxSize: 50000 },
{ name: "shared", type: "bool" },
{ name: "created", type: "autodate", onCreate: true, onUpdate: false },
{ name: "updated", type: "autodate", onCreate: true, onUpdate: true },
],
indexes: ["CREATE INDEX idx_page_collections_ws ON page_collections (workspace, creator)"],
}),
);
pages.fields.add(new JSONField({ name: "properties", maxSize: 100000 }));
pages.fields.add(new RelationField({ name: "tags", collectionId: tags.id, maxSelect: 100, cascadeDelete: false }));
pages.fields.add(new TextField({ name: "journal_date", max: 10 }));
pages.addIndex("idx_pages_journal", false, "space, journal_date", "");
app.save(pages);
spaces.fields.add(new RelationField({ name: "journal_owner", collectionId: users.id, maxSelect: 1, cascadeDelete: true }));
spaces.fields.add(new RelationField({ name: "journal_template", collectionId: pages.id, maxSelect: 1, cascadeDelete: false }));
app.save(spaces);
},
(app) => {
const spaces = app.findCollectionByNameOrId("spaces");
spaces.fields.removeByName("journal_owner");
spaces.fields.removeByName("journal_template");
app.save(spaces);
const pages = app.findCollectionByNameOrId("pages");
pages.removeIndex("idx_pages_journal");
pages.fields.removeByName("properties");
pages.fields.removeByName("tags");
pages.fields.removeByName("journal_date");
app.save(pages);
app.delete(app.findCollectionByNameOrId("page_collections"));
app.delete(app.findCollectionByNameOrId("tags"));
app.delete(app.findCollectionByNameOrId("workspace_properties"));
},
);
+23 -2
View File
@@ -38,8 +38,29 @@ admins can delete comments.
## Finding things
Press **Ctrl+K** (⌘K on a Mac) or click **Search** in the sidebar. With nothing typed it shows the pages you
visited last; type to search titles and text in every space you can open. Star a page (☆ in the header) to keep it
under **Favorites** in the sidebar.
visited last; type to search titles and text in every space you can open. The filters narrow results by space,
tag, author or date. Star a page (☆ in the header) to keep it under **Favorites** in the sidebar.
## Properties, tags and collections
Under each page title, **Properties** shows the page's tags, the workspace's custom properties (text, number,
checkbox, date, select, multi-select, person and link) and when the page was created and changed. **Info** in the
page header opens the same list in a side panel with every property, including hidden ones. Anyone who works in the
workspace can add properties there, or in **Settings → Page properties**, where you can also order them, choose when
they show under the title and edit select choices. **Settings → Tags** renames, recolours, merges and deletes tags.
**All docs** in the sidebar lists every page you can open, as a list, a grid or cards. Group and order the list by
any property, pick which properties show, and filter it with rules (for example "Status is Done" or "changed in the
last 7 days"). Tick pages to tag, move, trash or collect them at once. **Save as collection** keeps the filter as a
**collection** in the sidebar. A collection holds the pages its rules match, plus pages added by hand from its list
or from the page's Info panel. Collections are yours until you share them with the workspace.
## Journal
**Journal** in the sidebar opens today's page in your journal: one page per day, kept in a private **Journal**
space that only you see, workspace admins included. The week strip above a journal page jumps between days; a dot
marks days that already have a page. In read mode, clicking a date in any page opens that day's journal. Pick the
page new journal pages start from in the Info panel, under **Journal**; any page marked as a template can be used.
## Sharing
+90 -2
View File
@@ -78,6 +78,23 @@ export type SpaceGroup = Schemas["SpaceGroup"];
export type MemberUser = Schemas["MemberUser"];
export type InviteInfo = Schemas["InviteInfo"];
export type CreateInviteRequest = Schemas["CreateInviteRequest"];
export type PageUser = Schemas["PageUser"];
export type PropertyType = Schemas["PropertyType"];
export type LabelColor = Schemas["LabelColor"];
export type PropertyOption = Schemas["PropertyOption"];
export type PropertyVisibility = Schemas["PropertyVisibility"];
export type Property = Schemas["Property"];
export type PropertyInput = Schemas["PropertyInput"];
export type Tag = Schemas["Tag"];
export type TagInput = Schemas["TagInput"];
export type DocRule = Schemas["DocRule"];
export type DocFilter = Schemas["DocFilter"];
export type DocItem = Schemas["DocItem"];
export type DocList = Schemas["DocList"];
export type Collection = Schemas["Collection"];
export type CollectionInput = Schemas["CollectionInput"];
export type JournalDay = Schemas["JournalDay"];
export type JournalInfo = Schemas["JournalInfo"];
export type CreateSpaceRequest = { name: string; description?: string; icon?: string; visibility?: SpaceVisibility };
export type UpdateSpaceRequest = Partial<Pick<Space, "name" | "description" | "icon" | "visibility" | "defaultRole">>;
@@ -354,6 +371,62 @@ export function createClient(opts: ClientOptions) {
request<PageItem[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/recent${query({ limit })}`),
createGroup: (id: string, input: GroupRequest) =>
post<Group>(`/api/v1/workspaces/${encodeURIComponent(id)}/groups`, input),
properties: (id: string) => request<Property[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/properties`),
createProperty: (id: string, input: PropertyInput) =>
post<Property>(`/api/v1/workspaces/${encodeURIComponent(id)}/properties`, input),
tags: (id: string) => request<Tag[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/tags`),
createTag: (id: string, input: TagInput) => post<Tag>(`/api/v1/workspaces/${encodeURIComponent(id)}/tags`, input),
/** All docs: the pages the caller can open, narrowed by the query. */
docs: (id: string, q: { space?: string; tag?: string; collection?: string; filter?: DocFilter } = {}) =>
request<DocList>(
"GET",
`/api/v1/workspaces/${encodeURIComponent(id)}/docs${query({
space: q.space,
tag: q.tag,
collection: q.collection,
filter: q.filter?.rules.length ? JSON.stringify(q.filter) : undefined,
})}`,
),
collections: (id: string) =>
request<Collection[]>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/collections`),
createCollection: (id: string, input: CollectionInput) =>
post<Collection>(`/api/v1/workspaces/${encodeURIComponent(id)}/collections`, input),
/** The caller's journal days from from to to (YYYY-MM-DD). */
journal: (id: string, from: string, to: string) =>
request<JournalInfo>("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/journals${query({ from, to })}`),
setJournalTemplate: (id: string, template: string) =>
request<JournalInfo>("PATCH", `/api/v1/workspaces/${encodeURIComponent(id)}/journals`, { template }),
/** The caller's journal page for a day, made if there is none yet. */
openJournal: (id: string, date: string, title?: string) =>
request<Page>(
"PUT",
`/api/v1/workspaces/${encodeURIComponent(id)}/journals/${encodeURIComponent(date)}`,
title ? { title } : {},
),
},
properties: {
update: (id: string, patch: PropertyInput) =>
request<Property>("PATCH", `/api/v1/properties/${encodeURIComponent(id)}`, patch),
remove: (id: string) => request<void>("DELETE", `/api/v1/properties/${encodeURIComponent(id)}`),
},
tags: {
update: (id: string, patch: TagInput) => request<Tag>("PATCH", `/api/v1/tags/${encodeURIComponent(id)}`, patch),
remove: (id: string) => request<void>("DELETE", `/api/v1/tags/${encodeURIComponent(id)}`),
/** Moves every page of tag id to into, then deletes id. */
merge: (id: string, into: string) => post<Tag>(`/api/v1/tags/${encodeURIComponent(id)}/merge`, { into }),
},
collections: {
update: (id: string, patch: CollectionInput) =>
request<Collection>("PATCH", `/api/v1/collections/${encodeURIComponent(id)}`, patch),
remove: (id: string) => request<void>("DELETE", `/api/v1/collections/${encodeURIComponent(id)}`),
setPage: (id: string, page: string, on: boolean) =>
request<Collection>(
on ? "PUT" : "DELETE",
`/api/v1/collections/${encodeURIComponent(id)}/pages/${encodeURIComponent(page)}`,
),
},
groups: {
@@ -404,7 +477,16 @@ export function createClient(opts: ClientOptions) {
get: (id: string) => request<Page>("GET", `/api/v1/pages/${encodeURIComponent(id)}`),
update: (
id: string,
patch: { title?: string; icon?: string; isTemplate?: boolean; fullWidth?: boolean; font?: PageFont },
patch: {
title?: string;
icon?: string;
isTemplate?: boolean;
fullWidth?: boolean;
font?: PageFont;
tags?: string[];
/** Property values by property id; null clears one. */
properties?: Record<string, unknown>;
},
) => 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`),
@@ -494,7 +576,13 @@ 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 };
export type SearchFilter = {
space?: string;
tag?: string;
author?: string;
updatedAfter?: string;
updatedBefore?: string;
};
function query(params: Record<string, string | number | undefined>): string {
const qs = new URLSearchParams();
+903 -1
View File
@@ -810,7 +810,7 @@ export interface paths {
delete: operations["deletePage"];
options?: never;
head?: never;
/** Rename a page, change its icon or layout, or make it a template (editor) */
/** Rename a page, change its icon, layout, tags or properties, or make it a template (editor) */
patch: operations["updatePage"];
trace?: never;
};
@@ -1852,6 +1852,234 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/properties": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The workspace's custom page properties, in order */
get: operations["listProperties"];
put?: never;
/** Add a custom page property to the workspace (members) */
post: operations["createProperty"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/properties/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/** Remove a property; pages' values for it are ignored from then on (members) */
delete: operations["deleteProperty"];
options?: never;
head?: never;
/** Rename a property, change its type, options, visibility or place (members) */
patch: operations["updateProperty"];
trace?: never;
};
"/api/v1/workspaces/{id}/tags": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The workspace's tags by name, with how many live pages use each */
get: operations["listTags"];
put?: never;
/** Add a tag (members); names are unique in the workspace, ignoring case */
post: operations["createTag"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/tags/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/** Take a tag off every page and delete it (members) */
delete: operations["deleteTag"];
options?: never;
head?: never;
/** Rename or recolour a tag (members) */
patch: operations["updateTag"];
trace?: never;
};
"/api/v1/tags/{id}/merge": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
/** Move every page from this tag to another one, then delete this one (members) */
post: operations["mergeTag"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/docs": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/**
* All docs, the workspace's live pages the caller can open with their properties
* @description Newest change first. Archived pages, trashed pages and pages in other people's journals are left out. The query narrows the list; every part is optional.
*/
get: operations["listDocs"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/collections": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The caller's own collections and the shared ones, by name */
get: operations["listCollections"];
put?: never;
/** Save a collection (members) */
post: operations["createCollection"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/collections/{id}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/** Delete a collection; its pages stay where they are */
delete: operations["deleteCollection"];
options?: never;
head?: never;
/**
* Change a collection (its creator; workspace admins for shared ones)
* @description Only the creator can change shared.
*/
patch: operations["updateCollection"];
trace?: never;
};
"/api/v1/collections/{id}/pages/{page}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
page: string;
};
cookie?: never;
};
get?: never;
/** Add a page to the collection by hand */
put: operations["addCollectionPage"];
post?: never;
/** Take a page out of the collection, even when its rules match it */
delete: operations["removeCollectionPage"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/journals": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
/** The caller's journal days in a date range (at most a year), newest first */
get: operations["getJournal"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
/** Pick the page new journal pages are filled from (empty for none) */
patch: operations["setJournalTemplate"];
trace?: never;
};
"/api/v1/workspaces/{id}/journals/{date}": {
parameters: {
query?: never;
header?: never;
path: {
id: string;
date: string;
};
cookie?: never;
};
get?: never;
/**
* The caller's journal page for a day, made (with the journal space) if there is none yet
* @description A new page goes to the top of the journal space, newest day first, and is filled from the journal template when one is set. The journal space is private to its owner; workspace admins do not see into it.
*/
put: operations["openJournal"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/workspaces/{id}/templates": {
parameters: {
query?: never;
@@ -2341,6 +2569,8 @@ export interface components {
role: components["schemas"]["SpaceCallerRole"];
/** @description The caller cannot open the space itself and sees only pages shared with them */
limited: boolean;
/** @description A journal space: one person's daily pages, private to them */
journal: boolean;
created: string;
};
SpaceMember: {
@@ -2400,6 +2630,16 @@ export interface components {
/** @description Shown across the whole window instead of the reading column */
fullWidth: boolean;
font: components["schemas"]["PageFont"];
/** @description Tag ids */
tags: string[];
/** @description Custom property values by property id (see Property for their shapes) */
properties: {
[key: string]: unknown;
};
/** @description The day (YYYY-MM-DD) of a journal page; empty otherwise */
journalDate: string;
createdBy: components["schemas"]["PageUser"];
lastEditedBy: components["schemas"]["PageUser"];
};
/**
* @description The body font for everyone reading the page; empty is the default sans
@@ -2970,6 +3210,141 @@ export interface components {
size: number;
modified: string;
};
/**
* @description What a value looks like: text and link a string, number a number, checkbox a boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option ids, member a list of user ids.
* @enum {string}
*/
PropertyType: "text" | "number" | "checkbox" | "date" | "select" | "multi_select" | "member" | "link";
/**
* @description A colour of the editor palette, drawn from the theme; empty for none
* @enum {string}
*/
LabelColor: "" | "gray" | "red" | "orange" | "yellow" | "green" | "teal" | "blue" | "purple" | "pink";
PropertyOption: {
/** @description Empty when creating; the server picks one */
id: string;
name: string;
color: components["schemas"]["LabelColor"];
};
/**
* @description Whether the page's Info panel shows it always, only with a value, or never
* @enum {string}
*/
PropertyVisibility: "always" | "hide_empty" | "never";
Property: {
id: string;
workspace: string;
name: string;
type: components["schemas"]["PropertyType"];
options: components["schemas"]["PropertyOption"][];
visibility: components["schemas"]["PropertyVisibility"];
position: number;
};
/** @description Creating needs name and type; updating changes the fields that are set */
PropertyInput: {
name?: string;
type?: components["schemas"]["PropertyType"];
options?: components["schemas"]["PropertyOption"][];
visibility?: components["schemas"]["PropertyVisibility"];
position?: number;
};
Tag: {
id: string;
name: string;
color: components["schemas"]["LabelColor"];
/** @description Live pages with the tag */
pages: number;
};
TagInput: {
name?: string;
color?: components["schemas"]["LabelColor"];
};
DocRule: {
/** @description title, space, tags, created, updated, createdBy, lastEditedBy, template, journal, or "prop:" followed by a property id */
field: string;
/** @enum {string} */
op: "is" | "isNot" | "contains" | "notContains" | "before" | "after" | "withinDays" | "gt" | "lt" | "empty" | "notEmpty";
/** @description A string, a list of strings (any of them), a number or a boolean, as the op needs */
value?: unknown;
};
DocFilter: {
/** @enum {string} */
match: "all" | "any";
rules: components["schemas"]["DocRule"][];
};
DocItem: {
id: string;
title: string;
icon: string;
space: string;
spaceName: string;
parent: string;
created: string;
updated: string;
/** @description User id */
createdBy: string;
/** @description User id */
lastEditedBy: string;
isTemplate: boolean;
journalDate: string;
fullWidth: boolean;
tags: string[];
properties: {
[key: string]: unknown;
};
/** @description The caller's role on the page */
role: components["schemas"]["SpaceRole"];
};
DocList: {
items: components["schemas"]["DocItem"][];
/** @description Names of the people the items mention, by user id */
people: {
[key: string]: string;
};
};
Collection: {
id: string;
workspace: string;
name: string;
icon: string;
filter: components["schemas"]["DocFilter"];
/** @description Pages added by hand */
include: string[];
/** @description Pages taken out by hand */
exclude: string[];
/** @description Seen by everyone in the workspace */
shared: boolean;
creator: string;
canEdit: boolean;
updated: string;
};
/** @description Creating needs name; updating changes the fields that are set */
CollectionInput: {
name?: string;
icon?: string;
filter?: components["schemas"]["DocFilter"];
include?: string[];
exclude?: string[];
shared?: boolean;
};
JournalDay: {
/** Format: date */
date: string;
page: string;
title: string;
};
JournalInfo: {
/** @description The caller's journal space; empty until the first journal page */
space: string;
/** @description The page new journal pages are filled from; empty for none */
template: string;
days: components["schemas"]["JournalDay"][];
};
PageUser: {
id: string;
/** @description Empty when the account is gone */
name: string;
};
};
responses: {
/** @description Signed in */
@@ -4446,6 +4821,12 @@ export interface operations {
/** @description Use the whole window instead of the reading column */
fullWidth?: boolean;
font?: components["schemas"]["PageFont"];
/** @description Replaces the page's tags (tag ids) */
tags?: string[];
/** @description Sets these custom property values by property id; null clears one */
properties?: {
[key: string]: unknown;
};
};
};
};
@@ -5555,6 +5936,8 @@ export interface operations {
limit?: number;
/** @description Only pages in this space */
space?: string;
/** @description Only pages with this tag */
tag?: 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) */
@@ -6222,6 +6605,525 @@ export interface operations {
404: components["responses"]["Error"];
};
};
listProperties: {
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"]["Property"][];
};
};
404: components["responses"]["Error"];
};
};
createProperty: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["PropertyInput"];
};
};
responses: {
/** @description Created */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Property"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
deleteProperty: {
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"];
};
};
updateProperty: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["PropertyInput"];
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Property"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
listTags: {
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"]["Tag"][];
};
};
404: components["responses"]["Error"];
};
};
createTag: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["TagInput"];
};
};
responses: {
/** @description Created */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Tag"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
409: components["responses"]["Error"];
};
};
deleteTag: {
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"];
};
};
updateTag: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["TagInput"];
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Tag"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
409: components["responses"]["Error"];
};
};
mergeTag: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description The tag that stays */
into: string;
};
};
};
responses: {
/** @description The tag that stays */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Tag"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
listDocs: {
parameters: {
query?: {
/** @description Only pages in this space */
space?: string;
/** @description Only pages with this tag */
tag?: string;
/** @description Only the pages of this collection */
collection?: string;
/** @description A DocFilter as JSON */
filter?: string;
};
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["DocList"];
};
};
400: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
listCollections: {
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"]["Collection"][];
};
};
404: components["responses"]["Error"];
};
};
createCollection: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["CollectionInput"];
};
};
responses: {
/** @description Created */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Collection"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
deleteCollection: {
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"];
};
};
updateCollection: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["CollectionInput"];
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Collection"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
addCollectionPage: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
page: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Collection"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
removeCollectionPage: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
page: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Collection"];
};
};
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
getJournal: {
parameters: {
query: {
from: string;
to: string;
};
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["JournalInfo"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
setJournalTemplate: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
template: string;
};
};
};
responses: {
/** @description OK (days is empty) */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["JournalInfo"];
};
};
400: components["responses"]["Error"];
403: components["responses"]["Error"];
404: components["responses"]["Error"];
};
};
openJournal: {
parameters: {
query?: never;
header?: never;
path: {
id: string;
date: string;
};
cookie?: never;
};
requestBody?: {
content: {
"application/json": {
/** @description Title for a new page; the date when empty */
title?: 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"];
};
};
listTemplates: {
parameters: {
query?: never;
+5 -5
View File
@@ -146,7 +146,7 @@ img.ProseMirror-separator {
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(wk,this.editor.getAttributes(Tk)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new E({props:{handlePaste:(e,t)=>{if((t.clipboardData?.getData(`text/html`))?.trim())return!1;let n=t.clipboardData?.getData(`text/plain`);if(!n)return!1;let r=vk(n);if(!r)return!1;try{let t=e.state.schema.nodeFromJSON(r),n=e.state.tr.replaceSelectionWith(t);return e.dispatch(n),!0}catch{return!1}}}})]},addInputRules(){let e=(e,t)=>(!t.attrs.type||t.attrs.type===`1`)&&t.childCount+t.attrs.start===+e[1],t=Gp({find:Ek,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Gp({find:Ek,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(Tk)}),joinPredicate:e,editor:this.editor})),[t]}}),kk=/^\s*(\[([( |x])?\])\s$/,Ak=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,jk=(e,t,n)=>{var r;return(n==null||(r=n.checkboxLabel)==null?void 0:r.call(n,e,t))||`Task item checkbox for ${e.textContent||`empty task item`}`},Mk=Jp.create({name:`taskItem`,addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:`taskList`,a11y:void 0}},content(){return this.options.nested?`paragraph block*`:`paragraph+`},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-checked`);return t===``||t===`true`},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:e=>e.querySelector(`div`)??e}]},renderHTML({node:e,HTMLAttributes:t}){return[`li`,A(this.options.HTMLAttributes,t,{"data-type":this.name}),[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null}],[`span`]],[`div`,0]]},parseMarkdown:(e,t)=>{let n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode(`paragraph`,{},t.parseInline(e.tokens))):e.text?n.push(t.createNode(`paragraph`,{},[t.createNode(`text`,{text:e.text})])):n.push(t.createNode(`paragraph`,{},[])),e.nestedTokens&&e.nestedTokens.length>0){let r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode(`taskItem`,{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>op(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[kO(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{let i=document.createElement(`li`),a=document.createElement(`label`),o=document.createElement(`span`),s=document.createElement(`input`),c=document.createElement(`div`);o.style.cssText=Ak;let l=e=>{let t=jk(e,e.attrs.checked,this.options.a11y);s.setAttribute(`aria-label`,t),o.textContent=t};l(e),a.contentEditable=`false`,s.type=`checkbox`,s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`change`,t=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){s.checked=!s.checked;return}let{checked:i}=t.target;r.isEditable&&typeof n==`function`&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:e})=>{let t=n();if(typeof t!=`number`)return!1;let r=e.doc.nodeAt(t);return e.setNodeMarkup(t,void 0,{...r?.attrs,checked:i}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(s.checked=!s.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([e,t])=>{i.setAttribute(e,t)}),i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,a.append(s,o),i.append(a,c),Object.entries(t).forEach(([e,t])=>{i.setAttribute(e,t)});let u=new Set(Object.keys(t));return{dom:i,contentDOM:c,update:e=>{if(e.type!==this.type)return!1;i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,l(e);let t=r.extensionManager.attributes,n=Lu(e,t),a=new Set(Object.keys(n)),o=this.options.HTMLAttributes;return u.forEach(e=>{a.has(e)||(e in o?i.setAttribute(e,o[e]):i.removeAttribute(e))}),Object.entries(n).forEach(([e,t])=>{t==null?e in o?i.setAttribute(e,o[e]):i.removeAttribute(e):i.setAttribute(e,t)}),u=a,!0}}}},addInputRules(){return[Gp({find:kk,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),Nk=Jp.create({name:`taskList`,addOptions(){return{itemTypeName:`taskItem`,HTMLAttributes:{}}},group:`block list`,content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`uLine truncated
`):``,markdownTokenizer:{name:`taskList`,level:`block`,start(e){let t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)?.index;return t===void 0?-1:t},tokenize(e,t,n){let r=e=>{let t=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(t){let r={type:`taskList`,raw:t.raw,items:t.items},i=e.slice(t.raw.length);return i.trim()?[r,...n.blockTokens(i)]:[r]}return n.blockTokens(e)},i=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(i)return{type:`taskList`,raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Tp.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(TO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push($O.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(ck.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(Ok.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(Mk.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(Nk.configure(this.options.taskList)),e}});var Pk=`&nbsp;`,Fk=`\xA0`,Ik=Jp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,A(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{let n=e.tokens||[];if(n.length===1&&n[0].type===`image`)return t.parseChildren([n[0]]);let r=t.parseInline(n);return n.length===1&&n[0].type===`text`&&(n[0].raw===Pk||n[0].text===Pk||n[0].raw===Fk||n[0].text===Fk)&&r.length===1&&r[0].type===`text`&&(r[0].text===Pk||r[0].text===Fk)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?Pk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Lk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Rk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,zk=_p.create({name:`strike`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`s`},{tag:`del`},{tag:`strike`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`line-through`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`s`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`del`,parseMarkdown:(e,t)=>t.applyMark(`strike`,t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Hp({find:Lk,type:this.type})]},addPasteRules(){return[Yp({find:Rk,type:this.type})]}}),Bk=Jp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),Vk=_p.create({name:`underline`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`u`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`underline`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`u`,A(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||`underline`,t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`<u>${t.renderChildren(e)}</u>`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(`<u>`)},tokenize(e,t,n){if(!/^<u>/i.test(e))return;let r=/\\[\s\S]|`+|<\/u>/gi;r.lastIndex=3;let i=r.exec(e);for(;i;){if(i[0].startsWith("`")){let t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.exec(e.slice(i.index));t&&(r.lastIndex=i.index+t[0].length)}else if(!i[0].startsWith(`\\`)){let t=e.slice(3,i.index);return t?{type:`underline`,raw:e.slice(0,r.lastIndex),text:t,tokens:n.inlineTokens(t)}:void 0}i=r.exec(e)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleLine truncated
`).length:0;c!==o&&(o=c,i.textContent=Array.from({length:c},(e,t)=>t+1).join(`
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),jj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Mj(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Nj={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`],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`],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`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8 20H4v-4z`],sigma:[`M18 6V4H6l6 8lLine truncated
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),jj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Mj(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Nj={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`],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`],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`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8 20H4v-4z`],sigma:[`M18 6V4H6l6 8lLine truncated
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:oP(e)).join(`
`)}function cP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function lP(e,t){return t?e.split(t).join(`
`):e}function uP(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function dP(e,t,n={}){if(!e||!e.content||e.content.length===0)return``;let r=[];e.content.forEach(e=>{let i=[];e.content&&e.content.forEach(e=>{let r=``;r=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>lP(t.renderChildren(e),n.cellLineSeparator)).join(`
@@ -158,8 +158,8 @@ img.ProseMirror-separator {
`);if(a.length<2)return;let o=a[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes(`|`))return;let s=sP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
`).length,u=e.split(`
`).slice(0,l).join(`
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=nP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(w.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>jM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>MM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return PM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>LM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>RM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return BM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>$M(e,t),mergeCells:()=>({state:e,dispatch:t})=>UM(e,t),splitCell:()=>({state:e,dispatch:t})=>WM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>YM(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>YM(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>XM(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>UM(e,t)?!0:WM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>KM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>QM(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>QM(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&DM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=yM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:iP,"Mod-Backspace":iP,Delete:iP,"Mod-Delete":iP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[SN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],IN({allowTableNodeSelection:this.options.allowTableNodeSelection}),hP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),_P=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(gP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(qN.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(JN.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(YN.configure(this.options.tableRow)),e}}),vP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function yP(){return[Nk.configure({HTMLAttributes:{class:`dw-tasks`}}),Mk.configure({nested:!0})]}function bP(){return[_P.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var xP=vP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),SP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),CP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,wP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,TP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=wj(e.anchor,t,()=>{Oj(e.anchor,t,{placement:`bottom-start`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),cF===d&&(cF=null),n||e.onCancel?.())}let d=()=>u();return cF=d,n.focus(),e.multiline||n.select(),d}var uF=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function dF(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of uF){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function fF(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var pF=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function mF(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;lF({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(fF(t)),onCancel:()=>e(``)})})}async function hF(e,t,n,r){let i=await mF(e,t,t.blocks.embedUrl);i&&(dF(i)?e.chain().focus().insertEmbed(i).run():await _F(e,i,n,r))}async function gF(e,t,n,r){let i=await mF(e,t,t.blocks.linkUrl);i&&await _F(e,i,n,r)}async function _F(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var vF=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=fF(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=fF(e),i=dF(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${pF(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=nP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(w.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>jM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>MM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return PM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>LM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>RM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return BM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>$M(e,t),mergeCells:()=>({state:e,dispatch:t})=>UM(e,t),splitCell:()=>({state:e,dispatch:t})=>WM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>YM(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>YM(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>XM(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>UM(e,t)?!0:WM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>KM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>QM(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>QM(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&DM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=yM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:iP,"Mod-Backspace":iP,Delete:iP,"Mod-Delete":iP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[SN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],IN({allowTableNodeSelection:this.options.allowTableNodeSelection}),hP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),_P=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(gP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(qN.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(JN.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(YN.configure(this.options.tableRow)),e}}),vP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function yP(){return[Nk.configure({HTMLAttributes:{class:`dw-tasks`}}),Mk.configure({nested:!0})]}function bP(){return[_P.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var xP=vP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),SP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),CP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,wP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,TP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=wj(e.anchor,t,()=>{Oj(e.anchor,t,{placement:`bottom-start`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),cF===d&&(cF=null),n||e.onCancel?.())}let d=()=>u();return cF=d,n.focus(),e.multiline||n.select(),d}var uF=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function dF(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of uF){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function fF(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var pF=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function mF(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;lF({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(fF(t)),onCancel:()=>e(``)})})}async function hF(e,t,n,r){let i=await mF(e,t,t.blocks.embedUrl);i&&(dF(i)?e.chain().focus().insertEmbed(i).run():await _F(e,i,n,r))}async function gF(e,t,n,r){let i=await mF(e,t,t.blocks.linkUrl);i&&await _F(e,i,n,r)}async function _F(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var vF=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=fF(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=fF(e),i=dF(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${pF(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
@@ -418,9 +418,9 @@ l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(NV,t[0])&&!iL[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=NV[t[0]]+t.slice(1));var i=gV.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(iL[this.mode][t]){this.settings.strict&&this.mode===`math`&&EL.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=iL[this.mode][t].group,s=_B.range(e);a=fz(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&(mI(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:_B.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!MV[l])throw new I(`Unknown accent ' `+l+`'`,e);var u=MV[l][this.mode]||MV[l].text;if(!u)throw new I(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:_B.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};PV.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var FV=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new PV(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new I(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new vB(`\\df@tag`)])}]}return r},IV=function(e,t,n){t.textContent=``;var r=BV(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),IV=function(){throw new I(`KaTeX doesn't work in quirks mode.`)});var LV=function(e,t){return BV(e,t).toMarkup()},RV=function(e,t){return FV(e,new JF(t))},zV=function(e,t,n){if(n.throwOnError||!(e instanceof I))throw e;var r=Y([`katex-error`],[new WI(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},BV=function(e,t){var n=new JF(t);try{return ez(FV(e,n),e,n)}catch(t){return zV(t,e,n)}},VV={version:`0.18.10`,render:IV,renderToString:LV,ParseError:I,SETTINGS_SCHEMA:WF,__parse:RV,__renderToDomTree:BV,__renderToHTMLTree:function(e,t){var n=new JF(t);try{return tz(FV(e,n),e,n)}catch(t){return zV(t,e,n)}},__setFontMetrics:eL,__defineSymbol:z,__defineFunction:X,__defineMacro:$,__domTree:{Span:BI,Anchor:VI,SymbolNode:WI,SvgNode:GI,PathNode:KI,LineNode:qI}},HV=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{VV.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),UV=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},WV=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:UV,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{VV.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),GV=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[HV.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),WV.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function KV(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;lF({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return GV.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function qV(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=kf(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=RegELine truncated
`);return/\s/.test(n)}):!1}function YV(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function XV(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:YV(e)}function ZV({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!JV(r)}function QV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function $V({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function eH({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function tH({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function nH({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[Tj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(Dj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function rH(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function iH({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&rH(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=wj(c,o,()=>{Oj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function aH({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=tH({editor:e,items:n}),v=nH({placLine truncated
Idea --> Draft --> Review --> Published`,hH=null;function gH(e){return hH??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),hH}var _H=0;async function vH(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await gH(r)).render(`dw-mermaid-${++_H}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var yH=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=mH)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return vH(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;lF({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void vH(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),vH(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void vH(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),vH(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}}),bH=e=>`/p/${encodeURIComponent(e)}`,xH=/^\/p\/([A-Za-z0-9_-]+)\/?(?:[?#].*)?$/;function SH(e){return xH.exec(e)?.[1]??``}function CH(e,t,n,r=`Untitled`){let i=`${n.icon?`${n.icon} `:``}${n.title||r}`;e.chain().focus().deleteRange(t).insertContent([{type:`text`,text:i,marks:[{type:`link`,attrs:{href:bH(n.id)}}]},{type:`text`,text:` `}]).run()}async function wH(e,t,n){if(!t.create)return;let{from:r,to:i,empty:a}=e.state.selection,o=a?``:e.state.doc.textBetween(r,i,` `).trim().slice(0,200),s=await t.create(o);a||!o?CH(e,{from:r,to:r},s,n):e.chain().focus().setTextSelection({from:r,to:i}).setLink({href:bH(s.id)}).run()}var TH=Tp.create({name:`pageLinks`,addOptions(){return{host:void 0,labels:null,onNavigate:void 0}},addProseMirrorPlugins(){let{host:e,onNavigate:t}=this.options,n=this.options.labels,r=[];return e&&r.push(cH({editor:this.editor,pluginKey:new D(`pageLinks`),char:`[[`,allowSpaces:!0,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:async({query:t})=>(await e.search(t).catch(()=>[])).slice(0,8),render:Ij({label:n.pageLinks,empty:n.noPages,toItem:e=>({label:`${e.icon?`${e.icon} `:``}${e.title||`…`}`,description:e.hint,icon:`page`}),pick:(e,t)=>CH(e.editor,e.range,t)})})),t&&r.push(new E({key:new D(`pageLinkClicks`),props:{handleClick:(e,n,r)=>{let i=(r.target?.closest?.(`a[href]`))?.getAttribute(`href`)??``;return!SH(i)||e.editable&&!(r.ctrlKey||r.metaKey)?!1:(r.preventDefault(),t(i),!0)}}})),r}});function EH(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function DH(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`]Line truncated
Idea --> Draft --> Review --> Published`,hH=null;function gH(e){return hH??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),hH}var _H=0;async function vH(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await gH(r)).render(`dw-mermaid-${++_H}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var yH=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=mH)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return vH(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;lF({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void vH(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),vH(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void vH(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),vH(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}}),bH=e=>`/p/${encodeURIComponent(e)}`,xH=/^\/p\/([A-Za-z0-9_-]+)\/?(?:[?#].*)?$/;function SH(e){return xH.exec(e)?.[1]??``}function CH(e,t,n,r=`Untitled`){let i=`${n.icon?`${n.icon} `:``}${n.title||r}`;e.chain().focus().deleteRange(t).insertContent([{type:`text`,text:i,marks:[{type:`link`,attrs:{href:bH(n.id)}}]},{type:`text`,text:` `}]).run()}async function wH(e,t,n){if(!t.create)return;let{from:r,to:i,empty:a}=e.state.selection,o=a?``:e.state.doc.textBetween(r,i,` `).trim().slice(0,200),s=await t.create(o);a||!o?CH(e,{from:r,to:r},s,n):e.chain().focus().setTextSelection({from:r,to:i}).setLink({href:bH(s.id)}).run()}var TH=Tp.create({name:`pageLinks`,addOptions(){return{host:void 0,labels:null,onNavigate:void 0}},addProseMirrorPlugins(){let{host:e,onNavigate:t}=this.options,n=this.options.labels,r=[];return e&&r.push(cH({editor:this.editor,pluginKey:new D(`pageLinks`),char:`[[`,allowSpaces:!0,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:async({query:t})=>(await e.search(t).catch(()=>[])).slice(0,8),render:Ij({label:n.pageLinks,empty:n.noPages,toItem:e=>({label:`${e.icon?`${e.icon} `:``}${e.title||`…`}`,description:e.hint,icon:`page`}),pick:(e,t)=>CH(e.editor,e.range,t)})})),t&&r.push(new E({key:new D(`pageLinkClicks`),props:{handleClick:(e,n,r)=>{let i=(r.target?.closest?.(`a[href]`))?.getAttribute(`href`)??``;return!SH(i)||e.editable&&!(r.ctrlKey||r.metaKey)?!1:(r.preventDefault(),t(i),!0)}}})),r}});function EH(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function DH(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`]Line truncated
<style rel="stylesheet" crossorigin>/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--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;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--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-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);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.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-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-Line truncated
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--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;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--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-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);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.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-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-Line truncated
/*$vite$:1*/</style>
</head>
<body>
+3
View File
@@ -40,6 +40,8 @@ const props = withDefaults(
canComment?: boolean;
/** Whether code blocks show line numbers unless one was switched on or off itself. */
codeLineNumbers?: boolean;
/** Dates in the text open that day's journal (navigate to /journal/<date>). */
journals?: boolean;
}>(),
{ editable: true },
);
@@ -78,6 +80,7 @@ const editor = useEditor({
loadPdf: () => import("./pdfjs").then((m) => m.pdf),
codeLineNumbers: props.codeLineNumbers,
onNavigate: (path) => emit("navigate", path),
onOpenDate: props.journals ? (date) => emit("navigate", `/journal/${date}`) : undefined,
labels: props.labels,
onCommentSelect: (id) => emit("comment-select", id),
onError: (e) => emit("error", e),
+28 -4
View File
@@ -122,6 +122,8 @@ export interface DateMentionOptions {
labels: EditorLabels;
/** The signed-in person's id; without one dates cannot get reminders. */
me: () => string | undefined;
/** Opens the date's journal page; without it dates open nothing. */
onOpen?: (date: string) => void;
}
/**
@@ -138,7 +140,7 @@ export const DateMention = Node.create<DateMentionOptions>({
selectable: true,
addOptions() {
return { labels: undefined as unknown as EditorLabels, me: () => undefined };
return { labels: undefined as unknown as EditorLabels, me: () => undefined, onOpen: undefined };
},
addAttributes() {
@@ -178,13 +180,14 @@ export const DateMention = Node.create<DateMentionOptions>({
},
addNodeView() {
const { labels, me } = this.options;
const { labels, me, onOpen } = this.options;
return ({ node: initial, editor, getPos }) => {
let node = initial;
const dom = document.createElement("span");
dom.dataset.type = "date";
dom.className = "dw-date";
dom.contentEditable = "false";
dom.classList.toggle("is-link", !!onOpen);
let closePopover: (() => void) | null = null;
const draw = () => {
@@ -214,9 +217,17 @@ export const DateMention = Node.create<DateMentionOptions>({
};
dom.addEventListener("mousedown", (e) => {
if (!editor.isEditable || closePopover) return;
if (closePopover) return;
if (!editor.isEditable) {
// Reading: a date opens that day's journal.
if (onOpen && parseIso(node.attrs.date as string)) {
e.preventDefault();
onOpen(node.attrs.date as string);
}
return;
}
e.preventDefault();
closePopover = openPopover(dom, editor, node, labels, me(), set, () => (closePopover = null));
closePopover = openPopover(dom, editor, node, labels, me(), set, () => (closePopover = null), onOpen);
});
return {
@@ -267,6 +278,7 @@ function openPopover(
me: string | undefined,
set: (patch: Record<string, string>) => void,
onClose: () => void,
onOpen?: (date: string) => void,
): () => void {
const w = labels.dates;
const box = document.createElement("div");
@@ -303,6 +315,18 @@ function openPopover(
hint.textContent = w.reminderAt;
box.append(label, hint);
}
if (onOpen) {
const open = document.createElement("button");
open.type = "button";
open.className = "dw-date-pop__open";
open.textContent = w.openJournal ?? "Open journal";
open.addEventListener("click", () => {
const date = node.attrs.date as string;
close();
if (parseIso(date)) onOpen(date);
});
box.append(open);
}
document.body.append(box);
const stop = autoUpdate(anchor, box, () => {
+17 -1
View File
@@ -188,9 +188,25 @@
color: var(--color-ink-muted);
text-decoration: line-through;
}
.dw-prose[contenteditable="true"] .dw-date {
.dw-prose[contenteditable="true"] .dw-date,
.dw-prose .dw-date.is-link {
cursor: pointer;
}
.dw-prose[contenteditable="false"] .dw-date.is-link:hover {
text-decoration: underline;
}
.dw-date-pop__open {
align-self: flex-start;
border: 0;
background: none;
padding: 0;
font: inherit;
color: var(--color-accent);
cursor: pointer;
}
.dw-date-pop__open:hover {
text-decoration: underline;
}
.dw-date-pop {
position: fixed;
z-index: 60;
+3 -1
View File
@@ -54,6 +54,8 @@ export interface ExtensionOptions {
onBlockLinkCopied?: (url: string) => void;
/** Opens an app route, e.g. "/p/<id>" when a page link is followed. */
onNavigate?: (path: string) => void;
/** Opens a date's journal page (clicking a date mention); hosts without journals leave it out. */
onOpenDate?: (date: string) => void;
/** The Draw.io embed address (default https://embed.diagrams.net). */
drawioUrl?: string;
/** Loads Mermaid; without it diagrams show as their text. */
@@ -114,7 +116,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
Callout.configure({ labels }),
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
DateMention.configure({ labels, me: () => opts.mentions?.me }),
DateMention.configure({ labels, me: () => opts.mentions?.me, onOpen: opts.onOpenDate }),
SlashMenu.configure({
commands: slashCommands(labels, opts.files, opts.onError, opts.pages, !!opts.loadExcalidraw, opts.links),
labels,
+3
View File
@@ -131,6 +131,8 @@ export interface EditorLabels {
reminderAt: string;
someoneElse: string;
edit: string;
/** The button that opens the date's journal page, where the host has journals. */
openJournal?: string;
};
}
@@ -288,5 +290,6 @@ export const englishLabels: EditorLabels = {
reminderAt: "Reminder at 9:00 on the day",
someoneElse: "Someone else set a reminder on this date.",
edit: "Change date",
openJournal: "Open journal",
},
};
+8
View File
@@ -118,6 +118,14 @@ export const iconPaths = {
"M14.5 7.5h.01",
],
"page-plus": ["M6 3h8l4 4v14H6z", "M14 3v4h4", "M12 11v6", "M9 14h6"],
// Properties, tags, collections and journals.
tag: ["M4 4h7l9 9-7 7-9-9z", "M8 8h.01"],
grid: ["M4 4h7v7H4z", "M13 4h7v7h-7z", "M4 13h7v7H4z", "M13 13h7v7h-7z"],
cards: ["M4 5h16v6H4z", "M4 15h16v4H4z"],
filter: ["M4 5h16l-6 8v6l-4-2v-4z"],
layers: ["M12 4l8 4-8 4-8-4z", "M4 12l8 4 8-4", "M4 16l8 4 8-4"],
journal: ["M6 3h11a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H6z", "M9 3v18", "M12 8h3", "M12 12h3"],
sliders: ["M5 6h14", "M5 12h14", "M5 18h14", "M9 4v4", "M15 10v4", "M11 16v4"],
} as const;
export type IconName = keyof typeof iconPaths;
+654
View File
@@ -487,6 +487,7 @@ class Space {
required this.defaultRole,
required this.role,
required this.limited,
required this.journal,
required this.created,
});
@@ -501,6 +502,7 @@ class Space {
defaultRole: SpaceDefaultRole.fromJson(json['defaultRole'] as String),
role: SpaceCallerRole.fromJson(json['role'] as String),
limited: json['limited'] as bool,
journal: json['journal'] as bool,
created: json['created'] as String,
);
@@ -525,6 +527,9 @@ class Space {
/// The caller cannot open the space itself and sees only pages shared with them
final bool limited;
/// A journal space: one person's daily pages, private to them
final bool journal;
final String created;
Map<String, dynamic> toJson() => {
@@ -538,6 +543,7 @@ class Space {
'defaultRole': defaultRole.toJson(),
'role': role.toJson(),
'limited': limited,
'journal': journal,
'created': created,
};
}
@@ -672,6 +678,11 @@ class Page {
required this.pinnedAt,
required this.fullWidth,
required this.font,
required this.tags,
required this.properties,
required this.journalDate,
required this.createdBy,
required this.lastEditedBy,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
@@ -697,6 +708,13 @@ class Page {
pinnedAt: json['pinnedAt'] as String,
fullWidth: json['fullWidth'] as bool,
font: PageFont.fromJson(json['font'] as String),
tags: (json['tags'] as List).map((e) => e as String).toList(),
properties: json['properties'] as Map<String, dynamic>,
journalDate: json['journalDate'] as String,
createdBy: PageUser.fromJson(json['createdBy'] as Map<String, dynamic>),
lastEditedBy: PageUser.fromJson(
json['lastEditedBy'] as Map<String, dynamic>,
),
);
final String id;
@@ -750,6 +768,19 @@ class Page {
final PageFont font;
/// Tag ids
final List<String> tags;
/// Custom property values by property id (see Property for their shapes)
final Map<String, dynamic> properties;
/// The day (YYYY-MM-DD) of a journal page; empty otherwise
final String journalDate;
final PageUser createdBy;
final PageUser lastEditedBy;
Map<String, dynamic> toJson() => {
'id': id,
'workspace': workspace,
@@ -771,6 +802,11 @@ class Page {
'pinnedAt': pinnedAt,
'fullWidth': fullWidth,
'font': font.toJson(),
'tags': tags.map((e) => e).toList(),
'properties': properties,
'journalDate': journalDate,
'createdBy': createdBy.toJson(),
'lastEditedBy': lastEditedBy.toJson(),
};
}
@@ -3424,3 +3460,621 @@ class Backup {
'modified': modified,
};
}
/// What a value looks like: text and link a string, number a number, checkbox a boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option ids, member a list of user ids.
enum PropertyType {
text('text'),
number('number'),
checkbox('checkbox'),
date('date'),
select('select'),
multiSelect('multi_select'),
member('member'),
link('link');
const PropertyType(this.value);
final String value;
static PropertyType fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown PropertyType', value),
);
String toJson() => value;
}
/// A colour of the editor palette, drawn from the theme; empty for none
enum LabelColor {
none(''),
gray('gray'),
red('red'),
orange('orange'),
yellow('yellow'),
green('green'),
teal('teal'),
blue('blue'),
purple('purple'),
pink('pink');
const LabelColor(this.value);
final String value;
static LabelColor fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown LabelColor', value),
);
String toJson() => value;
}
class PropertyOption {
const PropertyOption({
required this.id,
required this.name,
required this.color,
});
factory PropertyOption.fromJson(Map<String, dynamic> json) => PropertyOption(
id: json['id'] as String,
name: json['name'] as String,
color: LabelColor.fromJson(json['color'] as String),
);
/// Empty when creating; the server picks one
final String id;
final String name;
final LabelColor color;
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'color': color.toJson(),
};
}
/// Whether the page's Info panel shows it always, only with a value, or never
enum PropertyVisibility {
always('always'),
hideEmpty('hide_empty'),
never('never');
const PropertyVisibility(this.value);
final String value;
static PropertyVisibility fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown PropertyVisibility', value),
);
String toJson() => value;
}
class Property {
const Property({
required this.id,
required this.workspace,
required this.name,
required this.type,
required this.options,
required this.visibility,
required this.position,
});
factory Property.fromJson(Map<String, dynamic> json) => Property(
id: json['id'] as String,
workspace: json['workspace'] as String,
name: json['name'] as String,
type: PropertyType.fromJson(json['type'] as String),
options: (json['options'] as List)
.map((e) => PropertyOption.fromJson(e as Map<String, dynamic>))
.toList(),
visibility: PropertyVisibility.fromJson(json['visibility'] as String),
position: (json['position'] as num).toDouble(),
);
final String id;
final String workspace;
final String name;
final PropertyType type;
final List<PropertyOption> options;
final PropertyVisibility visibility;
final double position;
Map<String, dynamic> toJson() => {
'id': id,
'workspace': workspace,
'name': name,
'type': type.toJson(),
'options': options.map((e) => e.toJson()).toList(),
'visibility': visibility.toJson(),
'position': position,
};
}
/// Creating needs name and type; updating changes the fields that are set
class PropertyInput {
const PropertyInput({
this.name,
this.type,
this.options,
this.visibility,
this.position,
});
factory PropertyInput.fromJson(Map<String, dynamic> json) => PropertyInput(
name: json['name'] == null ? null : json['name'] as String,
type: json['type'] == null
? null
: PropertyType.fromJson(json['type'] as String),
options: json['options'] == null
? null
: (json['options'] as List)
.map((e) => PropertyOption.fromJson(e as Map<String, dynamic>))
.toList(),
visibility: json['visibility'] == null
? null
: PropertyVisibility.fromJson(json['visibility'] as String),
position: json['position'] == null
? null
: (json['position'] as num).toDouble(),
);
final String? name;
final PropertyType? type;
final List<PropertyOption>? options;
final PropertyVisibility? visibility;
final double? position;
Map<String, dynamic> toJson() => {
'name': ?name,
'type': ?type?.toJson(),
'options': ?options?.map((e) => e.toJson()).toList(),
'visibility': ?visibility?.toJson(),
'position': ?position,
};
}
class Tag {
const Tag({
required this.id,
required this.name,
required this.color,
required this.pages,
});
factory Tag.fromJson(Map<String, dynamic> json) => Tag(
id: json['id'] as String,
name: json['name'] as String,
color: LabelColor.fromJson(json['color'] as String),
pages: (json['pages'] as num).toInt(),
);
final String id;
final String name;
final LabelColor color;
/// Live pages with the tag
final int pages;
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'color': color.toJson(),
'pages': pages,
};
}
class TagInput {
const TagInput({this.name, this.color});
factory TagInput.fromJson(Map<String, dynamic> json) => TagInput(
name: json['name'] == null ? null : json['name'] as String,
color: json['color'] == null
? null
: LabelColor.fromJson(json['color'] as String),
);
final String? name;
final LabelColor? color;
Map<String, dynamic> toJson() => {'name': ?name, 'color': ?color?.toJson()};
}
enum DocRuleOp {
is_('is'),
isNot('isNot'),
contains('contains'),
notContains('notContains'),
before('before'),
after('after'),
withinDays('withinDays'),
gt('gt'),
lt('lt'),
empty('empty'),
notEmpty('notEmpty');
const DocRuleOp(this.value);
final String value;
static DocRuleOp fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown DocRuleOp', value),
);
String toJson() => value;
}
class DocRule {
const DocRule({required this.field, required this.op, this.value});
factory DocRule.fromJson(Map<String, dynamic> json) => DocRule(
field: json['field'] as String,
op: DocRuleOp.fromJson(json['op'] as String),
value: json['value'] == null ? null : json['value'] as Object,
);
/// title, space, tags, created, updated, createdBy, lastEditedBy, template, journal, or "prop:" followed by a property id
final String field;
final DocRuleOp op;
/// A string, a list of strings (any of them), a number or a boolean, as the op needs
final Object? value;
Map<String, dynamic> toJson() => {
'field': field,
'op': op.toJson(),
'value': ?value,
};
}
enum DocFilterMatch {
all('all'),
any('any');
const DocFilterMatch(this.value);
final String value;
static DocFilterMatch fromJson(String value) => values.firstWhere(
(e) => e.value == value,
orElse: () => throw FormatException('unknown DocFilterMatch', value),
);
String toJson() => value;
}
class DocFilter {
const DocFilter({required this.match, required this.rules});
factory DocFilter.fromJson(Map<String, dynamic> json) => DocFilter(
match: DocFilterMatch.fromJson(json['match'] as String),
rules: (json['rules'] as List)
.map((e) => DocRule.fromJson(e as Map<String, dynamic>))
.toList(),
);
final DocFilterMatch match;
final List<DocRule> rules;
Map<String, dynamic> toJson() => {
'match': match.toJson(),
'rules': rules.map((e) => e.toJson()).toList(),
};
}
class DocItem {
const DocItem({
required this.id,
required this.title,
required this.icon,
required this.space,
required this.spaceName,
required this.parent,
required this.created,
required this.updated,
required this.createdBy,
required this.lastEditedBy,
required this.isTemplate,
required this.journalDate,
required this.fullWidth,
required this.tags,
required this.properties,
required this.role,
});
factory DocItem.fromJson(Map<String, dynamic> json) => DocItem(
id: json['id'] as String,
title: json['title'] as String,
icon: json['icon'] as String,
space: json['space'] as String,
spaceName: json['spaceName'] as String,
parent: json['parent'] as String,
created: json['created'] as String,
updated: json['updated'] as String,
createdBy: json['createdBy'] as String,
lastEditedBy: json['lastEditedBy'] as String,
isTemplate: json['isTemplate'] as bool,
journalDate: json['journalDate'] as String,
fullWidth: json['fullWidth'] as bool,
tags: (json['tags'] as List).map((e) => e as String).toList(),
properties: json['properties'] as Map<String, dynamic>,
role: SpaceRole.fromJson(json['role'] as String),
);
final String id;
final String title;
final String icon;
final String space;
final String spaceName;
final String parent;
final String created;
final String updated;
/// User id
final String createdBy;
/// User id
final String lastEditedBy;
final bool isTemplate;
final String journalDate;
final bool fullWidth;
final List<String> tags;
final Map<String, dynamic> properties;
/// The caller's role on the page
final SpaceRole role;
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'icon': icon,
'space': space,
'spaceName': spaceName,
'parent': parent,
'created': created,
'updated': updated,
'createdBy': createdBy,
'lastEditedBy': lastEditedBy,
'isTemplate': isTemplate,
'journalDate': journalDate,
'fullWidth': fullWidth,
'tags': tags.map((e) => e).toList(),
'properties': properties,
'role': role.toJson(),
};
}
class DocList {
const DocList({required this.items, required this.people});
factory DocList.fromJson(Map<String, dynamic> json) => DocList(
items: (json['items'] as List)
.map((e) => DocItem.fromJson(e as Map<String, dynamic>))
.toList(),
people: (json['people'] as Map<String, dynamic>).map(
(k, e) => MapEntry(k, e as String),
),
);
final List<DocItem> items;
/// Names of the people the items mention, by user id
final Map<String, String> people;
Map<String, dynamic> toJson() => {
'items': items.map((e) => e.toJson()).toList(),
'people': people,
};
}
class Collection {
const Collection({
required this.id,
required this.workspace,
required this.name,
required this.icon,
required this.filter,
required this.include,
required this.exclude,
required this.shared,
required this.creator,
required this.canEdit,
required this.updated,
});
factory Collection.fromJson(Map<String, dynamic> json) => Collection(
id: json['id'] as String,
workspace: json['workspace'] as String,
name: json['name'] as String,
icon: json['icon'] as String,
filter: DocFilter.fromJson(json['filter'] as Map<String, dynamic>),
include: (json['include'] as List).map((e) => e as String).toList(),
exclude: (json['exclude'] as List).map((e) => e as String).toList(),
shared: json['shared'] as bool,
creator: json['creator'] as String,
canEdit: json['canEdit'] as bool,
updated: json['updated'] as String,
);
final String id;
final String workspace;
final String name;
final String icon;
final DocFilter filter;
/// Pages added by hand
final List<String> include;
/// Pages taken out by hand
final List<String> exclude;
/// Seen by everyone in the workspace
final bool shared;
final String creator;
final bool canEdit;
final String updated;
Map<String, dynamic> toJson() => {
'id': id,
'workspace': workspace,
'name': name,
'icon': icon,
'filter': filter.toJson(),
'include': include.map((e) => e).toList(),
'exclude': exclude.map((e) => e).toList(),
'shared': shared,
'creator': creator,
'canEdit': canEdit,
'updated': updated,
};
}
/// Creating needs name; updating changes the fields that are set
class CollectionInput {
const CollectionInput({
this.name,
this.icon,
this.filter,
this.include,
this.exclude,
this.shared,
});
factory CollectionInput.fromJson(Map<String, dynamic> json) =>
CollectionInput(
name: json['name'] == null ? null : json['name'] as String,
icon: json['icon'] == null ? null : json['icon'] as String,
filter: json['filter'] == null
? null
: DocFilter.fromJson(json['filter'] as Map<String, dynamic>),
include: json['include'] == null
? null
: (json['include'] as List).map((e) => e as String).toList(),
exclude: json['exclude'] == null
? null
: (json['exclude'] as List).map((e) => e as String).toList(),
shared: json['shared'] == null ? null : json['shared'] as bool,
);
final String? name;
final String? icon;
final DocFilter? filter;
final List<String>? include;
final List<String>? exclude;
final bool? shared;
Map<String, dynamic> toJson() => {
'name': ?name,
'icon': ?icon,
'filter': ?filter?.toJson(),
'include': ?include?.map((e) => e).toList(),
'exclude': ?exclude?.map((e) => e).toList(),
'shared': ?shared,
};
}
class JournalDay {
const JournalDay({
required this.date,
required this.page,
required this.title,
});
factory JournalDay.fromJson(Map<String, dynamic> json) => JournalDay(
date: json['date'] as String,
page: json['page'] as String,
title: json['title'] as String,
);
final String date;
final String page;
final String title;
Map<String, dynamic> toJson() => {'date': date, 'page': page, 'title': title};
}
class JournalInfo {
const JournalInfo({
required this.space,
required this.template,
required this.days,
});
factory JournalInfo.fromJson(Map<String, dynamic> json) => JournalInfo(
space: json['space'] as String,
template: json['template'] as String,
days: (json['days'] as List)
.map((e) => JournalDay.fromJson(e as Map<String, dynamic>))
.toList(),
);
/// The caller's journal space; empty until the first journal page
final String space;
/// The page new journal pages are filled from; empty for none
final String template;
final List<JournalDay> days;
Map<String, dynamic> toJson() => {
'space': space,
'template': template,
'days': days.map((e) => e.toJson()).toList(),
};
}
class PageUser {
const PageUser({required this.id, required this.name});
factory PageUser.fromJson(Map<String, dynamic> json) =>
PageUser(id: json['id'] as String, name: json['name'] as String);
final String id;
/// Empty when the account is gone
final String name;
Map<String, dynamic> toJson() => {'id': id, 'name': name};
}
+3
View File
@@ -263,6 +263,9 @@ class _Generator {
);
}
switch (s['type']) {
// No type at all: any JSON value (DocRule.value).
case null:
return _Type('Object', (v) => '$v as Object', (v) => v);
case 'string':
return _Type('String', (v) => '$v as String', (v) => v);
case 'integer':
+54
View File
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package access
import "docwell/server/internal/apperr"
// Properties, tags and collections organize a workspace's pages. Anyone who
// works in the workspace (members and above) may shape them; guests, who see
// only pages shared with them, may only read them.
// OrganizeWorkspace allows adding, renaming and removing a workspace's page
// properties and tags, and making collections.
func OrganizeWorkspace(wsRole string) error {
switch {
case wsRole == "":
return apperr.NotFound("workspace not found")
case !AtLeast(wsRole, WorkspaceMember):
return apperr.Forbidden("guests cannot change the workspace's properties, tags or collections")
}
return nil
}
// EditCollection allows changing or deleting a collection: its creator may,
// and workspace admins may change shared ones.
func EditCollection(callerID, wsRole, creator string, shared bool) error {
if err := OrganizeWorkspace(wsRole); err != nil {
return err
}
if callerID == creator || (shared && AtLeast(wsRole, WorkspaceAdmin)) {
return nil
}
return apperr.Forbidden("only the collection's creator can change it")
}
// KeepJournal allows having a journal in a workspace (members and above).
func KeepJournal(wsRole string) error { return OrganizeWorkspace(wsRole) }
// JournalSpaceRole is the caller's role in someone's journal space. It belongs
// to its owner: workspace admins get no role from the cascade, so it stays
// out of their sidebar and search. A role given in the space itself (the
// owner's, or someone the owner added) still counts, and pages shared from it
// are reached through page grants as usual.
func JournalSpaceRole(wsRole, owner, callerID, memberRole string) string {
switch {
case wsRole == "":
return ""
case ValidSpaceRole(memberRole):
return memberRole
case owner == callerID:
// The owner is the space's admin even if their membership row is gone.
return SpaceAdmin
}
return ""
}
+50
View File
@@ -0,0 +1,50 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package access
import (
"testing"
"docwell/server/internal/apperr"
)
func TestOrganizeActions(t *testing.T) {
cases := []struct {
name string
err error
want apperr.Kind
}{
{"outsider", OrganizeWorkspace(""), notFound},
{"guest reads only", OrganizeWorkspace(WorkspaceGuest), forbidden},
{"member organizes", OrganizeWorkspace(WorkspaceMember), ok},
{"creator edits own collection", EditCollection("u1", WorkspaceMember, "u1", false), ok},
{"member cannot edit someone else's", EditCollection("u2", WorkspaceMember, "u1", true), forbidden},
{"admin edits shared collection", EditCollection("u2", WorkspaceAdmin, "u1", true), ok},
{"admin cannot edit private collection", EditCollection("u2", WorkspaceAdmin, "u1", false), forbidden},
{"guest cannot keep a journal", KeepJournal(WorkspaceGuest), forbidden},
}
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 TestJournalSpaceRole(t *testing.T) {
cases := []struct {
name string
ws, owner, caller, role string
want string
}{
{"owner", WorkspaceMember, "u1", "u1", SpaceAdmin, SpaceAdmin},
{"owner without membership row", WorkspaceMember, "u1", "u1", "", SpaceAdmin},
{"workspace admin gets nothing", WorkspaceOwner, "u1", "u2", "", ""},
{"someone the owner added", WorkspaceMember, "u1", "u2", SpaceViewer, SpaceViewer},
{"owner who left the workspace", "", "u1", "u1", SpaceAdmin, ""},
}
for _, c := range cases {
if got := JournalSpaceRole(c.ws, c.owner, c.caller, c.role); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
+439 -11
View File
@@ -45,6 +45,69 @@ func (e ApiTokenScope) Valid() bool {
}
}
// Defines values for DocFilterMatch.
const (
All DocFilterMatch = "all"
Any DocFilterMatch = "any"
)
// Valid indicates whether the value is a known member of the DocFilterMatch enum.
func (e DocFilterMatch) Valid() bool {
switch e {
case All:
return true
case Any:
return true
default:
return false
}
}
// Defines values for DocRuleOp.
const (
DocRuleOpAfter DocRuleOp = "after"
DocRuleOpBefore DocRuleOp = "before"
DocRuleOpContains DocRuleOp = "contains"
DocRuleOpEmpty DocRuleOp = "empty"
DocRuleOpGt DocRuleOp = "gt"
DocRuleOpIs DocRuleOp = "is"
DocRuleOpIsNot DocRuleOp = "isNot"
DocRuleOpLt DocRuleOp = "lt"
DocRuleOpNotContains DocRuleOp = "notContains"
DocRuleOpNotEmpty DocRuleOp = "notEmpty"
DocRuleOpWithinDays DocRuleOp = "withinDays"
)
// Valid indicates whether the value is a known member of the DocRuleOp enum.
func (e DocRuleOp) Valid() bool {
switch e {
case DocRuleOpAfter:
return true
case DocRuleOpBefore:
return true
case DocRuleOpContains:
return true
case DocRuleOpEmpty:
return true
case DocRuleOpGt:
return true
case DocRuleOpIs:
return true
case DocRuleOpIsNot:
return true
case DocRuleOpLt:
return true
case DocRuleOpNotContains:
return true
case DocRuleOpNotEmpty:
return true
case DocRuleOpWithinDays:
return true
default:
return false
}
}
// Defines values for InviteStatus.
const (
InviteStatusAdded InviteStatus = "added"
@@ -66,6 +129,48 @@ func (e InviteStatus) Valid() bool {
}
}
// Defines values for LabelColor.
const (
LabelColorBlue LabelColor = "blue"
LabelColorEmpty LabelColor = ""
LabelColorGray LabelColor = "gray"
LabelColorGreen LabelColor = "green"
LabelColorOrange LabelColor = "orange"
LabelColorPink LabelColor = "pink"
LabelColorPurple LabelColor = "purple"
LabelColorRed LabelColor = "red"
LabelColorTeal LabelColor = "teal"
LabelColorYellow LabelColor = "yellow"
)
// Valid indicates whether the value is a known member of the LabelColor enum.
func (e LabelColor) Valid() bool {
switch e {
case LabelColorBlue:
return true
case LabelColorEmpty:
return true
case LabelColorGray:
return true
case LabelColorGreen:
return true
case LabelColorOrange:
return true
case LabelColorPink:
return true
case LabelColorPurple:
return true
case LabelColorRed:
return true
case LabelColorTeal:
return true
case LabelColorYellow:
return true
default:
return false
}
}
// Defines values for NewApiTokenScope.
const (
NewApiTokenScopeRead NewApiTokenScope = "read"
@@ -216,6 +321,63 @@ func (e PageGrantRole) Valid() bool {
}
}
// Defines values for PropertyType.
const (
PropertyTypeCheckbox PropertyType = "checkbox"
PropertyTypeDate PropertyType = "date"
PropertyTypeLink PropertyType = "link"
PropertyTypeMember PropertyType = "member"
PropertyTypeMultiSelect PropertyType = "multi_select"
PropertyTypeNumber PropertyType = "number"
PropertyTypeSelect PropertyType = "select"
PropertyTypeText PropertyType = "text"
)
// Valid indicates whether the value is a known member of the PropertyType enum.
func (e PropertyType) Valid() bool {
switch e {
case PropertyTypeCheckbox:
return true
case PropertyTypeDate:
return true
case PropertyTypeLink:
return true
case PropertyTypeMember:
return true
case PropertyTypeMultiSelect:
return true
case PropertyTypeNumber:
return true
case PropertyTypeSelect:
return true
case PropertyTypeText:
return true
default:
return false
}
}
// Defines values for PropertyVisibility.
const (
Always PropertyVisibility = "always"
HideEmpty PropertyVisibility = "hide_empty"
Never PropertyVisibility = "never"
)
// Valid indicates whether the value is a known member of the PropertyVisibility enum.
func (e PropertyVisibility) Valid() bool {
switch e {
case Always:
return true
case HideEmpty:
return true
case Never:
return true
default:
return false
}
}
// Defines values for Role.
const (
RoleAdmin Role = "admin"
@@ -700,6 +862,37 @@ type BrandingSettings struct {
Logo string `json:"logo"`
}
// Collection defines model for Collection.
type Collection struct {
CanEdit bool `json:"canEdit"`
Creator string `json:"creator"`
// Exclude Pages taken out by hand
Exclude []string `json:"exclude"`
Filter DocFilter `json:"filter"`
Icon string `json:"icon"`
Id string `json:"id"`
// Include Pages added by hand
Include []string `json:"include"`
Name string `json:"name"`
// Shared Seen by everyone in the workspace
Shared bool `json:"shared"`
Updated string `json:"updated"`
Workspace string `json:"workspace"`
}
// CollectionInput Creating needs name; updating changes the fields that are set
type CollectionInput struct {
Exclude *[]string `json:"exclude,omitempty"`
Filter *DocFilter `json:"filter,omitempty"`
Icon *string `json:"icon,omitempty"`
Include *[]string `json:"include,omitempty"`
Name *string `json:"name,omitempty"`
Shared *bool `json:"shared,omitempty"`
}
// Comment defines model for Comment.
type Comment struct {
// Anchor As sent when the comment was created; null when there was none
@@ -758,6 +951,62 @@ type CreateUserRequest struct {
Role *Role `json:"role,omitempty"`
}
// DocFilter defines model for DocFilter.
type DocFilter struct {
Match DocFilterMatch `json:"match"`
Rules []DocRule `json:"rules"`
}
// DocFilterMatch defines model for DocFilter.Match.
type DocFilterMatch string
// DocItem defines model for DocItem.
type DocItem struct {
Created string `json:"created"`
// CreatedBy User id
CreatedBy string `json:"createdBy"`
FullWidth bool `json:"fullWidth"`
Icon string `json:"icon"`
Id string `json:"id"`
IsTemplate bool `json:"isTemplate"`
JournalDate string `json:"journalDate"`
// LastEditedBy User id
LastEditedBy string `json:"lastEditedBy"`
Parent string `json:"parent"`
Properties map[string]interface{} `json:"properties"`
// Role The caller's role on the page
Role SpaceRole `json:"role"`
Space string `json:"space"`
SpaceName string `json:"spaceName"`
Tags []string `json:"tags"`
Title string `json:"title"`
Updated string `json:"updated"`
}
// DocList defines model for DocList.
type DocList struct {
Items []DocItem `json:"items"`
// People Names of the people the items mention, by user id
People map[string]string `json:"people"`
}
// DocRule defines model for DocRule.
type DocRule struct {
// Field title, space, tags, created, updated, createdBy, lastEditedBy, template, journal, or "prop:" followed by a property id
Field string `json:"field"`
Op DocRuleOp `json:"op"`
// Value A string, a list of strings (any of them), a number or a boolean, as the op needs
Value interface{} `json:"value,omitempty"`
}
// DocRuleOp defines model for DocRule.Op.
type DocRuleOp string
// EmailRequest defines model for EmailRequest.
type EmailRequest struct {
Email openapi_types.Email `json:"email"`
@@ -878,6 +1127,27 @@ type Job struct {
Runs int `json:"runs"`
}
// JournalDay defines model for JournalDay.
type JournalDay struct {
Date openapi_types.Date `json:"date"`
Page string `json:"page"`
Title string `json:"title"`
}
// JournalInfo defines model for JournalInfo.
type JournalInfo struct {
Days []JournalDay `json:"days"`
// Space The caller's journal space; empty until the first journal page
Space string `json:"space"`
// Template The page new journal pages are filled from; empty for none
Template string `json:"template"`
}
// LabelColor A colour of the editor palette, drawn from the theme; empty for none
type LabelColor string
// LinkPreview defines model for LinkPreview.
type LinkPreview struct {
Description string `json:"description"`
@@ -1016,8 +1286,9 @@ type Page struct {
Archived bool `json:"archived"`
// ArchivedAt When the page itself was archived; empty otherwise
ArchivedAt string `json:"archivedAt"`
Created string `json:"created"`
ArchivedAt string `json:"archivedAt"`
Created string `json:"created"`
CreatedBy PageUser `json:"createdBy"`
// DeletedAt When the page itself was trashed; empty otherwise
DeletedAt string `json:"deletedAt"`
@@ -1037,21 +1308,31 @@ type Page struct {
InTrash bool `json:"inTrash"`
// IsTemplate Offered as a template for new pages
IsTemplate bool `json:"isTemplate"`
Parent string `json:"parent"`
IsTemplate bool `json:"isTemplate"`
// JournalDate The day (YYYY-MM-DD) of a journal page; empty otherwise
JournalDate string `json:"journalDate"`
LastEditedBy PageUser `json:"lastEditedBy"`
Parent string `json:"parent"`
// PinnedAt When the page was pinned to its space's home; empty if not
PinnedAt string `json:"pinnedAt"`
// Properties Custom property values by property id (see Property for their shapes)
Properties map[string]interface{} `json:"properties"`
// Restricted The page or one of its ancestors is restricted
Restricted bool `json:"restricted"`
// Role The caller's role on this page
Role SpaceRole `json:"role"`
Space string `json:"space"`
Title string `json:"title"`
Updated string `json:"updated"`
Workspace string `json:"workspace"`
Role SpaceRole `json:"role"`
Space string `json:"space"`
// Tags Tag ids
Tags []string `json:"tags"`
Title string `json:"title"`
Updated string `json:"updated"`
Workspace string `json:"workspace"`
}
// PageAccess defines model for PageAccess.
@@ -1151,6 +1432,14 @@ type PageRef struct {
Title string `json:"title"`
}
// PageUser defines model for PageUser.
type PageUser struct {
Id string `json:"id"`
// Name Empty when the account is gone
Name string `json:"name"`
}
// PageVersion defines model for PageVersion.
type PageVersion struct {
// Author Name (or email) of the last person who edited before it was taken
@@ -1169,6 +1458,50 @@ type PinnedPage struct {
Updated string `json:"updated"`
}
// Property defines model for Property.
type Property struct {
Id string `json:"id"`
Name string `json:"name"`
Options []PropertyOption `json:"options"`
Position float32 `json:"position"`
// Type What a value looks like: text and link a string, number a number, checkbox a boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option ids, member a list of user ids.
Type PropertyType `json:"type"`
// Visibility Whether the page's Info panel shows it always, only with a value, or never
Visibility PropertyVisibility `json:"visibility"`
Workspace string `json:"workspace"`
}
// PropertyInput Creating needs name and type; updating changes the fields that are set
type PropertyInput struct {
Name *string `json:"name,omitempty"`
Options *[]PropertyOption `json:"options,omitempty"`
Position *float32 `json:"position,omitempty"`
// Type What a value looks like: text and link a string, number a number, checkbox a boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option ids, member a list of user ids.
Type *PropertyType `json:"type,omitempty"`
// Visibility Whether the page's Info panel shows it always, only with a value, or never
Visibility *PropertyVisibility `json:"visibility,omitempty"`
}
// PropertyOption defines model for PropertyOption.
type PropertyOption struct {
// Color A colour of the editor palette, drawn from the theme; empty for none
Color LabelColor `json:"color"`
// Id Empty when creating; the server picks one
Id string `json:"id"`
Name string `json:"name"`
}
// PropertyType What a value looks like: text and link a string, number a number, checkbox a boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option ids, member a list of user ids.
type PropertyType string
// PropertyVisibility Whether the page's Info panel shows it always, only with a value, or never
type PropertyVisibility string
// PublicSettings defines model for PublicSettings.
type PublicSettings struct {
// AccentColor #rrggbb, or empty for the default
@@ -1303,6 +1636,9 @@ type Space struct {
Icon string `json:"icon"`
Id string `json:"id"`
// Journal A journal space: one person's daily pages, private to them
Journal bool `json:"journal"`
// Limited The caller cannot open the space itself and sees only pages shared with them
Limited bool `json:"limited"`
Name string `json:"name"`
@@ -1372,6 +1708,24 @@ type StorageSettings struct {
SecretSet *bool `json:"secretSet,omitempty"`
}
// Tag defines model for Tag.
type Tag struct {
// Color A colour of the editor palette, drawn from the theme; empty for none
Color LabelColor `json:"color"`
Id string `json:"id"`
Name string `json:"name"`
// Pages Live pages with the tag
Pages int `json:"pages"`
}
// TagInput defines model for TagInput.
type TagInput struct {
// Color A colour of the editor palette, drawn from the theme; empty for none
Color *LabelColor `json:"color,omitempty"`
Name *string `json:"name,omitempty"`
}
// Template defines model for Template.
type Template struct {
Icon string `json:"icon"`
@@ -1704,8 +2058,14 @@ type UpdatePageJSONBody struct {
Icon *string `json:"icon,omitempty"`
// IsTemplate Offer the page as a template for new pages
IsTemplate *bool `json:"isTemplate,omitempty"`
Title *string `json:"title,omitempty"`
IsTemplate *bool `json:"isTemplate,omitempty"`
// Properties Sets these custom property values by property id; null clears one
Properties *map[string]interface{} `json:"properties,omitempty"`
// Tags Replaces the page's tags (tag ids)
Tags *[]string `json:"tags,omitempty"`
Title *string `json:"title,omitempty"`
}
// SetPageRestrictedJSONBody defines parameters for SetPageRestricted.
@@ -1829,6 +2189,12 @@ type CreatePageJSONBody struct {
Title *string `json:"title,omitempty"`
}
// MergeTagJSONBody defines parameters for MergeTag.
type MergeTagJSONBody struct {
// Into The tag that stays
Into string `json:"into"`
}
// ListUsersParams defines parameters for ListUsers.
type ListUsersParams struct {
Page *int `form:"page,omitempty" json:"page,omitempty"`
@@ -1847,6 +2213,38 @@ type CreateWorkspaceJSONBody struct {
Organization *string `json:"organization,omitempty"`
}
// ListDocsParams defines parameters for ListDocs.
type ListDocsParams struct {
// Space Only pages in this space
Space *string `form:"space,omitempty" json:"space,omitempty"`
// Tag Only pages with this tag
Tag *string `form:"tag,omitempty" json:"tag,omitempty"`
// Collection Only the pages of this collection
Collection *string `form:"collection,omitempty" json:"collection,omitempty"`
// Filter A DocFilter as JSON
Filter *string `form:"filter,omitempty" json:"filter,omitempty"`
}
// GetJournalParams defines parameters for GetJournal.
type GetJournalParams struct {
From openapi_types.Date `form:"from" json:"from"`
To openapi_types.Date `form:"to" json:"to"`
}
// SetJournalTemplateJSONBody defines parameters for SetJournalTemplate.
type SetJournalTemplateJSONBody struct {
Template string `json:"template"`
}
// OpenJournalJSONBody defines parameters for OpenJournal.
type OpenJournalJSONBody struct {
// Title Title for a new page; the date when empty
Title *string `json:"title,omitempty"`
}
// SetWorkspaceMemberJSONBody defines parameters for SetWorkspaceMember.
type SetWorkspaceMemberJSONBody struct {
Email openapi_types.Email `json:"email"`
@@ -1872,6 +2270,9 @@ type SearchPagesParams struct {
// Space Only pages in this space
Space *string `form:"space,omitempty" json:"space,omitempty"`
// Tag Only pages with this tag
Tag *string `form:"tag,omitempty" json:"tag,omitempty"`
// Author Only pages this user created or last edited
Author *string `form:"author,omitempty" json:"author,omitempty"`
@@ -1934,6 +2335,9 @@ type ConfirmVerificationJSONRequestBody ConfirmVerificationJSONBody
// RequestVerificationJSONRequestBody defines body for RequestVerification for application/json ContentType.
type RequestVerificationJSONRequestBody = EmailRequest
// UpdateCollectionJSONRequestBody defines body for UpdateCollection for application/json ContentType.
type UpdateCollectionJSONRequestBody = CollectionInput
// UpdateCommentJSONRequestBody defines body for UpdateComment for application/json ContentType.
type UpdateCommentJSONRequestBody UpdateCommentJSONBody
@@ -2009,6 +2413,9 @@ type SetShareLinkJSONRequestBody SetShareLinkJSONBody
// SetPageWatchJSONRequestBody defines body for SetPageWatch for application/json ContentType.
type SetPageWatchJSONRequestBody = WatchState
// UpdatePropertyJSONRequestBody defines body for UpdateProperty for application/json ContentType.
type UpdatePropertyJSONRequestBody = PropertyInput
// UpdateSpaceJSONRequestBody defines body for UpdateSpace for application/json ContentType.
type UpdateSpaceJSONRequestBody UpdateSpaceJSONBody
@@ -2024,6 +2431,12 @@ type SetSpaceMemberJSONRequestBody SetSpaceMemberJSONBody
// CreatePageJSONRequestBody defines body for CreatePage for application/json ContentType.
type CreatePageJSONRequestBody CreatePageJSONBody
// UpdateTagJSONRequestBody defines body for UpdateTag for application/json ContentType.
type UpdateTagJSONRequestBody = TagInput
// MergeTagJSONRequestBody defines body for MergeTag for application/json ContentType.
type MergeTagJSONRequestBody MergeTagJSONBody
// CreateUserJSONRequestBody defines body for CreateUser for application/json ContentType.
type CreateUserJSONRequestBody = CreateUserRequest
@@ -2039,14 +2452,29 @@ type CreateWorkspaceJSONRequestBody CreateWorkspaceJSONBody
// RenameWorkspaceJSONRequestBody defines body for RenameWorkspace for application/json ContentType.
type RenameWorkspaceJSONRequestBody = NameRequest
// CreateCollectionJSONRequestBody defines body for CreateCollection for application/json ContentType.
type CreateCollectionJSONRequestBody = CollectionInput
// CreateGroupJSONRequestBody defines body for CreateGroup for application/json ContentType.
type CreateGroupJSONRequestBody = GroupRequest
// SetJournalTemplateJSONRequestBody defines body for SetJournalTemplate for application/json ContentType.
type SetJournalTemplateJSONRequestBody SetJournalTemplateJSONBody
// OpenJournalJSONRequestBody defines body for OpenJournal for application/json ContentType.
type OpenJournalJSONRequestBody OpenJournalJSONBody
// SetWorkspaceMemberJSONRequestBody defines body for SetWorkspaceMember for application/json ContentType.
type SetWorkspaceMemberJSONRequestBody SetWorkspaceMemberJSONBody
// CreatePropertyJSONRequestBody defines body for CreateProperty for application/json ContentType.
type CreatePropertyJSONRequestBody = PropertyInput
// CreateSpaceJSONRequestBody defines body for CreateSpace for application/json ContentType.
type CreateSpaceJSONRequestBody CreateSpaceJSONBody
// CreateTagJSONRequestBody defines body for CreateTag for application/json ContentType.
type CreateTagJSONRequestBody = TagInput
// CreateWebhookJSONRequestBody defines body for CreateWebhook for application/json ContentType.
type CreateWebhookJSONRequestBody = WebhookInput
+280
View File
@@ -0,0 +1,280 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"fmt"
"slices"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Collections -----------------------------------------------------------
//
// A collection is a saved view of pages: the pages its rules match, plus
// pages added by hand (include), minus pages taken out by hand (exclude). It
// is its creator's own, or shared with everyone in the workspace. Listing a
// collection's pages still shows only pages the caller can open.
const maxCollectionPages = 2000
// Collection is a saved view of pages in a workspace.
type Collection struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Icon string `json:"icon"`
Filter DocFilter `json:"filter"`
Include []string `json:"include"`
Exclude []string `json:"exclude"`
Shared bool `json:"shared"`
Creator string `json:"creator"`
// CanEdit is whether the caller may change or delete it.
CanEdit bool `json:"canEdit"`
Updated string `json:"updated"`
}
type collectionRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Creator string `json:"creator"`
Name string `json:"name"`
Icon string `json:"icon"`
Filter DocFilter `json:"filter"`
Include []string `json:"include"`
Exclude []string `json:"exclude"`
Shared bool `json:"shared"`
Updated string `json:"updated"`
}
func (r collectionRecord) view(c access.Caller, wsRole string) Collection {
f := r.Filter
if f.Rules == nil {
f.Rules = []DocRule{}
}
if f.Match == "" {
f.Match = "all"
}
return Collection{
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Icon: r.Icon, Filter: f,
Include: nonNil(r.Include), Exclude: nonNil(r.Exclude), Shared: r.Shared, Creator: r.Creator,
CanEdit: access.EditCollection(c.ID, wsRole, r.Creator, r.Shared) == nil, Updated: r.Updated,
}
}
// contains reports whether a page belongs in the collection. A collection
// without rules holds only the pages added to it.
func (r collectionRecord) contains(d DocItem, defs map[string]propertyRecord, now time.Time) bool {
if slices.Contains(r.Exclude, d.ID) {
return false
}
if slices.Contains(r.Include, d.ID) {
return true
}
return len(r.Filter.Rules) > 0 && r.Filter.matches(d, defs, now)
}
// visibleTo reports whether c may see the collection at all.
func (r collectionRecord) visibleTo(c access.Caller) bool { return r.Shared || r.Creator == c.ID }
// ListCollections lists the caller's own collections and the shared ones, by name.
func (s *Service) ListCollections(ctx context.Context, c access.Caller, wsID string) ([]Collection, error) {
ws, role, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return nil, err
}
rows, err := listAll[collectionRecord](ctx, s, "page_collections", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s' && (shared = true || creator = '%s')", ws.ID, c.ID),
})
if err != nil {
return nil, err
}
out := make([]Collection, 0, len(rows))
for _, r := range rows {
out = append(out, r.view(c, role))
}
sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
return out, nil
}
// CollectionInput creates a collection, or changes the fields that are set.
type CollectionInput struct {
Name *string `json:"name"`
Icon *string `json:"icon"`
Filter *DocFilter `json:"filter"`
Include *[]string `json:"include"`
Exclude *[]string `json:"exclude"`
Shared *bool `json:"shared"`
}
func collectionPatch(in CollectionInput) (map[string]any, error) {
patch := map[string]any{}
if in.Name != nil {
name, err := cleanName(*in.Name, "Collection")
if err != nil {
return nil, err
}
patch["name"] = name
}
if in.Icon != nil {
icon := strings.TrimSpace(*in.Icon)
if len(icon) > 32 {
return nil, apperr.InvalidFields(map[string]string{"icon": "Icon is too long."})
}
patch["icon"] = icon
}
if in.Filter != nil {
f := *in.Filter
if err := f.check(); err != nil {
return nil, err
}
if f.Match == "" {
f.Match = "all"
}
if f.Rules == nil {
f.Rules = []DocRule{}
}
patch["filter"] = f
}
for key, list := range map[string]*[]string{"include": in.Include, "exclude": in.Exclude} {
if list == nil {
continue
}
if len(*list) > maxCollectionPages {
return nil, apperr.InvalidFields(map[string]string{key: "At most 2000 pages."})
}
ids := []string{}
for _, id := range *list {
if !validID(id) {
return nil, apperr.InvalidFields(map[string]string{key: "Invalid page id."})
}
if !slices.Contains(ids, id) {
ids = append(ids, id)
}
}
patch[key] = ids
}
if in.Shared != nil {
patch["shared"] = *in.Shared
}
return patch, nil
}
// CreateCollection saves a new collection (members).
func (s *Service) CreateCollection(ctx context.Context, c access.Caller, wsID string, in CollectionInput) (Collection, error) {
ws, role, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return Collection{}, err
}
if err := access.OrganizeWorkspace(role); err != nil {
return Collection{}, err
}
if in.Name == nil {
return Collection{}, apperr.InvalidFields(map[string]string{"name": "Collection name is required."})
}
body, err := collectionPatch(in)
if err != nil {
return Collection{}, err
}
body["workspace"], body["creator"] = ws.ID, c.ID
for key, empty := range map[string]any{"filter": DocFilter{Match: "all", Rules: []DocRule{}}, "include": []string{}, "exclude": []string{}} {
if _, ok := body[key]; !ok {
body[key] = empty
}
}
rec, err := pocketbase.Create[collectionRecord](ctx, s.pb, "page_collections", body)
if err != nil {
return Collection{}, mapPB(err, "collection not found")
}
return rec.view(c, role), nil
}
// collectionFor loads a collection c may see.
func (s *Service) collectionFor(ctx context.Context, c access.Caller, id string) (collectionRecord, error) {
rec, _, err := s.collectionAccess(ctx, c, id)
return rec, err
}
func (s *Service) collectionAccess(ctx context.Context, c access.Caller, id string) (collectionRecord, string, error) {
if !validID(id) {
return collectionRecord{}, "", apperr.NotFound("collection not found")
}
rec, err := pocketbase.Get[collectionRecord](ctx, s.pb, "page_collections", id)
if err != nil {
return rec, "", mapPB(err, "collection not found")
}
_, role, err := s.workspaceFor(ctx, c, rec.Workspace)
if err != nil || !rec.visibleTo(c) {
return collectionRecord{}, "", apperr.NotFound("collection not found")
}
return rec, role, nil
}
// UpdateCollection changes a collection (its creator; workspace admins for shared ones).
func (s *Service) UpdateCollection(ctx context.Context, c access.Caller, id string, in CollectionInput) (Collection, error) {
rec, role, err := s.collectionAccess(ctx, c, id)
if err != nil {
return Collection{}, err
}
if err := access.EditCollection(c.ID, role, rec.Creator, rec.Shared); err != nil {
return Collection{}, err
}
// Only the creator decides who sees it.
if in.Shared != nil && *in.Shared != rec.Shared && c.ID != rec.Creator {
return Collection{}, apperr.Forbidden("only the collection's creator can change who sees it")
}
patch, err := collectionPatch(in)
if err != nil {
return Collection{}, err
}
if len(patch) > 0 {
if rec, err = pocketbase.Update[collectionRecord](ctx, s.pb, "page_collections", rec.ID, patch); err != nil {
return Collection{}, mapPB(err, "collection not found")
}
}
return rec.view(c, role), nil
}
// DeleteCollection deletes a collection; its pages stay where they are.
func (s *Service) DeleteCollection(ctx context.Context, c access.Caller, id string) error {
rec, role, err := s.collectionAccess(ctx, c, id)
if err != nil {
return err
}
if err := access.EditCollection(c.ID, role, rec.Creator, rec.Shared); err != nil {
return err
}
return mapPB(s.pb.Delete(ctx, "page_collections", rec.ID), "collection not found")
}
// SetCollectionPage adds a page to a collection by hand, or takes it out.
func (s *Service) SetCollectionPage(ctx context.Context, c access.Caller, id, pageID string, in bool) (Collection, error) {
rec, role, err := s.collectionAccess(ctx, c, id)
if err != nil {
return Collection{}, err
}
if err := access.EditCollection(c.ID, role, rec.Creator, rec.Shared); err != nil {
return Collection{}, err
}
p, _, err := s.pageFor(ctx, c, pageID)
if err != nil {
return Collection{}, err
}
if p.Workspace != rec.Workspace {
return Collection{}, apperr.Invalid("the page is in another workspace")
}
include, exclude := slices.DeleteFunc(rec.Include, func(x string) bool { return x == p.ID }),
slices.DeleteFunc(rec.Exclude, func(x string) bool { return x == p.ID })
if in {
include = append(include, p.ID)
} else {
exclude = append(exclude, p.ID)
}
return s.UpdateCollection(ctx, c, rec.ID, CollectionInput{Include: &include, Exclude: &exclude})
}
+493
View File
@@ -0,0 +1,493 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"encoding/json"
"fmt"
"slices"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- All docs --------------------------------------------------------------
//
// The All docs view lists a workspace's live pages the caller can open, with
// their properties, so the apps can group, order and lay them out. It can be
// narrowed to one space, one tag, a collection, or filter rules; the rules
// are the same ones collections save.
// DocItem is one page in the All docs list.
type DocItem struct {
ID string `json:"id"`
Title string `json:"title"`
Icon string `json:"icon"`
Space string `json:"space"`
SpaceName string `json:"spaceName"`
Parent string `json:"parent"`
Created string `json:"created"`
Updated string `json:"updated"`
CreatedBy string `json:"createdBy"`
LastEditedBy string `json:"lastEditedBy"`
IsTemplate bool `json:"isTemplate"`
JournalDate string `json:"journalDate"`
FullWidth bool `json:"fullWidth"`
Tags []string `json:"tags"`
Properties map[string]json.RawMessage `json:"properties"`
// Role is the caller's role on the page, for bulk actions.
Role string `json:"role"`
}
// DocList is the All docs result; People names everyone it mentions (as
// creator, last editor or in a member property).
type DocList struct {
Items []DocItem `json:"items"`
People map[string]string `json:"people"`
}
// DocFilter is a set of rules; Match is "all" (the default) or "any".
type DocFilter struct {
Match string `json:"match"`
Rules []DocRule `json:"rules"`
}
// DocRule tests one field of a page. Field is a built-in (title, space,
// tags, created, updated, createdBy, lastEditedBy, template, journal) or
// "prop:<property id>". Op is one of is, isNot, contains, notContains,
// before, after, withinDays, gt, lt, empty, notEmpty; Value is a string, a
// list of strings, a number or a boolean as the op needs.
type DocRule struct {
Field string `json:"field"`
Op string `json:"op"`
Value json.RawMessage `json:"value"`
}
const maxRules = 50
var ruleOps = []string{"is", "isNot", "contains", "notContains", "before", "after", "withinDays", "gt", "lt", "empty", "notEmpty"}
// check rejects rules that could never be understood.
func (f DocFilter) check() error {
if f.Match != "" && f.Match != "all" && f.Match != "any" {
return apperr.InvalidFields(map[string]string{"filter": "match must be all or any."})
}
if len(f.Rules) > maxRules {
return apperr.InvalidFields(map[string]string{"filter": "At most 50 rules."})
}
for _, r := range f.Rules {
if !slices.Contains(ruleOps, r.Op) {
return apperr.InvalidFields(map[string]string{"filter": "Unknown rule op " + r.Op + "."})
}
switch r.Field {
case "title", "space", "tags", "created", "updated", "createdBy", "lastEditedBy", "template", "journal":
default:
if !strings.HasPrefix(r.Field, "prop:") {
return apperr.InvalidFields(map[string]string{"filter": "Unknown rule field " + r.Field + "."})
}
}
}
return nil
}
// fieldValue is a page field reduced to what rules compare.
type fieldValue struct {
kind string // text, list, date, number, bool
text string // text, or a date as YYYY-MM-DD
list []string
num *float64
b bool
}
func (v fieldValue) empty() bool {
switch v.kind {
case "list":
return len(v.list) == 0
case "number":
return v.num == nil
case "bool":
return !v.b
}
return v.text == ""
}
// value reads one field of d; defs are the workspace's properties by id.
func (d DocItem) value(field string, defs map[string]propertyRecord) (fieldValue, bool) {
day := func(ts string) string {
if len(ts) >= 10 {
return ts[:10]
}
return ""
}
one := func(s string) []string {
if s == "" {
return nil
}
return []string{s}
}
switch field {
case "title":
return fieldValue{kind: "text", text: d.Title}, true
case "space":
return fieldValue{kind: "list", list: one(d.Space)}, true
case "tags":
return fieldValue{kind: "list", list: d.Tags}, true
case "created":
return fieldValue{kind: "date", text: day(d.Created)}, true
case "updated":
return fieldValue{kind: "date", text: day(d.Updated)}, true
case "createdBy":
return fieldValue{kind: "list", list: one(d.CreatedBy)}, true
case "lastEditedBy":
return fieldValue{kind: "list", list: one(d.LastEditedBy)}, true
case "template":
return fieldValue{kind: "bool", b: d.IsTemplate}, true
case "journal":
return fieldValue{kind: "date", text: d.JournalDate}, true
}
def, ok := defs[strings.TrimPrefix(field, "prop:")]
if !ok {
return fieldValue{}, false
}
raw := d.Properties[def.ID]
switch def.Type {
case PropNumber:
var n float64
if json.Unmarshal(raw, &n) == nil && len(raw) > 0 {
return fieldValue{kind: "number", num: &n}, true
}
return fieldValue{kind: "number"}, true
case PropCheckbox:
var b bool
_ = json.Unmarshal(raw, &b)
return fieldValue{kind: "bool", b: b}, true
case PropDate:
var s string
_ = json.Unmarshal(raw, &s)
return fieldValue{kind: "date", text: s}, true
case PropSelect:
var s string
_ = json.Unmarshal(raw, &s)
return fieldValue{kind: "list", list: one(s)}, true
case PropMultiSelect, PropMember:
var l []string
_ = json.Unmarshal(raw, &l)
return fieldValue{kind: "list", list: l}, true
}
var s string
_ = json.Unmarshal(raw, &s)
return fieldValue{kind: "text", text: s}, true
}
// ruleStrings reads a rule value as a list of strings (a single string counts).
func ruleStrings(raw json.RawMessage) []string {
var list []string
if json.Unmarshal(raw, &list) == nil {
return list
}
var s string
if json.Unmarshal(raw, &s) == nil && s != "" {
return []string{s}
}
return nil
}
func ruleString(raw json.RawMessage) string {
if l := ruleStrings(raw); len(l) > 0 {
return l[0]
}
return ""
}
// test reports whether d passes the rule. A rule on a property that no
// longer exists passes, so deleting a property does not empty collections,
// and so does a rule with nothing picked yet.
func (r DocRule) test(d DocItem, defs map[string]propertyRecord, now time.Time) bool {
v, ok := d.value(r.Field, defs)
if !ok {
return true
}
switch r.Op {
case "empty":
return v.empty()
case "notEmpty":
return !v.empty()
}
switch v.kind {
case "text":
want := strings.ToLower(strings.TrimSpace(ruleString(r.Value)))
have := strings.ToLower(v.text)
switch r.Op {
case "is":
return have == want
case "isNot":
return have != want
case "contains":
return strings.Contains(have, want)
case "notContains":
return !strings.Contains(have, want)
}
case "list":
want := ruleStrings(r.Value)
if len(want) == 0 {
// A rule still being written (nothing picked yet) narrows nothing.
return true
}
hit := slices.ContainsFunc(want, func(w string) bool { return slices.Contains(v.list, w) })
switch r.Op {
case "is", "contains":
return hit
case "isNot", "notContains":
return !hit
}
case "bool":
var want bool
if json.Unmarshal(r.Value, &want) != nil {
want = true
}
switch r.Op {
case "is":
return v.b == want
case "isNot":
return v.b != want
}
case "number":
var want float64
if v.num == nil || json.Unmarshal(r.Value, &want) != nil {
return false
}
switch r.Op {
case "is":
return *v.num == want
case "isNot":
return *v.num != want
case "gt":
return *v.num > want
case "lt":
return *v.num < want
}
case "date":
if v.text == "" {
return false
}
if r.Op == "withinDays" {
var days float64
if json.Unmarshal(r.Value, &days) != nil || days < 0 {
return false
}
from := now.AddDate(0, 0, -int(days)).Format(time.DateOnly)
return v.text >= from && v.text <= now.Format(time.DateOnly)
}
want := ruleString(r.Value)
if want == "" {
return true
}
switch r.Op {
case "is":
return v.text == want
case "isNot":
return v.text != want
case "before":
return v.text < want
case "after":
return v.text > want
}
}
return false
}
// matches reports whether d passes the filter; no rules match everything.
func (f DocFilter) matches(d DocItem, defs map[string]propertyRecord, now time.Time) bool {
if len(f.Rules) == 0 {
return true
}
anyOf := f.Match == "any"
for _, r := range f.Rules {
ok := r.test(d, defs, now)
if anyOf && ok {
return true
}
if !anyOf && !ok {
return false
}
}
return !anyOf
}
// DocQuery narrows the All docs list; every part is optional.
type DocQuery struct {
Space string
Tag string
Collection string
Filter *DocFilter
}
// workspaceDocs loads every live, unarchived page of the workspace that c
// can open, with the spaces' names. Pages in journal spaces of other people
// are left out like the spaces themselves.
func (s *Service) workspaceDocs(ctx context.Context, c access.Caller, wsID string) ([]DocItem, error) {
spaces, err := s.ListSpaces(ctx, c, wsID)
if err != nil {
return nil, err
}
rules := map[string]pageRules{}
names := map[string]string{}
for _, sp := range spaces {
_, r, err := s.spaceRules(ctx, c, sp.ID)
if err != nil {
return nil, err
}
rules[sp.ID], names[sp.ID] = r, sp.Name
}
all, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", wsID), Fields: pageDetailFields,
})
if err != nil {
return nil, err
}
trees := map[string]tree{}
for _, p := range all {
t, ok := trees[p.Space]
if !ok {
t = tree{byID: map[string]pageRecord{}}
trees[p.Space] = t
}
t.byID[p.ID] = p
}
out := []DocItem{}
for _, p := range all {
r, ok := rules[p.Space]
if !ok {
continue
}
t := trees[p.Space]
if !t.live(p.ID) || t.archived(p.ID) {
continue
}
role := r.role(p.ID)
if role == "" {
continue
}
props := p.Properties
if props == nil {
props = map[string]json.RawMessage{}
}
out = append(out, DocItem{
ID: p.ID, Title: p.Title, Icon: p.Icon, Space: p.Space, SpaceName: names[p.Space], Parent: p.Parent,
Created: p.Created, Updated: p.Updated, CreatedBy: p.Creator, LastEditedBy: p.LastEditor,
IsTemplate: p.IsTemplate, JournalDate: p.JournalDate, FullWidth: p.FullWidth,
Tags: nonNil(p.Tags), Properties: props, Role: role,
})
}
sort.Slice(out, func(i, j int) bool {
if out[i].Updated != out[j].Updated {
return out[i].Updated > out[j].Updated
}
return out[i].ID < out[j].ID
})
return out, nil
}
// ListDocs lists the pages of a workspace c can open, newest change first.
func (s *Service) ListDocs(ctx context.Context, c access.Caller, wsID string, q DocQuery) (DocList, error) {
ws, _, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return DocList{}, err
}
if q.Filter != nil {
if err := q.Filter.check(); err != nil {
return DocList{}, err
}
}
var col *collectionRecord
if q.Collection != "" {
rec, err := s.collectionFor(ctx, c, q.Collection)
if err != nil {
return DocList{}, err
}
if rec.Workspace != ws.ID {
return DocList{}, apperr.NotFound("collection not found")
}
col = &rec
}
docs, err := s.workspaceDocs(ctx, c, ws.ID)
if err != nil {
return DocList{}, err
}
defsList, err := s.workspaceProperties(ctx, ws.ID)
if err != nil {
return DocList{}, err
}
defs := make(map[string]propertyRecord, len(defsList))
for _, d := range defsList {
defs[d.ID] = d
}
now := time.Now().UTC()
items := []DocItem{}
for _, d := range docs {
if q.Space != "" && d.Space != q.Space {
continue
}
if q.Tag != "" && !slices.Contains(d.Tags, q.Tag) {
continue
}
if col != nil && !col.contains(d, defs, now) {
continue
}
if q.Filter != nil && !q.Filter.matches(d, defs, now) {
continue
}
items = append(items, d)
}
return DocList{Items: items, People: s.peopleOf(ctx, items, defs)}, nil
}
// peopleOf names the people the items mention (best effort).
func (s *Service) peopleOf(ctx context.Context, items []DocItem, defs map[string]propertyRecord) map[string]string {
ids := map[string]bool{}
for _, d := range items {
ids[d.CreatedBy], ids[d.LastEditedBy] = true, true
for id, raw := range d.Properties {
if def, ok := defs[id]; ok && def.Type == PropMember {
var l []string
_ = json.Unmarshal(raw, &l)
for _, u := range l {
ids[u] = true
}
}
}
}
delete(ids, "")
out := map[string]string{}
list := make([]string, 0, len(ids))
for id := range ids {
if validID(id) {
list = append(list, id)
}
}
sort.Strings(list)
// One query per 50 people keeps the filter short.
for start := 0; start < len(list); start += 50 {
chunk := list[start:min(start+50, len(list))]
parts := make([]string, len(chunk))
for i, id := range chunk {
parts[i] = fmt.Sprintf("id = '%s'", id)
}
res, err := pocketbase.List[struct {
ID string `json:"id"`
Name string `json:"name"`
}](ctx, s.pb, "users", pocketbase.ListOptions{PerPage: 50, Filter: strings.Join(parts, " || "), Fields: "id,name"})
if err != nil {
continue
}
for _, u := range res.Items {
out[u.ID] = u.Name
}
}
return out
}
+183
View File
@@ -0,0 +1,183 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"encoding/json"
"slices"
"testing"
"time"
)
var (
statusProp = propertyRecord{ID: "status", Type: PropSelect, Options: []PropertyOption{{ID: "todo", Name: "To do"}, {ID: "done", Name: "Done"}}}
labelsProp = propertyRecord{ID: "labels", Type: PropMultiSelect, Options: []PropertyOption{{ID: "a", Name: "A"}, {ID: "b", Name: "B"}}}
scoreProp = propertyRecord{ID: "score", Type: PropNumber}
dueProp = propertyRecord{ID: "due", Type: PropDate}
doneProp = propertyRecord{ID: "done", Type: PropCheckbox}
linkProp = propertyRecord{ID: "site", Type: PropLink}
testDefs = map[string]propertyRecord{"status": statusProp, "labels": labelsProp, "score": scoreProp, "due": dueProp, "done": doneProp, "site": linkProp}
)
func TestCleanValue(t *testing.T) {
cases := []struct {
def propertyRecord
in string
want string // "" = cleared
wantErr bool
}{
{statusProp, `"done"`, `"done"`, false},
{statusProp, `"nope"`, "", true},
{statusProp, `""`, "", false},
{labelsProp, `["a","b","a"]`, `["a","b"]`, false},
{labelsProp, `["c"]`, "", true},
{labelsProp, `[]`, "", false},
{scoreProp, `4.5`, `4.5`, false},
{scoreProp, `"4"`, "", true},
{dueProp, `"2026-11-14"`, `"2026-11-14"`, false},
{dueProp, `"14/11/2026"`, "", true},
{doneProp, `false`, `false`, false},
{linkProp, `"https://docwell.app"`, `"https://docwell.app"`, false},
{linkProp, `"javascript:alert(1)"`, "", true},
{propertyRecord{Type: PropText}, `" hi "`, `"hi"`, false},
{propertyRecord{Type: PropMember}, `["u1","bad id"]`, "", true},
{scoreProp, `null`, "", false},
}
for _, c := range cases {
got, err := cleanValue(c.def, json.RawMessage(c.in))
if (err != nil) != c.wantErr {
t.Errorf("%s %s: err = %v", c.def.Type, c.in, err)
continue
}
if string(got) != c.want {
t.Errorf("%s %s = %s, want %s", c.def.Type, c.in, got, c.want)
}
}
}
func TestCleanOptionsKeepsIDsAndAddsNew(t *testing.T) {
got, err := cleanOptions([]PropertyOption{{ID: "x1", Name: " One ", Color: "red"}, {Name: "Two"}, {ID: "x1", Name: "dup"}})
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0].ID != "x1" || got[0].Name != "One" || got[1].ID == "" || got[1].ID == "x1" {
t.Errorf("options = %+v", got)
}
if _, err := cleanOptions([]PropertyOption{{Name: "x", Color: "chartreuse"}}); err == nil {
t.Error("unknown colour accepted")
}
}
func rule(field, op string, value any) DocRule {
b, _ := json.Marshal(value)
return DocRule{Field: field, Op: op, Value: b}
}
func TestDocFilter(t *testing.T) {
now := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC)
doc := DocItem{
ID: "p1", Title: "Quarterly Plan", Space: "s1", Tags: []string{"t1", "t2"},
Created: "2026-11-01 08:00:00.000Z", Updated: "2026-11-13 08:00:00.000Z", CreatedBy: "u1",
Properties: map[string]json.RawMessage{
"status": json.RawMessage(`"todo"`), "labels": json.RawMessage(`["a"]`),
"score": json.RawMessage(`7`), "due": json.RawMessage(`"2026-12-01"`), "done": json.RawMessage(`true`),
},
}
cases := []struct {
name string
r DocRule
want bool
}{
{"title contains, any case", rule("title", "contains", "plan"), true},
{"title is not", rule("title", "isNot", "Quarterly plan"), false},
{"tag contains one of", rule("tags", "contains", []string{"t9", "t2"}), true},
{"tag does not contain", rule("tags", "notContains", "t1"), false},
{"no tags", rule("tags", "empty", nil), false},
{"space is", rule("space", "is", "s1"), true},
{"created before", rule("created", "before", "2026-11-02"), true},
{"updated after", rule("updated", "after", "2026-11-13"), false},
{"updated in the last week", rule("updated", "withinDays", 7), true},
{"created in the last week", rule("created", "withinDays", 7), false},
{"created by", rule("createdBy", "is", []string{"u1"}), true},
{"not a template", rule("template", "is", false), true},
{"not a journal", rule("journal", "notEmpty", nil), false},
{"select is", rule("prop:status", "is", "done"), false},
{"multi-select contains", rule("prop:labels", "contains", "a"), true},
{"number above", rule("prop:score", "gt", 5), true},
{"number below", rule("prop:score", "lt", 5), false},
{"date after", rule("prop:due", "after", "2026-11-30"), true},
{"checkbox ticked", rule("prop:done", "is", true), true},
{"link empty", rule("prop:site", "empty", nil), true},
{"deleted property passes", rule("prop:gone", "is", "x"), true},
{"nothing picked yet passes", rule("tags", "contains", []string{}), true},
{"no date yet passes", rule("created", "before", ""), true},
}
for _, c := range cases {
if got := c.r.test(doc, testDefs, now); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
all := DocFilter{Rules: []DocRule{rule("title", "contains", "plan"), rule("prop:status", "is", "done")}}
if all.matches(doc, testDefs, now) {
t.Error("all: matched with a failing rule")
}
all.Match = "any"
if !all.matches(doc, testDefs, now) {
t.Error("any: did not match with a passing rule")
}
if !(DocFilter{}).matches(doc, testDefs, now) {
t.Error("no rules should match everything")
}
}
func TestDocFilterCheck(t *testing.T) {
if err := (DocFilter{Rules: []DocRule{rule("title", "resembles", "x")}}).check(); err == nil {
t.Error("unknown op accepted")
}
if err := (DocFilter{Rules: []DocRule{rule("colour", "is", "x")}}).check(); err == nil {
t.Error("unknown field accepted")
}
if err := (DocFilter{Match: "any", Rules: []DocRule{rule("prop:abc", "is", "x")}}).check(); err != nil {
t.Error(err)
}
}
func TestCollectionContains(t *testing.T) {
now := time.Now()
col := collectionRecord{
Include: []string{"hand"}, Exclude: []string{"out"},
Filter: DocFilter{Rules: []DocRule{rule("tags", "contains", "t1")}},
}
for id, want := range map[string]bool{"hand": true, "out": false, "tagged": true, "other": false} {
d := DocItem{ID: id}
if id == "tagged" || id == "out" {
d.Tags = []string{"t1"}
}
if got := col.contains(d, nil, now); got != want {
t.Errorf("%s: got %v, want %v", id, got, want)
}
}
// Without rules a collection holds only what was added to it.
if (collectionRecord{}).contains(DocItem{ID: "x"}, nil, now) {
t.Error("an empty collection matched a page")
}
}
func TestReplaceTag(t *testing.T) {
if got := replaceTag([]string{"a", "b", "c"}, "b", "c"); !slices.Equal(got, []string{"a", "c"}) {
t.Errorf("merge = %v", got)
}
if got := replaceTag([]string{"a", "b"}, "a", ""); !slices.Equal(got, []string{"b"}) {
t.Errorf("remove = %v", got)
}
}
func TestJournalIndexKeepsNewestFirst(t *testing.T) {
siblings := []pageRecord{{JournalDate: "2026-11-14"}, {JournalDate: "2026-11-12"}, {JournalDate: "2026-11-10"}}
if got := journalIndex(siblings, "2026-11-13"); got != 1 {
t.Errorf("index = %d, want 1", got)
}
if got := journalIndex(siblings, "2026-11-20"); got != 0 {
t.Errorf("index = %d, want 0", got)
}
}
+244
View File
@@ -0,0 +1,244 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"errors"
"fmt"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Journals --------------------------------------------------------------
//
// Everyone who works in a workspace may keep a journal there: one page per
// day, in their own journal space (spaces.journal_owner). The space is made
// the first time it is needed, private, with its owner as admin; workspace
// admins do not see into it (access.JournalSpaceRole). A day's page is made
// when it is first opened, filled from the journal template if one is set,
// and kept newest first at the top of the space.
// JournalDay is a day that has a journal page.
type JournalDay struct {
Date string `json:"date"`
Page string `json:"page"`
Title string `json:"title"`
}
// JournalInfo is the caller's journal in a workspace. Space and Template are
// empty until they exist; Days lists the requested range.
type JournalInfo struct {
Space string `json:"space"`
Template string `json:"template"`
Days []JournalDay `json:"days"`
}
// journalSpace finds c's journal space in ws; with create it makes one.
func (s *Service) journalSpace(ctx context.Context, c access.Caller, ws workspaceRecord, create bool) (spaceRecord, error) {
res, err := pocketbase.List[spaceRecord](ctx, s.pb, "spaces", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && journal_owner = '%s'", ws.ID, c.ID), Sort: "created",
})
if err != nil {
return spaceRecord{}, err
}
if len(res.Items) > 0 || !create {
if len(res.Items) == 0 {
return spaceRecord{}, nil
}
return res.Items[0], nil
}
base := slugify("journal-"+c.ID, "journal")
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": "Journal", "slug": slug, "icon": "📔",
"description": "", "visibility": access.SpacePrivate, "default_role": access.SpaceEditor,
"journal_owner": c.ID,
})
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Data["slug"].Code == "validation_not_unique" {
continue
}
if err != nil {
return spaceRecord{}, mapPB(err, "space not found")
}
if _, err := pocketbase.Create[spaceMemberRecord](ctx, s.pb, "space_members", map[string]any{
"space": rec.ID, "principal_type": "user", "principal_id": c.ID, "role": access.SpaceAdmin,
}); err != nil {
return spaceRecord{}, mapPB(err, "space not found")
}
return rec, nil
}
return spaceRecord{}, apperr.Conflict("could not find a free address for the journal space")
}
func (s *Service) journalWorkspace(ctx context.Context, c access.Caller, wsID string) (workspaceRecord, error) {
ws, role, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return ws, err
}
return ws, access.KeepJournal(role)
}
func parseDay(v, field string) (string, error) {
if _, err := time.Parse(time.DateOnly, v); err != nil {
return "", apperr.InvalidFields(map[string]string{field: "Dates look like 2026-11-14."})
}
return v, nil
}
// GetJournal lists the caller's journal days from from to to (inclusive,
// YYYY-MM-DD; at most a year), newest first.
func (s *Service) GetJournal(ctx context.Context, c access.Caller, wsID, from, to string) (JournalInfo, error) {
ws, err := s.journalWorkspace(ctx, c, wsID)
if err != nil {
return JournalInfo{}, err
}
out := JournalInfo{Days: []JournalDay{}}
if from, err = parseDay(from, "from"); err != nil {
return out, err
}
if to, err = parseDay(to, "to"); err != nil {
return out, err
}
f, _ := time.Parse(time.DateOnly, from)
t, _ := time.Parse(time.DateOnly, to)
if t.Before(f) || t.Sub(f) > 366*24*time.Hour {
return out, apperr.InvalidFields(map[string]string{"to": "Pick a range of at most a year."})
}
sp, err := s.journalSpace(ctx, c, ws, false)
if err != nil || sp.ID == "" {
return out, err
}
out.Space, out.Template = sp.ID, sp.JournalTemplate
rows, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("space = '%s' && deleted_at = '' && journal_date >= '%s' && journal_date <= '%s'", sp.ID, from, to),
Fields: "id,title,journal_date", Sort: "-journal_date,created",
})
if err != nil {
return out, err
}
seen := map[string]bool{}
for _, p := range rows {
if !seen[p.JournalDate] {
seen[p.JournalDate] = true
out.Days = append(out.Days, JournalDay{Date: p.JournalDate, Page: p.ID, Title: p.Title})
}
}
return out, nil
}
// SetJournalTemplate picks the page new journal pages are filled from ("" = none).
func (s *Service) SetJournalTemplate(ctx context.Context, c access.Caller, wsID, template string) (JournalInfo, error) {
ws, err := s.journalWorkspace(ctx, c, wsID)
if err != nil {
return JournalInfo{}, err
}
if template != "" {
t, _, err := s.pageFor(ctx, c, template)
if err != nil || t.Workspace != ws.ID || t.DeletedAt != "" {
return JournalInfo{}, apperr.InvalidFields(map[string]string{"template": "Template not found."})
}
}
sp, err := s.journalSpace(ctx, c, ws, true)
if err != nil {
return JournalInfo{}, err
}
if _, err := pocketbase.Update[spaceRecord](ctx, s.pb, "spaces", sp.ID, map[string]any{"journal_template": template}); err != nil {
return JournalInfo{}, mapPB(err, "space not found")
}
return JournalInfo{Space: sp.ID, Template: template, Days: []JournalDay{}}, nil
}
// OpenJournal returns the caller's journal page for a day, making it (and
// the journal space) when there is none yet. title names a new page; it
// defaults to the date.
func (s *Service) OpenJournal(ctx context.Context, c access.Caller, wsID, date, title string) (Page, error) {
ws, err := s.journalWorkspace(ctx, c, wsID)
if err != nil {
return Page{}, err
}
if date, err = parseDay(date, "date"); err != nil {
return Page{}, err
}
sp, err := s.journalSpace(ctx, c, ws, true)
if err != nil {
return Page{}, err
}
existing, err := pocketbase.List[pageRecord](ctx, s.pb, "pages", pocketbase.ListOptions{
PerPage: 1, Filter: fmt.Sprintf("space = '%s' && journal_date = '%s' && deleted_at = ''", sp.ID, date),
Fields: "id", Sort: "created",
})
if err != nil {
return Page{}, err
}
if len(existing.Items) > 0 {
return s.GetPage(ctx, c, existing.Items[0].ID)
}
if title, err = cleanTitle(title); err != nil {
return Page{}, err
}
if title == "" {
title = date
}
t, err := s.loadTree(ctx, sp.ID)
if err != nil {
return Page{}, err
}
siblings := t.children[""]
pos, renumber := placement(siblings, journalIndex(siblings, date))
if err := s.renumber(ctx, renumber); err != nil {
return Page{}, err
}
rec, err := pocketbase.Create[pageRecord](ctx, s.pb, "pages", map[string]any{
"workspace": ws.ID, "space": sp.ID, "title": title, "position": pos, "journal_date": date,
"creator": c.ID, "last_editor": c.ID, "mentions": []string{}, "links": []string{},
})
if err != nil {
return Page{}, mapPB(err, "page not found")
}
if sp.JournalTemplate != "" {
s.fillFromTemplate(ctx, c, rec, sp.JournalTemplate)
}
s.autoWatch(ctx, rec.ID, c.ID)
s.emitPage(ctx, "page.created", rec, c.ID, nil)
return s.GetPage(ctx, c, rec.ID)
}
// journalIndex is where a day goes among the space's top-level pages: after
// every later day, so the newest day comes first.
func journalIndex(siblings []pageRecord, date string) int {
i := 0
for _, p := range siblings {
if p.JournalDate > date {
i++
}
}
return i
}
// fillFromTemplate copies a template's content into a new page (best effort:
// a template that is gone or out of reach leaves the page empty).
func (s *Service) fillFromTemplate(ctx context.Context, c access.Caller, p pageRecord, templateID string) {
t, _, err := s.pageFor(ctx, c, templateID)
if err != nil || t.Workspace != p.Workspace || t.DeletedAt != "" {
return
}
doc, err := s.docs.Content(ctx, t.ID)
if err != nil || !isDoc(doc) {
return
}
_ = s.docs.Replace(ctx, p.ID, c.ID, doc, "template")
if t.Icon != "" && strings.TrimSpace(p.Icon) == "" {
_, _ = pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{"icon": t.Icon})
}
}
+69 -4
View File
@@ -4,6 +4,7 @@ package directory
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
@@ -24,7 +25,10 @@ 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,pinned_at,full_width,font,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,tags,journal_date,created,updated"
// pageDetailFields adds the page's property values.
const pageDetailFields = pageFields + ",properties"
type pageRecord struct {
ID string `json:"id"`
@@ -43,8 +47,13 @@ type pageRecord struct {
PinnedAt string `json:"pinned_at"`
FullWidth bool `json:"full_width"`
Font string `json:"font"`
Created string `json:"created"`
Updated string `json:"updated"`
// Tags are tag ids; Properties maps workspace property ids to values
// (only loaded with pageDetailFields).
Tags []string `json:"tags"`
Properties map[string]json.RawMessage `json:"properties"`
JournalDate string `json:"journal_date"`
Created string `json:"created"`
Updated string `json:"updated"`
}
// PageNode is one entry of a space's page tree.
@@ -99,6 +108,20 @@ type Page struct {
// FullWidth and Font are how the page is shown to everyone.
FullWidth bool `json:"fullWidth"`
Font string `json:"font"`
// Tags are the page's tag ids, Properties its custom property values by
// property id (see properties.go).
Tags []string `json:"tags"`
Properties map[string]json.RawMessage `json:"properties"`
// JournalDate is the day (YYYY-MM-DD) of a journal page; empty otherwise.
JournalDate string `json:"journalDate"`
CreatedBy PageUser `json:"createdBy"`
LastEditedBy PageUser `json:"lastEditedBy"`
}
// PageUser is a person named on a page; Name is empty when the account is gone.
type PageUser struct {
ID string `json:"id"`
Name string `json:"name"`
}
type TrashedPage struct {
@@ -120,7 +143,7 @@ func (s *Service) getPage(ctx context.Context, id string) (pageRecord, error) {
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,
PerPage: 1, Filter: fmt.Sprintf("id = '%s'", id), Fields: pageDetailFields,
})
if err != nil {
return pageRecord{}, err
@@ -268,6 +291,11 @@ func (s *Service) GetPage(ctx context.Context, c access.Caller, id string) (Page
Ancestors: []PageRef{}, Role: a.role, Restricted: p.Restricted, IsTemplate: p.IsTemplate,
Favorite: s.isFavorite(ctx, c.ID, p.ID), PinnedAt: p.PinnedAt,
FullWidth: p.FullWidth, Font: p.Font,
Tags: nonNil(p.Tags), Properties: p.Properties, JournalDate: p.JournalDate,
CreatedBy: s.pageUser(ctx, p.Creator), LastEditedBy: s.pageUser(ctx, p.LastEditor),
}
if page.Properties == nil {
page.Properties = map[string]json.RawMessage{}
}
parent := p.Parent
for depth := 0; parent != "" && depth < 100; depth++ {
@@ -414,6 +442,10 @@ type UpdatePageInput struct {
IsTemplate *bool `json:"isTemplate"`
FullWidth *bool `json:"fullWidth"`
Font *string `json:"font"`
// Tags replaces the page's tags (ids of the workspace's tags).
Tags *[]string `json:"tags"`
// Properties sets the named property values; null clears one.
Properties map[string]json.RawMessage `json:"properties"`
}
// UpdatePage renames a page, changes its icon or how it is shown (editor).
@@ -460,6 +492,20 @@ func (s *Service) UpdatePage(ctx context.Context, c access.Caller, id string, in
return Page{}, apperr.InvalidFields(map[string]string{"font": "Font must be empty, serif or mono."})
}
}
if in.Tags != nil {
tags, err := s.checkTags(ctx, p.Workspace, *in.Tags)
if err != nil {
return Page{}, err
}
patch["tags"] = tags
}
if len(in.Properties) > 0 {
props, err := s.mergeProperties(ctx, p, in.Properties)
if err != nil {
return Page{}, err
}
patch["properties"] = props
}
updated, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch)
if err != nil {
return Page{}, mapPB(err, "page not found")
@@ -717,3 +763,22 @@ func (s *Service) PurgePage(ctx context.Context, c access.Caller, id string) err
s.emitPage(ctx, "page.deleted", p, c.ID, nil)
return nil
}
// pageUser names a person on a page (best effort: a deleted account keeps its id).
func (s *Service) pageUser(ctx context.Context, id string) PageUser {
if id == "" {
return PageUser{}
}
u, err := s.getUser(ctx, id)
if err != nil {
return PageUser{ID: id}
}
return PageUser{ID: id, Name: u.Name}
}
func nonNil(list []string) []string {
if list == nil {
return []string{}
}
return list
}
+457
View File
@@ -0,0 +1,457 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"crypto/rand"
"encoding/json"
"fmt"
"math"
"net/url"
"slices"
"sort"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Page properties -------------------------------------------------------
//
// A workspace defines the custom properties its pages can fill in
// (workspace_properties); each page keeps its values in pages.properties as
// { "<property id>": value }. Built-in properties (tags, created, updated,
// created by, last edited by, template, journal, width) come from the page's
// own fields and are not defined here. A value whose property was deleted
// stays in the page until it is next saved, and is ignored meanwhile.
// Property types and what their values look like in JSON.
const (
PropText = "text" // "free text"
PropNumber = "number" // 42.5
PropCheckbox = "checkbox" // true
PropDate = "date" // "2026-11-14"
PropSelect = "select" // "<option id>"
PropMultiSelect = "multi_select" // ["<option id>", …]
PropMember = "member" // ["<user id>", …]
PropLink = "link" // "https://…"
)
var propertyTypes = []string{PropText, PropNumber, PropCheckbox, PropDate, PropSelect, PropMultiSelect, PropMember, PropLink}
// Colours for select options and tags; the apps draw them from the theme.
var labelColors = []string{"", "gray", "red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
const (
maxProperties = 100
maxOptions = 200
maxListValues = 100
maxTextValue = 5000
maxPropertyName = 80
)
// PropertyOption is one choice of a select or multi-select property.
type PropertyOption struct {
ID string `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
}
// Property is a custom page property of a workspace.
type Property struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Type string `json:"type"`
Options []PropertyOption `json:"options"`
// Visibility is whether the page's Info panel shows it: always, only when
// it has a value (hide_empty), or never (it is then only in the side panel).
Visibility string `json:"visibility"`
Position float64 `json:"position"`
}
type propertyRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Type string `json:"type"`
Options []PropertyOption `json:"options"`
Visibility string `json:"visibility"`
Position float64 `json:"position"`
}
func (r propertyRecord) view() Property {
v := Property(r)
if v.Options == nil {
v.Options = []PropertyOption{}
}
if v.Visibility == "" {
v.Visibility = "always"
}
return v
}
func (s *Service) workspaceProperties(ctx context.Context, wsID string) ([]propertyRecord, error) {
rows, err := listAll[propertyRecord](ctx, s, "workspace_properties", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", wsID), Sort: "position,created",
})
return rows, err
}
// ListProperties lists a workspace's custom page properties in order.
func (s *Service) ListProperties(ctx context.Context, c access.Caller, wsID string) ([]Property, error) {
ws, _, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return nil, err
}
rows, err := s.workspaceProperties(ctx, ws.ID)
if err != nil {
return nil, err
}
out := make([]Property, len(rows))
for i, r := range rows {
out[i] = r.view()
}
return out, nil
}
// PropertyInput creates a property, or changes the fields that are set.
type PropertyInput struct {
Name *string `json:"name"`
Type *string `json:"type"`
Options *[]PropertyOption `json:"options"`
Visibility *string `json:"visibility"`
Position *float64 `json:"position"`
}
// CreateProperty adds a custom property to a workspace (members).
func (s *Service) CreateProperty(ctx context.Context, c access.Caller, wsID string, in PropertyInput) (Property, error) {
ws, role, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return Property{}, err
}
if err := access.OrganizeWorkspace(role); err != nil {
return Property{}, err
}
if in.Name == nil || in.Type == nil {
return Property{}, apperr.InvalidFields(map[string]string{"name": "Name and type are required."})
}
existing, err := s.workspaceProperties(ctx, ws.ID)
if err != nil {
return Property{}, err
}
if len(existing) >= maxProperties {
return Property{}, apperr.Invalid("a workspace can have at most 100 properties")
}
body, err := propertyPatch(in, true)
if err != nil {
return Property{}, err
}
body["workspace"] = ws.ID
if in.Position == nil {
next := 0.0
for _, p := range existing {
next = math.Max(next, p.Position+1)
}
body["position"] = next
}
if _, ok := body["visibility"]; !ok {
body["visibility"] = "always"
}
rec, err := pocketbase.Create[propertyRecord](ctx, s.pb, "workspace_properties", body)
if err != nil {
return Property{}, mapPB(err, "property not found")
}
return rec.view(), nil
}
func (s *Service) propertyFor(ctx context.Context, c access.Caller, id string) (propertyRecord, string, error) {
if !validID(id) {
return propertyRecord{}, "", apperr.NotFound("property not found")
}
rec, err := pocketbase.Get[propertyRecord](ctx, s.pb, "workspace_properties", id)
if err != nil {
return rec, "", mapPB(err, "property not found")
}
_, role, err := s.workspaceFor(ctx, c, rec.Workspace)
if err != nil {
return rec, "", apperr.NotFound("property not found")
}
return rec, role, nil
}
// UpdateProperty renames a property, changes its options, visibility or
// place. A changed type keeps the values that still fit and drops the rest
// as pages are next saved; reading ignores values of the wrong shape.
func (s *Service) UpdateProperty(ctx context.Context, c access.Caller, id string, in PropertyInput) (Property, error) {
rec, role, err := s.propertyFor(ctx, c, id)
if err != nil {
return Property{}, err
}
if err := access.OrganizeWorkspace(role); err != nil {
return Property{}, err
}
patch, err := propertyPatch(in, false)
if err != nil {
return Property{}, err
}
if len(patch) == 0 {
return rec.view(), nil
}
updated, err := pocketbase.Update[propertyRecord](ctx, s.pb, "workspace_properties", rec.ID, patch)
if err != nil {
return Property{}, mapPB(err, "property not found")
}
return updated.view(), nil
}
// DeleteProperty removes a property from the workspace (members). Pages'
// values for it are ignored from then on.
func (s *Service) DeleteProperty(ctx context.Context, c access.Caller, id string) error {
rec, role, err := s.propertyFor(ctx, c, id)
if err != nil {
return err
}
if err := access.OrganizeWorkspace(role); err != nil {
return err
}
return mapPB(s.pb.Delete(ctx, "workspace_properties", rec.ID), "property not found")
}
// propertyPatch checks a property's fields; creating needs name and type.
func propertyPatch(in PropertyInput, creating bool) (map[string]any, error) {
patch := map[string]any{}
if in.Name != nil {
name := strings.TrimSpace(*in.Name)
switch {
case name == "":
return nil, apperr.InvalidFields(map[string]string{"name": "Name is required."})
case len([]rune(name)) > maxPropertyName:
return nil, apperr.InvalidFields(map[string]string{"name": "Name is too long (max 80)."})
}
patch["name"] = name
}
if in.Type != nil {
if !slices.Contains(propertyTypes, *in.Type) {
return nil, apperr.InvalidFields(map[string]string{"type": "Unknown property type."})
}
patch["type"] = *in.Type
}
if in.Options != nil {
opts, err := cleanOptions(*in.Options)
if err != nil {
return nil, err
}
patch["options"] = opts
} else if creating {
patch["options"] = []PropertyOption{}
}
if in.Visibility != nil {
switch *in.Visibility {
case "always", "hide_empty", "never":
patch["visibility"] = *in.Visibility
default:
return nil, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be always, hide_empty or never."})
}
}
if in.Position != nil {
if math.IsNaN(*in.Position) || math.IsInf(*in.Position, 0) {
return nil, apperr.InvalidFields(map[string]string{"position": "Position must be a number."})
}
patch["position"] = *in.Position
}
return patch, nil
}
// cleanOptions checks select choices, giving new ones an id.
func cleanOptions(in []PropertyOption) ([]PropertyOption, error) {
if len(in) > maxOptions {
return nil, apperr.InvalidFields(map[string]string{"options": "At most 200 options."})
}
out := make([]PropertyOption, 0, len(in))
seen := map[string]bool{}
for _, o := range in {
name := strings.TrimSpace(o.Name)
if name == "" || len([]rune(name)) > 60 {
return nil, apperr.InvalidFields(map[string]string{"options": "Each option needs a name of at most 60 characters."})
}
if !slices.Contains(labelColors, o.Color) {
return nil, apperr.InvalidFields(map[string]string{"options": "Unknown option colour."})
}
id := o.ID
if id == "" {
id = newOptionID()
} else if !validID(id) {
return nil, apperr.InvalidFields(map[string]string{"options": "Invalid option id."})
}
if seen[id] {
continue
}
seen[id] = true
out = append(out, PropertyOption{ID: id, Name: name, Color: o.Color})
}
return out, nil
}
func newOptionID() string {
const letters = "abcdefghijklmnopqrstuvwxyz0123456789"
b := make([]byte, 10)
_, _ = rand.Read(b)
for i := range b {
b[i] = letters[int(b[i])%len(letters)]
}
return string(b)
}
// mergeProperties applies values to a page's properties, dropping values of
// properties that no longer exist. A null value clears one.
func (s *Service) mergeProperties(ctx context.Context, p pageRecord, in map[string]json.RawMessage) (map[string]json.RawMessage, error) {
defs, err := s.workspaceProperties(ctx, p.Workspace)
if err != nil {
return nil, err
}
byID := make(map[string]propertyRecord, len(defs))
for _, d := range defs {
byID[d.ID] = d
}
out := map[string]json.RawMessage{}
for id, v := range p.Properties {
if _, ok := byID[id]; ok {
out[id] = v
}
}
keys := make([]string, 0, len(in))
for id := range in {
keys = append(keys, id)
}
sort.Strings(keys)
for _, id := range keys {
def, ok := byID[id]
if !ok {
return nil, apperr.InvalidFields(map[string]string{"properties": "Unknown property " + id + "."})
}
v, err := cleanValue(def, in[id])
if err != nil {
return nil, apperr.InvalidFields(map[string]string{"properties": def.Name + ": " + err.Error()})
}
if v == nil {
delete(out, id)
} else {
out[id] = v
}
}
return out, nil
}
// cleanValue checks a value against its property's type and returns it as
// stored, or nil when it clears the property (null, "", [], false is kept).
func cleanValue(def propertyRecord, raw json.RawMessage) (json.RawMessage, error) {
if len(raw) == 0 || string(raw) == "null" {
return nil, nil
}
enc := func(v any) (json.RawMessage, error) {
b, err := json.Marshal(v)
return b, err
}
switch def.Type {
case PropText, PropLink:
var v string
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected text")
}
v = strings.TrimSpace(v)
if v == "" {
return nil, nil
}
if len(v) > maxTextValue {
return nil, fmt.Errorf("text is too long")
}
if def.Type == PropLink && !validLink(v) {
return nil, fmt.Errorf("expected an http, https or mailto link")
}
return enc(v)
case PropNumber:
var v float64
if json.Unmarshal(raw, &v) != nil || math.IsNaN(v) || math.IsInf(v, 0) {
return nil, fmt.Errorf("expected a number")
}
return enc(v)
case PropCheckbox:
var v bool
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected true or false")
}
return enc(v)
case PropDate:
var v string
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected a date")
}
if v == "" {
return nil, nil
}
if _, err := time.Parse(time.DateOnly, v); err != nil {
return nil, fmt.Errorf("dates look like 2026-11-14")
}
return enc(v)
case PropSelect:
var v string
if json.Unmarshal(raw, &v) != nil {
return nil, fmt.Errorf("expected an option id")
}
if v == "" {
return nil, nil
}
if !hasOption(def, v) {
return nil, fmt.Errorf("unknown option")
}
return enc(v)
case PropMultiSelect, PropMember:
var list []string
if json.Unmarshal(raw, &list) != nil {
return nil, fmt.Errorf("expected a list of ids")
}
out := []string{}
for _, id := range list {
if slices.Contains(out, id) {
continue
}
if def.Type == PropMultiSelect && !hasOption(def, id) {
return nil, fmt.Errorf("unknown option")
}
if def.Type == PropMember && !validID(id) {
return nil, fmt.Errorf("invalid person")
}
out = append(out, id)
}
if len(out) == 0 {
return nil, nil
}
if len(out) > maxListValues {
return nil, fmt.Errorf("too many values")
}
return enc(out)
}
return nil, fmt.Errorf("unknown property type")
}
func hasOption(def propertyRecord, id string) bool {
return slices.ContainsFunc(def.Options, func(o PropertyOption) bool { return o.ID == id })
}
func validLink(v string) bool {
u, err := url.Parse(v)
if err != nil {
return false
}
switch u.Scheme {
case "http", "https":
return u.Host != ""
case "mailto":
return u.Opaque != "" || u.Path != ""
}
return false
}
+35 -2
View File
@@ -5,6 +5,7 @@ package directory
import (
"context"
"slices"
"strings"
"time"
"docwell/server/internal/access"
@@ -30,12 +31,13 @@ type SearchResult struct {
Total int `json:"total"`
}
// SearchQuery is a search request. Space, Author, UpdatedAfter and
// SearchQuery is a search request. Space, Tag, 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
Tag string
Author string
UpdatedAfter string
UpdatedBefore string
@@ -99,19 +101,46 @@ func (s *Service) Search(ctx context.Context, c access.Caller, wsID string, sq S
if limit <= 0 {
limit = 20
}
// A tag narrows the hits to the pages carrying it.
var tagged map[string]bool
if sq.Tag != "" {
if !validID(sq.Tag) {
return out, nil
}
pages, err := s.taggedPages(ctx, wsID, sq.Tag)
if err != nil {
return SearchResult{}, err
}
tagged = make(map[string]bool, len(pages))
for _, p := range pages {
tagged[p.ID] = true
}
if len(tagged) == 0 {
return out, nil
}
filtered = true
// The index does not know tags: with no text and no other filter,
// have it list every page (newest first) for the tag to narrow.
if strings.TrimSpace(sq.Text) == "" && f.Author == "" && f.After.IsZero() && f.Before.IsZero() {
f.After = time.Unix(1, 0)
}
}
// Hidden pages are dropped after the query, so ask for more to keep
// the page of results full.
want := limit
if filtered {
want = limit*3 + 20
}
if tagged != nil {
want = limit*10 + 200
}
hits, total, err := s.search.Query(ctx, wsID, ids, sq.Text, f, want)
if err != nil {
return SearchResult{}, err
}
dropped := 0
for _, h := range hits {
if rules[h.Space].role(h.ID) == "" {
if rules[h.Space].role(h.ID) == "" || (tagged != nil && !tagged[h.ID]) {
dropped++
continue
}
@@ -120,5 +149,9 @@ func (s *Service) Search(ctx context.Context, c access.Caller, wsID string, sq S
}
}
out.Total = max(total-dropped, len(out.Items))
if tagged != nil {
// Only the hits read here are known to carry the tag.
out.Total = len(hits) - dropped
}
return out, nil
}
+25 -7
View File
@@ -6,6 +6,7 @@ import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
@@ -29,7 +30,10 @@ type Space struct {
Role string `json:"role"`
// Limited is true when the caller cannot open the space itself and sees
// only the pages shared with them (Role is then "").
Limited bool `json:"limited"`
Limited bool `json:"limited"`
// Journal is set on a journal space: one person's daily pages, kept
// out of everyone else's lists (see access.JournalSpaceRole).
Journal bool `json:"journal"`
Created string `json:"created"`
}
@@ -43,6 +47,9 @@ type spaceRecord struct {
Visibility string `json:"visibility"`
DefaultRole string `json:"default_role"`
Created string `json:"created"`
// JournalOwner is the person whose journal this space is ("" for others).
JournalOwner string `json:"journal_owner"`
JournalTemplate string `json:"journal_template"`
}
func (r spaceRecord) view(role string) Space {
@@ -52,10 +59,20 @@ func (r spaceRecord) view(role string) Space {
}
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, Limited: role == "", Created: r.Created,
Visibility: r.Visibility, DefaultRole: def, Role: role, Limited: role == "", Journal: r.JournalOwner != "",
Created: r.Created,
}
}
// role is the caller's role in the space after the cascade; explicit is
// their own (or their groups') role in it.
func (r spaceRecord) role(callerID, wsRole, explicit string) string {
if r.JournalOwner != "" {
return access.JournalSpaceRole(wsRole, r.JournalOwner, callerID, explicit)
}
return access.SpaceRole(wsRole, r.Visibility, r.DefaultRole, explicit)
}
type spaceMemberRecord struct {
ID string `json:"id"`
Space string `json:"space"`
@@ -128,12 +145,12 @@ func (s *Service) loadSpace(ctx context.Context, c access.Caller, id string) (sp
return spaceAccess{}, err
}
var explicit string
if wsRole != "" && !access.AtLeast(wsRole, access.WorkspaceAdmin) {
if wsRole != "" && (!access.AtLeast(wsRole, access.WorkspaceAdmin) || sp.JournalOwner != "") {
if explicit, err = s.explicitSpaceRole(ctx, sp, c.ID); err != nil {
return spaceAccess{}, err
}
}
role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit)
role := sp.role(c.ID, wsRole, explicit)
return spaceAccess{space: sp, ws: ws, wsRole: wsRole, spaceRole: role, role: role}, nil
}
@@ -183,7 +200,8 @@ func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string)
return nil, err
}
explicit := map[string]string{}
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
journals := slices.ContainsFunc(spaces, func(sp spaceRecord) bool { return sp.JournalOwner != "" })
if !access.AtLeast(wsRole, access.WorkspaceAdmin) || journals {
mine, err := s.userSpaceMemberships(ctx, c.ID, ws.ID)
if err != nil {
return nil, err
@@ -204,14 +222,14 @@ func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string)
}
}
var shared map[string]bool
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
if !access.AtLeast(wsRole, access.WorkspaceAdmin) || journals {
if shared, err = s.grantedSpaces(ctx, c, ws.ID); err != nil {
return nil, err
}
}
out := []Space{}
for _, sp := range spaces {
if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" || shared[sp.ID] {
if role := sp.role(c.ID, wsRole, explicit[sp.ID]); role != "" || shared[sp.ID] {
out = append(out, sp.view(role))
}
}
+273
View File
@@ -0,0 +1,273 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/store/pocketbase"
)
// ---- Tags ------------------------------------------------------------------
//
// Tags are coloured labels shared by a workspace's pages (pages.tags). Any
// member may create, rename, recolour, merge or delete them.
const maxTagsPerPage = 100
// Tag is one of a workspace's tags; Pages counts the live pages using it
// (all of them, not only those the caller can open).
type Tag struct {
ID string `json:"id"`
Name string `json:"name"`
Color string `json:"color"`
Pages int `json:"pages"`
}
type tagRecord struct {
ID string `json:"id"`
Workspace string `json:"workspace"`
Name string `json:"name"`
Color string `json:"color"`
}
func (s *Service) workspaceTags(ctx context.Context, wsID string) ([]tagRecord, error) {
return listAll[tagRecord](ctx, s, "tags", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s'", wsID), Sort: "name",
})
}
// taggedPages lists the live pages of a workspace that carry a tag ("" = any tag).
func (s *Service) taggedPages(ctx context.Context, wsID, tagID string) ([]pageRecord, error) {
filter := fmt.Sprintf("workspace = '%s' && deleted_at = ''", wsID)
if tagID != "" {
filter += fmt.Sprintf(" && tags.id ?= '%s'", tagID)
} else {
filter += " && tags:length > 0"
}
return listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{Filter: filter, Fields: "id,tags"})
}
// ListTags lists a workspace's tags by name, with how many pages use each.
func (s *Service) ListTags(ctx context.Context, c access.Caller, wsID string) ([]Tag, error) {
ws, _, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return nil, err
}
rows, err := s.workspaceTags(ctx, ws.ID)
if err != nil {
return nil, err
}
pages, err := s.taggedPages(ctx, ws.ID, "")
if err != nil {
return nil, err
}
counts := map[string]int{}
for _, p := range pages {
for _, t := range p.Tags {
counts[t]++
}
}
out := make([]Tag, len(rows))
for i, r := range rows {
out[i] = Tag{ID: r.ID, Name: r.Name, Color: r.Color, Pages: counts[r.ID]}
}
sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
return out, nil
}
type TagInput struct {
Name *string `json:"name"`
Color *string `json:"color"`
}
func tagPatch(in TagInput) (map[string]any, error) {
patch := map[string]any{}
if in.Name != nil {
name := strings.TrimSpace(*in.Name)
switch {
case name == "":
return nil, apperr.InvalidFields(map[string]string{"name": "Name is required."})
case len([]rune(name)) > 60:
return nil, apperr.InvalidFields(map[string]string{"name": "Name is too long (max 60)."})
}
patch["name"] = name
}
if in.Color != nil {
if !slices.Contains(labelColors, *in.Color) {
return nil, apperr.InvalidFields(map[string]string{"color": "Unknown colour."})
}
patch["color"] = *in.Color
}
return patch, nil
}
func tagError(err error) error {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Data["name"].Code == "validation_not_unique" {
return apperr.Conflict("a tag with this name already exists")
}
return mapPB(err, "tag not found")
}
// CreateTag adds a tag to a workspace (members).
func (s *Service) CreateTag(ctx context.Context, c access.Caller, wsID string, in TagInput) (Tag, error) {
ws, role, err := s.workspaceFor(ctx, c, wsID)
if err != nil {
return Tag{}, err
}
if err := access.OrganizeWorkspace(role); err != nil {
return Tag{}, err
}
if in.Name == nil {
return Tag{}, apperr.InvalidFields(map[string]string{"name": "Name is required."})
}
body, err := tagPatch(in)
if err != nil {
return Tag{}, err
}
body["workspace"] = ws.ID
rec, err := pocketbase.Create[tagRecord](ctx, s.pb, "tags", body)
if err != nil {
return Tag{}, tagError(err)
}
return Tag{ID: rec.ID, Name: rec.Name, Color: rec.Color}, nil
}
func (s *Service) tagFor(ctx context.Context, c access.Caller, id string) (tagRecord, string, error) {
if !validID(id) {
return tagRecord{}, "", apperr.NotFound("tag not found")
}
rec, err := pocketbase.Get[tagRecord](ctx, s.pb, "tags", id)
if err != nil {
return rec, "", mapPB(err, "tag not found")
}
_, role, err := s.workspaceFor(ctx, c, rec.Workspace)
if err != nil {
return rec, "", apperr.NotFound("tag not found")
}
if err := access.OrganizeWorkspace(role); err != nil {
return rec, role, err
}
return rec, role, nil
}
// UpdateTag renames or recolours a tag (members).
func (s *Service) UpdateTag(ctx context.Context, c access.Caller, id string, in TagInput) (Tag, error) {
rec, _, err := s.tagFor(ctx, c, id)
if err != nil {
return Tag{}, err
}
patch, err := tagPatch(in)
if err != nil {
return Tag{}, err
}
if len(patch) > 0 {
if rec, err = pocketbase.Update[tagRecord](ctx, s.pb, "tags", rec.ID, patch); err != nil {
return Tag{}, tagError(err)
}
}
pages, err := s.taggedPages(ctx, rec.Workspace, rec.ID)
if err != nil {
return Tag{}, err
}
return Tag{ID: rec.ID, Name: rec.Name, Color: rec.Color, Pages: len(pages)}, nil
}
// retag replaces tag from with to ("" = remove it) on every page carrying it,
// trashed pages included, so nothing points at a deleted tag.
func (s *Service) retag(ctx context.Context, wsID, from, to string) error {
pages, err := listAll[pageRecord](ctx, s, "pages", pocketbase.ListOptions{
Filter: fmt.Sprintf("workspace = '%s' && tags.id ?= '%s'", wsID, from), Fields: "id,tags",
})
if err != nil {
return err
}
for _, p := range pages {
next := replaceTag(p.Tags, from, to)
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{"tags": next}); err != nil {
return mapPB(err, "page not found")
}
}
return nil
}
// replaceTag swaps from for to in tags, keeping each tag once and the order.
func replaceTag(tags []string, from, to string) []string {
out := []string{}
for _, t := range tags {
if t == from {
t = to
}
if t != "" && !slices.Contains(out, t) {
out = append(out, t)
}
}
return out
}
// DeleteTag takes a tag off every page and deletes it (members).
func (s *Service) DeleteTag(ctx context.Context, c access.Caller, id string) error {
rec, _, err := s.tagFor(ctx, c, id)
if err != nil {
return err
}
if err := s.retag(ctx, rec.Workspace, rec.ID, ""); err != nil {
return err
}
return mapPB(s.pb.Delete(ctx, "tags", rec.ID), "tag not found")
}
// MergeTag moves every page from tag id to tag into, then deletes id (members).
func (s *Service) MergeTag(ctx context.Context, c access.Caller, id, into string) (Tag, error) {
rec, _, err := s.tagFor(ctx, c, id)
if err != nil {
return Tag{}, err
}
target, _, err := s.tagFor(ctx, c, into)
if err != nil || target.Workspace != rec.Workspace || target.ID == rec.ID {
return Tag{}, apperr.InvalidFields(map[string]string{"into": "Pick another tag of this workspace."})
}
if err := s.retag(ctx, rec.Workspace, rec.ID, target.ID); err != nil {
return Tag{}, err
}
if err := s.pb.Delete(ctx, "tags", rec.ID); err != nil {
return Tag{}, mapPB(err, "tag not found")
}
return s.UpdateTag(ctx, c, target.ID, TagInput{})
}
// checkTags makes sure every id is a tag of the workspace; it keeps each once.
func (s *Service) checkTags(ctx context.Context, wsID string, ids []string) ([]string, error) {
if len(ids) > maxTagsPerPage {
return nil, apperr.InvalidFields(map[string]string{"tags": "A page can have at most 100 tags."})
}
out := []string{}
if len(ids) == 0 {
return out, nil
}
rows, err := s.workspaceTags(ctx, wsID)
if err != nil {
return nil, err
}
known := make(map[string]bool, len(rows))
for _, r := range rows {
known[r.ID] = true
}
for _, id := range ids {
if !known[id] {
return nil, apperr.InvalidFields(map[string]string{"tags": "Unknown tag."})
}
if !slices.Contains(out, id) {
out = append(out, id)
}
}
return out, nil
}
+1
View File
@@ -211,6 +211,7 @@ func (a *api) routes(mux *routeMux) {
a.inviteRoutes(mux)
a.groupRoutes(mux)
a.favoriteRoutes(mux)
a.organizeRoutes(mux)
a.searchRoutes(mux)
a.transferRoutes(mux)
a.shareRoutes(mux)
+1
View File
@@ -46,6 +46,7 @@ type DirectoryService interface {
UserManager
WebhookService
CommentService
OrganizeService
}
func caller(r *http.Request) access.Caller {
+179
View File
@@ -0,0 +1,179 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"encoding/json"
"net/http"
"docwell/server/internal/access"
"docwell/server/internal/apperr"
"docwell/server/internal/directory"
)
// OrganizeService is the part of directory.Service for page properties,
// tags, the All docs list, collections and journals.
type OrganizeService interface {
ListProperties(ctx context.Context, c access.Caller, wsID string) ([]directory.Property, error)
CreateProperty(ctx context.Context, c access.Caller, wsID string, in directory.PropertyInput) (directory.Property, error)
UpdateProperty(ctx context.Context, c access.Caller, id string, in directory.PropertyInput) (directory.Property, error)
DeleteProperty(ctx context.Context, c access.Caller, id string) error
ListTags(ctx context.Context, c access.Caller, wsID string) ([]directory.Tag, error)
CreateTag(ctx context.Context, c access.Caller, wsID string, in directory.TagInput) (directory.Tag, error)
UpdateTag(ctx context.Context, c access.Caller, id string, in directory.TagInput) (directory.Tag, error)
DeleteTag(ctx context.Context, c access.Caller, id string) error
MergeTag(ctx context.Context, c access.Caller, id, into string) (directory.Tag, error)
ListDocs(ctx context.Context, c access.Caller, wsID string, q directory.DocQuery) (directory.DocList, error)
ListCollections(ctx context.Context, c access.Caller, wsID string) ([]directory.Collection, error)
CreateCollection(ctx context.Context, c access.Caller, wsID string, in directory.CollectionInput) (directory.Collection, error)
UpdateCollection(ctx context.Context, c access.Caller, id string, in directory.CollectionInput) (directory.Collection, error)
DeleteCollection(ctx context.Context, c access.Caller, id string) error
SetCollectionPage(ctx context.Context, c access.Caller, id, pageID string, in bool) (directory.Collection, error)
GetJournal(ctx context.Context, c access.Caller, wsID, from, to string) (directory.JournalInfo, error)
SetJournalTemplate(ctx context.Context, c access.Caller, wsID, template string) (directory.JournalInfo, error)
OpenJournal(ctx context.Context, c access.Caller, wsID, date, title string) (directory.Page, error)
}
func (a *api) organizeRoutes(mux *routeMux) {
// Properties.
mux.HandleFunc("GET /api/v1/workspaces/{id}/properties", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
list, err := a.dir.ListProperties(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/workspaces/{id}/properties", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.PropertyInput
if !a.decode(w, r, &in) {
return
}
p, err := a.dir.CreateProperty(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, p, err)
}))
mux.HandleFunc("PATCH /api/v1/properties/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.PropertyInput
if !a.decode(w, r, &in) {
return
}
p, err := a.dir.UpdateProperty(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, p, err)
}))
mux.HandleFunc("DELETE /api/v1/properties/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.dir.DeleteProperty(r.Context(), caller(r), r.PathValue("id")))
}))
// Tags.
mux.HandleFunc("GET /api/v1/workspaces/{id}/tags", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
list, err := a.dir.ListTags(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/workspaces/{id}/tags", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.TagInput
if !a.decode(w, r, &in) {
return
}
t, err := a.dir.CreateTag(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, t, err)
}))
mux.HandleFunc("PATCH /api/v1/tags/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.TagInput
if !a.decode(w, r, &in) {
return
}
t, err := a.dir.UpdateTag(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, t, err)
}))
mux.HandleFunc("DELETE /api/v1/tags/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.dir.DeleteTag(r.Context(), caller(r), r.PathValue("id")))
}))
mux.HandleFunc("POST /api/v1/tags/{id}/merge", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct {
Into string `json:"into"`
}
if !a.decode(w, r, &in) {
return
}
t, err := a.dir.MergeTag(r.Context(), caller(r), r.PathValue("id"), in.Into)
a.respond(w, t, err)
}))
// All docs.
mux.HandleFunc("GET /api/v1/workspaces/{id}/docs", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
dq := directory.DocQuery{Space: q.Get("space"), Tag: q.Get("tag"), Collection: q.Get("collection")}
if raw := q.Get("filter"); raw != "" {
var f directory.DocFilter
if err := json.Unmarshal([]byte(raw), &f); err != nil {
a.writeError(w, apperr.InvalidFields(map[string]string{"filter": "The filter is not valid JSON."}))
return
}
dq.Filter = &f
}
list, err := a.dir.ListDocs(r.Context(), caller(r), r.PathValue("id"), dq)
a.respond(w, list, err)
}))
// Collections.
mux.HandleFunc("GET /api/v1/workspaces/{id}/collections", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
list, err := a.dir.ListCollections(r.Context(), caller(r), r.PathValue("id"))
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/workspaces/{id}/collections", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.CollectionInput
if !a.decode(w, r, &in) {
return
}
col, err := a.dir.CreateCollection(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, col, err)
}))
mux.HandleFunc("PATCH /api/v1/collections/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in directory.CollectionInput
if !a.decode(w, r, &in) {
return
}
col, err := a.dir.UpdateCollection(r.Context(), caller(r), r.PathValue("id"), in)
a.respond(w, col, err)
}))
mux.HandleFunc("DELETE /api/v1/collections/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
a.respondNoContent(w, a.dir.DeleteCollection(r.Context(), caller(r), r.PathValue("id")))
}))
mux.HandleFunc("PUT /api/v1/collections/{id}/pages/{page}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
col, err := a.dir.SetCollectionPage(r.Context(), caller(r), r.PathValue("id"), r.PathValue("page"), true)
a.respond(w, col, err)
}))
mux.HandleFunc("DELETE /api/v1/collections/{id}/pages/{page}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
col, err := a.dir.SetCollectionPage(r.Context(), caller(r), r.PathValue("id"), r.PathValue("page"), false)
a.respond(w, col, err)
}))
// Journals.
mux.HandleFunc("GET /api/v1/workspaces/{id}/journals", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
j, err := a.dir.GetJournal(r.Context(), caller(r), r.PathValue("id"), q.Get("from"), q.Get("to"))
a.respond(w, j, err)
}))
mux.HandleFunc("PATCH /api/v1/workspaces/{id}/journals", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct {
Template string `json:"template"`
}
if !a.decode(w, r, &in) {
return
}
j, err := a.dir.SetJournalTemplate(r.Context(), caller(r), r.PathValue("id"), in.Template)
a.respond(w, j, err)
}))
mux.HandleFunc("PUT /api/v1/workspaces/{id}/journals/{date}", a.requireUser(func(w http.ResponseWriter, r *http.Request) {
var in struct {
Title string `json:"title"`
}
// The body is optional.
if r.ContentLength != 0 && !a.decode(w, r, &in) {
return
}
p, err := a.dir.OpenJournal(r.Context(), caller(r), r.PathValue("id"), r.PathValue("date"), in.Title)
a.respond(w, p, err)
}))
}
+1 -1
View File
@@ -21,7 +21,7 @@ func (a *api) searchRoutes(mux *routeMux) {
q := r.URL.Query()
limit, _ := strconv.Atoi(q.Get("limit"))
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"),
Text: q.Get("q"), Space: q.Get("space"), Tag: q.Get("tag"), Author: q.Get("author"),
UpdatedAfter: q.Get("updatedAfter"), UpdatedBefore: q.Get("updatedBefore"),
Limit: min(max(limit, 0), 50),
})
+458 -1
View File
@@ -719,6 +719,34 @@
"presentable": false,
"system": false,
"type": "autodate"
},
{
"cascadeDelete": true,
"collectionId": "_pb_users_auth_",
"help": "",
"hidden": false,
"id": "relation750507350",
"maxSelect": 1,
"minSelect": 0,
"name": "journal_owner",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"cascadeDelete": false,
"collectionId": "pbc_3945946014",
"help": "",
"hidden": false,
"id": "relation1204859450",
"maxSelect": 1,
"minSelect": 0,
"name": "journal_template",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
}
],
"id": "pbc_3929545014",
@@ -1154,12 +1182,53 @@
"serif",
"mono"
]
},
{
"help": "",
"hidden": false,
"id": "json2277716423",
"maxSize": 100000,
"name": "properties",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"cascadeDelete": false,
"collectionId": "pbc_1219621782",
"help": "",
"hidden": false,
"id": "relation1874629670",
"maxSelect": 100,
"minSelect": 0,
"name": "tags",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text312872946",
"max": 10,
"min": 0,
"name": "journal_date",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
}
],
"id": "pbc_3945946014",
"indexes": [
"CREATE INDEX idx_pages_workspace ON pages (workspace, updated)",
"CREATE INDEX idx_pages_tree ON pages (space, parent, position)"
"CREATE INDEX idx_pages_tree ON pages (space, parent, position)",
"CREATE INDEX `idx_pages_journal` ON `pages` (space, journal_date)"
],
"listRule": null,
"name": "pages",
@@ -4013,5 +4082,393 @@
"type": "base",
"updateRule": null,
"viewRule": null
},
{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"help": "",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": true,
"collectionId": "pbc_2170078043",
"help": "",
"hidden": false,
"id": "relation2375286809",
"maxSelect": 1,
"minSelect": 0,
"name": "workspace",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1579384326",
"max": 80,
"min": 0,
"name": "name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"help": "",
"hidden": false,
"id": "select2363381545",
"maxSelect": 1,
"name": "type",
"presentable": false,
"required": true,
"system": false,
"type": "select",
"values": [
"text",
"number",
"checkbox",
"date",
"select",
"multi_select",
"member",
"link"
]
},
{
"help": "",
"hidden": false,
"id": "json3493198471",
"maxSize": 20000,
"name": "options",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"help": "",
"hidden": false,
"id": "select1368277760",
"maxSelect": 1,
"name": "visibility",
"presentable": false,
"required": false,
"system": false,
"type": "select",
"values": [
"always",
"hide_empty",
"never"
]
},
{
"help": "",
"hidden": false,
"id": "number1177347317",
"max": null,
"min": null,
"name": "position",
"onlyInt": false,
"presentable": false,
"required": false,
"system": false,
"type": "number"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_1666803664",
"indexes": [
"CREATE INDEX idx_workspace_properties_ws ON workspace_properties (workspace, position)"
],
"listRule": null,
"name": "workspace_properties",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
},
{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"help": "",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": true,
"collectionId": "pbc_2170078043",
"help": "",
"hidden": false,
"id": "relation2375286809",
"maxSelect": 1,
"minSelect": 0,
"name": "workspace",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1579384326",
"max": 60,
"min": 0,
"name": "name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1716930793",
"max": 20,
"min": 0,
"name": "color",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_1219621782",
"indexes": [
"CREATE UNIQUE INDEX idx_tags_name ON tags (workspace, name COLLATE NOCASE)"
],
"listRule": null,
"name": "tags",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
},
{
"createRule": null,
"deleteRule": null,
"fields": [
{
"autogeneratePattern": "[a-z0-9]{15}",
"help": "",
"hidden": false,
"id": "text3208210256",
"max": 15,
"min": 15,
"name": "id",
"pattern": "^[a-z0-9]+$",
"presentable": false,
"primaryKey": true,
"required": true,
"system": true,
"type": "text"
},
{
"cascadeDelete": true,
"collectionId": "pbc_2170078043",
"help": "",
"hidden": false,
"id": "relation2375286809",
"maxSelect": 1,
"minSelect": 0,
"name": "workspace",
"presentable": false,
"required": true,
"system": false,
"type": "relation"
},
{
"cascadeDelete": true,
"collectionId": "_pb_users_auth_",
"help": "",
"hidden": false,
"id": "relation3154569827",
"maxSelect": 1,
"minSelect": 0,
"name": "creator",
"presentable": false,
"required": false,
"system": false,
"type": "relation"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1579384326",
"max": 120,
"min": 0,
"name": "name",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": true,
"system": false,
"type": "text"
},
{
"autogeneratePattern": "",
"help": "",
"hidden": false,
"id": "text1704208859",
"max": 32,
"min": 0,
"name": "icon",
"pattern": "",
"presentable": false,
"primaryKey": false,
"required": false,
"system": false,
"type": "text"
},
{
"help": "",
"hidden": false,
"id": "json2143575837",
"maxSize": 20000,
"name": "filter",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"help": "",
"hidden": false,
"id": "json1890413707",
"maxSize": 50000,
"name": "include",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"help": "",
"hidden": false,
"id": "json1652746105",
"maxSize": 50000,
"name": "exclude",
"presentable": false,
"required": false,
"system": false,
"type": "json"
},
{
"help": "",
"hidden": false,
"id": "bool328004795",
"name": "shared",
"presentable": false,
"required": false,
"system": false,
"type": "bool"
},
{
"hidden": false,
"id": "autodate2990389176",
"name": "created",
"onCreate": true,
"onUpdate": false,
"presentable": false,
"system": false,
"type": "autodate"
},
{
"hidden": false,
"id": "autodate3332085495",
"name": "updated",
"onCreate": true,
"onUpdate": true,
"presentable": false,
"system": false,
"type": "autodate"
}
],
"id": "pbc_3673568025",
"indexes": [
"CREATE INDEX idx_page_collections_ws ON page_collections (workspace, creator)"
],
"listRule": null,
"name": "page_collections",
"system": false,
"type": "base",
"updateRule": null,
"viewRule": null
}
]
@@ -2,6 +2,7 @@
<script setup lang="ts">
import { DwButton, DwCallout, DwIcon, useTheme, type IconName, type ThemeMode } from "@docwell/ui";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { clearFileToken } from "../composables/useFiles";
import { useFormErrors } from "../composables/useFormErrors";
@@ -10,6 +11,7 @@ import { SIDEBAR_DEFAULT, clampWidth, useSidebar } from "../composables/useSideb
import { useAuthStore } from "../stores/auth";
import { useFavoritesStore } from "../stores/favorites";
import { useNotificationsStore } from "../stores/notifications";
import { useOrganizeStore } from "../stores/organize";
import { useSpacesStore } from "../stores/spaces";
import { atLeast, useWorkspacesStore } from "../stores/workspaces";
import PageTreeNode from "./PageTreeNode.vue";
@@ -25,9 +27,11 @@ const workspaces = useWorkspacesStore();
const spaces = useSpacesStore();
const favorites = useFavoritesStore();
const notifications = useNotificationsStore();
const org = useOrganizeStore();
const router = useRouter();
const route = useRoute();
const { mode } = useTheme();
const { t } = useI18n();
const errors = useFormErrors();
const sidebar = useSidebar();
@@ -48,6 +52,7 @@ watch(
if (!id) return;
spaces.load(id).catch(showError);
favorites.load(id).catch(showError);
org.load(id).catch(showError);
},
{ immediate: true },
);
@@ -78,6 +83,23 @@ const stopCommands = onCommand((c) => {
onBeforeUnmount(stopCommands);
const ws = computed(() => workspaces.current);
const canOrganize = computed(() => atLeast(ws.value?.role, "member"));
const docsActive = computed(() => route.name === "docs" && !route.query.collection);
const collectionActive = (id: string) => route.name === "docs" && route.query.collection === id;
const journalActive = computed(
() => route.name === "journal" || (route.name === "page" && spaces.space(spaces.active.space)?.journal === true),
);
async function newCollection() {
const name = prompt(t("collections.namePrompt"))?.trim();
if (!name || !ws.value) return;
try {
const c = await org.createCollection({ name });
router.push({ name: "docs", params: { id: ws.value.id }, query: { collection: c.id } });
} catch (e) {
showError(e);
}
}
const canCreateSpace = computed(() => atLeast(ws.value?.role, "admin"));
// "New page" goes into the space on screen, else the first space the user can edit.
@@ -214,6 +236,22 @@ function signOut() {
>{{ notifications.unread > 99 ? "99+" : notifications.unread }}</span
>
</RouterLink>
<RouterLink
v-if="ws"
:to="{ name: 'docs', params: { id: ws.id } }"
:class="[navRow, docsActive ? navActive : '']"
data-testid="nav-docs"
>
<DwIcon name="layers" :size="16" />{{ $t("docs.title") }}
</RouterLink>
<RouterLink
v-if="ws && canOrganize"
:to="{ name: 'journal' }"
:class="[navRow, journalActive ? navActive : '']"
data-testid="nav-journal"
>
<DwIcon name="journal" :size="16" />{{ $t("journal.title") }}
</RouterLink>
<RouterLink
v-if="ws"
:to="{ name: 'workspace-settings', params: { id: ws.id } }"
@@ -246,6 +284,45 @@ function signOut() {
</li>
</ul>
</section>
<section v-if="org.collections.length || canOrganize" data-testid="collections">
<div class="group flex h-7 items-center gap-1 rounded-sm pr-1 pl-2 hover:bg-surface-hover">
<h2 class="min-w-0 flex-1 truncate text-ui-xs font-medium text-ink-muted">
{{ $t("collections.title") }}
</h2>
<button
v-if="canOrganize"
:class="[iconLink, 'opacity-0 group-focus-within:opacity-100 group-hover:opacity-100']"
:aria-label="$t('collections.new')"
:title="$t('collections.new')"
data-testid="new-collection"
@click="newCollection"
>
<DwIcon name="plus" :size="14" />
</button>
</div>
<ul class="mt-0.5 flex flex-col gap-px">
<li v-for="c in org.collections" :key="c.id">
<RouterLink
:to="{ name: 'docs', params: { id: ws.id }, query: { collection: c.id } }"
:class="[navRow, collectionActive(c.id) ? navActive : '']"
>
<span v-if="c.icon" class="w-4 shrink-0 text-center">{{ c.icon }}</span>
<DwIcon v-else name="layers" :size="16" />
<span class="truncate">{{ c.name }}</span>
<DwIcon
v-if="!c.shared"
name="lock"
:size="12"
class="ml-auto shrink-0"
:label="$t('collections.private')"
/>
</RouterLink>
</li>
<li v-if="!org.collections.length" class="px-2 py-1 text-ui-sm text-ink-faint">
{{ $t("collections.empty") }}
</li>
</ul>
</section>
<section v-for="s in spaces.items" :key="s.id">
<div
class="group flex h-7 items-center gap-1 rounded-sm pr-1 pl-2 hover:bg-surface-hover"
@@ -274,6 +351,14 @@ function signOut() {
>
<DwIcon name="open" :size="14" />
</RouterLink>
<RouterLink
:to="{ name: 'docs', params: { id: ws.id }, query: { space: s.id } }"
:class="iconLink"
:aria-label="$t('docs.inSpace', { space: s.name })"
:title="$t('docs.inSpace', { space: s.name })"
>
<DwIcon name="layers" :size="14" />
</RouterLink>
<RouterLink
:to="{ name: 'trash', params: { id: s.id } }"
:class="iconLink"
@@ -0,0 +1,223 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { DocFilter, DocRule, Space } from "@docwell/api-client";
import { DwButton, DwIcon } from "@docwell/ui";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import {
builtinFields,
defaultValue,
fieldKind,
opNeedsValue,
opsFor,
propField,
propertyOf,
valueList,
type FieldKind,
} from "../lib/properties";
import { useOrganizeStore } from "../stores/organize";
import LabelChip from "./LabelChip.vue";
import OptionPicker, { type PickerOption } from "./OptionPicker.vue";
// Rules that narrow a list of pages: All docs filters and collection rules.
// The server applies them (directory/docs.go); this only edits them.
const props = defineProps<{
modelValue: DocFilter;
workspace: string;
spaces: Space[];
people: Record<string, string>;
}>();
const emit = defineEmits<{ "update:modelValue": [filter: DocFilter] }>();
const api = useApi();
const org = useOrganizeStore();
const { t } = useI18n();
const fields = computed(() => [
...builtinFields.map((f) => ({ id: f, label: t(`filters.fields.${f}`) })),
...org.properties.map((p) => ({ id: propField(p), label: p.name })),
]);
const kind = (r: DocRule): FieldKind => fieldKind(r.field, org.properties) ?? "text";
function set(rules: DocRule[], match = props.modelValue.match) {
emit("update:modelValue", { match, rules });
}
function patch(i: number, change: Partial<DocRule>) {
const rules = props.modelValue.rules.map((r, j) => (j === i ? { ...r, ...change } : r));
set(rules);
}
function setField(i: number, field: string) {
const k = fieldKind(field, org.properties) ?? "text";
const op = opsFor(k)[0]!;
patch(i, { field, op, value: defaultValue(k, op) });
}
function setOp(i: number, op: DocRule["op"]) {
const r = props.modelValue.rules[i]!;
const k = kind(r);
// Keep a value that still fits; date ops switch between a day and a count of days.
const keep =
opNeedsValue(op) && r.value !== undefined && (k !== "date" || (op === "withinDays") === (r.op === "withinDays"));
patch(i, { op, value: keep ? r.value : defaultValue(k, op) });
}
function addRule() {
set([...props.modelValue.rules, { field: "tags", op: "contains", value: [] }]);
}
function removeRule(i: number) {
set(props.modelValue.rules.filter((_, j) => j !== i));
}
// The choices a list rule picks from.
const peopleNames = ref<Record<string, string>>({});
const searchPeople = async (q: string): Promise<PickerOption[]> => {
const list = await api.workspaces.people(props.workspace, q, 20);
for (const u of list) peopleNames.value[u.id] = u.name;
return list.map((u) => ({ id: u.id, label: u.name || u.email, hint: u.email }));
};
function isPeople(r: DocRule) {
return (
r.field === "createdBy" || r.field === "lastEditedBy" || propertyOf(r.field, org.properties)?.type === "member"
);
}
function choices(r: DocRule): PickerOption[] {
if (r.field === "tags") return org.tags.map((x) => ({ id: x.id, label: x.name, color: x.color }));
if (r.field === "space") return props.spaces.map((s) => ({ id: s.id, label: s.name }));
const p = propertyOf(r.field, org.properties);
return p ? p.options.map((o) => ({ id: o.id, label: o.name, color: o.color })) : [];
}
function chosen(r: DocRule) {
const opts = choices(r);
return valueList(r.value).map((id) => {
const o = opts.find((x) => x.id === id);
return { id, label: o?.label ?? peopleNames.value[id] ?? props.people[id] ?? "…", color: o?.color };
});
}
function toggleChoice(i: number, id: string) {
const cur = valueList(props.modelValue.rules[i]!.value);
patch(i, { value: cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id] });
}
</script>
<template>
<div class="space-y-2" data-testid="filter-editor">
<div v-if="modelValue.rules.length > 1" class="flex items-center gap-2 text-ui-sm text-ink-muted">
<label class="flex items-center gap-2">
{{ $t("filters.matchLabel") }}
<select
class="dw-input h-7"
:value="modelValue.match"
@change="set(modelValue.rules, ($event.target as HTMLSelectElement).value as DocFilter['match'])"
>
<option value="all">{{ $t("filters.matchAll") }}</option>
<option value="any">{{ $t("filters.matchAny") }}</option>
</select>
</label>
</div>
<div
v-for="(r, i) in modelValue.rules"
:key="i"
class="flex flex-wrap items-center gap-1.5"
data-testid="filter-rule"
>
<select
class="dw-input h-7 max-w-48"
:value="r.field"
:aria-label="$t('filters.field')"
@change="setField(i, ($event.target as HTMLSelectElement).value)"
>
<option v-for="f in fields" :key="f.id" :value="f.id">{{ f.label }}</option>
<option v-if="!fields.some((f) => f.id === r.field)" :value="r.field">{{ $t("filters.deleted") }}</option>
</select>
<select
class="dw-input h-7"
:value="r.op"
:aria-label="$t('filters.op')"
@change="setOp(i, ($event.target as HTMLSelectElement).value as DocRule['op'])"
>
<option v-for="op in opsFor(kind(r))" :key="op" :value="op">{{ $t(`filters.ops.${op}`) }}</option>
</select>
<template v-if="opNeedsValue(r.op)">
<template v-if="kind(r) === 'list'">
<span class="flex flex-wrap items-center gap-1">
<LabelChip
v-for="c in chosen(r)"
:key="c.id"
:label="c.label"
:color="c.color"
removable
:remove-label="$t('properties.removeValue')"
@remove="toggleChoice(i, c.id)"
/>
<OptionPicker
:options="isPeople(r) ? [] : choices(r)"
:search="isPeople(r) ? searchPeople : undefined"
:selected="valueList(r.value)"
:label="$t('properties.pick')"
@toggle="toggleChoice(i, $event)"
/>
</span>
</template>
<template v-else-if="kind(r) === 'date' && r.op === 'withinDays'">
<label class="flex items-center gap-1 text-ui-sm text-ink-muted">
<input
type="number"
min="0"
max="3650"
class="dw-input h-7 w-20"
:value="r.value as number"
@change="patch(i, { value: Number(($event.target as HTMLInputElement).value) || 0 })"
/>
{{ $t("filters.days") }}
</label>
</template>
<input
v-else-if="kind(r) === 'date'"
type="date"
class="dw-input h-7"
:value="r.value as string"
:aria-label="$t('filters.value')"
@change="patch(i, { value: ($event.target as HTMLInputElement).value })"
/>
<input
v-else-if="kind(r) === 'number'"
type="number"
step="any"
class="dw-input h-7 w-28"
:value="r.value as number"
:aria-label="$t('filters.value')"
@change="patch(i, { value: Number(($event.target as HTMLInputElement).value) })"
/>
<select
v-else-if="kind(r) === 'bool'"
class="dw-input h-7"
:value="r.value === false ? 'no' : 'yes'"
:aria-label="$t('filters.value')"
@change="patch(i, { value: ($event.target as HTMLSelectElement).value === 'yes' })"
>
<option value="yes">{{ $t("filters.yes") }}</option>
<option value="no">{{ $t("filters.no") }}</option>
</select>
<input
v-else
class="dw-input h-7 w-48"
:value="r.value as string"
:aria-label="$t('filters.value')"
@change="patch(i, { value: ($event.target as HTMLInputElement).value })"
/>
</template>
<button
type="button"
class="grid size-6 cursor-pointer place-items-center rounded-xs text-ink-muted hover:bg-surface-hover hover:text-ink"
:aria-label="$t('filters.removeRule')"
:title="$t('filters.removeRule')"
@click="removeRule(i)"
>
<DwIcon name="close" :size="14" />
</button>
</div>
<DwButton size="sm" variant="ghost" icon="plus" data-testid="add-rule" @click="addRule">{{
$t("filters.addRule")
}}</DwButton>
</div>
</template>
@@ -0,0 +1,123 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { JournalInfo, Template } from "@docwell/api-client";
import { DwButton } from "@docwell/ui";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import { addDays, parseDay, today, weekStart } from "../lib/properties";
// A week of the signed-in person's journal: one button per day, a dot on
// the days that have a page. With settings it also picks the journal template.
const props = withDefaults(defineProps<{ workspace: string; date?: string; settings?: boolean }>(), {
date: "",
settings: false,
});
const emit = defineEmits<{ error: [err: unknown] }>();
const api = useApi();
const { locale } = useI18n();
const start = ref(weekStart(props.date || today()));
watch(
() => props.date,
(d) => (start.value = weekStart(d || today())),
);
const days = computed(() => Array.from({ length: 7 }, (_, i) => addDays(start.value, i)));
const info = ref<JournalInfo | null>(null);
const has = computed(() => new Set(info.value?.days.map((d) => d.date)));
async function load() {
try {
const from = start.value;
const res = await api.workspaces.journal(props.workspace, from, addDays(from, 6));
if (start.value === from) info.value = res;
} catch (e) {
emit("error", e);
}
}
watch([start, () => props.workspace, () => props.date], load, { immediate: true });
const weekday = (d: string) => new Intl.DateTimeFormat(locale.value, { weekday: "short" }).format(parseDay(d)!);
const dayNum = (d: string) => parseDay(d)!.getDate();
const range = computed(() => {
const f = new Intl.DateTimeFormat(locale.value, { month: "short", day: "numeric" });
return `${f.format(parseDay(days.value[0]!)!)} – ${f.format(parseDay(days.value[6]!)!)}`;
});
// The template new journal pages start from.
const templates = ref<Template[]>([]);
watch(
() => props.settings && props.workspace,
async (ws) => {
if (ws) templates.value = await api.workspaces.templates(ws).catch(() => []);
},
{ immediate: true },
);
async function setTemplate(id: string) {
try {
const res = await api.workspaces.setJournalTemplate(props.workspace, id);
if (info.value) info.value = { ...info.value, template: res.template, space: res.space };
} catch (e) {
emit("error", e);
}
}
</script>
<template>
<div data-testid="journal-strip">
<div class="flex items-center gap-1">
<DwButton
size="sm"
variant="ghost"
icon="chevron-right"
class="rotate-180"
:aria-label="$t('journal.previousWeek')"
:title="$t('journal.previousWeek')"
@click="start = addDays(start, -7)"
/>
<span class="min-w-0 flex-1 text-center text-ui-sm text-ink-muted">{{ range }}</span>
<DwButton
size="sm"
variant="ghost"
icon="chevron-right"
:aria-label="$t('journal.nextWeek')"
:title="$t('journal.nextWeek')"
@click="start = addDays(start, 7)"
/>
<RouterLink
:to="{ name: 'journal', params: { date: today() } }"
class="rounded-sm px-2 py-1 text-ui-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
>{{ $t("journal.today") }}</RouterLink
>
</div>
<ol class="mt-1 grid grid-cols-7 gap-1">
<li v-for="d in days" :key="d">
<RouterLink
:to="{ name: 'journal', params: { date: d } }"
class="flex flex-col items-center rounded-sm py-1 text-ui-sm hover:bg-surface-hover"
:class="d === date ? 'bg-surface-hover font-semibold text-ink' : 'text-ink-muted'"
:aria-current="d === date ? 'date' : undefined"
:aria-label="`${weekday(d)} ${dayNum(d)}${has.has(d) ? ` · ${$t('journal.hasPage')}` : ''}`"
>
<span class="text-ui-xs uppercase">{{ weekday(d) }}</span>
<span class="tabular-nums" :class="{ 'text-accent': d === today() }">{{ dayNum(d) }}</span>
<span class="mt-0.5 size-1 rounded-full" :class="has.has(d) ? 'bg-accent' : 'bg-transparent'" />
</RouterLink>
</li>
</ol>
<label v-if="settings" class="mt-3 flex flex-col gap-1 text-ui-sm text-ink-muted">
{{ $t("journal.template") }}
<select
class="dw-input"
:value="info?.template ?? ''"
data-testid="journal-template"
@change="setTemplate(($event.target as HTMLSelectElement).value)"
>
<option value="">{{ $t("journal.noTemplate") }}</option>
<option v-for="tpl in templates" :key="tpl.id" :value="tpl.id">
{{ tpl.icon ? `${tpl.icon} ` : "" }}{{ tpl.title || $t("home.untitled") }}
</option>
</select>
</label>
</div>
</template>
@@ -0,0 +1,29 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { LabelColor } from "@docwell/api-client";
// A tag or select option: a small rounded label in one of the palette's
// colours (editor.css defines them for both themes through data-color).
defineProps<{ label: string; color?: LabelColor; removable?: boolean; removeLabel?: string }>();
defineEmits<{ remove: [] }>();
</script>
<template>
<span
class="inline-flex max-w-full items-center gap-1 rounded-full px-2 py-px text-ui-sm leading-5"
:data-color="color || undefined"
:style="{ background: 'var(--dw-bg, var(--color-surface-hover))', color: 'var(--dw-c, var(--color-ink))' }"
>
<span class="truncate">{{ label }}</span>
<button
v-if="removable"
type="button"
class="-mr-1 grid size-4 shrink-0 cursor-pointer place-items-center rounded-full opacity-70 hover:opacity-100"
:aria-label="removeLabel"
:title="removeLabel"
@click.stop="$emit('remove')"
>
×
</button>
</span>
</template>
@@ -0,0 +1,172 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { LabelColor } from "@docwell/api-client";
import { DwIcon } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, ref, useId, watch } from "vue";
import LabelChip from "./LabelChip.vue";
export interface PickerOption {
id: string;
label: string;
color?: LabelColor;
hint?: string;
}
// A button that opens a searchable list of options (tags, select choices,
// people). With creatable, a query that matches nothing offers to make it.
// search, when set, is asked for options as the query changes (people).
const props = withDefaults(
defineProps<{
options: PickerOption[];
selected: string[];
label: string;
multiple?: boolean;
creatable?: boolean;
createLabel?: (name: string) => string;
search?: (q: string) => Promise<PickerOption[]>;
disabled?: boolean;
}>(),
{ multiple: true, creatable: false, createLabel: (n: string) => n, search: undefined, disabled: false },
);
const emit = defineEmits<{ toggle: [id: string]; create: [name: string] }>();
const open = ref(false);
const query = ref("");
const found = ref<PickerOption[] | null>(null);
const root = ref<HTMLElement | null>(null);
const input = ref<HTMLInputElement | null>(null);
const active = ref(0);
const listId = useId();
const pool = computed(() => found.value ?? props.options);
const shown = computed(() => {
const q = query.value.trim().toLowerCase();
return q && !props.search ? pool.value.filter((o) => o.label.toLowerCase().includes(q)) : pool.value;
});
const canCreate = computed(() => {
const q = query.value.trim();
return props.creatable && !!q && !props.options.some((o) => o.label.toLowerCase() === q.toLowerCase());
});
const rows = computed(() => shown.value.length + (canCreate.value ? 1 : 0));
let seq = 0;
watch(query, async (q) => {
active.value = 0;
if (!props.search || !open.value) return;
const mine = ++seq;
const list = await props.search(q.trim()).catch(() => []);
if (mine === seq) found.value = list;
});
function onDocDown(e: PointerEvent) {
if (root.value && !root.value.contains(e.target as Node)) close();
}
async function toggleOpen() {
if (open.value) return close();
open.value = true;
query.value = "";
found.value = null;
document.addEventListener("pointerdown", onDocDown);
if (props.search) found.value = await props.search("").catch(() => []);
await nextTick();
input.value?.focus();
}
function close() {
open.value = false;
document.removeEventListener("pointerdown", onDocDown);
}
onBeforeUnmount(close);
function choose(i: number) {
const o = shown.value[i];
if (o) {
emit("toggle", o.id);
if (!props.multiple) close();
} else if (canCreate.value) {
emit("create", query.value.trim());
query.value = "";
if (!props.multiple) close();
}
}
function onKey(e: KeyboardEvent) {
if (e.key === "ArrowDown") {
e.preventDefault();
active.value = (active.value + 1) % Math.max(rows.value, 1);
} else if (e.key === "ArrowUp") {
e.preventDefault();
active.value = (active.value - 1 + rows.value) % Math.max(rows.value, 1);
} else if (e.key === "Enter") {
e.preventDefault();
choose(active.value);
} else if (e.key === "Escape") {
e.preventDefault();
close();
}
}
</script>
<template>
<div ref="root" class="relative inline-block">
<slot name="trigger" :toggle="toggleOpen" :open="open">
<button
type="button"
class="flex h-6 cursor-pointer items-center gap-1 rounded-xs px-1.5 text-ui-sm text-ink-muted hover:bg-surface-hover hover:text-ink disabled:cursor-default disabled:opacity-60"
:aria-expanded="open"
:aria-controls="listId"
:disabled="disabled"
@click="toggleOpen"
>
<DwIcon name="plus" :size="14" />{{ label }}
</button>
</slot>
<div
v-if="open"
class="absolute top-full left-0 z-40 mt-1 w-64 rounded-md border border-line bg-surface-raised p-1 shadow-menu"
>
<input
ref="input"
v-model="query"
class="dw-input w-full"
:placeholder="label"
:aria-label="label"
role="combobox"
:aria-expanded="true"
:aria-controls="listId"
@keydown="onKey"
/>
<ul :id="listId" role="listbox" :aria-multiselectable="multiple" class="mt-1 max-h-64 overflow-y-auto">
<li
v-for="(o, i) in shown"
:key="o.id"
role="option"
:aria-selected="selected.includes(o.id)"
class="flex cursor-pointer items-center gap-2 rounded-xs px-2 py-1 text-ui-md"
:class="{ 'bg-surface-hover': i === active }"
@mouseenter="active = i"
@click="choose(i)"
>
<span class="grid w-4 shrink-0 place-items-center text-accent">{{ selected.includes(o.id) ? "✓" : "" }}</span>
<LabelChip v-if="o.color !== undefined" :label="o.label" :color="o.color" />
<span v-else class="min-w-0 truncate">{{ o.label }}</span>
<span v-if="o.hint" class="ml-auto truncate text-ui-xs text-ink-faint">{{ o.hint }}</span>
</li>
<li
v-if="canCreate"
role="option"
:aria-selected="false"
class="flex cursor-pointer items-center gap-2 rounded-xs px-2 py-1 text-ui-md"
:class="{ 'bg-surface-hover': active === shown.length }"
@mouseenter="active = shown.length"
@click="choose(shown.length)"
>
<DwIcon name="plus" :size="14" class="text-ink-muted" />
<span class="min-w-0 truncate">{{ createLabel(query.trim()) }}</span>
</li>
<li v-if="!rows" class="px-2 py-1 text-ui-sm text-ink-faint">{{ $t("editor.noMatches") }}</li>
</ul>
</div>
</div>
</template>
@@ -0,0 +1,368 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { Page, Property, PropertyType } from "@docwell/api-client";
import { DwButton, DwIcon } from "@docwell/ui";
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import { formatDay, localDay, valueList } from "../lib/properties";
import { useOrganizeStore } from "../stores/organize";
import LabelChip from "./LabelChip.vue";
import OptionPicker, { type PickerOption } from "./OptionPicker.vue";
// The page's Info panel: tags, the workspace's custom properties and the
// built-in ones. Under the title it follows each property's visibility;
// in the side panel (all) it shows every property.
const props = withDefaults(defineProps<{ page: Page; editable: boolean; all?: boolean }>(), { all: false });
const emit = defineEmits<{ update: [page: Page]; error: [err: unknown] }>();
const api = useApi();
const org = useOrganizeStore();
const { t, locale } = useI18n();
const busy = ref(false);
const showHidden = ref(false);
async function save(patch: Parameters<typeof api.pages.update>[1]) {
busy.value = true;
try {
emit("update", await api.pages.update(props.page.id, patch));
} catch (e) {
emit("error", e);
} finally {
busy.value = false;
}
}
// ---- Tags ----
const pageTags = computed(() => props.page.tags.map((id) => org.tag(id)).filter((x) => !!x));
const tagOptions = computed<PickerOption[]>(() => org.tags.map((x) => ({ id: x.id, label: x.name, color: x.color })));
function toggleTag(id: string) {
const has = props.page.tags.includes(id);
void save({ tags: has ? props.page.tags.filter((x) => x !== id) : [...props.page.tags, id] });
}
async function createTag(name: string) {
try {
const tag = await org.createTag(name);
await save({ tags: [...props.page.tags, tag.id] });
} catch (e) {
emit("error", e);
}
}
// ---- Custom properties ----
const value = (p: Property) => props.page.properties[p.id];
const isEmpty = (v: unknown) => v === undefined || v === null || v === "" || (Array.isArray(v) && !v.length);
const shown = computed(() =>
org.properties.filter(
(p) =>
props.all ||
showHidden.value ||
p.visibility === "always" ||
(p.visibility === "hide_empty" && !isEmpty(value(p))),
),
);
const hiddenCount = computed(() => org.properties.length - shown.value.length);
const setValue = (p: Property, v: unknown) => save({ properties: { [p.id]: isEmpty(v) ? null : v } });
function optionsOf(p: Property): PickerOption[] {
return p.options.map((o) => ({ id: o.id, label: o.name, color: o.color }));
}
function toggleOption(p: Property, id: string) {
const cur = valueList(value(p));
if (p.type === "select") return setValue(p, cur[0] === id ? null : id);
return setValue(p, cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]);
}
async function createOption(p: Property, name: string) {
try {
const updated = await org.updateProperty(p.id, { options: [...p.options, { id: "", name, color: "" }] });
const added = updated.options.find((o) => !p.options.some((x) => x.id === o.id));
if (added) await toggleOption(updated, added.id);
} catch (e) {
emit("error", e);
}
}
// People: chosen ones by name, the rest found as the query changes.
const people = ref<Record<string, string>>({});
const searchPeople = async (q: string): Promise<PickerOption[]> => {
const list = await api.workspaces.people(props.page.workspace, q, 20);
for (const u of list) people.value[u.id] = u.name;
return list.map((u) => ({ id: u.id, label: u.name || u.email, hint: u.email }));
};
const personName = (id: string) =>
people.value[id] ?? (id === props.page.createdBy.id ? props.page.createdBy.name : "");
// Names for the people already chosen (best effort).
onMounted(() => {
if (org.properties.some((p) => p.type === "member" && valueList(value(p)).length))
void searchPeople("").catch(() => {});
});
function togglePerson(p: Property, id: string) {
const cur = valueList(value(p));
void setValue(p, cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]);
}
function commitText(p: Property, e: Event) {
const v = (e.target as HTMLInputElement).value.trim();
if (v !== (value(p) ?? "")) void setValue(p, v);
}
function commitNumber(p: Property, e: Event) {
const raw = (e.target as HTMLInputElement).value;
const v = raw === "" ? null : Number(raw);
if (v === null || Number.isFinite(v)) void setValue(p, v);
}
// ---- Adding a property ----
const types: PropertyType[] = ["text", "number", "checkbox", "date", "select", "multi_select", "member", "link"];
const adding = ref(false);
const newName = ref("");
const newType = ref<PropertyType>("text");
async function addProperty() {
busy.value = true;
try {
await org.createProperty({ name: newName.value, type: newType.value });
adding.value = false;
newName.value = "";
newType.value = "text";
} catch (e) {
emit("error", e);
} finally {
busy.value = false;
}
}
const canOrganize = computed(() => props.editable);
const day = (ts: string) => formatDay(localDay(ts), locale.value);
const label = "w-32 shrink-0 truncate pt-0.5 text-ui-sm text-ink-muted";
const row = "flex min-h-7 items-start gap-3";
const field =
"min-w-0 flex-1 rounded-xs border border-transparent bg-transparent px-1.5 py-0.5 text-ui-md text-ink hover:border-line focus:border-line-strong focus:outline-none disabled:hover:border-transparent";
</script>
<template>
<div class="space-y-1" data-testid="page-properties">
<div :class="row">
<span :class="label"><DwIcon name="tag" :size="14" class="mr-1 inline" />{{ $t("properties.tags") }}</span>
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-1" data-testid="page-tags">
<RouterLink
v-for="tag in pageTags"
:key="tag.id"
:to="{ name: 'docs', params: { id: page.workspace }, query: { tag: tag.id } }"
class="max-w-full"
>
<LabelChip
:label="tag.name"
:color="tag.color"
:removable="editable"
:remove-label="$t('properties.removeTag', { name: tag.name })"
@remove="toggleTag(tag.id)"
/>
</RouterLink>
<OptionPicker
v-if="editable"
:options="tagOptions"
:selected="page.tags"
:label="$t('properties.addTag')"
creatable
:create-label="(name: string) => $t('properties.createTag', { name })"
:disabled="busy"
@toggle="toggleTag"
@create="createTag"
/>
<span v-else-if="!pageTags.length" class="px-1.5 text-ui-md text-ink-faint">{{ $t("properties.empty") }}</span>
</div>
</div>
<div v-for="p in shown" :key="p.id" :class="row" data-testid="page-property">
<span :class="label" :title="p.name">{{ p.name }}</span>
<template v-if="p.type === 'checkbox'">
<input
type="checkbox"
class="mt-1.5 ml-1.5"
:checked="value(p) === true"
:disabled="!editable || busy"
:aria-label="p.name"
@change="setValue(p, ($event.target as HTMLInputElement).checked)"
/>
</template>
<template v-else-if="p.type === 'select' || p.type === 'multi_select'">
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-1">
<template v-for="id in valueList(value(p))" :key="id">
<LabelChip
v-if="p.options.find((o) => o.id === id)"
:label="p.options.find((o) => o.id === id)!.name"
:color="p.options.find((o) => o.id === id)!.color"
:removable="editable"
:remove-label="$t('properties.removeValue')"
@remove="toggleOption(p, id)"
/>
</template>
<OptionPicker
v-if="editable"
:options="optionsOf(p)"
:selected="valueList(value(p))"
:multiple="p.type === 'multi_select'"
:label="$t('properties.pick')"
:creatable="canOrganize"
:create-label="(name: string) => $t('properties.createOption', { name })"
:disabled="busy"
@toggle="toggleOption(p, $event)"
@create="createOption(p, $event)"
/>
<span v-else-if="isEmpty(value(p))" class="px-1.5 text-ui-md text-ink-faint">{{
$t("properties.empty")
}}</span>
</div>
</template>
<template v-else-if="p.type === 'member'">
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-1">
<LabelChip
v-for="id in valueList(value(p))"
:key="id"
:label="personName(id) || '…'"
:removable="editable"
:remove-label="$t('properties.removeValue')"
@remove="togglePerson(p, id)"
/>
<OptionPicker
v-if="editable"
:options="[]"
:selected="valueList(value(p))"
:label="$t('properties.pickPerson')"
:search="searchPeople"
:disabled="busy"
@toggle="togglePerson(p, $event)"
/>
</div>
</template>
<template v-else-if="p.type === 'date'">
<input
type="date"
:class="field"
:value="(value(p) as string) ?? ''"
:disabled="!editable || busy"
:aria-label="p.name"
@change="setValue(p, ($event.target as HTMLInputElement).value)"
/>
</template>
<template v-else-if="p.type === 'number'">
<input
type="number"
step="any"
:class="field"
:value="(value(p) as number) ?? ''"
:placeholder="$t('properties.empty')"
:disabled="!editable || busy"
:aria-label="p.name"
@change="commitNumber(p, $event)"
/>
</template>
<template v-else>
<input
:type="p.type === 'link' ? 'url' : 'text'"
:class="field"
:value="(value(p) as string) ?? ''"
:placeholder="$t('properties.empty')"
:disabled="!editable || busy"
:aria-label="p.name"
maxlength="5000"
@change="commitText(p, $event)"
@keydown.enter.prevent="($event.target as HTMLInputElement).blur()"
/>
<a
v-if="p.type === 'link' && value(p)"
:href="value(p) as string"
target="_blank"
rel="noopener noreferrer"
class="grid size-6 shrink-0 place-items-center rounded-xs text-ink-muted hover:bg-surface-hover hover:text-ink"
:aria-label="$t('properties.openLink')"
:title="$t('properties.openLink')"
>
<DwIcon name="open" :size="14" />
</a>
</template>
</div>
<div :class="row">
<span :class="label">{{ $t("properties.created") }}</span>
<span class="px-1.5 text-ui-md text-ink">{{ day(page.created) }}</span>
</div>
<div :class="row">
<span :class="label">{{ $t("properties.updated") }}</span>
<span class="px-1.5 text-ui-md text-ink">{{ day(page.updated) }}</span>
</div>
<template v-if="all">
<div :class="row">
<span :class="label">{{ $t("properties.createdBy") }}</span>
<span class="px-1.5 text-ui-md text-ink">{{ page.createdBy.name || "—" }}</span>
</div>
<div :class="row">
<span :class="label">{{ $t("properties.lastEditedBy") }}</span>
<span class="px-1.5 text-ui-md text-ink">{{ page.lastEditedBy.name || "—" }}</span>
</div>
<div :class="row">
<span :class="label">{{ $t("properties.template") }}</span>
<input
type="checkbox"
class="mt-1.5 ml-1.5"
:checked="page.isTemplate"
:disabled="!editable || busy"
:aria-label="$t('properties.template')"
@change="save({ isTemplate: ($event.target as HTMLInputElement).checked })"
/>
</div>
<div :class="row">
<span :class="label">{{ $t("properties.width") }}</span>
<select
:class="field"
:value="page.fullWidth ? 'full' : 'standard'"
:disabled="!editable || busy"
:aria-label="$t('properties.width')"
@change="save({ fullWidth: ($event.target as HTMLSelectElement).value === 'full' })"
>
<option value="standard">{{ $t("properties.widthStandard") }}</option>
<option value="full">{{ $t("properties.widthFull") }}</option>
</select>
</div>
</template>
<div v-if="page.journalDate" :class="row">
<span :class="label">{{ $t("properties.journal") }}</span>
<span class="px-1.5 text-ui-md text-ink">{{ formatDay(page.journalDate, locale, "full") }}</span>
</div>
<div class="flex flex-wrap items-center gap-1 pt-1">
<button
v-if="!all && hiddenCount > 0"
type="button"
class="h-6 cursor-pointer rounded-xs px-1.5 text-ui-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
@click="showHidden = !showHidden"
>
{{ showHidden ? $t("properties.fewer") : $t("properties.more", { n: hiddenCount }) }}
</button>
<button
v-if="editable && !adding"
type="button"
class="flex h-6 cursor-pointer items-center gap-1 rounded-xs px-1.5 text-ui-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
data-testid="add-property"
@click="adding = true"
>
<DwIcon name="plus" :size="14" />{{ $t("properties.add") }}
</button>
<form v-if="adding" class="flex flex-wrap items-center gap-1" @submit.prevent="addProperty">
<input
v-model="newName"
required
maxlength="80"
class="dw-input h-7 w-40"
:placeholder="$t('properties.name')"
:aria-label="$t('properties.name')"
/>
<select v-model="newType" class="dw-input h-7" :aria-label="$t('properties.type')">
<option v-for="ty in types" :key="ty" :value="ty">{{ t(`properties.types.${ty}`) }}</option>
</select>
<DwButton size="sm" type="submit" :disabled="busy || !newName.trim()">{{ $t("properties.addShort") }}</DwButton>
<DwButton size="sm" variant="ghost" type="button" @click="adding = false">{{ $t("comments.cancel") }}</DwButton>
</form>
</div>
</div>
</template>
@@ -6,6 +6,7 @@ import { computed, nextTick, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useApi } from "../api";
import { useAuthStore } from "../stores/auth";
import { useOrganizeStore } from "../stores/organize";
import { useSpacesStore } from "../stores/spaces";
import { useWorkspacesStore } from "../stores/workspaces";
@@ -17,6 +18,7 @@ const router = useRouter();
const workspaces = useWorkspacesStore();
const spaces = useSpacesStore();
const auth = useAuthStore();
const org = useOrganizeStore();
const input = ref<HTMLInputElement | null>(null);
const q = ref("");
@@ -29,6 +31,7 @@ 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 tag = ref("");
const author = ref("");
const since = ref<"" | "day" | "week" | "month" | "year">("");
const people = ref<MemberUser[]>([]);
@@ -36,10 +39,11 @@ const sinceDays = { day: 1, week: 7, month: 30, year: 365 } as const;
const filter = computed<SearchFilter>(() => ({
space: space.value || undefined,
tag: tag.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 filtered = computed(() => !!(space.value || tag.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));
@@ -174,6 +178,17 @@ function onKey(e: KeyboardEvent) {
<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-if="org.tags.length"
v-model="tag"
class="dw-filter"
:class="{ on: tag }"
:aria-label="$t('search.tag')"
data-testid="search-tag"
>
<option value="">{{ $t("search.anyTag") }}</option>
<option v-for="tg in org.tags" :key="tg.id" :value="tg.id">{{ tg.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>
@@ -190,7 +205,7 @@ function onKey(e: KeyboardEvent) {
v-if="filtered"
type="button"
class="ml-auto text-ink-muted hover:text-ink"
@click="((space = ''), (author = ''), (since = ''))"
@click="((space = ''), (tag = ''), (author = ''), (since = ''))"
>
{{ $t("search.clear") }}
</button>
@@ -0,0 +1,225 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { LabelColor, Property, PropertyOption, PropertyType, PropertyVisibility } from "@docwell/api-client";
import { DwButton, DwCallout, DwIcon } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useFormErrors } from "../composables/useFormErrors";
import { labelColors, useOrganizeStore } from "../stores/organize";
import LabelChip from "./LabelChip.vue";
// Workspace settings: the custom properties every page can fill in, their
// order, whether the Info panel shows them, and select choices.
const props = defineProps<{ workspace: string; canEdit: boolean }>();
const org = useOrganizeStore();
const { t } = useI18n();
const errors = useFormErrors();
const types: PropertyType[] = ["text", "number", "checkbox", "date", "select", "multi_select", "member", "link"];
const visibilities: PropertyVisibility[] = ["always", "hide_empty", "never"];
const newName = ref("");
const newType = ref<PropertyType>("text");
const open = ref<string | null>(null);
const newOption = ref("");
const busy = ref(false);
onMounted(() => {
if (org.workspace !== props.workspace) org.load(props.workspace).catch(errors.show);
});
async function run(action: () => Promise<unknown>) {
busy.value = true;
errors.reset();
try {
await action();
return true;
} catch (e) {
errors.show(e);
return false;
} finally {
busy.value = false;
}
}
async function create() {
if (await run(() => org.createProperty({ name: newName.value, type: newType.value }))) newName.value = "";
}
async function rename(p: Property, e: Event) {
const name = (e.target as HTMLInputElement).value.trim();
if (name && name !== p.name) await run(() => org.updateProperty(p.id, { name }));
}
const setType = (p: Property, type: PropertyType) => {
if (confirm(t("properties.settings.confirmType"))) void run(() => org.updateProperty(p.id, { type }));
};
const setVisibility = (p: Property, visibility: PropertyVisibility) =>
run(() => org.updateProperty(p.id, { visibility }));
async function remove(p: Property) {
if (confirm(t("properties.settings.confirmDelete", { name: p.name }))) await run(() => org.removeProperty(p.id));
}
// Moving swaps positions with the neighbour.
async function moveBy(p: Property, step: number) {
const list = org.properties;
const i = list.indexOf(p);
const other = list[i + step];
if (!other) return;
await run(async () => {
await org.updateProperty(p.id, { position: other.position });
await org.updateProperty(other.id, { position: p.position === other.position ? p.position + step : p.position });
});
}
const setOptions = (p: Property, options: PropertyOption[]) => run(() => org.updateProperty(p.id, { options }));
async function addOption(p: Property) {
const name = newOption.value.trim();
if (name && (await setOptions(p, [...p.options, { id: "", name, color: "" }]))) newOption.value = "";
}
const recolor = (p: Property, o: PropertyOption, color: LabelColor) =>
setOptions(
p,
p.options.map((x) => (x.id === o.id ? { ...x, color } : x)),
);
const renameOption = (p: Property, o: PropertyOption, e: Event) => {
const name = (e.target as HTMLInputElement).value.trim();
if (name && name !== o.name)
void setOptions(
p,
p.options.map((x) => (x.id === o.id ? { ...x, name } : x)),
);
};
const removeOption = (p: Property, o: PropertyOption) =>
setOptions(
p,
p.options.filter((x) => x.id !== o.id),
);
const hasOptions = (p: Property) => p.type === "select" || p.type === "multi_select";
</script>
<template>
<section class="dw-card" data-testid="workspace-properties">
<h2 class="text-ui-lg">{{ $t("properties.settings.title") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("properties.settings.hint") }}</p>
<DwCallout v-if="errors.message.value" tone="danger" size="ui" class="mt-3">{{ errors.message.value }}</DwCallout>
<form v-if="canEdit" class="mt-4 flex flex-wrap gap-2" @submit.prevent="create">
<input
v-model="newName"
required
maxlength="80"
:placeholder="$t('properties.name')"
:aria-label="$t('properties.name')"
class="dw-input min-w-48 flex-1"
/>
<select v-model="newType" class="dw-input" :aria-label="$t('properties.type')">
<option v-for="ty in types" :key="ty" :value="ty">{{ $t(`properties.types.${ty}`) }}</option>
</select>
<DwButton type="submit" :disabled="busy || !newName.trim()">{{ $t("properties.add") }}</DwButton>
</form>
<p v-if="errors.fields.value.name" class="mt-1 text-ui-sm text-danger">{{ errors.fields.value.name }}</p>
<ul class="mt-4 divide-y divide-line">
<li v-for="(p, i) in org.properties" :key="p.id" class="py-2" data-testid="property">
<div class="flex flex-wrap items-center gap-2">
<input
class="dw-input min-w-40 flex-1"
:value="p.name"
maxlength="80"
:readonly="!canEdit"
:aria-label="$t('properties.name')"
@change="rename(p, $event)"
/>
<select
class="dw-input"
:value="p.type"
:disabled="!canEdit || busy"
:aria-label="$t('properties.type')"
@change="setType(p, ($event.target as HTMLSelectElement).value as PropertyType)"
>
<option v-for="ty in types" :key="ty" :value="ty">{{ $t(`properties.types.${ty}`) }}</option>
</select>
<select
class="dw-input"
:value="p.visibility"
:disabled="!canEdit || busy"
:aria-label="$t('properties.settings.visibility')"
@change="setVisibility(p, ($event.target as HTMLSelectElement).value as PropertyVisibility)"
>
<option v-for="v in visibilities" :key="v" :value="v">{{ $t(`properties.visibility.${v}`) }}</option>
</select>
<template v-if="canEdit">
<DwButton
size="sm"
variant="ghost"
icon="arrow-up"
:disabled="busy || i === 0"
:aria-label="$t('properties.settings.moveUp')"
@click="moveBy(p, -1)"
/>
<DwButton
size="sm"
variant="ghost"
icon="arrow-down"
:disabled="busy || i === org.properties.length - 1"
:aria-label="$t('properties.settings.moveDown')"
@click="moveBy(p, 1)"
/>
<button
v-if="hasOptions(p)"
class="text-ui-md text-ink-muted hover:text-ink hover:underline"
:aria-expanded="open === p.id"
@click="open = open === p.id ? null : p.id"
>
{{ $t("properties.settings.options", { n: p.options.length }) }}
</button>
<button class="text-ui-md text-danger hover:underline" :disabled="busy" @click="remove(p)">
{{ $t("properties.settings.delete") }}
</button>
</template>
</div>
<div v-if="open === p.id && hasOptions(p)" class="mt-2 space-y-2 rounded-sm bg-surface-sunken p-3">
<div v-for="o in p.options" :key="o.id" class="flex flex-wrap items-center gap-2">
<LabelChip :label="o.name" :color="o.color" />
<input
class="dw-input h-7 min-w-32 flex-1"
:value="o.name"
maxlength="60"
@change="renameOption(p, o, $event)"
/>
<span class="flex gap-0.5" role="group" :aria-label="$t('properties.settings.color')">
<button
v-for="c in labelColors"
:key="c || 'none'"
type="button"
class="dw-swatch dw-swatch--fill"
:class="{ 'dw-swatch--none': !c }"
:data-color="c || undefined"
:aria-pressed="o.color === c"
:aria-label="c ? $t(`editor.colors.${c}`) : $t('properties.settings.noColor')"
:title="c ? $t(`editor.colors.${c}`) : $t('properties.settings.noColor')"
@click="recolor(p, o, c)"
/>
</span>
<button
class="grid size-6 place-items-center text-ink-muted hover:text-danger"
:aria-label="$t('properties.settings.deleteOption', { name: o.name })"
@click="removeOption(p, o)"
>
<DwIcon name="close" :size="14" />
</button>
</div>
<form class="flex gap-2" @submit.prevent="addOption(p)">
<input
v-model="newOption"
maxlength="60"
class="dw-input h-7 flex-1"
:placeholder="$t('properties.settings.newOption')"
:aria-label="$t('properties.settings.newOption')"
/>
<DwButton size="sm" type="submit" :disabled="busy || !newOption.trim()">{{ $t("workspace.add") }}</DwButton>
</form>
</div>
</li>
<li v-if="!org.properties.length" class="py-2 text-ui-md text-ink-muted">{{ $t("properties.settings.none") }}</li>
</ul>
</section>
</template>
@@ -0,0 +1,140 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { LabelColor, Tag } from "@docwell/api-client";
import { DwButton, DwCallout } from "@docwell/ui";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { useFormErrors } from "../composables/useFormErrors";
import { labelColors, useOrganizeStore } from "../stores/organize";
import LabelChip from "./LabelChip.vue";
// Workspace settings: the tags pages share. Rename, recolour, merge one into
// another, or delete (which takes it off every page).
const props = defineProps<{ workspace: string; canEdit: boolean }>();
const org = useOrganizeStore();
const { t } = useI18n();
const errors = useFormErrors();
const newName = ref("");
const newColor = ref<LabelColor>("");
const busy = ref(false);
const merging = ref<string | null>(null);
const mergeInto = ref("");
onMounted(() => {
if (org.workspace !== props.workspace) org.load(props.workspace).catch(errors.show);
});
async function run(action: () => Promise<unknown>) {
busy.value = true;
errors.reset();
try {
await action();
return true;
} catch (e) {
errors.show(e);
return false;
} finally {
busy.value = false;
}
}
async function create() {
if (await run(() => org.createTag(newName.value.trim(), newColor.value))) newName.value = "";
}
async function rename(tag: Tag, e: Event) {
const name = (e.target as HTMLInputElement).value.trim();
if (name && name !== tag.name) await run(() => org.updateTag(tag.id, { name }));
}
const recolor = (tag: Tag, color: LabelColor) => run(() => org.updateTag(tag.id, { color }));
async function remove(tag: Tag) {
if (confirm(t("tags.confirmDelete", { name: tag.name, n: tag.pages }, tag.pages)))
await run(() => org.removeTag(tag.id));
}
async function merge(tag: Tag) {
const into = org.tag(mergeInto.value);
if (!into || !confirm(t("tags.confirmMerge", { from: tag.name, into: into.name }))) return;
if (await run(() => org.mergeTag(tag.id, into.id))) merging.value = null;
}
</script>
<template>
<section class="dw-card" data-testid="workspace-tags">
<h2 class="text-ui-lg">{{ $t("tags.title") }}</h2>
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("tags.hint") }}</p>
<DwCallout v-if="errors.message.value" tone="danger" size="ui" class="mt-3">{{ errors.message.value }}</DwCallout>
<form v-if="canEdit" class="mt-4 flex flex-wrap gap-2" @submit.prevent="create">
<input
v-model="newName"
required
maxlength="60"
:placeholder="$t('tags.name')"
:aria-label="$t('tags.name')"
class="dw-input min-w-48 flex-1"
/>
<DwButton type="submit" :disabled="busy || !newName.trim()">{{ $t("tags.create") }}</DwButton>
</form>
<ul class="mt-4 divide-y divide-line">
<li v-for="tag in org.tags" :key="tag.id" class="py-2" data-testid="tag">
<div class="flex flex-wrap items-center gap-2">
<RouterLink :to="{ name: 'docs', params: { id: workspace }, query: { tag: tag.id } }">
<LabelChip :label="tag.name" :color="tag.color" />
</RouterLink>
<span class="text-ui-sm text-ink-muted tabular-nums">{{
$t("tags.pages", { n: tag.pages }, tag.pages)
}}</span>
<template v-if="canEdit">
<input
class="dw-input h-7 min-w-32 flex-1"
:value="tag.name"
maxlength="60"
:aria-label="$t('tags.name')"
@change="rename(tag, $event)"
/>
<span class="flex gap-0.5" role="group" :aria-label="$t('properties.settings.color')">
<button
v-for="c in labelColors"
:key="c || 'none'"
type="button"
class="dw-swatch dw-swatch--fill"
:class="{ 'dw-swatch--none': !c }"
:data-color="c || undefined"
:aria-pressed="tag.color === c"
:aria-label="c ? $t(`editor.colors.${c}`) : $t('properties.settings.noColor')"
:title="c ? $t(`editor.colors.${c}`) : $t('properties.settings.noColor')"
:disabled="busy"
@click="recolor(tag, c)"
/>
</span>
<button
v-if="org.tags.length > 1"
class="text-ui-md text-ink-muted hover:text-ink hover:underline"
:aria-expanded="merging === tag.id"
@click="((merging = merging === tag.id ? null : tag.id), (mergeInto = ''))"
>
{{ $t("tags.merge") }}
</button>
<button class="text-ui-md text-danger hover:underline" :disabled="busy" @click="remove(tag)">
{{ $t("tags.delete") }}
</button>
</template>
</div>
<form v-if="merging === tag.id" class="mt-2 flex flex-wrap items-center gap-2" @submit.prevent="merge(tag)">
<label class="flex items-center gap-2 text-ui-sm text-ink-muted">
{{ $t("tags.mergeInto", { name: tag.name }) }}
<select v-model="mergeInto" class="dw-input h-7" required>
<option value="" disabled>{{ $t("properties.pick") }}</option>
<option v-for="o in org.tags.filter((x) => x.id !== tag.id)" :key="o.id" :value="o.id">
{{ o.name }}
</option>
</select>
</label>
<DwButton size="sm" type="submit" :disabled="busy || !mergeInto">{{ $t("tags.merge") }}</DwButton>
</form>
</li>
<li v-if="!org.tags.length" class="py-2 text-ui-md text-ink-muted">{{ $t("tags.none") }}</li>
</ul>
</section>
</template>
+123
View File
@@ -0,0 +1,123 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { DocItem, Property } from "@docwell/api-client";
import { describe, expect, it } from "vitest";
import {
addDays,
compareDocs,
fieldKind,
groupDocs,
opsFor,
valueText,
weekStart,
type ValueContext,
} from "./properties";
const status: Property = {
id: "st",
workspace: "w",
name: "Status",
type: "select",
options: [
{ id: "todo", name: "To do", color: "gray" },
{ id: "done", name: "Done", color: "green" },
],
visibility: "always",
position: 0,
};
const owner: Property = { ...status, id: "ow", name: "Owner", type: "member", options: [] };
const props = [status, owner];
const ctx: ValueContext = {
tags: [
{ id: "t1", name: "Beta", color: "blue", pages: 1 },
{ id: "t2", name: "Alpha", color: "", pages: 1 },
],
people: { u1: "Ann", u2: "Bo" },
spaces: { s1: "Docs" },
locale: "en",
};
function doc(id: string, patch: Partial<DocItem> = {}): DocItem {
return {
id,
title: id,
icon: "",
space: "s1",
spaceName: "Docs",
parent: "",
created: "2026-11-01 10:00:00.000Z",
updated: "2026-11-10 10:00:00.000Z",
createdBy: "u1",
lastEditedBy: "u1",
isTemplate: false,
journalDate: "",
fullWidth: false,
tags: [],
properties: {},
role: "editor",
...patch,
};
}
describe("rule fields", () => {
it("knows each field's kind and ops", () => {
expect(fieldKind("tags", props)).toBe("list");
expect(fieldKind("prop:st", props)).toBe("list");
expect(fieldKind("prop:gone", props)).toBeUndefined();
expect(opsFor("date")[0]).toBe("withinDays");
expect(opsFor("bool")).toEqual(["is"]);
});
});
describe("values", () => {
it("prints options and people by name", () => {
expect(valueText(status, "done", ctx)).toBe("Done");
expect(valueText(owner, ["u2", "u1"], ctx)).toBe("Bo, Ann");
expect(valueText(status, undefined, ctx)).toBe("");
});
});
describe("grouping", () => {
it("puts a page in every tag's group, untagged last", () => {
const groups = groupDocs([doc("a", { tags: ["t1", "t2"] }), doc("b")], "tags", props, ctx);
expect(groups.map((g) => [g.group.label, g.items.map((d) => d.id)])).toEqual([
["Alpha", ["a"]],
["Beta", ["a"]],
["", ["b"]],
]);
});
it("groups by a select property", () => {
const groups = groupDocs(
[doc("a", { properties: { st: "done" } }), doc("b", { properties: { st: "todo" } })],
"prop:st",
props,
ctx,
);
expect(groups.map((g) => g.group.label)).toEqual(["Done", "To do"]);
});
it("orders date groups newest first", () => {
const groups = groupDocs(
[doc("old", { created: "2026-01-05 10:00:00.000Z" }), doc("new", { created: "2026-11-05 10:00:00.000Z" })],
"created",
props,
ctx,
);
expect(groups.map((g) => g.items[0]!.id)).toEqual(["new", "old"]);
});
});
describe("ordering and days", () => {
it("orders by title with untitled pages last", () => {
const list = [doc("b", { title: "" }), doc("a", { title: "zeta" }), doc("c", { title: "Alpha" })];
expect(list.sort((x, y) => compareDocs(x, y, "title", false)).map((d) => d.id)).toEqual(["c", "a", "b"]);
});
it("finds the week's Monday", () => {
expect(weekStart("2026-11-14")).toBe("2026-11-09");
expect(weekStart("2026-11-09")).toBe("2026-11-09");
expect(addDays("2026-12-31", 1)).toBe("2027-01-01");
});
});
+298
View File
@@ -0,0 +1,298 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { DocItem, DocRule, LabelColor, Property, Tag } from "@docwell/api-client";
/**
* Helpers for page properties, the All docs view and collection rules. The
* server evaluates the rules (directory/docs.go); these only describe them
* for the editors and group, order and print the results.
*/
export type FieldKind = "text" | "list" | "date" | "number" | "bool";
export type RuleOp = DocRule["op"];
/** Built-in fields every page has, in the order pickers list them. */
export const builtinFields = [
"title",
"space",
"tags",
"created",
"updated",
"createdBy",
"lastEditedBy",
"template",
"journal",
] as const;
export type BuiltinField = (typeof builtinFields)[number];
const builtinKinds: Record<BuiltinField, FieldKind> = {
title: "text",
space: "list",
tags: "list",
created: "date",
updated: "date",
createdBy: "list",
lastEditedBy: "list",
template: "bool",
journal: "date",
};
export const propField = (p: Pick<Property, "id">) => `prop:${p.id}`;
export function propertyOf(field: string, props: Property[]): Property | undefined {
return field.startsWith("prop:") ? props.find((p) => p.id === field.slice(5)) : undefined;
}
/** What a field's values look like to rules; undefined for a deleted property. */
export function fieldKind(field: string, props: Property[]): FieldKind | undefined {
if (field in builtinKinds) return builtinKinds[field as BuiltinField];
const p = propertyOf(field, props);
if (!p) return undefined;
switch (p.type) {
case "number":
return "number";
case "checkbox":
return "bool";
case "date":
return "date";
case "select":
case "multi_select":
case "member":
return "list";
}
return "text";
}
/** The ops a rule on a field of this kind can use, the first being the default. */
export function opsFor(kind: FieldKind): RuleOp[] {
switch (kind) {
case "text":
return ["contains", "notContains", "is", "isNot", "empty", "notEmpty"];
case "list":
return ["contains", "notContains", "empty", "notEmpty"];
case "date":
return ["withinDays", "after", "before", "is", "empty", "notEmpty"];
case "number":
return ["gt", "lt", "is", "isNot", "empty", "notEmpty"];
case "bool":
return ["is"];
}
}
/** Whether a rule with op needs a value at all. */
export const opNeedsValue = (op: RuleOp) => op !== "empty" && op !== "notEmpty";
/** A new rule's starting value for its field and op. */
export function defaultValue(kind: FieldKind, op: RuleOp): unknown {
if (!opNeedsValue(op)) return undefined;
switch (kind) {
case "list":
return [];
case "number":
return 0;
case "bool":
return true;
case "date":
return op === "withinDays" ? 7 : today();
}
return "";
}
/** The local calendar date of d as YYYY-MM-DD. */
export function isoDay(d: Date): string {
const p = (n: number) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
export const today = () => isoDay(new Date());
/** The day of a PocketBase timestamp ("2026-11-14 08:00:00.000Z") in local time. */
export function localDay(ts: string): string {
if (!ts) return "";
const d = new Date(ts.replace(" ", "T"));
return Number.isNaN(d.getTime()) ? ts.slice(0, 10) : isoDay(d);
}
/** Midnight local time of a YYYY-MM-DD day. */
export function parseDay(day: string): Date | null {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(day);
if (!m) return null;
const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
return isoDay(d) === day ? d : null;
}
export function addDays(day: string, n: number): string {
const d = parseDay(day);
if (!d) return day;
d.setDate(d.getDate() + n);
return isoDay(d);
}
/** The Monday of day's week. */
export function weekStart(day: string): string {
const d = parseDay(day);
if (!d) return day;
return addDays(day, -((d.getDay() + 6) % 7));
}
export function formatDay(day: string, locale: string, style: "medium" | "full" = "medium"): string {
const d = parseDay(day);
return d ? new Intl.DateTimeFormat(locale, { dateStyle: style }).format(d) : day;
}
/** What the apps know to print a value: tags, people and spaces by id. */
export interface ValueContext {
tags: Tag[];
people: Record<string, string>;
spaces: Record<string, string>;
locale: string;
}
/** A value read from a page's properties, as a list of strings (empty when unset). */
export function valueList(raw: unknown): string[] {
if (Array.isArray(raw)) return raw.filter((v): v is string => typeof v === "string");
return typeof raw === "string" && raw ? [raw] : [];
}
/** A property value as readable text ("" when unset). */
export function valueText(p: Property, raw: unknown, ctx: ValueContext): string {
if (raw === undefined || raw === null || raw === "") return "";
switch (p.type) {
case "number":
return typeof raw === "number" ? new Intl.NumberFormat(ctx.locale).format(raw) : "";
case "checkbox":
return raw === true ? "✓" : "";
case "date":
return typeof raw === "string" ? formatDay(raw, ctx.locale) : "";
case "select":
case "multi_select":
return valueList(raw)
.map((id) => p.options.find((o) => o.id === id)?.name)
.filter(Boolean)
.join(", ");
case "member":
return valueList(raw)
.map((id) => ctx.people[id] ?? "?")
.join(", ");
}
return typeof raw === "string" ? raw : "";
}
/** A label shown in a group header or chip. */
export interface Label {
key: string;
label: string;
color?: LabelColor;
}
export type GroupBy =
"" | "space" | "tags" | "createdBy" | "lastEditedBy" | "created" | "updated" | "template" | string;
const month = (ts: string, locale: string) => {
const d = parseDay(localDay(ts));
return d
? {
key: isoDay(d).slice(0, 7),
label: new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(d),
}
: { key: "", label: "" };
};
/**
* The groups a page goes in. Pages with several tags or options appear in
* each; pages without a value go in the "" group, which callers name.
*/
export function groupsOf(d: DocItem, by: GroupBy, props: Property[], ctx: ValueContext): Label[] {
const none: Label[] = [{ key: "", label: "" }];
switch (by) {
case "":
return none;
case "space":
return [{ key: d.space, label: d.spaceName }];
case "tags": {
const tags = d.tags.map((id) => ctx.tags.find((t) => t.id === id)).filter((t): t is Tag => !!t);
return tags.length ? tags.map((t) => ({ key: t.id, label: t.name, color: t.color })) : none;
}
case "createdBy":
case "lastEditedBy": {
const id = d[by];
return id ? [{ key: id, label: ctx.people[id] ?? "?" }] : none;
}
case "created":
case "updated":
return [month(d[by], ctx.locale)];
case "template":
return [{ key: d.isTemplate ? "yes" : "", label: d.isTemplate ? "✓" : "" }];
}
const p = propertyOf(by, props);
if (!p) return none;
const raw = d.properties[p.id];
switch (p.type) {
case "select":
case "multi_select": {
const opts = valueList(raw)
.map((id) => p.options.find((o) => o.id === id))
.filter((o) => !!o);
return opts.length ? opts.map((o) => ({ key: o.id, label: o.name, color: o.color })) : none;
}
case "member": {
const ids = valueList(raw);
return ids.length ? ids.map((id) => ({ key: id, label: ctx.people[id] ?? "?" })) : none;
}
case "date":
return typeof raw === "string" && raw ? [{ key: raw.slice(0, 7), label: month(raw, ctx.locale).label }] : none;
}
const text = valueText(p, raw, ctx);
return text ? [{ key: text, label: text }] : none;
}
/** Fields the All docs view can group by: built-ins, then properties that group well. */
export function groupableFields(props: Property[]): string[] {
return [
"space",
"tags",
"createdBy",
"lastEditedBy",
"created",
"updated",
"template",
...props.filter((p) => p.type !== "text" && p.type !== "link").map(propField),
];
}
export type OrderBy = "updated" | "created" | "title";
export function compareDocs(a: DocItem, b: DocItem, by: OrderBy, desc: boolean): number {
let c: number;
if (by === "title") c = (a.title || "￿").localeCompare(b.title || "￿", undefined, { sensitivity: "base" });
else c = a[by] < b[by] ? -1 : a[by] > b[by] ? 1 : 0;
if (desc) c = -c;
return c || a.id.localeCompare(b.id);
}
/**
* Splits docs into ordered groups. Groups come in order of their label, the
* empty group last; dates (created, updated, date properties) newest first.
*/
export function groupDocs(
docs: DocItem[],
by: GroupBy,
props: Property[],
ctx: ValueContext,
): { group: Label; items: DocItem[] }[] {
const groups = new Map<string, { group: Label; items: DocItem[] }>();
for (const d of docs) {
for (const g of groupsOf(d, by, props, ctx)) {
const entry = groups.get(g.key) ?? { group: g, items: [] };
entry.items.push(d);
groups.set(g.key, entry);
}
}
const byDate = by === "created" || by === "updated" || propertyOf(by, props)?.type === "date";
return [...groups.values()].sort((x, y) => {
if (!x.group.key) return 1;
if (!y.group.key) return -1;
if (byDate) return y.group.key.localeCompare(x.group.key);
return x.group.label.localeCompare(y.group.label, undefined, { sensitivity: "base" });
});
}
+187 -3
View File
@@ -121,7 +121,9 @@
},
"common": {
"back": "Zurück",
"save": "Speichern"
"save": "Speichern",
"close": "Schließen",
"done": "Fertig"
},
"roles": {
"user": "Benutzer",
@@ -344,7 +346,9 @@
"pastWeek": "Letzte Woche",
"pastMonth": "Letzter Monat",
"pastYear": "Letztes Jahr",
"clear": "Filter zurücksetzen"
"clear": "Filter zurücksetzen",
"tag": "Tag",
"anyTag": "Alle Tags"
},
"share": {
"button": "Teilen",
@@ -406,7 +410,8 @@
"remindMe": "Erinnere mich",
"reminderAt": "Erinnerung um 9:00 am Tag",
"someoneElse": "Jemand anderes hat für dieses Datum eine Erinnerung gesetzt.",
"edit": "Datum ändern"
"edit": "Datum ändern",
"openJournal": "Journal öffnen"
},
"slashMenu": "Block einfügen",
"noMatches": "Keine passenden Blöcke",
@@ -778,5 +783,184 @@
"change": "Server wechseln",
"manage": "Server verwalten",
"signedInTo": "Angemeldet bei {url}"
},
"properties": {
"title": "Eigenschaften",
"info": "Info",
"tags": "Tags",
"addTag": "Tag hinzufügen",
"createTag": "Tag „{name}“ anlegen",
"removeTag": "Tag {name} entfernen",
"removeValue": "Entfernen",
"empty": "Leer",
"pick": "Auswählen",
"pickPerson": "Person hinzufügen",
"createOption": "Option „{name}“ hinzufügen",
"openLink": "Link öffnen",
"more": "{n} weitere",
"fewer": "Weniger Eigenschaften",
"add": "Eigenschaft hinzufügen",
"addShort": "Hinzufügen",
"name": "Name der Eigenschaft",
"type": "Typ",
"created": "Erstellt",
"updated": "Geändert",
"createdBy": "Erstellt von",
"lastEditedBy": "Zuletzt bearbeitet von",
"template": "Vorlage",
"journal": "Journal",
"width": "Seitenbreite",
"widthStandard": "Standard",
"widthFull": "Volle Breite",
"types": {
"text": "Text",
"number": "Zahl",
"checkbox": "Kontrollkästchen",
"date": "Datum",
"select": "Auswahl",
"multi_select": "Mehrfachauswahl",
"member": "Person",
"link": "Link"
},
"visibility": {
"always": "Immer anzeigen",
"hide_empty": "Anzeigen, wenn ausgefüllt",
"never": "Nur im Info-Bereich"
},
"settings": {
"title": "Seiteneigenschaften",
"hint": "Jede Seite im Arbeitsbereich kann sie ausfüllen. Sie stehen unter dem Seitentitel und in Alle Dokumente, wo Seiten danach gruppiert und gefiltert werden können.",
"none": "Noch keine Eigenschaften.",
"visibility": "Unter dem Titel angezeigt",
"moveUp": "Nach oben",
"moveDown": "Nach unten",
"options": "Optionen ({n})",
"newOption": "Neue Option",
"deleteOption": "Option {name} löschen",
"color": "Farbe",
"noColor": "Keine Farbe",
"delete": "Löschen",
"confirmDelete": "Eigenschaft „{name}“ löschen? Die Seiten verlieren ihre Werte dafür.",
"confirmType": "Typ ändern? Werte, die nicht zum neuen Typ passen, gehen verloren."
}
},
"tags": {
"title": "Tags",
"hint": "Farbige Markierungen für Seiten. Ein Tag öffnet alle seine Seiten.",
"name": "Name des Tags",
"create": "Tag hinzufügen",
"none": "Noch keine Tags.",
"pages": "{n} Seite | {n} Seiten",
"merge": "Zusammenführen",
"mergeInto": "Seiten von {name} verschieben nach",
"confirmMerge": "Alle Seiten von „{from}“ nach „{into}“ verschieben und „{from}“ löschen?",
"delete": "Löschen",
"confirmDelete": "Tag „{name}“ löschen? Er wird von {n} Seite entfernt. | Tag „{name}“ löschen? Er wird von {n} Seiten entfernt."
},
"docs": {
"title": "Alle Dokumente",
"inSpace": "Alle Dokumente in {space}",
"tagged": "Mit Tag {tag}",
"count": "{n} Seite | {n} Seiten",
"allTags": "Alle",
"none": "Hier gibt es noch keine Seiten.",
"noneFiltered": "Keine Seiten passen.",
"filter": "Filter",
"layout": "Ansicht",
"layouts": {
"list": "Liste",
"grid": "Raster",
"cards": "Karten"
},
"groupBy": "Gruppieren",
"noGroup": "Keine",
"noValue": "Ohne {field}",
"order": "Sortieren",
"orders": {
"updated": "Zuletzt geändert",
"created": "Erstellt",
"title": "Titel"
},
"ascending": "Aufsteigend",
"descending": "Absteigend",
"columns": "Eigenschaften",
"selectAll": "Alle auswählen",
"select": "{title} auswählen",
"selected": "{n} ausgewählt | {n} ausgewählt",
"clearSelection": "Aufheben",
"moveTo": "Verschieben nach",
"topLevel": "Oberste Ebene von {space}",
"confirmTrash": "{n} Seite in den Papierkorb verschieben? | {n} Seiten in den Papierkorb verschieben?"
},
"filters": {
"field": "Eigenschaft",
"op": "Bedingung",
"value": "Wert",
"deleted": "Gelöschte Eigenschaft",
"addRule": "Regel hinzufügen",
"removeRule": "Regel entfernen",
"matchLabel": "Seiten erfüllen",
"matchAll": "alle Regeln",
"matchAny": "eine der Regeln",
"days": "Tagen",
"yes": "Ja",
"no": "Nein",
"fields": {
"title": "Titel",
"space": "Bereich",
"tags": "Tags",
"created": "Erstellt",
"updated": "Zuletzt geändert",
"createdBy": "Erstellt von",
"lastEditedBy": "Zuletzt bearbeitet von",
"template": "Vorlage",
"journal": "Journaltag"
},
"ops": {
"is": "ist",
"isNot": "ist nicht",
"contains": "enthält",
"notContains": "enthält nicht",
"before": "vor",
"after": "nach",
"withinDays": "in den letzten",
"gt": "mehr als",
"lt": "weniger als",
"empty": "ist leer",
"notEmpty": "ist nicht leer"
}
},
"collections": {
"title": "Sammlungen",
"new": "Neue Sammlung",
"namePrompt": "Name der Sammlung",
"empty": "Noch keine Sammlungen.",
"private": "Nur du",
"privateNote": "Nur du siehst diese Sammlung.",
"sharedNote": "Alle im Arbeitsbereich sehen diese Sammlung.",
"share": "Mit dem Arbeitsbereich teilen",
"makePrivate": "Privat machen",
"rename": "Umbenennen",
"delete": "Löschen",
"confirmDelete": "Sammlung „{name}“ löschen? Ihre Seiten bleiben, wo sie sind.",
"rules": "Regeln",
"rulesHint": "Seiten, die diese Regeln erfüllen, gehören zur Sammlung, dazu die von Hand hinzugefügten.",
"saveRules": "Regeln speichern",
"revert": "Verwerfen",
"saveAs": "Als Sammlung speichern",
"addTo": "Zu Sammlung hinzufügen",
"removeFrom": "Aus Sammlung entfernen",
"byHandHint": "Angehakte Seiten sind von Hand hinzugefügt; Regeln können weitere aufnehmen."
},
"journal": {
"title": "Journal",
"today": "Heute",
"previousWeek": "Vorige Woche",
"nextWeek": "Nächste Woche",
"hasPage": "hat eine Seite",
"template": "Neue Journalseiten beginnen mit",
"noTemplate": "Einer leeren Seite",
"opening": "Journal wird geöffnet…",
"failed": "Das Journal konnte nicht geöffnet werden."
}
}
+187 -3
View File
@@ -121,7 +121,9 @@
},
"common": {
"back": "Back",
"save": "Save"
"save": "Save",
"close": "Close",
"done": "Done"
},
"roles": {
"user": "User",
@@ -344,7 +346,9 @@
"pastWeek": "Past week",
"pastMonth": "Past month",
"pastYear": "Past year",
"clear": "Clear filters"
"clear": "Clear filters",
"tag": "Tag",
"anyTag": "Any tag"
},
"share": {
"button": "Share",
@@ -406,7 +410,8 @@
"remindMe": "Remind me",
"reminderAt": "Reminder at 9:00 on the day",
"someoneElse": "Someone else set a reminder on this date.",
"edit": "Change date"
"edit": "Change date",
"openJournal": "Open journal"
},
"slashMenu": "Insert block",
"noMatches": "No matching blocks",
@@ -778,5 +783,184 @@
"change": "Change server",
"manage": "Manage servers",
"signedInTo": "Signed in to {url}"
},
"properties": {
"title": "Properties",
"info": "Info",
"tags": "Tags",
"addTag": "Add tag",
"createTag": "Create tag “{name}”",
"removeTag": "Remove the tag {name}",
"removeValue": "Remove",
"empty": "Empty",
"pick": "Choose",
"pickPerson": "Add person",
"createOption": "Add option “{name}”",
"openLink": "Open link",
"more": "{n} more",
"fewer": "Fewer properties",
"add": "Add property",
"addShort": "Add",
"name": "Property name",
"type": "Type",
"created": "Created",
"updated": "Updated",
"createdBy": "Created by",
"lastEditedBy": "Last edited by",
"template": "Template",
"journal": "Journal",
"width": "Page width",
"widthStandard": "Standard",
"widthFull": "Full width",
"types": {
"text": "Text",
"number": "Number",
"checkbox": "Checkbox",
"date": "Date",
"select": "Select",
"multi_select": "Multi-select",
"member": "Person",
"link": "Link"
},
"visibility": {
"always": "Always show",
"hide_empty": "Show when filled in",
"never": "Only in the Info panel"
},
"settings": {
"title": "Page properties",
"hint": "Every page in the workspace can fill these in. They show under the page title and in All docs, where pages can be grouped and filtered by them.",
"none": "No properties yet.",
"visibility": "Shown under the title",
"moveUp": "Move up",
"moveDown": "Move down",
"options": "Options ({n})",
"newOption": "New option",
"deleteOption": "Delete the option {name}",
"color": "Colour",
"noColor": "No colour",
"delete": "Delete",
"confirmDelete": "Delete the property “{name}”? Pages lose their values for it.",
"confirmType": "Change the type? Values that do not fit the new type are dropped."
}
},
"tags": {
"title": "Tags",
"hint": "Coloured labels for pages. Open a tag to see all of its pages.",
"name": "Tag name",
"create": "Add tag",
"none": "No tags yet.",
"pages": "{n} page | {n} pages",
"merge": "Merge",
"mergeInto": "Move the pages of {name} to",
"confirmMerge": "Move every page from “{from}” to “{into}” and delete “{from}”?",
"delete": "Delete",
"confirmDelete": "Delete the tag “{name}”? It comes off {n} page. | Delete the tag “{name}”? It comes off {n} pages."
},
"docs": {
"title": "All docs",
"inSpace": "All docs in {space}",
"tagged": "Tagged {tag}",
"count": "{n} page | {n} pages",
"allTags": "All",
"none": "No pages here yet.",
"noneFiltered": "No pages match.",
"filter": "Filter",
"layout": "Layout",
"layouts": {
"list": "List",
"grid": "Grid",
"cards": "Cards"
},
"groupBy": "Group",
"noGroup": "None",
"noValue": "No {field}",
"order": "Order",
"orders": {
"updated": "Last changed",
"created": "Created",
"title": "Title"
},
"ascending": "Ascending",
"descending": "Descending",
"columns": "Properties",
"selectAll": "Select all",
"select": "Select {title}",
"selected": "{n} selected | {n} selected",
"clearSelection": "Clear",
"moveTo": "Move to",
"topLevel": "Top of {space}",
"confirmTrash": "Move {n} page to the trash? | Move {n} pages to the trash?"
},
"filters": {
"field": "Property",
"op": "Condition",
"value": "Value",
"deleted": "Deleted property",
"addRule": "Add rule",
"removeRule": "Remove rule",
"matchLabel": "Pages match",
"matchAll": "all rules",
"matchAny": "any rule",
"days": "days",
"yes": "Yes",
"no": "No",
"fields": {
"title": "Title",
"space": "Space",
"tags": "Tags",
"created": "Created",
"updated": "Last changed",
"createdBy": "Created by",
"lastEditedBy": "Last edited by",
"template": "Template",
"journal": "Journal day"
},
"ops": {
"is": "is",
"isNot": "is not",
"contains": "contains",
"notContains": "does not contain",
"before": "before",
"after": "after",
"withinDays": "in the last",
"gt": "more than",
"lt": "less than",
"empty": "is empty",
"notEmpty": "is not empty"
}
},
"collections": {
"title": "Collections",
"new": "New collection",
"namePrompt": "Name of the collection",
"empty": "No collections yet.",
"private": "Only you",
"privateNote": "Only you see this collection.",
"sharedNote": "Everyone in the workspace sees this collection.",
"share": "Share with the workspace",
"makePrivate": "Make private",
"rename": "Rename",
"delete": "Delete",
"confirmDelete": "Delete the collection “{name}”? Its pages stay where they are.",
"rules": "Rules",
"rulesHint": "Pages that match these rules are in the collection, with the pages added by hand.",
"saveRules": "Save rules",
"revert": "Discard",
"saveAs": "Save as collection",
"addTo": "Add to collection",
"removeFrom": "Remove from collection",
"byHandHint": "Ticked pages are added by hand; rules can add more."
},
"journal": {
"title": "Journal",
"today": "Today",
"previousWeek": "Previous week",
"nextWeek": "Next week",
"hasPage": "has a page",
"template": "New journal pages start from",
"noTemplate": "An empty page",
"opening": "Opening the journal…",
"failed": "The journal could not be opened."
}
}
+187 -3
View File
@@ -121,7 +121,9 @@
},
"common": {
"back": "Atrás",
"save": "Guardar"
"save": "Guardar",
"close": "Cerrar",
"done": "Listo"
},
"roles": {
"user": "Usuario",
@@ -344,7 +346,9 @@
"pastWeek": "Última semana",
"pastMonth": "Último mes",
"pastYear": "Último año",
"clear": "Quitar filtros"
"clear": "Quitar filtros",
"tag": "Etiqueta",
"anyTag": "Cualquier etiqueta"
},
"share": {
"button": "Compartir",
@@ -406,7 +410,8 @@
"remindMe": "Recuérdamelo",
"reminderAt": "Recordatorio a las 9:00 de ese día",
"someoneElse": "Otra persona puso un recordatorio en esta fecha.",
"edit": "Cambiar fecha"
"edit": "Cambiar fecha",
"openJournal": "Abrir el diario"
},
"slashMenu": "Insertar bloque",
"noMatches": "No hay bloques que coincidan",
@@ -778,5 +783,184 @@
"change": "Cambiar de servidor",
"manage": "Gestionar servidores",
"signedInTo": "Sesión iniciada en {url}"
},
"properties": {
"title": "Propiedades",
"info": "Información",
"tags": "Etiquetas",
"addTag": "Añadir etiqueta",
"createTag": "Crear la etiqueta «{name}»",
"removeTag": "Quitar la etiqueta {name}",
"removeValue": "Quitar",
"empty": "Vacío",
"pick": "Elegir",
"pickPerson": "Añadir persona",
"createOption": "Añadir la opción «{name}»",
"openLink": "Abrir enlace",
"more": "{n} más",
"fewer": "Menos propiedades",
"add": "Añadir propiedad",
"addShort": "Añadir",
"name": "Nombre de la propiedad",
"type": "Tipo",
"created": "Creada",
"updated": "Modificada",
"createdBy": "Creada por",
"lastEditedBy": "Editada por última vez por",
"template": "Plantilla",
"journal": "Diario",
"width": "Ancho de página",
"widthStandard": "Estándar",
"widthFull": "Ancho completo",
"types": {
"text": "Texto",
"number": "Número",
"checkbox": "Casilla",
"date": "Fecha",
"select": "Selección",
"multi_select": "Selección múltiple",
"member": "Persona",
"link": "Enlace"
},
"visibility": {
"always": "Mostrar siempre",
"hide_empty": "Mostrar si tiene valor",
"never": "Solo en el panel de información"
},
"settings": {
"title": "Propiedades de página",
"hint": "Todas las páginas del espacio de trabajo pueden rellenarlas. Aparecen bajo el título de la página y en Todos los documentos, donde las páginas se pueden agrupar y filtrar por ellas.",
"none": "Todavía no hay propiedades.",
"visibility": "Se muestra bajo el título",
"moveUp": "Subir",
"moveDown": "Bajar",
"options": "Opciones ({n})",
"newOption": "Nueva opción",
"deleteOption": "Eliminar la opción {name}",
"color": "Color",
"noColor": "Sin color",
"delete": "Eliminar",
"confirmDelete": "¿Eliminar la propiedad «{name}»? Las páginas pierden sus valores.",
"confirmType": "¿Cambiar el tipo? Los valores que no encajen con el nuevo tipo se descartan."
}
},
"tags": {
"title": "Etiquetas",
"hint": "Marcas de color para las páginas. Abre una etiqueta para ver todas sus páginas.",
"name": "Nombre de la etiqueta",
"create": "Añadir etiqueta",
"none": "Todavía no hay etiquetas.",
"pages": "{n} página | {n} páginas",
"merge": "Combinar",
"mergeInto": "Pasar las páginas de {name} a",
"confirmMerge": "¿Pasar todas las páginas de «{from}» a «{into}» y eliminar «{from}»?",
"delete": "Eliminar",
"confirmDelete": "¿Eliminar la etiqueta «{name}»? Se quita de {n} página. | ¿Eliminar la etiqueta «{name}»? Se quita de {n} páginas."
},
"docs": {
"title": "Todos los documentos",
"inSpace": "Todos los documentos de {space}",
"tagged": "Con la etiqueta {tag}",
"count": "{n} página | {n} páginas",
"allTags": "Todas",
"none": "Todavía no hay páginas aquí.",
"noneFiltered": "Ninguna página coincide.",
"filter": "Filtro",
"layout": "Vista",
"layouts": {
"list": "Lista",
"grid": "Cuadrícula",
"cards": "Tarjetas"
},
"groupBy": "Agrupar",
"noGroup": "Sin agrupar",
"noValue": "Sin {field}",
"order": "Ordenar",
"orders": {
"updated": "Último cambio",
"created": "Creación",
"title": "Título"
},
"ascending": "Ascendente",
"descending": "Descendente",
"columns": "Propiedades",
"selectAll": "Seleccionar todo",
"select": "Seleccionar {title}",
"selected": "{n} seleccionada | {n} seleccionadas",
"clearSelection": "Quitar selección",
"moveTo": "Mover a",
"topLevel": "Nivel superior de {space}",
"confirmTrash": "¿Mover {n} página a la papelera? | ¿Mover {n} páginas a la papelera?"
},
"filters": {
"field": "Propiedad",
"op": "Condición",
"value": "Valor",
"deleted": "Propiedad eliminada",
"addRule": "Añadir regla",
"removeRule": "Quitar regla",
"matchLabel": "Las páginas cumplen",
"matchAll": "todas las reglas",
"matchAny": "alguna regla",
"days": "días",
"yes": "Sí",
"no": "No",
"fields": {
"title": "Título",
"space": "Espacio",
"tags": "Etiquetas",
"created": "Creación",
"updated": "Último cambio",
"createdBy": "Creada por",
"lastEditedBy": "Editada por última vez por",
"template": "Plantilla",
"journal": "Día del diario"
},
"ops": {
"is": "es",
"isNot": "no es",
"contains": "contiene",
"notContains": "no contiene",
"before": "antes del",
"after": "después del",
"withinDays": "en los últimos",
"gt": "mayor que",
"lt": "menor que",
"empty": "está vacío",
"notEmpty": "no está vacío"
}
},
"collections": {
"title": "Colecciones",
"new": "Nueva colección",
"namePrompt": "Nombre de la colección",
"empty": "Todavía no hay colecciones.",
"private": "Solo tú",
"privateNote": "Solo tú ves esta colección.",
"sharedNote": "Todo el espacio de trabajo ve esta colección.",
"share": "Compartir con el espacio de trabajo",
"makePrivate": "Hacer privada",
"rename": "Cambiar nombre",
"delete": "Eliminar",
"confirmDelete": "¿Eliminar la colección «{name}»? Sus páginas se quedan donde están.",
"rules": "Reglas",
"rulesHint": "Las páginas que cumplen estas reglas están en la colección, junto con las añadidas a mano.",
"saveRules": "Guardar reglas",
"revert": "Descartar",
"saveAs": "Guardar como colección",
"addTo": "Añadir a una colección",
"removeFrom": "Quitar de la colección",
"byHandHint": "Las páginas marcadas se añaden a mano; las reglas pueden añadir más."
},
"journal": {
"title": "Diario",
"today": "Hoy",
"previousWeek": "Semana anterior",
"nextWeek": "Semana siguiente",
"hasPage": "tiene página",
"template": "Las páginas nuevas del diario empiezan con",
"noTemplate": "Una página vacía",
"opening": "Abriendo el diario…",
"failed": "No se pudo abrir el diario."
}
}
+187 -3
View File
@@ -121,7 +121,9 @@
},
"common": {
"back": "Retour",
"save": "Enregistrer"
"save": "Enregistrer",
"close": "Fermer",
"done": "Terminé"
},
"roles": {
"user": "Utilisateur",
@@ -344,7 +346,9 @@
"pastWeek": "Semaine dernière",
"pastMonth": "Mois dernier",
"pastYear": "Année dernière",
"clear": "Effacer les filtres"
"clear": "Effacer les filtres",
"tag": "Étiquette",
"anyTag": "Toutes les étiquettes"
},
"share": {
"button": "Partager",
@@ -406,7 +410,8 @@
"remindMe": "Me le rappeler",
"reminderAt": "Rappel à 9 h 00 le jour même",
"someoneElse": "Quelqu’un d’autre a mis un rappel sur cette date.",
"edit": "Changer la date"
"edit": "Changer la date",
"openJournal": "Ouvrir le journal"
},
"slashMenu": "Insérer un bloc",
"noMatches": "Aucun bloc correspondant",
@@ -778,5 +783,184 @@
"change": "Changer de serveur",
"manage": "Gérer les serveurs",
"signedInTo": "Connecté à {url}"
},
"properties": {
"title": "Propriétés",
"info": "Infos",
"tags": "Étiquettes",
"addTag": "Ajouter une étiquette",
"createTag": "Créer l’étiquette « {name} »",
"removeTag": "Retirer l’étiquette {name}",
"removeValue": "Retirer",
"empty": "Vide",
"pick": "Choisir",
"pickPerson": "Ajouter une personne",
"createOption": "Ajouter l’option « {name} »",
"openLink": "Ouvrir le lien",
"more": "{n} de plus",
"fewer": "Moins de propriétés",
"add": "Ajouter une propriété",
"addShort": "Ajouter",
"name": "Nom de la propriété",
"type": "Type",
"created": "Créée",
"updated": "Modifiée",
"createdBy": "Créée par",
"lastEditedBy": "Modifiée en dernier par",
"template": "Modèle",
"journal": "Journal",
"width": "Largeur de page",
"widthStandard": "Standard",
"widthFull": "Pleine largeur",
"types": {
"text": "Texte",
"number": "Nombre",
"checkbox": "Case à cocher",
"date": "Date",
"select": "Choix",
"multi_select": "Choix multiple",
"member": "Personne",
"link": "Lien"
},
"visibility": {
"always": "Toujours afficher",
"hide_empty": "Afficher si renseignée",
"never": "Seulement dans le panneau Infos"
},
"settings": {
"title": "Propriétés des pages",
"hint": "Chaque page de l’espace de travail peut les renseigner. Elles apparaissent sous le titre de la page et dans Tous les documents, où l’on peut grouper et filtrer les pages par elles.",
"none": "Aucune propriété pour l’instant.",
"visibility": "Affichée sous le titre",
"moveUp": "Monter",
"moveDown": "Descendre",
"options": "Options ({n})",
"newOption": "Nouvelle option",
"deleteOption": "Supprimer l’option {name}",
"color": "Couleur",
"noColor": "Sans couleur",
"delete": "Supprimer",
"confirmDelete": "Supprimer la propriété « {name} » ? Les pages perdent leurs valeurs.",
"confirmType": "Changer le type ? Les valeurs qui ne conviennent pas au nouveau type sont abandonnées."
}
},
"tags": {
"title": "Étiquettes",
"hint": "Des marques de couleur pour les pages. Ouvrez une étiquette pour voir toutes ses pages.",
"name": "Nom de l’étiquette",
"create": "Ajouter une étiquette",
"none": "Aucune étiquette pour l’instant.",
"pages": "{n} page | {n} pages",
"merge": "Fusionner",
"mergeInto": "Déplacer les pages de {name} vers",
"confirmMerge": "Déplacer toutes les pages de « {from} » vers « {into} » et supprimer « {from} » ?",
"delete": "Supprimer",
"confirmDelete": "Supprimer l’étiquette « {name} » ? Elle est retirée de {n} page. | Supprimer l’étiquette « {name} » ? Elle est retirée de {n} pages."
},
"docs": {
"title": "Tous les documents",
"inSpace": "Tous les documents de {space}",
"tagged": "Étiquetés {tag}",
"count": "{n} page | {n} pages",
"allTags": "Toutes",
"none": "Aucune page ici pour l’instant.",
"noneFiltered": "Aucune page ne correspond.",
"filter": "Filtre",
"layout": "Affichage",
"layouts": {
"list": "Liste",
"grid": "Grille",
"cards": "Cartes"
},
"groupBy": "Grouper",
"noGroup": "Aucun",
"noValue": "Sans {field}",
"order": "Trier",
"orders": {
"updated": "Dernière modification",
"created": "Création",
"title": "Titre"
},
"ascending": "Croissant",
"descending": "Décroissant",
"columns": "Propriétés",
"selectAll": "Tout sélectionner",
"select": "Sélectionner {title}",
"selected": "{n} sélectionnée | {n} sélectionnées",
"clearSelection": "Désélectionner",
"moveTo": "Déplacer vers",
"topLevel": "Haut de {space}",
"confirmTrash": "Mettre {n} page à la corbeille ? | Mettre {n} pages à la corbeille ?"
},
"filters": {
"field": "Propriété",
"op": "Condition",
"value": "Valeur",
"deleted": "Propriété supprimée",
"addRule": "Ajouter une règle",
"removeRule": "Retirer la règle",
"matchLabel": "Les pages respectent",
"matchAll": "toutes les règles",
"matchAny": "une des règles",
"days": "jours",
"yes": "Oui",
"no": "Non",
"fields": {
"title": "Titre",
"space": "Espace",
"tags": "Étiquettes",
"created": "Création",
"updated": "Dernière modification",
"createdBy": "Créée par",
"lastEditedBy": "Modifiée en dernier par",
"template": "Modèle",
"journal": "Jour du journal"
},
"ops": {
"is": "est",
"isNot": "n’est pas",
"contains": "contient",
"notContains": "ne contient pas",
"before": "avant le",
"after": "après le",
"withinDays": "dans les derniers",
"gt": "supérieur à",
"lt": "inférieur à",
"empty": "est vide",
"notEmpty": "n’est pas vide"
}
},
"collections": {
"title": "Collections",
"new": "Nouvelle collection",
"namePrompt": "Nom de la collection",
"empty": "Aucune collection pour l’instant.",
"private": "Vous seul",
"privateNote": "Vous seul voyez cette collection.",
"sharedNote": "Tout l’espace de travail voit cette collection.",
"share": "Partager avec l’espace de travail",
"makePrivate": "Rendre privée",
"rename": "Renommer",
"delete": "Supprimer",
"confirmDelete": "Supprimer la collection « {name} » ? Ses pages restent où elles sont.",
"rules": "Règles",
"rulesHint": "Les pages qui respectent ces règles font partie de la collection, avec celles ajoutées à la main.",
"saveRules": "Enregistrer les règles",
"revert": "Annuler",
"saveAs": "Enregistrer comme collection",
"addTo": "Ajouter à une collection",
"removeFrom": "Retirer de la collection",
"byHandHint": "Les pages cochées sont ajoutées à la main ; les règles peuvent en ajouter d’autres."
},
"journal": {
"title": "Journal",
"today": "Aujourd’hui",
"previousWeek": "Semaine précédente",
"nextWeek": "Semaine suivante",
"hasPage": "a une page",
"template": "Les nouvelles pages du journal partent de",
"noTemplate": "Une page vide",
"opening": "Ouverture du journal…",
"failed": "Le journal n’a pas pu être ouvert."
}
}
+187 -3
View File
@@ -121,7 +121,9 @@
},
"common": {
"back": "Wstecz",
"save": "Zapisz"
"save": "Zapisz",
"close": "Zamknij",
"done": "Gotowe"
},
"roles": {
"user": "Użytkownik",
@@ -344,7 +346,9 @@
"pastWeek": "Ostatni tydzień",
"pastMonth": "Ostatni miesiąc",
"pastYear": "Ostatni rok",
"clear": "Wyczyść filtry"
"clear": "Wyczyść filtry",
"tag": "Tag",
"anyTag": "Dowolny tag"
},
"share": {
"button": "Udostępnij",
@@ -406,7 +410,8 @@
"remindMe": "Przypomnij mi",
"reminderAt": "Przypomnienie o 9:00 tego dnia",
"someoneElse": "Ktoś inny ustawił przypomnienie na tę datę.",
"edit": "Zmień datę"
"edit": "Zmień datę",
"openJournal": "Otwórz dziennik"
},
"slashMenu": "Wstaw blok",
"noMatches": "Brak pasujących bloków",
@@ -778,5 +783,184 @@
"change": "Zmień serwer",
"manage": "Zarządzaj serwerami",
"signedInTo": "Zalogowano do {url}"
},
"properties": {
"title": "Właściwości",
"info": "Informacje",
"tags": "Tagi",
"addTag": "Dodaj tag",
"createTag": "Utwórz tag „{name}”",
"removeTag": "Usuń tag {name}",
"removeValue": "Usuń",
"empty": "Puste",
"pick": "Wybierz",
"pickPerson": "Dodaj osobę",
"createOption": "Dodaj opcję „{name}”",
"openLink": "Otwórz link",
"more": "Jeszcze {n}",
"fewer": "Mniej właściwości",
"add": "Dodaj właściwość",
"addShort": "Dodaj",
"name": "Nazwa właściwości",
"type": "Typ",
"created": "Utworzono",
"updated": "Zmieniono",
"createdBy": "Utworzył(a)",
"lastEditedBy": "Ostatnio edytował(a)",
"template": "Szablon",
"journal": "Dziennik",
"width": "Szerokość strony",
"widthStandard": "Standardowa",
"widthFull": "Pełna szerokość",
"types": {
"text": "Tekst",
"number": "Liczba",
"checkbox": "Pole wyboru",
"date": "Data",
"select": "Wybór",
"multi_select": "Wielokrotny wybór",
"member": "Osoba",
"link": "Link"
},
"visibility": {
"always": "Zawsze pokazuj",
"hide_empty": "Pokazuj, gdy wypełniona",
"never": "Tylko w panelu informacji"
},
"settings": {
"title": "Właściwości stron",
"hint": "Każda strona w obszarze roboczym może je wypełnić. Widać je pod tytułem strony i we Wszystkich dokumentach, gdzie można według nich grupować i filtrować strony.",
"none": "Nie ma jeszcze właściwości.",
"visibility": "Widoczna pod tytułem",
"moveUp": "Przenieś wyżej",
"moveDown": "Przenieś niżej",
"options": "Opcje ({n})",
"newOption": "Nowa opcja",
"deleteOption": "Usuń opcję {name}",
"color": "Kolor",
"noColor": "Bez koloru",
"delete": "Usuń",
"confirmDelete": "Usunąć właściwość „{name}”? Strony stracą jej wartości.",
"confirmType": "Zmienić typ? Wartości niepasujące do nowego typu przepadną."
}
},
"tags": {
"title": "Tagi",
"hint": "Kolorowe etykiety stron. Otwórz tag, aby zobaczyć wszystkie jego strony.",
"name": "Nazwa tagu",
"create": "Dodaj tag",
"none": "Nie ma jeszcze tagów.",
"pages": "{n} strona | {n} strony | {n} stron",
"merge": "Scal",
"mergeInto": "Przenieś strony z {name} do",
"confirmMerge": "Przenieść wszystkie strony z „{from}” do „{into}” i usunąć „{from}”?",
"delete": "Usuń",
"confirmDelete": "Usunąć tag „{name}”? Zniknie z {n} strony. | Usunąć tag „{name}”? Zniknie z {n} stron. | Usunąć tag „{name}”? Zniknie z {n} stron."
},
"docs": {
"title": "Wszystkie dokumenty",
"inSpace": "Wszystkie dokumenty w {space}",
"tagged": "Z tagiem {tag}",
"count": "{n} strona | {n} strony | {n} stron",
"allTags": "Wszystkie",
"none": "Nie ma tu jeszcze stron.",
"noneFiltered": "Żadna strona nie pasuje.",
"filter": "Filtr",
"layout": "Widok",
"layouts": {
"list": "Lista",
"grid": "Siatka",
"cards": "Karty"
},
"groupBy": "Grupuj",
"noGroup": "Brak",
"noValue": "Bez: {field}",
"order": "Sortuj",
"orders": {
"updated": "Ostatnia zmiana",
"created": "Utworzenie",
"title": "Tytuł"
},
"ascending": "Rosnąco",
"descending": "Malejąco",
"columns": "Właściwości",
"selectAll": "Zaznacz wszystkie",
"select": "Zaznacz {title}",
"selected": "Zaznaczono {n} | Zaznaczono {n} | Zaznaczono {n}",
"clearSelection": "Odznacz",
"moveTo": "Przenieś do",
"topLevel": "Najwyższy poziom: {space}",
"confirmTrash": "Przenieść {n} stronę do kosza? | Przenieść {n} strony do kosza? | Przenieść {n} stron do kosza?"
},
"filters": {
"field": "Właściwość",
"op": "Warunek",
"value": "Wartość",
"deleted": "Usunięta właściwość",
"addRule": "Dodaj regułę",
"removeRule": "Usuń regułę",
"matchLabel": "Strony spełniają",
"matchAll": "wszystkie reguły",
"matchAny": "dowolną regułę",
"days": "dni",
"yes": "Tak",
"no": "Nie",
"fields": {
"title": "Tytuł",
"space": "Przestrzeń",
"tags": "Tagi",
"created": "Utworzenie",
"updated": "Ostatnia zmiana",
"createdBy": "Utworzył(a)",
"lastEditedBy": "Ostatnio edytował(a)",
"template": "Szablon",
"journal": "Dzień dziennika"
},
"ops": {
"is": "to",
"isNot": "to nie",
"contains": "zawiera",
"notContains": "nie zawiera",
"before": "przed",
"after": "po",
"withinDays": "w ostatnich",
"gt": "więcej niż",
"lt": "mniej niż",
"empty": "jest puste",
"notEmpty": "nie jest puste"
}
},
"collections": {
"title": "Kolekcje",
"new": "Nowa kolekcja",
"namePrompt": "Nazwa kolekcji",
"empty": "Nie ma jeszcze kolekcji.",
"private": "Tylko ty",
"privateNote": "Tylko ty widzisz tę kolekcję.",
"sharedNote": "Cały obszar roboczy widzi tę kolekcję.",
"share": "Udostępnij obszarowi roboczemu",
"makePrivate": "Ustaw jako prywatną",
"rename": "Zmień nazwę",
"delete": "Usuń",
"confirmDelete": "Usunąć kolekcję „{name}”? Jej strony zostaną na swoich miejscach.",
"rules": "Reguły",
"rulesHint": "Strony spełniające te reguły należą do kolekcji, razem ze stronami dodanymi ręcznie.",
"saveRules": "Zapisz reguły",
"revert": "Odrzuć",
"saveAs": "Zapisz jako kolekcję",
"addTo": "Dodaj do kolekcji",
"removeFrom": "Usuń z kolekcji",
"byHandHint": "Zaznaczone strony są dodane ręcznie; reguły mogą dodać kolejne."
},
"journal": {
"title": "Dziennik",
"today": "Dziś",
"previousWeek": "Poprzedni tydzień",
"nextWeek": "Następny tydzień",
"hasPage": "ma stronę",
"template": "Nowe strony dziennika zaczynają się od",
"noTemplate": "Pustej strony",
"opening": "Otwieranie dziennika…",
"failed": "Nie udało się otworzyć dziennika."
}
}
+4
View File
@@ -35,6 +35,10 @@ export function createDocwellRouter(platform: Platform) {
props: true,
},
{ path: "notifications", name: "notifications", component: () => import("./views/NotificationsView.vue") },
// All docs of a workspace; ?space=, ?tag= or ?collection= narrow it.
{ path: "w/:id/docs", name: "docs", component: () => import("./views/docs/DocsView.vue"), props: true },
// The signed-in person's journal page for a day (today without one).
{ path: "journal/:date?", name: "journal", component: () => import("./views/JournalView.vue"), props: true },
],
},
{
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {
Collection,
CollectionInput,
LabelColor,
Property,
PropertyInput,
Tag,
TagInput,
} from "@docwell/api-client";
import { defineStore } from "pinia";
import { ref } from "vue";
import { useApi } from "../api";
/** The current workspace's page properties, tags and collections. */
export const useOrganizeStore = defineStore("organize", () => {
const api = useApi();
const workspace = ref("");
const properties = ref<Property[]>([]);
const tags = ref<Tag[]>([]);
const collections = ref<Collection[]>([]);
async function load(wsId: string) {
if (workspace.value !== wsId) {
workspace.value = wsId;
properties.value = [];
tags.value = [];
collections.value = [];
}
await Promise.all([loadProperties(), loadTags(), loadCollections()]);
}
// Each loader drops its answer if the workspace changed meanwhile.
async function loadProperties() {
const ws = workspace.value;
const list = await api.workspaces.properties(ws);
if (workspace.value === ws) properties.value = list;
}
async function loadTags() {
const ws = workspace.value;
const list = await api.workspaces.tags(ws);
if (workspace.value === ws) tags.value = list;
}
async function loadCollections() {
const ws = workspace.value;
const list = await api.workspaces.collections(ws);
if (workspace.value === ws) collections.value = list;
}
const tag = (id: string) => tags.value.find((t) => t.id === id);
const property = (id: string) => properties.value.find((p) => p.id === id);
const collection = (id: string) => collections.value.find((c) => c.id === id);
async function createTag(name: string, color: LabelColor = "") {
const t = await api.workspaces.createTag(workspace.value, { name, color });
await loadTags();
return t;
}
async function updateTag(id: string, patch: TagInput) {
await api.tags.update(id, patch);
await loadTags();
}
async function removeTag(id: string) {
await api.tags.remove(id);
await loadTags();
}
async function mergeTag(id: string, into: string) {
await api.tags.merge(id, into);
await loadTags();
}
async function createProperty(input: PropertyInput) {
const p = await api.workspaces.createProperty(workspace.value, input);
await loadProperties();
return p;
}
async function updateProperty(id: string, patch: PropertyInput) {
const p = await api.properties.update(id, patch);
await loadProperties();
return p;
}
async function removeProperty(id: string) {
await api.properties.remove(id);
await loadProperties();
}
async function createCollection(input: CollectionInput) {
const c = await api.workspaces.createCollection(workspace.value, input);
await loadCollections();
return c;
}
async function updateCollection(id: string, patch: CollectionInput) {
const c = await api.collections.update(id, patch);
await loadCollections();
return c;
}
async function removeCollection(id: string) {
await api.collections.remove(id);
await loadCollections();
}
async function setCollectionPage(id: string, page: string, on: boolean) {
const c = await api.collections.setPage(id, page, on);
await loadCollections();
return c;
}
return {
workspace,
properties,
tags,
collections,
load,
loadProperties,
loadTags,
loadCollections,
tag,
property,
collection,
createTag,
updateTag,
removeTag,
mergeTag,
createProperty,
updateProperty,
removeProperty,
createCollection,
updateCollection,
removeCollection,
setCollectionPage,
};
});
/** The colours tags and options can have (the editor's palette). */
export const labelColors: LabelColor[] = [
"",
"gray",
"red",
"orange",
"yellow",
"green",
"teal",
"blue",
"purple",
"pink",
];
@@ -0,0 +1,47 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import { DwCallout } from "@docwell/ui";
import { ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { useApi } from "../api";
import { formatDay, parseDay, today } from "../lib/properties";
import { useSpacesStore } from "../stores/spaces";
import { useWorkspacesStore } from "../stores/workspaces";
// /journal/<date>: opens the signed-in person's journal page for that day in
// the current workspace (today without a date), making it the first time.
const props = defineProps<{ date?: string }>();
const api = useApi();
const router = useRouter();
const workspaces = useWorkspacesStore();
const spaces = useSpacesStore();
const { locale } = useI18n();
const error = ref("");
watch(
[() => props.date, () => workspaces.current?.id],
async ([date, ws]) => {
if (!ws) return;
const day = date && parseDay(date) ? date : today();
error.value = "";
try {
const page = await api.workspaces.openJournal(ws, day, formatDay(day, locale.value, "full"));
// A new journal space or page appears in the sidebar.
if (!spaces.space(page.space)) await spaces.load(ws);
else await spaces.loadTree(page.space);
router.replace({ name: "page", params: { id: page.id } });
} catch (e) {
error.value = e instanceof Error ? e.message : String(e);
}
},
{ immediate: true },
);
</script>
<template>
<div class="mx-auto max-w-doc px-4 pt-10">
<DwCallout v-if="error" tone="danger" size="ui">{{ $t("journal.failed") }}</DwCallout>
<p v-else class="text-ui-md text-ink-muted" role="status">{{ $t("journal.opening") }}</p>
</div>
</template>
@@ -0,0 +1,704 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import type { DocFilter, DocItem, DocList, LabelColor } from "@docwell/api-client";
import { DwButton, DwCallout, DwIcon } from "@docwell/ui";
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { useApi } from "../../api";
import FilterEditor from "../../components/FilterEditor.vue";
import LabelChip from "../../components/LabelChip.vue";
import OptionPicker, { type PickerOption } from "../../components/OptionPicker.vue";
import {
compareDocs,
formatDay,
groupableFields,
groupDocs,
localDay,
propertyOf,
propField,
valueList,
valueText,
type OrderBy,
type ValueContext,
} from "../../lib/properties";
import { useAuthStore } from "../../stores/auth";
import { useOrganizeStore } from "../../stores/organize";
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
import { atLeast, useWorkspacesStore } from "../../stores/workspaces";
// All docs: every page of the workspace the caller can open, or one space's,
// one tag's or one collection's, laid out as a list, a grid or cards,
// grouped and ordered by any property.
const props = defineProps<{ id: string }>();
const emit = defineEmits<{ error: [err: unknown] }>();
const api = useApi();
const org = useOrganizeStore();
const spaces = useSpacesStore();
const workspaces = useWorkspacesStore();
const route = useRoute();
const router = useRouter();
const { t, locale } = useI18n();
const spaceId = computed(() => (typeof route.query.space === "string" ? route.query.space : ""));
const tagId = computed(() => (typeof route.query.tag === "string" ? route.query.tag : ""));
const collectionId = computed(() => (typeof route.query.collection === "string" ? route.query.collection : ""));
const collection = computed(() => (collectionId.value ? org.collection(collectionId.value) : undefined));
const ws = computed(() => workspaces.items.find((w) => w.id === props.id));
const canOrganize = computed(() => atLeast(ws.value?.role, "member"));
const auth = useAuthStore();
// Only the creator decides who sees a collection.
const isCreator = computed(() => !!collection.value && collection.value.creator === auth.user?.id);
// ---- View settings, remembered per workspace on this device ----
type Layout = "list" | "grid" | "cards";
interface ViewPrefs {
layout: Layout;
groupBy: string;
orderBy: OrderBy;
desc: boolean;
columns: string[];
}
const prefsKey = computed(() => `docwell.docs.${props.id}`);
const defaults: ViewPrefs = {
layout: "list",
groupBy: "",
orderBy: "updated",
desc: true,
columns: ["tags", "updated"],
};
function readPrefs(): ViewPrefs {
try {
return { ...defaults, ...(JSON.parse(localStorage.getItem(prefsKey.value) ?? "{}") as Partial<ViewPrefs>) };
} catch {
return { ...defaults };
}
}
const prefs = ref<ViewPrefs>(readPrefs());
watch(prefsKey, () => (prefs.value = readPrefs()));
watch(
prefs,
(p) => {
try {
localStorage.setItem(prefsKey.value, JSON.stringify(p));
} catch {
// per-device convenience only
}
},
{ deep: true },
);
// ---- Loading ----
const selected = ref(new Set<string>());
const draft = ref<DocFilter | null>(null);
const list = ref<DocList | null>(null);
const loading = ref(false);
const filter = ref<DocFilter>({ match: "all", rules: [] });
const filterOpen = ref(false);
let seq = 0;
async function load() {
const mine = ++seq;
loading.value = true;
try {
const res = await api.workspaces.docs(props.id, {
space: spaceId.value || undefined,
tag: tagId.value || undefined,
collection: collectionId.value || undefined,
filter: collectionId.value ? undefined : filter.value,
});
if (mine === seq) list.value = res;
} catch (e) {
if (mine === seq) emit("error", e);
} finally {
if (mine === seq) loading.value = false;
}
}
let timer: ReturnType<typeof setTimeout> | undefined;
watch(
[() => props.id, spaceId, tagId, collectionId, () => collection.value?.updated],
() => {
selected.value = new Set();
void load();
},
{ immediate: true },
);
watch(
filter,
() => {
clearTimeout(timer);
timer = setTimeout(load, 300);
},
{ deep: true },
);
onBeforeUnmount(() => clearTimeout(timer));
// A new collection's rules start from the filter that was on screen.
watch(collectionId, () => {
filter.value = { match: "all", rules: [] };
filterOpen.value = false;
draft.value = null;
});
// ---- Grouping, ordering and printing ----
const ctx = computed<ValueContext>(() => ({
tags: org.tags,
people: list.value?.people ?? {},
spaces: Object.fromEntries(spaces.items.map((s) => [s.id, s.name])),
locale: locale.value,
}));
const sorted = computed(() =>
[...(list.value?.items ?? [])].sort((a, b) => compareDocs(a, b, prefs.value.orderBy, prefs.value.desc)),
);
const groups = computed(() => groupDocs(sorted.value, prefs.value.groupBy, org.properties, ctx.value));
const fieldLabel = (f: string) => propertyOf(f, org.properties)?.name ?? t(`filters.fields.${f}`);
const columnChoices = computed(() => [
"tags",
"space",
"updated",
"created",
"createdBy",
"lastEditedBy",
...org.properties.map(propField),
]);
const columns = computed(() => prefs.value.columns.filter((c) => columnChoices.value.includes(c)));
function toggleColumn(c: string) {
const cur = prefs.value.columns;
prefs.value.columns = cur.includes(c) ? cur.filter((x) => x !== c) : [...cur, c];
}
interface Cell {
chips?: { id: string; label: string; color?: LabelColor }[];
text?: string;
}
function cell(d: DocItem, f: string): Cell {
switch (f) {
case "tags":
return {
chips: d.tags
.map((id) => org.tag(id))
.filter((x) => !!x)
.map((x) => ({ id: x.id, label: x.name, color: x.color })),
};
case "space":
return { text: d.spaceName };
case "created":
case "updated":
return { text: formatDay(localDay(d[f]), locale.value) };
case "createdBy":
case "lastEditedBy":
return { text: ctx.value.people[d[f]] ?? "" };
}
const p = propertyOf(f, org.properties);
if (!p) return {};
const raw = d.properties[p.id];
if (p.type === "select" || p.type === "multi_select") {
return {
chips: valueList(raw)
.map((id) => p.options.find((o) => o.id === id))
.filter((o) => !!o)
.map((o) => ({ id: o.id, label: o.name, color: o.color })),
};
}
return { text: valueText(p, raw, ctx.value) };
}
const groupName = (label: string) => label || t("docs.noValue", { field: fieldLabel(prefs.value.groupBy) });
// ---- Title ----
const heading = computed(() => {
if (collection.value) return `${collection.value.icon ? `${collection.value.icon} ` : ""}${collection.value.name}`;
if (tagId.value) return t("docs.tagged", { tag: org.tag(tagId.value)?.name ?? "…" });
if (spaceId.value) return t("docs.inSpace", { space: spaces.space(spaceId.value)?.name ?? "…" });
return t("docs.title");
});
const count = computed(() => list.value?.items.length ?? 0);
// ---- Selection and bulk actions ----
const chosen = computed(() => (list.value?.items ?? []).filter((d) => selected.value.has(d.id)));
const editableChosen = computed(() => chosen.value.filter((d) => spaceAtLeast(d.role, "editor")));
function toggle(id: string) {
const s = new Set(selected.value);
if (s.has(id)) s.delete(id);
else s.add(id);
selected.value = s;
}
const allSelected = computed(() => count.value > 0 && selected.value.size === count.value);
function toggleAll() {
selected.value = allSelected.value ? new Set() : new Set(list.value?.items.map((d) => d.id));
}
const busy = ref(false);
async function bulk(action: () => Promise<unknown>, keepSelection = false) {
busy.value = true;
try {
await action();
} catch (e) {
emit("error", e);
} finally {
busy.value = false;
if (!keepSelection) selected.value = new Set();
await Promise.all([load(), org.loadTags().catch(() => {})]);
}
}
const tagOptions = computed<PickerOption[]>(() => org.tags.map((x) => ({ id: x.id, label: x.name, color: x.color })));
const addTag = (tag: string) =>
bulk(
() =>
Promise.all(
editableChosen.value
.filter((d) => !d.tags.includes(tag))
.map((d) => api.pages.update(d.id, { tags: [...d.tags, tag] })),
),
true,
);
const createAndAddTag = (name: string) =>
bulk(async () => {
const tag = await org.createTag(name);
await Promise.all(editableChosen.value.map((d) => api.pages.update(d.id, { tags: [...d.tags, tag.id] })));
}, true);
function trashSelected() {
if (!confirm(t("docs.confirmTrash", { n: editableChosen.value.length }, editableChosen.value.length))) return;
const touched = new Set(editableChosen.value.map((d) => d.space));
void bulk(async () => {
for (const d of editableChosen.value) await api.pages.trash(d.id);
await Promise.all([...touched].map((s) => spaces.loadTree(s)));
});
}
// Moving: every chosen page in the same space, under a page of it (or its top level).
const moveSpace = computed(() => {
const ids = new Set(editableChosen.value.map((d) => d.space));
return ids.size === 1 && editableChosen.value.length === chosen.value.length ? [...ids][0]! : "";
});
const moveTargets = computed(() => {
if (!moveSpace.value) return [];
const moving = new Set(chosen.value.map((d) => d.id));
const nodes = spaces.trees[moveSpace.value] ?? [];
const parentOf = new Map(nodes.map((n) => [n.id, n.parent]));
const inside = (id: string) => {
for (let p: string | undefined = id; p; p = parentOf.get(p)) if (moving.has(p)) return true;
return false;
};
return nodes.filter((n) => !inside(n.id));
});
const moveTo = ref("__none");
function move() {
const parent = moveTo.value === "__top" ? "" : moveTo.value;
if (moveTo.value === "__none") return;
const space = moveSpace.value;
moveTo.value = "__none";
void bulk(async () => {
for (const d of chosen.value) {
await spaces.move(space, d.id, parent, spaces.childrenOf(space, parent).filter((n) => n.id !== d.id).length);
}
});
}
const collectionOptions = computed<PickerOption[]>(() =>
org.collections.filter((c) => c.canEdit).map((c) => ({ id: c.id, label: `${c.icon ? `${c.icon} ` : ""}${c.name}` })),
);
const addToCollection = (id: string) =>
bulk(async () => {
for (const d of chosen.value) await org.setCollectionPage(id, d.id, true);
}, true);
const removeFromCollection = () =>
bulk(async () => {
for (const d of chosen.value) await org.setCollectionPage(collectionId.value, d.id, false);
});
// ---- Collections ----
async function saveAsCollection() {
const name = prompt(t("collections.namePrompt"))?.trim();
if (!name) return;
const rules = [...filter.value.rules];
if (tagId.value) rules.push({ field: "tags", op: "contains", value: [tagId.value] });
if (spaceId.value) rules.push({ field: "space", op: "contains", value: [spaceId.value] });
try {
const c = await org.createCollection({ name, filter: { match: filter.value.match, rules } });
router.push({ name: "docs", params: { id: props.id }, query: { collection: c.id } });
} catch (e) {
emit("error", e);
}
}
const rules = computed({
get: () => draft.value ?? collection.value?.filter ?? { match: "all" as const, rules: [] },
set: (f: DocFilter) => (draft.value = f),
});
const saveRules = () =>
bulk(async () => {
if (!draft.value || !collection.value) return;
await org.updateCollection(collection.value.id, { filter: draft.value });
draft.value = null;
}, true);
async function renameCollection() {
const c = collection.value;
const name = c && prompt(t("collections.namePrompt"), c.name)?.trim();
if (!c || !name || name === c.name) return;
await bulk(() => org.updateCollection(c.id, { name }), true);
}
const toggleShared = () =>
bulk(() => org.updateCollection(collection.value!.id, { shared: !collection.value!.shared }), true);
async function deleteCollection() {
const c = collection.value;
if (!c || !confirm(t("collections.confirmDelete", { name: c.name }))) return;
try {
await org.removeCollection(c.id);
router.replace({ name: "docs", params: { id: props.id } });
} catch (e) {
emit("error", e);
}
}
// ---- New page here ----
const newPageSpace = computed(() => {
if (spaceId.value) return spaces.canEdit(spaceId.value) ? spaceId.value : "";
const active = spaces.active.space;
return spaces.canEdit(active) ? active : (spaces.items.find((s) => spaces.canEdit(s.id) && !s.journal)?.id ?? "");
});
async function newPage() {
try {
const page = await spaces.createPage(newPageSpace.value);
if (tagId.value) await api.pages.update(page.id, { tags: [tagId.value] });
if (collection.value?.canEdit) await org.setCollectionPage(collection.value.id, page.id, true);
router.push({ name: "page", params: { id: page.id } });
} catch (e) {
emit("error", e);
}
}
const filterCount = computed(() => (collectionId.value ? rules.value.rules.length : filter.value.rules.length));
const tab = (on: boolean) =>
`flex h-control-sm cursor-pointer items-center gap-1.5 rounded-sm px-2 text-ui-sm ${on ? "bg-surface-hover font-semibold text-ink" : "text-ink-muted hover:bg-surface-hover hover:text-ink"}`;
const layouts: { id: Layout; icon: "list" | "grid" | "cards" }[] = [
{ id: "list", icon: "list" },
{ id: "grid", icon: "grid" },
{ id: "cards", icon: "cards" },
];
const columnsOpen = ref(false);
</script>
<template>
<Teleport defer to="#app-header">
<h1 class="min-w-0 flex-1 truncate text-ui-md font-semibold text-ink" data-testid="docs-title">{{ heading }}</h1>
<span class="hidden text-ui-sm text-ink-muted tabular-nums sm:inline">{{
$t("docs.count", { n: count }, count)
}}</span>
<DwButton v-if="newPageSpace" variant="ghost" size="sm" icon="plus" @click="newPage">
<span class="sr-only sm:not-sr-only">{{ $t("app.newPage") }}</span>
</DwButton>
</Teleport>
<div class="mx-auto max-w-6xl px-4 pt-4 pb-16 sm:px-8" data-testid="docs-view">
<!-- Tags as quick filters; a collection keeps its own rules instead. -->
<nav
v-if="!collectionId && org.tags.length"
class="mb-3 flex flex-wrap items-center gap-1"
:aria-label="$t('properties.tags')"
>
<RouterLink :to="{ query: { ...route.query, tag: undefined } }" :class="tab(!tagId)">{{
$t("docs.allTags")
}}</RouterLink>
<RouterLink
v-for="tg in org.tags"
:key="tg.id"
:to="{ query: { ...route.query, tag: tg.id } }"
:class="tab(tagId === tg.id)"
>
<span class="size-2 rounded-full" :data-color="tg.color || 'gray'" style="background: var(--dw-c)" />
{{ tg.name }}
<span class="text-ink-faint tabular-nums">{{ tg.pages }}</span>
</RouterLink>
</nav>
<div
v-if="collection"
class="mb-3 flex flex-wrap items-center gap-2 text-ui-sm text-ink-muted"
data-testid="collection-bar"
>
<DwIcon name="layers" :size="14" />
<span>{{ collection.shared ? $t("collections.sharedNote") : $t("collections.privateNote") }}</span>
<template v-if="collection.canEdit">
<button class="cursor-pointer hover:text-ink hover:underline" @click="renameCollection">
{{ $t("collections.rename") }}
</button>
<button v-if="isCreator" class="cursor-pointer hover:text-ink hover:underline" @click="toggleShared">
{{ collection.shared ? $t("collections.makePrivate") : $t("collections.share") }}
</button>
<button class="cursor-pointer text-danger hover:underline" @click="deleteCollection">
{{ $t("collections.delete") }}
</button>
</template>
</div>
<div class="flex flex-wrap items-center gap-1.5">
<DwButton
size="sm"
variant="ghost"
icon="filter"
:class="{ 'bg-surface-hover text-ink': filterOpen }"
:aria-pressed="filterOpen"
data-testid="filter-toggle"
@click="filterOpen = !filterOpen"
>
{{ collectionId ? $t("collections.rules") : $t("docs.filter") }}
<span v-if="filterCount" class="tabular-nums">{{ filterCount }}</span>
</DwButton>
<span class="flex rounded-sm border border-line" role="group" :aria-label="$t('docs.layout')">
<button
v-for="l in layouts"
:key="l.id"
type="button"
class="grid size-control-sm cursor-pointer place-items-center text-ink-muted hover:text-ink"
:class="{ 'bg-surface-hover text-ink': prefs.layout === l.id }"
:aria-pressed="prefs.layout === l.id"
:aria-label="$t(`docs.layouts.${l.id}`)"
:title="$t(`docs.layouts.${l.id}`)"
@click="prefs.layout = l.id"
>
<DwIcon :name="l.icon" :size="16" />
</button>
</span>
<label class="flex items-center gap-1 text-ui-sm text-ink-muted">
{{ $t("docs.groupBy") }}
<select v-model="prefs.groupBy" class="dw-input h-7" data-testid="group-by">
<option value="">{{ $t("docs.noGroup") }}</option>
<option v-for="f in groupableFields(org.properties)" :key="f" :value="f">{{ fieldLabel(f) }}</option>
</select>
</label>
<label class="flex items-center gap-1 text-ui-sm text-ink-muted">
{{ $t("docs.order") }}
<select v-model="prefs.orderBy" class="dw-input h-7">
<option v-for="o in ['updated', 'created', 'title'] as const" :key="o" :value="o">
{{ $t(`docs.orders.${o}`) }}
</option>
</select>
</label>
<DwButton
size="sm"
variant="ghost"
:icon="prefs.desc ? 'arrow-down' : 'arrow-up'"
:aria-label="prefs.desc ? $t('docs.descending') : $t('docs.ascending')"
:title="prefs.desc ? $t('docs.descending') : $t('docs.ascending')"
@click="prefs.desc = !prefs.desc"
/>
<div class="relative">
<DwButton
size="sm"
variant="ghost"
icon="sliders"
:aria-expanded="columnsOpen"
@click="columnsOpen = !columnsOpen"
>{{ $t("docs.columns") }}</DwButton
>
<div
v-if="columnsOpen"
class="absolute top-full left-0 z-40 mt-1 w-56 rounded-md border border-line bg-surface-raised p-2 shadow-menu"
@keydown.escape="columnsOpen = false"
>
<label v-for="c in columnChoices" :key="c" class="flex items-center gap-2 py-0.5 text-ui-md">
<input type="checkbox" :checked="columns.includes(c)" @change="toggleColumn(c)" />
<span class="truncate">{{ fieldLabel(c) }}</span>
</label>
<DwButton size="sm" variant="ghost" class="mt-1" @click="columnsOpen = false">{{
$t("common.done")
}}</DwButton>
</div>
</div>
<span class="flex-1" />
<DwButton
v-if="!collectionId && canOrganize && (filter.rules.length || tagId || spaceId)"
size="sm"
icon="layers"
data-testid="save-collection"
@click="saveAsCollection"
>{{ $t("collections.saveAs") }}</DwButton
>
</div>
<div v-if="filterOpen" class="mt-3 rounded-md border border-line bg-surface-sunken p-3">
<template v-if="collection">
<p class="mb-2 text-ui-sm text-ink-muted">{{ $t("collections.rulesHint") }}</p>
<FilterEditor
v-model="rules"
:workspace="id"
:spaces="spaces.items"
:people="list?.people ?? {}"
:class="{ 'pointer-events-none opacity-70': !collection.canEdit }"
/>
<div v-if="draft && collection.canEdit" class="mt-2 flex gap-2">
<DwButton size="sm" variant="primary" :disabled="busy" @click="saveRules">{{
$t("collections.saveRules")
}}</DwButton>
<DwButton size="sm" variant="ghost" @click="draft = null">{{ $t("collections.revert") }}</DwButton>
</div>
</template>
<FilterEditor v-else v-model="filter" :workspace="id" :spaces="spaces.items" :people="list?.people ?? {}" />
</div>
<!-- Bulk actions for the chosen pages. -->
<div
v-if="selected.size"
class="sticky top-0 z-20 mt-3 flex flex-wrap items-center gap-2 rounded-md border border-line bg-surface-raised px-3 py-2 shadow-menu"
data-testid="bulk-bar"
>
<span class="text-ui-sm font-semibold">{{ $t("docs.selected", { n: selected.size }, selected.size) }}</span>
<template v-if="editableChosen.length">
<OptionPicker
:options="tagOptions"
:selected="[]"
:label="$t('properties.addTag')"
:creatable="canOrganize"
:create-label="(name: string) => $t('properties.createTag', { name })"
:disabled="busy"
@toggle="addTag"
@create="createAndAddTag"
/>
<label v-if="moveSpace" class="flex items-center gap-1 text-ui-sm text-ink-muted">
<select
v-model="moveTo"
class="dw-input h-7 max-w-56"
:disabled="busy"
:aria-label="$t('docs.moveTo')"
@change="move"
>
<option value="__none" disabled>{{ $t("docs.moveTo") }}</option>
<option value="__top">{{ $t("docs.topLevel", { space: spaces.space(moveSpace)?.name ?? "" }) }}</option>
<option v-for="n in moveTargets" :key="n.id" :value="n.id">{{ n.title || $t("home.untitled") }}</option>
</select>
</label>
</template>
<OptionPicker
v-if="collectionOptions.length"
:options="collectionOptions"
:selected="[]"
:multiple="false"
:label="$t('collections.addTo')"
:disabled="busy"
@toggle="addToCollection"
/>
<DwButton v-if="collection?.canEdit" size="sm" variant="ghost" :disabled="busy" @click="removeFromCollection">{{
$t("collections.removeFrom")
}}</DwButton>
<DwButton
v-if="editableChosen.length"
size="sm"
variant="ghost"
icon="trash"
:disabled="busy"
@click="trashSelected"
>{{ $t("page.moveToTrash") }}</DwButton
>
<span class="flex-1" />
<DwButton size="sm" variant="ghost" @click="selected = new Set()">{{ $t("docs.clearSelection") }}</DwButton>
</div>
<DwCallout v-if="list && !count && !loading" tone="info" size="ui" class="mt-6">
{{ filterCount || tagId ? $t("docs.noneFiltered") : $t("docs.none") }}
</DwCallout>
<label v-if="count && prefs.layout === 'list'" class="mt-4 flex items-center gap-2 px-3 text-ui-sm text-ink-muted">
<input type="checkbox" :checked="allSelected" data-testid="select-all" @change="toggleAll" />
{{ $t("docs.selectAll") }}
</label>
<section v-for="g in groups" :key="g.group.key" class="mt-4" data-testid="docs-group">
<h2 v-if="prefs.groupBy" class="mb-2 flex items-center gap-2 px-1 text-ui-sm font-medium text-ink-muted">
<LabelChip v-if="g.group.color !== undefined && g.group.key" :label="g.group.label" :color="g.group.color" />
<span v-else>{{ groupName(g.group.label) }}</span>
<span class="text-ink-faint tabular-nums">{{ g.items.length }}</span>
</h2>
<ul v-if="prefs.layout === 'list'" class="divide-y divide-line rounded-md border border-line bg-surface-raised">
<li
v-for="d in g.items"
:key="d.id"
class="flex min-h-11 flex-wrap items-center gap-x-3 gap-y-1 px-3 py-1.5"
data-testid="doc-row"
>
<input
type="checkbox"
:checked="selected.has(d.id)"
:aria-label="$t('docs.select', { title: d.title || $t('home.untitled') })"
@change="toggle(d.id)"
/>
<RouterLink
:to="{ name: 'page', params: { id: d.id } }"
class="flex min-w-40 flex-1 items-center gap-2 rounded-xs py-1 text-ink hover:text-accent"
>
<span v-if="d.icon" class="w-4 text-center">{{ d.icon }}</span>
<DwIcon v-else :name="d.journalDate ? 'journal' : 'page'" :size="16" class="text-ink-muted" />
<span class="truncate">{{ d.title || $t("home.untitled") }}</span>
<DwIcon
v-if="d.isTemplate"
name="file"
:size="12"
class="text-ink-faint"
:label="$t('properties.template')"
/>
</RouterLink>
<span
v-for="c in columns"
:key="c"
class="flex max-w-64 min-w-0 flex-wrap items-center gap-1 text-ui-sm text-ink-muted"
:title="fieldLabel(c)"
>
<template v-if="cell(d, c).chips">
<LabelChip v-for="ch in cell(d, c).chips" :key="ch.id" :label="ch.label" :color="ch.color" />
</template>
<span v-else class="truncate">{{ cell(d, c).text }}</span>
</span>
</li>
</ul>
<ul
v-else
class="grid gap-3"
:class="
prefs.layout === 'grid'
? 'grid-cols-[repeat(auto-fill,minmax(11rem,1fr))]'
: 'grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]'
"
>
<li
v-for="d in g.items"
:key="d.id"
class="group relative flex flex-col gap-2 rounded-md border border-line bg-surface-raised p-3 hover:border-line-strong"
:class="{ 'ring-2 ring-focus-ring': selected.has(d.id), 'min-h-36': prefs.layout === 'cards' }"
data-testid="doc-card"
>
<input
type="checkbox"
class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 focus:opacity-100"
:class="{ 'opacity-100': selected.has(d.id) }"
:checked="selected.has(d.id)"
:aria-label="$t('docs.select', { title: d.title || $t('home.untitled') })"
@change="toggle(d.id)"
/>
<RouterLink
:to="{ name: 'page', params: { id: d.id } }"
class="flex items-start gap-2 pr-5 text-ink hover:text-accent"
>
<span v-if="d.icon" class="text-lg leading-6">{{ d.icon }}</span>
<DwIcon v-else :name="d.journalDate ? 'journal' : 'page'" :size="18" class="mt-0.5 text-ink-muted" />
<span class="line-clamp-2 font-medium">{{ d.title || $t("home.untitled") }}</span>
</RouterLink>
<p class="text-ui-xs text-ink-faint">{{ d.spaceName }}</p>
<dl class="mt-auto space-y-1">
<div
v-for="c in prefs.layout === 'cards' ? columns : columns.slice(0, 2)"
:key="c"
class="flex min-w-0 flex-wrap items-center gap-1 text-ui-sm text-ink-muted"
>
<dt class="sr-only">{{ fieldLabel(c) }}</dt>
<dd class="flex min-w-0 flex-wrap items-center gap-1">
<template v-if="cell(d, c).chips">
<LabelChip v-for="ch in cell(d, c).chips" :key="ch.id" :label="ch.label" :color="ch.color" />
</template>
<span v-else class="truncate">{{ cell(d, c).text }}</span>
</dd>
</div>
</dl>
</li>
</ul>
</section>
</div>
</template>
+114 -1
View File
@@ -19,8 +19,10 @@ import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { useApi, useToken } from "../../api";
import PageHistory from "../../components/PageHistory.vue";
import JournalStrip from "../../components/JournalStrip.vue";
import PageComments from "../../components/PageComments.vue";
import PageList from "../../components/PageList.vue";
import PageProperties from "../../components/PageProperties.vue";
import ShareDialog from "../../components/ShareDialog.vue";
import { useEditorLabels, useMentions, usePageLinks } from "../../composables/useEditorHosts";
import { useFileHost } from "../../composables/useFiles";
@@ -28,14 +30,16 @@ import { saveBlob } from "../../lib/download";
import { usePlatform, useRuntimeConfig } from "../../platform";
import { useAuthStore } from "../../stores/auth";
import { useFavoritesStore } from "../../stores/favorites";
import { useOrganizeStore } from "../../stores/organize";
import { spaceAtLeast, useSpacesStore } from "../../stores/spaces";
import { useWorkspacesStore } from "../../stores/workspaces";
import { atLeast, useWorkspacesStore } from "../../stores/workspaces";
const props = defineProps<{ id: string }>();
const emit = defineEmits<{ error: [err: unknown] }>();
const api = useApi();
const spaces = useSpacesStore();
const favorites = useFavoritesStore();
const org = useOrganizeStore();
const workspaces = useWorkspacesStore();
const router = useRouter();
const route = useRoute();
@@ -94,6 +98,40 @@ function scrollToHash() {
attempt();
}
// Properties: under the title (folded away if the reader chose so on this
// device) and, all of them, in the Info side panel with collections and the
// journal. The side panel and the comments share the right edge.
const infoKey = "docwell.pageInfo";
const readInfoFolded = () => {
try {
return localStorage.getItem(infoKey) === "folded";
} catch {
return false;
}
};
const infoFolded = ref(readInfoFolded());
function toggleInfoFolded() {
infoFolded.value = !infoFolded.value;
try {
localStorage.setItem(infoKey, infoFolded.value ? "folded" : "open");
} catch {
// per-device convenience only
}
}
const infoOpen = ref(false);
watch(infoOpen, (on) => on && (commentsOpen.value = false));
function propertiesSaved(p: Page) {
if (page.value?.id !== p.id) return;
page.value = { ...p, title: page.value.title };
void org.loadTags();
}
const canOrganize = computed(() =>
atLeast(workspaces.items.find((w) => w.id === page.value?.workspace)?.role, "member"),
);
const editableCollections = computed(() => org.collections.filter((c) => c.canEdit));
const inCollection = (id: string) => !!page.value && !!org.collection(id)?.include.includes(page.value.id);
const toggleCollection = (id: string) => run(() => org.setCollectionPage(id, page.value!.id, !inCollection(id)));
// Inline comments: listed in a side panel, their text lit in the editor.
const commentsOpen = ref(false);
const comments = ref<Comment[]>([]);
@@ -199,6 +237,7 @@ function selectComment(id: string) {
activeComment.value = id;
commentsOpen.value = true;
}
watch(commentsOpen, (on) => on && (infoOpen.value = false));
async function commentsChanged() {
draft.value = null;
await loadComments();
@@ -535,6 +574,17 @@ const purge = () =>
<!-- Phones get icon-only header buttons; the label stays for screen readers. -->
<span class="sr-only sm:not-sr-only">{{ $t("page.history.title") }}</span>
</DwButton>
<DwButton
variant="ghost"
size="sm"
icon="info"
:class="{ 'bg-surface-hover text-ink': infoOpen }"
:aria-pressed="infoOpen"
data-testid="info-toggle"
@click="infoOpen = !infoOpen"
>
<span class="sr-only sm:not-sr-only">{{ $t("properties.info") }}</span>
</DwButton>
<DwButton
variant="ghost"
size="sm"
@@ -594,6 +644,14 @@ const purge = () =>
</template>
</DwCallout>
<JournalStrip
v-if="page.journalDate"
:workspace="page.workspace"
:date="page.journalDate"
class="mb-4"
@error="emit('error', $event)"
/>
<input
v-model="title"
:readonly="!editable"
@@ -610,6 +668,26 @@ const purge = () =>
{{ $t("page.readOnly") }}
</p>
<div v-if="!page.inTrash" class="mt-3">
<button
type="button"
class="flex h-6 cursor-pointer items-center gap-1 rounded-xs px-1 text-ui-sm text-ink-muted hover:bg-surface-hover hover:text-ink"
:aria-expanded="!infoFolded"
data-testid="properties-fold"
@click="toggleInfoFolded"
>
<DwIcon :name="infoFolded ? 'chevron-right' : 'chevron-down'" :size="14" />{{ $t("properties.title") }}
</button>
<PageProperties
v-if="!infoFolded"
:page="page"
:editable="editable"
class="mt-1 border-b border-line pb-3"
@update="propertiesSaved"
@error="emit('error', $event)"
/>
</div>
<PageHistory
v-if="historyOpen"
:page="page"
@@ -632,6 +710,7 @@ const purge = () =>
:drawio-url="config.drawioUrl"
:labels="labels"
:can-comment="canComment"
:journals="canOrganize"
:user="me"
:editable="editable"
:placeholder="editable ? $t('page.placeholder') : ''"
@@ -693,6 +772,40 @@ const purge = () =>
{{ $t("page.linkCopied") }}
</p>
<!-- Beside the text on wide screens; a sheet over the bottom on narrow ones. -->
<aside
v-if="page && infoOpen"
class="fixed inset-x-0 bottom-0 z-30 max-h-[60vh] space-y-6 overflow-y-auto border-t border-line bg-surface p-4 shadow-dialog lg:sticky lg:top-0 lg:z-auto lg:max-h-[calc(100dvh-5rem)] lg:w-80 lg:shrink-0 lg:border-t-0 lg:border-l lg:shadow-none"
:aria-label="$t('properties.info')"
data-testid="info-panel"
>
<div class="flex items-center justify-between">
<h2 class="text-ui-md font-semibold">{{ $t("properties.info") }}</h2>
<DwButton variant="ghost" size="sm" icon="close" :aria-label="$t('common.close')" @click="infoOpen = false" />
</div>
<PageProperties :page="page" :editable="editable" all @update="propertiesSaved" @error="emit('error', $event)" />
<section v-if="editableCollections.length" data-testid="page-collections">
<h3 class="dw-label">{{ $t("collections.title") }}</h3>
<ul class="mt-2 space-y-1">
<li v-for="c in editableCollections" :key="c.id">
<label class="flex items-center gap-2 text-ui-md">
<input type="checkbox" :checked="inCollection(c.id)" :disabled="busy" @change="toggleCollection(c.id)" />
<span class="truncate">{{ c.icon ? `${c.icon} ` : "" }}{{ c.name }}</span>
</label>
</li>
</ul>
<p class="mt-1 text-ui-xs text-ink-faint">{{ $t("collections.byHandHint") }}</p>
</section>
<section v-if="canOrganize">
<h3 class="dw-label">{{ $t("journal.title") }}</h3>
<JournalStrip
:workspace="page.workspace"
:date="page.journalDate"
settings
class="mt-2"
@error="emit('error', $event)"
/>
</section>
</aside>
<PageComments
v-if="page && commentsOpen"
:page="page.id"
@@ -8,6 +8,8 @@ import { useRouter } from "vue-router";
import { useApi } from "../../api";
import PageShell from "../../components/PageShell.vue";
import WorkspaceGroups from "../../components/WorkspaceGroups.vue";
import WorkspaceProperties from "../../components/WorkspaceProperties.vue";
import WorkspaceTags from "../../components/WorkspaceTags.vue";
import WorkspaceWebhooks from "../../components/WorkspaceWebhooks.vue";
import { useFormErrors } from "../../composables/useFormErrors";
import { useAuthStore } from "../../stores/auth";
@@ -232,6 +234,8 @@ async function removeWorkspace() {
</section>
<WorkspaceGroups v-if="atLeast(myRole, 'member')" :workspace="ws.id" :can-manage="canManage" />
<WorkspaceProperties :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
<WorkspaceTags :workspace="ws.id" :can-edit="atLeast(myRole, 'member')" />
<WorkspaceWebhooks v-if="canManage" :workspace="ws.id" />
<section v-if="atLeast(myRole, 'owner')" class="dw-card">
+518 -3
View File
@@ -981,7 +981,7 @@ paths:
patch:
operationId: updatePage
tags: [pages]
summary: Rename a page, change its icon or layout, or make it a template (editor)
summary: Rename a page, change its icon, layout, tags or properties, or make it a template (editor)
security: [{ bearer: [] }]
requestBody:
required: true
@@ -995,6 +995,11 @@ paths:
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" }
tags: { type: array, items: { type: string }, maxItems: 100, description: "Replaces the page's tags (tag ids)" }
properties:
type: object
additionalProperties: true
description: Sets these custom property values by property id; null clears one
responses:
"200":
description: OK
@@ -1771,6 +1776,7 @@ paths:
- { 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: tag, in: query, description: Only pages with this tag, schema: { type: string } }
- { name: author, in: query, description: Only pages this user created or last edited, schema: { type: string } }
- name: updatedAfter
in: query
@@ -2266,6 +2272,357 @@ paths:
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/properties:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listProperties
tags: [organize]
summary: The workspace's custom page properties, in order
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Property" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createProperty
tags: [organize]
summary: Add a custom page property to the workspace (members)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/PropertyInput" }
responses:
"200":
description: Created
content:
application/json:
schema: { $ref: "#/components/schemas/Property" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/properties/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
patch:
operationId: updateProperty
tags: [organize]
summary: Rename a property, change its type, options, visibility or place (members)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/PropertyInput" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Property" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteProperty
tags: [organize]
summary: Remove a property; pages' values for it are ignored from then on (members)
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/tags:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listTags
tags: [organize]
summary: The workspace's tags by name, with how many live pages use each
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Tag" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createTag
tags: [organize]
summary: Add a tag (members); names are unique in the workspace, ignoring case
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/TagInput" }
responses:
"200":
description: Created
content:
application/json:
schema: { $ref: "#/components/schemas/Tag" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
"409": { $ref: "#/components/responses/Error" }
/api/v1/tags/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
patch:
operationId: updateTag
tags: [organize]
summary: Rename or recolour a tag (members)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/TagInput" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Tag" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
"409": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteTag
tags: [organize]
summary: Take a tag off every page and delete it (members)
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/tags/{id}/merge:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
post:
operationId: mergeTag
tags: [organize]
summary: Move every page from this tag to another one, then delete this one (members)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [into]
properties:
into: { type: string, description: The tag that stays }
responses:
"200":
description: The tag that stays
content:
application/json:
schema: { $ref: "#/components/schemas/Tag" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/docs:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listDocs
tags: [organize]
summary: All docs, the workspace's live pages the caller can open with their properties
description: >-
Newest change first. Archived pages, trashed pages and pages in other people's
journals are left out. The query narrows the list; every part is optional.
security: [{ bearer: [] }]
parameters:
- { name: space, in: query, description: Only pages in this space, schema: { type: string } }
- { name: tag, in: query, description: Only pages with this tag, schema: { type: string } }
- { name: collection, in: query, description: Only the pages of this collection, schema: { type: string } }
- { name: filter, in: query, description: A DocFilter as JSON, schema: { type: string } }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/DocList" }
"400": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/collections:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: listCollections
tags: [organize]
summary: The caller's own collections and the shared ones, by name
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Collection" } }
"404": { $ref: "#/components/responses/Error" }
post:
operationId: createCollection
tags: [organize]
summary: Save a collection (members)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/CollectionInput" }
responses:
"200":
description: Created
content:
application/json:
schema: { $ref: "#/components/schemas/Collection" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/collections/{id}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
patch:
operationId: updateCollection
tags: [organize]
summary: Change a collection (its creator; workspace admins for shared ones)
description: Only the creator can change shared.
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/CollectionInput" }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Collection" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: deleteCollection
tags: [organize]
summary: Delete a collection; its pages stay where they are
security: [{ bearer: [] }]
responses:
"204": { description: Deleted }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/collections/{id}/pages/{page}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
- { name: page, in: path, required: true, schema: { type: string } }
put:
operationId: addCollectionPage
tags: [organize]
summary: Add a page to the collection by hand
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Collection" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
delete:
operationId: removeCollectionPage
tags: [organize]
summary: Take a page out of the collection, even when its rules match it
security: [{ bearer: [] }]
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/Collection" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/journals:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
get:
operationId: getJournal
tags: [organize]
summary: The caller's journal days in a date range (at most a year), newest first
security: [{ bearer: [] }]
parameters:
- { name: from, in: query, required: true, schema: { type: string, format: date } }
- { name: to, in: query, required: true, schema: { type: string, format: date } }
responses:
"200":
description: OK
content:
application/json:
schema: { $ref: "#/components/schemas/JournalInfo" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
patch:
operationId: setJournalTemplate
tags: [organize]
summary: Pick the page new journal pages are filled from (empty for none)
security: [{ bearer: [] }]
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [template]
properties:
template: { type: string }
responses:
"200":
description: OK (days is empty)
content:
application/json:
schema: { $ref: "#/components/schemas/JournalInfo" }
"400": { $ref: "#/components/responses/Error" }
"403": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/workspaces/{id}/journals/{date}:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
- { name: date, in: path, required: true, schema: { type: string, format: date } }
put:
operationId: openJournal
tags: [organize]
summary: The caller's journal page for a day, made (with the journal space) if there is none yet
description: >-
A new page goes to the top of the journal space, newest day first, and is filled
from the journal template when one is set. The journal space is private to its
owner; workspace admins do not see into it.
security: [{ bearer: [] }]
requestBody:
content:
application/json:
schema:
type: object
properties:
title: { type: string, maxLength: 500, description: Title for a new page; the date when empty }
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/workspaces/{id}/templates:
parameters:
- { name: id, in: path, required: true, schema: { type: string } }
@@ -2792,7 +3149,7 @@ components:
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, limited, created]
required: [id, workspace, name, slug, icon, description, visibility, defaultRole, role, limited, journal, created]
properties:
id: { type: string }
workspace: { type: string }
@@ -2804,6 +3161,7 @@ components:
defaultRole: { $ref: "#/components/schemas/SpaceDefaultRole" }
role: { $ref: "#/components/schemas/SpaceCallerRole" }
limited: { type: boolean, description: The caller cannot open the space itself and sees only pages shared with them }
journal: { type: boolean, description: "A journal space: one person's daily pages, private to them" }
created: { type: string }
SpaceMember:
type: object
@@ -2840,7 +3198,7 @@ components:
Page:
type: object
required:
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite, pinnedAt, fullWidth, font]
[id, workspace, space, parent, title, icon, created, updated, deletedAt, inTrash, archivedAt, archived, ancestors, role, restricted, isTemplate, favorite, pinnedAt, fullWidth, font, tags, properties, journalDate, createdBy, lastEditedBy]
properties:
id: { type: string }
workspace: { type: string }
@@ -2862,6 +3220,14 @@ components:
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" }
tags: { type: array, items: { type: string }, description: Tag ids }
properties:
type: object
additionalProperties: true
description: Custom property values by property id (see Property for their shapes)
journalDate: { type: string, description: The day (YYYY-MM-DD) of a journal page; empty otherwise }
createdBy: { $ref: "#/components/schemas/PageUser" }
lastEditedBy: { $ref: "#/components/schemas/PageUser" }
PageFont:
type: string
enum: ["", serif, mono]
@@ -3484,3 +3850,152 @@ components:
key: { type: string }
size: { type: integer }
modified: { type: string }
PropertyType:
type: string
enum: [text, number, checkbox, date, select, multi_select, member, link]
description: >-
What a value looks like: text and link a string, number a number, checkbox a
boolean, date "YYYY-MM-DD", select an option id, multi_select a list of option
ids, member a list of user ids.
LabelColor:
type: string
enum: ["", gray, red, orange, yellow, green, teal, blue, purple, pink]
description: A colour of the editor palette, drawn from the theme; empty for none
PropertyOption:
type: object
required: [id, name, color]
properties:
id: { type: string, description: Empty when creating; the server picks one }
name: { type: string, maxLength: 60 }
color: { $ref: "#/components/schemas/LabelColor" }
PropertyVisibility:
type: string
enum: [always, hide_empty, never]
description: Whether the page's Info panel shows it always, only with a value, or never
Property:
type: object
required: [id, workspace, name, type, options, visibility, position]
properties:
id: { type: string }
workspace: { type: string }
name: { type: string }
type: { $ref: "#/components/schemas/PropertyType" }
options: { type: array, items: { $ref: "#/components/schemas/PropertyOption" } }
visibility: { $ref: "#/components/schemas/PropertyVisibility" }
position: { type: number }
PropertyInput:
type: object
description: Creating needs name and type; updating changes the fields that are set
properties:
name: { type: string, maxLength: 80 }
type: { $ref: "#/components/schemas/PropertyType" }
options: { type: array, items: { $ref: "#/components/schemas/PropertyOption" } }
visibility: { $ref: "#/components/schemas/PropertyVisibility" }
position: { type: number }
Tag:
type: object
required: [id, name, color, pages]
properties:
id: { type: string }
name: { type: string }
color: { $ref: "#/components/schemas/LabelColor" }
pages: { type: integer, description: Live pages with the tag, including ones the caller cannot open }
TagInput:
type: object
properties:
name: { type: string, maxLength: 60 }
color: { $ref: "#/components/schemas/LabelColor" }
DocRule:
type: object
required: [field, op]
properties:
field:
type: string
description: >-
title, space, tags, created, updated, createdBy, lastEditedBy, template, journal,
or "prop:" followed by a property id
op:
type: string
enum: [is, isNot, contains, notContains, before, after, withinDays, gt, lt, empty, notEmpty]
value:
description: A string, a list of strings (any of them), a number or a boolean, as the op needs
DocFilter:
type: object
required: [match, rules]
properties:
match: { type: string, enum: [all, any] }
rules: { type: array, items: { $ref: "#/components/schemas/DocRule" }, maxItems: 50 }
DocItem:
type: object
required: [id, title, icon, space, spaceName, parent, created, updated, createdBy, lastEditedBy, isTemplate, journalDate, fullWidth, tags, properties, role]
properties:
id: { type: string }
title: { type: string }
icon: { type: string }
space: { type: string }
spaceName: { type: string }
parent: { type: string }
created: { type: string }
updated: { type: string }
createdBy: { type: string, description: User id }
lastEditedBy: { type: string, description: User id }
isTemplate: { type: boolean }
journalDate: { type: string }
fullWidth: { type: boolean }
tags: { type: array, items: { type: string } }
properties: { type: object, additionalProperties: true }
role: { $ref: "#/components/schemas/SpaceRole", description: The caller's role on the page }
DocList:
type: object
required: [items, people]
properties:
items: { type: array, items: { $ref: "#/components/schemas/DocItem" } }
people:
type: object
additionalProperties: { type: string }
description: Names of the people the items mention, by user id
Collection:
type: object
required: [id, workspace, name, icon, filter, include, exclude, shared, creator, canEdit, updated]
properties:
id: { type: string }
workspace: { type: string }
name: { type: string }
icon: { type: string }
filter: { $ref: "#/components/schemas/DocFilter" }
include: { type: array, items: { type: string }, description: Pages added by hand }
exclude: { type: array, items: { type: string }, description: Pages taken out by hand }
shared: { type: boolean, description: Seen by everyone in the workspace, not only its creator }
creator: { type: string }
canEdit: { type: boolean }
updated: { type: string }
CollectionInput:
type: object
description: Creating needs name; updating changes the fields that are set
properties:
name: { type: string, maxLength: 120 }
icon: { type: string, maxLength: 32 }
filter: { $ref: "#/components/schemas/DocFilter" }
include: { type: array, items: { type: string }, maxItems: 2000 }
exclude: { type: array, items: { type: string }, maxItems: 2000 }
shared: { type: boolean }
JournalDay:
type: object
required: [date, page, title]
properties:
date: { type: string, format: date }
page: { type: string }
title: { type: string }
JournalInfo:
type: object
required: [space, template, days]
properties:
space: { type: string, description: The caller's journal space; empty until the first journal page }
template: { type: string, description: The page new journal pages are filled from; empty for none }
days: { type: array, items: { $ref: "#/components/schemas/JournalDay" } }
PageUser:
type: object
required: [id, name]
properties:
id: { type: string }
name: { type: string, description: Empty when the account is gone }