From 92cd81fd967ec42d5326fcdeac75e740a5da5383 Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:25:19 +0100 Subject: [PATCH] Add the slash menu, bubble menu, mentions and inline comments Editor: - "/" opens a filterable block menu (text, headings, lists, quote, code, divider, and image or file upload when the host can store files). - Selecting text shows a formatting toolbar (bold, italic, strike, code, link) and, for anyone who may comment, a Comment button. - "@" finds people in the page's workspace; the mention node is always in the schema so documents with mentions open in every client. - The popups are plain DOM in the design system's slash-menu style, so the framework-free mobile bridge keeps building and can use them. - Menu words come from the host; the web app passes English or Polish. Inline comments (basic): commenters cannot edit the document, so a comment's anchor is a pair of Yjs relative positions stored with the comment rather than a mark in the text. Highlights follow local edits by mapping and are re-resolved when comments change or remote edits arrive. Pages get a comments panel (side column, or a bottom sheet on narrow screens). Authors and space admins can delete comments. Server: comments collection and endpoints, and a people lookup any workspace member may use for mentions. Co-Authored-By: Claude Opus 5.5 --- Database/pb_migrations/1762700000_comments.js | 40 +++ Packages/api-client/src/index.ts | 10 + Packages/api-client/src/schema.d.ts | 179 +++++++++++++ Packages/editor-bridge/dist/index.html | 89 +++---- Packages/editor/package.json | 2 + Packages/editor/src/DocwellEditor.vue | 113 +++++++- Packages/editor/src/comments.ts | 138 ++++++++++ Packages/editor/src/editor.css | 89 +++++++ Packages/editor/src/extensions.ts | 13 + Packages/editor/src/index.ts | 4 + Packages/editor/src/labels.ts | 51 ++++ Packages/editor/src/mention.ts | 40 +++ Packages/editor/src/slash.ts | 127 +++++++++ Packages/editor/src/suggestion.ts | 179 +++++++++++++ Packages/ui/package.json | 1 + Phone-App/lib/api/generated/models.dart | 54 ++++ Server/internal/access/spaces.go | 22 ++ Server/internal/access/spaces_test.go | 15 ++ Server/internal/api/api.gen.go | 32 +++ Server/internal/directory/comments.go | 144 +++++++++++ Server/internal/directory/people.go | 65 +++++ Server/internal/httpapi/auth.go | 1 + Server/internal/httpapi/comments.go | 36 +++ Server/internal/httpapi/directory.go | 7 + .../frontend/src/components/PageComments.vue | 146 +++++++++++ .../src/composables/useEditorHosts.ts | 47 ++++ Web-App/frontend/src/locales/en.json | 69 +++++ Web-App/frontend/src/locales/pl.json | 69 +++++ Web-App/frontend/src/views/page/PageView.vue | 241 ++++++++++++------ api/openapi.yaml | 87 +++++++ go.work.sum | 3 +- package-lock.json | 2 + 32 files changed, 1992 insertions(+), 123 deletions(-) create mode 100644 Database/pb_migrations/1762700000_comments.js create mode 100644 Packages/editor/src/comments.ts create mode 100644 Packages/editor/src/labels.ts create mode 100644 Packages/editor/src/mention.ts create mode 100644 Packages/editor/src/slash.ts create mode 100644 Packages/editor/src/suggestion.ts create mode 100644 Server/internal/directory/comments.go create mode 100644 Server/internal/directory/people.go create mode 100644 Server/internal/httpapi/comments.go create mode 100644 Web-App/frontend/src/components/PageComments.vue create mode 100644 Web-App/frontend/src/composables/useEditorHosts.ts diff --git a/Database/pb_migrations/1762700000_comments.js b/Database/pb_migrations/1762700000_comments.js new file mode 100644 index 0000000..34bfe2d --- /dev/null +++ b/Database/pb_migrations/1762700000_comments.js @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// Inline comments. A comment points at a range of the page's text through +// anchor: Yjs relative positions (encoded by the editor), which follow the +// text as people edit. Commenters cannot change the document, so the anchor +// lives here instead of as a mark in the text. + +migrate( + (app) => { + const users = app.findCollectionByNameOrId("users"); + const pages = app.findCollectionByNameOrId("pages"); + const workspaces = app.findCollectionByNameOrId("workspaces"); + + app.save( + new Collection({ + type: "base", + name: "comments", + fields: [ + { name: "page", type: "relation", collectionId: pages.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "author", type: "relation", collectionId: users.id, maxSelect: 1, cascadeDelete: false }, + { name: "body", type: "text", required: true, max: 5000 }, + // The commented text when the comment was written. + { name: "quote", type: "text", max: 500 }, + { name: "anchor", type: "json", maxSize: 4096 }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: ["CREATE INDEX idx_comments_page ON comments (page, created)"], + }), + ); + }, + (app) => { + try { + app.delete(app.findCollectionByNameOrId("comments")); + } catch (_) {} + }, +); diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index a35b4a3..f9b4939 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -38,6 +38,7 @@ export type PageItem = Schemas["PageItem"]; export type Attachment = Schemas["Attachment"]; export type SearchHit = Schemas["SearchHit"]; export type ShareLink = Schemas["ShareLink"]; +export type Comment = Schemas["Comment"]; export type SharedPage = Schemas["SharedPage"]; export type SearchResult = Schemas["SearchResult"]; export type GroupRequest = Schemas["GroupRequest"]; @@ -166,6 +167,10 @@ export function createClient(opts: ClientOptions) { post("/api/v1/auth/invites/accept", { token, name, password }), }, + comments: { + remove: (id: string) => request("DELETE", `/api/v1/comments/${encodeURIComponent(id)}`), + }, + files: { /** A short-lived token for ?token= on file URLs (img tags cannot send headers). */ token: () => post<{ token: string; expires: string }>("/api/v1/files/token"), @@ -232,6 +237,8 @@ export function createClient(opts: ClientOptions) { createSpace: (id: string, input: CreateSpaceRequest) => post(`/api/v1/workspaces/${encodeURIComponent(id)}/spaces`, input), groups: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/groups`), + people: (id: string, q: string, limit?: number) => + request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/people${query({ q, limit })}`), search: (id: string, q: string, limit?: number) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/search${query({ q, limit })}`), favorites: (id: string) => request("GET", `/api/v1/workspaces/${encodeURIComponent(id)}/favorites`), @@ -309,6 +316,9 @@ export function createClient(opts: ClientOptions) { form.append("file", file, name); return upload(`/api/v1/pages/${encodeURIComponent(id)}/attachments`, form); }, + comments: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/comments`), + addComment: (id: string, input: { body: string; quote?: string; anchor?: Record | null }) => + post(`/api/v1/pages/${encodeURIComponent(id)}/comments`, input), /** The public link; rejects with a 404 ApiError when sharing is off. */ shareLink: (id: string) => request("GET", `/api/v1/pages/${encodeURIComponent(id)}/share`), setShareLink: (id: string, includeSubpages: boolean) => diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index e071911..3d5fd54 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -1290,6 +1290,64 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workspaces/{id}/people": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** Find people in the workspace by name or email (for mentions; any member) */ + get: operations["listPeople"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/pages/{id}/comments": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The page's inline comments, oldest first */ + get: operations["listComments"]; + put?: never; + /** Comment on the page (commenter) */ + post: operations["createComment"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/comments/{id}": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** Delete a comment (its author, or a space admin) */ + delete: operations["deleteComment"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -1690,6 +1748,19 @@ export interface components { /** @description Pages under the shared page */ pages: components["schemas"]["PageNode"][]; }; + Comment: { + id: string; + page: string; + author: components["schemas"]["MemberUser"]; + body: string; + quote: string; + /** @description As sent when the comment was created; null when there was none */ + anchor: { + [key: string]: unknown; + } | null; + created: string; + canDelete: boolean; + }; }; responses: { /** @description Signed in */ @@ -3992,4 +4063,112 @@ export interface operations { 404: components["responses"]["Error"]; }; }; + listPeople: { + parameters: { + query?: { + q?: string; + limit?: number; + }; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MemberUser"][]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + listComments: { + 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"]["Comment"][]; + }; + }; + 404: components["responses"]["Error"]; + }; + }; + createComment: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + body: string; + /** @description The commented text */ + quote?: string; + /** @description The editor's encoding of the commented range (opaque to the server) */ + anchor?: { + [key: string]: unknown; + }; + }; + }; + }; + responses: { + /** @description Created */ + 201: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Comment"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + deleteComment: { + 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"]; + }; + }; } diff --git a/Packages/editor-bridge/dist/index.html b/Packages/editor-bridge/dist/index.html index 598d0a6..4df8923 100644 --- a/Packages/editor-bridge/dist/index.html +++ b/Packages/editor-bridge/dist/index.html @@ -5,30 +5,30 @@ Docwell editor - +`).trim();if(u){let e=n.blockTokens(u);l.push(...e)}let d=i+1,f=[];for(;dt;)f.push(e[d]),d+=1;if(f.length>0){let e=JO(f,Math.min(...f.map(e=>e.indent)),n);l.push({type:`list`,ordered:!0,start:f[0].number,typeMarker:f[0].type,items:e,raw:f.map(e=>e.raw).join(` +`)})}r.push({type:`list_item`,raw:a.raw,tokens:l}),i=d}else i+=1}return r}function YO(e,t){return e.map(e=>{if(e.type!==`list_item`)return t.parseChildren([e])[0];let n=[];return e.tokens&&e.tokens.length>0&&e.tokens.forEach(e=>{if(e.type===`paragraph`||e.type===`list`||e.type===`blockquote`||e.type===`code`)n.push(...t.parseChildren([e]));else if(e.type===`text`&&e.tokens){let r=t.parseChildren([e]);n.push({type:`paragraph`,content:r})}else{let r=t.parseChildren([e]);r.length>0&&n.push(...r)}}),{type:`listItem`,content:n}})}var XO=64;function ZO(e,t){let n=[],r=0;for(;n.lengthe.hasAttribute(`start`)?parseInt(e.getAttribute(`start`)||``,10):1},type:{default:null,parseHTML:e=>{let t=e.getAttribute(`type`);if(t)return t;let n=e.getAttribute(`style`);if(n){let e=nk(n);if(e)return e}let r=e.querySelector(`li`);if(r){let e=r.getAttribute(`style`);if(e){let t=nk(e);if(t)return t}}return null}}}},parseHTML(){return[{tag:`ol`}]},renderHTML({HTMLAttributes:e}){let{start:t,type:n,...r}=e,i=I(this.options.HTMLAttributes,r);return t!==1&&(i.start=t),n&&n!==`1`&&(i.type=n),[`ol`,i,0]},markdownTokenName:`list`,parseMarkdown:(e,t)=>{if(e.type!==`list`||!e.ordered)return[];let n=e.start||1,r=e.typeMarker,i=e.items?YO(e.items,t):[],a={};return n!==1&&(a.start=n),r&&(a.type=r),Object.keys(a).length>0?{type:`orderedList`,attrs:a,content:i}:{type:`orderedList`,content:i}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,` +`):``,markdownTokenizer:{name:`orderedList`,level:`block`,start:()=>-1,tokenize:(e,t,n)=>{let[r,i,a]=QO(e);if(r.length===0)return;let o=JO(r,r[0].indent,n);if(o.length!==0)return{type:`list`,ordered:!0,start:r[0]?.number||1,typeMarker:r[0]?.type,items:o,raw:a.slice(0,i).join(` +`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes($O,this.editor.getAttributes(ek)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new O({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=qO(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=Mp({find:tk,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Mp({find:tk,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(ek)}),joinPredicate:e,editor:this.editor})),[t]}}),ik=/^\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`,ok=(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`}`},sk=Fp.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`,I(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)=>Jf(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[iO(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=ok(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=Au(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[Mp({find:ik,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),ck=Fp.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`,I(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=Gf(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=Gf(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()}}});L.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(eO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(OO.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(LO.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(rk.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(sk.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(ck.configure(this.options.taskList)),e}});var lk=` `,uk=`\xA0`,dk=Fp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,I(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===lk||n[0].text===lk||n[0].raw===uk||n[0].text===uk)&&r.length===1&&r[0].type===`text`&&(r[0].text===lk||r[0].text===uk)?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?lk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),fk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,pk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,mk=ap.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`,I(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[kp({find:fk,type:this.type})]},addPasteRules(){return[Ip({find:pk,type:this.type})]}}),hk=Fp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),gk=ap.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`,I(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()}}}),_k=L.create({name:`starterKit`,addExtensions(){let e=[];return this.options.bold!==!1&&e.push(lT.configure(this.options.bold)),this.options.blockquote!==!1&&e.push(iT.configure(this.options.blockquote)),this.options.bulletList!==!1&&e.push(eO.configure(this.options.bulletList)),this.options.code!==!1&&e.push(pT.configure(this.options.code)),this.options.codeBlock!==!1&&e.push(_T.configure(this.options.codeBlock)),this.options.document!==!1&&e.push(vT.configure(this.options.document)),this.options.dropcursor!==!1&&e.push(Sw.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&e.push(Cw.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&e.push(yT.configure(this.options.hardBreak)),this.options.heading!==!1&&e.push(bT.configure(this.options.heading)),this.options.undoRedo!==!1&&e.push(Jw.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&e.push(xT.configure(this.options.horizontalRule)),this.options.italic!==!1&&e.push(ET.configure(this.options.italic)),this.options.listItem!==!1&&e.push(OO.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(LO.configure(this.options?.listKeymap)),this.options.link!==!1&&e.push(XD.configure(this.options?.link)),this.options.orderedList!==!1&&e.push(rk.configure(this.options.orderedList)),this.options.paragraph!==!1&&e.push(dk.configure(this.options.paragraph)),this.options.strike!==!1&&e.push(mk.configure(this.options.strike)),this.options.text!==!1&&e.push(hk.configure(this.options.text)),this.options.underline!==!1&&e.push(gk.configure(this.options?.underline)),this.options.trailingNode!==!1&&e.push(qw.configure(this.options?.trailingNode)),e}});function vk(e){let t=Y.getState(e);return t?.type&&t.binding&&t.doc?t:null}function yk(e,t){let n=vk(e);if(!n||!t?.from||!t.to)return null;try{let r=e=>uS(n.doc,n.type,Jv(ng(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 bk=new k(`docwellComments`);function xk(e,t,n){let r=[];for(let i of t){let t=yk(e,i.anchor);t&&r.push(hs.inline(t.from,t.to,{class:i.id===n?`dw-comment is-active`:`dw-comment`,"data-comment":i.id}))}return M.create(e.doc,r)}var Sk=L.create({name:`commentHighlights`,addOptions(){return{onSelect:void 0}},addProseMirrorPlugins(){let e=()=>this.options.onSelect;return[new O({key:bk,state:{init:()=>({marks:[],active:``,decos:M.empty}),apply(e,t,n,r){let i=e.getMeta(bk);if(i)return{...i,decos:xk(r,i.marks,i.active)};if(!e.docChanged||!t.marks.length)return t;let a=e.getMeta(Y)?.isChangeOrigin;return{...t,decos:a?xk(r,t.marks,t.active):t.decos.map(e.mapping,e.doc)}}},props:{decorations:e=>bk.getState(e)?.decos??M.empty,handleClick(t,n,r){let i=r.target?.closest?.(`[data-comment]`)?.getAttribute(`data-comment`);return i&&e()?.(i),!1}}})]}}),Ck=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,wk=Fp.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`,I(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=I(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 Pp({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=Au(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[Ap({find:Ck,type:this.type,getAttributes:e=>{let[,,t,n,r]=e;return{src:n,alt:t,title:r}}})]}});async function Tk(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}};e.chain().focus().insertContentAt(r??e.state.selection.to,a).run(),r=void 0}}var Ek=wk.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 Dk(e){if(!e)return``;let t=[`B`,`KB`,`MB`,`GB`],n=0,r=e;for(;r>=1024&&n({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`)??``})}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,I(t,{"data-type":`file`,"data-url":e.attrs.url,"data-name":e.attrs.name,"data-size":e.attrs.size,"data-mime":e.attrs.mime}),[`a`,{href:e.attrs.url,download:e.attrs.name},e.attrs.name]]},addNodeView(){return({node:e})=>{let t=document.createElement(`div`);t.className=`dw-file`,t.setAttribute(`data-type`,`file`);let n=document.createElement(`a`);n.className=`dw-file__name`,n.target=`_blank`,n.rel=`noopener`;let r=document.createElement(`span`);r.className=`dw-file__size`;let i=e=>{let t=String(e.attrs.url??``);n.href=this.options.host?this.options.host.resolve(t):t,n.textContent=String(e.attrs.name??`file`),r.textContent=Dk(Number(e.attrs.size??0))};return i(e),t.append(n,r),{dom:t,update:t=>t.type===e.type&&(i(t),!0)}}}}),kk=L.create({name:`fileDrop`,addOptions(){return{host:void 0,onError:void 0}},addProseMirrorPlugins(){let e=this.options.host;return e?[Ak(()=>this.editor,e,this.options.onError)]:[]}});function Ak(e,t,n){let r=(r,i)=>{let a=e();return!a||!r.length||!t.upload?!1:(Tk(a,t,r,i).catch(n),!0)};return new O({key:new k(`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 jk={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`},bullet:{label:`Bulleted list`,description:`A simple list`},ordered:{label:`Numbered list`,description:`A list with numbers`},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`}},format:{bold:`Bold`,italic:`Italic`,strike:`Strikethrough`,code:`Inline code`,link:`Link`,linkPrompt:`Link address (leave empty to remove the link)`,comment:`Comment`},mentions:`Mention someone`,noPeople:`Nobody found`},Mk=Math.min,Nk=Math.max,Pk=Math.round,Fk=Math.floor,Ik=e=>({x:e,y:e}),Lk={left:`right`,right:`left`,bottom:`top`,top:`bottom`};function Rk(e,t,n){return Nk(e,Mk(t,n))}function zk(e,t){return typeof e==`function`?e(t):e}function Bk(e){return e.split(`-`)[0]}function Vk(e){return e.split(`-`)[1]}function Hk(e){return e===`x`?`y`:`x`}function Uk(e){return e===`y`?`height`:`width`}function Wk(e){let t=e[0];return t===`t`||t===`b`?`y`:`x`}function Gk(e){return Hk(Wk(e))}function Kk(e,t,n){n===void 0&&(n=!1);let r=Vk(e),i=Gk(e),a=Uk(i),o=i===`x`?r===(n?`end`:`start`)?`right`:`left`:r===`start`?`bottom`:`top`;return t.reference[a]>t.floating[a]&&(o=tA(o)),[o,tA(o)]}function qk(e){let t=tA(e);return[Jk(e),t,Jk(t)]}function Jk(e){return e.includes(`start`)?e.replace(`start`,`end`):e.replace(`end`,`start`)}var Yk=[`left`,`right`],Xk=[`right`,`left`],Zk=[`top`,`bottom`],Qk=[`bottom`,`top`];function $k(e,t,n){switch(e){case`top`:case`bottom`:return n?t?Xk:Yk:t?Yk:Xk;case`left`:case`right`:return t?Zk:Qk;default:return[]}}function eA(e,t,n,r){let i=Vk(e),a=$k(Bk(e),n===`start`,r);return i&&(a=a.map(e=>e+`-`+i),t&&(a=a.concat(a.map(Jk)))),a}function tA(e){let t=Bk(e);return Lk[t]+e.slice(t.length)}function nA(e){return{top:e.top??0,right:e.right??0,bottom:e.bottom??0,left:e.left??0}}function rA(e){return typeof e==`number`?{top:e,right:e,bottom:e,left:e}:nA(e)}function iA(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 aA(e,t,n){let{reference:r,floating:i}=e,a=Wk(t),o=Gk(t),s=Uk(o),c=Bk(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=Vk(t);return m&&(p[o]+=f*(m===`end`?1:-1)*(n&&l?-1:1)),p}async function oA(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}=zk(t,e),p=rA(f),m=o[d?u===`floating`?`reference`:`floating`:u],h=iA(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=iA(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 sA=50,cA=async(e,t,n)=>{let{placement:r=`bottom`,strategy:i=`absolute`,middleware:a=[],platform:o}=n,s=o.detectOverflow?o:{...o,detectOverflow:oA},c=await(o.isRTL==null?void 0:o.isRTL(t)),l=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:u,y:d}=aA(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`||_===Wk(t)||ne.every(e=>Wk(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=Wk(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{}}}},uA=new Set([`left`,`top`]);async function dA(e,t){let{placement:n,platform:r,elements:i}=e,a=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Bk(n),s=Vk(n),c=Wk(n)===`y`,l=uA.has(o)?-1:1,u=a&&c?-1:1,d=zk(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 fA=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 dA(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}}}}},pA=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}=zk(e,t),u={x:n,y:r},d=await a.detectOverflow(t,l),f=Wk(i),p=Hk(f),m=u[p],h=u[f],g=(e,t)=>Rk(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 mA(){return typeof window<`u`}function hA(e){return vA(e)?(e.nodeName||``).toLowerCase():`#document`}function gA(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function _A(e){return((vA(e)?e.ownerDocument:e.document)||window.document)?.documentElement}function vA(e){return mA()?e instanceof Node||e instanceof gA(e).Node:!1}function yA(e){return mA()?e instanceof Element||e instanceof gA(e).Element:!1}function bA(e){return mA()?e instanceof HTMLElement||e instanceof gA(e).HTMLElement:!1}function xA(e){return!mA()||typeof ShadowRoot>`u`?!1:e instanceof ShadowRoot||e instanceof gA(e).ShadowRoot}function SA(e){let{overflow:t,overflowX:n,overflowY:r,display:i}=NA(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!==`inline`&&i!==`contents`}function CA(e){return/^(table|td|th)$/.test(hA(e))}function wA(e){try{if(e.matches(`:popover-open`))return!0}catch{}try{return e.matches(`:modal`)}catch{return!1}}var TA=/transform|translate|scale|rotate|perspective|filter/,EA=/paint|layout|strict|content/,DA=e=>!!e&&e!==`none`,OA;function kA(e){let t=yA(e)?NA(e):e;return DA(t.transform)||DA(t.translate)||DA(t.scale)||DA(t.rotate)||DA(t.perspective)||!jA()&&(DA(t.backdropFilter)||DA(t.filter))||TA.test(t.willChange||``)||EA.test(t.contain||``)}function AA(e){let t=FA(e);for(;bA(t)&&!MA(t);){if(kA(t))return t;if(wA(t))return null;t=FA(t)}return null}function jA(){return OA??=typeof CSS<`u`&&CSS.supports&&CSS.supports(`-webkit-backdrop-filter`,`none`),OA}function MA(e){return/^(html|body|#document)$/.test(hA(e))}function NA(e){return gA(e).getComputedStyle(e)}function PA(e){return yA(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function FA(e){if(hA(e)===`html`)return e;let t=e.assignedSlot||e.parentNode||xA(e)&&e.host||_A(e);return xA(t)?t.host:t}function IA(e){let t=FA(e);return MA(t)?(e.ownerDocument||e).body:bA(t)&&SA(t)?t:IA(t)}function LA(e,t,n){t===void 0&&(t=[]),n===void 0&&(n=!0);let r=IA(e),i=r===e.ownerDocument?.body,a=gA(r);if(i){let e=RA(a);return t.concat(a,a.visualViewport||[],SA(r)?r:[],e&&n?LA(e):[])}return t.concat(r,LA(r,[],n))}function RA(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function zA(e){let t=NA(e),n=parseFloat(t.width)||0,r=parseFloat(t.height)||0,i=bA(e),a=i?e.offsetWidth:n,o=i?e.offsetHeight:r,s=Pk(n)!==a||Pk(r)!==o;return s&&(n=a,r=o),{width:n,height:r,$:s}}function BA(e){return yA(e)?e:e.contextElement}function VA(e){let t=BA(e);if(!bA(t))return Ik(1);let n=t.getBoundingClientRect(),{width:r,height:i,$:a}=zA(t),o=(a?Pk(n.width):n.width)/r,s=(a?Pk(n.height):n.height)/i;return o&&Number.isFinite(o)||(o=1),s&&Number.isFinite(s)||(s=1),{x:o,y:s}}var HA=Ik(0);function UA(e){let t=gA(e);return!jA()||!t.visualViewport?HA:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WA(e,t,n){return t===void 0&&(t=!1),!!n&&t&&n===gA(e)}function GA(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);let i=e.getBoundingClientRect(),a=BA(e),o=Ik(1);t&&(r?yA(r)&&(o=VA(r)):o=VA(e));let s=WA(a,n,r)?UA(a):Ik(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=gA(a),t=yA(r)?gA(r):r,n=e,i=RA(n);for(;i&&t!==n;){let e=VA(i),t=i.getBoundingClientRect(),r=NA(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=gA(i),i=RA(n)}}return iA({width:u,height:d,x:c,y:l})}function KA(e,t){let n=PA(e).scrollLeft;return t?t.left+n:GA(_A(e)).left+n}function qA(e,t){let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-KA(e,n),y:n.top+t.scrollTop}}function JA(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e,a=i===`fixed`,o=_A(r),s=t?wA(t.floating):!1;if(r===o||s&&a)return n;let c={scrollLeft:0,scrollTop:0},l=Ik(1),u=Ik(0),d=bA(r);if((d||!a)&&((hA(r)!==`body`||SA(o))&&(c=PA(r)),d)){let e=GA(r);l=VA(r),u.x=e.x+r.clientLeft,u.y=e.y+r.clientTop}let f=o&&!d&&!a?qA(o,c):Ik(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 YA(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function XA(e){let t=PA(e),n=e.ownerDocument.body,r=Nk(e.scrollWidth,e.clientWidth,n.scrollWidth,n.clientWidth),i=Nk(e.scrollHeight,e.clientHeight,n.scrollHeight,n.clientHeight),a=-t.scrollLeft+KA(e),o=-t.scrollTop;return NA(n).direction===`rtl`&&(a+=Nk(e.clientWidth,n.clientWidth)-r),{width:r,height:i,x:a,y:o}}var ZA=25;function QA(e,t,n){n===void 0&&(n=`viewport`);let r=n===`layoutViewport`,i=gA(e),a=_A(e),o=i.visualViewport,s=a.clientWidth,c=a.clientHeight,l=0,u=0;if(o){let e=!jA()||t===`fixed`;r?e||(l=-o.offsetLeft,u=-o.offsetTop):(s=o.width,c=o.height,e&&(l=o.offsetLeft,u=o.offsetTop))}if(KA(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<=ZA&&(s-=o)}return{width:s,height:c,x:l,y:u}}function $A(e,t){let n=GA(e,!0,t===`fixed`),r=n.top+e.clientTop,i=n.left+e.clientLeft,a=VA(e);return{width:e.clientWidth*a.x,height:e.clientHeight*a.y,x:i*a.x,y:r*a.y}}function ej(e,t,n){let r;if(t===`viewport`||t===`layoutViewport`)r=QA(e,n,t);else if(t===`document`)r=XA(_A(e));else if(yA(t))r=$A(t,n);else{let n=UA(e);r={x:t.x-n.x,y:t.y-n.y,width:t.width,height:t.height}}return iA(r)}function tj(e,t){let n=t.get(e);if(n)return n;let r=LA(e,[],!1).filter(e=>yA(e)&&hA(e)!==`body`),i=null,a=NA(e).position===`fixed`,o=a?FA(e):e;for(;yA(o)&&!MA(o);){let e=NA(o),t=kA(o),n=i?i.position:a?`fixed`:``;!t&&(n===`fixed`||n===`absolute`&&e.position===`static`)?r=r.filter(e=>e!==o):i=e,o=FA(o)}return t.set(e,r),r}function nj(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e,a=[...n===`clippingAncestors`?wA(t)?[]:tj(t,this._c):[].concat(n),r],o=ej(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=gA(e),l=()=>s(n);return c.addEventListener(`resize`,l),s(!0),()=>{c.removeEventListener(`resize`,l),o()}}function pj(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=BA(e),u=i||a?[...l?LA(l):[],...t?LA(t):[]]:[];u.forEach(e=>{i&&e.addEventListener(`scroll`,n),a&&e.addEventListener(`resize`,n)});let d=l&&s?fj(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?GA(e):null;c&&g();function g(){let t=GA(e);h&&!dj(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 mj=fA,hj=pA,gj=lA,_j=(e,t,n)=>{let r=new Map,i=n??{},a={...uj,...i.platform,_c:r};return cA(e,t,{...i,platform:a})};function vj(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=Sf(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(Sf).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 yj(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 bj(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 xj(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:bj(e)}function Sj({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&&!yj(r)}function Cj({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function wj({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),M.create(a.doc,[hs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function Tj({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 Ej({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 Dj({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[mj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(gj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function Oj(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 kj({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&&Oj(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=pj(c,o,()=>{_j(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 Aj({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,_=Ej({editor:e,items:n}),v=Dj({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 C=S===`stopped`?b:x,ie=n.dom.querySelector(`[data-decoration-id="${C.decorationId}"]`),ae=m(n,ie),oe=i===0||(C.query?C.query.length>=i:!1),se=(S===`started`||S===`updated`)&&oe;if(g={editor:e,range:C.range,query:C.query||``,text:C.text||``,items:o??[],command:t=>p({editor:e,range:C.range,props:t}),decorationNode:ie,clientRect:ae,loading:se,placement:s,offset:{mainAxis:c.mainAxis??4,crossAxis:c.crossAxis??0},container:l,flip:u,floatingUi:v,mount:kj({getReferenceRect:ae,contextElement:n.dom,config:v,container:l,dismissOnOutsideClick:f,dismiss:()=>h(e.view)})},S===`started`){var ce;r==null||(ce=r.onBeforeStart)==null||ce.call(r,g)}if(S===`updated`){var le;r==null||(le=r.onBeforeUpdate)==null||le.call(r,g)}if(S===`started`&&y(S,g),S===`started`||S===`updated`){if(!se)_.abort(),g={...g,items:o??[],loading:!1};else{g={...g,items:o??[],loading:!0},S=`updated`,y(S,g);let e=await _.fetch(C.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 jj=new k(`suggestion`);function Mj({pluginKey:e=jj,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=vj,shouldShow:ne,shouldResetDismissed:re}){let C=S?.(),ie=r&&!i,ae=(n,r)=>xj(t,n,r,e);function oe(e){return Sj({...e,editor:t,shouldResetDismissed:re,effectiveAllowSpaces:ie})}let se=t=>Cj({view:t,pluginKeyRef:e});return new O({key:e,view:()=>Aj({editor:t,pluginKey:e,items:f,renderer:C,minQueryLength:p,debounce:m,initialItems:h,placement:g,offset:_,container:v,flip:y,floatingUi:b,dismissOnOutsideClick:x,command:d,clientRectFor:ae,dispatchExit:se}),state:Tj({editor:t,char:n,effectiveAllowSpaces:ie,allowToIncludeChar:i,allowedPrefixes:a,startOfLine:o,findSuggestionMatch:te,allow:ee,shouldShow:ne,shouldKeepDismissed:oe,pluginKey:e}),props:wj({pluginKey:e,decorationTag:s,decorationClass:c,decorationContent:l,decorationEmptyClass:u,renderer:C,dispatchExit:se})})}var Nj=Mj;function Pj({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new k,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 Fj(e){return(e.options.suggestions.length?e.options.suggestions:[e.options.suggestion]).map(t=>Pj({editor:e.editor,overrideSuggestionOptions:t,extensionName:e.name,char:t.char}))}function Ij(e,t){let n=Fj(e);return n.find(e=>e.char===t)||(n.length?n[0]:null)}var Lj=Fp.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`,I(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=Ij(this,e.attrs.mentionSuggestionChar);if(this.options.renderLabel!==void 0)return console.warn(`renderLabel is deprecated use renderText and renderHTML instead`),[`span`,I({"data-type":this.name},this.options.HTMLAttributes,t),this.options.renderLabel({options:this.options,node:e,suggestion:n})];let r={...this.options};r.HTMLAttributes=I({"data-type":this.name},this.options.HTMLAttributes,t);let i=this.options.renderHTML({options:r,node:e,suggestion:n});return typeof i==`string`?[`span`,I({"data-type":this.name},this.options.HTMLAttributes,t),i]:i},...Vf({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:Ij(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 ce,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 Fj(this).map(Mj)}}),Rj={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-down":[`M6 10l6 6 6-6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],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`],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`],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`]},zj=`http://www.w3.org/2000/svg`;function Bj(e){let t=document.createElementNS(zj,`svg`);for(let[e,n]of Object.entries({width:`18`,height:`18`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":`1.75`,"stroke-linecap":`round`,"stroke-linejoin":`round`,"aria-hidden":`true`}))t.setAttribute(e,n);for(let n of Rj[e]){let e=document.createElementNS(zj,`path`);e.setAttribute(`d`,n),t.append(e)}return t}function Vj(e){return()=>{let t=null,n=null,r=null,i=0,a=t=>{let n=r?.items[t];r&&n!==void 0&&e.pick(r,n)},o=()=>{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(n.items.length)n.items.forEach((n,r)=>{let o=e.toItem(n),s=document.createElement(`div`);s.className=r===i?`dw-suggest__item is-active`:`dw-suggest__item`,s.setAttribute(`role`,`option`),s.setAttribute(`aria-selected`,String(r===i)),s.addEventListener(`mousedown`,e=>{e.preventDefault(),a(r)});let c=document.createElement(`span`);c.className=`dw-suggest__icon`,c.append(Bj(o.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=o.label,l.append(u),o.description){let e=document.createElement(`span`);e.className=`dw-suggest__desc`,e.textContent=o.description,l.append(e)}s.append(c,l),t.append(s)}),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)}},s=()=>{let e=r?.clientRect?.();if(!t||!e)return;let i={getBoundingClientRect:()=>r?.clientRect?.()??e};n?.(),n=pj(i,t,()=>{t&&_j(i,t,{placement:`bottom-start`,strategy:`fixed`,middleware:[mj(6),gj(),hj({padding:8})]}).then(({x:e,y:n})=>{t&&Object.assign(t.style,{left:`${e}px`,top:`${n}px`})})})},c=()=>{n?.(),n=null,t?.remove(),t=null};return{onStart(n){r=n,i=0,t=document.createElement(`div`),t.className=`dw-suggest`,t.setAttribute(`role`,`listbox`),t.setAttribute(`aria-label`,e.label),document.body.append(t),o(),s()},onUpdate(e){e.items!==r?.items&&(i=0),r=e,o(),s()},onKeyDown({event:e}){let t=r?.items.length??0;return e.key===`Escape`?(c(),!0):t?e.key===`ArrowDown`||e.key===`ArrowUp`?(i=(i+(e.key===`ArrowDown`?1:-1)+t)%t,o(),!0):e.key===`Enter`||e.key===`Tab`?(a(i),!0):!1:!1},onExit(){r=null,c()}}}}function Hj(e,t){return Lj.configure({HTMLAttributes:{class:`dw-mention`},renderText:({node:e})=>`@${e.attrs.label??e.attrs.id}`,suggestion:{char:`@`,allow:()=>!!t,items:async({query:e})=>t?(await t.search(e).catch(()=>[])).slice(0,8):[],render:Vj({label:e.mentions,empty:e.noPeople,toItem:e=>({label:e.label,description:e.hint,icon:`at`}),pick:(e,t)=>e.command({id:t.id,label:t.label})})}})}function Uj(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 Wj(e,t,n){let r=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),i=[r(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),r(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),r(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),r(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),r(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),r(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),r(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),r(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),r(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run())];if(t?.upload){let e=e=>(r,i)=>{r.chain().focus().deleteRange(i).run(),Uj(e).then(e=>Tk(r,t,e).catch(n))};i.push(r(`image`,`image`,[`picture`,`photo`,`img`],e(`image/*`)),r(`file`,`paperclip`,[`attachment`,`upload`,`pdf`],e(``)))}return i}function Gj(e,t){let n=t.trim().toLowerCase();return n?e.filter(e=>e.label.toLowerCase().includes(n)||e.id.startsWith(n)||e.keywords.some(e=>e.toLowerCase().startsWith(n))):e}var Kj=L.create({name:`slashMenu`,addOptions(){return{commands:[],labels:void 0}},addProseMirrorPlugins(){return[Nj({editor:this.editor,pluginKey:new k(`slashMenu`),char:`/`,allowSpaces:!1,startOfLine:!1,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:({query:e})=>Gj(this.options.commands,e),render:Vj({label:this.options.labels.slashMenu,empty:this.options.labels.noMatches,showQuery:!0,toItem:e=>({label:e.label,description:e.description,icon:e.icon}),pick:(e,t)=>t.run(e.editor,e.range)})})]}});function qj(e={}){let t=e.labels??jk,n=[_k.configure({heading:{levels:[1,2,3]},link:{openOnClick:!1,autolink:!0},undoRedo:!e.collab&&void 0}),Vw.configure({placeholder:e.placeholder??`Type '/' for commands…`}),Ek.configure({host:e.files}),Ok.configure({host:e.files}),kk.configure({host:e.files,onError:e.onError}),Hj(t,e.mentions),Kj.configure({commands:Wj(t,e.files,e.onError),labels:t}),Sk.configure({onSelect:e.onCommentSelect})];return e.collab&&n.push(rw.configure({document:e.collab.provider.doc}),cw.configure({provider:e.collab.provider,user:e.collab.user,render:Jj})),n}function Jj(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 Yj=3e4,Xj=class extends Zp{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=vh();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&&Zj(this,t,`timeout`)},Qp(Yj/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:vh()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),Rh(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}},Zj=(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]))},Qj=(e,t,n=e.states)=>{let r=t.length,i=ym();R(i,r);for(let a=0;a{let r=Qm(t),i=vh(),a=[],o=[],s=[],c=[],l=B(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])},eM=(e,t)=>{R(e,0),jm(e,Av(t))},tM=(e,t,n)=>{R(e,1),jm(e,wv(t,n))},nM=(e,t,n)=>tM(t,n,th(e)),rM=(e,t,n,r)=>{try{xv(t,th(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},iM=(e,t)=>{R(e,2),jm(e,t)},aM=rM,oM=(e,t,n,r,i)=>{let a=B(e);switch(a){case 0:nM(e,t,n);break;case 1:rM(e,n,r,i);break;case 2:aM(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},sM=0,cM=1,lM=4401,uM=4404,dM=4409,fM=class{opts;doc=new av;awareness=new Xj(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),Zj(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=ym();R(t,sM),eM(t,this.doc),e.send(Sm(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);Zj(this.awareness,n,this),this.destroyed||(t.code===lM||t.code===uM?this.set(`denied`,!1):t.code===dM?this.set(`changed`):(this.set(`offline`),this.retryTimer=setTimeout(()=>this.connect(),Math.min(1e3*2**this.retries++,3e4))))}}onMessage(e){let t=Qm(e),n=B(t);if(n===sM){let e=ym();R(e,sM);let n=oM(t,e,this.doc,this);xm(e)>1&&this.ws?.send(Sm(e)),n===1&&(this.retries=0,this.set(`connected`,!0))}else n===cM&&$j(this.awareness,th(t),this)}onDocUpdate=(e,t)=>{if(t===this||this.ws?.readyState!==WebSocket.OPEN)return;let n=ym();R(n,sM),iM(n,e),this.ws.send(Sm(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=ym();R(t,cM),jm(t,Qj(this.awareness,e)),this.ws.send(Sm(t))}onUnload=()=>Zj(this.awareness,[this.doc.clientID],`unload`)},pM={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(),undo:e=>e.chain().focus().undo().run(),redo:e=>e.chain().focus().redo().run()},mM=[[`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`)]],hM=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:1})}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:1}),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`command`:{let t=pM[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 fM({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 Op({element:this.el,editable:this.editable,extensions:qj(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:mM.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 gM(e){let t=JSON.stringify(e);window.DocwellNative?window.DocwellNative.postMessage(t):(window.parent.postMessage(t,`*`),console.debug(`[docwell bridge]`,e))}var _M=new hM(document.getElementById(`editor`),gM);window.docwell={receive:e=>_M.receive(e)}; diff --git a/Packages/editor/package.json b/Packages/editor/package.json index c0c865a..e8d73f4 100644 --- a/Packages/editor/package.json +++ b/Packages/editor/package.json @@ -12,6 +12,8 @@ "./editor.css": "./src/editor.css" }, "dependencies": { + "@docwell/ui": "*", + "@floating-ui/dom": "^1.8.0", "@tiptap/core": "^3.32.2", "@tiptap/extension-bubble-menu": "^3.32.2", "@tiptap/extension-collaboration": "^3.32.2", diff --git a/Packages/editor/src/DocwellEditor.vue b/Packages/editor/src/DocwellEditor.vue index bb3d8ca..19315fe 100644 --- a/Packages/editor/src/DocwellEditor.vue +++ b/Packages/editor/src/DocwellEditor.vue @@ -1,10 +1,14 @@ diff --git a/Packages/editor/src/comments.ts b/Packages/editor/src/comments.ts new file mode 100644 index 0000000..e39c705 --- /dev/null +++ b/Packages/editor/src/comments.ts @@ -0,0 +1,138 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { Extension, type Editor } from "@tiptap/core"; +import { Plugin, PluginKey, type EditorState } from "@tiptap/pm/state"; +import { Decoration, DecorationSet } from "@tiptap/pm/view"; +import { + absolutePositionToRelativePosition, + relativePositionToAbsolutePosition, + ySyncPluginKey, +} from "@tiptap/y-tiptap"; +import { fromBase64, toBase64 } from "lib0/buffer"; +import * as Y from "yjs"; + +/** + * Where a comment points: Yjs relative positions of the range's ends, which + * keep pointing at the same text while people edit around it. Only editors + * on a shared (collaborative) document can make or read them. + */ +export interface CommentAnchor { + from: string; + to: string; +} + +/** A comment to highlight: its id and anchor (null anchors are not drawn). */ +export interface CommentMark { + id: string; + anchor: CommentAnchor | null; +} + +type SyncState = { + type: Y.XmlFragment; + doc: Y.Doc; + binding: { mapping: Parameters[2] }; +}; + +function sync(state: EditorState): SyncState | null { + const s = ySyncPluginKey.getState(state) as Partial | undefined; + return s?.type && s.binding && s.doc ? (s as SyncState) : null; +} + +/** Encodes the range from–to of the editor's document. */ +export function encodeAnchor(editor: Editor, from: number, to: number): CommentAnchor | null { + const s = sync(editor.state); + if (!s) return null; + const rel = (pos: number) => + toBase64(Y.encodeRelativePosition(absolutePositionToRelativePosition(pos, s.type, s.binding.mapping))); + return { from: rel(from), to: rel(to) }; +} + +/** + * The range an anchor points at in state's document, or null when its text + * was deleted. The Yjs document must already contain state's changes. + */ +export function decodeAnchor(state: EditorState, anchor: CommentAnchor | null): { from: number; to: number } | null { + const s = sync(state); + if (!s || !anchor?.from || !anchor.to) return null; + try { + const abs = (b64: string) => + relativePositionToAbsolutePosition(s.doc, s.type, Y.decodeRelativePosition(fromBase64(b64)), s.binding.mapping); + const from = abs(anchor.from); + const to = abs(anchor.to); + if (from === null || to === null || to <= from || to > state.doc.content.size) return null; + return { from, to }; + } catch { + return null; + } +} + +type Highlights = { marks: CommentMark[]; active: string; decos: DecorationSet }; + +const key = new PluginKey("docwellComments"); + +/** Replaces the highlighted comments (and which one is active). */ +export function setCommentMarks(editor: Editor, marks: CommentMark[], active = "") { + editor.view.dispatch(editor.state.tr.setMeta(key, { marks, active })); +} + +function draw(state: EditorState, marks: CommentMark[], active: string): DecorationSet { + const decos: Decoration[] = []; + for (const m of marks) { + const range = decodeAnchor(state, m.anchor); + if (!range) continue; + decos.push( + Decoration.inline(range.from, range.to, { + class: m.id === active ? "dw-comment is-active" : "dw-comment", + "data-comment": m.id, + }), + ); + } + return DecorationSet.create(state.doc, decos); +} + +/** + * Highlights commented text. Clicking a highlight calls onSelect with the + * comment's id, so the host can scroll its comment list to it. + * + * Anchors are resolved through Yjs only when the comments change or a remote + * edit arrives; a local edit reaches the Yjs document after the transaction, + * so for those the highlights are mapped through the edit instead. + */ +export const CommentHighlights = Extension.create<{ onSelect?: (id: string) => void }>({ + name: "commentHighlights", + + addOptions() { + return { onSelect: undefined }; + }, + + addProseMirrorPlugins() { + const onSelect = () => this.options.onSelect; + return [ + new Plugin({ + key, + state: { + init: () => ({ marks: [], active: "", decos: DecorationSet.empty }), + apply(tr, value, _old, state) { + const set = tr.getMeta(key) as { marks: CommentMark[]; active: string } | undefined; + if (set) return { ...set, decos: draw(state, set.marks, set.active) }; + if (!tr.docChanged || !value.marks.length) return value; + const remote = (tr.getMeta(ySyncPluginKey) as { isChangeOrigin?: boolean } | undefined)?.isChangeOrigin; + return { + ...value, + decos: remote ? draw(state, value.marks, value.active) : value.decos.map(tr.mapping, tr.doc), + }; + }, + }, + props: { + decorations: (state) => key.getState(state)?.decos ?? DecorationSet.empty, + handleClick(_view, _pos, event) { + const id = (event.target as HTMLElement | null)?.closest?.("[data-comment]")?.getAttribute("data-comment"); + if (!id) return false; + onSelect()?.(id); + return false; + }, + }, + }), + ]; + }, +}); diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css index 6403b5b..2bf74c9 100644 --- a/Packages/editor/src/editor.css +++ b/Packages/editor/src/editor.css @@ -149,3 +149,92 @@ white-space: nowrap; user-select: none; } + +/* "@" mentions. */ +.dw-prose .dw-mention { + border-radius: var(--radius-xs); + background: var(--color-accent-soft); + padding: 0 0.15em; + font-weight: 500; + white-space: nowrap; +} + +/* Commented text; the active comment's text stands out more. */ +.dw-prose .dw-comment { + background: color-mix(in srgb, var(--color-warning-soft) 70%, transparent); + border-bottom: 2px solid color-mix(in srgb, var(--color-warning) 55%, transparent); + cursor: pointer; +} +.dw-prose .dw-comment.is-active { + background: var(--color-warning-soft); + border-bottom-color: var(--color-warning); +} + +/* The "/" and "@" popups (suggestion.ts): the design system's slash menu, + drawn without a framework so every host can show it. */ +.dw-suggest { + position: fixed; + z-index: 60; + left: 0; + top: 0; + width: 20rem; + max-width: calc(100vw - 16px); + max-height: 22rem; + overflow-y: auto; + padding: 4px; + border: 1px solid var(--color-line); + border-radius: var(--radius-md); + background: var(--color-surface-raised); + box-shadow: var(--dw-shadow-menu); + font-family: var(--font-sans); +} +.dw-suggest__query { + padding: 8px 8px 4px; + font-family: var(--font-mono); + font-size: var(--text-ui-xs); + color: var(--color-ink-muted); +} +.dw-suggest__empty { + padding: 6px 8px; + font-size: var(--text-ui-sm); + color: var(--color-ink-muted); +} +.dw-suggest__item { + display: flex; + align-items: center; + gap: 12px; + padding: 6px 8px; + border-radius: var(--radius-sm); + cursor: pointer; +} +.dw-suggest__item.is-active { + background: var(--color-surface-hover); +} +.dw-suggest__icon { + display: grid; + place-items: center; + flex-shrink: 0; + width: 36px; + height: 36px; + border: 1px solid var(--color-line); + border-radius: var(--radius-sm); + background: var(--color-surface); + color: var(--color-ink-muted); +} +.dw-suggest__text { + display: flex; + flex-direction: column; + min-width: 0; +} +.dw-suggest__label { + font-size: var(--text-ui-md); + font-weight: 500; + color: var(--color-ink); +} +.dw-suggest__desc { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: var(--text-ui-xs); + color: var(--color-ink-muted); +} diff --git a/Packages/editor/src/extensions.ts b/Packages/editor/src/extensions.ts index f174416..f8b0231 100644 --- a/Packages/editor/src/extensions.ts +++ b/Packages/editor/src/extensions.ts @@ -5,7 +5,11 @@ import Collaboration from "@tiptap/extension-collaboration"; import CollaborationCaret from "@tiptap/extension-collaboration-caret"; import { Placeholder } from "@tiptap/extensions"; import StarterKit from "@tiptap/starter-kit"; +import { CommentHighlights } from "./comments"; import { DocwellImage, FileAttachment, FileDrop, type FileHost } from "./files"; +import { englishLabels, type EditorLabels } from "./labels"; +import { docwellMention, type MentionHost } from "./mention"; +import { SlashMenu, slashCommands } from "./slash"; import type { CollabProvider } from "./provider"; export interface CollabUser { @@ -19,6 +23,11 @@ export interface ExtensionOptions { collab?: { provider: CollabProvider; user: CollabUser }; /** Loads and uploads attachments; without it images use their src as is. */ files?: FileHost; + /** Finds people for "@" mentions. */ + mentions?: MentionHost; + labels?: EditorLabels; + /** Clicking highlighted comment text calls this with the comment id. */ + onCommentSelect?: (id: string) => void; onError?: (e: unknown) => void; } @@ -27,6 +36,7 @@ export interface ExtensionOptions { * must build its editor from this list so documents stay compatible. */ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] { + const labels = opts.labels ?? englishLabels; const list: AnyExtension[] = [ StarterKit.configure({ heading: { levels: [1, 2, 3] }, @@ -38,6 +48,9 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] { DocwellImage.configure({ host: opts.files }), FileAttachment.configure({ host: opts.files }), FileDrop.configure({ host: opts.files, onError: opts.onError }), + docwellMention(labels, opts.mentions), + SlashMenu.configure({ commands: slashCommands(labels, opts.files, opts.onError), labels }), + CommentHighlights.configure({ onSelect: opts.onCommentSelect }), ]; if (opts.collab) { list.push( diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts index bae0f27..2cf9b3c 100644 --- a/Packages/editor/src/index.ts +++ b/Packages/editor/src/index.ts @@ -3,5 +3,9 @@ export { default as DocwellEditor } from "./DocwellEditor.vue"; export type { JSONContent } from "@tiptap/core"; export { docwellExtensions, userColor, type CollabUser, type ExtensionOptions } from "./extensions"; +export { decodeAnchor, encodeAnchor, setCommentMarks, type CommentAnchor, type CommentMark } from "./comments"; +export { englishLabels, type EditorLabels } from "./labels"; +export type { MentionHost, Person } from "./mention"; +export { filterCommands, slashCommands, type SlashCommand } from "./slash"; export { insertFiles, type FileHost, type UploadedFile } from "./files"; export { CollabProvider, type CollabProviderOptions, type CollabStatus } from "./provider"; diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts new file mode 100644 index 0000000..2f3c076 --- /dev/null +++ b/Packages/editor/src/labels.ts @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/** + * The editor's own words (menus, buttons). The editor has no i18n of its own: + * hosts pass translated labels, and English is the default. + */ +export interface EditorLabels { + slashMenu: string; + noMatches: string; + slash: Record; + format: { + bold: string; + italic: string; + strike: string; + code: string; + link: string; + linkPrompt: string; + comment: string; + }; + mentions: string; + noPeople: string; +} + +export const englishLabels: EditorLabels = { + 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" }, + bullet: { label: "Bulleted list", description: "A simple list" }, + ordered: { label: "Numbered list", description: "A list with numbers" }, + 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" }, + }, + format: { + bold: "Bold", + italic: "Italic", + strike: "Strikethrough", + code: "Inline code", + link: "Link", + linkPrompt: "Link address (leave empty to remove the link)", + comment: "Comment", + }, + mentions: "Mention someone", + noPeople: "Nobody found", +}; diff --git a/Packages/editor/src/mention.ts b/Packages/editor/src/mention.ts new file mode 100644 index 0000000..c1f0d28 --- /dev/null +++ b/Packages/editor/src/mention.ts @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import Mention from "@tiptap/extension-mention"; +import type { EditorLabels } from "./labels"; +import { floatingList } from "./suggestion"; + +/** A person who can be mentioned. */ +export interface Person { + id: string; + label: string; + /** Shown under the name, e.g. the email address. */ + hint?: string; +} + +/** Finds people for "@" mentions; without one, typing "@" does nothing special. */ +export interface MentionHost { + search(query: string): Promise; +} + +/** + * "@" mentions. The node is always part of the schema so documents with + * mentions open everywhere; only editors with a host get the people picker. + */ +export function docwellMention(labels: EditorLabels, host?: MentionHost) { + return Mention.configure({ + HTMLAttributes: { class: "dw-mention" }, + renderText: ({ node }) => `@${node.attrs.label ?? node.attrs.id}`, + suggestion: { + char: "@", + allow: () => !!host, + items: async ({ query }) => (host ? (await host.search(query).catch(() => [])).slice(0, 8) : []), + render: floatingList({ + label: labels.mentions, + empty: labels.noPeople, + toItem: (p) => ({ label: p.label, description: p.hint, icon: "at" }), + pick: (props, p) => props.command({ id: p.id, label: p.label }), + }), + }, + }); +} diff --git a/Packages/editor/src/slash.ts b/Packages/editor/src/slash.ts new file mode 100644 index 0000000..5b022a1 --- /dev/null +++ b/Packages/editor/src/slash.ts @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { Extension, type Editor, type Range } from "@tiptap/core"; +import { PluginKey } from "@tiptap/pm/state"; +import Suggestion from "@tiptap/suggestion"; +import type { IconName } from "@docwell/ui/icons"; +import { insertFiles, type FileHost } from "./files"; +import type { EditorLabels } from "./labels"; +import { floatingList } from "./suggestion"; + +/** One "/" command. */ +export interface SlashCommand { + id: string; + label: string; + description: string; + icon: IconName; + /** Extra words the filter matches, e.g. "h1" for Heading 1. */ + keywords: string[]; + run: (editor: Editor, range: Range) => void; +} + +/** Opens the system file picker and resolves with the chosen files. */ +function pickFiles(accept: string): Promise { + return new Promise((resolve) => { + const input = document.createElement("input"); + input.type = "file"; + input.accept = accept; + input.multiple = true; + input.onchange = () => resolve([...(input.files ?? [])]); + input.click(); + }); +} + +/** The block commands, in menu order. */ +export function slashCommands(l: EditorLabels, files?: FileHost, onError?: (e: unknown) => void): SlashCommand[] { + const block = ( + id: string, + icon: IconName, + keywords: string[], + apply: (e: Editor, r: Range) => void, + ): SlashCommand => ({ + id, + icon, + keywords, + label: l.slash[id]?.label ?? id, + description: l.slash[id]?.description ?? "", + run: apply, + }); + const list: SlashCommand[] = [ + block("text", "text", ["paragraph", "p"], (e, r) => e.chain().focus().deleteRange(r).setParagraph().run()), + block("h1", "heading", ["heading", "title", "#"], (e, r) => + e.chain().focus().deleteRange(r).setHeading({ level: 1 }).run(), + ), + block("h2", "heading", ["heading", "subtitle", "##"], (e, r) => + e.chain().focus().deleteRange(r).setHeading({ level: 2 }).run(), + ), + block("h3", "heading", ["heading", "###"], (e, r) => + e.chain().focus().deleteRange(r).setHeading({ level: 3 }).run(), + ), + block("bullet", "list", ["list", "ul", "-"], (e, r) => e.chain().focus().deleteRange(r).toggleBulletList().run()), + block("ordered", "list-ordered", ["list", "ol", "1."], (e, r) => + e.chain().focus().deleteRange(r).toggleOrderedList().run(), + ), + block("quote", "quote", ["blockquote", ">"], (e, r) => e.chain().focus().deleteRange(r).toggleBlockquote().run()), + block("code", "code", ["codeblock", "```", "snippet"], (e, r) => + e.chain().focus().deleteRange(r).toggleCodeBlock().run(), + ), + block("divider", "divider", ["hr", "rule", "line", "---"], (e, r) => + e.chain().focus().deleteRange(r).setHorizontalRule().run(), + ), + ]; + if (files?.upload) { + const upload = (accept: string) => (e: Editor, r: Range) => { + e.chain().focus().deleteRange(r).run(); + void pickFiles(accept).then((picked) => insertFiles(e, files, picked).catch(onError)); + }; + list.push( + block("image", "image", ["picture", "photo", "img"], upload("image/*")), + block("file", "paperclip", ["attachment", "upload", "pdf"], upload("")), + ); + } + return list; +} + +/** Filters commands by what follows the "/": label, id or keywords. */ +export function filterCommands(commands: SlashCommand[], query: string): SlashCommand[] { + const q = query.trim().toLowerCase(); + if (!q) return commands; + return commands.filter( + (c) => + c.label.toLowerCase().includes(q) || c.id.startsWith(q) || c.keywords.some((k) => k.toLowerCase().startsWith(q)), + ); +} + +/** Typing "/" at the start of a word opens the block menu. */ +export const SlashMenu = Extension.create<{ commands: SlashCommand[]; labels: EditorLabels }>({ + name: "slashMenu", + + addOptions() { + return { commands: [], labels: undefined as unknown as EditorLabels }; + }, + + addProseMirrorPlugins() { + return [ + Suggestion({ + editor: this.editor, + pluginKey: new PluginKey("slashMenu"), + char: "/", + allowSpaces: false, + startOfLine: false, + // Not inside code, where "/" is just a character. + allow: ({ state, range }) => { + const $from = state.doc.resolve(range.from); + return !$from.parent.type.spec.code; + }, + items: ({ query }) => filterCommands(this.options.commands, query), + render: floatingList({ + label: this.options.labels.slashMenu, + empty: this.options.labels.noMatches, + showQuery: true, + toItem: (c) => ({ label: c.label, description: c.description, icon: c.icon }), + pick: (p, c) => c.run(p.editor, p.range), + }), + }), + ]; + }, +}); diff --git a/Packages/editor/src/suggestion.ts b/Packages/editor/src/suggestion.ts new file mode 100644 index 0000000..5545f25 --- /dev/null +++ b/Packages/editor/src/suggestion.ts @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { autoUpdate, computePosition, flip, offset, shift } from "@floating-ui/dom"; +import type { SuggestionKeyDownProps, SuggestionProps } from "@tiptap/suggestion"; +import { iconPaths, type IconName } from "@docwell/ui/icons"; + +/** One row of a suggestion list. */ +export interface ListItem { + label: string; + description?: string; + icon?: IconName; +} + +const svgNS = "http://www.w3.org/2000/svg"; + +function icon(name: IconName): SVGSVGElement { + const svg = document.createElementNS(svgNS, "svg"); + for (const [k, v] of Object.entries({ + width: "18", + height: "18", + viewBox: "0 0 24 24", + fill: "none", + stroke: "currentColor", + "stroke-width": "1.75", + "stroke-linecap": "round", + "stroke-linejoin": "round", + "aria-hidden": "true", + })) { + svg.setAttribute(k, v); + } + for (const d of iconPaths[name]) { + const path = document.createElementNS(svgNS, "path"); + path.setAttribute("d", d); + svg.append(path); + } + return svg; +} + +/** + * A Suggestion render() for a floating list ("/" commands, "@" mentions). It + * draws plain DOM in the design system's slash-menu style (see editor.css), + * so it works in every host, including the framework-free mobile bridge. The + * editor keeps focus: arrows move, Enter or Tab picks, Escape closes. + */ +export function floatingList(opts: { + label: string; + empty: string; + toItem: (item: T) => ListItem; + pick: (props: SuggestionProps, item: T) => void; + showQuery?: boolean; +}) { + return () => { + let box: HTMLDivElement | null = null; + let stop: (() => void) | null = null; + let current: SuggestionProps | null = null; + let active = 0; + + const choose = (i: number) => { + const item = current?.items[i]; + if (current && item !== undefined) opts.pick(current, item); + }; + + const draw = () => { + if (!box || !current) return; + const p = current; + box.replaceChildren(); + if (opts.showQuery) { + const q = document.createElement("div"); + q.className = "dw-suggest__query"; + q.textContent = `/${p.query}`; + box.append(q); + } + if (!p.items.length) { + const empty = document.createElement("div"); + empty.className = "dw-suggest__empty"; + empty.setAttribute("role", "status"); + empty.textContent = opts.empty; + box.append(empty); + return; + } + p.items.forEach((raw, i) => { + const it = opts.toItem(raw); + const row = document.createElement("div"); + row.className = i === active ? "dw-suggest__item is-active" : "dw-suggest__item"; + row.setAttribute("role", "option"); + row.setAttribute("aria-selected", String(i === active)); + // Pick on mousedown so the editor keeps focus. + row.addEventListener("mousedown", (e) => { + e.preventDefault(); + choose(i); + }); + const glyph = document.createElement("span"); + glyph.className = "dw-suggest__icon"; + glyph.append(icon(it.icon ?? "text")); + const text = document.createElement("span"); + text.className = "dw-suggest__text"; + const label = document.createElement("span"); + label.className = "dw-suggest__label"; + label.textContent = it.label; + text.append(label); + if (it.description) { + const desc = document.createElement("span"); + desc.className = "dw-suggest__desc"; + desc.textContent = it.description; + text.append(desc); + } + row.append(glyph, text); + box!.append(row); + }); + box.querySelector(".is-active")?.scrollIntoView({ block: "nearest" }); + }; + + const place = () => { + const rect = current?.clientRect?.(); + if (!box || !rect) return; + const anchor = { getBoundingClientRect: () => current?.clientRect?.() ?? rect }; + stop?.(); + stop = autoUpdate(anchor, box, () => { + if (!box) return; + void computePosition(anchor, box, { + placement: "bottom-start", + strategy: "fixed", + middleware: [offset(6), flip(), shift({ padding: 8 })], + }).then(({ x, y }) => { + if (box) Object.assign(box.style, { left: `${x}px`, top: `${y}px` }); + }); + }); + }; + + const close = () => { + stop?.(); + stop = null; + box?.remove(); + box = null; + }; + + return { + onStart(p: SuggestionProps) { + current = p; + active = 0; + box = document.createElement("div"); + box.className = "dw-suggest"; + box.setAttribute("role", "listbox"); + box.setAttribute("aria-label", opts.label); + document.body.append(box); + draw(); + place(); + }, + onUpdate(p: SuggestionProps) { + if (p.items !== current?.items) active = 0; + current = p; + draw(); + place(); + }, + onKeyDown({ event }: SuggestionKeyDownProps) { + const n = current?.items.length ?? 0; + if (event.key === "Escape") { + close(); + return true; + } + if (!n) return false; + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + active = (active + (event.key === "ArrowDown" ? 1 : -1) + n) % n; + draw(); + return true; + } + if (event.key === "Enter" || event.key === "Tab") { + choose(active); + return true; + } + return false; + }, + onExit() { + current = null; + close(); + }, + }; + }; +} diff --git a/Packages/ui/package.json b/Packages/ui/package.json index e89d59c..a471fd0 100644 --- a/Packages/ui/package.json +++ b/Packages/ui/package.json @@ -7,6 +7,7 @@ "main": "./src/index.ts", "exports": { ".": "./src/index.ts", + "./icons": "./src/icons.ts", "./theme.css": "./src/theme.css" }, "peerDependencies": { diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 5ef2eff..c0a5664 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -1814,3 +1814,57 @@ class SharedPage { 'pages': pages.map((e) => e.toJson()).toList(), }; } + +class Comment { + const Comment({ + required this.id, + required this.page, + required this.author, + required this.body, + required this.quote, + required this.anchor, + required this.created, + required this.canDelete, + }); + + factory Comment.fromJson(Map json) => Comment( + id: json['id'] as String, + page: json['page'] as String, + author: MemberUser.fromJson(json['author'] as Map), + body: json['body'] as String, + quote: json['quote'] as String, + anchor: json['anchor'] == null + ? null + : json['anchor'] as Map, + created: json['created'] as String, + canDelete: json['canDelete'] as bool, + ); + + final String id; + + final String page; + + final MemberUser author; + + final String body; + + final String quote; + + /// As sent when the comment was created; null when there was none + final Map? anchor; + + final String created; + + final bool canDelete; + + Map toJson() => { + 'id': id, + 'page': page, + 'author': author.toJson(), + 'body': body, + 'quote': quote, + 'anchor': anchor, + 'created': created, + 'canDelete': canDelete, + }; +} diff --git a/Server/internal/access/spaces.go b/Server/internal/access/spaces.go index ad72d3d..8ebcabe 100644 --- a/Server/internal/access/spaces.go +++ b/Server/internal/access/spaces.go @@ -105,6 +105,28 @@ func EditPages(spaceRole string) error { return nil } +// CommentPages (writing comments) needs commenter. +func CommentPages(spaceRole string) error { + if err := ViewSpace(spaceRole); err != nil { + return err + } + if !SpaceAtLeast(spaceRole, SpaceCommenter) { + return apperr.Forbidden("commenter role required") + } + return nil +} + +// DeleteComment: authors delete their own comments, space admins any. +func DeleteComment(actorID, authorID, spaceRole string) error { + if actorID != "" && actorID == authorID { + return nil + } + if !SpaceAtLeast(spaceRole, SpaceAdmin) { + return apperr.Forbidden("only the author or a space admin can delete this comment") + } + return nil +} + // PurgePage (permanent delete from the trash) needs space admin. func PurgePage(spaceRole string) error { if err := ViewSpace(spaceRole); err != nil { diff --git a/Server/internal/access/spaces_test.go b/Server/internal/access/spaces_test.go index 780e09e..d6ae730 100644 --- a/Server/internal/access/spaces_test.go +++ b/Server/internal/access/spaces_test.go @@ -96,3 +96,18 @@ func TestGroupRules(t *testing.T) { t.Error("SetSpaceGroup") } } + +func TestCommentRules(t *testing.T) { + if CommentPages(SpaceCommenter) != nil || CommentPages(SpaceViewer) == nil || CommentPages("") == nil { + t.Error("CommentPages needs commenter") + } + if DeleteComment("u", "u", SpaceViewer) != nil { + t.Error("authors delete their own") + } + if DeleteComment("u", "v", SpaceEditor) == nil || DeleteComment("u", "v", SpaceAdmin) != nil { + t.Error("only space admins delete other people's comments") + } + if DeleteComment("", "", SpaceViewer) == nil { + t.Error("an empty author is nobody's comment") + } +} diff --git a/Server/internal/api/api.gen.go b/Server/internal/api/api.gen.go index bff654c..fea137d 100644 --- a/Server/internal/api/api.gen.go +++ b/Server/internal/api/api.gen.go @@ -255,6 +255,19 @@ type BrandingSettings struct { Logo string `json:"logo"` } +// Comment defines model for Comment. +type Comment struct { + // Anchor As sent when the comment was created; null when there was none + Anchor *map[string]interface{} `json:"anchor"` + Author MemberUser `json:"author"` + Body string `json:"body"` + CanDelete bool `json:"canDelete"` + Created string `json:"created"` + Id string `json:"id"` + Page string `json:"page"` + Quote string `json:"quote"` +} + // CreateInviteRequest defines model for CreateInviteRequest. type CreateInviteRequest struct { Email openapi_types.Email `json:"email"` @@ -794,6 +807,16 @@ type UploadAttachmentMultipartBody struct { File openapi_types.File `json:"file"` } +// CreateCommentJSONBody defines parameters for CreateComment. +type CreateCommentJSONBody struct { + // Anchor The editor's encoding of the commented range (opaque to the server) + Anchor *map[string]interface{} `json:"anchor,omitempty"` + Body string `json:"body"` + + // Quote The commented text + Quote *string `json:"quote,omitempty"` +} + // SavePageContentJSONBody defines parameters for SavePageContent. type SavePageContentJSONBody struct { // Content Tiptap JSON with type "doc" @@ -888,6 +911,12 @@ type SetWorkspaceMemberJSONBody struct { Role WorkspaceRole `json:"role"` } +// ListPeopleParams defines parameters for ListPeople. +type ListPeopleParams struct { + Q *string `form:"q,omitempty" json:"q,omitempty"` + Limit *int `form:"limit,omitempty" json:"limit,omitempty"` +} + // ListRecentPagesParams defines parameters for ListRecentPages. type ListRecentPagesParams struct { Limit *int `form:"limit,omitempty" json:"limit,omitempty"` @@ -963,6 +992,9 @@ type UpdatePageJSONRequestBody UpdatePageJSONBody // UploadAttachmentMultipartRequestBody defines body for UploadAttachment for multipart/form-data ContentType. type UploadAttachmentMultipartRequestBody UploadAttachmentMultipartBody +// CreateCommentJSONRequestBody defines body for CreateComment for application/json ContentType. +type CreateCommentJSONRequestBody CreateCommentJSONBody + // SavePageContentJSONRequestBody defines body for SavePageContent for application/json ContentType. type SavePageContentJSONRequestBody SavePageContentJSONBody diff --git a/Server/internal/directory/comments.go b/Server/internal/directory/comments.go new file mode 100644 index 0000000..b0a633e --- /dev/null +++ b/Server/internal/directory/comments.go @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "docwell/server/internal/access" + "docwell/server/internal/apperr" + "docwell/server/internal/store/pocketbase" +) + +// ---- Inline comments ------------------------------------------------------- + +type Comment struct { + ID string `json:"id"` + Page string `json:"page"` + Author MemberUser `json:"author"` + Body string `json:"body"` + Quote string `json:"quote"` + // Anchor is the editor's encoding of the commented range; the server + // stores it without looking inside. + Anchor json.RawMessage `json:"anchor"` + Created string `json:"created"` + CanDelete bool `json:"canDelete"` +} + +type commentRecord struct { + ID string `json:"id"` + Page string `json:"page"` + Author string `json:"author"` + Body string `json:"body"` + Quote string `json:"quote"` + Anchor json.RawMessage `json:"anchor"` + Created string `json:"created"` + Expand struct { + Author *struct { + ID string `json:"id"` + Email string `json:"email"` + Name string `json:"name"` + } `json:"author"` + } `json:"expand"` +} + +func (r commentRecord) view(c access.Caller, role string) Comment { + out := Comment{ + ID: r.ID, Page: r.Page, Body: r.Body, Quote: r.Quote, Anchor: r.Anchor, Created: r.Created, + CanDelete: access.DeleteComment(c.ID, r.Author, role) == nil, + } + if len(out.Anchor) == 0 { + out.Anchor = json.RawMessage("null") + } + if a := r.Expand.Author; a != nil { + out.Author = MemberUser{ID: a.ID, Email: a.Email, Name: a.Name} + } + return out +} + +// ListComments lists a page's comments, oldest first (viewer). +func (s *Service) ListComments(ctx context.Context, c access.Caller, pageID string) ([]Comment, error) { + p, a, err := s.pageFor(ctx, c, pageID) + if err != nil { + return nil, err + } + recs, err := listAll[commentRecord](ctx, s, "comments", pocketbase.ListOptions{ + Filter: fmt.Sprintf("page = '%s'", p.ID), Sort: "created", Expand: "author", + }) + if err != nil { + return nil, err + } + out := make([]Comment, 0, len(recs)) + for _, r := range recs { + out = append(out, r.view(c, a.role)) + } + return out, nil +} + +type CreateCommentInput struct { + Body string `json:"body"` + Quote string `json:"quote"` + Anchor json.RawMessage `json:"anchor"` +} + +// CreateComment adds a comment to a page (commenter; not in the trash). +func (s *Service) CreateComment(ctx context.Context, c access.Caller, pageID string, in CreateCommentInput) (Comment, error) { + p, a, err := s.pageFor(ctx, c, pageID) + if err != nil { + return Comment{}, err + } + if err := access.CommentPages(a.role); err != nil { + return Comment{}, err + } + if p.DeletedAt != "" { + return Comment{}, apperr.Invalid("restore the page from the trash first") + } + body := strings.TrimSpace(in.Body) + switch { + case body == "": + return Comment{}, apperr.InvalidFields(map[string]string{"body": "Write something first."}) + case len(body) > 5000: + return Comment{}, apperr.InvalidFields(map[string]string{"body": "The comment is too long (max 5000)."}) + case len(in.Anchor) > 4096: + return Comment{}, apperr.InvalidFields(map[string]string{"anchor": "The anchor is too large."}) + } + quote := strings.TrimSpace(in.Quote) + if r := []rune(quote); len(r) > 500 { + quote = string(r[:500]) + } + fields := map[string]any{"page": p.ID, "workspace": p.Workspace, "author": c.ID, "body": body, "quote": quote} + if len(in.Anchor) > 0 && json.Valid(in.Anchor) { + fields["anchor"] = in.Anchor + } + rec, err := pocketbase.Create[commentRecord](ctx, s.pb, "comments", fields) + if err != nil { + return Comment{}, mapPB(err, "page not found") + } + rec, err = pocketbase.GetExpand[commentRecord](ctx, s.pb, "comments", rec.ID, "author") + if err != nil { + return Comment{}, mapPB(err, "comment not found") + } + return rec.view(c, a.role), nil +} + +// DeleteComment removes a comment (its author, or a space admin). +func (s *Service) DeleteComment(ctx context.Context, c access.Caller, id string) error { + if !validID(id) { + return apperr.NotFound("comment not found") + } + rec, err := pocketbase.Get[commentRecord](ctx, s.pb, "comments", id) + if err != nil { + return mapPB(err, "comment not found") + } + _, a, err := s.pageFor(ctx, c, rec.Page) + if err != nil { + return apperr.NotFound("comment not found") + } + if err := access.DeleteComment(c.ID, rec.Author, a.role); err != nil { + return err + } + return mapPB(s.pb.Delete(ctx, "comments", rec.ID), "comment not found") +} diff --git a/Server/internal/directory/people.go b/Server/internal/directory/people.go new file mode 100644 index 0000000..9316dd0 --- /dev/null +++ b/Server/internal/directory/people.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package directory + +import ( + "context" + "fmt" + "sort" + "strings" + + "docwell/server/internal/access" + "docwell/server/internal/auth" + "docwell/server/internal/store/pocketbase" +) + +// ListPeople finds people in a workspace by name or email, for mentions. Any +// member may look; it lists the explicit members and the organization's +// admins (who are in every workspace through the cascade). +func (s *Service) ListPeople(ctx context.Context, c access.Caller, wsID, query string, limit int) ([]MemberUser, error) { + ws, _, err := s.workspaceFor(ctx, c, wsID) + if err != nil { + return nil, err + } + if limit <= 0 || limit > 50 { + limit = 10 + } + q := filterValue(query) + match := "" + if q != "" { + match = fmt.Sprintf(" && (user.name ~ '%s' || user.email ~ '%s')", q, q) + } + members, err := pocketbase.List[memberRecord](ctx, s.pb, "workspace_members", pocketbase.ListOptions{ + PerPage: limit, Filter: fmt.Sprintf("workspace = '%s'", ws.ID) + match, Expand: "user", + }) + if err != nil { + return nil, err + } + seen := map[string]bool{} + out := []MemberUser{} + add := func(u *auth.UserRecord) { + if u == nil || seen[u.ID] || u.Status == "disabled" { + return + } + seen[u.ID] = true + out = append(out, MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}) + } + for _, m := range members.Items { + add(m.Expand.User) + } + adminMatch := "" + if q != "" { + adminMatch = fmt.Sprintf(" && (name ~ '%s' || email ~ '%s')", q, q) + } + admins, err := pocketbase.List[auth.UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{ + PerPage: limit, Filter: fmt.Sprintf("organization = '%s' && role = 'admin'", ws.Organization) + adminMatch, + }) + if err != nil { + return nil, err + } + for i := range admins.Items { + add(&admins.Items[i]) + } + sort.Slice(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) }) + return out[:min(limit, len(out))], nil +} diff --git a/Server/internal/httpapi/auth.go b/Server/internal/httpapi/auth.go index 2014c0b..ed65313 100644 --- a/Server/internal/httpapi/auth.go +++ b/Server/internal/httpapi/auth.go @@ -151,6 +151,7 @@ func (a *api) routes(mux *routeMux) { a.searchRoutes(mux) a.transferRoutes(mux) a.shareRoutes(mux) + a.commentRoutes(mux) } func (a *api) decode(w http.ResponseWriter, r *http.Request, v any) bool { diff --git a/Server/internal/httpapi/comments.go b/Server/internal/httpapi/comments.go new file mode 100644 index 0000000..1b36ecf --- /dev/null +++ b/Server/internal/httpapi/comments.go @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +package httpapi + +import ( + "context" + "net/http" + + "docwell/server/internal/access" + "docwell/server/internal/directory" +) + +// CommentService is the part of directory.Service for inline comments. +type CommentService interface { + ListComments(ctx context.Context, c access.Caller, pageID string) ([]directory.Comment, error) + CreateComment(ctx context.Context, c access.Caller, pageID string, in directory.CreateCommentInput) (directory.Comment, error) + DeleteComment(ctx context.Context, c access.Caller, id string) error +} + +func (a *api) commentRoutes(mux *routeMux) { + mux.HandleFunc("GET /api/v1/pages/{id}/comments", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + list, err := a.dir.ListComments(r.Context(), caller(r), r.PathValue("id")) + a.respond(w, list, err) + })) + mux.HandleFunc("POST /api/v1/pages/{id}/comments", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + var in directory.CreateCommentInput + if !a.decode(w, r, &in) { + return + } + cm, err := a.dir.CreateComment(r.Context(), caller(r), r.PathValue("id"), in) + a.respondStatus(w, http.StatusCreated, cm, err) + })) + mux.HandleFunc("DELETE /api/v1/comments/{id}", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + a.respondNoContent(w, a.dir.DeleteComment(r.Context(), caller(r), r.PathValue("id"))) + })) +} diff --git a/Server/internal/httpapi/directory.go b/Server/internal/httpapi/directory.go index 40b1bed..3161291 100644 --- a/Server/internal/httpapi/directory.go +++ b/Server/internal/httpapi/directory.go @@ -31,6 +31,7 @@ type DirectoryService interface { ListMembers(ctx context.Context, c access.Caller, wsID string) ([]directory.Member, error) SetMember(ctx context.Context, c access.Caller, wsID, email, role string) (directory.Member, error) RemoveMember(ctx context.Context, c access.Caller, wsID, userID string) error + ListPeople(ctx context.Context, c access.Caller, wsID, query string, limit int) ([]directory.MemberUser, error) SpaceService InviteService @@ -40,6 +41,7 @@ type DirectoryService interface { SearchService TransferService ShareService + CommentService } func caller(r *http.Request) access.Caller { @@ -139,6 +141,11 @@ func (a *api) directoryRoutes(mux *routeMux) { m, err := a.dir.SetMember(r.Context(), caller(r), r.PathValue("id"), in.Email, in.Role) a.respond(w, m, err) })) + mux.HandleFunc("GET /api/v1/workspaces/{id}/people", a.requireUser(func(w http.ResponseWriter, r *http.Request) { + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + people, err := a.dir.ListPeople(r.Context(), caller(r), r.PathValue("id"), r.URL.Query().Get("q"), limit) + a.respond(w, people, err) + })) mux.HandleFunc("DELETE /api/v1/workspaces/{id}/members/{userId}", a.requireUser(func(w http.ResponseWriter, r *http.Request) { a.respondNoContent(w, a.dir.RemoveMember(r.Context(), caller(r), r.PathValue("id"), r.PathValue("userId"))) })) diff --git a/Web-App/frontend/src/components/PageComments.vue b/Web-App/frontend/src/components/PageComments.vue new file mode 100644 index 0000000..937cc5d --- /dev/null +++ b/Web-App/frontend/src/components/PageComments.vue @@ -0,0 +1,146 @@ + + + +