From ec11abd8b8e5a36a88180e64b1058fe904ec286a Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:35:42 +0100 Subject: [PATCH] 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 --- .../pb_migrations/1763700000_properties.js | 111 +++ Docs-Site/guide/using-docwell.md | 25 +- Packages/api-client/src/index.ts | 92 +- Packages/api-client/src/schema.d.ts | 904 +++++++++++++++++- Packages/editor-bridge/dist/index.html | 10 +- Packages/editor/src/DocwellEditor.vue | 3 + Packages/editor/src/dates.ts | 32 +- Packages/editor/src/editor.css | 18 +- Packages/editor/src/extensions.ts | 4 +- Packages/editor/src/labels.ts | 3 + Packages/ui/src/icons.ts | 8 + Phone-App/lib/api/generated/models.dart | 654 +++++++++++++ Phone-App/tool/generate_api.dart | 3 + Server/internal/access/organize.go | 54 ++ Server/internal/access/organize_test.go | 50 + Server/internal/api/api.gen.go | 450 ++++++++- Server/internal/directory/collections.go | 280 ++++++ Server/internal/directory/docs.go | 493 ++++++++++ Server/internal/directory/docs_test.go | 183 ++++ Server/internal/directory/journals.go | 244 +++++ Server/internal/directory/pages.go | 73 +- Server/internal/directory/properties.go | 457 +++++++++ Server/internal/directory/search.go | 37 +- Server/internal/directory/spaces.go | 32 +- Server/internal/directory/tags.go | 273 ++++++ Server/internal/httpapi/auth.go | 1 + Server/internal/httpapi/directory.go | 1 + Server/internal/httpapi/organize.go | 179 ++++ Server/internal/httpapi/search.go | 2 +- Server/internal/pbschema/schema.json | 459 ++++++++- Web-App/frontend/src/components/AppLayout.vue | 85 ++ .../frontend/src/components/FilterEditor.vue | 223 +++++ .../frontend/src/components/JournalStrip.vue | 123 +++ Web-App/frontend/src/components/LabelChip.vue | 29 + .../frontend/src/components/OptionPicker.vue | 172 ++++ .../src/components/PageProperties.vue | 368 +++++++ .../frontend/src/components/SearchPalette.vue | 19 +- .../src/components/WorkspaceProperties.vue | 225 +++++ .../frontend/src/components/WorkspaceTags.vue | 140 +++ Web-App/frontend/src/lib/properties.test.ts | 123 +++ Web-App/frontend/src/lib/properties.ts | 298 ++++++ Web-App/frontend/src/locales/de.json | 190 +++- Web-App/frontend/src/locales/en.json | 190 +++- Web-App/frontend/src/locales/es.json | 190 +++- Web-App/frontend/src/locales/fr.json | 190 +++- Web-App/frontend/src/locales/pl.json | 190 +++- Web-App/frontend/src/router.ts | 4 + Web-App/frontend/src/stores/organize.ts | 146 +++ Web-App/frontend/src/views/JournalView.vue | 47 + Web-App/frontend/src/views/docs/DocsView.vue | 704 ++++++++++++++ Web-App/frontend/src/views/page/PageView.vue | 115 ++- .../views/workspace/WorkspaceSettingsView.vue | 4 + api/openapi.yaml | 521 +++++++++- 53 files changed, 9368 insertions(+), 63 deletions(-) create mode 100644 Database/pb_migrations/1763700000_properties.js create mode 100644 Server/internal/access/organize.go create mode 100644 Server/internal/access/organize_test.go create mode 100644 Server/internal/directory/collections.go create mode 100644 Server/internal/directory/docs.go create mode 100644 Server/internal/directory/docs_test.go create mode 100644 Server/internal/directory/journals.go create mode 100644 Server/internal/directory/properties.go create mode 100644 Server/internal/directory/tags.go create mode 100644 Server/internal/httpapi/organize.go create mode 100644 Web-App/frontend/src/components/FilterEditor.vue create mode 100644 Web-App/frontend/src/components/JournalStrip.vue create mode 100644 Web-App/frontend/src/components/LabelChip.vue create mode 100644 Web-App/frontend/src/components/OptionPicker.vue create mode 100644 Web-App/frontend/src/components/PageProperties.vue create mode 100644 Web-App/frontend/src/components/WorkspaceProperties.vue create mode 100644 Web-App/frontend/src/components/WorkspaceTags.vue create mode 100644 Web-App/frontend/src/lib/properties.test.ts create mode 100644 Web-App/frontend/src/lib/properties.ts create mode 100644 Web-App/frontend/src/stores/organize.ts create mode 100644 Web-App/frontend/src/views/JournalView.vue create mode 100644 Web-App/frontend/src/views/docs/DocsView.vue diff --git a/Database/pb_migrations/1763700000_properties.js b/Database/pb_migrations/1763700000_properties.js new file mode 100644 index 0000000..dc00399 --- /dev/null +++ b/Database/pb_migrations/1763700000_properties.js @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// 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 { "": 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")); + }, +); diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index d256659..e9804d8 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -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 diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 3d6e42d..62e3070 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -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>; @@ -354,6 +371,62 @@ export function createClient(opts: ClientOptions) { request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/recent${query({ limit })}`), createGroup: (id: string, input: GroupRequest) => post(`/api/v1/workspaces/${encodeURIComponent(id)}/groups`, input), + properties: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/properties`), + createProperty: (id: string, input: PropertyInput) => + post(`/api/v1/workspaces/${encodeURIComponent(id)}/properties`, input), + tags: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/tags`), + createTag: (id: string, input: TagInput) => post(`/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( + "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("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/collections`), + createCollection: (id: string, input: CollectionInput) => + post(`/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("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/journals${query({ from, to })}`), + setJournalTemplate: (id: string, template: string) => + request("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( + "PUT", + `/api/v1/workspaces/${encodeURIComponent(id)}/journals/${encodeURIComponent(date)}`, + title ? { title } : {}, + ), + }, + + properties: { + update: (id: string, patch: PropertyInput) => + request("PATCH", `/api/v1/properties/${encodeURIComponent(id)}`, patch), + remove: (id: string) => request("DELETE", `/api/v1/properties/${encodeURIComponent(id)}`), + }, + + tags: { + update: (id: string, patch: TagInput) => request("PATCH", `/api/v1/tags/${encodeURIComponent(id)}`, patch), + remove: (id: string) => request("DELETE", `/api/v1/tags/${encodeURIComponent(id)}`), + /** Moves every page of tag id to into, then deletes id. */ + merge: (id: string, into: string) => post(`/api/v1/tags/${encodeURIComponent(id)}/merge`, { into }), + }, + + collections: { + update: (id: string, patch: CollectionInput) => + request("PATCH", `/api/v1/collections/${encodeURIComponent(id)}`, patch), + remove: (id: string) => request("DELETE", `/api/v1/collections/${encodeURIComponent(id)}`), + setPage: (id: string, page: string, on: boolean) => + request( + 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("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; + }, ) => request("PATCH", `/api/v1/pages/${encodeURIComponent(id)}`, patch), /** Moves a page under parent ("" = top level) at index among its other children. */ content: (id: string) => request("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 { const qs = new URLSearchParams(); diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index 338c985..04baf53 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -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; diff --git a/Packages/editor-bridge/dist/index.html b/Packages/editor-bridge/dist/index.html index 56080ff..0393ad7 100644 --- a/Packages/editor-bridge/dist/index.html +++ b/Packages/editor-bridge/dist/index.html @@ -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:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:e}){return[`ul`,A(this.options.HTMLAttributes,e,{"data-type":this.name}),0]},parseMarkdown:(e,t)=>t.createNode(`taskList`,{},t.parseChildren(e.items||[])),renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,` `):``,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=` `,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`${t.renderChildren(e)}`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(``)},tokenize(e,t,n){if(!/^/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),toggleUnderline:()=>({commands:e})=>e.toggleMark(this.name),unsetUnderline:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),Hk=Tp.create({name:`starterKit`,addExtensions(){let e=[];return this.options.bold!==!1&&e.push(jT.configure(this.options.bold)),this.options.blockquote!==!1&&e.push(ET.configure(this.options.blockquote)),this.options.bulletList!==!1&&e.push(TO.configure(this.options.bulletList)),this.options.code!==!1&&e.push(FT.configure(this.options.code)),this.options.codeBlock!==!1&&e.push(zT.configure(this.options.codeBlock)),this.options.document!==!1&&e.push(VT.configure(this.options.document)),this.options.dropcursor!==!1&&e.push(Ww.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&e.push(Gw.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&e.push(HT.configure(this.options.hardBreak)),this.options.heading!==!1&&e.push(UT.configure(this.options.heading)),this.options.undoRedo!==!1&&e.push(gT.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&e.push(WT.configure(this.options.horizontalRule)),this.options.italic!==!1&&e.push(YT.configure(this.options.italic)),this.options.listItem!==!1&&e.push($O.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(ck.configure(this.options?.listKeymap)),this.options.link!==!1&&e.push(xO.configure(this.options?.link)),this.options.orderedList!==!1&&e.push(Ok.configure(this.options.orderedList)),this.options.paragraph!==!1&&e.push(Ik.configure(this.options.paragraph)),this.options.strike!==!1&&e.push(zk.configure(this.options.strike)),this.options.text!==!1&&e.push(Bk.configure(this.options.text)),this.options.underline!==!1&&e.push(Vk.configure(this.options?.underline)),this.options.trailingNode!==!1&&e.push(hT.configure(this.options?.trailingNode)),e}}),Uk=Math.min,Wk=Math.max,Gk=Math.round,Kk=Math.floor,qk=e=>({x:e,y:e}),Jk={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Yk(e,t,n){return Wk(e,Uk(t,n))}function Xk(e,t){return typeof e==`function`?e(t):e}function Zk(e){return e.split(`-`)[0]}function Qk(e){return e.split(`-`)[1]}function $k(e){return e===`x`?`y`:`x`}function eA(e){return e===`y`?`height`:`width`}function tA(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function nA(e){return $k(tA(e))}function rA(e,t,n){n===void 0&&(n=!1);let r=Qk(e),i=nA(e),a=eA(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=fA(o)),[o,fA(o)]}function iA(e){let t=fA(e);return[aA(e),t,aA(t)]}function aA(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var oA=[`left`,`right`],sA=[`right`,`left`],cA=[`top`,`bottom`],lA=[`bottom`,`top`];function uA(e,t,n){switch(e){case`top`:case`bottom`:return n?t?sA:oA:t?oA:sA;case`left`:case`right`:return t?cA:lA;default:return[]}}function dA(e,t,n,r){let i=Qk(e),a=uA(Zk(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(aA)))),a}function fA(e){let t=Zk(e);return Jk[t]+e.slice(t.length)}function pA(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function mA(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:pA(e)}function hA(e){let{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function gA(e,t,n){let{reference:r,floating:i}=e,a=tA(t),o=nA(t),s=eA(o),c=Zk(t),l=a===`y`,u=r.x+r.width/2-i.width/2,d=r.y+r.height/2-i.height/2,f=r[s]/2-i[s]/2,p;switch(c){case`top`:p={x:u,y:r.y-i.height};break;case`bottom`:p={x:u,y:r.y+r.height};break;case`right`:p={x:r.x+r.width,y:d};break;case`left`:p={x:r.x-i.width,y:d};break;default:p={x:r.x,y:r.y}}let m=Qk(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function _A(e,t){t===void 0&&(t={});let{x:n,y:r,platform:i,rects:a,elements:o,strategy:s}=e,{boundary:c=`clippingAncestors`,rootBoundary:l=`viewport`,elementContext:u=`floating`,altBoundary:d=!1,padding:f=0}=Xk(t,e),p=mA(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=hA(await i.getClippingRect({element:await(i.isElement==null?void 0:i.isElement(m))??!0?m:m.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:c,rootBoundary:l,strategy:s})),g=u===`floating`?{x:n,y:r,width:a.floating.width,height:a.floating.height}:a.reference,_=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),v=await(i.isElement==null?void 0:i.isElement(_))&&await(i.getScale==null?void 0:i.getScale(_))||{x:1,y:1},y=hA(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:g,offsetParent:_,strategy:s}):g);return{top:(h.top-y.top+p.top)/v.y,bottom:(y.bottom-h.bottom+p.bottom)/v.y,left:(h.left-y.left+p.left)/v.x,right:(y.right-h.right+p.right)/v.x}}var vA=50,yA=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:_A},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=gA(l,r,c),f=r,p=0,m={};for(let n=0;ne<=0)){let e=(i.flip?.index||0)+1,t=S[e];if(t&&(u!==`alignment`||_===tA(t)||ne.every(e=>tA(e.placement)!==_||e.overflows[0]>0)))return{data:{index:e,overflows:ne},reset:{placement:t}};let n=ne.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0]?.placement;if(!n)switch(f){case`bestFit`:{let e=ne.filter(e=>{if(x){let t=tA(e.placement);return t===_||t===`y`}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0]?.[0];e&&(n=e);break}case`initialPlacement`:n=o}if(r!==n)return{reset:{placement:n}}}return{}}}},xA=new Set([`left`,`top`]);async function SA(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Zk(n),s=Qk(n),c=tA(n)===`y`,l=xA.has(o)?-1:1,u=a&&c?-1:1,d=Xk(t,e),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d==`number`?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return s&&typeof m==`number`&&(p=s===`end`?m*-1:m),c?{x:p*u,y:f*l}:{x:f*l,y:p*u}}var CA=function(e){return e===void 0&&(e=0),{name:`offset`,options:e,async fn(t){var n;let{x:r,y:i,placement:a,middlewareData:o}=t,s=await SA(t,e);return a===o.offset?.placement&&(n=o.arrow)!=null&&n.alignmentOffset?{}:{x:r+s.x,y:i+s.y,data:{...s,placement:a}}}}},wA=function(e){return e===void 0&&(e={}),{name:`shift`,options:e,async fn(t){let{x:n,y:r,placement:i,platform:a}=t,{mainAxis:o=!0,crossAxis:s=!1,limiter:c={fn:e=>{let{x:t,y:n}=e;return{x:t,y:n}}},...l}=Xk(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=tA(i),p=$k(f),m=u[p],h=u[f],g=(e,t)=>Yk(t+d[e===`y`?`top`:`left`],t,t-d[e===`y`?`bottom`:`right`]);o&&(m=g(p,m)),s&&(h=g(f,h));let _=c.fn({...t,[p]:m,[f]:h});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:o,[f]:s}}}}}};function TA(){return typeof window<`u`}function EA(e){return kA(e)?(e.nodeName||``).toLowerCase():`#document`}function DA(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function OA(e){return((kA(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function kA(e){return TA()?e instanceof Node||e instanceof DA(e).Node:!1}function AA(e){return TA()?e instanceof Element||e instanceof DA(e).Element:!1}function jA(e){return TA()?e instanceof HTMLElement||e instanceof DA(e).HTMLElement:!1}function MA(e){return!TA()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof DA(e).ShadowRoot}function NA(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=WA(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function PA(e){return/^(table|td|th)$/.test(EA(e))}function FA(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var IA=/transform|translate|scale|rotate|perspective|filter/,LA=/paint|layout|strict|content/,RA=e=>!!e&&e!==`none`,zA;function BA(e){let t=AA(e)?WA(e):e;return RA(t.transform)||RA(t.translate)||RA(t.scale)||RA(t.rotate)||RA(t.perspective)||!HA()&&(RA(t.backdropFilter)||RA(t.filter))||IA.test(t.willChange||``)||LA.test(t.contain||``)}function VA(e){let t=KA(e);for(;jA(t)&&!UA(t);){if(BA(t))return t;if(FA(t))return null;t=KA(t)}return null}function HA(){return zA??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),zA}function UA(e){return/^(html|body|#document)$/.test(EA(e))}function WA(e){return DA(e).getComputedStyle(e)}function GA(e){return AA(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function KA(e){if(EA(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||MA(e)&&e.host||OA(e);return MA(t)?t.host:t}function qA(e){let t=KA(e);return UA(t)?(e.ownerDocument||e).body:jA(t)&&NA(t)?t:qA(t)}function JA(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=qA(e),i=r===e.ownerDocument?.body,a=DA(r);if(i){let e=YA(a);return t.concat(a,a.visualViewport||[],NA(r)?r:[],e&&n?JA(e):[])}return t.concat(r,JA(r,[],n))}function YA(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function XA(e){let t=WA(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=jA(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Gk(n)!==a||Gk(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function ZA(e){return AA(e)?e:e.contextElement}function QA(e){let t=ZA(e);if(!jA(t))return qk(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=XA(t),o=(a?Gk(n.width):n.width)/r,s=(a?Gk(n.height):n.height)/i;return o&&Number.isFinite(o)||(o=1),s&&Number.isFinite(s)||(s=1),{x:o,y:s}}var $A=qk(0);function ej(e){let t=DA(e);return!HA()||!t.visualViewport?$A:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tj(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===DA(e)}function nj(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=ZA(e),o=qk(1);t&&(r?AA(r)&&(o=QA(r)):o=QA(e));let s=tj(a,n,r)?ej(a):qk(0),c=(i.left+s.x)/o.x,l=(i.top+s.y)/o.y,u=i.width/o.x,d=i.height/o.y;if(a&&r){let e=DA(a),t=AA(r)?DA(r):r,n=e,i=YA(n);for(;i&&t!==n;){let e=QA(i),t=i.getBoundingClientRect(),r=WA(i),a=t.left+(i.clientLeft+parseFloat(r.paddingLeft))*e.x,o=t.top+(i.clientTop+parseFloat(r.paddingTop))*e.y;c*=e.x,l*=e.y,u*=e.x,d*=e.y,c+=a,l+=o,n=DA(i),i=YA(n)}}return hA({width:u,height:d,x:c,y:l})}function rj(e,t){let n=GA(e).scrollLeft;return t?t.left+n:nj(OA(e)).left+n}function ij(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-rj(e,n),y:n.top+t.scrollTop}}function aj(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=OA(r),s=t?FA(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=qk(1),u=qk(0),d=jA(r);if((d||!a)&&((EA(r)!==`body`||NA(o))&&(c=GA(r)),d)){let e=nj(r);l=QA(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?ij(o,c):qk(0);return{width:n.width*l.x,height:n.height*l.y,x:n.x*l.x-c.scrollLeft*l.x+u.x+f.x,y:n.y*l.y-c.scrollTop*l.y+u.y+f.y}}function oj(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function sj(e){let t=GA(e),n=e.ownerDocument.body,r=Wk(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Wk(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+rj(e),o=-t.scrollTop;return WA(n).direction===`rtl`&&(a+=Wk(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var cj=25;function lj(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=DA(e),a=OA(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!HA()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(rj(a)<=0){let e=a.ownerDocument,t=e.body,n=getComputedStyle(t),r=e.compatMode===`CSS1Compat`&&parseFloat(n.marginLeft)+parseFloat(n.marginRight)||0,i=Math.abs(a.clientWidth-t.clientWidth-r),o=getComputedStyle(a).scrollbarGutter===`stable both-edges`?i/2:i;o<=cj&&(s-=o)}return{width:s,height:c,x:l,y:u}}function uj(e,t){let n=nj(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=QA(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function dj(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=lj(e,n,t);else if(t===`document`)r=sj(OA(e));else if(AA(t))r=uj(t,n);else{let n=ej(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return hA(r)}function fj(e,t){let n=t.get(e);if(n)return n;let r=JA(e,[],!1).filter(e=>AA(e)&&EA(e)!==`body`),i=null,a=WA(e).position===`fixed`,o=a?KA(e):e;for(;AA(o)&&!UA(o);){let e=WA(o),t=BA(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=KA(o)}return t.set(e,r),r}function pj(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?FA(t)?[]:fj(t,this._c):[].concat(n),r],o=dj(t,a[0],i),s=o.top,c=o.right,l=o.bottom,u=o.left;for(let e=1;e{s(!1,1e-7)},1e3)}y=!1}try{r=new IntersectionObserver(b,{...v,root:a.ownerDocument})}catch{r=new IntersectionObserver(b,v)}r.observe(e)}let c=DA(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function wj(e,t,n,r){r===void 0&&(r={});let{ancestorScroll:i=!0,ancestorResize:a=!0,elementResize:o=typeof ResizeObserver==`function`,layoutShift:s=typeof IntersectionObserver==`function`,animationFrame:c=!1}=r,l=ZA(e),u=i||a?[...l?JA(l):[],...t?JA(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?Cj(l,n,a):null,f=-1,p=null;o&&(p=new ResizeObserver(e=>{let[r]=e;r&&r.target===l&&p&&t&&(p.unobserve(t),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var e;(e=p)==null||e.observe(t)})),n()}),l&&!c&&p.observe(l),t&&p.observe(t));let m,h=c?nj(e):null;c&&g();function g(){let t=nj(e);h&&!Sj(h,t)&&n(),h=t,m=requestAnimationFrame(g)}return n(),()=>{var e;u.forEach(e=>{i&&e.removeEventListener(`scroll`,n),a&&e.removeEventListener(`resize`,n)}),d?.(),(e=p)==null||e.disconnect(),p=null,c&&cancelAnimationFrame(m)}}var Tj=CA,Ej=wA,Dj=bA,Oj=(e,t,n)=>{let r=new Map,i=n??{},a={...xj,...i.platform,_c:r};return yA(e,t,{...i,platform:a})};function kj(e,t){return typeof e==`boolean`?e:t}var Aj=BT.extend({addOptions(){return{...this.parent(),lineNumbers:!1}},addAttributes(){return{...this.parent?.(),lineNumbers:{default:null,parseHTML:e=>{let t=e.getAttribute(`data-line-numbers`);return t===`true`||t!==`false`&&null},renderHTML:e=>typeof e.lineNumbers==`boolean`?{"data-line-numbers":String(e.lineNumbers)}:{}}}},addCommands(){return{...this.parent?.(),toggleCodeLineNumbers:()=>({editor:e,commands:t})=>{if(!e.isActive(this.name))return!1;let n=kj(e.getAttributes(this.name).lineNumbers,this.options.lineNumbers);return t.updateAttributes(this.name,{lineNumbers:!n})}}},addNodeView(){let e=this.options.lineNumbers,t=this.options.languageClassPrefix??`language-`;return({node:n})=>{let r=document.createElement(`pre`);r.className=`dw-code`;let i=document.createElement(`div`);i.className=`dw-code__gutter`,i.contentEditable=`false`,i.setAttribute(`aria-hidden`,`true`);let a=document.createElement(`code`);r.append(i,a);let o=-1,s=n=>{let s=kj(n.attrs.lineNumbers,e);r.classList.toggle(`dw-code--numbered`,s),a.className=n.attrs.language?`${t}${String(n.attrs.language)}`:``;let c=s?n.textContent.split(` `).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 8l-6 8h12v-2`],diagram:[`M4 4h6v5H4z`,`M14 15h6v5h-6z`,`M7 9v4a2 2 0 0 0 2 2h5`],video:[`M4 6h11v12H4z`,`M15 10l5-3v10l-5-3`],archive:[`M4 5h16v4H4z`,`M5 9v10h14V9`,`M10 13h4`],pin:[`M9 4h6`,`M10 4v6l-3 4h10l-3-4V4`,`M12 14v6`],width:[`M3 12h18`,`M7 8l-4 4 4 4`,`M17 8l4 4-4 4`],type:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`],server:[`M4 4h16v6H4z`,`M4 14h16v6H4z`,`M8 7h.01`,`M8 17h.01`],users:[`M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z`,`M3 20a6 6 0 0 1 12 0`,`M16 4.5a3.5 3.5 0 0 1 0 6.5`,`M18 14a6 6 0 0 1 3 6`],"align-left":[`M4 6h16`,`M4 10h10`,`M4 14h16`,`M4 18h10`],"align-center":[`M4 6h16`,`M7 10h10`,`M4 14h16`,`M7 18h10`],"align-right":[`M4 6h16`,`M10 10h10`,`M4 14h16`,`M10 18h10`],grip:[`M9 6h.01`,`M15 6h.01`,`M9 12h.01`,`M15 12h.01`,`M9 18h.01`,`M15 18h.01`],copy:[`M9 9h11v11H9z`,`M5 15H4V4h11v1`],"arrow-up":[`M12 19V5`,`M6 11l6-6 6 6`],"arrow-down":[`M12 5v14`,`M6 13l6 6 6-6`],callout:[`M4 5h16v14H4z`,`M8 10h.01`,`M11 10h5`,`M8 14h8`],palette:[`M12 3a9 9 0 1 0 0 18c1 0 1.5-.7 1.5-1.5 0-1.2-1-1.5-1-2.5s.8-1.5 2-1.5H17a4 4 0 0 0 4-4c0-4.7-4-8.5-9-8.5z`,`M7.5 11h.01`,`M10 7.5h.01`,`M14.5 7.5h.01`],"page-plus":[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M12 11v6`,`M9 14h6`]},Pj=`http://www.w3.org/2000/svg`;function Fj(e,t=18){let n=document.createElementNS(Pj,`svg`);for(let[e,r]of Object.entries({width:String(t),height:String(t),viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.75`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`}))n.setAttribute(e,r);for(let t of Nj[e]){let e=document.createElementNS(Pj,`path`);e.setAttribute(`d`,t),n.append(e)}return n}function Ij(e){return()=>{let t=null,n=null,r=null,i=0,a=null,o=()=>a?.items??r?.items??[],s=t=>{let n=o()[t];if(!r||n===void 0)return;let s=e.children?.(n);s?.length?(a={parent:n,items:s},i=0,c()):e.pick(r,n)},c=()=>{if(!t||!r)return;let n=r;if(t.replaceChildren(),e.showQuery){let e=document.createElement(`div`);e.className=`dw-suggest__query`,e.textContent=`/${n.query}`,t.append(e)}if(a){let n=document.createElement(`div`);n.className=`dw-suggest__query`,n.textContent=`‹ ${e.toItem(a.parent).label}`,t.append(n)}let c=o();if(c.length)c.forEach((n,r)=>{let a=e.toItem(n),o=document.createElement(`div`);o.className=r===i?`dw-suggest__item is-active`:`dw-suggest__item`,o.setAttribute(`role`,`option`),o.setAttribute(`aria-selected`,String(r===i)),o.addEventListener(`mousedown`,e=>{e.preventDefault(),s(r)});let c=document.createElement(`span`);c.className=`dw-suggest__icon`,c.append(Fj(a.icon??`text`));let l=document.createElement(`span`);l.className=`dw-suggest__text`;let u=document.createElement(`span`);if(u.className=`dw-suggest__label`,u.textContent=a.label,l.append(u),a.description){let e=document.createElement(`span`);e.className=`dw-suggest__desc`,e.textContent=a.description,l.append(e)}if(o.append(c,l),e.children?.(n)?.length){o.setAttribute(`aria-haspopup`,`listbox`);let e=Fj(`chevron-right`,14);e.classList.add(`dw-suggest__more`),o.append(e)}t.append(o)}),t.querySelector(`.is-active`)?.scrollIntoView({block:`nearest`});else{let n=document.createElement(`div`);n.className=`dw-suggest__empty`,n.setAttribute(`role`,`status`),n.textContent=e.empty,t.append(n)}},l=()=>{let e=r?.clientRect?.();if(!t||!e)return;let i={getBoundingClientRect:()=>r?.clientRect?.()??e};n?.(),n=wj(i,t,()=>{t&&Oj(i,t,{placement:`bottom-start`,strategy:`fixed`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:n})=>{t&&Object.assign(t.style,{left:`${e}px`,top:`${n}px`})})})},u=()=>{n?.(),n=null,t?.remove(),t=null};return{onStart(n){r=n,i=0,a=null,t=document.createElement(`div`),t.className=`dw-suggest`,t.setAttribute(`role`,`listbox`),t.setAttribute(`aria-label`,e.label),document.body.append(t),c(),l()},onUpdate(e){e.items!==r?.items&&(i=0,a=null),r=e,c(),l()},onKeyDown({event:t}){let n=o().length;if(a&&(t.key===`Escape`||t.key===`ArrowLeft`))return a=null,i=0,c(),!0;let r=o()[i];return t.key===`ArrowRight`&&r!==void 0&&e.children?.(r)?.length?(s(i),!0):t.key===`Escape`?(u(),!0):n?t.key===`ArrowDown`||t.key===`ArrowUp`?(i=(i+(t.key===`ArrowDown`?1:-1)+n)%n,c(),!0):t.key===`Enter`||t.key===`Tab`?(s(i),!0):!1:!1},onExit(){r=null,u()}}}}var Lj=[[`text`,`text`,e=>e],[`h1`,`heading`,e=>e.setNode(`heading`,{level:1})],[`h2`,`heading`,e=>e.setNode(`heading`,{level:2})],[`h3`,`heading`,e=>e.setNode(`heading`,{level:3})],[`bullet`,`list`,e=>e.toggleBulletList()],[`ordered`,`list-ordered`,e=>e.toggleOrderedList()],[`todo`,`todo`,e=>e.toggleTaskList()],[`quote`,`quote`,e=>e.setBlockquote()],[`code`,`code`,e=>e.setCodeBlock()],[`callout`,`callout`,e=>e.setCallout()]],Rj=[`paragraph`,`heading`,`codeBlock`,`blockquote`,`bulletList`,`orderedList`,`taskList`,`callout`];function zj(e){let t={...e};return t.attrs&&`blockId`in t.attrs&&(t.attrs={...t.attrs,blockId:null}),t.content&&=t.content.map(zj),t}function Bj(e,t,n,r){let i=e.state.doc.nodeAt(t);if(!i)return[];let a=n.blockMenu,o=t+i.nodeSize,c=e.state.doc.resolve(t).index(0),l=[];if(Rj.includes(i.type.name)&&l.push({id:`turnInto`,label:a.turnInto,icon:`text`,children:Lj.map(([r,a,c])=>({id:r,icon:a,label:n.slash[r]?.label??r,run:()=>{if(r===`callout`){if(i.type.name===`callout`)return;let n=i.type.name===`blockquote`?i.content:s.from(i),r=e.schema.nodes.callout.create(null,n),a=e.state.tr.replaceWith(t,o,r);e.view.dispatch(a.setSelection(C.near(a.doc.resolve(t+1))).scrollIntoView()),e.commands.focus();return}let n=e.state.doc,a=C.findFrom(n.resolve(t),1,!0)?.from??t+1,l=C.findFrom(n.resolve(o),-1,!0)?.to??o-1;c(e.chain().focus().setTextSelection({from:a,to:l}).clearNodes()).run()}}))}),i.type.name===`codeBlock`){let n=!!e.extensionManager.extensions.find(e=>e.name===`codeBlock`)?.options.lineNumbers,r=kj(i.attrs.lineNumbers,n);l.push({id:`lineNumbers`,label:r?a.hideLineNumbers:a.showLineNumbers,icon:`list-ordered`,run:()=>e.view.dispatch(e.state.tr.setNodeAttribute(t,`lineNumbers`,!r))})}if(i.type.name===`fileAttachment`&&jj(i.attrs.mime,i.attrs.name)){let n=i.attrs.view===`preview`;l.push({id:`pdfView`,label:n?a.showAsFile:a.showPages,icon:n?`paperclip`:`file`,run:()=>e.view.dispatch(e.state.tr.setNodeAttribute(t,`view`,n?`card`:`preview`))})}return c>0&&l.push({id:`moveUp`,label:a.moveUp,icon:`arrow-up`,run:()=>{let n=e.state.doc.child(c-1),r=e.state.tr.delete(t,o).insert(t-n.nodeSize,i);e.view.dispatch(r.scrollIntoView())}}),c{let n=e.state.doc.child(c+1),r=e.state.tr.delete(t,o).insert(t+n.nodeSize,i);e.view.dispatch(r.scrollIntoView())}}),l.push({id:`duplicate`,label:a.duplicate,icon:`plus`,run:()=>{let t=e.schema.nodeFromJSON(zj(i.toJSON()));e.view.dispatch(e.state.tr.insert(o,t).scrollIntoView())}},{id:`copy`,label:a.copy,icon:`copy`,run:()=>{e.chain().focus().setNodeSelection(t).run(),document.execCommand(`copy`)}}),r&&l.push({id:`copyLink`,label:n.blocks.copyBlockLink,icon:`link`,run:r}),l.push({id:`delete`,label:a.delete,icon:`trash`,danger:!0,run:()=>{e.view.dispatch(e.state.tr.delete(t,o)),e.commands.focus()}}),l}function Vj(e,t,n,r){let i=document.createElement(`div`);i.className=`dw-suggest dw-block-menu`,i.setAttribute(`role`,`menu`),i.setAttribute(`aria-label`,n);let a=t,o=0,s=[],c=()=>{i.replaceChildren(),a.forEach((e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`dw-suggest__item${t===o?` is-active`:``}${e.danger?` is-danger`:``}`,n.setAttribute(`role`,`menuitem`),n.tabIndex=-1,e.children&&n.setAttribute(`aria-haspopup`,`menu`);let r=document.createElement(`span`);r.className=`dw-suggest__icon`,r.append(Fj(e.icon));let a=document.createElement(`span`);if(a.className=`dw-suggest__label`,a.textContent=e.label,n.append(r,a),e.children){let e=Fj(`chevron-right`,14);e.classList.add(`dw-block-menu__more`),n.append(e)}n.addEventListener(`mousedown`,e=>e.preventDefault()),n.addEventListener(`click`,()=>l(t)),n.addEventListener(`mouseenter`,()=>{o=t;for(let[e,n]of[...i.children].entries())n.classList.toggle(`is-active`,e===t)}),i.append(n)}),i.children[o]?.focus()},l=e=>{let t=a[e];t&&(t.children?(s.push(a),a=t.children,o=0,c()):(m(),t.run?.()))},u=e=>{e.key===`Escape`||e.key===`ArrowLeft`&&s.length?(e.preventDefault(),e.stopPropagation(),s.length?(a=s.pop(),o=0,c()):m()):e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),o=(o+(e.key===`ArrowDown`?1:-1)+a.length)%a.length,c()):(e.key===`Enter`||e.key===` `||e.key===`ArrowRight`)&&(e.preventDefault(),(e.key!==`ArrowRight`||a[o]?.children)&&l(o))},d=t=>{!i.contains(t.target)&&!e.contains(t.target)&&m()};document.body.append(i);let f=wj(e,i,()=>{Oj(e,i,{placement:`bottom-start`,strategy:`fixed`,middleware:[Tj(4),Dj(),Ej({padding:8})]}).then(({x:e,y:t})=>Object.assign(i.style,{left:`${e}px`,top:`${t}px`}))});i.addEventListener(`keydown`,u),document.addEventListener(`mousedown`,d,!0);let p=!1;function m(){p||(p=!0,f(),i.remove(),document.removeEventListener(`mousedown`,d,!0),s=[],r?.())}return c(),m}var Hj=[`paragraph`,`heading`,`blockquote`,`codeBlock`,`bulletList`,`orderedList`,`taskList`,`callout`,`table`,`details`,`image`,`embed`,`linkCard`,`mermaid`,`blockMath`,`drawio`,`excalidraw`,`fileAttachment`],Uj=/^[a-z0-9]{6,16}$/,Wj=e=>`#b-${e}`;function Gj(){return[...crypto.getRandomValues(new Uint8Array(8))].map(e=>(e%36).toString(36)).join(``)}function Kj(e,t){let n=e.state.doc.nodeAt(t);if(!n)return null;let r=n.attrs.blockId;if(r)return r;if(!e.editable||!Hj.includes(n.type.name))return null;let i=Gj();return e.dispatch(e.state.tr.setNodeAttribute(t,`blockId`,i)),i}async function qj(e,t,n,r){let i=Kj(e,t);if(!i)return!1;let a=n(Wj(i));try{await navigator.clipboard.writeText(a),r?.(a)}catch{window.prompt(``,a)}return!0}var Jj=Tp.create({name:`blockLinks`,addOptions(){return{labels:null,link:void 0,onCopied:void 0}},addGlobalAttributes(){return[{types:Hj,attributes:{blockId:{default:null,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-block-id`);return t&&Uj.test(t)?t:null},renderHTML:e=>e.blockId?{"data-block-id":e.blockId}:{}}}}]},addKeyboardShortcuts(){let{link:e,onCopied:t}=this.options;return{"Mod-Shift-c":({editor:n})=>{if(!e)return!1;let r=n.state.selection.$from;if(r.depth<1)return!1;let i=r.before(1),a=n.state.doc.nodeAt(i);return!a||!Hj.includes(a.type.name)||!a.attrs.blockId&&!n.isEditable?!1:(qj(n.view,i,e,t),!0)}}},addProseMirrorPlugins(){let{link:e,onCopied:t}=this.options,n=this.options.labels,r=this.editor;return[new E({key:new D(`blockLinks`),view:i=>new Zj(i,r,n,e,t)})]}}),Yj=``,Xj=``,Zj=class{view;editor;labels;link;onCopied;gutter=document.createElement(`div`);linkButton=document.createElement(`button`);grip=document.createElement(`button`);pos=-1;closeMenu=null;constructor(e,t,n,r,i){this.view=e,this.editor=t,this.labels=n,this.link=r,this.onCopied=i;let a=this.gutter;a.className=`dw-block-gutter`,a.contentEditable=`false`,a.hidden=!0,a.addEventListener(`mouseleave`,this.leave);let o=this.linkButton;o.type=`button`,o.className=`dw-block-handle`,o.setAttribute(`aria-label`,n.blocks.copyBlockLink),o.title=n.blocks.copyBlockLink,o.innerHTML=Yj,o.addEventListener(`mousedown`,e=>e.preventDefault()),o.addEventListener(`click`,()=>void this.copy());let s=this.grip;s.type=`button`,s.className=`dw-block-handle dw-block-grip`,s.setAttribute(`aria-label`,n.blockMenu.open),s.setAttribute(`aria-haspopup`,`menu`),s.setAttribute(`aria-expanded`,`false`),s.title=n.blockMenu.open,s.innerHTML=Xj,s.draggable=!0,s.addEventListener(`click`,this.openMenu),s.addEventListener(`dragstart`,this.dragStart),s.addEventListener(`dragend`,()=>this.hide()),r&&a.append(o),a.append(s),e.dom.addEventListener(`mousemove`,this.move),e.dom.addEventListener(`mouseleave`,this.leave)}get host(){let e=this.view.dom.parentElement;return e&&this.gutter.parentElement!==e&&(e.classList.add(`dw-block-host`),e.append(this.gutter)),e}hide=()=>{this.closeMenu||(this.gutter.hidden=!0,this.pos=-1)};leave=e=>{let t=e.relatedTarget;t&&(this.gutter.contains(t)||this.view.dom.contains(t))||this.hide()};move=e=>{if(this.closeMenu)return;let t=e.target;for(;t&&t.parentElement!==this.view.dom;)t=t.parentElement;let n=this.host;if(!t||!n)return this.hide();let r;try{r=this.view.posAtDOM(t,0)}catch{return this.hide()}let i=this.view.state.doc.resolve(Math.min(r,this.view.state.doc.content.size)),a=i.depth>=1?i.before(1):r,o=this.view.state.doc.nodeAt(a);if(!o)return this.hide();let s=!!this.link&&Hj.includes(o.type.name)&&(!!o.attrs.blockId||this.view.editable),c=this.view.editable;if(!s&&!c)return this.hide();this.linkButton.hidden=!s,this.grip.hidden=!c,this.pos=a;let l=t.getBoundingClientRect(),u=n.getBoundingClientRect();this.gutter.style.top=`${l.top-u.top+Math.min(l.height/2,14)-11}px`,this.gutter.hidden=!1};openMenu=()=>{if(this.closeMenu){this.closeMenu();return}let e=this.pos;if(e<0||!this.view.editable)return;let t=this.view.state.doc.nodeAt(e),n=!!this.link&&!!t&&Hj.includes(t.type.name),r=Bj(this.editor,e,this.labels,n?()=>void this.copy(e):void 0);this.grip.setAttribute(`aria-expanded`,`true`),this.closeMenu=Vj(this.grip,r,this.labels.blockMenu.open,()=>{this.closeMenu=null,this.grip.setAttribute(`aria-expanded`,`false`),this.hide()})};dragStart=e=>{let t=this.pos;if(t<0||!e.dataTransfer)return;this.closeMenu?.();let n=T.create(this.view.state.doc,t);this.view.dispatch(this.view.state.tr.setSelection(n)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,n.node.textContent);let r=this.view.nodeDOM(t);r instanceof HTMLElement&&e.dataTransfer.setDragImage(r,0,0),this.view.dragging={slice:n.content(),move:!0}};async copy(e=this.pos){e>=0&&this.link&&await qj(this.view,e,this.link,this.onCopied)}update(){this.pos>=this.view.state.doc.content.size&&this.hide()}destroy(){this.closeMenu?.(),this.gutter.parentElement?.classList.remove(`dw-block-host`),this.gutter.remove(),this.view.dom.removeEventListener(`mousemove`,this.move),this.view.dom.removeEventListener(`mouseleave`,this.leave)}},Qj,$j;if(typeof WeakMap<`u`){let e=new WeakMap;Qj=t=>e.get(t),$j=(t,n)=>(e.set(t,n),n)}else{let e=[],t=0;Qj=t=>{for(let n=0;n(t==10&&(t=0),e[t++]=n,e[t++]=r)}var eM=class{constructor(e,t,n,r){this.width=e,this.height=t,this.map=n,this.problems=r}findCell(e){for(let t=0;t=n){(a||=[]).push({type:`overlong_rowspan`,pos:c,n:f-e});break}let l=i+e*t;for(let e=0;er&&(a+=i.attrs.colspan)}}for(let e=0;e1&&(n=!0)}t==-1?t=a:t!=a&&(t=Math.max(t,a))}return t}function rM(e,t,n){e.problems||=[];let r={};for(let i=0;i0;t--)if(e.node(t).type.spec.tableRole==`row`)return e.node(0).resolve(e.before(t+1));return null}function cM(e){for(let t=e.depth;t>0;t--){let n=e.node(t).type.spec.tableRole;if(n===`cell`||n===`header_cell`)return e.node(t)}return null}function lM(e){let t=e.selection.$head;for(let e=t.depth;e>0;e--)if(t.node(e).type.spec.tableRole==`row`)return!0;return!1}function uM(e){let t=e.selection;if(`$anchorCell`in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if(`node`in t&&t.node&&t.node.type.spec.tableRole==`cell`)return t.$anchor;let n=sM(t.$head)||dM(t.$head);if(n)return n;throw RangeError(`No cell found around position ${t.head}`)}function dM(e){for(let t=e.nodeAfter,n=e.pos;t;t=t.firstChild,n++){let r=t.type.spec.tableRole;if(r==`cell`||r==`header_cell`)return e.doc.resolve(n)}for(let t=e.nodeBefore,n=e.pos;t;t=t.lastChild,n--){let r=t.type.spec.tableRole;if(r==`cell`||r==`header_cell`)return e.doc.resolve(n-t.nodeSize)}}function fM(e){return e.parent.type.spec.tableRole==`row`&&!!e.nodeAfter}function pM(e){return e.node(0).resolve(e.pos+e.nodeAfter.nodeSize)}function mM(e,t){return e.depth==t.depth&&e.pos>=t.start(-1)&&e.pos<=t.end(-1)}function hM(e,t,n){let r=e.node(-1),i=eM.get(r),a=e.start(-1),o=i.nextCell(e.pos-a,t,n);return o==null?null:e.node(0).resolve(a+o)}function gM(e,t,n=1){let r={...e,colspan:e.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(t,n),r.colwidth.some(e=>e>0)||(r.colwidth=null)),r}function _M(e,t,n=1){let r={...e,colspan:e.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let e=0;ee!=t.pos-i);s.unshift(t.pos-i);let c=s.map(e=>{let t=n.nodeAt(e);if(!t)throw RangeError(`No cell with offset ${e} found`);let r=i+e+1;return new Cn(o.resolve(r),o.resolve(r+t.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=t}map(t,n){let r=t.resolve(n.map(this.$anchorCell.pos)),i=t.resolve(n.map(this.$headCell.pos));if(fM(r)&&fM(i)&&mM(r,i)){let t=this.$anchorCell.node(-1)!=r.node(-1);return t&&this.isRowSelection()?e.rowSelection(r,i):t&&this.isColSelection()?e.colSelection(r,i):new e(r,i)}return w.between(r,i)}content(){let e=this.$anchorCell.node(-1),t=eM.get(e),n=this.$anchorCell.start(-1),r=t.rectBetween(this.$anchorCell.pos-n,this.$headCell.pos-n),i={},a=[];for(let n=r.top;n0||u>0){let e=c.attrs;if(l>0&&(e=gM(e,0,l)),u>0&&(e=gM(e,e.colspan-u,u)),s.leftr.bottom){let e={...c.attrs,rowspan:Math.min(s.bottom,r.bottom)-Math.max(s.top,r.top)};c=s.top0)return!1;let n=e+this.$anchorCell.nodeAfter.attrs.rowspan,r=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(n,r)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){let r=t.node(-1),i=eM.get(r),a=t.start(-1),o=i.findCell(t.pos-a),s=i.findCell(n.pos-a),c=t.node(0);return o.top<=s.top?(o.top>0&&(t=c.resolve(a+i.map[o.left])),s.bottom0&&(n=c.resolve(a+i.map[s.left])),o.bottom0)return!1;let a=r+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(a,o)==t.width}eq(t){return t instanceof e&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){let r=t.node(-1),i=eM.get(r),a=t.start(-1),o=i.findCell(t.pos-a),s=i.findCell(n.pos-a),c=t.node(0);return o.left<=s.left?(o.left>0&&(t=c.resolve(a+i.map[o.top*i.width])),s.right0&&(n=c.resolve(a+i.map[s.top*i.width])),o.right{t.push(vs.node(n,n+e.nodeSize,{class:`selectedCell`}))}),xs.create(e.doc,t)}function SM({$from:e,$to:t}){if(e.pos==t.pos||e.pos=0&&!(e.after(i+1)=0&&!(t.before(e+1)>t.start(e));e--,r--);return n==r&&/row|table/.test(e.node(i).type.spec.tableRole)}function CM({$from:e,$to:t}){let n,r;for(let t=e.depth;t>0;t--){let r=e.node(t);if(r.type.spec.tableRole===`cell`||r.type.spec.tableRole===`header_cell`){n=r;break}}for(let e=t.depth;e>0;e--){let n=t.node(e);if(n.type.spec.tableRole===`cell`||n.type.spec.tableRole===`header_cell`){r=n;break}}return n!==r&&t.parentOffset===0}function wM(e,t,n){let r=(t||e).selection,i=(t||e).doc,a,o;if(r instanceof T&&(o=r.node.type.spec.tableRole)){if(o==`cell`||o==`header_cell`)a=yM.create(i,r.from);else if(o==`row`){let e=i.resolve(r.from+1);a=yM.rowSelection(e,e)}else if(!n){let e=eM.get(r.node),t=r.from+1,n=t+e.map[e.width*e.height-1];a=yM.create(i,t+1,n)}}else r instanceof w&&SM(r)?a=w.create(i,r.from):r instanceof w&&CM(r)&&(a=w.create(i,r.$from.start(),r.$from.end()));return a&&(t||=e.tr).setSelection(a),t}var TM=new D(`fix-tables`);function EM(e,t,n,r){let i=e.childCount,a=t.childCount;outer:for(let o=0,s=0;o{t.type.spec.tableRole==`table`&&(n=OM(e,t,r,n))};return t?t.doc!=e.doc&&EM(t.doc,e.doc,0,r):e.doc.descendants(r),n}function OM(e,t,n,r){let i=eM.get(t);if(!i.problems)return r;r||=e.tr;let a=[];for(let e=0;e0){let t=`cell`;n.firstChild&&(t=n.firstChild.type.spec.tableRole);let a=[];for(let n=0;n0?-1:0;vM(t,r,i+a)&&(a=i==0||i==t.width?null:0);for(let o=0;o0&&i0&&t.map[s-1]==c||i0?-1:0;FM(t,r,i+s)&&(s=i==0||i==t.height?null:0);for(let a=0,c=t.width*i;a0&&i0&&l==t.map[o-t.width]){let t=n.nodeAt(l).attrs;e.setNodeMarkup(e.mapping.slice(s).map(l+r),null,{...t,rowspan:t.rowspan-1}),a+=t.colspan-1}else if(i0&&n[a]==n[a-1]||r.right0&&n[i]==n[i-e]||r.bottom0){let e=c+1+l.content.size,t=VM(l)?c+1:e;n.replaceWith(t+r.tableStart,e+r.tableStart,o)}n.setSelection(new yM(n.doc.resolve(c+r.tableStart))),t(n)}return!0}function WM(e,t){let n=aM(e.schema);return GM(({node:e})=>n[e.type.spec.tableRole])(e,t)}function GM(e){return(t,n)=>{let r=t.selection,i,a;if(r instanceof yM){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;i=r.$anchorCell.nodeAfter,a=r.$anchorCell.pos}else{if(i=cM(r.$from),!i)return!1;a=sM(r.$from)?.pos}if(i==null||a==null||i.attrs.colspan==1&&i.attrs.rowspan==1)return!1;if(n){let o=i.attrs,s=[],c=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});let l=kM(t),u=t.tr;for(let e=0;e{n.attrs[e]!==t&&a.setNodeMarkup(r,null,{...n.attrs,[e]:t})}):a.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[e]:t}),r(a)}return!0}}function qM(e){return function(t,n){if(!lM(t))return!1;if(n){let r=aM(t.schema),i=kM(t),a=t.tr,o=i.map.cellsInRect(e==`column`?{left:i.left,top:0,right:i.right,bottom:i.map.height}:e==`row`?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),s=o.map(e=>i.table.nodeAt(e));for(let e=0;e{let t=e+i.tableStart,n=a.doc.nodeAt(t);n&&a.setNodeMarkup(t,u,n.attrs)}),n(a)}return!0}}YM(`row`,{useDeprecatedLogic:!0}),YM(`column`,{useDeprecatedLogic:!0});var XM=YM(`cell`,{useDeprecatedLogic:!0});function ZM(e,t){if(t<0){let t=e.nodeBefore;if(t)return e.pos-t.nodeSize;for(let t=e.index(-1)-1,n=e.before();t>=0;t--){let r=e.node(-1).child(t),i=r.lastChild;if(i)return n-1-i.nodeSize;n-=r.nodeSize}}else{if(e.index()0;r--)if(n.node(r).type.spec.tableRole==`table`)return t&&t(e.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function eN(e,t){let n=e.selection;if(!(n instanceof yM))return!1;if(t){let r=e.tr,i=aM(e.schema).cell.createAndFill().content;n.forEachCell((e,t)=>{e.content.eq(i)||r.replace(r.mapping.map(t+1),r.mapping.map(t+e.nodeSize-1),new p(i,0,0))}),r.docChanged&&t(r)}return!0}function tN(e){if(e.size===0)return null;let{content:t,openStart:n,openEnd:r}=e;for(;t.childCount==1&&(n>0&&r>0||t.child(0).type.spec.tableRole==`table`);)n--,r--,t=t.child(0).content;let i=t.child(0),a=i.type.spec.tableRole,o=i.type.schema,s=[];if(a==`row`)for(let e=0;e=0;t--){let{rowspan:i,colspan:a}=r.child(t).attrs;for(let t=e;t=t.length&&t.push(s.empty),n[i]r&&(s=s.type.createChecked(gM(s.attrs,s.attrs.colspan,n+s.attrs.colspan-r),s.content)),o.push(s),n+=s.attrs.colspan;for(let n=1;ni&&(t=t.type.create({...t.attrs,rowspan:Math.max(1,i-t.attrs.rowspan)},t.content)),o.push(t)}e.push(s.from(o))}n=e,t=i}return{width:e,height:t,rows:n}}function aN(e,t,n,r,i,a,o){let c=e.doc.type.schema,l=aM(c),u,d;if(i>t.width)for(let a=0,s=0;at.height){let c=[];for(let e=0,r=(t.height-1)*t.width;e=t.width?!1:n.nodeAt(t.map[r+e]).type==l.header_cell;c.push(i?d||=l.header_cell.createAndFill():u||=l.cell.createAndFill())}let f=l.row.create(null,s.from(c)),p=[];for(let e=t.height;e{if(!i)return!1;let a=n.selection;if(a instanceof yM)return uN(n,r,C.near(a.$headCell,t));if(e!=`horiz`&&!a.empty)return!1;let o=gN(i,e,t);if(o==null)return!1;if(e==`horiz`)return uN(n,r,C.near(n.doc.resolve(a.head+t),t));{let i=n.doc.resolve(o),a=hM(i,e,t),s;return s=a?C.near(a,1):t<0?C.near(n.doc.resolve(i.before(-1)),-1):C.near(n.doc.resolve(i.after(-1)),1),uN(n,r,s)}}}function fN(e,t){return(n,r,i)=>{if(!i)return!1;let a=n.selection,o;if(a instanceof yM)o=a;else{let r=gN(i,e,t);if(r==null)return!1;o=new yM(n.doc.resolve(r))}let s=hM(o.$headCell,e,t);return s?uN(n,r,new yM(o.$anchorCell,s)):!1}}function pN(e,t){let n=e.state.doc,r=sM(n.resolve(t));return r?(e.dispatch(e.state.tr.setSelection(new yM(r))),!0):!1}function mN(e,t,n){if(!lM(e.state))return!1;let r=tN(n),i=e.state.selection;if(i instanceof yM){r||={width:1,height:1,rows:[s.from(rN(aM(e.state.schema).cell,n))]};let t=i.$anchorCell.node(-1),a=i.$anchorCell.start(-1),o=eM.get(t).rectBetween(i.$anchorCell.pos-a,i.$headCell.pos-a);return r=iN(r,o.right-o.left,o.bottom-o.top),cN(e.state,e.dispatch,a,o,r),!0}if(r){let t=uM(e.state),n=t.start(-1);return cN(e.state,e.dispatch,n,eM.get(t.node(-1)).findCell(t.pos-n),r),!0}return!1}function hN(e,t){if(t.button!=0||t.ctrlKey||t.metaKey)return;let n=_N(e,t.target),r;if(t.shiftKey&&e.state.selection instanceof yM)i(e.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&n&&(r=sM(e.state.selection.$anchor))!=null&&vN(e,t)?.pos!=r.pos)i(r,t),t.preventDefault();else if(!n)return;function i(t,n){let r=vN(e,n),i=oM.getState(e.state)==null;if(!r||!mM(t,r)){if(i)r=t;else return}let a=new yM(t,r);if(i||!e.state.selection.eq(a)){let n=e.state.tr.setSelection(a);i&&n.setMeta(oM,t.pos),e.dispatch(n)}}function a(){e.root.removeEventListener(`mouseup`,a),e.root.removeEventListener(`dragstart`,a),e.root.removeEventListener(`mousemove`,o),oM.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta(oM,-1))}function o(r){let o=r,s=oM.getState(e.state),c;if(s!=null)c=e.state.doc.resolve(s);else if(_N(e,o.target)!=n&&(c=vN(e,t),!c))return a();c&&i(c,o)}e.root.addEventListener(`mouseup`,a),e.root.addEventListener(`dragstart`,a),e.root.addEventListener(`mousemove`,o)}function gN(e,t,n){if(!(e.state.selection instanceof w))return null;let{$head:r}=e.state.selection;for(let i=r.depth-1;i>=0;i--){let a=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:a.childCount))return null;if(a.type.spec.tableRole==`cell`||a.type.spec.tableRole==`header_cell`){let a=r.before(i),o=t==`vert`?n>0?`down`:`up`:n>0?`right`:`left`;return e.endOfTextblock(o)?a:null}}return null}function _N(e,t){for(;t&&t!=e.dom;t=t.parentNode)if(t.nodeName==`TD`||t.nodeName==`TH`)return t;return null}function vN(e,t){let n=e.posAtCoords({left:t.clientX,top:t.clientY});if(!n)return null;let{inside:r,pos:i}=n;return r>=0&&sM(e.state.doc.resolve(r))||sM(e.state.doc.resolve(i))}var yN=class{constructor(e,t){this.node=e,this.defaultCellMinWidth=t,this.dom=document.createElement(`div`),this.dom.className=`tableWrapper`,this.table=this.dom.appendChild(document.createElement(`table`)),this.table.style.setProperty(`--default-cell-min-width`,`${t}px`),this.colgroup=this.table.appendChild(document.createElement(`colgroup`)),bN(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement(`tbody`))}update(e){return e.type==this.node.type&&(this.node=e,bN(e,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(e){return e.type==`attributes`&&(e.target==this.table||this.colgroup.contains(e.target))}};function bN(e,t,n,r,i,a){let o=0,s=!0,c=t.firstChild,l=e.firstChild;if(l){for(let e=0,n=0;enew r(e,n,t)),new CN(-1,!1)},apply(e,t){return t.apply(e)}},props:{attributes:e=>{let t=xN.getState(e);return t&&t.activeHandle>-1?{class:`resize-cursor`}:{}},handleDOMEvents:{mousemove:(t,n)=>{wN(t,n,e,i)},mouseleave:e=>{TN(e)},mousedown:(e,r)=>{EN(e,r,t,n)}},decorations:e=>{let t=xN.getState(e);if(t&&t.activeHandle>-1)return FN(e,t.activeHandle)},nodeViews:{}}});return a}var CN=class e{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(t){let n=this,r=t.getMeta(xN);if(r&&r.setHandle!=null)return new e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let r=t.mapping.map(n.activeHandle,-1);return fM(t.doc.resolve(r))||(r=-1),new e(r,n.dragging)}return n}};function wN(e,t,n,r){if(!e.editable)return;let i=xN.getState(e.state);if(i&&!i.dragging){let a=ON(t.target),o=-1;if(a){let{left:r,right:i}=a.getBoundingClientRect();t.clientX-r<=n?o=kN(e,t,`left`,n):i-t.clientX<=n&&(o=kN(e,t,`right`,n))}if(o!=i.activeHandle){if(!r&&o!==-1){let t=e.state.doc.resolve(o),n=t.node(-1),r=eM.get(n),i=t.start(-1);if(r.colCount(t.pos-i)+t.nodeAfter.attrs.colspan-1==r.width-1)return}jN(e,o)}}}function TN(e){if(!e.editable)return;let t=xN.getState(e.state);t&&t.activeHandle>-1&&!t.dragging&&jN(e,-1)}function EN(e,t,n,r){if(!e.editable)return!1;let i=e.dom.ownerDocument.defaultView??window,a=xN.getState(e.state);if(!a||a.activeHandle==-1||a.dragging)return!1;let o=e.state.doc.nodeAt(a.activeHandle),s=DN(e,a.activeHandle,o.attrs);e.dispatch(e.state.tr.setMeta(xN,{setDragging:{startX:t.clientX,startWidth:s}}));function c(t){i.removeEventListener(`mouseup`,c),i.removeEventListener(`mousemove`,l);let r=xN.getState(e.state);r?.dragging&&(MN(e,r.activeHandle,AN(r.dragging,t,n)),e.dispatch(e.state.tr.setMeta(xN,{setDragging:null})))}function l(t){if(!t.which)return c(t);let i=xN.getState(e.state);if(i&&i.dragging){let a=AN(i.dragging,t,n);NN(e,i.activeHandle,a,r)}}return NN(e,a.activeHandle,s,r),i.addEventListener(`mouseup`,c),i.addEventListener(`mousemove`,l),t.preventDefault(),!0}function DN(e,t,{colspan:n,colwidth:r}){let i=r&&r[r.length-1];if(i)return i;let a=e.domAtPos(t),o=a.node.childNodes[a.offset].offsetWidth,s=n;if(r)for(let e=0;eRN(e),renderHTML:e=>{let t=LN(e.align);return Pf(t)?{style:`text-align: ${t}`}:{}}}}function VN(e){let t=e.parentElement,n=e.closest(`table`);if(!t||!n)return null;let r=Array.from(t.children).indexOf(e),i=n.querySelectorAll(`colgroup > col`)[r]?.getAttribute(`width`);return i?[parseInt(i,10)]:null}function HN(e){let t=e.getAttribute(`colwidth`);return t?t.split(`,`).map(e=>parseInt(e,10)):VN(e)}var UN=/[ \t\r\n\f]+/g;function WN(e){return e.children.length>0?!1:(e.textContent??``).replace(UN,``)===``}function GN(e){let t=e.createAndFill();if(!t)throw Error(`[tiptap error]: "${e.name}" has no default content to backfill.`);return t.content}function KN(e,t,n){if(!(n in t))return;let r=t[n];(r===1||r===`1`||r==null)&&delete e[n]}var qN=Jp.create({name:`tableCell`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:HN},align:BN()}},tableRole:`cell`,isolating:!0,parseHTML(){return[{tag:`td`,getAttrs:e=>WN(e)?{}:!1,getContent:(e,t)=>GN(t.nodes[this.name])},{tag:`td`}]},renderHTML({HTMLAttributes:e}){let t=A(this.options.HTMLAttributes,e);return KN(t,e,`colspan`),KN(t,e,`rowspan`),[`td`,t,0]}}),JN=Jp.create({name:`tableHeader`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:HN},align:BN()}},tableRole:`header_cell`,isolating:!0,parseHTML(){return[{tag:`th`,getAttrs:e=>WN(e)?{}:!1,getContent:(e,t)=>GN(t.nodes[this.name])},{tag:`th`}]},renderHTML({HTMLAttributes:e}){let t=A(this.options.HTMLAttributes,e);return KN(t,e,`colspan`),KN(t,e,`rowspan`),[`th`,t,0]}}),YN=Jp.create({name:`tableRow`,addOptions(){return{HTMLAttributes:{}}},content:`(tableCell | tableHeader)*`,tableRole:`row`,parseHTML(){return[{tag:`tr`}]},renderHTML({HTMLAttributes:e}){return[`tr`,A(this.options.HTMLAttributes,e),0]}});function XN(e,t){return t?[`width`,`${Math.max(t,e)}px`]:[`min-width`,`${e}px`]}function ZN(e,t,n,r,i,a){let o=0,s=!0,c=t.firstChild,l=e.firstChild;if(l!==null)for(let e=0,n=0;e{let r=e.nodes[n];r.spec.tableRole&&(t[r.spec.tableRole]=r)}),e.cached.tableNodeTypes=t,t}function nP(e,t,n,r,i){let a=tP(e),o=[],s=[];for(let e=0;e{let{selection:t}=e.state;if(!rP(t))return!1;let n=0;return vu(t.ranges[0].$from,e=>e.type.name===`table`)?.node.descendants(e=>{if(e.type.name===`table`)return!1;[`tableCell`,`tableHeader`].includes(e.type.name)&&(n+=1)}),n===t.ranges.length&&(e.commands.deleteTable(),!0)};function aP(e,t){let n=e.mapping.map(t);if(vu(e.selection.$from,e=>e.type.name===`table`)?.pos===n)return;let r=e.doc.nodeAt(n);if(!r)return;let i=n+r.nodeSize-1;e.setSelection(w.near(e.doc.resolve(i),-1))}function oP(e){let t=``,n=0;for(;ne===`|`?`\\|`:e)+e.slice(i,i+r),n=i+r,a=!0;break}i+=o}a||(t+=e.slice(n,n+r),n+=r)}return t}function sP(e){return e.split(` +`))};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 8l-6 8h12v-2`],diagram:[`M4 4h6v5H4z`,`M14 15h6v5h-6z`,`M7 9v4a2 2 0 0 0 2 2h5`],video:[`M4 6h11v12H4z`,`M15 10l5-3v10l-5-3`],archive:[`M4 5h16v4H4z`,`M5 9v10h14V9`,`M10 13h4`],pin:[`M9 4h6`,`M10 4v6l-3 4h10l-3-4V4`,`M12 14v6`],width:[`M3 12h18`,`M7 8l-4 4 4 4`,`M17 8l4 4-4 4`],type:[`M5 7V5h14v2`,`M12 5v14`,`M9 19h6`],server:[`M4 4h16v6H4z`,`M4 14h16v6H4z`,`M8 7h.01`,`M8 17h.01`],users:[`M9 11a3.5 3.5 0 1 0 0-7a3.5 3.5 0 1 0 0 7z`,`M3 20a6 6 0 0 1 12 0`,`M16 4.5a3.5 3.5 0 0 1 0 6.5`,`M18 14a6 6 0 0 1 3 6`],"align-left":[`M4 6h16`,`M4 10h10`,`M4 14h16`,`M4 18h10`],"align-center":[`M4 6h16`,`M7 10h10`,`M4 14h16`,`M7 18h10`],"align-right":[`M4 6h16`,`M10 10h10`,`M4 14h16`,`M10 18h10`],grip:[`M9 6h.01`,`M15 6h.01`,`M9 12h.01`,`M15 12h.01`,`M9 18h.01`,`M15 18h.01`],copy:[`M9 9h11v11H9z`,`M5 15H4V4h11v1`],"arrow-up":[`M12 19V5`,`M6 11l6-6 6 6`],"arrow-down":[`M12 5v14`,`M6 13l6 6 6-6`],callout:[`M4 5h16v14H4z`,`M8 10h.01`,`M11 10h5`,`M8 14h8`],palette:[`M12 3a9 9 0 1 0 0 18c1 0 1.5-.7 1.5-1.5 0-1.2-1-1.5-1-2.5s.8-1.5 2-1.5H17a4 4 0 0 0 4-4c0-4.7-4-8.5-9-8.5z`,`M7.5 11h.01`,`M10 7.5h.01`,`M14.5 7.5h.01`],"page-plus":[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M12 11v6`,`M9 14h6`],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`]},Pj=`http://www.w3.org/2000/svg`;function Fj(e,t=18){let n=document.createElementNS(Pj,`svg`);for(let[e,r]of Object.entries({width:String(t),height:String(t),viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.75`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`}))n.setAttribute(e,r);for(let t of Nj[e]){let e=document.createElementNS(Pj,`path`);e.setAttribute(`d`,t),n.append(e)}return n}function Ij(e){return()=>{let t=null,n=null,r=null,i=0,a=null,o=()=>a?.items??r?.items??[],s=t=>{let n=o()[t];if(!r||n===void 0)return;let s=e.children?.(n);s?.length?(a={parent:n,items:s},i=0,c()):e.pick(r,n)},c=()=>{if(!t||!r)return;let n=r;if(t.replaceChildren(),e.showQuery){let e=document.createElement(`div`);e.className=`dw-suggest__query`,e.textContent=`/${n.query}`,t.append(e)}if(a){let n=document.createElement(`div`);n.className=`dw-suggest__query`,n.textContent=`‹ ${e.toItem(a.parent).label}`,t.append(n)}let c=o();if(c.length)c.forEach((n,r)=>{let a=e.toItem(n),o=document.createElement(`div`);o.className=r===i?`dw-suggest__item is-active`:`dw-suggest__item`,o.setAttribute(`role`,`option`),o.setAttribute(`aria-selected`,String(r===i)),o.addEventListener(`mousedown`,e=>{e.preventDefault(),s(r)});let c=document.createElement(`span`);c.className=`dw-suggest__icon`,c.append(Fj(a.icon??`text`));let l=document.createElement(`span`);l.className=`dw-suggest__text`;let u=document.createElement(`span`);if(u.className=`dw-suggest__label`,u.textContent=a.label,l.append(u),a.description){let e=document.createElement(`span`);e.className=`dw-suggest__desc`,e.textContent=a.description,l.append(e)}if(o.append(c,l),e.children?.(n)?.length){o.setAttribute(`aria-haspopup`,`listbox`);let e=Fj(`chevron-right`,14);e.classList.add(`dw-suggest__more`),o.append(e)}t.append(o)}),t.querySelector(`.is-active`)?.scrollIntoView({block:`nearest`});else{let n=document.createElement(`div`);n.className=`dw-suggest__empty`,n.setAttribute(`role`,`status`),n.textContent=e.empty,t.append(n)}},l=()=>{let e=r?.clientRect?.();if(!t||!e)return;let i={getBoundingClientRect:()=>r?.clientRect?.()??e};n?.(),n=wj(i,t,()=>{t&&Oj(i,t,{placement:`bottom-start`,strategy:`fixed`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:n})=>{t&&Object.assign(t.style,{left:`${e}px`,top:`${n}px`})})})},u=()=>{n?.(),n=null,t?.remove(),t=null};return{onStart(n){r=n,i=0,a=null,t=document.createElement(`div`),t.className=`dw-suggest`,t.setAttribute(`role`,`listbox`),t.setAttribute(`aria-label`,e.label),document.body.append(t),c(),l()},onUpdate(e){e.items!==r?.items&&(i=0,a=null),r=e,c(),l()},onKeyDown({event:t}){let n=o().length;if(a&&(t.key===`Escape`||t.key===`ArrowLeft`))return a=null,i=0,c(),!0;let r=o()[i];return t.key===`ArrowRight`&&r!==void 0&&e.children?.(r)?.length?(s(i),!0):t.key===`Escape`?(u(),!0):n?t.key===`ArrowDown`||t.key===`ArrowUp`?(i=(i+(t.key===`ArrowDown`?1:-1)+n)%n,c(),!0):t.key===`Enter`||t.key===`Tab`?(s(i),!0):!1:!1},onExit(){r=null,u()}}}}var Lj=[[`text`,`text`,e=>e],[`h1`,`heading`,e=>e.setNode(`heading`,{level:1})],[`h2`,`heading`,e=>e.setNode(`heading`,{level:2})],[`h3`,`heading`,e=>e.setNode(`heading`,{level:3})],[`bullet`,`list`,e=>e.toggleBulletList()],[`ordered`,`list-ordered`,e=>e.toggleOrderedList()],[`todo`,`todo`,e=>e.toggleTaskList()],[`quote`,`quote`,e=>e.setBlockquote()],[`code`,`code`,e=>e.setCodeBlock()],[`callout`,`callout`,e=>e.setCallout()]],Rj=[`paragraph`,`heading`,`codeBlock`,`blockquote`,`bulletList`,`orderedList`,`taskList`,`callout`];function zj(e){let t={...e};return t.attrs&&`blockId`in t.attrs&&(t.attrs={...t.attrs,blockId:null}),t.content&&=t.content.map(zj),t}function Bj(e,t,n,r){let i=e.state.doc.nodeAt(t);if(!i)return[];let a=n.blockMenu,o=t+i.nodeSize,c=e.state.doc.resolve(t).index(0),l=[];if(Rj.includes(i.type.name)&&l.push({id:`turnInto`,label:a.turnInto,icon:`text`,children:Lj.map(([r,a,c])=>({id:r,icon:a,label:n.slash[r]?.label??r,run:()=>{if(r===`callout`){if(i.type.name===`callout`)return;let n=i.type.name===`blockquote`?i.content:s.from(i),r=e.schema.nodes.callout.create(null,n),a=e.state.tr.replaceWith(t,o,r);e.view.dispatch(a.setSelection(C.near(a.doc.resolve(t+1))).scrollIntoView()),e.commands.focus();return}let n=e.state.doc,a=C.findFrom(n.resolve(t),1,!0)?.from??t+1,l=C.findFrom(n.resolve(o),-1,!0)?.to??o-1;c(e.chain().focus().setTextSelection({from:a,to:l}).clearNodes()).run()}}))}),i.type.name===`codeBlock`){let n=!!e.extensionManager.extensions.find(e=>e.name===`codeBlock`)?.options.lineNumbers,r=kj(i.attrs.lineNumbers,n);l.push({id:`lineNumbers`,label:r?a.hideLineNumbers:a.showLineNumbers,icon:`list-ordered`,run:()=>e.view.dispatch(e.state.tr.setNodeAttribute(t,`lineNumbers`,!r))})}if(i.type.name===`fileAttachment`&&jj(i.attrs.mime,i.attrs.name)){let n=i.attrs.view===`preview`;l.push({id:`pdfView`,label:n?a.showAsFile:a.showPages,icon:n?`paperclip`:`file`,run:()=>e.view.dispatch(e.state.tr.setNodeAttribute(t,`view`,n?`card`:`preview`))})}return c>0&&l.push({id:`moveUp`,label:a.moveUp,icon:`arrow-up`,run:()=>{let n=e.state.doc.child(c-1),r=e.state.tr.delete(t,o).insert(t-n.nodeSize,i);e.view.dispatch(r.scrollIntoView())}}),c{let n=e.state.doc.child(c+1),r=e.state.tr.delete(t,o).insert(t+n.nodeSize,i);e.view.dispatch(r.scrollIntoView())}}),l.push({id:`duplicate`,label:a.duplicate,icon:`plus`,run:()=>{let t=e.schema.nodeFromJSON(zj(i.toJSON()));e.view.dispatch(e.state.tr.insert(o,t).scrollIntoView())}},{id:`copy`,label:a.copy,icon:`copy`,run:()=>{e.chain().focus().setNodeSelection(t).run(),document.execCommand(`copy`)}}),r&&l.push({id:`copyLink`,label:n.blocks.copyBlockLink,icon:`link`,run:r}),l.push({id:`delete`,label:a.delete,icon:`trash`,danger:!0,run:()=>{e.view.dispatch(e.state.tr.delete(t,o)),e.commands.focus()}}),l}function Vj(e,t,n,r){let i=document.createElement(`div`);i.className=`dw-suggest dw-block-menu`,i.setAttribute(`role`,`menu`),i.setAttribute(`aria-label`,n);let a=t,o=0,s=[],c=()=>{i.replaceChildren(),a.forEach((e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`dw-suggest__item${t===o?` is-active`:``}${e.danger?` is-danger`:``}`,n.setAttribute(`role`,`menuitem`),n.tabIndex=-1,e.children&&n.setAttribute(`aria-haspopup`,`menu`);let r=document.createElement(`span`);r.className=`dw-suggest__icon`,r.append(Fj(e.icon));let a=document.createElement(`span`);if(a.className=`dw-suggest__label`,a.textContent=e.label,n.append(r,a),e.children){let e=Fj(`chevron-right`,14);e.classList.add(`dw-block-menu__more`),n.append(e)}n.addEventListener(`mousedown`,e=>e.preventDefault()),n.addEventListener(`click`,()=>l(t)),n.addEventListener(`mouseenter`,()=>{o=t;for(let[e,n]of[...i.children].entries())n.classList.toggle(`is-active`,e===t)}),i.append(n)}),i.children[o]?.focus()},l=e=>{let t=a[e];t&&(t.children?(s.push(a),a=t.children,o=0,c()):(m(),t.run?.()))},u=e=>{e.key===`Escape`||e.key===`ArrowLeft`&&s.length?(e.preventDefault(),e.stopPropagation(),s.length?(a=s.pop(),o=0,c()):m()):e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),o=(o+(e.key===`ArrowDown`?1:-1)+a.length)%a.length,c()):(e.key===`Enter`||e.key===` `||e.key===`ArrowRight`)&&(e.preventDefault(),(e.key!==`ArrowRight`||a[o]?.children)&&l(o))},d=t=>{!i.contains(t.target)&&!e.contains(t.target)&&m()};document.body.append(i);let f=wj(e,i,()=>{Oj(e,i,{placement:`bottom-start`,strategy:`fixed`,middleware:[Tj(4),Dj(),Ej({padding:8})]}).then(({x:e,y:t})=>Object.assign(i.style,{left:`${e}px`,top:`${t}px`}))});i.addEventListener(`keydown`,u),document.addEventListener(`mousedown`,d,!0);let p=!1;function m(){p||(p=!0,f(),i.remove(),document.removeEventListener(`mousedown`,d,!0),s=[],r?.())}return c(),m}var Hj=[`paragraph`,`heading`,`blockquote`,`codeBlock`,`bulletList`,`orderedList`,`taskList`,`callout`,`table`,`details`,`image`,`embed`,`linkCard`,`mermaid`,`blockMath`,`drawio`,`excalidraw`,`fileAttachment`],Uj=/^[a-z0-9]{6,16}$/,Wj=e=>`#b-${e}`;function Gj(){return[...crypto.getRandomValues(new Uint8Array(8))].map(e=>(e%36).toString(36)).join(``)}function Kj(e,t){let n=e.state.doc.nodeAt(t);if(!n)return null;let r=n.attrs.blockId;if(r)return r;if(!e.editable||!Hj.includes(n.type.name))return null;let i=Gj();return e.dispatch(e.state.tr.setNodeAttribute(t,`blockId`,i)),i}async function qj(e,t,n,r){let i=Kj(e,t);if(!i)return!1;let a=n(Wj(i));try{await navigator.clipboard.writeText(a),r?.(a)}catch{window.prompt(``,a)}return!0}var Jj=Tp.create({name:`blockLinks`,addOptions(){return{labels:null,link:void 0,onCopied:void 0}},addGlobalAttributes(){return[{types:Hj,attributes:{blockId:{default:null,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-block-id`);return t&&Uj.test(t)?t:null},renderHTML:e=>e.blockId?{"data-block-id":e.blockId}:{}}}}]},addKeyboardShortcuts(){let{link:e,onCopied:t}=this.options;return{"Mod-Shift-c":({editor:n})=>{if(!e)return!1;let r=n.state.selection.$from;if(r.depth<1)return!1;let i=r.before(1),a=n.state.doc.nodeAt(i);return!a||!Hj.includes(a.type.name)||!a.attrs.blockId&&!n.isEditable?!1:(qj(n.view,i,e,t),!0)}}},addProseMirrorPlugins(){let{link:e,onCopied:t}=this.options,n=this.options.labels,r=this.editor;return[new E({key:new D(`blockLinks`),view:i=>new Zj(i,r,n,e,t)})]}}),Yj=``,Xj=``,Zj=class{view;editor;labels;link;onCopied;gutter=document.createElement(`div`);linkButton=document.createElement(`button`);grip=document.createElement(`button`);pos=-1;closeMenu=null;constructor(e,t,n,r,i){this.view=e,this.editor=t,this.labels=n,this.link=r,this.onCopied=i;let a=this.gutter;a.className=`dw-block-gutter`,a.contentEditable=`false`,a.hidden=!0,a.addEventListener(`mouseleave`,this.leave);let o=this.linkButton;o.type=`button`,o.className=`dw-block-handle`,o.setAttribute(`aria-label`,n.blocks.copyBlockLink),o.title=n.blocks.copyBlockLink,o.innerHTML=Yj,o.addEventListener(`mousedown`,e=>e.preventDefault()),o.addEventListener(`click`,()=>void this.copy());let s=this.grip;s.type=`button`,s.className=`dw-block-handle dw-block-grip`,s.setAttribute(`aria-label`,n.blockMenu.open),s.setAttribute(`aria-haspopup`,`menu`),s.setAttribute(`aria-expanded`,`false`),s.title=n.blockMenu.open,s.innerHTML=Xj,s.draggable=!0,s.addEventListener(`click`,this.openMenu),s.addEventListener(`dragstart`,this.dragStart),s.addEventListener(`dragend`,()=>this.hide()),r&&a.append(o),a.append(s),e.dom.addEventListener(`mousemove`,this.move),e.dom.addEventListener(`mouseleave`,this.leave)}get host(){let e=this.view.dom.parentElement;return e&&this.gutter.parentElement!==e&&(e.classList.add(`dw-block-host`),e.append(this.gutter)),e}hide=()=>{this.closeMenu||(this.gutter.hidden=!0,this.pos=-1)};leave=e=>{let t=e.relatedTarget;t&&(this.gutter.contains(t)||this.view.dom.contains(t))||this.hide()};move=e=>{if(this.closeMenu)return;let t=e.target;for(;t&&t.parentElement!==this.view.dom;)t=t.parentElement;let n=this.host;if(!t||!n)return this.hide();let r;try{r=this.view.posAtDOM(t,0)}catch{return this.hide()}let i=this.view.state.doc.resolve(Math.min(r,this.view.state.doc.content.size)),a=i.depth>=1?i.before(1):r,o=this.view.state.doc.nodeAt(a);if(!o)return this.hide();let s=!!this.link&&Hj.includes(o.type.name)&&(!!o.attrs.blockId||this.view.editable),c=this.view.editable;if(!s&&!c)return this.hide();this.linkButton.hidden=!s,this.grip.hidden=!c,this.pos=a;let l=t.getBoundingClientRect(),u=n.getBoundingClientRect();this.gutter.style.top=`${l.top-u.top+Math.min(l.height/2,14)-11}px`,this.gutter.hidden=!1};openMenu=()=>{if(this.closeMenu){this.closeMenu();return}let e=this.pos;if(e<0||!this.view.editable)return;let t=this.view.state.doc.nodeAt(e),n=!!this.link&&!!t&&Hj.includes(t.type.name),r=Bj(this.editor,e,this.labels,n?()=>void this.copy(e):void 0);this.grip.setAttribute(`aria-expanded`,`true`),this.closeMenu=Vj(this.grip,r,this.labels.blockMenu.open,()=>{this.closeMenu=null,this.grip.setAttribute(`aria-expanded`,`false`),this.hide()})};dragStart=e=>{let t=this.pos;if(t<0||!e.dataTransfer)return;this.closeMenu?.();let n=T.create(this.view.state.doc,t);this.view.dispatch(this.view.state.tr.setSelection(n)),e.dataTransfer.effectAllowed=`copyMove`,e.dataTransfer.setData(`text/plain`,n.node.textContent);let r=this.view.nodeDOM(t);r instanceof HTMLElement&&e.dataTransfer.setDragImage(r,0,0),this.view.dragging={slice:n.content(),move:!0}};async copy(e=this.pos){e>=0&&this.link&&await qj(this.view,e,this.link,this.onCopied)}update(){this.pos>=this.view.state.doc.content.size&&this.hide()}destroy(){this.closeMenu?.(),this.gutter.parentElement?.classList.remove(`dw-block-host`),this.gutter.remove(),this.view.dom.removeEventListener(`mousemove`,this.move),this.view.dom.removeEventListener(`mouseleave`,this.leave)}},Qj,$j;if(typeof WeakMap<`u`){let e=new WeakMap;Qj=t=>e.get(t),$j=(t,n)=>(e.set(t,n),n)}else{let e=[],t=0;Qj=t=>{for(let n=0;n(t==10&&(t=0),e[t++]=n,e[t++]=r)}var eM=class{constructor(e,t,n,r){this.width=e,this.height=t,this.map=n,this.problems=r}findCell(e){for(let t=0;t=n){(a||=[]).push({type:`overlong_rowspan`,pos:c,n:f-e});break}let l=i+e*t;for(let e=0;er&&(a+=i.attrs.colspan)}}for(let e=0;e1&&(n=!0)}t==-1?t=a:t!=a&&(t=Math.max(t,a))}return t}function rM(e,t,n){e.problems||=[];let r={};for(let i=0;i0;t--)if(e.node(t).type.spec.tableRole==`row`)return e.node(0).resolve(e.before(t+1));return null}function cM(e){for(let t=e.depth;t>0;t--){let n=e.node(t).type.spec.tableRole;if(n===`cell`||n===`header_cell`)return e.node(t)}return null}function lM(e){let t=e.selection.$head;for(let e=t.depth;e>0;e--)if(t.node(e).type.spec.tableRole==`row`)return!0;return!1}function uM(e){let t=e.selection;if(`$anchorCell`in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if(`node`in t&&t.node&&t.node.type.spec.tableRole==`cell`)return t.$anchor;let n=sM(t.$head)||dM(t.$head);if(n)return n;throw RangeError(`No cell found around position ${t.head}`)}function dM(e){for(let t=e.nodeAfter,n=e.pos;t;t=t.firstChild,n++){let r=t.type.spec.tableRole;if(r==`cell`||r==`header_cell`)return e.doc.resolve(n)}for(let t=e.nodeBefore,n=e.pos;t;t=t.lastChild,n--){let r=t.type.spec.tableRole;if(r==`cell`||r==`header_cell`)return e.doc.resolve(n-t.nodeSize)}}function fM(e){return e.parent.type.spec.tableRole==`row`&&!!e.nodeAfter}function pM(e){return e.node(0).resolve(e.pos+e.nodeAfter.nodeSize)}function mM(e,t){return e.depth==t.depth&&e.pos>=t.start(-1)&&e.pos<=t.end(-1)}function hM(e,t,n){let r=e.node(-1),i=eM.get(r),a=e.start(-1),o=i.nextCell(e.pos-a,t,n);return o==null?null:e.node(0).resolve(a+o)}function gM(e,t,n=1){let r={...e,colspan:e.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(t,n),r.colwidth.some(e=>e>0)||(r.colwidth=null)),r}function _M(e,t,n=1){let r={...e,colspan:e.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let e=0;ee!=t.pos-i);s.unshift(t.pos-i);let c=s.map(e=>{let t=n.nodeAt(e);if(!t)throw RangeError(`No cell with offset ${e} found`);let r=i+e+1;return new Cn(o.resolve(r),o.resolve(r+t.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=t}map(t,n){let r=t.resolve(n.map(this.$anchorCell.pos)),i=t.resolve(n.map(this.$headCell.pos));if(fM(r)&&fM(i)&&mM(r,i)){let t=this.$anchorCell.node(-1)!=r.node(-1);return t&&this.isRowSelection()?e.rowSelection(r,i):t&&this.isColSelection()?e.colSelection(r,i):new e(r,i)}return w.between(r,i)}content(){let e=this.$anchorCell.node(-1),t=eM.get(e),n=this.$anchorCell.start(-1),r=t.rectBetween(this.$anchorCell.pos-n,this.$headCell.pos-n),i={},a=[];for(let n=r.top;n0||u>0){let e=c.attrs;if(l>0&&(e=gM(e,0,l)),u>0&&(e=gM(e,e.colspan-u,u)),s.leftr.bottom){let e={...c.attrs,rowspan:Math.min(s.bottom,r.bottom)-Math.max(s.top,r.top)};c=s.top0)return!1;let n=e+this.$anchorCell.nodeAfter.attrs.rowspan,r=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(n,r)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){let r=t.node(-1),i=eM.get(r),a=t.start(-1),o=i.findCell(t.pos-a),s=i.findCell(n.pos-a),c=t.node(0);return o.top<=s.top?(o.top>0&&(t=c.resolve(a+i.map[o.left])),s.bottom0&&(n=c.resolve(a+i.map[s.left])),o.bottom0)return!1;let a=r+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(a,o)==t.width}eq(t){return t instanceof e&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){let r=t.node(-1),i=eM.get(r),a=t.start(-1),o=i.findCell(t.pos-a),s=i.findCell(n.pos-a),c=t.node(0);return o.left<=s.left?(o.left>0&&(t=c.resolve(a+i.map[o.top*i.width])),s.right0&&(n=c.resolve(a+i.map[s.top*i.width])),o.right{t.push(vs.node(n,n+e.nodeSize,{class:`selectedCell`}))}),xs.create(e.doc,t)}function SM({$from:e,$to:t}){if(e.pos==t.pos||e.pos=0&&!(e.after(i+1)=0&&!(t.before(e+1)>t.start(e));e--,r--);return n==r&&/row|table/.test(e.node(i).type.spec.tableRole)}function CM({$from:e,$to:t}){let n,r;for(let t=e.depth;t>0;t--){let r=e.node(t);if(r.type.spec.tableRole===`cell`||r.type.spec.tableRole===`header_cell`){n=r;break}}for(let e=t.depth;e>0;e--){let n=t.node(e);if(n.type.spec.tableRole===`cell`||n.type.spec.tableRole===`header_cell`){r=n;break}}return n!==r&&t.parentOffset===0}function wM(e,t,n){let r=(t||e).selection,i=(t||e).doc,a,o;if(r instanceof T&&(o=r.node.type.spec.tableRole)){if(o==`cell`||o==`header_cell`)a=yM.create(i,r.from);else if(o==`row`){let e=i.resolve(r.from+1);a=yM.rowSelection(e,e)}else if(!n){let e=eM.get(r.node),t=r.from+1,n=t+e.map[e.width*e.height-1];a=yM.create(i,t+1,n)}}else r instanceof w&&SM(r)?a=w.create(i,r.from):r instanceof w&&CM(r)&&(a=w.create(i,r.$from.start(),r.$from.end()));return a&&(t||=e.tr).setSelection(a),t}var TM=new D(`fix-tables`);function EM(e,t,n,r){let i=e.childCount,a=t.childCount;outer:for(let o=0,s=0;o{t.type.spec.tableRole==`table`&&(n=OM(e,t,r,n))};return t?t.doc!=e.doc&&EM(t.doc,e.doc,0,r):e.doc.descendants(r),n}function OM(e,t,n,r){let i=eM.get(t);if(!i.problems)return r;r||=e.tr;let a=[];for(let e=0;e0){let t=`cell`;n.firstChild&&(t=n.firstChild.type.spec.tableRole);let a=[];for(let n=0;n0?-1:0;vM(t,r,i+a)&&(a=i==0||i==t.width?null:0);for(let o=0;o0&&i0&&t.map[s-1]==c||i0?-1:0;FM(t,r,i+s)&&(s=i==0||i==t.height?null:0);for(let a=0,c=t.width*i;a0&&i0&&l==t.map[o-t.width]){let t=n.nodeAt(l).attrs;e.setNodeMarkup(e.mapping.slice(s).map(l+r),null,{...t,rowspan:t.rowspan-1}),a+=t.colspan-1}else if(i0&&n[a]==n[a-1]||r.right0&&n[i]==n[i-e]||r.bottom0){let e=c+1+l.content.size,t=VM(l)?c+1:e;n.replaceWith(t+r.tableStart,e+r.tableStart,o)}n.setSelection(new yM(n.doc.resolve(c+r.tableStart))),t(n)}return!0}function WM(e,t){let n=aM(e.schema);return GM(({node:e})=>n[e.type.spec.tableRole])(e,t)}function GM(e){return(t,n)=>{let r=t.selection,i,a;if(r instanceof yM){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;i=r.$anchorCell.nodeAfter,a=r.$anchorCell.pos}else{if(i=cM(r.$from),!i)return!1;a=sM(r.$from)?.pos}if(i==null||a==null||i.attrs.colspan==1&&i.attrs.rowspan==1)return!1;if(n){let o=i.attrs,s=[],c=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});let l=kM(t),u=t.tr;for(let e=0;e{n.attrs[e]!==t&&a.setNodeMarkup(r,null,{...n.attrs,[e]:t})}):a.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[e]:t}),r(a)}return!0}}function qM(e){return function(t,n){if(!lM(t))return!1;if(n){let r=aM(t.schema),i=kM(t),a=t.tr,o=i.map.cellsInRect(e==`column`?{left:i.left,top:0,right:i.right,bottom:i.map.height}:e==`row`?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),s=o.map(e=>i.table.nodeAt(e));for(let e=0;e{let t=e+i.tableStart,n=a.doc.nodeAt(t);n&&a.setNodeMarkup(t,u,n.attrs)}),n(a)}return!0}}YM(`row`,{useDeprecatedLogic:!0}),YM(`column`,{useDeprecatedLogic:!0});var XM=YM(`cell`,{useDeprecatedLogic:!0});function ZM(e,t){if(t<0){let t=e.nodeBefore;if(t)return e.pos-t.nodeSize;for(let t=e.index(-1)-1,n=e.before();t>=0;t--){let r=e.node(-1).child(t),i=r.lastChild;if(i)return n-1-i.nodeSize;n-=r.nodeSize}}else{if(e.index()0;r--)if(n.node(r).type.spec.tableRole==`table`)return t&&t(e.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function eN(e,t){let n=e.selection;if(!(n instanceof yM))return!1;if(t){let r=e.tr,i=aM(e.schema).cell.createAndFill().content;n.forEachCell((e,t)=>{e.content.eq(i)||r.replace(r.mapping.map(t+1),r.mapping.map(t+e.nodeSize-1),new p(i,0,0))}),r.docChanged&&t(r)}return!0}function tN(e){if(e.size===0)return null;let{content:t,openStart:n,openEnd:r}=e;for(;t.childCount==1&&(n>0&&r>0||t.child(0).type.spec.tableRole==`table`);)n--,r--,t=t.child(0).content;let i=t.child(0),a=i.type.spec.tableRole,o=i.type.schema,s=[];if(a==`row`)for(let e=0;e=0;t--){let{rowspan:i,colspan:a}=r.child(t).attrs;for(let t=e;t=t.length&&t.push(s.empty),n[i]r&&(s=s.type.createChecked(gM(s.attrs,s.attrs.colspan,n+s.attrs.colspan-r),s.content)),o.push(s),n+=s.attrs.colspan;for(let n=1;ni&&(t=t.type.create({...t.attrs,rowspan:Math.max(1,i-t.attrs.rowspan)},t.content)),o.push(t)}e.push(s.from(o))}n=e,t=i}return{width:e,height:t,rows:n}}function aN(e,t,n,r,i,a,o){let c=e.doc.type.schema,l=aM(c),u,d;if(i>t.width)for(let a=0,s=0;at.height){let c=[];for(let e=0,r=(t.height-1)*t.width;e=t.width?!1:n.nodeAt(t.map[r+e]).type==l.header_cell;c.push(i?d||=l.header_cell.createAndFill():u||=l.cell.createAndFill())}let f=l.row.create(null,s.from(c)),p=[];for(let e=t.height;e{if(!i)return!1;let a=n.selection;if(a instanceof yM)return uN(n,r,C.near(a.$headCell,t));if(e!=`horiz`&&!a.empty)return!1;let o=gN(i,e,t);if(o==null)return!1;if(e==`horiz`)return uN(n,r,C.near(n.doc.resolve(a.head+t),t));{let i=n.doc.resolve(o),a=hM(i,e,t),s;return s=a?C.near(a,1):t<0?C.near(n.doc.resolve(i.before(-1)),-1):C.near(n.doc.resolve(i.after(-1)),1),uN(n,r,s)}}}function fN(e,t){return(n,r,i)=>{if(!i)return!1;let a=n.selection,o;if(a instanceof yM)o=a;else{let r=gN(i,e,t);if(r==null)return!1;o=new yM(n.doc.resolve(r))}let s=hM(o.$headCell,e,t);return s?uN(n,r,new yM(o.$anchorCell,s)):!1}}function pN(e,t){let n=e.state.doc,r=sM(n.resolve(t));return r?(e.dispatch(e.state.tr.setSelection(new yM(r))),!0):!1}function mN(e,t,n){if(!lM(e.state))return!1;let r=tN(n),i=e.state.selection;if(i instanceof yM){r||={width:1,height:1,rows:[s.from(rN(aM(e.state.schema).cell,n))]};let t=i.$anchorCell.node(-1),a=i.$anchorCell.start(-1),o=eM.get(t).rectBetween(i.$anchorCell.pos-a,i.$headCell.pos-a);return r=iN(r,o.right-o.left,o.bottom-o.top),cN(e.state,e.dispatch,a,o,r),!0}if(r){let t=uM(e.state),n=t.start(-1);return cN(e.state,e.dispatch,n,eM.get(t.node(-1)).findCell(t.pos-n),r),!0}return!1}function hN(e,t){if(t.button!=0||t.ctrlKey||t.metaKey)return;let n=_N(e,t.target),r;if(t.shiftKey&&e.state.selection instanceof yM)i(e.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&n&&(r=sM(e.state.selection.$anchor))!=null&&vN(e,t)?.pos!=r.pos)i(r,t),t.preventDefault();else if(!n)return;function i(t,n){let r=vN(e,n),i=oM.getState(e.state)==null;if(!r||!mM(t,r)){if(i)r=t;else return}let a=new yM(t,r);if(i||!e.state.selection.eq(a)){let n=e.state.tr.setSelection(a);i&&n.setMeta(oM,t.pos),e.dispatch(n)}}function a(){e.root.removeEventListener(`mouseup`,a),e.root.removeEventListener(`dragstart`,a),e.root.removeEventListener(`mousemove`,o),oM.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta(oM,-1))}function o(r){let o=r,s=oM.getState(e.state),c;if(s!=null)c=e.state.doc.resolve(s);else if(_N(e,o.target)!=n&&(c=vN(e,t),!c))return a();c&&i(c,o)}e.root.addEventListener(`mouseup`,a),e.root.addEventListener(`dragstart`,a),e.root.addEventListener(`mousemove`,o)}function gN(e,t,n){if(!(e.state.selection instanceof w))return null;let{$head:r}=e.state.selection;for(let i=r.depth-1;i>=0;i--){let a=r.node(i);if((n<0?r.index(i):r.indexAfter(i))!=(n<0?0:a.childCount))return null;if(a.type.spec.tableRole==`cell`||a.type.spec.tableRole==`header_cell`){let a=r.before(i),o=t==`vert`?n>0?`down`:`up`:n>0?`right`:`left`;return e.endOfTextblock(o)?a:null}}return null}function _N(e,t){for(;t&&t!=e.dom;t=t.parentNode)if(t.nodeName==`TD`||t.nodeName==`TH`)return t;return null}function vN(e,t){let n=e.posAtCoords({left:t.clientX,top:t.clientY});if(!n)return null;let{inside:r,pos:i}=n;return r>=0&&sM(e.state.doc.resolve(r))||sM(e.state.doc.resolve(i))}var yN=class{constructor(e,t){this.node=e,this.defaultCellMinWidth=t,this.dom=document.createElement(`div`),this.dom.className=`tableWrapper`,this.table=this.dom.appendChild(document.createElement(`table`)),this.table.style.setProperty(`--default-cell-min-width`,`${t}px`),this.colgroup=this.table.appendChild(document.createElement(`colgroup`)),bN(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement(`tbody`))}update(e){return e.type==this.node.type&&(this.node=e,bN(e,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(e){return e.type==`attributes`&&(e.target==this.table||this.colgroup.contains(e.target))}};function bN(e,t,n,r,i,a){let o=0,s=!0,c=t.firstChild,l=e.firstChild;if(l){for(let e=0,n=0;enew r(e,n,t)),new CN(-1,!1)},apply(e,t){return t.apply(e)}},props:{attributes:e=>{let t=xN.getState(e);return t&&t.activeHandle>-1?{class:`resize-cursor`}:{}},handleDOMEvents:{mousemove:(t,n)=>{wN(t,n,e,i)},mouseleave:e=>{TN(e)},mousedown:(e,r)=>{EN(e,r,t,n)}},decorations:e=>{let t=xN.getState(e);if(t&&t.activeHandle>-1)return FN(e,t.activeHandle)},nodeViews:{}}});return a}var CN=class e{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(t){let n=this,r=t.getMeta(xN);if(r&&r.setHandle!=null)return new e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let r=t.mapping.map(n.activeHandle,-1);return fM(t.doc.resolve(r))||(r=-1),new e(r,n.dragging)}return n}};function wN(e,t,n,r){if(!e.editable)return;let i=xN.getState(e.state);if(i&&!i.dragging){let a=ON(t.target),o=-1;if(a){let{left:r,right:i}=a.getBoundingClientRect();t.clientX-r<=n?o=kN(e,t,`left`,n):i-t.clientX<=n&&(o=kN(e,t,`right`,n))}if(o!=i.activeHandle){if(!r&&o!==-1){let t=e.state.doc.resolve(o),n=t.node(-1),r=eM.get(n),i=t.start(-1);if(r.colCount(t.pos-i)+t.nodeAfter.attrs.colspan-1==r.width-1)return}jN(e,o)}}}function TN(e){if(!e.editable)return;let t=xN.getState(e.state);t&&t.activeHandle>-1&&!t.dragging&&jN(e,-1)}function EN(e,t,n,r){if(!e.editable)return!1;let i=e.dom.ownerDocument.defaultView??window,a=xN.getState(e.state);if(!a||a.activeHandle==-1||a.dragging)return!1;let o=e.state.doc.nodeAt(a.activeHandle),s=DN(e,a.activeHandle,o.attrs);e.dispatch(e.state.tr.setMeta(xN,{setDragging:{startX:t.clientX,startWidth:s}}));function c(t){i.removeEventListener(`mouseup`,c),i.removeEventListener(`mousemove`,l);let r=xN.getState(e.state);r?.dragging&&(MN(e,r.activeHandle,AN(r.dragging,t,n)),e.dispatch(e.state.tr.setMeta(xN,{setDragging:null})))}function l(t){if(!t.which)return c(t);let i=xN.getState(e.state);if(i&&i.dragging){let a=AN(i.dragging,t,n);NN(e,i.activeHandle,a,r)}}return NN(e,a.activeHandle,s,r),i.addEventListener(`mouseup`,c),i.addEventListener(`mousemove`,l),t.preventDefault(),!0}function DN(e,t,{colspan:n,colwidth:r}){let i=r&&r[r.length-1];if(i)return i;let a=e.domAtPos(t),o=a.node.childNodes[a.offset].offsetWidth,s=n;if(r)for(let e=0;eRN(e),renderHTML:e=>{let t=LN(e.align);return Pf(t)?{style:`text-align: ${t}`}:{}}}}function VN(e){let t=e.parentElement,n=e.closest(`table`);if(!t||!n)return null;let r=Array.from(t.children).indexOf(e),i=n.querySelectorAll(`colgroup > col`)[r]?.getAttribute(`width`);return i?[parseInt(i,10)]:null}function HN(e){let t=e.getAttribute(`colwidth`);return t?t.split(`,`).map(e=>parseInt(e,10)):VN(e)}var UN=/[ \t\r\n\f]+/g;function WN(e){return e.children.length>0?!1:(e.textContent??``).replace(UN,``)===``}function GN(e){let t=e.createAndFill();if(!t)throw Error(`[tiptap error]: "${e.name}" has no default content to backfill.`);return t.content}function KN(e,t,n){if(!(n in t))return;let r=t[n];(r===1||r===`1`||r==null)&&delete e[n]}var qN=Jp.create({name:`tableCell`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:HN},align:BN()}},tableRole:`cell`,isolating:!0,parseHTML(){return[{tag:`td`,getAttrs:e=>WN(e)?{}:!1,getContent:(e,t)=>GN(t.nodes[this.name])},{tag:`td`}]},renderHTML({HTMLAttributes:e}){let t=A(this.options.HTMLAttributes,e);return KN(t,e,`colspan`),KN(t,e,`rowspan`),[`td`,t,0]}}),JN=Jp.create({name:`tableHeader`,addOptions(){return{HTMLAttributes:{}}},content:`block+`,addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:HN},align:BN()}},tableRole:`header_cell`,isolating:!0,parseHTML(){return[{tag:`th`,getAttrs:e=>WN(e)?{}:!1,getContent:(e,t)=>GN(t.nodes[this.name])},{tag:`th`}]},renderHTML({HTMLAttributes:e}){let t=A(this.options.HTMLAttributes,e);return KN(t,e,`colspan`),KN(t,e,`rowspan`),[`th`,t,0]}}),YN=Jp.create({name:`tableRow`,addOptions(){return{HTMLAttributes:{}}},content:`(tableCell | tableHeader)*`,tableRole:`row`,parseHTML(){return[{tag:`tr`}]},renderHTML({HTMLAttributes:e}){return[`tr`,A(this.options.HTMLAttributes,e),0]}});function XN(e,t){return t?[`width`,`${Math.max(t,e)}px`]:[`min-width`,`${e}px`]}function ZN(e,t,n,r,i,a){let o=0,s=!0,c=t.firstChild,l=e.firstChild;if(l!==null)for(let e=0,n=0;e{let r=e.nodes[n];r.spec.tableRole&&(t[r.spec.tableRole]=r)}),e.cached.tableNodeTypes=t,t}function nP(e,t,n,r,i){let a=tP(e),o=[],s=[];for(let e=0;e{let{selection:t}=e.state;if(!rP(t))return!1;let n=0;return vu(t.ranges[0].$from,e=>e.type.name===`table`)?.node.descendants(e=>{if(e.type.name===`table`)return!1;[`tableCell`,`tableHeader`].includes(e.type.name)&&(n+=1)}),n===t.ranges.length&&(e.commands.deleteTable(),!0)};function aP(e,t){let n=e.mapping.map(t);if(vu(e.selection.$from,e=>e.type.name===`table`)?.pos===n)return;let r=e.doc.nodeAt(n);if(!r)return;let i=n+r.nodeSize-1;e.setSelection(w.near(e.doc.resolve(i),-1))}function oP(e){let t=``,n=0;for(;ne===`|`?`\\|`:e)+e.slice(i,i+r),n=i+r,a=!0;break}i+=o}a||(t+=e.slice(n,n+r),n+=r)}return t}function sP(e){return e.split(` `).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}){return[`mark`,A(this.options.HTMLAttributes,e),0]},renderMarkdown:(e,t)=>`==${t.renderChildren(e)}==`,parseMarkdown:(e,t)=>t.applyMark(`highlight`,t.parseInline(e.tokens||[])),markdownTokenizer:{name:`highlight`,level:`inline`,start:e=>e.indexOf(`==`),tokenize(e,t,n){let r=/^(==)(?!\s)([^=]*[^=\s])(==)/.exec(e);if(r){let e=r[2].trim(),t=n.inlineTokens(e);return{type:`highlight`,raw:r[0],text:e,tokens:t}}}},addCommands(){return{setHighlight:e=>({commands:t})=>t.setMark(this.name,e),toggleHighlight:e=>({commands:t})=>t.toggleMark(this.name,e),unsetHighlight:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[Hp({find:CP,type:this.type})]},addPasteRules(){return[Yp({find:wP,type:this.type})]}}),EP=[`gray`,`red`,`orange`,`yellow`,`green`,`teal`,`blue`,`purple`,`pink`],DP=e=>typeof e==`string`&&EP.includes(e),OP=_p.create({name:`textColor`,addAttributes(){return{color:{default:null,parseHTML:e=>{let t=e.getAttribute(`data-color`);return DP(t)?t:null},renderHTML:e=>e.color?{"data-color":e.color}:{}}}},parseHTML(){return[{tag:`span[data-color]`,getAttrs:e=>DP(e.getAttribute(`data-color`))?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{class:`dw-text-color`}),0]},addCommands(){return{setTextColor:e=>({commands:t})=>t.setMark(this.name,{color:e}),unsetTextColor:()=>({commands:e})=>e.unsetMark(this.name)}}}),kP=TP.extend({addOptions(){return{...this.parent(),multicolor:!0}},addAttributes(){return{color:{default:null,parseHTML:e=>{let t=e.getAttribute(`data-color`);return DP(t)?t:null},renderHTML:e=>({"data-color":DP(e.color)?e.color:`yellow`})}}},renderHTML({HTMLAttributes:e}){return[`mark`,A(e,{class:`dw-highlight`}),0]}}),AP=`💡`;function jP(e){let t=e.trim();return t&&[...t].length<=4?t:``}var MP=Jp.create({name:`callout`,group:`block`,content:`block+`,defining:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{emoji:{default:AP,parseHTML:e=>jP(e.getAttribute(`data-emoji`)??``)||AP,renderHTML:e=>({"data-emoji":e.emoji})},color:{default:`blue`,parseHTML:e=>{let t=e.getAttribute(`data-color`);return DP(t)?t:`blue`},renderHTML:e=>({"data-color":e.color})}}},parseHTML(){return[{tag:`aside[data-type=callout]`,contentElement:e=>e.querySelector(`:scope > .callout-body`)??e}]},renderHTML({HTMLAttributes:e}){return[`aside`,A(e,{"data-type":`callout`,class:`dw-callout`}),0]},addCommands(){return{setCallout:e=>({commands:t})=>t.wrapIn(this.name,e),unsetCallout:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{Backspace:({editor:e})=>{let{$from:t,empty:n}=e.state.selection;if(!n||t.parentOffset>0)return!1;for(let n=t.depth-1;n>0;n--){if(t.node(n).type.name===this.name)return t.index(n)!==0||t.start(n+1)!==t.start()?!1:e.commands.lift(this.name);if(t.index(n)!==0)return!1}return!1}}},addNodeView(){return({node:e,getPos:t,editor:n})=>{let r=this.options.labels,i=document.createElement(`aside`);i.className=`dw-callout`,i.setAttribute(`data-type`,`callout`);let a=document.createElement(`div`);a.className=`dw-callout__side`,a.contentEditable=`false`;let o=document.createElement(`button`);o.type=`button`,o.className=`dw-callout__emoji`;let s=document.createElement(`button`);s.type=`button`,s.className=`dw-callout__color`,a.append(o,s);let c=document.createElement(`div`);c.className=`dw-callout__body`,i.append(a,c);let l=e,u=e=>{let r=t();typeof r==`number`&&n.isEditable&&n.view.dispatch(n.state.tr.setNodeMarkup(r,void 0,{...l.attrs,...e}))};o.addEventListener(`mousedown`,e=>e.preventDefault()),o.addEventListener(`click`,()=>{if(!n.isEditable)return;let e=jP(window.prompt(r?.blocks.calloutEmoji??`Emoji`,l.attrs.emoji)??``);e&&u({emoji:e})}),s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`click`,()=>{let e=EP.indexOf(l.attrs.color);u({color:EP[(e+1)%EP.length]})});let d=()=>{i.setAttribute(`data-color`,String(l.attrs.color)),o.textContent=String(l.attrs.emoji);let e=r?.blocks.calloutEmoji??`Emoji`;o.setAttribute(`aria-label`,e),o.title=e;let t=r?.blocks.calloutColor??`Colour`;s.setAttribute(`aria-label`,t),s.title=t};return d(),{dom:i,contentDOM:c,update:t=>t.type===e.type&&(l=t,d(),!0),stopEvent:e=>a.contains(e.target),ignoreMutation:e=>a.contains(e.target)}}}});function NP(e){let t=MS.getState(e);return t?.type&&t.binding&&t.doc?t:null}function PP(e,t){let n=NP(e);if(!n||!t?.from||!t.to)return null;try{let r=e=>jS(n.doc,n.type,ly(gg(e)),n.binding.mapping),i=r(t.from),a=r(t.to);return i===null||a===null||a<=i||a>e.doc.content.size?null:{from:i,to:a}}catch{return null}}var FP=new D(`docwellComments`);function IP(e,t,n){let r=[];for(let i of t){let t=PP(e,i.anchor);t&&r.push(vs.inline(t.from,t.to,{class:i.id===n?`dw-comment is-active`:`dw-comment`,"data-comment":i.id}))}return xs.create(e.doc,r)}var LP=Tp.create({name:`commentHighlights`,addOptions(){return{onSelect:void 0}},addProseMirrorPlugins(){let e=()=>this.options.onSelect;return[new E({key:FP,state:{init:()=>({marks:[],active:``,decos:xs.empty}),apply(e,t,n,r){let i=e.getMeta(FP);if(i)return{...i,decos:IP(r,i.marks,i.active)};if(!e.docChanged||!t.marks.length)return t;let a=e.getMeta(MS)?.isChangeOrigin;return{...t,decos:a?IP(r,t.marks,t.active):t.decos.map(e.mapping,e.doc)}}},props:{decorations:e=>FP.getState(e)?.decos??xs.empty,handleClick(t,n,r){let i=r.target?.closest?.(`[data-comment]`)?.getAttribute(`data-comment`);return i&&e()?.(i),!1}}})]}}),RP=/^(\d{4})-(\d{2})-(\d{2})$/;function zP(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function BP(e){let t=RP.exec(e);if(!t)return null;let n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return zP(n)===e?n:null}function VP(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t)}function HP(e,t){return Math.round((t.getTime()-e.getTime())/864e5)}function UP(e,t,n=new Date){let r=BP(e);if(!r)return e;let i=t.dates,a=HP(VP(n,0),r);return a===0?i.today:a===1?i.tomorrow:a===-1?i.yesterday:new Intl.DateTimeFormat(t.locale,{month:`short`,day:`numeric`,year:r.getFullYear()===n.getFullYear()?void 0:`numeric`}).format(r)}function WP(e,t){let n=BP(e);return n?new Intl.DateTimeFormat(t.locale,{dateStyle:`full`}).format(n):e}function GP(e,t,n,r=new Date){let i=t.dates,a=e.trim().toLowerCase(),o=!1;for(let e of new Set([i.remindWord.toLowerCase(),`remind`])){if(a.startsWith(e)){o=!0,a=a.slice(e.length).trim();break}if(a.length>=3&&e.startsWith(a)){o=!0,a=``;break}}if(o&&!n)return[];let s=VP(r,0);if(!a)return o?[1,0,7].map(e=>({date:zP(VP(s,e)),remind:o})):[{date:zP(s),remind:!1},...n?[{date:zP(VP(s,1)),remind:!0}]:[]];let c=[{words:[i.today,`today`],date:s},{words:[i.tomorrow,`tomorrow`],date:VP(s,1)},{words:[i.nextWeek,`next week`],date:VP(s,7)}];o||c.push({words:[i.yesterday,`yesterday`],date:VP(s,-1)});let l=e=>new Intl.DateTimeFormat(e,{weekday:`long`});for(let e=1;e<=7;e++){let n=VP(s,e);c.push({words:[l(t.locale).format(n),l(`en`).format(n)],date:n})}let u=[];BP(a)&&u.push({date:a,remind:o});for(let e of c)e.words.some(e=>e.toLowerCase().startsWith(a))&&u.push({date:zP(e.date),remind:o});return u.filter((e,t)=>u.findIndex(t=>t.date===e.date)===t).slice(0,5)}function KP(e,t){let n=e.toLowerCase().split(` `),r=[t.dates.remindWord,`remind`,t.dates.nextWeek.split(` `)[0]??``,`next`];return n.length>1&&n.length<=3&&r.some(e=>e&&e.toLowerCase()===n[0])}var qP=Jp.create({name:`dateMention`,group:`inline`,inline:!0,atom:!0,selectable:!0,addOptions(){return{labels:void 0,me:()=>void 0}},addAttributes(){return{date:{default:``,parseHTML:e=>e.getAttribute(`data-date`)??``,renderHTML:e=>({"data-date":e.date})},remind:{default:``,parseHTML:e=>e.getAttribute(`data-remind`)??``,renderHTML:e=>e.remind?{"data-remind":e.remind}:{}},tz:{default:``,parseHTML:e=>e.getAttribute(`data-tz`)??``,renderHTML:e=>e.tz?{"data-tz":e.tz}:{}}}},parseHTML(){return[{tag:`span[data-type="date"]`}]},renderHTML({node:e,HTMLAttributes:t}){return[`span`,A({"data-type":`date`,class:`dw-date`},t),UP(e.attrs.date,this.options.labels)]},renderText({node:e}){return UP(e.attrs.date,this.options.labels)},addNodeView(){let{labels:e,me:t}=this.options;return({node:n,editor:r,getPos:i})=>{let a=n,o=document.createElement(`span`);o.dataset.type=`date`,o.className=`dw-date`,o.contentEditable=`false`;let s=null,c=()=>{let t=a.attrs.date,n=a.attrs.remind,r=!!BP(t)&&t{let t=typeof i==`function`?i():void 0;t!==void 0&&r.chain().command(({tr:n})=>(n.setNodeMarkup(t,void 0,{...a.attrs,...e}),!0)).run()};return o.addEventListener(`mousedown`,n=>{r.isEditable&&!s&&(n.preventDefault(),s=XP(o,r,a,e,t(),l,()=>s=null))}),{dom:o,update(e){return e.type===a.type&&(a=e,c(),!0)},ignoreMutation:()=>!0,stopEvent:e=>o.contains(e.target)&&e.type!==`mousedown`,destroy(){s?.()}}}}});function JP(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone??``}catch{return``}}function YP(e,t,n,r){let i={date:n.date,remind:n.remind&&r?r:``,tz:n.remind&&r?JP():``};e.chain().focus().insertContentAt(t,[{type:`dateMention`,attrs:i},{type:`text`,text:` `}]).run()}function XP(e,t,n,r,i,a,o){let s=r.dates,c=document.createElement(`div`);c.className=`dw-date-pop`,c.setAttribute(`role`,`dialog`),c.setAttribute(`aria-label`,s.edit);let l=document.createElement(`input`);l.type=`date`,l.className=`dw-input`,l.value=n.attrs.date,l.setAttribute(`aria-label`,s.edit),l.addEventListener(`change`,()=>{BP(l.value)&&a({date:l.value})}),c.append(l);let u=n.attrs.remind;if(u&&u!==i){let e=document.createElement(`p`);e.className=`dw-date-pop__note`,e.textContent=s.someoneElse,c.append(e)}else if(i){let e=document.createElement(`label`);e.className=`dw-date-pop__check`;let t=document.createElement(`input`);t.type=`checkbox`,t.checked=u===i,t.addEventListener(`change`,()=>a(t.checked?{remind:i,tz:JP()}:{remind:``,tz:``})),e.append(t,document.createTextNode(s.remindMe));let n=document.createElement(`span`);n.className=`dw-date-pop__note`,n.textContent=s.reminderAt,c.append(e,n)}document.body.append(c);let d=wj(e,c,()=>{Oj(e,c,{placement:`bottom-start`,strategy:`fixed`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:t})=>Object.assign(c.style,{left:`${e}px`,top:`${t}px`}))}),f=t=>{!c.contains(t.target)&&!e.contains(t.target)&&m()},p=e=>{e.key===`Escape`&&(e.preventDefault(),m(),t.commands.focus())};function m(){d(),c.remove(),document.removeEventListener(`mousedown`,f,!0),document.removeEventListener(`keydown`,p,!0),o()}return document.addEventListener(`mousedown`,f,!0),document.addEventListener(`keydown`,p,!0),l.focus(),m}function ZP(e){let t=document.createElement(`div`);t.className=`dw-diagram-editor`,t.setAttribute(`role`,`dialog`),t.setAttribute(`aria-modal`,`true`),t.setAttribute(`aria-label`,e);let n=document.createElement(`p`);n.className=`dw-diagram-editor__status`,t.append(n),document.body.append(t);let r=document.body.style.overflow;return document.body.style.overflow=`hidden`,{root:t,status:e=>{n.textContent=e,n.hidden=!e},close:()=>{t.remove(),document.body.style.overflow=r}}}async function QP(e,t){let n=await fetch(e.resolve(t));if(!n.ok)throw Error(`loading the drawing failed (${n.status})`);return n.text()}function $P(e,t){return new File([e],t,{type:`image/svg+xml`})}function eF(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function tF(e,t,n){return new Promise(r=>{let i=ZP(n.slash.drawio?.label??`Draw.io`),a=document.createElement(`iframe`),o=new URL(e);for(let[e,t]of Object.entries({embed:`1`,proto:`json`,spin:`1`,saveAndExit:`1`,noExitBtn:`0`}))o.searchParams.set(e,t);a.src=o.toString(),a.className=`dw-diagram-editor__frame`,a.title=n.slash.drawio?.label??`Draw.io`;let s=document.createElement(`div`);s.className=`dw-diagram-editor__bar`;let c=document.createElement(`button`);c.type=`button`,c.className=`dw-source__btn`,c.textContent=n.blocks.cancel,c.addEventListener(`click`,()=>d(null)),s.append(c),i.root.append(s,a),i.status(``);let l=e=>a.contentWindow?.postMessage(JSON.stringify(e),o.origin),u=!1,d=e=>{window.removeEventListener(`message`,f),i.close(),r(e)},f=e=>{if(e.source!==a.contentWindow||e.origin!==o.origin||typeof e.data!=`string`)return;let n;try{n=JSON.parse(e.data)}catch{return}switch(n.event){case`init`:l({action:`load`,autosave:0,xml:t?`data:image/svg+xml;base64,${eF(t)}`:``});break;case`save`:u=!0,l({action:`export`,format:`xmlsvg`,spinKey:`saving`});break;case`export`:{let e=n.data??``,t=e.indexOf(`,`),r=e.slice(0,t),i=e.slice(t+1),a=r.includes(`;base64`)?new TextDecoder().decode(Uint8Array.from(atob(i),e=>e.charCodeAt(0))):decodeURIComponent(i);d(u?a:null);break}case`exit`:d(null)}};window.addEventListener(`message`,f)})}async function nF(e,t,n){let r=ZP(n.slash.excalidraw?.label??`Excalidraw`);r.status(``);try{let{openExcalidraw:i}=await e();return await i(r.root,t,n)}finally{r.close()}}var rF=!1;function iF(e){return Jp.create({name:e,group:`block`,atom:!0,draggable:!0,addOptions(){return{host:void 0,loadExcalidraw:void 0,labels:null,drawioUrl:void 0,onError:void 0}},addAttributes(){return{src:{default:``},alt:{default:``}}},parseHTML(){return[{tag:`figure[data-type='${e}']`,getAttrs:e=>({src:e.querySelector(`img`)?.getAttribute(`src`)??``})}]},renderHTML({node:t,HTMLAttributes:n}){return[`figure`,A(n,{"data-type":e}),[`img`,{src:String(t.attrs.src),alt:String(t.attrs.alt||e)}]]},addCommands(){return{insertDiagram:e=>({commands:t})=>(rF=!0,t.insertContent({type:e,attrs:{src:``}}))}},addNodeView(){return({node:t,editor:n,getPos:r})=>{let i=this.options,a=i.labels,o=document.createElement(`figure`);o.className=`dw-diagram dw-diagram--${e}`,o.setAttribute(`data-type`,e);let s=document.createElement(`img`);s.className=`dw-diagram__img`;let c=document.createElement(`p`);c.className=`dw-diagram__empty`,c.textContent=e===`drawio`?a.blocks.emptyDrawio:a.blocks.emptyExcalidraw;let l=document.createElement(`button`);l.type=`button`,l.className=`dw-diagram__edit`,l.textContent=a.blocks.edit,o.append(s,c,l);let u=``,d=t=>{u=String(t.attrs.src??``),s.hidden=!u,c.hidden=!!u,u&&(s.src=i.host?i.host.resolve(u):u,s.alt=String(t.attrs.alt||a.slash[e]?.label||e))};d(t);let f=!1,p=async()=>{if(!f&&m()&&i.host?.upload){f=!0;try{let t=u?await QP(i.host,u):``,o=e===`drawio`?await tF(i.drawioUrl||`https://embed.diagrams.net`,t,a):await nF(i.loadExcalidraw,t,a);if(o===null)return;let s=await i.host.upload($P(o,`${e===`drawio`?`diagram.drawio`:`drawing.excalidraw`}.svg`)),c=typeof r==`function`?r():void 0;c!==void 0&&aF(n,c,e,s.url)}catch(e){i.onError?.(e)}finally{f=!1}}},m=()=>n.isEditable&&!!i.host?.upload&&(e===`drawio`||!!i.loadExcalidraw),h=()=>l.hidden=!m()||!u;return h(),n.on(`update`,h),o.addEventListener(`dblclick`,()=>void p()),c.addEventListener(`click`,()=>void p()),l.addEventListener(`click`,()=>void p()),rF&&(rF=!1,queueMicrotask(()=>void p())),{dom:o,update:t=>t.type.name===e&&(d(t),h(),!0),ignoreMutation:()=>!0,stopEvent:e=>e.target===l||e.target===c,destroy:()=>n.off(`update`,h)}}}})}function aF(e,t,n,r){e.chain().setNodeSelection(t).updateAttributes(n,{src:r}).run()}var oF=iF(`drawio`),sF=iF(`excalidraw`),cF=null;function lF(e){cF?.();let t=document.createElement(`div`);t.className=`dw-source`,t.setAttribute(`role`,`dialog`),t.setAttribute(`aria-label`,e.label);let n=document.createElement(e.multiline?`textarea`:`input`);n.className=`dw-source__field`+(e.monospace?` dw-source__field--mono`:``),n.value=e.value,n.setAttribute(`aria-label`,e.label),n.spellcheck=!1,n instanceof HTMLTextAreaElement&&(n.rows=Math.min(16,Math.max(4,e.value.split(` -`).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.target=`_blank`,s.rel=`noopener noreferrer`,s.textContent=pF(r),o.append(s),n.append(a,o)},i=String(e.attrs.url);return r(i),{dom:n,update:e=>e.type.name===`embed`&&(e.attrs.url!==i&&r(i=String(e.attrs.url)),!0),ignoreMutation:()=>!0,stopEvent:e=>e.target instanceof Element&&!!e.target.closest(`a`)}}}}),yF=Jp.create({name:`linkCard`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){let e=e=>({default:``,parseHTML:t=>t.getAttribute(`data-${e}`)??``,renderHTML:t=>({[`data-${e}`]:t[e]})});return{url:e(`url`),title:e(`title`),description:e(`description`),image:e(`image`),site:e(`site`)}},parseHTML(){return[{tag:`div[data-type='link-card']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=fF(String(e.attrs.url));return[`div`,A(t,{"data-type":`link-card`}),[`a`,{href:n},String(e.attrs.title||n)]]},addCommands(){return{insertLinkCard:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e.url,title:e.title??``,description:e.description??``,image:e.image??``,site:e.site??``}})}},addNodeView(){return({node:e})=>{let t=document.createElement(`a`);t.className=`dw-linkcard`,t.setAttribute(`data-type`,`link-card`),t.contentEditable=`false`,t.target=`_blank`,t.rel=`noopener noreferrer`;let n=e=>{let n=fF(String(e.url));t.href=n,t.replaceChildren();let r=document.createElement(`span`);r.className=`dw-linkcard__text`;let i=document.createElement(`span`);if(i.className=`dw-linkcard__title`,i.textContent=String(e.title||``)||pF(n),r.append(i),e.description){let t=document.createElement(`span`);t.className=`dw-linkcard__desc`,t.textContent=String(e.description),r.append(t)}let a=document.createElement(`span`);a.className=`dw-linkcard__site`,a.textContent=String(e.site||``)||pF(n),r.append(a),t.append(r);let o=fF(String(e.image||``));if(o.startsWith(`https:`)){let e=document.createElement(`img`);e.className=`dw-linkcard__image`,e.src=o,e.alt=``,e.loading=`lazy`,e.referrerPolicy=`no-referrer`,e.onerror=()=>e.remove(),t.append(e)}},r=e;return n(e.attrs),t.addEventListener(`click`,e=>{this.editor.view.editable&&!(e.ctrlKey||e.metaKey)&&e.preventDefault()}),{dom:t,update:e=>e.type.name===`linkCard`&&(e.attrs!==r.attrs&&n(e.attrs),r=e,!0),ignoreMutation:()=>!0}}}}),bF=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,xF=Jp.create({name:`image`,addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?`inline`:`block`},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?`img[src]`:`img[src]:not([src^="data:"])`}]},renderHTML({HTMLAttributes:e}){return[`img`,A(this.options.HTMLAttributes,e)]},parseMarkdown:(e,t)=>t.createNode(`image`,{src:e.href,title:e.title,alt:e.text}),renderMarkdown:e=>{let t=e.attrs?.src??``,n=e.attrs?.alt??``,r=e.attrs?.title??``;return r?`![${n}](${t} "${r}")`:`![${n}](${t})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>`u`)return null;let{directions:e,minWidth:t,minHeight:n,alwaysPreserveAspectRatio:r}=this.options.resize,i=new Set([`src`,`width`,`height`]);return({node:a,getPos:o,HTMLAttributes:s,editor:c})=>{let l=document.createElement(`img`);l.draggable=!1;let u=A(this.options.HTMLAttributes,s);Object.entries(u).forEach(([e,t])=>{if(t!=null)switch(e){case`src`:case`width`:case`height`:break;default:l.setAttribute(e,t)}}),u.src!==null&&(l.src=u.src);let d={...s},f=e=>{typeof e==`string`&&e!==``?l.getAttribute(`src`)!==e&&(l.src=e):(l.hasAttribute(`src`)&&l.removeAttribute(`src`),l.src!==``&&(l.src=``))};f(s.src);let p=new qp({element:l,editor:c,node:a,getPos:o,onResize:(e,t)=>{l.style.width=`${e}px`,l.style.height=`${t}px`},onCommit:(e,t)=>{let n=o();n!==void 0&&this.editor.chain().setNodeSelection(n).updateAttributes(this.name,{width:e,height:t}).run()},onUpdate:e=>{if(e.type!==a.type)return!1;let t=Lu(e,c.extensionManager.attributes.filter(t=>t.type===e.type.name));return Object.keys(d).forEach(e=>{!i.has(e)&&!(e in t)&&l.removeAttribute(e)}),Object.entries(t).forEach(([e,t])=>{i.has(e)||(t==null?l.removeAttribute(e):l.setAttribute(e,t))}),f(t.src),d=t,!0},options:{directions:e,min:{width:t,height:n},preserveAspectRatio:r===!0}}),m=p.dom,h=()=>{m.style.visibility=``,m.style.pointerEvents=``};return m.style.visibility=`hidden`,m.style.pointerEvents=`none`,l.complete&&l.naturalWidth>0?h():(l.onload=h,l.onerror=h),p}},addCommands(){return{setImage:e=>({commands:t})=>t.insertContent({type:this.name,attrs:e})}},addInputRules(){return[Up({find:bF,type:this.type,getAttributes:e=>{let[,,t,n,r]=e;return{src:n,alt:t,title:r}}})]}});async function SF(e,t,n,r){if(t.upload)for(let i of n){let n=await t.upload(i),a=n.mime.startsWith(`image/`)?{type:`image`,attrs:{src:n.url,alt:n.name}}:{type:`fileAttachment`,attrs:{url:n.url,name:n.name,size:n.size,mime:n.mime,view:jj(n.mime,n.name)?`preview`:`card`}};e.chain().focus().insertContentAt(r??e.state.selection.to,a).run(),r=void 0}}var CF=xF.extend({addOptions(){return{...this.parent(),host:void 0,inline:!1,allowBase64:!1}},addNodeView(){return({node:e})=>{let t=document.createElement(`img`),n=e=>{let n=String(e.attrs.src??``);t.src=this.options.host?this.options.host.resolve(n):n,t.alt=String(e.attrs.alt??``),e.attrs.title&&(t.title=String(e.attrs.title))};return n(e),t.draggable=!0,{dom:t,update:t=>t.type===e.type&&(n(t),!0)}}}});function wF(e){if(!e)return``;let t=[`B`,`KB`,`MB`,`GB`],n=0,r=e;for(;r>=1024&&n({editor:e,commands:t})=>{let n=e.getAttributes(this.name);return!e.isActive(this.name)||!jj(n.mime,n.name)?!1:t.updateAttributes(this.name,{view:n.view===`preview`?`card`:`preview`})}}},parseHTML(){return[{tag:`div[data-type=file]`,getAttrs:e=>({url:e.getAttribute(`data-url`)??``,name:e.getAttribute(`data-name`)??e.textContent??`file`,size:Number(e.getAttribute(`data-size`)??0),mime:e.getAttribute(`data-mime`)??``,view:e.getAttribute(`data-view`)===`preview`?`preview`:`card`})}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`file`,"data-url":e.attrs.url,"data-name":e.attrs.name,"data-size":e.attrs.size,"data-mime":e.attrs.mime,"data-view":e.attrs.view}),[`a`,{href:e.attrs.url,download:e.attrs.name},e.attrs.name]]},addNodeView(){return({node:e})=>{let{host:t,loadPdf:n,labels:r}=this.options,i=document.createElement(`div`);i.className=`dw-file-block`,i.setAttribute(`data-type`,`file`);let a=document.createElement(`div`);a.className=`dw-file`;let o=document.createElement(`a`);o.className=`dw-file__name`,o.target=`_blank`,o.rel=`noopener`;let s=document.createElement(`span`);s.className=`dw-file__size`,a.append(o,s),i.append(a);let c=null,l=null,u=``,d=e=>{let a=String(e.attrs.url??``),d=t?t.resolve(a):a;o.href=d,o.textContent=String(e.attrs.name??`file`),s.textContent=wF(Number(e.attrs.size??0)),!(e.attrs.view===`preview`&&jj(e.attrs.mime,e.attrs.name)&&a)||!n||!r?(l?.(),l=null,c?.remove(),c=null,u=``):u!==d&&(l?.(),c||(c=document.createElement(`div`),c.className=`dw-pdf`,c.tabIndex=0,c.setAttribute(`role`,`document`),i.append(c)),c.setAttribute(`aria-label`,String(e.attrs.name??`PDF`)),u=d,l=Mj(c,d,n,r))};return d(e),{dom:i,update:t=>t.type===e.type&&(d(t),!0),stopEvent:e=>!!c&&c.contains(e.target)&&e.type!==`mousedown`,ignoreMutation:()=>!0,destroy:()=>l?.()}}}}),EF=Tp.create({name:`fileDrop`,addOptions(){return{host:void 0,onError:void 0}},addProseMirrorPlugins(){let e=this.options.host;return e?[DF(()=>this.editor,e,this.options.onError)]:[]}});function DF(e,t,n){let r=(r,i)=>{let a=e();return!a||!r.length||!t.upload?!1:(SF(a,t,r,i).catch(n),!0)};return new E({key:new D(`docwellFileDrop`),props:{handlePaste(e,t){return r([...t.clipboardData?.files??[]])},handleDrop(e,t){let n=[...t.dataTransfer?.files??[]];if(!n.length)return!1;let i=e.posAtCoords({left:t.clientX,top:t.clientY});return t.preventDefault(),r(n,i?.pos)}}})}var OF=new D(`dwFind`),kF=``;function AF(e,t,n=!1){if(!t)return[];let r=n?t:t.toLowerCase(),i=[];return e.descendants((e,t)=>{if(!e.isTextblock)return!0;let a=``,o=[];e.forEach((e,n)=>{let r=t+1+n;if(e.isText){let t=e.text??``;for(let e=0;ee.from>=r);return a===-1&&(a=i.length?0:-1),{term:t,caseSensitive:n,matches:i,current:a}}function MF(e,t){return t&&e.setSelection(w.create(e.doc,t.from,t.to)).scrollIntoView(),e}var NF=Tp.create({name:`findReplace`,addCommands(){return{setFind:(e,t=!1)=>({state:n,tr:r,dispatch:i})=>{let a=jF(n.doc,e,t,n.selection.from);return r.setMeta(OF,{term:e,caseSensitive:t,near:n.selection.from}),i&&i(MF(r,a.matches[a.current])),!0},findStep:e=>({state:t,tr:n,dispatch:r})=>{let i=OF.getState(t);if(!i?.matches.length)return!1;let a=(i.current+e+i.matches.length)%i.matches.length;return n.setMeta(OF,{current:a}),r&&r(MF(n,i.matches[a])),!0},replaceCurrent:e=>({state:t,tr:n,dispatch:r})=>{let i=OF.getState(t),a=i?.matches[i.current];if(!i||!a)return!1;if(r){n.insertText(e,a.from,a.to),n.setMeta(OF,{term:i.term,caseSensitive:i.caseSensitive,near:a.from+e.length});let t=jF(n.doc,i.term,i.caseSensitive,a.from+e.length);r(MF(n,t.matches[t.current]))}return!0},replaceAll:e=>({state:t,tr:n,dispatch:r})=>{let i=OF.getState(t);if(!i?.matches.length)return!1;if(r){for(let t of[...i.matches].reverse())n.insertText(e,t.from,t.to);n.setMeta(OF,{term:i.term,caseSensitive:i.caseSensitive,near:0}),r(n)}return!0},clearFind:()=>({tr:e,dispatch:t})=>(t&&t(e.setMeta(OF,{clear:!0})),!0)}},addProseMirrorPlugins(){let e={term:``,caseSensitive:!1,matches:[],current:-1};return[new E({key:OF,state:{init:()=>e,apply(t,n,r,i){let a=t.getMeta(OF);if(a&&`clear`in a)return e;if(a&&`term`in a)return jF(i.doc,a.term,a.caseSensitive,a.near);if(a&&`current`in a)return{...n,current:a.current};if(!n.term||!t.docChanged)return n;let o=n.matches[n.current]?.from??0;return jF(i.doc,n.term,n.caseSensitive,t.mapping.map(o))}},props:{decorations(e){let t=OF.getState(e);return t?.matches.length?xs.create(e.doc,t.matches.map((e,n)=>vs.inline(e.from,e.to,{class:n===t.current?`dw-find dw-find-current`:`dw-find`}))):null}}})]}}),PF={slashMenu:`Insert block`,noMatches:`No matching blocks`,slash:{text:{label:`Text`,description:`Plain paragraph`},h1:{label:`Heading 1`,description:`Big section heading`},h2:{label:`Heading 2`,description:`Medium section heading`},h3:{label:`Heading 3`,description:`Small section heading`},otherHeadings:{label:`Other headings`,description:`Headings 4 to 6`},h4:{label:`Heading 4`,description:`A heading below level 3`},h5:{label:`Heading 5`,description:`A heading below level 4`},h6:{label:`Heading 6`,description:`The smallest heading`},bullet:{label:`Bulleted list`,description:`A simple list`},ordered:{label:`Numbered list`,description:`A list with numbers`},todo:{label:`To-do list`,description:`Tasks to tick off (or type [])`},callout:{label:`Callout`,description:`Set a note apart with an emoji and colour`},table:{label:`Table`,description:`Rows and columns`},quote:{label:`Quote`,description:`Set text apart as a quote`},code:{label:`Code block`,description:`Monospaced code`},divider:{label:`Divider`,description:`A line between sections`},image:{label:`Image`,description:`Upload a picture`},file:{label:`File`,description:`Attach a file to download`},math:{label:`Math block`,description:`A formula on its own line (LaTeX)`},mathInline:{label:`Inline math`,description:`A formula inside the text (LaTeX)`},mermaid:{label:`Mermaid diagram`,description:`Flowcharts and sequences from text`},drawio:{label:`Draw.io diagram`,description:`Draw a diagram with diagrams.net`},excalidraw:{label:`Excalidraw drawing`,description:`Sketch by hand`},toc:{label:`Table of contents`,description:`The page's headings, kept up to date`},pageLink:{label:`Link to page`,description:`Link another page (or type [[)`},toggle:{label:`Toggle`,description:`A heading that hides the blocks under it`},embed:{label:`Embed`,description:`A video, design or document from YouTube, Figma and more`},linkCard:{label:`Link card`,description:`A link with its page's title and picture`},newPage:{label:`New page`,description:`Make a page and link it here`},today:{label:`Today`,description:`Insert today's date`},tomorrow:{label:`Tomorrow`,description:`Insert tomorrow's date`},yesterday:{label:`Yesterday`,description:`Insert yesterday's date`},now:{label:`Now`,description:`Insert the date and time`}},format:{bold:`Bold`,italic:`Italic`,strike:`Strikethrough`,code:`Inline code`,link:`Link`,linkPrompt:`Link address (leave empty to remove the link)`,comment:`Comment`,underline:`Underline`,color:`Colour`,textColor:`Text colour`,highlight:`Highlight`,noColor:`Default`,align:`Align`,alignLeft:`Align left`,alignCenter:`Align centre`,alignRight:`Align right`,math:`Inline math`,linkedPage:`Make a linked page`},colors:{gray:`Grey`,red:`Red`,orange:`Orange`,yellow:`Yellow`,green:`Green`,teal:`Teal`,blue:`Blue`,purple:`Purple`,pink:`Pink`},table:{toolbar:`Table`,dragRow:`Drag to move the row`,dragColumn:`Drag to move the column`,moveRowUp:`Move row up`,moveRowDown:`Move row down`,moveColumnLeft:`Move column left`,moveColumnRight:`Move column right`,addRowBefore:`Add row above`,addRowAfter:`Add row below`,addColumnBefore:`Add column left`,addColumnAfter:`Add column right`,deleteRow:`Delete row`,deleteColumn:`Delete column`,toggleHeaderRow:`Header row`,mergeCells:`Merge cells`,splitCell:`Split cell`,deleteTable:`Delete table`},blockMenu:{open:`Drag to move, click for actions`,turnInto:`Turn into`,moveUp:`Move up`,moveDown:`Move down`,duplicate:`Duplicate`,copy:`Copy`,delete:`Delete`,showLineNumbers:`Show line numbers`,hideLineNumbers:`Hide line numbers`,showPages:`Show pages`,showAsFile:`Show as file`},mentions:`Mention someone`,noPeople:`Nobody found`,pageLinks:`Link to a page`,noPages:`No pages found`,blocks:{edit:`Edit`,done:`Done`,cancel:`Cancel`,save:`Save`,remove:`Remove`,saving:`Saving…`,latex:`LaTeX formula`,mermaid:`Mermaid diagram source`,mermaidError:`This diagram has an error:`,emptyDrawio:`Empty diagram. Click to draw.`,emptyExcalidraw:`Empty drawing. Click to sketch.`,loadFailed:`The editor could not be loaded.`,toc:`Contents`,tocEmpty:`Add headings to the page to fill the table of contents.`,expand:`Show contents`,collapse:`Hide contents`,embed:`Embedded content`,embedUrl:`Address of the video, design or document`,embedInvalid:`This address can't be embedded.`,linkUrl:`Address of the page to link`,copyBlockLink:`Copy link to this block`,calloutEmoji:`Change emoji`,calloutColor:`Change colour`,pdfLoading:`Loading PDF…`,pdfPage:`Page {n}`},find:{find:`Find in page`,replace:`Replace with`,previous:`Previous match`,next:`Next match`,replaceOne:`Replace`,replaceAll:`Replace all`,matchCase:`Match case`,close:`Close`,count:`{current} of {total}`,none:`No matches`},dates:{today:`Today`,tomorrow:`Tomorrow`,yesterday:`Yesterday`,nextWeek:`Next week`,remindWord:`remind`,remindMe:`Remind me`,reminderAt:`Reminder at 9:00 on the day`,someoneElse:`Someone else set a reminder on this date.`,edit:`Change date`}},I=class e extends Error{constructor(t,n){var r=`KaTeX parse error: `+t,i,a,o=n&&n.loc;if(o&&o.start<=o.end){var s=o.lexer.input;i=o.start,a=o.end,i===s.length?r+=` at end of input: `:r+=` at position `+(i+1)+`: `;var c=s.slice(i,a).replace(/[^]/g,`$&̲`),l=i>15?`…`+s.slice(i-15,i):s.slice(0,i),u=a+15e.replace(FF,`-$1`).toLowerCase(),LF={"&":`&`,">":`>`,"<":`<`,'"':`"`,"'":`'`},RF=/[&><"']/g,zF=e=>String(e).replace(RF,e=>LF[e]),BF=e=>e.type===`ordgroup`||e.type===`color`?e.body.length===1?BF(e.body[0]):e:e.type===`font`?BF(e.body):e,VF=new Set([`mathord`,`textord`,`atom`]),HF=e=>VF.has(BF(e).type),UF=e=>{var t=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(e);return t?t[2]!==`:`||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t[1])?null:t[1].toLowerCase():`_relative`},WF={displayMode:{type:`boolean`,description:`Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.`,cli:`-d, --display-mode`},output:{type:{enum:[`htmlAndMathml`,`html`,`mathml`]},description:`Determines the markup language of the output.`,cli:`-F, --format `},leqno:{type:`boolean`,description:`Render display math in leqno style (left-justified tags).`},fleqn:{type:`boolean`,description:`Render display math flush left.`},throwOnError:{type:`boolean`,default:!0,cli:`-t, --no-throw-on-error`,cliDescription:`Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error.`},errorColor:{type:`string`,default:`#cc0000`,cli:`-c, --error-color `,cliDescription:`A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.`,cliProcessor:e=>`#`+e},macros:{type:`object`,cli:`-m, --macro `,cliDescription:`Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).`,cliDefault:[],cliProcessor:(e,t)=>(t.push(e),t)},minRuleThickness:{type:`number`,description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:e=>Math.max(0,e),cli:`--min-rule-thickness `,cliProcessor:parseFloat},colorIsTextColor:{type:`boolean`,description:`Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.`,cli:`-b, --color-is-text-color`},strict:{type:[{enum:[`warn`,`ignore`,`error`]},`boolean`,`function`],description:`Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.`,cli:`-S, --strict`,cliDefault:!1},trust:{type:[`boolean`,`function`],description:`Trust the input, enabling all HTML features such as \\url.`,cli:`-T, --trust`},maxSize:{type:`number`,default:1/0,description:`If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large`,processor:e=>Math.max(0,e),cli:`-s, --max-size `,cliProcessor:parseInt},maxExpand:{type:`number`,default:1e3,description:`Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.`,processor:e=>Math.max(0,e),cli:`-e, --max-expand `,cliProcessor:e=>e===`Infinity`?1/0:parseInt(e)},globalGroup:{type:`boolean`,cli:!1}};function GF(e){if(typeof e!=`string`)return e.enum[0];switch(e){case`boolean`:return!1;case`string`:return``;case`number`:return 0;case`object`:return{};default:throw Error(`Unexpected schema type; settings must declare an explicit default.`)}}function KF(e){return Object.prototype.hasOwnProperty.call(e,`default`)&&e.default!==void 0?e.default:GF(Array.isArray(e.type)?e.type[0]:e.type)}function qF(e,t,n,r){var i=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0,a=Object.prototype.hasOwnProperty.call(r,`processor`)?r.processor:void 0;e[t]=i===void 0?KF(r):a?a(i):i}var JF=class{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e||={};for(var t of Object.keys(WF)){var n=WF[t];n&&qF(this,t,e,n)}}reportNonstrict(e,t,n){var r=this.strict;if(typeof r==`function`&&(r=r(e,t,n)),r&&r!==`ignore`){if(r===!0||r===`error`)throw new I(`LaTeX-incompatible input and strict mode is set to 'error': `+(t+` [`+e+`]`),n);r===`warn`?typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to 'warn': `+(t+` [`+e+`]`)):typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to `+(`unrecognized '`+r+`': `+t+` [`+e+`]`))}}useStrictBehavior(e,t,n){var r=this.strict;if(typeof r==`function`)try{r=r(e,t,n)}catch{r=`error`}return!r||r===`ignore`?!1:r===!0||r===`error`?!0:r===`warn`?(typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to 'warn': `+(t+` [`+e+`]`)),!1):(typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to `+(`unrecognized '`+r+`': `+t+` [`+e+`]`)),!1)}isTrusted(e){if(`url`in e&&e.url&&!e.protocol){var t=UF(e.url);if(t==null)return!1;e.protocol=t}return!!(typeof this.trust==`function`?this.trust(e):this.trust)}},YF=class{constructor(e,t,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=t,this.cramped=n}sup(){return iI[aI[this.id]]}sub(){return iI[oI[this.id]]}fracNum(){return iI[sI[this.id]]}fracDen(){return iI[cI[this.id]]}cramp(){return iI[lI[this.id]]}text(){return iI[uI[this.id]]}isTight(){return this.size>=2}},XF=0,ZF=1,QF=2,$F=3,eI=4,tI=5,nI=6,rI=7,iI=[new YF(XF,0,!1),new YF(ZF,0,!0),new YF(QF,1,!1),new YF($F,1,!0),new YF(eI,2,!1),new YF(tI,2,!0),new YF(nI,3,!1),new YF(rI,3,!0)],aI=[eI,tI,eI,tI,nI,rI,nI,rI],oI=[tI,tI,tI,tI,rI,rI,rI,rI],sI=[QF,$F,eI,tI,nI,rI,nI,rI],cI=[$F,$F,tI,tI,rI,rI,rI,rI],lI=[ZF,ZF,$F,$F,tI,tI,rI,rI],uI=[XF,ZF,QF,$F,QF,$F,QF,$F],L={DISPLAY:iI[XF],TEXT:iI[QF],SCRIPT:iI[eI],SCRIPTSCRIPT:iI[nI]},dI=[{name:`latin`,blocks:[[256,591],[768,879]]},{name:`cyrillic`,blocks:[[1024,1279]]},{name:`armenian`,blocks:[[1328,1423]]},{name:`brahmic`,blocks:[[2304,4255]]},{name:`georgian`,blocks:[[4256,4351]]},{name:`cjk`,blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:`hangul`,blocks:[[44032,55215]]}];function fI(e){for(var t=0;t=i[0]&&e<=i[1])return n.name}return null}var pI=[];dI.forEach(e=>e.blocks.forEach(e=>pI.push(...e)));function mI(e){for(var t=0;t=pI[t]&&e<=pI[t+1])return!0;return!1}var hI=e=>e+` `+e,gI=80,_I=function(e,t){return`M95,`+(622+e+t)+` +`);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}){return[`mark`,A(this.options.HTMLAttributes,e),0]},renderMarkdown:(e,t)=>`==${t.renderChildren(e)}==`,parseMarkdown:(e,t)=>t.applyMark(`highlight`,t.parseInline(e.tokens||[])),markdownTokenizer:{name:`highlight`,level:`inline`,start:e=>e.indexOf(`==`),tokenize(e,t,n){let r=/^(==)(?!\s)([^=]*[^=\s])(==)/.exec(e);if(r){let e=r[2].trim(),t=n.inlineTokens(e);return{type:`highlight`,raw:r[0],text:e,tokens:t}}}},addCommands(){return{setHighlight:e=>({commands:t})=>t.setMark(this.name,e),toggleHighlight:e=>({commands:t})=>t.toggleMark(this.name,e),unsetHighlight:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-h":()=>this.editor.commands.toggleHighlight()}},addInputRules(){return[Hp({find:CP,type:this.type})]},addPasteRules(){return[Yp({find:wP,type:this.type})]}}),EP=[`gray`,`red`,`orange`,`yellow`,`green`,`teal`,`blue`,`purple`,`pink`],DP=e=>typeof e==`string`&&EP.includes(e),OP=_p.create({name:`textColor`,addAttributes(){return{color:{default:null,parseHTML:e=>{let t=e.getAttribute(`data-color`);return DP(t)?t:null},renderHTML:e=>e.color?{"data-color":e.color}:{}}}},parseHTML(){return[{tag:`span[data-color]`,getAttrs:e=>DP(e.getAttribute(`data-color`))?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{class:`dw-text-color`}),0]},addCommands(){return{setTextColor:e=>({commands:t})=>t.setMark(this.name,{color:e}),unsetTextColor:()=>({commands:e})=>e.unsetMark(this.name)}}}),kP=TP.extend({addOptions(){return{...this.parent(),multicolor:!0}},addAttributes(){return{color:{default:null,parseHTML:e=>{let t=e.getAttribute(`data-color`);return DP(t)?t:null},renderHTML:e=>({"data-color":DP(e.color)?e.color:`yellow`})}}},renderHTML({HTMLAttributes:e}){return[`mark`,A(e,{class:`dw-highlight`}),0]}}),AP=`💡`;function jP(e){let t=e.trim();return t&&[...t].length<=4?t:``}var MP=Jp.create({name:`callout`,group:`block`,content:`block+`,defining:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{emoji:{default:AP,parseHTML:e=>jP(e.getAttribute(`data-emoji`)??``)||AP,renderHTML:e=>({"data-emoji":e.emoji})},color:{default:`blue`,parseHTML:e=>{let t=e.getAttribute(`data-color`);return DP(t)?t:`blue`},renderHTML:e=>({"data-color":e.color})}}},parseHTML(){return[{tag:`aside[data-type=callout]`,contentElement:e=>e.querySelector(`:scope > .callout-body`)??e}]},renderHTML({HTMLAttributes:e}){return[`aside`,A(e,{"data-type":`callout`,class:`dw-callout`}),0]},addCommands(){return{setCallout:e=>({commands:t})=>t.wrapIn(this.name,e),unsetCallout:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{Backspace:({editor:e})=>{let{$from:t,empty:n}=e.state.selection;if(!n||t.parentOffset>0)return!1;for(let n=t.depth-1;n>0;n--){if(t.node(n).type.name===this.name)return t.index(n)!==0||t.start(n+1)!==t.start()?!1:e.commands.lift(this.name);if(t.index(n)!==0)return!1}return!1}}},addNodeView(){return({node:e,getPos:t,editor:n})=>{let r=this.options.labels,i=document.createElement(`aside`);i.className=`dw-callout`,i.setAttribute(`data-type`,`callout`);let a=document.createElement(`div`);a.className=`dw-callout__side`,a.contentEditable=`false`;let o=document.createElement(`button`);o.type=`button`,o.className=`dw-callout__emoji`;let s=document.createElement(`button`);s.type=`button`,s.className=`dw-callout__color`,a.append(o,s);let c=document.createElement(`div`);c.className=`dw-callout__body`,i.append(a,c);let l=e,u=e=>{let r=t();typeof r==`number`&&n.isEditable&&n.view.dispatch(n.state.tr.setNodeMarkup(r,void 0,{...l.attrs,...e}))};o.addEventListener(`mousedown`,e=>e.preventDefault()),o.addEventListener(`click`,()=>{if(!n.isEditable)return;let e=jP(window.prompt(r?.blocks.calloutEmoji??`Emoji`,l.attrs.emoji)??``);e&&u({emoji:e})}),s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`click`,()=>{let e=EP.indexOf(l.attrs.color);u({color:EP[(e+1)%EP.length]})});let d=()=>{i.setAttribute(`data-color`,String(l.attrs.color)),o.textContent=String(l.attrs.emoji);let e=r?.blocks.calloutEmoji??`Emoji`;o.setAttribute(`aria-label`,e),o.title=e;let t=r?.blocks.calloutColor??`Colour`;s.setAttribute(`aria-label`,t),s.title=t};return d(),{dom:i,contentDOM:c,update:t=>t.type===e.type&&(l=t,d(),!0),stopEvent:e=>a.contains(e.target),ignoreMutation:e=>a.contains(e.target)}}}});function NP(e){let t=MS.getState(e);return t?.type&&t.binding&&t.doc?t:null}function PP(e,t){let n=NP(e);if(!n||!t?.from||!t.to)return null;try{let r=e=>jS(n.doc,n.type,ly(gg(e)),n.binding.mapping),i=r(t.from),a=r(t.to);return i===null||a===null||a<=i||a>e.doc.content.size?null:{from:i,to:a}}catch{return null}}var FP=new D(`docwellComments`);function IP(e,t,n){let r=[];for(let i of t){let t=PP(e,i.anchor);t&&r.push(vs.inline(t.from,t.to,{class:i.id===n?`dw-comment is-active`:`dw-comment`,"data-comment":i.id}))}return xs.create(e.doc,r)}var LP=Tp.create({name:`commentHighlights`,addOptions(){return{onSelect:void 0}},addProseMirrorPlugins(){let e=()=>this.options.onSelect;return[new E({key:FP,state:{init:()=>({marks:[],active:``,decos:xs.empty}),apply(e,t,n,r){let i=e.getMeta(FP);if(i)return{...i,decos:IP(r,i.marks,i.active)};if(!e.docChanged||!t.marks.length)return t;let a=e.getMeta(MS)?.isChangeOrigin;return{...t,decos:a?IP(r,t.marks,t.active):t.decos.map(e.mapping,e.doc)}}},props:{decorations:e=>FP.getState(e)?.decos??xs.empty,handleClick(t,n,r){let i=r.target?.closest?.(`[data-comment]`)?.getAttribute(`data-comment`);return i&&e()?.(i),!1}}})]}}),RP=/^(\d{4})-(\d{2})-(\d{2})$/;function zP(e){let t=e=>String(e).padStart(2,`0`);return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function BP(e){let t=RP.exec(e);if(!t)return null;let n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return zP(n)===e?n:null}function VP(e,t){return new Date(e.getFullYear(),e.getMonth(),e.getDate()+t)}function HP(e,t){return Math.round((t.getTime()-e.getTime())/864e5)}function UP(e,t,n=new Date){let r=BP(e);if(!r)return e;let i=t.dates,a=HP(VP(n,0),r);return a===0?i.today:a===1?i.tomorrow:a===-1?i.yesterday:new Intl.DateTimeFormat(t.locale,{month:`short`,day:`numeric`,year:r.getFullYear()===n.getFullYear()?void 0:`numeric`}).format(r)}function WP(e,t){let n=BP(e);return n?new Intl.DateTimeFormat(t.locale,{dateStyle:`full`}).format(n):e}function GP(e,t,n,r=new Date){let i=t.dates,a=e.trim().toLowerCase(),o=!1;for(let e of new Set([i.remindWord.toLowerCase(),`remind`])){if(a.startsWith(e)){o=!0,a=a.slice(e.length).trim();break}if(a.length>=3&&e.startsWith(a)){o=!0,a=``;break}}if(o&&!n)return[];let s=VP(r,0);if(!a)return o?[1,0,7].map(e=>({date:zP(VP(s,e)),remind:o})):[{date:zP(s),remind:!1},...n?[{date:zP(VP(s,1)),remind:!0}]:[]];let c=[{words:[i.today,`today`],date:s},{words:[i.tomorrow,`tomorrow`],date:VP(s,1)},{words:[i.nextWeek,`next week`],date:VP(s,7)}];o||c.push({words:[i.yesterday,`yesterday`],date:VP(s,-1)});let l=e=>new Intl.DateTimeFormat(e,{weekday:`long`});for(let e=1;e<=7;e++){let n=VP(s,e);c.push({words:[l(t.locale).format(n),l(`en`).format(n)],date:n})}let u=[];BP(a)&&u.push({date:a,remind:o});for(let e of c)e.words.some(e=>e.toLowerCase().startsWith(a))&&u.push({date:zP(e.date),remind:o});return u.filter((e,t)=>u.findIndex(t=>t.date===e.date)===t).slice(0,5)}function KP(e,t){let n=e.toLowerCase().split(` `),r=[t.dates.remindWord,`remind`,t.dates.nextWeek.split(` `)[0]??``,`next`];return n.length>1&&n.length<=3&&r.some(e=>e&&e.toLowerCase()===n[0])}var qP=Jp.create({name:`dateMention`,group:`inline`,inline:!0,atom:!0,selectable:!0,addOptions(){return{labels:void 0,me:()=>void 0,onOpen:void 0}},addAttributes(){return{date:{default:``,parseHTML:e=>e.getAttribute(`data-date`)??``,renderHTML:e=>({"data-date":e.date})},remind:{default:``,parseHTML:e=>e.getAttribute(`data-remind`)??``,renderHTML:e=>e.remind?{"data-remind":e.remind}:{}},tz:{default:``,parseHTML:e=>e.getAttribute(`data-tz`)??``,renderHTML:e=>e.tz?{"data-tz":e.tz}:{}}}},parseHTML(){return[{tag:`span[data-type="date"]`}]},renderHTML({node:e,HTMLAttributes:t}){return[`span`,A({"data-type":`date`,class:`dw-date`},t),UP(e.attrs.date,this.options.labels)]},renderText({node:e}){return UP(e.attrs.date,this.options.labels)},addNodeView(){let{labels:e,me:t,onOpen:n}=this.options;return({node:r,editor:i,getPos:a})=>{let o=r,s=document.createElement(`span`);s.dataset.type=`date`,s.className=`dw-date`,s.contentEditable=`false`,s.classList.toggle(`is-link`,!!n);let c=null,l=()=>{let t=o.attrs.date,n=o.attrs.remind,r=!!BP(t)&&t{let t=typeof a==`function`?a():void 0;t!==void 0&&i.chain().command(({tr:n})=>(n.setNodeMarkup(t,void 0,{...o.attrs,...e}),!0)).run()};return s.addEventListener(`mousedown`,r=>{c||(i.isEditable?(r.preventDefault(),c=XP(s,i,o,e,t(),u,()=>c=null,n)):n&&BP(o.attrs.date)&&(r.preventDefault(),n(o.attrs.date)))}),{dom:s,update(e){return e.type===o.type&&(o=e,l(),!0)},ignoreMutation:()=>!0,stopEvent:e=>s.contains(e.target)&&e.type!==`mousedown`,destroy(){c?.()}}}}});function JP(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone??``}catch{return``}}function YP(e,t,n,r){let i={date:n.date,remind:n.remind&&r?r:``,tz:n.remind&&r?JP():``};e.chain().focus().insertContentAt(t,[{type:`dateMention`,attrs:i},{type:`text`,text:` `}]).run()}function XP(e,t,n,r,i,a,o,s){let c=r.dates,l=document.createElement(`div`);l.className=`dw-date-pop`,l.setAttribute(`role`,`dialog`),l.setAttribute(`aria-label`,c.edit);let u=document.createElement(`input`);u.type=`date`,u.className=`dw-input`,u.value=n.attrs.date,u.setAttribute(`aria-label`,c.edit),u.addEventListener(`change`,()=>{BP(u.value)&&a({date:u.value})}),l.append(u);let d=n.attrs.remind;if(d&&d!==i){let e=document.createElement(`p`);e.className=`dw-date-pop__note`,e.textContent=c.someoneElse,l.append(e)}else if(i){let e=document.createElement(`label`);e.className=`dw-date-pop__check`;let t=document.createElement(`input`);t.type=`checkbox`,t.checked=d===i,t.addEventListener(`change`,()=>a(t.checked?{remind:i,tz:JP()}:{remind:``,tz:``})),e.append(t,document.createTextNode(c.remindMe));let n=document.createElement(`span`);n.className=`dw-date-pop__note`,n.textContent=c.reminderAt,l.append(e,n)}if(s){let e=document.createElement(`button`);e.type=`button`,e.className=`dw-date-pop__open`,e.textContent=c.openJournal??`Open journal`,e.addEventListener(`click`,()=>{let e=n.attrs.date;h(),BP(e)&&s(e)}),l.append(e)}document.body.append(l);let f=wj(e,l,()=>{Oj(e,l,{placement:`bottom-start`,strategy:`fixed`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:t})=>Object.assign(l.style,{left:`${e}px`,top:`${t}px`}))}),p=t=>{!l.contains(t.target)&&!e.contains(t.target)&&h()},m=e=>{e.key===`Escape`&&(e.preventDefault(),h(),t.commands.focus())};function h(){f(),l.remove(),document.removeEventListener(`mousedown`,p,!0),document.removeEventListener(`keydown`,m,!0),o()}return document.addEventListener(`mousedown`,p,!0),document.addEventListener(`keydown`,m,!0),u.focus(),h}function ZP(e){let t=document.createElement(`div`);t.className=`dw-diagram-editor`,t.setAttribute(`role`,`dialog`),t.setAttribute(`aria-modal`,`true`),t.setAttribute(`aria-label`,e);let n=document.createElement(`p`);n.className=`dw-diagram-editor__status`,t.append(n),document.body.append(t);let r=document.body.style.overflow;return document.body.style.overflow=`hidden`,{root:t,status:e=>{n.textContent=e,n.hidden=!e},close:()=>{t.remove(),document.body.style.overflow=r}}}async function QP(e,t){let n=await fetch(e.resolve(t));if(!n.ok)throw Error(`loading the drawing failed (${n.status})`);return n.text()}function $P(e,t){return new File([e],t,{type:`image/svg+xml`})}function eF(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function tF(e,t,n){return new Promise(r=>{let i=ZP(n.slash.drawio?.label??`Draw.io`),a=document.createElement(`iframe`),o=new URL(e);for(let[e,t]of Object.entries({embed:`1`,proto:`json`,spin:`1`,saveAndExit:`1`,noExitBtn:`0`}))o.searchParams.set(e,t);a.src=o.toString(),a.className=`dw-diagram-editor__frame`,a.title=n.slash.drawio?.label??`Draw.io`;let s=document.createElement(`div`);s.className=`dw-diagram-editor__bar`;let c=document.createElement(`button`);c.type=`button`,c.className=`dw-source__btn`,c.textContent=n.blocks.cancel,c.addEventListener(`click`,()=>d(null)),s.append(c),i.root.append(s,a),i.status(``);let l=e=>a.contentWindow?.postMessage(JSON.stringify(e),o.origin),u=!1,d=e=>{window.removeEventListener(`message`,f),i.close(),r(e)},f=e=>{if(e.source!==a.contentWindow||e.origin!==o.origin||typeof e.data!=`string`)return;let n;try{n=JSON.parse(e.data)}catch{return}switch(n.event){case`init`:l({action:`load`,autosave:0,xml:t?`data:image/svg+xml;base64,${eF(t)}`:``});break;case`save`:u=!0,l({action:`export`,format:`xmlsvg`,spinKey:`saving`});break;case`export`:{let e=n.data??``,t=e.indexOf(`,`),r=e.slice(0,t),i=e.slice(t+1),a=r.includes(`;base64`)?new TextDecoder().decode(Uint8Array.from(atob(i),e=>e.charCodeAt(0))):decodeURIComponent(i);d(u?a:null);break}case`exit`:d(null)}};window.addEventListener(`message`,f)})}async function nF(e,t,n){let r=ZP(n.slash.excalidraw?.label??`Excalidraw`);r.status(``);try{let{openExcalidraw:i}=await e();return await i(r.root,t,n)}finally{r.close()}}var rF=!1;function iF(e){return Jp.create({name:e,group:`block`,atom:!0,draggable:!0,addOptions(){return{host:void 0,loadExcalidraw:void 0,labels:null,drawioUrl:void 0,onError:void 0}},addAttributes(){return{src:{default:``},alt:{default:``}}},parseHTML(){return[{tag:`figure[data-type='${e}']`,getAttrs:e=>({src:e.querySelector(`img`)?.getAttribute(`src`)??``})}]},renderHTML({node:t,HTMLAttributes:n}){return[`figure`,A(n,{"data-type":e}),[`img`,{src:String(t.attrs.src),alt:String(t.attrs.alt||e)}]]},addCommands(){return{insertDiagram:e=>({commands:t})=>(rF=!0,t.insertContent({type:e,attrs:{src:``}}))}},addNodeView(){return({node:t,editor:n,getPos:r})=>{let i=this.options,a=i.labels,o=document.createElement(`figure`);o.className=`dw-diagram dw-diagram--${e}`,o.setAttribute(`data-type`,e);let s=document.createElement(`img`);s.className=`dw-diagram__img`;let c=document.createElement(`p`);c.className=`dw-diagram__empty`,c.textContent=e===`drawio`?a.blocks.emptyDrawio:a.blocks.emptyExcalidraw;let l=document.createElement(`button`);l.type=`button`,l.className=`dw-diagram__edit`,l.textContent=a.blocks.edit,o.append(s,c,l);let u=``,d=t=>{u=String(t.attrs.src??``),s.hidden=!u,c.hidden=!!u,u&&(s.src=i.host?i.host.resolve(u):u,s.alt=String(t.attrs.alt||a.slash[e]?.label||e))};d(t);let f=!1,p=async()=>{if(!f&&m()&&i.host?.upload){f=!0;try{let t=u?await QP(i.host,u):``,o=e===`drawio`?await tF(i.drawioUrl||`https://embed.diagrams.net`,t,a):await nF(i.loadExcalidraw,t,a);if(o===null)return;let s=await i.host.upload($P(o,`${e===`drawio`?`diagram.drawio`:`drawing.excalidraw`}.svg`)),c=typeof r==`function`?r():void 0;c!==void 0&&aF(n,c,e,s.url)}catch(e){i.onError?.(e)}finally{f=!1}}},m=()=>n.isEditable&&!!i.host?.upload&&(e===`drawio`||!!i.loadExcalidraw),h=()=>l.hidden=!m()||!u;return h(),n.on(`update`,h),o.addEventListener(`dblclick`,()=>void p()),c.addEventListener(`click`,()=>void p()),l.addEventListener(`click`,()=>void p()),rF&&(rF=!1,queueMicrotask(()=>void p())),{dom:o,update:t=>t.type.name===e&&(d(t),h(),!0),ignoreMutation:()=>!0,stopEvent:e=>e.target===l||e.target===c,destroy:()=>n.off(`update`,h)}}}})}function aF(e,t,n,r){e.chain().setNodeSelection(t).updateAttributes(n,{src:r}).run()}var oF=iF(`drawio`),sF=iF(`excalidraw`),cF=null;function lF(e){cF?.();let t=document.createElement(`div`);t.className=`dw-source`,t.setAttribute(`role`,`dialog`),t.setAttribute(`aria-label`,e.label);let n=document.createElement(e.multiline?`textarea`:`input`);n.className=`dw-source__field`+(e.monospace?` dw-source__field--mono`:``),n.value=e.value,n.setAttribute(`aria-label`,e.label),n.spellcheck=!1,n instanceof HTMLTextAreaElement&&(n.rows=Math.min(16,Math.max(4,e.value.split(` +`).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.target=`_blank`,s.rel=`noopener noreferrer`,s.textContent=pF(r),o.append(s),n.append(a,o)},i=String(e.attrs.url);return r(i),{dom:n,update:e=>e.type.name===`embed`&&(e.attrs.url!==i&&r(i=String(e.attrs.url)),!0),ignoreMutation:()=>!0,stopEvent:e=>e.target instanceof Element&&!!e.target.closest(`a`)}}}}),yF=Jp.create({name:`linkCard`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){let e=e=>({default:``,parseHTML:t=>t.getAttribute(`data-${e}`)??``,renderHTML:t=>({[`data-${e}`]:t[e]})});return{url:e(`url`),title:e(`title`),description:e(`description`),image:e(`image`),site:e(`site`)}},parseHTML(){return[{tag:`div[data-type='link-card']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=fF(String(e.attrs.url));return[`div`,A(t,{"data-type":`link-card`}),[`a`,{href:n},String(e.attrs.title||n)]]},addCommands(){return{insertLinkCard:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e.url,title:e.title??``,description:e.description??``,image:e.image??``,site:e.site??``}})}},addNodeView(){return({node:e})=>{let t=document.createElement(`a`);t.className=`dw-linkcard`,t.setAttribute(`data-type`,`link-card`),t.contentEditable=`false`,t.target=`_blank`,t.rel=`noopener noreferrer`;let n=e=>{let n=fF(String(e.url));t.href=n,t.replaceChildren();let r=document.createElement(`span`);r.className=`dw-linkcard__text`;let i=document.createElement(`span`);if(i.className=`dw-linkcard__title`,i.textContent=String(e.title||``)||pF(n),r.append(i),e.description){let t=document.createElement(`span`);t.className=`dw-linkcard__desc`,t.textContent=String(e.description),r.append(t)}let a=document.createElement(`span`);a.className=`dw-linkcard__site`,a.textContent=String(e.site||``)||pF(n),r.append(a),t.append(r);let o=fF(String(e.image||``));if(o.startsWith(`https:`)){let e=document.createElement(`img`);e.className=`dw-linkcard__image`,e.src=o,e.alt=``,e.loading=`lazy`,e.referrerPolicy=`no-referrer`,e.onerror=()=>e.remove(),t.append(e)}},r=e;return n(e.attrs),t.addEventListener(`click`,e=>{this.editor.view.editable&&!(e.ctrlKey||e.metaKey)&&e.preventDefault()}),{dom:t,update:e=>e.type.name===`linkCard`&&(e.attrs!==r.attrs&&n(e.attrs),r=e,!0),ignoreMutation:()=>!0}}}}),bF=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,xF=Jp.create({name:`image`,addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?`inline`:`block`},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?`img[src]`:`img[src]:not([src^="data:"])`}]},renderHTML({HTMLAttributes:e}){return[`img`,A(this.options.HTMLAttributes,e)]},parseMarkdown:(e,t)=>t.createNode(`image`,{src:e.href,title:e.title,alt:e.text}),renderMarkdown:e=>{let t=e.attrs?.src??``,n=e.attrs?.alt??``,r=e.attrs?.title??``;return r?`![${n}](${t} "${r}")`:`![${n}](${t})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>`u`)return null;let{directions:e,minWidth:t,minHeight:n,alwaysPreserveAspectRatio:r}=this.options.resize,i=new Set([`src`,`width`,`height`]);return({node:a,getPos:o,HTMLAttributes:s,editor:c})=>{let l=document.createElement(`img`);l.draggable=!1;let u=A(this.options.HTMLAttributes,s);Object.entries(u).forEach(([e,t])=>{if(t!=null)switch(e){case`src`:case`width`:case`height`:break;default:l.setAttribute(e,t)}}),u.src!==null&&(l.src=u.src);let d={...s},f=e=>{typeof e==`string`&&e!==``?l.getAttribute(`src`)!==e&&(l.src=e):(l.hasAttribute(`src`)&&l.removeAttribute(`src`),l.src!==``&&(l.src=``))};f(s.src);let p=new qp({element:l,editor:c,node:a,getPos:o,onResize:(e,t)=>{l.style.width=`${e}px`,l.style.height=`${t}px`},onCommit:(e,t)=>{let n=o();n!==void 0&&this.editor.chain().setNodeSelection(n).updateAttributes(this.name,{width:e,height:t}).run()},onUpdate:e=>{if(e.type!==a.type)return!1;let t=Lu(e,c.extensionManager.attributes.filter(t=>t.type===e.type.name));return Object.keys(d).forEach(e=>{!i.has(e)&&!(e in t)&&l.removeAttribute(e)}),Object.entries(t).forEach(([e,t])=>{i.has(e)||(t==null?l.removeAttribute(e):l.setAttribute(e,t))}),f(t.src),d=t,!0},options:{directions:e,min:{width:t,height:n},preserveAspectRatio:r===!0}}),m=p.dom,h=()=>{m.style.visibility=``,m.style.pointerEvents=``};return m.style.visibility=`hidden`,m.style.pointerEvents=`none`,l.complete&&l.naturalWidth>0?h():(l.onload=h,l.onerror=h),p}},addCommands(){return{setImage:e=>({commands:t})=>t.insertContent({type:this.name,attrs:e})}},addInputRules(){return[Up({find:bF,type:this.type,getAttributes:e=>{let[,,t,n,r]=e;return{src:n,alt:t,title:r}}})]}});async function SF(e,t,n,r){if(t.upload)for(let i of n){let n=await t.upload(i),a=n.mime.startsWith(`image/`)?{type:`image`,attrs:{src:n.url,alt:n.name}}:{type:`fileAttachment`,attrs:{url:n.url,name:n.name,size:n.size,mime:n.mime,view:jj(n.mime,n.name)?`preview`:`card`}};e.chain().focus().insertContentAt(r??e.state.selection.to,a).run(),r=void 0}}var CF=xF.extend({addOptions(){return{...this.parent(),host:void 0,inline:!1,allowBase64:!1}},addNodeView(){return({node:e})=>{let t=document.createElement(`img`),n=e=>{let n=String(e.attrs.src??``);t.src=this.options.host?this.options.host.resolve(n):n,t.alt=String(e.attrs.alt??``),e.attrs.title&&(t.title=String(e.attrs.title))};return n(e),t.draggable=!0,{dom:t,update:t=>t.type===e.type&&(n(t),!0)}}}});function wF(e){if(!e)return``;let t=[`B`,`KB`,`MB`,`GB`],n=0,r=e;for(;r>=1024&&n({editor:e,commands:t})=>{let n=e.getAttributes(this.name);return!e.isActive(this.name)||!jj(n.mime,n.name)?!1:t.updateAttributes(this.name,{view:n.view===`preview`?`card`:`preview`})}}},parseHTML(){return[{tag:`div[data-type=file]`,getAttrs:e=>({url:e.getAttribute(`data-url`)??``,name:e.getAttribute(`data-name`)??e.textContent??`file`,size:Number(e.getAttribute(`data-size`)??0),mime:e.getAttribute(`data-mime`)??``,view:e.getAttribute(`data-view`)===`preview`?`preview`:`card`})}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`file`,"data-url":e.attrs.url,"data-name":e.attrs.name,"data-size":e.attrs.size,"data-mime":e.attrs.mime,"data-view":e.attrs.view}),[`a`,{href:e.attrs.url,download:e.attrs.name},e.attrs.name]]},addNodeView(){return({node:e})=>{let{host:t,loadPdf:n,labels:r}=this.options,i=document.createElement(`div`);i.className=`dw-file-block`,i.setAttribute(`data-type`,`file`);let a=document.createElement(`div`);a.className=`dw-file`;let o=document.createElement(`a`);o.className=`dw-file__name`,o.target=`_blank`,o.rel=`noopener`;let s=document.createElement(`span`);s.className=`dw-file__size`,a.append(o,s),i.append(a);let c=null,l=null,u=``,d=e=>{let a=String(e.attrs.url??``),d=t?t.resolve(a):a;o.href=d,o.textContent=String(e.attrs.name??`file`),s.textContent=wF(Number(e.attrs.size??0)),!(e.attrs.view===`preview`&&jj(e.attrs.mime,e.attrs.name)&&a)||!n||!r?(l?.(),l=null,c?.remove(),c=null,u=``):u!==d&&(l?.(),c||(c=document.createElement(`div`),c.className=`dw-pdf`,c.tabIndex=0,c.setAttribute(`role`,`document`),i.append(c)),c.setAttribute(`aria-label`,String(e.attrs.name??`PDF`)),u=d,l=Mj(c,d,n,r))};return d(e),{dom:i,update:t=>t.type===e.type&&(d(t),!0),stopEvent:e=>!!c&&c.contains(e.target)&&e.type!==`mousedown`,ignoreMutation:()=>!0,destroy:()=>l?.()}}}}),EF=Tp.create({name:`fileDrop`,addOptions(){return{host:void 0,onError:void 0}},addProseMirrorPlugins(){let e=this.options.host;return e?[DF(()=>this.editor,e,this.options.onError)]:[]}});function DF(e,t,n){let r=(r,i)=>{let a=e();return!a||!r.length||!t.upload?!1:(SF(a,t,r,i).catch(n),!0)};return new E({key:new D(`docwellFileDrop`),props:{handlePaste(e,t){return r([...t.clipboardData?.files??[]])},handleDrop(e,t){let n=[...t.dataTransfer?.files??[]];if(!n.length)return!1;let i=e.posAtCoords({left:t.clientX,top:t.clientY});return t.preventDefault(),r(n,i?.pos)}}})}var OF=new D(`dwFind`),kF=``;function AF(e,t,n=!1){if(!t)return[];let r=n?t:t.toLowerCase(),i=[];return e.descendants((e,t)=>{if(!e.isTextblock)return!0;let a=``,o=[];e.forEach((e,n)=>{let r=t+1+n;if(e.isText){let t=e.text??``;for(let e=0;ee.from>=r);return a===-1&&(a=i.length?0:-1),{term:t,caseSensitive:n,matches:i,current:a}}function MF(e,t){return t&&e.setSelection(w.create(e.doc,t.from,t.to)).scrollIntoView(),e}var NF=Tp.create({name:`findReplace`,addCommands(){return{setFind:(e,t=!1)=>({state:n,tr:r,dispatch:i})=>{let a=jF(n.doc,e,t,n.selection.from);return r.setMeta(OF,{term:e,caseSensitive:t,near:n.selection.from}),i&&i(MF(r,a.matches[a.current])),!0},findStep:e=>({state:t,tr:n,dispatch:r})=>{let i=OF.getState(t);if(!i?.matches.length)return!1;let a=(i.current+e+i.matches.length)%i.matches.length;return n.setMeta(OF,{current:a}),r&&r(MF(n,i.matches[a])),!0},replaceCurrent:e=>({state:t,tr:n,dispatch:r})=>{let i=OF.getState(t),a=i?.matches[i.current];if(!i||!a)return!1;if(r){n.insertText(e,a.from,a.to),n.setMeta(OF,{term:i.term,caseSensitive:i.caseSensitive,near:a.from+e.length});let t=jF(n.doc,i.term,i.caseSensitive,a.from+e.length);r(MF(n,t.matches[t.current]))}return!0},replaceAll:e=>({state:t,tr:n,dispatch:r})=>{let i=OF.getState(t);if(!i?.matches.length)return!1;if(r){for(let t of[...i.matches].reverse())n.insertText(e,t.from,t.to);n.setMeta(OF,{term:i.term,caseSensitive:i.caseSensitive,near:0}),r(n)}return!0},clearFind:()=>({tr:e,dispatch:t})=>(t&&t(e.setMeta(OF,{clear:!0})),!0)}},addProseMirrorPlugins(){let e={term:``,caseSensitive:!1,matches:[],current:-1};return[new E({key:OF,state:{init:()=>e,apply(t,n,r,i){let a=t.getMeta(OF);if(a&&`clear`in a)return e;if(a&&`term`in a)return jF(i.doc,a.term,a.caseSensitive,a.near);if(a&&`current`in a)return{...n,current:a.current};if(!n.term||!t.docChanged)return n;let o=n.matches[n.current]?.from??0;return jF(i.doc,n.term,n.caseSensitive,t.mapping.map(o))}},props:{decorations(e){let t=OF.getState(e);return t?.matches.length?xs.create(e.doc,t.matches.map((e,n)=>vs.inline(e.from,e.to,{class:n===t.current?`dw-find dw-find-current`:`dw-find`}))):null}}})]}}),PF={slashMenu:`Insert block`,noMatches:`No matching blocks`,slash:{text:{label:`Text`,description:`Plain paragraph`},h1:{label:`Heading 1`,description:`Big section heading`},h2:{label:`Heading 2`,description:`Medium section heading`},h3:{label:`Heading 3`,description:`Small section heading`},otherHeadings:{label:`Other headings`,description:`Headings 4 to 6`},h4:{label:`Heading 4`,description:`A heading below level 3`},h5:{label:`Heading 5`,description:`A heading below level 4`},h6:{label:`Heading 6`,description:`The smallest heading`},bullet:{label:`Bulleted list`,description:`A simple list`},ordered:{label:`Numbered list`,description:`A list with numbers`},todo:{label:`To-do list`,description:`Tasks to tick off (or type [])`},callout:{label:`Callout`,description:`Set a note apart with an emoji and colour`},table:{label:`Table`,description:`Rows and columns`},quote:{label:`Quote`,description:`Set text apart as a quote`},code:{label:`Code block`,description:`Monospaced code`},divider:{label:`Divider`,description:`A line between sections`},image:{label:`Image`,description:`Upload a picture`},file:{label:`File`,description:`Attach a file to download`},math:{label:`Math block`,description:`A formula on its own line (LaTeX)`},mathInline:{label:`Inline math`,description:`A formula inside the text (LaTeX)`},mermaid:{label:`Mermaid diagram`,description:`Flowcharts and sequences from text`},drawio:{label:`Draw.io diagram`,description:`Draw a diagram with diagrams.net`},excalidraw:{label:`Excalidraw drawing`,description:`Sketch by hand`},toc:{label:`Table of contents`,description:`The page's headings, kept up to date`},pageLink:{label:`Link to page`,description:`Link another page (or type [[)`},toggle:{label:`Toggle`,description:`A heading that hides the blocks under it`},embed:{label:`Embed`,description:`A video, design or document from YouTube, Figma and more`},linkCard:{label:`Link card`,description:`A link with its page's title and picture`},newPage:{label:`New page`,description:`Make a page and link it here`},today:{label:`Today`,description:`Insert today's date`},tomorrow:{label:`Tomorrow`,description:`Insert tomorrow's date`},yesterday:{label:`Yesterday`,description:`Insert yesterday's date`},now:{label:`Now`,description:`Insert the date and time`}},format:{bold:`Bold`,italic:`Italic`,strike:`Strikethrough`,code:`Inline code`,link:`Link`,linkPrompt:`Link address (leave empty to remove the link)`,comment:`Comment`,underline:`Underline`,color:`Colour`,textColor:`Text colour`,highlight:`Highlight`,noColor:`Default`,align:`Align`,alignLeft:`Align left`,alignCenter:`Align centre`,alignRight:`Align right`,math:`Inline math`,linkedPage:`Make a linked page`},colors:{gray:`Grey`,red:`Red`,orange:`Orange`,yellow:`Yellow`,green:`Green`,teal:`Teal`,blue:`Blue`,purple:`Purple`,pink:`Pink`},table:{toolbar:`Table`,dragRow:`Drag to move the row`,dragColumn:`Drag to move the column`,moveRowUp:`Move row up`,moveRowDown:`Move row down`,moveColumnLeft:`Move column left`,moveColumnRight:`Move column right`,addRowBefore:`Add row above`,addRowAfter:`Add row below`,addColumnBefore:`Add column left`,addColumnAfter:`Add column right`,deleteRow:`Delete row`,deleteColumn:`Delete column`,toggleHeaderRow:`Header row`,mergeCells:`Merge cells`,splitCell:`Split cell`,deleteTable:`Delete table`},blockMenu:{open:`Drag to move, click for actions`,turnInto:`Turn into`,moveUp:`Move up`,moveDown:`Move down`,duplicate:`Duplicate`,copy:`Copy`,delete:`Delete`,showLineNumbers:`Show line numbers`,hideLineNumbers:`Hide line numbers`,showPages:`Show pages`,showAsFile:`Show as file`},mentions:`Mention someone`,noPeople:`Nobody found`,pageLinks:`Link to a page`,noPages:`No pages found`,blocks:{edit:`Edit`,done:`Done`,cancel:`Cancel`,save:`Save`,remove:`Remove`,saving:`Saving…`,latex:`LaTeX formula`,mermaid:`Mermaid diagram source`,mermaidError:`This diagram has an error:`,emptyDrawio:`Empty diagram. Click to draw.`,emptyExcalidraw:`Empty drawing. Click to sketch.`,loadFailed:`The editor could not be loaded.`,toc:`Contents`,tocEmpty:`Add headings to the page to fill the table of contents.`,expand:`Show contents`,collapse:`Hide contents`,embed:`Embedded content`,embedUrl:`Address of the video, design or document`,embedInvalid:`This address can't be embedded.`,linkUrl:`Address of the page to link`,copyBlockLink:`Copy link to this block`,calloutEmoji:`Change emoji`,calloutColor:`Change colour`,pdfLoading:`Loading PDF…`,pdfPage:`Page {n}`},find:{find:`Find in page`,replace:`Replace with`,previous:`Previous match`,next:`Next match`,replaceOne:`Replace`,replaceAll:`Replace all`,matchCase:`Match case`,close:`Close`,count:`{current} of {total}`,none:`No matches`},dates:{today:`Today`,tomorrow:`Tomorrow`,yesterday:`Yesterday`,nextWeek:`Next week`,remindWord:`remind`,remindMe:`Remind me`,reminderAt:`Reminder at 9:00 on the day`,someoneElse:`Someone else set a reminder on this date.`,edit:`Change date`,openJournal:`Open journal`}},I=class e extends Error{constructor(t,n){var r=`KaTeX parse error: `+t,i,a,o=n&&n.loc;if(o&&o.start<=o.end){var s=o.lexer.input;i=o.start,a=o.end,i===s.length?r+=` at end of input: `:r+=` at position `+(i+1)+`: `;var c=s.slice(i,a).replace(/[^]/g,`$&̲`),l=i>15?`…`+s.slice(i-15,i):s.slice(0,i),u=a+15e.replace(FF,`-$1`).toLowerCase(),LF={"&":`&`,">":`>`,"<":`<`,'"':`"`,"'":`'`},RF=/[&><"']/g,zF=e=>String(e).replace(RF,e=>LF[e]),BF=e=>e.type===`ordgroup`||e.type===`color`?e.body.length===1?BF(e.body[0]):e:e.type===`font`?BF(e.body):e,VF=new Set([`mathord`,`textord`,`atom`]),HF=e=>VF.has(BF(e).type),UF=e=>{var t=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(e);return t?t[2]!==`:`||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(t[1])?null:t[1].toLowerCase():`_relative`},WF={displayMode:{type:`boolean`,description:`Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.`,cli:`-d, --display-mode`},output:{type:{enum:[`htmlAndMathml`,`html`,`mathml`]},description:`Determines the markup language of the output.`,cli:`-F, --format `},leqno:{type:`boolean`,description:`Render display math in leqno style (left-justified tags).`},fleqn:{type:`boolean`,description:`Render display math flush left.`},throwOnError:{type:`boolean`,default:!0,cli:`-t, --no-throw-on-error`,cliDescription:`Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error.`},errorColor:{type:`string`,default:`#cc0000`,cli:`-c, --error-color `,cliDescription:`A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.`,cliProcessor:e=>`#`+e},macros:{type:`object`,cli:`-m, --macro `,cliDescription:`Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).`,cliDefault:[],cliProcessor:(e,t)=>(t.push(e),t)},minRuleThickness:{type:`number`,description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:e=>Math.max(0,e),cli:`--min-rule-thickness `,cliProcessor:parseFloat},colorIsTextColor:{type:`boolean`,description:`Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.`,cli:`-b, --color-is-text-color`},strict:{type:[{enum:[`warn`,`ignore`,`error`]},`boolean`,`function`],description:`Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.`,cli:`-S, --strict`,cliDefault:!1},trust:{type:[`boolean`,`function`],description:`Trust the input, enabling all HTML features such as \\url.`,cli:`-T, --trust`},maxSize:{type:`number`,default:1/0,description:`If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large`,processor:e=>Math.max(0,e),cli:`-s, --max-size `,cliProcessor:parseInt},maxExpand:{type:`number`,default:1e3,description:`Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.`,processor:e=>Math.max(0,e),cli:`-e, --max-expand `,cliProcessor:e=>e===`Infinity`?1/0:parseInt(e)},globalGroup:{type:`boolean`,cli:!1}};function GF(e){if(typeof e!=`string`)return e.enum[0];switch(e){case`boolean`:return!1;case`string`:return``;case`number`:return 0;case`object`:return{};default:throw Error(`Unexpected schema type; settings must declare an explicit default.`)}}function KF(e){return Object.prototype.hasOwnProperty.call(e,`default`)&&e.default!==void 0?e.default:GF(Array.isArray(e.type)?e.type[0]:e.type)}function qF(e,t,n,r){var i=Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0,a=Object.prototype.hasOwnProperty.call(r,`processor`)?r.processor:void 0;e[t]=i===void 0?KF(r):a?a(i):i}var JF=class{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e||={};for(var t of Object.keys(WF)){var n=WF[t];n&&qF(this,t,e,n)}}reportNonstrict(e,t,n){var r=this.strict;if(typeof r==`function`&&(r=r(e,t,n)),r&&r!==`ignore`){if(r===!0||r===`error`)throw new I(`LaTeX-incompatible input and strict mode is set to 'error': `+(t+` [`+e+`]`),n);r===`warn`?typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to 'warn': `+(t+` [`+e+`]`)):typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to `+(`unrecognized '`+r+`': `+t+` [`+e+`]`))}}useStrictBehavior(e,t,n){var r=this.strict;if(typeof r==`function`)try{r=r(e,t,n)}catch{r=`error`}return!r||r===`ignore`?!1:r===!0||r===`error`?!0:r===`warn`?(typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to 'warn': `+(t+` [`+e+`]`)),!1):(typeof console<`u`&&console.warn(`LaTeX-incompatible input and strict mode is set to `+(`unrecognized '`+r+`': `+t+` [`+e+`]`)),!1)}isTrusted(e){if(`url`in e&&e.url&&!e.protocol){var t=UF(e.url);if(t==null)return!1;e.protocol=t}return!!(typeof this.trust==`function`?this.trust(e):this.trust)}},YF=class{constructor(e,t,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=t,this.cramped=n}sup(){return iI[aI[this.id]]}sub(){return iI[oI[this.id]]}fracNum(){return iI[sI[this.id]]}fracDen(){return iI[cI[this.id]]}cramp(){return iI[lI[this.id]]}text(){return iI[uI[this.id]]}isTight(){return this.size>=2}},XF=0,ZF=1,QF=2,$F=3,eI=4,tI=5,nI=6,rI=7,iI=[new YF(XF,0,!1),new YF(ZF,0,!0),new YF(QF,1,!1),new YF($F,1,!0),new YF(eI,2,!1),new YF(tI,2,!0),new YF(nI,3,!1),new YF(rI,3,!0)],aI=[eI,tI,eI,tI,nI,rI,nI,rI],oI=[tI,tI,tI,tI,rI,rI,rI,rI],sI=[QF,$F,eI,tI,nI,rI,nI,rI],cI=[$F,$F,tI,tI,rI,rI,rI,rI],lI=[ZF,ZF,$F,$F,tI,tI,rI,rI],uI=[XF,ZF,QF,$F,QF,$F,QF,$F],L={DISPLAY:iI[XF],TEXT:iI[QF],SCRIPT:iI[eI],SCRIPTSCRIPT:iI[nI]},dI=[{name:`latin`,blocks:[[256,591],[768,879]]},{name:`cyrillic`,blocks:[[1024,1279]]},{name:`armenian`,blocks:[[1328,1423]]},{name:`brahmic`,blocks:[[2304,4255]]},{name:`georgian`,blocks:[[4256,4351]]},{name:`cjk`,blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:`hangul`,blocks:[[44032,55215]]}];function fI(e){for(var t=0;t=i[0]&&e<=i[1])return n.name}return null}var pI=[];dI.forEach(e=>e.blocks.forEach(e=>pI.push(...e)));function mI(e){for(var t=0;t=pI[t]&&e<=pI[t+1])return!0;return!1}var hI=e=>e+` `+e,gI=80,_I=function(e,t){return`M95,`+(622+e+t)+` 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;ce.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=RegExp(s?`${u}${c}.*?(?=\\s${d}|$)`:`${u}(?:^)?${c}[^\\s${d}]*`,`gm`),p=o.nodeBefore?.isText&&o.nodeBefore.text;if(!p)return null;let m=o.pos-p.length,h=Array.from(p.matchAll(f)).pop();if(!h||h.input===void 0||h.index===void 0)return null;let g=h.input.slice(Math.max(0,h.index-1),h.index),_=RegExp(`^[${i?.map(kf).join(``)}\0]?$`).test(g);if(i!==null&&!_)return null;let v=m+h.index,y=v+h[0].length;return s&&l.test(p.slice(y-1,y+1))&&(h[0]+=` `,y+=1),v=o.pos?{range:{from:v,to:y},query:h[0].slice(t.length),text:h[0]}:null}function JV(e){return e.docChanged?e.steps.some(e=>{let t=e.slice;if(!t?.content)return!1;let n=t.content.textBetween(0,t.content.size,` `);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)){(yf.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({placement:s,offset:c,flip:u,floatingUi:d});function y(e,t){switch(e){case`started`:var n;r==null||(n=r.onStart)==null||n.call(r,t);break;case`updated`:var i;r==null||(i=r.onUpdate)==null||i.call(r,t);break;case`stopped`:var a;r==null||(a=r.onExit)==null||a.call(r,t)}}return{update:async(n,d)=>{let b=t.getState(d),x=t.getState(n.state);if(!b||!x)return;let S=null,ee=b.query!==x.query,te=b.text!==x.text,ne=b.range.from!==x.range.from||b.range.to!==x.range.to,re=ee||te||ne;if(!b.active&&x.active)S=`started`;else if(b.active&&!x.active)S=`stopped`;else if(x.active&&re)S=`updated`;else return;let ie=S===`stopped`?b:x,ae=n.dom.querySelector(`[data-decoration-id="${ie.decorationId}"]`),oe=m(n,ae),se=i===0||(ie.query?ie.query.length>=i:!1),ce=(S===`started`||S===`updated`)&&se;if(g={editor:e,range:ie.range,query:ie.query||``,text:ie.text||``,items:o??[],command:t=>p({editor:e,range:ie.range,props:t}),decorationNode:ae,clientRect:oe,loading:ce,placement:s,offset:{mainAxis:c.mainAxis??4,crossAxis:c.crossAxis??0},container:l,flip:u,floatingUi:v,mount:iH({getReferenceRect:oe,contextElement:n.dom,config:v,container:l,dismissOnOutsideClick:f,dismiss:()=>h(e.view)})},S===`started`){var le;r==null||(le=r.onBeforeStart)==null||le.call(r,g)}if(S===`updated`){var ue;r==null||(ue=r.onBeforeUpdate)==null||ue.call(r,g)}if(S===`started`&&y(S,g),S===`started`||S===`updated`){if(!ce)_.abort(),g={...g,items:o??[],loading:!1};else{g={...g,items:o??[],loading:!0},S=`updated`,y(S,g);let e=await _.fetch(ie.query||``,a);if(e.status===`aborted`)return;if(!t.getState(n.state)?.active){_.abort();return}g=e.status===`resolved`?{...g,items:e.items,loading:!1}:{...g,loading:!1}}}S===`stopped`?(_.abort(),y(S,g),g=void 0):S===`updated`&&y(S,g)},destroy:()=>{var e;_.abort(),g&&(r==null||(e=r.onExit)==null||e.call(r,g))}}}var oH=new D(`suggestion`);function sH({pluginKey:e=oH,editor:t,char:n=`@`,allowSpaces:r=!1,allowToIncludeChar:i=!1,allowedPrefixes:a=[` `],startOfLine:o=!1,decorationTag:s=`span`,decorationClass:c=`suggestion`,decorationContent:l=``,decorationEmptyClass:u=`is-empty`,command:d=()=>null,items:f=()=>[],minQueryLength:p=0,debounce:m=0,initialItems:h,placement:g=`bottom-start`,offset:_={},container:v,flip:y=!0,floatingUi:b,dismissOnOutsideClick:x=!0,render:S=()=>({}),allow:ee=()=>!0,findSuggestionMatch:te=qV,shouldShow:ne,shouldResetDismissed:re}){let ie=S?.(),ae=r&&!i,oe=(n,r)=>XV(t,n,r,e);function se(e){return ZV({...e,editor:t,shouldResetDismissed:re,effectiveAllowSpaces:ae})}let ce=t=>QV({view:t,pluginKeyRef:e});return new E({key:e,view:()=>aH({editor:t,pluginKey:e,items:f,renderer:ie,minQueryLength:p,debounce:m,initialItems:h,placement:g,offset:_,container:v,flip:y,floatingUi:b,dismissOnOutsideClick:x,command:d,clientRectFor:oe,dispatchExit:ce}),state:eH({editor:t,char:n,effectiveAllowSpaces:ae,allowToIncludeChar:i,allowedPrefixes:a,startOfLine:o,findSuggestionMatch:te,allow:ee,shouldShow:ne,shouldKeepDismissed:se,pluginKey:e}),props:$V({pluginKey:e,decorationTag:s,decorationClass:c,decorationContent:l,decorationEmptyClass:u,renderer:ie,dispatchExit:ce})})}var cH=sH;function lH({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new D,command:({editor:e,range:t,props:i})=>{var a,o;let s=e.view.state.selection.$to.nodeAfter;s!=null&&(a=s.text)!=null&&a.startsWith(` `)&&(t.to+=1),e.chain().focus().insertContentAt(t,[{type:n,attrs:{...i,mentionSuggestionChar:r}},{type:`text`,text:` `}]).run(),(o=e.view.dom.ownerDocument.defaultView)==null||(o=o.getSelection())==null||o.collapseToEnd()},allow:({state:e,range:t})=>{let r=e.doc.resolve(t.from),i=e.schema.nodes[n];return!!r.parent.type.contentMatch.matchType(i)},...t}}function uH(e){return(e.options.suggestions.length?e.options.suggestions:[e.options.suggestion]).map(t=>lH({editor:e.editor,overrideSuggestionOptions:t,extensionName:e.name,char:t.char}))}function dH(e,t){let n=uH(e);return n.find(e=>e.char===t)||(n.length?n[0]:null)}var fH=Jp.create({name:`mention`,priority:101,addOptions(){return{HTMLAttributes:{},renderText({node:e,suggestion:t}){return`${t?.char??`@`}${e.attrs.label??e.attrs.id}`},deleteTriggerWithBackspace:!1,renderHTML({options:e,node:t,suggestion:n}){return[`span`,A(this.HTMLAttributes,e.HTMLAttributes),`${n?.char??`@`}${t.attrs.label??t.attrs.id}`]},suggestions:[],suggestion:{}}},group:`inline`,inline:!0,selectable:!1,atom:!0,addAttributes(){return{id:{default:null,parseHTML:e=>e.getAttribute(`data-id`),renderHTML:e=>e.id?{"data-id":e.id}:{}},label:{default:null,parseHTML:e=>e.getAttribute(`data-label`),renderHTML:e=>e.label?{"data-label":e.label}:{}},mentionSuggestionChar:{default:`@`,parseHTML:e=>e.getAttribute(`data-mention-suggestion-char`),renderHTML:e=>({"data-mention-suggestion-char":e.mentionSuggestionChar})}}},parseHTML(){return[{tag:`span[data-type="${this.name}"]`}]},renderHTML({node:e,HTMLAttributes:t}){let n=dH(this,e.attrs.mentionSuggestionChar);if(this.options.renderLabel!==void 0)return console.warn(`renderLabel is deprecated use renderText and renderHTML instead`),[`span`,A({"data-type":this.name},this.options.HTMLAttributes,t),this.options.renderLabel({options:this.options,node:e,suggestion:n})];let r={...this.options};r.HTMLAttributes=A({"data-type":this.name},this.options.HTMLAttributes,t);let i=this.options.renderHTML({options:r,node:e,suggestion:n});return typeof i==`string`?[`span`,A({"data-type":this.name},this.options.HTMLAttributes,t),i]:i},...$f({nodeName:`mention`,name:`@`,selfClosing:!0,allowedAttributes:[`id`,`label`,{name:`mentionSuggestionChar`,skipIfDefault:`@`}],parseAttributes:e=>{let t={},n=/(?:^|\s)(\w+)=(?:"([^"]*)"|'([^']*)')/g,r=n.exec(e);for(;r!==null;){let[,i,a,o]=r;t[i===`char`?`mentionSuggestionChar`:i]=a??o,r=n.exec(e)}return t},serializeAttributes:e=>Object.entries(e).filter(([,e])=>e!=null).map(([e,t])=>`${e===`mentionSuggestionChar`?`char`:e}="${t}"`).join(` `)}),renderText({node:e}){let t={options:this.options,node:e,suggestion:dH(this,e.attrs.mentionSuggestionChar)};return this.options.renderLabel===void 0?this.options.renderText(t):(console.warn(`renderLabel is deprecated use renderText and renderHTML instead`),this.options.renderLabel(t))},addKeyboardShortcuts(){return{Backspace:()=>this.editor.commands.command(({tr:e,state:t})=>{let n=!1,{selection:r}=t,{empty:i,anchor:a}=r;if(!i)return!1;let o=new le,s=0;return t.doc.nodesBetween(a-1,a,(e,t)=>{if(e.type.name===this.name)return n=!0,o=e,s=t,!1}),n&&e.insertText(this.options.deleteTriggerWithBackspace?``:o.attrs.mentionSuggestionChar,s,s+o.nodeSize),n})}},addProseMirrorPlugins(){return uH(this).map(sH)}});function pH(e,t){return fH.configure({HTMLAttributes:{class:`dw-mention`},renderText:({node:e})=>`@${e.attrs.label??e.attrs.id}`,suggestion:{char:`@`,allow:()=>!!t,findSuggestionMatch:t=>{let n=qV({...t,allowSpaces:!0});return n&&KP(n.query,e)?n:qV({...t,allowSpaces:!1})},items:async({query:n})=>{if(!t)return[];let r=GP(n,e,!!t.me).map(e=>({date:e})),i=(await t.search(n).catch(()=>[])).map(e=>({person:e}));return n.trim()?[...r,...i].slice(0,8):[...i.slice(0,6),...r]},render:Ij({label:e.mentions,empty:e.noPeople,toItem:t=>`person`in t?{label:t.person.label,description:t.person.hint,icon:`at`}:{label:UP(t.date.date,e),description:t.date.remind?`${e.dates.remindMe} · ${WP(t.date.date,e)}`:WP(t.date.date,e),icon:t.date.remind?`bell`:`calendar`},pick:(e,n)=>{`person`in n?e.command({id:n.person.id,label:n.person.label}):YP(e.editor,e.range,n.date,t?.me)}})}})}var mH=`flowchart LR - 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`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().focus().deleteRange(r).run(),hF(t,e,a,n)}),o(`linkCard`,`link`,[`bookmark`,`preview`,`card`,`url`,`web`],(t,r)=>{t.chain().focus().deleteRange(r).run(),gF(t,e,a,n)})],c=e=>{let t=new Date;return zP(new Date(t.getFullYear(),t.getMonth(),t.getDate()+e))};if(s.push(o(`today`,`calendar`,[`date`,`day`],(e,t)=>YP(e,t,{date:c(0),remind:!1})),o(`tomorrow`,`calendar`,[`date`,`day`],(e,t)=>YP(e,t,{date:c(1),remind:!1})),o(`yesterday`,`calendar`,[`date`,`day`],(e,t)=>YP(e,t,{date:c(-1),remind:!1})),o(`now`,`clock`,[`time`,`date`,`timestamp`],(t,n)=>{YP(t,n,{date:c(0),remind:!1});let r=new Intl.DateTimeFormat(e.locale,{hour:`numeric`,minute:`2-digit`}).format(new Date);t.chain().focus().insertContent(`${r} `).run()})),r&&(s.push(o(`pageLink`,`link`,[`page`,`link`,`[[`,`wiki`],(e,t)=>e.chain().focus().deleteRange(t).insertContent(`[[`).run())),r.create&&s.push(o(`newPage`,`page-plus`,[`page`,`doc`,`subpage`,`create`],(e,t)=>{e.chain().focus().deleteRange(t).run(),wH(e,r,``).catch(n)}))),t?.upload){let e=e=>(r,i)=>{r.chain().focus().deleteRange(i).run(),EH(e).then(e=>SF(r,t,e).catch(n))};s.push(o(`image`,`image`,[`picture`,`photo`,`img`],e(`image/*`)),o(`file`,`paperclip`,[`attachment`,`upload`,`pdf`],e(``)),o(`drawio`,`diagram`,[`diagram`,`diagrams.net`,`draw`,`chart`,`uml`],(e,t)=>e.chain().focus().deleteRange(t).insertDiagram(`drawio`).run())),i&&s.push(o(`excalidraw`,`pencil`,[`drawing`,`sketch`,`whiteboard`,`draw`],(e,t)=>e.chain().focus().deleteRange(t).insertDiagram(`excalidraw`).run()))}return s}function OH(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e=>e.label.toLowerCase().includes(n)||e.id.startsWith(n)||e.keywords.some(e=>e.toLowerCase().startsWith(n));return e.flatMap(e=>{let t=e.children?.filter(r)??[];return t.length?t:r(e)?[e]:[]})}var kH=Tp.create({name:`slashMenu`,addOptions(){return{commands:[],labels:void 0}},addProseMirrorPlugins(){return[cH({editor:this.editor,pluginKey:new D(`slashMenu`),char:`/`,allowSpaces:!1,startOfLine:!1,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:({query:e})=>OH(this.options.commands,e),render:Ij({label:this.options.labels.slashMenu,empty:this.options.labels.noMatches,showQuery:!0,toItem:e=>({label:e.label,description:e.description,icon:e.icon}),children:e=>e.children,pick:(e,t)=>t.run(e.editor,e.range)})})]}});function AH(e,t){let n=!0,r=e.firstChild?.childCount??0;return e.forEach(e=>{t===`column`&&e.childCount!==r&&(n=!1),e.forEach(e=>{((t===`row`?e.attrs.rowspan:e.attrs.colspan)??1)>1&&(n=!1)})}),n}function jH(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}var MH=e=>{let t=[];return e.forEach(e=>t.push(e)),t};function NH(e,t,n,r,i,a=0){let o=e.doc.nodeAt(t);if(!o||o.type.name!==`table`||!AH(o,n))return null;let c=MH(o),l=n===`row`?c.length:c[0]?.childCount??0;if(r===i||r<0||i<0||r>=l||i>=l)return null;let u=n===`row`?jH(c,r,i):c.map(e=>e.copy(s.fromArray(jH(MH(e),r,i)))),d=e.tr.replaceWith(t,t+o.nodeSize,o.copy(s.fromArray(u))),[f,p]=n===`row`?[i,0]:[Math.min(a,u.length-1),i],m=t+1;for(let e=0;e0;e--)if(n.node(e).type.name===`table`)return{tablePos:n.before(e),row:n.index(e),column:e+1<=n.depth?n.index(e+1):0};return null}var FH=Tp.create({name:`tableMove`,addOptions(){return{labels:null}},addCommands(){let e=e=>t=>({state:n,dispatch:r})=>{let i=PH(n,n.selection.from);if(!i)return!1;let a=e===`row`?i.row:i.column,o=NH(n,i.tablePos,e,a,a+t,i.row);return o?(r?.(o),!0):!1};return{moveTableRow:e(`row`),moveTableColumn:e(`column`)}},addKeyboardShortcuts(){return{"Mod-Alt-ArrowUp":()=>this.editor.commands.moveTableRow(-1),"Mod-Alt-ArrowDown":()=>this.editor.commands.moveTableRow(1),"Mod-Alt-ArrowLeft":()=>this.editor.commands.moveTableColumn(-1),"Mod-Alt-ArrowRight":()=>this.editor.commands.moveTableColumn(1)}},addProseMirrorPlugins(){let e=this.options.labels?.table;return[new E({key:new D(`tableMove`),view:t=>new IH(t,{row:e?.dragRow??`Drag to move the row`,column:e?.dragColumn??`Drag to move the column`})})]}}),IH=class{view;grips={row:document.createElement(`button`),column:document.createElement(`button`)};line=document.createElement(`div`);cell=null;drag=null;constructor(e,t){this.view=e;for(let e of[`row`,`column`]){let n=this.grips[e];n.type=`button`,n.className=`dw-table-grip dw-table-grip--${e}`,n.contentEditable=`false`,n.setAttribute(`aria-label`,t[e]),n.title=t[e],n.hidden=!0,n.tabIndex=-1,n.addEventListener(`pointerdown`,t=>this.start(t,e)),n.addEventListener(`mouseleave`,this.leave)}this.line.className=`dw-table-drop`,this.line.hidden=!0,e.dom.addEventListener(`mousemove`,this.move),e.dom.addEventListener(`mouseleave`,this.leave)}get host(){let e=this.view.dom.parentElement;return e&&this.line.parentElement!==e&&(e.classList.add(`dw-block-host`),e.append(this.grips.row,this.grips.column,this.line)),e}hide=()=>{this.drag||(this.grips.row.hidden=!0,this.grips.column.hidden=!0,this.cell=null)};leave=e=>{let t=e.relatedTarget;t&&(this.grips.row.contains(t)||this.grips.column.contains(t)||this.view.dom.contains(t))||this.hide()};move=e=>{if(this.drag)return;let t=e.target?.closest?.(`td, th`),n=this.host;if(!this.view.editable||!n||!(t instanceof HTMLTableCellElement)||!this.view.dom.contains(t))return this.hide();let r=this.locate(t),i=r&&this.view.state.doc.nodeAt(r.tablePos);if(!r||!i)return this.hide();this.cell=t;let a=n.getBoundingClientRect(),o=t.closest(`table`).getBoundingClientRect(),s=t.parentElement.getBoundingClientRect(),c=t.getBoundingClientRect(),l=i.childCount>1&&AH(i,`row`),u=(i.firstChild?.childCount??0)>1&&AH(i,`column`);Object.assign(this.grips.row.style,{top:`${s.top-a.top+s.height/2-11}px`,left:`${o.left-a.left-7}px`}),Object.assign(this.grips.column.style,{top:`${o.top-a.top-7}px`,left:`${c.left-a.left+c.width/2-11}px`}),this.grips.row.hidden=!l,this.grips.column.hidden=!u};locate(e){try{return PH(this.view.state,this.view.posAtDOM(e,0))}catch{return null}}start(e,t){let n=this.cell;if(!n||e.button!==0)return;let r=this.locate(n),i=n.parentElement?.parentElement;if(!r||!i)return;e.preventDefault();let a=this.grips[t];a.setPointerCapture(e.pointerId);let o=[...i.children].filter(e=>e instanceof HTMLTableRowElement),s=t===`row`?r.row:r.column,c=t===`row`?o:[...o[0]?.children??[]],l=t===`row`?[o[s]]:o.map(e=>e.children[s]).filter(Boolean);for(let e of l)e.classList.add(`dw-table-dragging`);this.drag={axis:t,tablePos:r.tablePos,from:s,slots:c,dimmed:l,to:s,cursorRow:r.row},a.addEventListener(`pointermove`,this.dragMove),a.addEventListener(`pointerup`,this.drop),a.addEventListener(`pointercancel`,this.cancel)}dragMove=e=>{let t=this.drag,n=this.host;if(!t||!n)return;let r=t.axis===`row`,i=r?e.clientY:e.clientX,a=t.slots.length;for(let[e,n]of t.slots.entries()){let t=n.getBoundingClientRect();if(i<(r?t.top+t.height/2:t.left+t.width/2)){a=e;break}}t.to=a>t.from?a-1:a;let o=n.getBoundingClientRect(),s=t.slots[0].closest(`table`).getBoundingClientRect(),c=t.slots.at(-1).getBoundingClientRect(),l=t.slots[a]?.getBoundingClientRect(),u=r?l?.top??c.bottom:l?.left??c.right;Object.assign(this.line.style,r?{top:`${u-o.top-1}px`,left:`${s.left-o.left}px`,width:`${s.width}px`,height:`2px`}:{top:`${s.top-o.top}px`,left:`${u-o.left-1}px`,width:`2px`,height:`${s.height}px`}),this.line.hidden=t.to===t.from};drop=()=>{let e=this.drag;if(this.cancel(),!e||e.to===e.from)return;let t=NH(this.view.state,e.tablePos,e.axis,e.from,e.to,e.cursorRow);t&&this.view.dispatch(t),this.view.focus()};cancel=()=>{let e=this.drag;for(let t of e?.dimmed??[])t.classList.remove(`dw-table-dragging`);this.drag=null,this.line.hidden=!0;for(let e of Object.values(this.grips))e.removeEventListener(`pointermove`,this.dragMove),e.removeEventListener(`pointerup`,this.drop),e.removeEventListener(`pointercancel`,this.cancel);this.hide()};update(){this.cell&&!this.cell.isConnected&&this.hide()}destroy(){this.cancel();for(let e of Object.values(this.grips))e.remove();this.line.remove(),this.view.dom.removeEventListener(`mousemove`,this.move),this.view.dom.removeEventListener(`mouseleave`,this.leave)}};function LH(e){let t=[];return e.descendants((e,n)=>e.type.name!==`heading`||(t.push({level:Number(e.attrs.level)||1,text:e.textContent.trim(),pos:n}),!1)),t}function RH(e,t){let n=e.view.nodeDOM(t);n instanceof HTMLElement&&n.scrollIntoView({behavior:`smooth`,block:`start`}),e.isEditable&&e.commands.setTextSelection(t+1)}var zH=Jp.create({name:`tableOfContents`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},parseHTML(){return[{tag:`nav[data-type='toc']`}]},renderHTML(){return[`nav`,{"data-type":`toc`}]},addCommands(){return{insertTableOfContents:()=>({commands:e})=>e.insertContent({type:this.name})}},addNodeView(){return({editor:e})=>{let t=this.options.labels.blocks,n=document.createElement(`nav`);n.className=`dw-toc`,n.setAttribute(`data-type`,`toc`),n.setAttribute(`aria-label`,t.toc),n.contentEditable=`false`;let r=document.createElement(`p`);r.className=`dw-toc__title`,r.textContent=t.toc;let i=document.createElement(`ol`);i.className=`dw-toc__list`,n.append(r,i);let a=``,o=()=>{let n=LH(e.state.doc),r=JSON.stringify(n.map(e=>[e.level,e.text]));if(r===a){i.querySelectorAll(`a`).forEach((e,t)=>e.dataset.pos=String(n[t]?.pos??0));return}if(a=r,i.replaceChildren(),!n.length){let e=document.createElement(`li`);e.className=`dw-toc__empty`,e.textContent=t.tocEmpty,i.append(e);return}let o=Math.min(...n.map(e=>e.level));for(let t of n){let n=document.createElement(`li`);n.style.paddingLeft=`${(t.level-o)*1}rem`;let r=document.createElement(`a`);r.href=`#`,r.textContent=t.text||`…`,r.dataset.pos=String(t.pos),r.addEventListener(`click`,t=>{t.preventDefault(),RH(e,Number(r.dataset.pos))}),n.append(r),i.append(n)}};return o(),e.on(`update`,o),{dom:n,update:e=>e.type.name===`tableOfContents`,ignoreMutation:()=>!0,stopEvent:e=>e.target instanceof Element&&!!e.target.closest(`a`),destroy:()=>e.off(`update`,o)}}}}),BH=(e,t)=>{let n=t.view.domAtPos(e).node,r=n.nodeType===Node.ELEMENT_NODE?n:n.parentElement;return r?r.offsetParent!==null:!1},VH=(e,t,n)=>{for(let r=e.depth;r>0;--r){let i=e.node(r),a=t(i),o=BH(e.start(r),n);if(a&&o)return{pos:r>0?e.before(r):0,start:e.start(r),depth:r,node:i}}},HH=(e,t)=>{let{state:n,view:r,extensionManager:i}=e,{schema:a,selection:o}=n,{empty:s,$anchor:c}=o,l=!!i.extensions.find(e=>e.name===`gapCursor`);if(!s||c.parent.type!==a.nodes.detailsSummary||!l||t===`right`&&c.parentOffset!==c.parent.nodeSize-2)return!1;let u=yu(e=>e.type===a.nodes.details)(o);if(!u)return!1;let d=gu(u.node,e=>e.type===a.nodes.detailsContent);if(!d.length||BH(u.start+d[0].pos+1,e))return!1;let f=n.doc.resolve(u.pos+u.node.nodeSize),p=Nw.findFrom(f,1,!1);if(!p)return!1;let{tr:m}=n,h=new Nw(p);return m.setSelection(h),m.scrollIntoView(),r.dispatch(m),!0},UH=Jp.create({name:`details`,content:`detailsSummary detailsContent`,group:`block`,defining:!0,isolating:!0,allowGapCursor:!1,addOptions(){return{persist:!1,openClassName:`is-open`,HTMLAttributes:{},renderToggleButton:({element:e,isOpen:t})=>{e.setAttribute(`aria-label`,t?`Collapse details content`:`Expand details content`)}}},addAttributes(){return this.options.persist?{open:{default:!1,parseHTML:e=>e.hasAttribute(`open`),renderHTML:({open:e})=>e?{open:``}:{}}}:[]},parseHTML(){return[{tag:`details`}]},renderHTML({HTMLAttributes:e}){return[`details`,A(this.options.HTMLAttributes,e),0]},...Xf({nodeName:`details`,content:`block`}),addNodeView(){return({editor:e,getPos:t,node:n,HTMLAttributes:r})=>{let i=document.createElement(`div`),a=A(this.options.HTMLAttributes,r,{"data-type":this.name});Object.entries(a).forEach(([e,t])=>i.setAttribute(e,t));let o=document.createElement(`button`);o.type=`button`;let s=e=>{this.options.renderToggleButton({element:o,...e})};i.append(o);let c=document.createElement(`div`);i.append(c);let l=e=>{let{setToValue:t,node:r=n}=e||{};if(t!==void 0){if(t){if(i.classList.contains(this.options.openClassName))return;i.classList.add(this.options.openClassName)}else{if(!i.classList.contains(this.options.openClassName))return;i.classList.remove(this.options.openClassName)}}else i.classList.toggle(this.options.openClassName);let a=i.classList.contains(this.options.openClassName);s({isOpen:a,node:r});let o=new Event(`toggleDetailsContent`);c.querySelector(`:scope > div[data-type="detailsContent"]`)?.dispatchEvent(o)};return s({isOpen:!!n.attrs.open,node:n}),n.attrs.open&&setTimeout(()=>l()),o.addEventListener(`click`,()=>{if(l(),!this.options.persist)e.commands.focus(void 0,{scrollIntoView:!1});else if(e.isEditable&&typeof t==`function`){let{from:n,to:r}=e.state.selection;e.chain().command(({tr:e})=>{let n=t();if(typeof n!=`number`)return!1;let r=e.doc.nodeAt(n);return r?.type===this.type&&(e.setNodeMarkup(n,void 0,{open:!r.attrs.open}),!0)}).setTextSelection({from:n,to:r}).focus(void 0,{scrollIntoView:!1}).run()}}),{dom:i,contentDOM:c,ignoreMutation(e){if(e.type===`selection`)return!1;let t=e.target,n=i.contains(t);return o.contains(t)||!n||i===t},update:e=>e.type===this.type&&(e.attrs.open===void 0?s({isOpen:i.classList.contains(this.options.openClassName),node:e}):l({setToValue:e.attrs.open,node:e}),!0)}}},addCommands(){return{setDetails:()=>({state:e,chain:t})=>{let{schema:n,selection:r}=e,{$from:i,$to:a}=r,o=i.blockRange(a);if(!o)return!1;let s=e.doc.slice(o.start,o.end);if(!n.nodes.detailsContent.contentMatch.matchFragment(s.content))return!1;let c=s.toJSON()?.content||[];return t().insertContentAt({from:o.start,to:o.end},{type:this.name,content:[{type:`detailsSummary`},{type:`detailsContent`,content:c}]}).setTextSelection(o.start+2).run()},unsetDetails:()=>({state:e,chain:t})=>{let{selection:n,schema:r}=e,i=yu(e=>e.type===this.type)(n);if(!i)return!1;let a=gu(i.node,e=>e.type===r.nodes.detailsSummary),o=gu(i.node,e=>e.type===r.nodes.detailsContent);if(!a.length||!o.length)return!1;let s=a[0],c=o[0],l=i.pos,u=e.doc.resolve(l),d={from:l,to:l+i.node.nodeSize},f=c.node.content.toJSON()||[],p=[u.parent.type.contentMatch.defaultType?.create(null,s.node.content).toJSON(),...f];return t().insertContentAt(d,p).setTextSelection(l+1).run()}}},addKeyboardShortcuts(){return{Backspace:()=>{let{schema:e,selection:t}=this.editor.state,{empty:n,$anchor:r}=t;return!n||r.parent.type!==e.nodes.detailsSummary?!1:r.parentOffset===0?this.editor.commands.unsetDetails():this.editor.commands.command(({tr:e})=>{let t=r.pos-1,n=r.pos;return e.delete(t,n),!0})},Enter:({editor:e})=>{let{state:t,view:n}=e,{schema:r,selection:i}=t,{$head:a}=i;if(a.parent.type!==r.nodes.detailsSummary)return!1;let o=BH(a.after()+1,e),s=o?t.doc.nodeAt(a.after()):a.node(-2);if(!s)return!1;let c=o?0:a.indexAfter(-1),l=Ll(s.contentMatchAt(c));if(!l||!s.canReplaceWith(c,c,l))return!1;let u=l.createAndFill();if(!u)return!1;let d=o?a.after()+1:a.after(-1),f=t.tr.replaceWith(d,d,u),p=f.doc.resolve(d),m=C.near(p,1);return f.setSelection(m),f.scrollIntoView(),n.dispatch(f),!0},ArrowRight:({editor:e})=>HH(e,`right`),ArrowDown:({editor:e})=>HH(e,`down`)}},addProseMirrorPlugins(){return[new E({key:new D(`detailsSelection`),appendTransaction:(e,t,n)=>{let{editor:r,type:i}=this;if(r.view.composing||!e.some(e=>e.selectionSet)||!t.selection.empty||!n.selection.empty||!sd(n,i.name))return;let{$from:a}=n.selection;if(BH(a.pos,r))return;let o=VH(a,e=>e.type===i,r);if(!o)return;let s=gu(o.node,e=>e.type===n.schema.nodes.detailsSummary);if(!s.length)return;let c=s[0],l=(t.selection.from{let t=document.createElement(`div`),n=A(this.options.HTMLAttributes,e,{"data-type":this.name,hidden:`hidden`});return Object.entries(n).forEach(([e,n])=>t.setAttribute(e,n)),t.addEventListener(`toggleDetailsContent`,()=>{t.toggleAttribute(`hidden`)}),{dom:t,contentDOM:t,ignoreMutation(e){return e.type===`selection`?!1:!t.contains(e.target)||t===e.target},update:e=>e.type===this.type}}},addKeyboardShortcuts(){return{Enter:({editor:e})=>{let{state:t,view:n}=e,{selection:r}=t,{$from:i,empty:a}=r,o=yu(e=>e.type===this.type)(r);if(!a||!o||!o.node.childCount)return!1;let s=i.index(o.depth),{childCount:c}=o.node;if(c!==s+1)return!1;let l=o.node.type.contentMatch.defaultType?.createAndFill();if(!l)return!1;let u=t.doc.resolve(o.pos+1),d=c-1,f=o.node.child(d),p=u.posAtIndex(d,o.depth);if(!f.eq(l))return!1;let m=i.node(-3);if(!m)return!1;let h=i.indexAfter(-3),g=Ll(m.contentMatchAt(h));if(!g||!m.canReplaceWith(h,h,g))return!1;let _=g.createAndFill();if(!_)return!1;let{tr:v}=t,y=i.after(-2);v.replaceWith(y,y,_);let b=v.doc.resolve(y),x=C.near(b,1);v.setSelection(x);let S=p,ee=p+f.nodeSize;return v.delete(S,ee),v.scrollIntoView(),n.dispatch(v),!0}}},...Xf({nodeName:`detailsContent`})}),GH=Jp.create({name:`detailsSummary`,content:`text*`,defining:!0,selectable:!1,isolating:!0,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`summary`}]},renderHTML({HTMLAttributes:e}){return[`summary`,A(this.options.HTMLAttributes,e),0]},...Xf({nodeName:`detailsSummary`,content:`inline`})});function KH(e){return[UH.configure({persist:!1,HTMLAttributes:{class:`dw-toggle`},renderToggleButton:({element:t,isOpen:n})=>{t.setAttribute(`aria-label`,n?e.blocks.collapse:e.blocks.expand),t.setAttribute(`aria-expanded`,String(n))}}),GH,WH]}function qH(e={}){let t=e.labels??PF,n=null,r=Tp.create({name:`editorRef`,onCreate(){n=this.editor}}),i={host:e.files,labels:t,drawioUrl:e.drawioUrl,loadExcalidraw:e.loadExcalidraw,onError:e.onError},a=[r,Hk.configure({heading:{levels:[1,2,3,4,5,6]},codeBlock:!1,link:{openOnClick:!1,autolink:!0},undoRedo:!e.collab&&void 0}),lT.configure({placeholder:e.placeholder??`Type '/' for commands…`}),CF.configure({host:e.files}),TF.configure({host:e.files,loadPdf:e.loadPdf,labels:t}),Aj.configure({lineNumbers:e.codeLineNumbers??!1}),SP,xP,OP,kP,...yP(),...bP(),FH.configure({labels:t}),MP.configure({labels:t}),EF.configure({host:e.files,onError:e.onError}),pH(t,e.mentions),qP.configure({labels:t,me:()=>e.mentions?.me}),kH.configure({commands:DH(t,e.files,e.onError,e.pages,!!e.loadExcalidraw,e.links),labels:t}),LP.configure({onSelect:e.onCommentSelect}),KV(t,()=>n),yH.configure({labels:t,load:e.loadMermaid}),zH.configure({labels:t}),oF.configure(i),sF.configure(i),TH.configure({host:e.pages,labels:t,onNavigate:e.onNavigate}),...KH(t),vF.configure({labels:t}),yF.configure({labels:t}),Jj.configure({labels:t,link:e.blockLink,onCopied:e.onBlockLinkCopied}),NF];return e.collab&&a.push(Tw.configure({document:e.collab.provider.doc}),Aw.configure({provider:e.collab.provider,user:e.collab.user,render:JH})),a}function JH(e){let t=typeof e.color==`string`&&/^#[0-9a-f]{3,8}$/i.test(e.color)?e.color:`#888`,n=document.createElement(`span`);n.classList.add(`collaboration-carets__caret`),n.style.borderColor=t;let r=document.createElement(`div`);return r.classList.add(`collaboration-carets__label`),r.setAttribute(`aria-hidden`,`true`),r.style.backgroundColor=t,r.textContent=typeof e.name==`string`?e.name:``,n.append(r),n}var YH=3e4,XH=class extends um{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Mh();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&ZH(this,t,`timeout`)},dm(YH/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Mh()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),Qh(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},ZH=(e,t,n)=>{let r=[];for(let n=0;n0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},QH=(e,t,n=e.states)=>{let r=t.length,i=Mm();j(i,r);for(let a=0;a{let r=fh(t),i=Mh(),a=[],o=[],s=[],c=[],l=M(r);for(let t=0;t0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},eU=(e,t)=>{j(e,0),Wm(e,Gv(t))},tU=(e,t,n)=>{j(e,1),Wm(e,zv(t,n))},nU=(e,t,n)=>tU(t,n,hh(e)),rU=(e,t,n,r)=>{try{Iv(t,hh(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},iU=(e,t)=>{j(e,2),Wm(e,t)},aU=rU,oU=(e,t,n,r,i)=>{let a=M(e);switch(a){case 0:nU(e,t,n);break;case 1:rU(e,n,r,i);break;case 2:aU(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},sU=0,cU=1,lU=4401,uU=4404,dU=4409,fU=class{opts;doc=new bv;awareness=new XH(this.doc);status=`connecting`;synced=!1;ws=null;retries=0;retryTimer;destroyed=!1;listeners=new Set;constructor(e){this.opts=e,this.doc.on(`update`,this.onDocUpdate),this.awareness.on(`update`,this.onAwarenessUpdate),window.addEventListener(`beforeunload`,this.onUnload),this.connect()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.destroyed||(this.destroyed=!0,this.listeners.clear(),clearTimeout(this.retryTimer),window.removeEventListener(`beforeunload`,this.onUnload),ZH(this.awareness,[this.doc.clientID],`local`),this.doc.off(`update`,this.onDocUpdate),this.awareness.off(`update`,this.onAwarenessUpdate),this.ws?.close(),this.awareness.destroy(),this.doc.destroy(),this.listeners.clear())}set(e,t=this.synced){(e!==this.status||t!==this.synced)&&(this.status=e,this.synced=t,this.listeners.forEach(e=>e()))}connect(){let e=new WebSocket(`${this.opts.url}?page=${encodeURIComponent(this.opts.page)}`);e.binaryType=`arraybuffer`,this.ws=e,e.onopen=()=>{e.send(this.opts.token()??``);let t=Mm();j(t,sU),eU(t,this.doc),e.send(Fm(t)),this.awareness.getLocalState()!==null&&this.sendAwareness([this.doc.clientID])},e.onmessage=e=>this.onMessage(new Uint8Array(e.data)),e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=[...this.awareness.getStates().keys()].filter(e=>e!==this.doc.clientID);ZH(this.awareness,n,this),this.destroyed||(t.code===lU||t.code===uU?this.set(`denied`,!1):t.code===dU?this.set(`changed`):(this.set(`offline`),this.retryTimer=setTimeout(()=>this.connect(),Math.min(1e3*2**this.retries++,3e4))))}}onMessage(e){let t=fh(e),n=M(t);if(n===sU){let e=Mm();j(e,sU);let n=oU(t,e,this.doc,this);Pm(e)>1&&this.ws?.send(Fm(e)),n===1&&(this.retries=0,this.set(`connected`,!0))}else n===cU&&$H(this.awareness,hh(t),this)}onDocUpdate=(e,t)=>{if(t===this||this.ws?.readyState!==WebSocket.OPEN)return;let n=Mm();j(n,sU),iU(n,e),this.ws.send(Fm(n))};onAwarenessUpdate=({added:e,updated:t,removed:n},r)=>{r!==this&&this.sendAwareness([...e,...t,...n])};sendAwareness(e){if(this.ws?.readyState!==WebSocket.OPEN)return;let t=Mm();j(t,cU),Wm(t,QH(this.awareness,e)),this.ws.send(Fm(t))}onUnload=()=>ZH(this.awareness,[this.doc.clientID],`unload`)},pU={bold:e=>e.chain().focus().toggleBold().run(),italic:e=>e.chain().focus().toggleItalic().run(),strike:e=>e.chain().focus().toggleStrike().run(),code:e=>e.chain().focus().toggleCode().run(),heading1:e=>e.chain().focus().toggleHeading({level:1}).run(),heading2:e=>e.chain().focus().toggleHeading({level:2}).run(),heading3:e=>e.chain().focus().toggleHeading({level:3}).run(),bulletList:e=>e.chain().focus().toggleBulletList().run(),orderedList:e=>e.chain().focus().toggleOrderedList().run(),blockquote:e=>e.chain().focus().toggleBlockquote().run(),codeBlock:e=>e.chain().focus().toggleCodeBlock().run(),underline:e=>e.chain().focus().toggleUnderline().run(),taskList:e=>e.chain().focus().toggleTaskList().run(),callout:e=>e.isActive(`callout`)?e.chain().focus().unsetCallout().run():e.chain().focus().setCallout().run(),table:e=>e.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run(),undo:e=>e.chain().focus().undo().run(),redo:e=>e.chain().focus().redo().run()},mU=[[`bold`,e=>e.isActive(`bold`)],[`italic`,e=>e.isActive(`italic`)],[`strike`,e=>e.isActive(`strike`)],[`code`,e=>e.isActive(`code`)],[`heading1`,e=>e.isActive(`heading`,{level:1})],[`heading2`,e=>e.isActive(`heading`,{level:2})],[`heading3`,e=>e.isActive(`heading`,{level:3})],[`bulletList`,e=>e.isActive(`bulletList`)],[`orderedList`,e=>e.isActive(`orderedList`)],[`blockquote`,e=>e.isActive(`blockquote`)],[`codeBlock`,e=>e.isActive(`codeBlock`)],[`underline`,e=>e.isActive(`underline`)],[`taskList`,e=>e.isActive(`taskList`)],[`callout`,e=>e.isActive(`callout`)],[`table`,e=>e.isActive(`table`)]],hU=class{el;send;editor;provider=null;lastState=``;editable=!0;constructor(e,t){this.el=e,this.send=t,this.editor=this.create({}),t({type:`ready`,version:2})}receive(e){try{let t=typeof e==`string`?JSON.parse(e):e;this.handle(t)}catch(e){this.send({type:`error`,message:e instanceof Error?e.message:String(e)})}}get content(){return this.editor.getJSON()}destroy(){this.editor.destroy(),this.provider?.destroy()}handle(e){switch(e.type){case`hello`:this.send({type:`ready`,version:2}),this.lastState=``,this.reportState(this.editor);return;case`setContent`:this.editor.commands.setContent(e.content??``,{emitUpdate:!1}),this.reportState(this.editor);return;case`setEditable`:this.editable=e.editable,this.editor.setEditable(e.editable);return;case`setTheme`:document.documentElement.classList.toggle(`dark`,e.dark);return;case`setLayout`:{let t=document.documentElement.classList;t.toggle(`dw-full-width`,e.fullWidth),t.toggle(`dw-font-serif`,e.font===`serif`),t.toggle(`dw-font-mono`,e.font===`mono`);return}case`command`:{let t=pU[e.command];if(!t)throw Error(`unknown command ${e.command}`);t(this.editor);return}case`focus`:this.editor.commands.focus();return;case`blur`:this.editor.commands.blur();return;case`connect`:this.connect(e);return;default:throw Error(`unknown message ${e.type}`)}}connect(e){this.provider?.destroy();let t=new fU({url:e.url,page:e.page,token:()=>e.token});t.onChange(()=>this.send({type:`collab`,status:t.status})),this.provider=t,this.editor.destroy(),this.editor=this.create({collab:{provider:t,user:e.user}})}create(e){return this.el.replaceChildren(),new Vp({element:this.el,editable:this.editable,extensions:qH({...e,onNavigate:e=>this.send({type:`navigate`,path:e})}),editorProps:{attributes:{class:`dw-prose`}},onUpdate:({editor:e})=>this.send({type:`change`,content:e.getJSON()}),onSelectionUpdate:({editor:e})=>this.reportState(e),onTransaction:({editor:e})=>this.reportState(e),onFocus:({editor:e})=>this.reportState(e),onBlur:({editor:e})=>this.reportState(e)})}reportState(e){let t={active:mU.filter(([,t])=>t(e)).map(([e])=>e),canUndo:e.can().undo(),canRedo:e.can().redo(),focused:e.isFocused},n=JSON.stringify(t);n!==this.lastState&&(this.lastState=n,this.send({type:`state`,state:t}))}};function gU(e){let t=JSON.stringify(e);window.DocwellNative?window.DocwellNative.postMessage(t):(window.parent.postMessage(t,`*`),console.debug(`[docwell bridge]`,e))}var _U=new hU(document.getElementById(`editor`),gU);window.docwell={receive:e=>_U.receive(e)}; + 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`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().focus().deleteRange(r).run(),hF(t,e,a,n)}),o(`linkCard`,`link`,[`bookmark`,`preview`,`card`,`url`,`web`],(t,r)=>{t.chain().focus().deleteRange(r).run(),gF(t,e,a,n)})],c=e=>{let t=new Date;return zP(new Date(t.getFullYear(),t.getMonth(),t.getDate()+e))};if(s.push(o(`today`,`calendar`,[`date`,`day`],(e,t)=>YP(e,t,{date:c(0),remind:!1})),o(`tomorrow`,`calendar`,[`date`,`day`],(e,t)=>YP(e,t,{date:c(1),remind:!1})),o(`yesterday`,`calendar`,[`date`,`day`],(e,t)=>YP(e,t,{date:c(-1),remind:!1})),o(`now`,`clock`,[`time`,`date`,`timestamp`],(t,n)=>{YP(t,n,{date:c(0),remind:!1});let r=new Intl.DateTimeFormat(e.locale,{hour:`numeric`,minute:`2-digit`}).format(new Date);t.chain().focus().insertContent(`${r} `).run()})),r&&(s.push(o(`pageLink`,`link`,[`page`,`link`,`[[`,`wiki`],(e,t)=>e.chain().focus().deleteRange(t).insertContent(`[[`).run())),r.create&&s.push(o(`newPage`,`page-plus`,[`page`,`doc`,`subpage`,`create`],(e,t)=>{e.chain().focus().deleteRange(t).run(),wH(e,r,``).catch(n)}))),t?.upload){let e=e=>(r,i)=>{r.chain().focus().deleteRange(i).run(),EH(e).then(e=>SF(r,t,e).catch(n))};s.push(o(`image`,`image`,[`picture`,`photo`,`img`],e(`image/*`)),o(`file`,`paperclip`,[`attachment`,`upload`,`pdf`],e(``)),o(`drawio`,`diagram`,[`diagram`,`diagrams.net`,`draw`,`chart`,`uml`],(e,t)=>e.chain().focus().deleteRange(t).insertDiagram(`drawio`).run())),i&&s.push(o(`excalidraw`,`pencil`,[`drawing`,`sketch`,`whiteboard`,`draw`],(e,t)=>e.chain().focus().deleteRange(t).insertDiagram(`excalidraw`).run()))}return s}function OH(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e=>e.label.toLowerCase().includes(n)||e.id.startsWith(n)||e.keywords.some(e=>e.toLowerCase().startsWith(n));return e.flatMap(e=>{let t=e.children?.filter(r)??[];return t.length?t:r(e)?[e]:[]})}var kH=Tp.create({name:`slashMenu`,addOptions(){return{commands:[],labels:void 0}},addProseMirrorPlugins(){return[cH({editor:this.editor,pluginKey:new D(`slashMenu`),char:`/`,allowSpaces:!1,startOfLine:!1,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:({query:e})=>OH(this.options.commands,e),render:Ij({label:this.options.labels.slashMenu,empty:this.options.labels.noMatches,showQuery:!0,toItem:e=>({label:e.label,description:e.description,icon:e.icon}),children:e=>e.children,pick:(e,t)=>t.run(e.editor,e.range)})})]}});function AH(e,t){let n=!0,r=e.firstChild?.childCount??0;return e.forEach(e=>{t===`column`&&e.childCount!==r&&(n=!1),e.forEach(e=>{((t===`row`?e.attrs.rowspan:e.attrs.colspan)??1)>1&&(n=!1)})}),n}function jH(e,t,n){let r=[...e],[i]=r.splice(t,1);return r.splice(n,0,i),r}var MH=e=>{let t=[];return e.forEach(e=>t.push(e)),t};function NH(e,t,n,r,i,a=0){let o=e.doc.nodeAt(t);if(!o||o.type.name!==`table`||!AH(o,n))return null;let c=MH(o),l=n===`row`?c.length:c[0]?.childCount??0;if(r===i||r<0||i<0||r>=l||i>=l)return null;let u=n===`row`?jH(c,r,i):c.map(e=>e.copy(s.fromArray(jH(MH(e),r,i)))),d=e.tr.replaceWith(t,t+o.nodeSize,o.copy(s.fromArray(u))),[f,p]=n===`row`?[i,0]:[Math.min(a,u.length-1),i],m=t+1;for(let e=0;e0;e--)if(n.node(e).type.name===`table`)return{tablePos:n.before(e),row:n.index(e),column:e+1<=n.depth?n.index(e+1):0};return null}var FH=Tp.create({name:`tableMove`,addOptions(){return{labels:null}},addCommands(){let e=e=>t=>({state:n,dispatch:r})=>{let i=PH(n,n.selection.from);if(!i)return!1;let a=e===`row`?i.row:i.column,o=NH(n,i.tablePos,e,a,a+t,i.row);return o?(r?.(o),!0):!1};return{moveTableRow:e(`row`),moveTableColumn:e(`column`)}},addKeyboardShortcuts(){return{"Mod-Alt-ArrowUp":()=>this.editor.commands.moveTableRow(-1),"Mod-Alt-ArrowDown":()=>this.editor.commands.moveTableRow(1),"Mod-Alt-ArrowLeft":()=>this.editor.commands.moveTableColumn(-1),"Mod-Alt-ArrowRight":()=>this.editor.commands.moveTableColumn(1)}},addProseMirrorPlugins(){let e=this.options.labels?.table;return[new E({key:new D(`tableMove`),view:t=>new IH(t,{row:e?.dragRow??`Drag to move the row`,column:e?.dragColumn??`Drag to move the column`})})]}}),IH=class{view;grips={row:document.createElement(`button`),column:document.createElement(`button`)};line=document.createElement(`div`);cell=null;drag=null;constructor(e,t){this.view=e;for(let e of[`row`,`column`]){let n=this.grips[e];n.type=`button`,n.className=`dw-table-grip dw-table-grip--${e}`,n.contentEditable=`false`,n.setAttribute(`aria-label`,t[e]),n.title=t[e],n.hidden=!0,n.tabIndex=-1,n.addEventListener(`pointerdown`,t=>this.start(t,e)),n.addEventListener(`mouseleave`,this.leave)}this.line.className=`dw-table-drop`,this.line.hidden=!0,e.dom.addEventListener(`mousemove`,this.move),e.dom.addEventListener(`mouseleave`,this.leave)}get host(){let e=this.view.dom.parentElement;return e&&this.line.parentElement!==e&&(e.classList.add(`dw-block-host`),e.append(this.grips.row,this.grips.column,this.line)),e}hide=()=>{this.drag||(this.grips.row.hidden=!0,this.grips.column.hidden=!0,this.cell=null)};leave=e=>{let t=e.relatedTarget;t&&(this.grips.row.contains(t)||this.grips.column.contains(t)||this.view.dom.contains(t))||this.hide()};move=e=>{if(this.drag)return;let t=e.target?.closest?.(`td, th`),n=this.host;if(!this.view.editable||!n||!(t instanceof HTMLTableCellElement)||!this.view.dom.contains(t))return this.hide();let r=this.locate(t),i=r&&this.view.state.doc.nodeAt(r.tablePos);if(!r||!i)return this.hide();this.cell=t;let a=n.getBoundingClientRect(),o=t.closest(`table`).getBoundingClientRect(),s=t.parentElement.getBoundingClientRect(),c=t.getBoundingClientRect(),l=i.childCount>1&&AH(i,`row`),u=(i.firstChild?.childCount??0)>1&&AH(i,`column`);Object.assign(this.grips.row.style,{top:`${s.top-a.top+s.height/2-11}px`,left:`${o.left-a.left-7}px`}),Object.assign(this.grips.column.style,{top:`${o.top-a.top-7}px`,left:`${c.left-a.left+c.width/2-11}px`}),this.grips.row.hidden=!l,this.grips.column.hidden=!u};locate(e){try{return PH(this.view.state,this.view.posAtDOM(e,0))}catch{return null}}start(e,t){let n=this.cell;if(!n||e.button!==0)return;let r=this.locate(n),i=n.parentElement?.parentElement;if(!r||!i)return;e.preventDefault();let a=this.grips[t];a.setPointerCapture(e.pointerId);let o=[...i.children].filter(e=>e instanceof HTMLTableRowElement),s=t===`row`?r.row:r.column,c=t===`row`?o:[...o[0]?.children??[]],l=t===`row`?[o[s]]:o.map(e=>e.children[s]).filter(Boolean);for(let e of l)e.classList.add(`dw-table-dragging`);this.drag={axis:t,tablePos:r.tablePos,from:s,slots:c,dimmed:l,to:s,cursorRow:r.row},a.addEventListener(`pointermove`,this.dragMove),a.addEventListener(`pointerup`,this.drop),a.addEventListener(`pointercancel`,this.cancel)}dragMove=e=>{let t=this.drag,n=this.host;if(!t||!n)return;let r=t.axis===`row`,i=r?e.clientY:e.clientX,a=t.slots.length;for(let[e,n]of t.slots.entries()){let t=n.getBoundingClientRect();if(i<(r?t.top+t.height/2:t.left+t.width/2)){a=e;break}}t.to=a>t.from?a-1:a;let o=n.getBoundingClientRect(),s=t.slots[0].closest(`table`).getBoundingClientRect(),c=t.slots.at(-1).getBoundingClientRect(),l=t.slots[a]?.getBoundingClientRect(),u=r?l?.top??c.bottom:l?.left??c.right;Object.assign(this.line.style,r?{top:`${u-o.top-1}px`,left:`${s.left-o.left}px`,width:`${s.width}px`,height:`2px`}:{top:`${s.top-o.top}px`,left:`${u-o.left-1}px`,width:`2px`,height:`${s.height}px`}),this.line.hidden=t.to===t.from};drop=()=>{let e=this.drag;if(this.cancel(),!e||e.to===e.from)return;let t=NH(this.view.state,e.tablePos,e.axis,e.from,e.to,e.cursorRow);t&&this.view.dispatch(t),this.view.focus()};cancel=()=>{let e=this.drag;for(let t of e?.dimmed??[])t.classList.remove(`dw-table-dragging`);this.drag=null,this.line.hidden=!0;for(let e of Object.values(this.grips))e.removeEventListener(`pointermove`,this.dragMove),e.removeEventListener(`pointerup`,this.drop),e.removeEventListener(`pointercancel`,this.cancel);this.hide()};update(){this.cell&&!this.cell.isConnected&&this.hide()}destroy(){this.cancel();for(let e of Object.values(this.grips))e.remove();this.line.remove(),this.view.dom.removeEventListener(`mousemove`,this.move),this.view.dom.removeEventListener(`mouseleave`,this.leave)}};function LH(e){let t=[];return e.descendants((e,n)=>e.type.name!==`heading`||(t.push({level:Number(e.attrs.level)||1,text:e.textContent.trim(),pos:n}),!1)),t}function RH(e,t){let n=e.view.nodeDOM(t);n instanceof HTMLElement&&n.scrollIntoView({behavior:`smooth`,block:`start`}),e.isEditable&&e.commands.setTextSelection(t+1)}var zH=Jp.create({name:`tableOfContents`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},parseHTML(){return[{tag:`nav[data-type='toc']`}]},renderHTML(){return[`nav`,{"data-type":`toc`}]},addCommands(){return{insertTableOfContents:()=>({commands:e})=>e.insertContent({type:this.name})}},addNodeView(){return({editor:e})=>{let t=this.options.labels.blocks,n=document.createElement(`nav`);n.className=`dw-toc`,n.setAttribute(`data-type`,`toc`),n.setAttribute(`aria-label`,t.toc),n.contentEditable=`false`;let r=document.createElement(`p`);r.className=`dw-toc__title`,r.textContent=t.toc;let i=document.createElement(`ol`);i.className=`dw-toc__list`,n.append(r,i);let a=``,o=()=>{let n=LH(e.state.doc),r=JSON.stringify(n.map(e=>[e.level,e.text]));if(r===a){i.querySelectorAll(`a`).forEach((e,t)=>e.dataset.pos=String(n[t]?.pos??0));return}if(a=r,i.replaceChildren(),!n.length){let e=document.createElement(`li`);e.className=`dw-toc__empty`,e.textContent=t.tocEmpty,i.append(e);return}let o=Math.min(...n.map(e=>e.level));for(let t of n){let n=document.createElement(`li`);n.style.paddingLeft=`${(t.level-o)*1}rem`;let r=document.createElement(`a`);r.href=`#`,r.textContent=t.text||`…`,r.dataset.pos=String(t.pos),r.addEventListener(`click`,t=>{t.preventDefault(),RH(e,Number(r.dataset.pos))}),n.append(r),i.append(n)}};return o(),e.on(`update`,o),{dom:n,update:e=>e.type.name===`tableOfContents`,ignoreMutation:()=>!0,stopEvent:e=>e.target instanceof Element&&!!e.target.closest(`a`),destroy:()=>e.off(`update`,o)}}}}),BH=(e,t)=>{let n=t.view.domAtPos(e).node,r=n.nodeType===Node.ELEMENT_NODE?n:n.parentElement;return r?r.offsetParent!==null:!1},VH=(e,t,n)=>{for(let r=e.depth;r>0;--r){let i=e.node(r),a=t(i),o=BH(e.start(r),n);if(a&&o)return{pos:r>0?e.before(r):0,start:e.start(r),depth:r,node:i}}},HH=(e,t)=>{let{state:n,view:r,extensionManager:i}=e,{schema:a,selection:o}=n,{empty:s,$anchor:c}=o,l=!!i.extensions.find(e=>e.name===`gapCursor`);if(!s||c.parent.type!==a.nodes.detailsSummary||!l||t===`right`&&c.parentOffset!==c.parent.nodeSize-2)return!1;let u=yu(e=>e.type===a.nodes.details)(o);if(!u)return!1;let d=gu(u.node,e=>e.type===a.nodes.detailsContent);if(!d.length||BH(u.start+d[0].pos+1,e))return!1;let f=n.doc.resolve(u.pos+u.node.nodeSize),p=Nw.findFrom(f,1,!1);if(!p)return!1;let{tr:m}=n,h=new Nw(p);return m.setSelection(h),m.scrollIntoView(),r.dispatch(m),!0},UH=Jp.create({name:`details`,content:`detailsSummary detailsContent`,group:`block`,defining:!0,isolating:!0,allowGapCursor:!1,addOptions(){return{persist:!1,openClassName:`is-open`,HTMLAttributes:{},renderToggleButton:({element:e,isOpen:t})=>{e.setAttribute(`aria-label`,t?`Collapse details content`:`Expand details content`)}}},addAttributes(){return this.options.persist?{open:{default:!1,parseHTML:e=>e.hasAttribute(`open`),renderHTML:({open:e})=>e?{open:``}:{}}}:[]},parseHTML(){return[{tag:`details`}]},renderHTML({HTMLAttributes:e}){return[`details`,A(this.options.HTMLAttributes,e),0]},...Xf({nodeName:`details`,content:`block`}),addNodeView(){return({editor:e,getPos:t,node:n,HTMLAttributes:r})=>{let i=document.createElement(`div`),a=A(this.options.HTMLAttributes,r,{"data-type":this.name});Object.entries(a).forEach(([e,t])=>i.setAttribute(e,t));let o=document.createElement(`button`);o.type=`button`;let s=e=>{this.options.renderToggleButton({element:o,...e})};i.append(o);let c=document.createElement(`div`);i.append(c);let l=e=>{let{setToValue:t,node:r=n}=e||{};if(t!==void 0){if(t){if(i.classList.contains(this.options.openClassName))return;i.classList.add(this.options.openClassName)}else{if(!i.classList.contains(this.options.openClassName))return;i.classList.remove(this.options.openClassName)}}else i.classList.toggle(this.options.openClassName);let a=i.classList.contains(this.options.openClassName);s({isOpen:a,node:r});let o=new Event(`toggleDetailsContent`);c.querySelector(`:scope > div[data-type="detailsContent"]`)?.dispatchEvent(o)};return s({isOpen:!!n.attrs.open,node:n}),n.attrs.open&&setTimeout(()=>l()),o.addEventListener(`click`,()=>{if(l(),!this.options.persist)e.commands.focus(void 0,{scrollIntoView:!1});else if(e.isEditable&&typeof t==`function`){let{from:n,to:r}=e.state.selection;e.chain().command(({tr:e})=>{let n=t();if(typeof n!=`number`)return!1;let r=e.doc.nodeAt(n);return r?.type===this.type&&(e.setNodeMarkup(n,void 0,{open:!r.attrs.open}),!0)}).setTextSelection({from:n,to:r}).focus(void 0,{scrollIntoView:!1}).run()}}),{dom:i,contentDOM:c,ignoreMutation(e){if(e.type===`selection`)return!1;let t=e.target,n=i.contains(t);return o.contains(t)||!n||i===t},update:e=>e.type===this.type&&(e.attrs.open===void 0?s({isOpen:i.classList.contains(this.options.openClassName),node:e}):l({setToValue:e.attrs.open,node:e}),!0)}}},addCommands(){return{setDetails:()=>({state:e,chain:t})=>{let{schema:n,selection:r}=e,{$from:i,$to:a}=r,o=i.blockRange(a);if(!o)return!1;let s=e.doc.slice(o.start,o.end);if(!n.nodes.detailsContent.contentMatch.matchFragment(s.content))return!1;let c=s.toJSON()?.content||[];return t().insertContentAt({from:o.start,to:o.end},{type:this.name,content:[{type:`detailsSummary`},{type:`detailsContent`,content:c}]}).setTextSelection(o.start+2).run()},unsetDetails:()=>({state:e,chain:t})=>{let{selection:n,schema:r}=e,i=yu(e=>e.type===this.type)(n);if(!i)return!1;let a=gu(i.node,e=>e.type===r.nodes.detailsSummary),o=gu(i.node,e=>e.type===r.nodes.detailsContent);if(!a.length||!o.length)return!1;let s=a[0],c=o[0],l=i.pos,u=e.doc.resolve(l),d={from:l,to:l+i.node.nodeSize},f=c.node.content.toJSON()||[],p=[u.parent.type.contentMatch.defaultType?.create(null,s.node.content).toJSON(),...f];return t().insertContentAt(d,p).setTextSelection(l+1).run()}}},addKeyboardShortcuts(){return{Backspace:()=>{let{schema:e,selection:t}=this.editor.state,{empty:n,$anchor:r}=t;return!n||r.parent.type!==e.nodes.detailsSummary?!1:r.parentOffset===0?this.editor.commands.unsetDetails():this.editor.commands.command(({tr:e})=>{let t=r.pos-1,n=r.pos;return e.delete(t,n),!0})},Enter:({editor:e})=>{let{state:t,view:n}=e,{schema:r,selection:i}=t,{$head:a}=i;if(a.parent.type!==r.nodes.detailsSummary)return!1;let o=BH(a.after()+1,e),s=o?t.doc.nodeAt(a.after()):a.node(-2);if(!s)return!1;let c=o?0:a.indexAfter(-1),l=Ll(s.contentMatchAt(c));if(!l||!s.canReplaceWith(c,c,l))return!1;let u=l.createAndFill();if(!u)return!1;let d=o?a.after()+1:a.after(-1),f=t.tr.replaceWith(d,d,u),p=f.doc.resolve(d),m=C.near(p,1);return f.setSelection(m),f.scrollIntoView(),n.dispatch(f),!0},ArrowRight:({editor:e})=>HH(e,`right`),ArrowDown:({editor:e})=>HH(e,`down`)}},addProseMirrorPlugins(){return[new E({key:new D(`detailsSelection`),appendTransaction:(e,t,n)=>{let{editor:r,type:i}=this;if(r.view.composing||!e.some(e=>e.selectionSet)||!t.selection.empty||!n.selection.empty||!sd(n,i.name))return;let{$from:a}=n.selection;if(BH(a.pos,r))return;let o=VH(a,e=>e.type===i,r);if(!o)return;let s=gu(o.node,e=>e.type===n.schema.nodes.detailsSummary);if(!s.length)return;let c=s[0],l=(t.selection.from{let t=document.createElement(`div`),n=A(this.options.HTMLAttributes,e,{"data-type":this.name,hidden:`hidden`});return Object.entries(n).forEach(([e,n])=>t.setAttribute(e,n)),t.addEventListener(`toggleDetailsContent`,()=>{t.toggleAttribute(`hidden`)}),{dom:t,contentDOM:t,ignoreMutation(e){return e.type===`selection`?!1:!t.contains(e.target)||t===e.target},update:e=>e.type===this.type}}},addKeyboardShortcuts(){return{Enter:({editor:e})=>{let{state:t,view:n}=e,{selection:r}=t,{$from:i,empty:a}=r,o=yu(e=>e.type===this.type)(r);if(!a||!o||!o.node.childCount)return!1;let s=i.index(o.depth),{childCount:c}=o.node;if(c!==s+1)return!1;let l=o.node.type.contentMatch.defaultType?.createAndFill();if(!l)return!1;let u=t.doc.resolve(o.pos+1),d=c-1,f=o.node.child(d),p=u.posAtIndex(d,o.depth);if(!f.eq(l))return!1;let m=i.node(-3);if(!m)return!1;let h=i.indexAfter(-3),g=Ll(m.contentMatchAt(h));if(!g||!m.canReplaceWith(h,h,g))return!1;let _=g.createAndFill();if(!_)return!1;let{tr:v}=t,y=i.after(-2);v.replaceWith(y,y,_);let b=v.doc.resolve(y),x=C.near(b,1);v.setSelection(x);let S=p,ee=p+f.nodeSize;return v.delete(S,ee),v.scrollIntoView(),n.dispatch(v),!0}}},...Xf({nodeName:`detailsContent`})}),GH=Jp.create({name:`detailsSummary`,content:`text*`,defining:!0,selectable:!1,isolating:!0,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`summary`}]},renderHTML({HTMLAttributes:e}){return[`summary`,A(this.options.HTMLAttributes,e),0]},...Xf({nodeName:`detailsSummary`,content:`inline`})});function KH(e){return[UH.configure({persist:!1,HTMLAttributes:{class:`dw-toggle`},renderToggleButton:({element:t,isOpen:n})=>{t.setAttribute(`aria-label`,n?e.blocks.collapse:e.blocks.expand),t.setAttribute(`aria-expanded`,String(n))}}),GH,WH]}function qH(e={}){let t=e.labels??PF,n=null,r=Tp.create({name:`editorRef`,onCreate(){n=this.editor}}),i={host:e.files,labels:t,drawioUrl:e.drawioUrl,loadExcalidraw:e.loadExcalidraw,onError:e.onError},a=[r,Hk.configure({heading:{levels:[1,2,3,4,5,6]},codeBlock:!1,link:{openOnClick:!1,autolink:!0},undoRedo:!e.collab&&void 0}),lT.configure({placeholder:e.placeholder??`Type '/' for commands…`}),CF.configure({host:e.files}),TF.configure({host:e.files,loadPdf:e.loadPdf,labels:t}),Aj.configure({lineNumbers:e.codeLineNumbers??!1}),SP,xP,OP,kP,...yP(),...bP(),FH.configure({labels:t}),MP.configure({labels:t}),EF.configure({host:e.files,onError:e.onError}),pH(t,e.mentions),qP.configure({labels:t,me:()=>e.mentions?.me,onOpen:e.onOpenDate}),kH.configure({commands:DH(t,e.files,e.onError,e.pages,!!e.loadExcalidraw,e.links),labels:t}),LP.configure({onSelect:e.onCommentSelect}),KV(t,()=>n),yH.configure({labels:t,load:e.loadMermaid}),zH.configure({labels:t}),oF.configure(i),sF.configure(i),TH.configure({host:e.pages,labels:t,onNavigate:e.onNavigate}),...KH(t),vF.configure({labels:t}),yF.configure({labels:t}),Jj.configure({labels:t,link:e.blockLink,onCopied:e.onBlockLinkCopied}),NF];return e.collab&&a.push(Tw.configure({document:e.collab.provider.doc}),Aw.configure({provider:e.collab.provider,user:e.collab.user,render:JH})),a}function JH(e){let t=typeof e.color==`string`&&/^#[0-9a-f]{3,8}$/i.test(e.color)?e.color:`#888`,n=document.createElement(`span`);n.classList.add(`collaboration-carets__caret`),n.style.borderColor=t;let r=document.createElement(`div`);return r.classList.add(`collaboration-carets__label`),r.setAttribute(`aria-hidden`,`true`),r.style.backgroundColor=t,r.textContent=typeof e.name==`string`?e.name:``,n.append(r),n}var YH=3e4,XH=class extends um{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Mh();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&ZH(this,t,`timeout`)},dm(YH/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Mh()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),Qh(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},ZH=(e,t,n)=>{let r=[];for(let n=0;n0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},QH=(e,t,n=e.states)=>{let r=t.length,i=Mm();j(i,r);for(let a=0;a{let r=fh(t),i=Mh(),a=[],o=[],s=[],c=[],l=M(r);for(let t=0;t0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},eU=(e,t)=>{j(e,0),Wm(e,Gv(t))},tU=(e,t,n)=>{j(e,1),Wm(e,zv(t,n))},nU=(e,t,n)=>tU(t,n,hh(e)),rU=(e,t,n,r)=>{try{Iv(t,hh(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},iU=(e,t)=>{j(e,2),Wm(e,t)},aU=rU,oU=(e,t,n,r,i)=>{let a=M(e);switch(a){case 0:nU(e,t,n);break;case 1:rU(e,n,r,i);break;case 2:aU(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},sU=0,cU=1,lU=4401,uU=4404,dU=4409,fU=class{opts;doc=new bv;awareness=new XH(this.doc);status=`connecting`;synced=!1;ws=null;retries=0;retryTimer;destroyed=!1;listeners=new Set;constructor(e){this.opts=e,this.doc.on(`update`,this.onDocUpdate),this.awareness.on(`update`,this.onAwarenessUpdate),window.addEventListener(`beforeunload`,this.onUnload),this.connect()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}destroy(){this.destroyed||(this.destroyed=!0,this.listeners.clear(),clearTimeout(this.retryTimer),window.removeEventListener(`beforeunload`,this.onUnload),ZH(this.awareness,[this.doc.clientID],`local`),this.doc.off(`update`,this.onDocUpdate),this.awareness.off(`update`,this.onAwarenessUpdate),this.ws?.close(),this.awareness.destroy(),this.doc.destroy(),this.listeners.clear())}set(e,t=this.synced){(e!==this.status||t!==this.synced)&&(this.status=e,this.synced=t,this.listeners.forEach(e=>e()))}connect(){let e=new WebSocket(`${this.opts.url}?page=${encodeURIComponent(this.opts.page)}`);e.binaryType=`arraybuffer`,this.ws=e,e.onopen=()=>{e.send(this.opts.token()??``);let t=Mm();j(t,sU),eU(t,this.doc),e.send(Fm(t)),this.awareness.getLocalState()!==null&&this.sendAwareness([this.doc.clientID])},e.onmessage=e=>this.onMessage(new Uint8Array(e.data)),e.onclose=t=>{if(this.ws!==e)return;this.ws=null;let n=[...this.awareness.getStates().keys()].filter(e=>e!==this.doc.clientID);ZH(this.awareness,n,this),this.destroyed||(t.code===lU||t.code===uU?this.set(`denied`,!1):t.code===dU?this.set(`changed`):(this.set(`offline`),this.retryTimer=setTimeout(()=>this.connect(),Math.min(1e3*2**this.retries++,3e4))))}}onMessage(e){let t=fh(e),n=M(t);if(n===sU){let e=Mm();j(e,sU);let n=oU(t,e,this.doc,this);Pm(e)>1&&this.ws?.send(Fm(e)),n===1&&(this.retries=0,this.set(`connected`,!0))}else n===cU&&$H(this.awareness,hh(t),this)}onDocUpdate=(e,t)=>{if(t===this||this.ws?.readyState!==WebSocket.OPEN)return;let n=Mm();j(n,sU),iU(n,e),this.ws.send(Fm(n))};onAwarenessUpdate=({added:e,updated:t,removed:n},r)=>{r!==this&&this.sendAwareness([...e,...t,...n])};sendAwareness(e){if(this.ws?.readyState!==WebSocket.OPEN)return;let t=Mm();j(t,cU),Wm(t,QH(this.awareness,e)),this.ws.send(Fm(t))}onUnload=()=>ZH(this.awareness,[this.doc.clientID],`unload`)},pU={bold:e=>e.chain().focus().toggleBold().run(),italic:e=>e.chain().focus().toggleItalic().run(),strike:e=>e.chain().focus().toggleStrike().run(),code:e=>e.chain().focus().toggleCode().run(),heading1:e=>e.chain().focus().toggleHeading({level:1}).run(),heading2:e=>e.chain().focus().toggleHeading({level:2}).run(),heading3:e=>e.chain().focus().toggleHeading({level:3}).run(),bulletList:e=>e.chain().focus().toggleBulletList().run(),orderedList:e=>e.chain().focus().toggleOrderedList().run(),blockquote:e=>e.chain().focus().toggleBlockquote().run(),codeBlock:e=>e.chain().focus().toggleCodeBlock().run(),underline:e=>e.chain().focus().toggleUnderline().run(),taskList:e=>e.chain().focus().toggleTaskList().run(),callout:e=>e.isActive(`callout`)?e.chain().focus().unsetCallout().run():e.chain().focus().setCallout().run(),table:e=>e.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run(),undo:e=>e.chain().focus().undo().run(),redo:e=>e.chain().focus().redo().run()},mU=[[`bold`,e=>e.isActive(`bold`)],[`italic`,e=>e.isActive(`italic`)],[`strike`,e=>e.isActive(`strike`)],[`code`,e=>e.isActive(`code`)],[`heading1`,e=>e.isActive(`heading`,{level:1})],[`heading2`,e=>e.isActive(`heading`,{level:2})],[`heading3`,e=>e.isActive(`heading`,{level:3})],[`bulletList`,e=>e.isActive(`bulletList`)],[`orderedList`,e=>e.isActive(`orderedList`)],[`blockquote`,e=>e.isActive(`blockquote`)],[`codeBlock`,e=>e.isActive(`codeBlock`)],[`underline`,e=>e.isActive(`underline`)],[`taskList`,e=>e.isActive(`taskList`)],[`callout`,e=>e.isActive(`callout`)],[`table`,e=>e.isActive(`table`)]],hU=class{el;send;editor;provider=null;lastState=``;editable=!0;constructor(e,t){this.el=e,this.send=t,this.editor=this.create({}),t({type:`ready`,version:2})}receive(e){try{let t=typeof e==`string`?JSON.parse(e):e;this.handle(t)}catch(e){this.send({type:`error`,message:e instanceof Error?e.message:String(e)})}}get content(){return this.editor.getJSON()}destroy(){this.editor.destroy(),this.provider?.destroy()}handle(e){switch(e.type){case`hello`:this.send({type:`ready`,version:2}),this.lastState=``,this.reportState(this.editor);return;case`setContent`:this.editor.commands.setContent(e.content??``,{emitUpdate:!1}),this.reportState(this.editor);return;case`setEditable`:this.editable=e.editable,this.editor.setEditable(e.editable);return;case`setTheme`:document.documentElement.classList.toggle(`dark`,e.dark);return;case`setLayout`:{let t=document.documentElement.classList;t.toggle(`dw-full-width`,e.fullWidth),t.toggle(`dw-font-serif`,e.font===`serif`),t.toggle(`dw-font-mono`,e.font===`mono`);return}case`command`:{let t=pU[e.command];if(!t)throw Error(`unknown command ${e.command}`);t(this.editor);return}case`focus`:this.editor.commands.focus();return;case`blur`:this.editor.commands.blur();return;case`connect`:this.connect(e);return;default:throw Error(`unknown message ${e.type}`)}}connect(e){this.provider?.destroy();let t=new fU({url:e.url,page:e.page,token:()=>e.token});t.onChange(()=>this.send({type:`collab`,status:t.status})),this.provider=t,this.editor.destroy(),this.editor=this.create({collab:{provider:t,user:e.user}})}create(e){return this.el.replaceChildren(),new Vp({element:this.el,editable:this.editable,extensions:qH({...e,onNavigate:e=>this.send({type:`navigate`,path:e})}),editorProps:{attributes:{class:`dw-prose`}},onUpdate:({editor:e})=>this.send({type:`change`,content:e.getJSON()}),onSelectionUpdate:({editor:e})=>this.reportState(e),onTransaction:({editor:e})=>this.reportState(e),onFocus:({editor:e})=>this.reportState(e),onBlur:({editor:e})=>this.reportState(e)})}reportState(e){let t={active:mU.filter(([,t])=>t(e)).map(([e])=>e),canUndo:e.can().undo(),canRedo:e.can().redo(),focused:e.isFocused},n=JSON.stringify(t);n!==this.lastState&&(this.lastState=n,this.send({type:`state`,state:t}))}};function gU(e){let t=JSON.stringify(e);window.DocwellNative?window.DocwellNative.postMessage(t):(window.parent.postMessage(t,`*`),console.debug(`[docwell bridge]`,e))}var _U=new hU(document.getElementById(`editor`),gU);window.docwell={receive:e=>_U.receive(e)}; diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue index f553ad4..6c37993 100644 --- a/Packages/editor/src/DocwellEditor.vue +++ b/Packages/editor/src/DocwellEditor.vue @@ -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/). */ + 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), diff --git a/Packages/editor/src/dates.ts b/Packages/editor/src/dates.ts index d416ace..2d2a511 100644 --- a/Packages/editor/src/dates.ts +++ b/Packages/editor/src/dates.ts @@ -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({ 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({ }, 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({ }; 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) => 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, () => { diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css index e3890f3..9d25192 100644 --- a/Packages/editor/src/editor.css +++ b/Packages/editor/src/editor.css @@ -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; diff --git a/Packages/editor/src/extensions.ts b/Packages/editor/src/extensions.ts index 8ce660c..0b7a943 100644 --- a/Packages/editor/src/extensions.ts +++ b/Packages/editor/src/extensions.ts @@ -54,6 +54,8 @@ export interface ExtensionOptions { onBlockLinkCopied?: (url: string) => void; /** Opens an app route, e.g. "/p/" 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, diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts index ac7107b..e0a4f00 100644 --- a/Packages/editor/src/labels.ts +++ b/Packages/editor/src/labels.ts @@ -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", }, }; diff --git a/Packages/ui/src/icons.ts b/Packages/ui/src/icons.ts index 833611c..e09aa9e 100644 --- a/Packages/ui/src/icons.ts +++ b/Packages/ui/src/icons.ts @@ -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; diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 3751405..d9ed9c0 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -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 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 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, + journalDate: json['journalDate'] as String, + createdBy: PageUser.fromJson(json['createdBy'] as Map), + lastEditedBy: PageUser.fromJson( + json['lastEditedBy'] as Map, + ), ); final String id; @@ -750,6 +768,19 @@ class Page { final PageFont font; + /// Tag ids + final List tags; + + /// Custom property values by property id (see Property for their shapes) + final Map properties; + + /// The day (YYYY-MM-DD) of a journal page; empty otherwise + final String journalDate; + + final PageUser createdBy; + + final PageUser lastEditedBy; + Map 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 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 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 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)) + .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 options; + + final PropertyVisibility visibility; + + final double position; + + Map 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 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)) + .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? options; + + final PropertyVisibility? visibility; + + final double? position; + + Map 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 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 toJson() => { + 'id': id, + 'name': name, + 'color': color.toJson(), + 'pages': pages, + }; +} + +class TagInput { + const TagInput({this.name, this.color}); + + factory TagInput.fromJson(Map 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 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 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 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 json) => DocFilter( + match: DocFilterMatch.fromJson(json['match'] as String), + rules: (json['rules'] as List) + .map((e) => DocRule.fromJson(e as Map)) + .toList(), + ); + + final DocFilterMatch match; + + final List rules; + + Map 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 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, + 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 tags; + + final Map properties; + + /// The caller's role on the page + final SpaceRole role; + + Map 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 json) => DocList( + items: (json['items'] as List) + .map((e) => DocItem.fromJson(e as Map)) + .toList(), + people: (json['people'] as Map).map( + (k, e) => MapEntry(k, e as String), + ), + ); + + final List items; + + /// Names of the people the items mention, by user id + final Map people; + + Map 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 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), + 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 include; + + /// Pages taken out by hand + final List exclude; + + /// Seen by everyone in the workspace + final bool shared; + + final String creator; + + final bool canEdit; + + final String updated; + + Map 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 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), + 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? include; + + final List? exclude; + + final bool? shared; + + Map 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 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 toJson() => {'date': date, 'page': page, 'title': title}; +} + +class JournalInfo { + const JournalInfo({ + required this.space, + required this.template, + required this.days, + }); + + factory JournalInfo.fromJson(Map json) => JournalInfo( + space: json['space'] as String, + template: json['template'] as String, + days: (json['days'] as List) + .map((e) => JournalDay.fromJson(e as Map)) + .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 days; + + Map 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 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 toJson() => {'id': id, 'name': name}; +} diff --git a/Phone-App/tool/generate_api.dart b/Phone-App/tool/generate_api.dart index 0ff3b0d..23d130b 100644 --- a/Phone-App/tool/generate_api.dart +++ b/Phone-App/tool/generate_api.dart @@ -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': diff --git a/Server/internal/access/organize.go b/Server/internal/access/organize.go new file mode 100644 index 0000000..46c30c2 --- /dev/null +++ b/Server/internal/access/organize.go @@ -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 "" +} diff --git a/Server/internal/access/organize_test.go b/Server/internal/access/organize_test.go new file mode 100644 index 0000000..db4e778 --- /dev/null +++ b/Server/internal/access/organize_test.go @@ -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) + } + } +} diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index 9a04ce4..d26a24d 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -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 diff --git a/Server/internal/directory/collections.go b/Server/internal/directory/collections.go new file mode 100644 index 0000000..8b083ff --- /dev/null +++ b/Server/internal/directory/collections.go @@ -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}) +} diff --git a/Server/internal/directory/docs.go b/Server/internal/directory/docs.go new file mode 100644 index 0000000..08c56f1 --- /dev/null +++ b/Server/internal/directory/docs.go @@ -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:". 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 +} diff --git a/Server/internal/directory/docs_test.go b/Server/internal/directory/docs_test.go new file mode 100644 index 0000000..8992101 --- /dev/null +++ b/Server/internal/directory/docs_test.go @@ -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) + } +} diff --git a/Server/internal/directory/journals.go b/Server/internal/directory/journals.go new file mode 100644 index 0000000..676096f --- /dev/null +++ b/Server/internal/directory/journals.go @@ -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}) + } +} diff --git a/Server/internal/directory/pages.go b/Server/internal/directory/pages.go index 4d369e0..081735a 100644 --- a/Server/internal/directory/pages.go +++ b/Server/internal/directory/pages.go @@ -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 +} diff --git a/Server/internal/directory/properties.go b/Server/internal/directory/properties.go new file mode 100644 index 0000000..9ea750f --- /dev/null +++ b/Server/internal/directory/properties.go @@ -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 +// { "": 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" // "