Add Word export, column dragging and the rest of editor parity
CI / go (Server) (push) Failing after 8m51s
CI / go (Web-App) (push) Successful in 11m46s
CI / mobile (push) Failing after 3m44s
CI / docker (push) Successful in 54m15s
Docs / build (push) Successful in 12m28s
Docs / deploy (push) Skipped
CI / frontend (push) Failing after 7m47s
CI / desktop (ubuntu-latest) (push) Successful in 1h27m22s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s

Word export: pages download as .docx from the page menu and from
GET /pages/{id}/export?format=docx. The file keeps headings, alignment,
lists, to-dos, quotes, callouts, code, tables with a repeating header
row, text formatting, colours, highlights, links and the page's images.
Word import now reads callouts, to-dos and shaded highlights, so a page
exported to Word imports back as it was. The user guide says how to move
pages to Notion, whose Import reads Word and Markdown files.

Editor:
- Columns move like rows: a grip on the column's top edge drags it, and
  the table toolbar and Ctrl+Alt+Left/Right move it from the keyboard.
  Row and column moving share tablemove.ts.
- Ctrl+Shift+C copies a link to the block the cursor is in.
- Headings 4 to 6 sit under "Other headings" in the slash menu; a search
  still finds them directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-14 13:01:06 +01:00
1 parent d28f1e02db
commit 3dea2bb2f4
28 files changed
+1630 -432

No files matched your search

+14 -8
View File
@@ -14,8 +14,13 @@ Pages save as you type, and everyone with the page open sees changes and cursors
| To | Do this |
| --- | --- |
| Insert a heading, list, quote, code block, divider, image or file | Type `/` and pick from the menu (keep typing to filter) |
| Format text or add a link | Select it and use the toolbar that appears |
| Insert a heading, list, to-do list, table, callout, quote, code block, divider, image or file | Type `/` and pick from the menu (keep typing to filter); headings 4–6 are under **Other headings** |
| Start a to-do list | Type `[] ` at the start of a line |
| Format text, colour or highlight it, align it, or add a link | Select it and use the toolbar that appears |
| Move, duplicate, turn into another kind, or delete a block | Point at it and drag the ⠿ grip in the margin, or click the grip for a menu |
| Change a table | Click in it for the table toolbar; drag the grips on a row's left edge or a column's top edge to move it (or Ctrl+Alt+arrow keys) |
| Copy a link to a block | Ctrl+Shift+C in the desktop app, or the link button in the margin or the toolbar |
| Headings by keyboard | Ctrl+Shift+1 to 6, and Ctrl+Shift+0 for plain text |
| Mention someone | Type `@` and their name |
| Add an image or file | Paste or drop it, or use `/image`, `/file` or the paperclip in the header |
| Undo | Ctrl+Z (your own changes only) |
@@ -44,17 +49,18 @@ account. Turning it off makes the link stop working at once. Pages in the trash
## Import and export
- **Export:** the **⋯** menu in the page header saves the page as Markdown, HTML or PDF. PDFs are A4, with a bookmark
per heading and the page's images. Draw.io and Excalidraw diagrams become a link to their file, and Mermaid charts
show their source.
- **Export:** the **⋯** menu in the page header saves the page as Markdown, HTML, PDF or Word. PDFs are A4, with a
bookmark per heading and the page's images. Word files keep headings, lists, to-dos, callouts, tables, colours and
the page's images, and import back into Docwell as they were. Draw.io and Excalidraw diagrams become a link to their
file, and Mermaid charts show their source.
- **Import:** **Import** on a space's page list creates a page per Markdown (`.md`, `.txt`), HTML or Word (`.docx`)
file. A leading `# Heading`, or the Word document's title, becomes the page title. Word headings, lists, quotes,
links and images are kept. Up to 20 files at once.
tables, alignment, colours, links and images are kept. Up to 20 files at once.
- **From Notion:** in Notion, choose **Settings → Export**, pick **Markdown & CSV** or **HTML** and include subpages and
files. Import the `.zip` you get (up to 100 MB, 2000 pages) as it is. Docwell rebuilds the page tree, keeps links
between the pages, and stores images and files as attachments. Each database becomes a page that lists its rows,
with the row pages under it. Tables in pages and databases come in as one line per row, since the editor has no
tables yet.
with the row pages under it. Tables in pages, and databases, come in as tables; callouts and to-do lists are kept.
- **To Notion:** export the page as Word or Markdown, then import that file with **Import** in Notion's sidebar.
## Trash
+1 -1
View File
@@ -484,7 +484,7 @@ export function createClient(opts: ClientOptions) {
"DELETE",
`/api/v1/pages/${encodeURIComponent(id)}/access/groups/${encodeURIComponent(groupId)}`,
),
export: (id: string, format: "markdown" | "html" | "pdf") =>
export: (id: string, format: "markdown" | "html" | "pdf" | "docx") =>
download(`/api/v1/pages/${encodeURIComponent(id)}/export${query({ format })}`),
/** Records that the user opened the page, for their recent list. */
visit: (id: string) => post(`/api/v1/pages/${encodeURIComponent(id)}/visit`),
+4 -3
View File
@@ -1508,8 +1508,8 @@ export interface paths {
cookie?: never;
};
/**
* Download the page as Markdown, HTML or PDF
* @description Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open. PDFs are A4 with a bookmark per heading; images stored on the page are drawn in, diagrams become a link to their file and Mermaid charts show their source.
* Download the page as Markdown, HTML, PDF or Word
* @description Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open. PDFs are A4 with a bookmark per heading; images stored on the page are drawn in, diagrams become a link to their file and Mermaid charts show their source. Word files (docx) embed the page's images the same way and keep headings, lists, to-dos, callouts, tables, colours and alignment in a form Docwell imports back.
*/
get: operations["exportPage"];
put?: never;
@@ -5586,7 +5586,7 @@ export interface operations {
exportPage: {
parameters: {
query?: {
format?: "markdown" | "html" | "pdf";
format?: "markdown" | "html" | "pdf" | "docx";
};
header?: never;
path: {
@@ -5605,6 +5605,7 @@ export interface operations {
"text/markdown": string;
"text/html": string;
"application/pdf": string;
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": string;
};
};
400: components["responses"]["Error"];
+29 -29
View File
@@ -146,20 +146,20 @@ img.ProseMirror-separator {
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(wk,this.editor.getAttributes(Tk)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new E({props:{handlePaste:(e,t)=>{if((t.clipboardData?.getData(`text/html`))?.trim())return!1;let n=t.clipboardData?.getData(`text/plain`);if(!n)return!1;let r=vk(n);if(!r)return!1;try{let t=e.state.schema.nodeFromJSON(r),n=e.state.tr.replaceSelectionWith(t);return e.dispatch(n),!0}catch{return!1}}}})]},addInputRules(){let e=(e,t)=>(!t.attrs.type||t.attrs.type===`1`)&&t.childCount+t.attrs.start===+e[1],t=Gp({find:Ek,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Gp({find:Ek,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(Tk)}),joinPredicate:e,editor:this.editor})),[t]}}),kk=/^\s*(\[([( |x])?\])\s$/,Ak=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,jk=(e,t,n)=>{var r;return(n==null||(r=n.checkboxLabel)==null?void 0:r.call(n,e,t))||`Task item checkbox for ${e.textContent||`empty task item`}`},Mk=Jp.create({name:`taskItem`,addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:`taskList`,a11y:void 0}},content(){return this.options.nested?`paragraph block*`:`paragraph+`},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:e=>{let t=e.getAttribute(`data-checked`);return t===``||t===`true`},renderHTML:e=>({"data-checked":e.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:e=>e.querySelector(`div`)??e}]},renderHTML({node:e,HTMLAttributes:t}){return[`li`,A(this.options.HTMLAttributes,t,{"data-type":this.name}),[`label`,[`input`,{type:`checkbox`,checked:e.attrs.checked?`checked`:null}],[`span`]],[`div`,0]]},parseMarkdown:(e,t)=>{let n=[];if(e.tokens&&e.tokens.length>0?n.push(t.createNode(`paragraph`,{},t.parseInline(e.tokens))):e.text?n.push(t.createNode(`paragraph`,{},[t.createNode(`text`,{text:e.text})])):n.push(t.createNode(`paragraph`,{},[])),e.nestedTokens&&e.nestedTokens.length>0){let r=t.parseChildren(e.nestedTokens);n.push(...r)}return t.createNode(`taskItem`,{checked:e.checked||!1},n)},renderMarkdown:(e,t)=>op(e,t,`- [${e.attrs?.checked?`x`:` `}] `,void 0,{indentMainContent:!0}),addExtensions(){return this.options.nested?[kO(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){let e={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...e,Tab:()=>this.editor.commands.sinkListItem(this.name)}:e},addNodeView(){return({node:e,HTMLAttributes:t,getPos:n,editor:r})=>{let i=document.createElement(`li`),a=document.createElement(`label`),o=document.createElement(`span`),s=document.createElement(`input`),c=document.createElement(`div`);o.style.cssText=Ak;let l=e=>{let t=jk(e,e.attrs.checked,this.options.a11y);s.setAttribute(`aria-label`,t),o.textContent=t};l(e),a.contentEditable=`false`,s.type=`checkbox`,s.addEventListener(`mousedown`,e=>e.preventDefault()),s.addEventListener(`change`,t=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){s.checked=!s.checked;return}let{checked:i}=t.target;r.isEditable&&typeof n==`function`&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:e})=>{let t=n();if(typeof t!=`number`)return!1;let r=e.doc.nodeAt(t);return e.setNodeMarkup(t,void 0,{...r?.attrs,checked:i}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(e,i)||(s.checked=!s.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([e,t])=>{i.setAttribute(e,t)}),i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,a.append(s,o),i.append(a,c),Object.entries(t).forEach(([e,t])=>{i.setAttribute(e,t)});let u=new Set(Object.keys(t));return{dom:i,contentDOM:c,update:e=>{if(e.type!==this.type)return!1;i.dataset.checked=e.attrs.checked,s.checked=e.attrs.checked,l(e);let t=r.extensionManager.attributes,n=Lu(e,t),a=new Set(Object.keys(n)),o=this.options.HTMLAttributes;return u.forEach(e=>{a.has(e)||(e in o?i.setAttribute(e,o[e]):i.removeAttribute(e))}),Object.entries(n).forEach(([e,t])=>{t==null?e in o?i.setAttribute(e,o[e]):i.removeAttribute(e):i.setAttribute(e,t)}),u=a,!0}}}},addInputRules(){return[Gp({find:kk,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),Nk=Jp.create({name:`taskList`,addOptions(){return{itemTypeName:`taskItem`,HTMLAttributes:{}}},group:`block list`,content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`uLine truncated
`):``,markdownTokenizer:{name:`taskList`,level:`block`,start(e){let t=e.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)?.index;return t===void 0?-1:t},tokenize(e,t,n){let r=e=>{let t=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(t){let r={type:`taskList`,raw:t.raw,items:t.items},i=e.slice(t.raw.length);return i.trim()?[r,...n.blockTokens(i)]:[r]}return n.blockTokens(e)},i=rp(e,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:e=>({indentLevel:e[1].length,mainContent:e[4],checked:e[3].toLowerCase()===`x`}),createToken:(e,t)=>({type:`taskItem`,raw:``,mainContent:e.mainContent,indentLevel:e.indentLevel,checked:e.checked,text:e.mainContent,tokens:n.inlineTokens(e.mainContent),nestedTokens:t}),customNestedParser:r},n);if(i)return{type:`taskList`,raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:e})=>e.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});Tp.create({name:`listKit`,addExtensions(){let e=[];return this.options.bulletList!==!1&&e.push(TO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push($O.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(ck.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(Ok.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(Mk.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(Nk.configure(this.options.taskList)),e}});var Pk=`&nbsp;`,Fk=`\xA0`,Ik=Jp.create({name:`paragraph`,priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:`block`,content:`inline*`,parseHTML(){return[{tag:`p`}]},renderHTML({HTMLAttributes:e}){return[`p`,A(this.options.HTMLAttributes,e),0]},parseMarkdown:(e,t)=>{let n=e.tokens||[];if(n.length===1&&n[0].type===`image`)return t.parseChildren([n[0]]);let r=t.parseInline(n);return n.length===1&&n[0].type===`text`&&(n[0].raw===Pk||n[0].text===Pk||n[0].raw===Fk||n[0].text===Fk)&&r.length===1&&r[0].type===`text`&&(r[0].text===Pk||r[0].text===Fk)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?Pk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Lk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Rk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,zk=_p.create({name:`strike`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`s`},{tag:`del`},{tag:`strike`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`line-through`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`s`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`del`,parseMarkdown:(e,t)=>t.applyMark(`strike`,t.parseInline(e.tokens||[])),renderMarkdown:(e,t)=>`~~${t.renderChildren(e)}~~`,addCommands(){return{setStrike:()=>({commands:e})=>e.setMark(this.name),toggleStrike:()=>({commands:e})=>e.toggleMark(this.name),unsetStrike:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[Hp({find:Lk,type:this.type})]},addPasteRules(){return[Yp({find:Rk,type:this.type})]}}),Bk=Jp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),Vk=_p.create({name:`underline`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`u`},{style:`text-decoration`,consuming:!1,getAttrs:e=>e.includes(`underline`)?{}:!1}]},renderHTML({HTMLAttributes:e}){return[`u`,A(this.options.HTMLAttributes,e),0]},parseMarkdown(e,t){return t.applyMark(this.name||`underline`,t.parseInline(e.tokens||[]))},renderMarkdown(e,t){return`<u>${t.renderChildren(e)}</u>`},markdownTokenizer:{name:`underline`,level:`inline`,start(e){return e.toLowerCase().indexOf(`<u>`)},tokenize(e,t,n){if(!/^<u>/i.test(e))return;let r=/\\[\s\S]|`+|<\/u>/gi;r.lastIndex=3;let i=r.exec(e);for(;i;){if(i[0].startsWith("`")){let t=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.exec(e.slice(i.index));t&&(r.lastIndex=i.index+t[0].length)}else if(!i[0].startsWith(`\\`)){let t=e.slice(3,i.index);return t?{type:`underline`,raw:e.slice(0,r.lastIndex),text:t,tokens:n.inlineTokens(t)}:void 0}i=r.exec(e)}}},addCommands(){return{setUnderline:()=>({commands:e})=>e.setMark(this.name),toggleLine truncated
`).length:0;c!==o&&(o=c,i.textContent=Array.from({length:c},(e,t)=>t+1).join(`
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),jj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Mj(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Nj={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-down":[`M6 10l6 6 6-6`],"chevron-up":[`M6 14l6-6 6 6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],lock:[`M6 11h12v9H6z`,`M8.5 11V8a3.5 3.5 0 0 1 7 0v3`],trash:[`M4 7h16`,`M10 4h4`,`M6 7l1 13h10l1-13`,`M10 11v6`,`M14 11v6`],settings:[`M4 7h9`,`M17 7h3`,`M15 5v4`,`M4 17h3`,`M11 17h9`,`M9 15v4`],menu:[`M4 7h16`,`M4 12h16`,`M4 17h16`],close:[`M6 6l12 12`,`M18 6L6 18`],open:[`M8 16L16 8`,`M9 8h7v7`],restore:[`M4.5 13a7.5 7.5 0 1 0 2.2-6.3`,`M5 4v4h4`],"sign-out":[`M14 4h5v16h-5`,`M10 8l-4 4 4 4`,`M6 12h9`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8 20H4v-4z`],sigma:[`M18 6V4H6l6 8lLine truncated
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:aP(e)).join(`
`)}function sP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function cP(e,t){return t?e.split(t).join(`
`):e}function lP(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function uP(e,t,n={}){if(!e||!e.content||e.content.length===0)return``;let r=[];e.content.forEach(e=>{let i=[];e.content&&e.content.forEach(e=>{let r=``;r=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>cP(t.renderChildren(e),n.cellLineSeparator)).join(`
`):cP(e.content?t.renderChildren(e.content):``,n.cellLineSeparator);let a=lP(sP(r.replace(/[ \t]*\r?\n[ \t]*/g,`<br>`))),o=e.type===`tableHeader`,s=RN(e.attrs);i.push({text:a,isHeader:o,align:s})}),r.push(i)});let i=r.reduce((e,t)=>Math.max(e,t.length),0);if(i===0)return``;let a=Array.from({length:i}).fill(0);r.forEach(e=>{for(let t=0;t<i;t+=1){let n=(e[t]?.text||``).length;n>a[t]&&(a[t]=n),a[t]<3&&(a[t]=3)}});let o=(e,t)=>e+` `.repeat(Math.max(0,t-e.length)),s=r[0],c=s.some(e=>e.isHeader),l=Array.from({length:i}).fill(null);r.forEach(e=>{for(let t=0;t<i;t+=1)!l[t]&&e[t]?.align&&(l[t]=e[t].align)});let u=`
`,d=Array.from({length:i}).map((e,t)=>c&&s[t]&&s[t].text||``);return u+=`| ${d.map((e,t)=>o(e,a[t])).join(` | `)} |\n`,u+=`| ${a.map((e,t)=>{let n=Math.max(3,e),r=l[t];return r===`left`?`:${`-`.repeat(n)}`:r===`right`?`${`-`.repeat(n)}:`:r===`center`?`:${`-`.repeat(n)}:`:`-`.repeat(n)}).join(` | `)} |\n`,(c?r.slice(1):r).forEach(e=>{u+=`| ${Array.from({length:i}).fill(0).map((t,n)=>o(e[n]&&e[n].text||``,a[n])).join(` | `)} |\n`}),u}var dP=new D(`preserveCellSelectionOnContextMenu`);function fP(e,t){let n=e.posAtCoords({left:t.clientX,top:t.clientY});if(n)return n.pos;if(!(t.target instanceof Node))return null;try{return e.posAtDOM(t.target,0)}catch{return null}}function pP(e,t){let n=!1;return e.forEachCell((e,r)=>{t>=r&&t<r+e.nodeSize&&(n=!0)}),n}function mP(){return new E({key:dP,props:{handleDOMEvents:{mousedown(e,t){if(t.button!==2)return!1;let{selection:n}=e.state;if(!nP(n)||n.ranges.length<2)return!1;let r=fP(e,t);return r==null||!pP(n,r)?!1:(t.preventDefault(),!0)}}}})}var hP=Jp.create({name:`table`,addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:ZN,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:`tableRow+`,tableRole:`table`,isolating:!0,group:`block`,parseHTML(){return[{tag:`table`}]},renderHTML({node:e,HTMLAttributes:t}){let{colgroup:n,tableWidth:r,tableMinWidth:i}=QN(e,this.options.cellMinWidth),a=t.style;function o(){return a||(r?`width: ${r}`:`min-width: ${i}`)}let s=[`table`,A(this.options.HTMLAttributes,t,{style:o()}),n,[`tbody`,0]];return this.options.renderWrapper?[`div`,{class:`tableWrapper`},s]:s},parseMarkdown:(e,t)=>{let n=[],r=Array.isArray(e.align)?e.align:[];if(e.header){let i=[];e.header.forEach((e,n)=>{let a=IN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableHeader`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}return e.rows&&e.rows.forEach(e=>{let i=[];e.forEach((e,n)=>{let a=IN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableCell`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}),t.createNode(`table`,void 0,n)},renderMarkdown:(e,t)=>uP(e,t),markdownTokenizer:{name:`table`,level:`block`,start:e=>{let t=e.split(`
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),jj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Mj(e,t,n,r){let i=!1,a=null,o=null,s=document.createElement(`div`);return s.className=`dw-pdf__status`,s.textContent=r.blocks.pdfLoading,e.replaceChildren(s),(async()=>{try{let c=await n();if(i)return;o=c.getDocument({url:t});let l=await o.promise;if(i)return;s.remove();let u=Math.max(e.clientWidth-2,200),d=window.devicePixelRatio||1;a=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target;a?.unobserve(e),p(e,Number(e.dataset.page))}},{root:e,rootMargin:`400px 0px`});let f=(await l.getPage(1)).getViewport({scale:1});for(let t=1;t<=l.numPages;t++){let n=document.createElement(`div`);n.className=`dw-pdf__page`,n.dataset.page=String(t),n.style.aspectRatio=`${f.width} / ${f.height}`,n.setAttribute(`aria-label`,r.blocks.pdfPage.replace(`{n}`,String(t))),e.append(n),a.observe(n)}async function p(e,t){let n=await l.getPage(t);if(i)return;let r=u/n.getViewport({scale:1}).width,a=n.getViewport({scale:r*d}),o=document.createElement(`canvas`);o.width=Math.floor(a.width),o.height=Math.floor(a.height),e.style.aspectRatio=`${a.width} / ${a.height}`,e.append(o),await n.render({canvas:o,viewport:a}).promise}}catch{i||(s.textContent=r.blocks.loadFailed)}})(),()=>{i=!0,a?.disconnect(),o?.destroy()}}var Nj={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-down":[`M6 10l6 6 6-6`],"chevron-up":[`M6 14l6-6 6 6`],plus:[`M12 5v14`,`M5 12h14`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14z`,`M16.5 16.5L20 20`],more:[`M6 12h.01`,`M12 12h.01`,`M18 12h.01`],drop:[`M12 4h7v7a7 7 0 1 1-7-7z`],info:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 11v5`,`M12 8h.01`],check:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8 12.5l2.5 2.5L16 9.5`],alert:[`M12 4l9 16H3z`,`M12 10v4`,`M12 17h.01`],error:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M9 9l6 6`,`M15 9l-6 6`],text:[`M5 6h14`,`M12 6v13`],heading:[`M6 5v14`,`M18 5v14`,`M6 12h12`],list:[`M9 6h11`,`M9 12h11`,`M9 18h11`,`M4.5 6h.01`,`M4.5 12h.01`,`M4.5 18h.01`],todo:[`M4 4h7v7H4z`,`M5.5 7.5l1.5 1.5 2.5-2.5`,`M14 7h6`,`M4 14h7v7H4z`,`M14 17h6`],code:[`M9 7l-5 5 5 5`,`M15 7l5 5-5 5`],quote:[`M6 6v12`,`M10 8h9`,`M10 12h9`,`M10 16h6`],image:[`M4 5h16v14H4z`,`M4 16l5-5 4 4 2-2 5 5`,`M15.5 8.5h.01`],table:[`M4 5h16v14H4z`,`M4 10h16`,`M4 15h16`,`M10 5v14`],lock:[`M6 11h12v9H6z`,`M8.5 11V8a3.5 3.5 0 0 1 7 0v3`],trash:[`M4 7h16`,`M10 4h4`,`M6 7l1 13h10l1-13`,`M10 11v6`,`M14 11v6`],settings:[`M4 7h9`,`M17 7h3`,`M15 5v4`,`M4 17h3`,`M11 17h9`,`M9 15v4`],menu:[`M4 7h16`,`M4 12h16`,`M4 17h16`],close:[`M6 6l12 12`,`M18 6L6 18`],open:[`M8 16L16 8`,`M9 8h7v7`],restore:[`M4.5 13a7.5 7.5 0 1 0 2.2-6.3`,`M5 4v4h4`],"sign-out":[`M14 4h5v16h-5`,`M10 8l-4 4 4 4`,`M6 12h9`],sidebar:[`M4 5h16v14H4z`,`M9.5 5v14`],home:[`M4 11l8-7 8 7`,`M6 9.5V20h12V9.5`,`M10 20v-5h4v5`],sun:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M12 3v1.5`,`M12 19.5V21`,`M3 12h1.5`,`M19.5 12H21`,`M5.6 5.6l1.1 1.1`,`M17.3 17.3l1.1 1.1`,`M5.6 18.4l1.1-1.1`,`M17.3 6.7l1.1-1.1`],moon:[`M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z`],monitor:[`M4 5h16v11H4z`,`M9 20h6`,`M12 16v4`],selector:[`M8 9l4-4 4 4`,`M8 15l4 4 4-4`],star:[`M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.9l-4.9 2.6.9-5.6-4-3.9 5.5-.8z`],clock:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M12 7v5l3 2`],calendar:[`M5 5h14a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z`,`M4 10h16`,`M8 3v4`,`M16 3v4`],share:[`M12 4v11`,`M8 8l4-4 4 4`,`M6 13v7h12v-7`],link:[`M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1`,`M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1`],upload:[`M12 16V4`,`M7 9l5-5 5 5`,`M4 20h16`],download:[`M12 4v12`,`M7 11l5 5 5-5`,`M4 20h16`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],paperclip:[`M18 11.5l-6.4 6.4a4.2 4.2 0 0 1-6-6l7-7a2.8 2.8 0 0 1 4 4l-7 7a1.4 1.4 0 0 1-2-2l6.4-6.4`],comment:[`M5 5h14v10H9l-4 4z`],at:[`M12 8a4 4 0 1 0 0 8a4 4 0 1 0 0-8z`,`M16 12v1.5a2.5 2.5 0 0 0 5 0V12a9 9 0 1 0-3.5 7.1`],bold:[`M7 5h6a3.5 3.5 0 0 1 0 7H7z`,`M7 12h7a3.5 3.5 0 0 1 0 7H7z`],italic:[`M10 5h8`,`M6 19h8`,`M14 5l-4 14`],strike:[`M5 12h14`,`M16 7.5A3.5 3 0 0 0 12.5 5h-1A3.5 3 0 0 0 8 8c0 4 8 3 8 7.5a3.5 3.5 0 0 1-3.5 3.5h-1A3.5 3 0 0 1 8 16.5`],underline:[`M7 4v7a5 5 0 0 0 10 0V4`,`M5 20h14`],"list-ordered":[`M10 6h10`,`M10 12h10`,`M10 18h10`,`M4 5l1.5-1v5`,`M4 15.5a1.5 1.5 0 0 1 3 .5L4 19h3`],divider:[`M4 12h16`],globe:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M3 12h18`,`M12 3c2.5 2.5 3.5 5.5 3.5 9s-1 6.5-3.5 9`,`M12 3C9.5 5.5 8.5 8.5 8.5 12s1 6.5 3.5 9`],bell:[`M6 16V11a6 6 0 0 1 12 0v5l1.5 2h-15z`,`M10 20a2 2 0 0 0 4 0`],"bell-off":[`M6 16V11a6 6 0 0 1 9.5-4.9`,`M18 11v5l1.5 2H8`,`M10 20a2 2 0 0 0 4 0`,`M4 4l16 16`],smile:[`M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z`,`M8.5 14a4 4 0 0 0 7 0`,`M9 9.5h.01`,`M15 9.5h.01`],reply:[`M9 7L4 12l5 5`,`M4 12h10a6 6 0 0 1 6 6v1`],pencil:[`M15 5l4 4L8 20H4v-4z`],sigma:[`M18 6V4H6l6 8lLine truncated
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:oP(e)).join(`
`)}function cP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function lP(e,t){return t?e.split(t).join(`
`):e}function uP(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function dP(e,t,n={}){if(!e||!e.content||e.content.length===0)return``;let r=[];e.content.forEach(e=>{let i=[];e.content&&e.content.forEach(e=>{let r=``;r=e.content&&Array.isArray(e.content)&&e.content.length>1?e.content.map(e=>lP(t.renderChildren(e),n.cellLineSeparator)).join(`
`):lP(e.content?t.renderChildren(e.content):``,n.cellLineSeparator);let a=uP(cP(r.replace(/[ \t]*\r?\n[ \t]*/g,`<br>`))),o=e.type===`tableHeader`,s=zN(e.attrs);i.push({text:a,isHeader:o,align:s})}),r.push(i)});let i=r.reduce((e,t)=>Math.max(e,t.length),0);if(i===0)return``;let a=Array.from({length:i}).fill(0);r.forEach(e=>{for(let t=0;t<i;t+=1){let n=(e[t]?.text||``).length;n>a[t]&&(a[t]=n),a[t]<3&&(a[t]=3)}});let o=(e,t)=>e+` `.repeat(Math.max(0,t-e.length)),s=r[0],c=s.some(e=>e.isHeader),l=Array.from({length:i}).fill(null);r.forEach(e=>{for(let t=0;t<i;t+=1)!l[t]&&e[t]?.align&&(l[t]=e[t].align)});let u=`
`,d=Array.from({length:i}).map((e,t)=>c&&s[t]&&s[t].text||``);return u+=`| ${d.map((e,t)=>o(e,a[t])).join(` | `)} |\n`,u+=`| ${a.map((e,t)=>{let n=Math.max(3,e),r=l[t];return r===`left`?`:${`-`.repeat(n)}`:r===`right`?`${`-`.repeat(n)}:`:r===`center`?`:${`-`.repeat(n)}:`:`-`.repeat(n)}).join(` | `)} |\n`,(c?r.slice(1):r).forEach(e=>{u+=`| ${Array.from({length:i}).fill(0).map((t,n)=>o(e[n]&&e[n].text||``,a[n])).join(` | `)} |\n`}),u}var fP=new D(`preserveCellSelectionOnContextMenu`);function pP(e,t){let n=e.posAtCoords({left:t.clientX,top:t.clientY});if(n)return n.pos;if(!(t.target instanceof Node))return null;try{return e.posAtDOM(t.target,0)}catch{return null}}function mP(e,t){let n=!1;return e.forEachCell((e,r)=>{t>=r&&t<r+e.nodeSize&&(n=!0)}),n}function hP(){return new E({key:fP,props:{handleDOMEvents:{mousedown(e,t){if(t.button!==2)return!1;let{selection:n}=e.state;if(!rP(n)||n.ranges.length<2)return!1;let r=pP(e,t);return r==null||!mP(n,r)?!1:(t.preventDefault(),!0)}}}})}var gP=Jp.create({name:`table`,addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:QN,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:`tableRow+`,tableRole:`table`,isolating:!0,group:`block`,parseHTML(){return[{tag:`table`}]},renderHTML({node:e,HTMLAttributes:t}){let{colgroup:n,tableWidth:r,tableMinWidth:i}=$N(e,this.options.cellMinWidth),a=t.style;function o(){return a||(r?`width: ${r}`:`min-width: ${i}`)}let s=[`table`,A(this.options.HTMLAttributes,t,{style:o()}),n,[`tbody`,0]];return this.options.renderWrapper?[`div`,{class:`tableWrapper`},s]:s},parseMarkdown:(e,t)=>{let n=[],r=Array.isArray(e.align)?e.align:[];if(e.header){let i=[];e.header.forEach((e,n)=>{let a=LN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableHeader`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}return e.rows&&e.rows.forEach(e=>{let i=[];e.forEach((e,n)=>{let a=LN(r[n]??e.align),o=a?{align:a}:{};i.push(t.createNode(`tableCell`,o,[{type:`paragraph`,content:t.parseInline(e.tokens)}]))}),n.push(t.createNode(`tableRow`,{},i))}),t.createNode(`table`,void 0,n)},renderMarkdown:(e,t)=>dP(e,t),markdownTokenizer:{name:`table`,level:`block`,start:e=>{let t=e.split(`
`);if(t.length<2)return-1;let n=t[1];return!/^[ \t|:]*-[ \t|:-]*$/.test(n)||!n.includes(`|`)?-1:t[0].includes(`|`)?0:-1},tokenize(e,t,n){let r=e.indexOf(`
`),i=r>=0?e.slice(0,r):e,a=i.split(`
`);if(a.length<2)return;let o=a[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes(`|`))return;let s=oP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
`);if(a.length<2)return;let o=a[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes(`|`))return;let s=sP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
`).length,u=e.split(`
`).slice(0,l).join(`
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=tP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(w.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>AM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>jM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return NM(e,t&&(e=>{n&&iP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>IM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>LM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return zM(e,t&&(e=>{n&&iP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>QM(e,t),mergeCells:()=>({state:e,dispatch:t})=>HM(e,t),splitCell:()=>({state:e,dispatch:t})=>UM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>JM(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>JM(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>YM(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>HM(e,t)?!0:UM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>GM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>ZM(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>ZM(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&EM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=vM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:rP,"Mod-Backspace":rP,Delete:rP,"Mod-Delete":rP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[xN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],FN({allowTableNodeSelection:this.options.allowTableNodeSelection}),mP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),gP=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(hP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(KN.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(qN.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(JN.configure(this.options.tableRow)),e}}),_P=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function vP(){return[Nk.configure({HTMLAttributes:{class:`dw-tasks`}}),Mk.configure({nested:!0})]}function yP(){return[gP.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var bP=_P.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),xP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),SP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,CP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,wP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=wj(e.anchor,t,()=>{Oj(e.anchor,t,{placement:`bottom-start`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),sF===d&&(sF=null),n||e.onCancel?.())}let d=()=>u();return sF=d,n.focus(),e.multiline||n.select(),d}var lF=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function uF(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of lF){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function dF(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var fF=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function pF(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;cF({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(dF(t)),onCancel:()=>e(``)})})}async function mF(e,t,n,r){let i=await pF(e,t,t.blocks.embedUrl);i&&(uF(i)?e.chain().focus().insertEmbed(i).run():await gF(e,i,n,r))}async function hF(e,t,n,r){let i=await pF(e,t,t.blocks.linkUrl);i&&await gF(e,i,n,r)}async function gF(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var _F=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=dF(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=dF(e),i=uF(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${fF(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=nP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(w.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>jM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>MM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return PM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>LM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>RM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return BM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>$M(e,t),mergeCells:()=>({state:e,dispatch:t})=>UM(e,t),splitCell:()=>({state:e,dispatch:t})=>WM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>YM(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>YM(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>XM(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>UM(e,t)?!0:WM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>KM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>QM(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>QM(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&DM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=yM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:iP,"Mod-Backspace":iP,Delete:iP,"Mod-Delete":iP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[SN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],IN({allowTableNodeSelection:this.options.allowTableNodeSelection}),hP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),_P=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(gP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(qN.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(JN.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(YN.configure(this.options.tableRow)),e}}),vP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function yP(){return[Nk.configure({HTMLAttributes:{class:`dw-tasks`}}),Mk.configure({nested:!0})]}function bP(){return[_P.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var xP=vP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),SP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),CP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,wP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,TP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
`).length+1)));let r=document.createElement(`div`);r.className=`dw-source__actions`;let i=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`dw-source__btn ${t}`,r.textContent=e,r.addEventListener(`mousedown`,e=>e.preventDefault()),r.addEventListener(`click`,n),r};e.onRemove&&r.append(i(e.labels.remove,`dw-source__btn--danger`,()=>{u(!0),e.onRemove()}));let a=document.createElement(`span`);a.style.flex=`1`,r.append(a,i(e.labels.cancel,``,()=>u()),i(e.labels.done,`dw-source__btn--primary`,()=>o())),t.append(n,r),document.body.append(t);let o=()=>{let t=n.value;u(!0),e.onSave(t)};n.addEventListener(`input`,()=>e.onInput?.(n.value)),n.addEventListener(`keydown`,t=>{let n=t;n.key===`Escape`?(n.preventDefault(),u()):n.key===`Enter`&&(n.ctrlKey||n.metaKey||!e.multiline)&&(n.preventDefault(),o()),n.stopPropagation()});let s=n=>{!t.contains(n.target)&&!e.anchor.contains(n.target)&&u()};setTimeout(()=>document.addEventListener(`mousedown`,s),0);let c=wj(e.anchor,t,()=>{Oj(e.anchor,t,{placement:`bottom-start`,middleware:[Tj(6),Dj(),Ej({padding:8})]}).then(({x:e,y:n})=>Object.assign(t.style,{left:`${e}px`,top:`${n}px`}))}),l=!1;function u(n=!1){l||(l=!0,c(),document.removeEventListener(`mousedown`,s),t.remove(),cF===d&&(cF=null),n||e.onCancel?.())}let d=()=>u();return cF=d,n.focus(),e.multiline||n.select(),d}var uF=[{pattern:/^https:\/\/(?:www\.|m\.)?youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/|live\/)([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/youtu\.be\/([\w-]{11})/,src:e=>`https://www.youtube-nocookie.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?vimeo\.com\/(?:video\/)?(\d+)/,src:e=>`https://player.vimeo.com/video/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-f]{32})/,src:e=>`https://www.loom.com/embed/${e[1]}`},{pattern:/^https:\/\/(?:www\.)?figma\.com\/(?:file|design|proto|board|slides)\/[\w-]+/,src:(e,t)=>`https://www.figma.com/embed?embed_host=docwell&url=${encodeURIComponent(t.href)}`},{pattern:/^https:\/\/codepen\.io\/([\w-]+)\/(?:pen|embed)\/([\w-]+)/,src:e=>`https://codepen.io/${e[1]}/embed/${e[2]}?default-tab=result`},{pattern:/^https:\/\/open\.spotify\.com\/(?:embed\/)?(track|album|playlist|episode|show)\/(\w+)/,src:e=>`https://open.spotify.com/embed/${e[1]}/${e[2]}`,ratio:`audio`},{pattern:/^https:\/\/docs\.google\.com\/(document|spreadsheets|presentation)\/d\/([\w-]+)/,src:e=>`https://docs.google.com/${e[1]}/d/${e[2]}/preview`,ratio:`tall`},{pattern:/^https:\/\/(?:www\.)?google\.com\/maps\/embed\?/,src:(e,t)=>t.href}];function dF(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of uF){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function fF(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var pF=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function mF(e,t,n){let{node:r}=e.view.domAtPos(e.state.selection.from),i=r instanceof HTMLElement?r:r.parentElement??e.view.dom;return new Promise(e=>{let r=t.blocks;lF({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(fF(t)),onCancel:()=>e(``)})})}async function hF(e,t,n,r){let i=await mF(e,t,t.blocks.embedUrl);i&&(dF(i)?e.chain().focus().insertEmbed(i).run():await _F(e,i,n,r))}async function gF(e,t,n,r){let i=await mF(e,t,t.blocks.linkUrl);i&&await _F(e,i,n,r)}async function _F(e,t,n,r){let i={url:t};if(n)try{i={...await n.preview(t),url:t}}catch(e){r?.(e)}e.chain().focus().insertLinkCard(i).run()}var vF=Jp.create({name:`embed`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null}},addAttributes(){return{url:{default:``,parseHTML:e=>e.getAttribute(`data-url`)??``,renderHTML:e=>({"data-url":e.url})}}},parseHTML(){return[{tag:`div[data-type='embed']`}]},renderHTML({node:e,HTMLAttributes:t}){let n=fF(String(e.attrs.url));return[`div`,A(t,{"data-type":`embed`}),[`a`,{href:n},n]]},addCommands(){return{insertEmbed:e=>({commands:t})=>t.insertContent({type:this.name,attrs:{url:e}})}},addNodeView(){return({node:e})=>{let t=this.options.labels.blocks,n=document.createElement(`figure`);n.className=`dw-embed`,n.setAttribute(`data-type`,`embed`),n.contentEditable=`false`;let r=e=>{let r=fF(e),i=dF(r);if(n.replaceChildren(),!i){let e=document.createElement(`a`);e.href=r,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=r||t.embedInvalid,n.append(e);return}n.dataset.ratio=i.ratio;let a=document.createElement(`iframe`);a.className=`dw-embed__frame`,a.src=i.src,a.title=`${t.embed}: ${pF(r)}`,a.loading=`lazy`,a.allow=`fullscreen; picture-in-picture; encrypted-media; clipboard-write`,a.referrerPolicy=`strict-origin-when-cross-origin`,a.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups allow-presentation`);let o=document.createElement(`figcaption`);o.className=`dw-embed__caption`;let s=document.createElement(`a`);s.href=r,s.targeLine truncated
c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14
c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54
c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10
@@ -170,7 +170,7 @@ c5.3,-9.3,12,-14,20,-14
H400000v`+(40+e)+`H845.2724
s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7
c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},_I=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
M`+(834+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},vI=function(e,t){return`M263,`+(601+e+t)+`c0.7,0,18,39.7,52,119
c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120
c340,-704.7,510.7,-1060.3,512,-1067
l`+e/2.084+` -`+e+`
@@ -180,7 +180,7 @@ s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,
c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1
s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26
c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},vI=function(e,t){return`M983 `+(10+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},yI=function(e,t){return`M983 `+(10+e+t)+`
l`+e/3.13+` -`+e+`
c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+`
H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7
@@ -189,7 +189,7 @@ c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30
c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722
c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5
c53.7,-170.3,84.5,-266.8,92.5,-289.5z
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},yI=function(e,t){return`M424,`+(2398+e+t)+`
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},bI=function(e,t){return`M424,`+(2398+e+t)+`
c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514
c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20
s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121
@@ -199,18 +199,18 @@ v`+(40+e)+`H1014.6
s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185
c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+` `+t+`
h400000v`+(40+e)+`h-400000z`},bI=function(e,t){return`M473,`+(2713+e+t)+`
h400000v`+(40+e)+`h-400000z`},xI=function(e,t){return`M473,`+(2713+e+t)+`
c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+` -`+e+`
c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7
s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9
c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200
c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26
s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104,
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},xI=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},SI=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
606zM`+(1001+e)+` `+t+`h400000v`+(40+e)+`H1017.7z`},SI=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},CI=function(e,t,n){var r=n-54-t-e;return`M702 `+(e+t)+`H400000`+(40+e)+`
H742v`+r+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1
h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170
c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},CI=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=gI(t,hI);break;case`sqrtSize1`:r=_I(t,hI);break;case`sqrtSize2`:r=vI(t,hI);break;case`sqrtSize3`:r=yI(t,hI);break;case`sqrtSize4`:r=bI(t,hI);break;case`sqrtTall`:r=SI(t,hI,n)}return r},wI=function(e,t){switch(e){case`⎜`:return mI(`M291 0 H417 V`+t+` H291z`);case`∣`:return mI(`M145 0 H188 V`+t+` H145z`);case`∥`:return mI(`M145 0 H188 V`+t+` H145z`)+mI(`M367 0 H410 V`+t+` H367z`);case`⎟`:return mI(`M457 0 H583 V`+t+` H457z`);case`⎢`:return mI(`M319 0 H403 V`+t+` H319z`);case`⎥`:return mI(`M263 0 H347 V`+t+` H263z`);case`⎪`:return mI(`M384 0 H504 V`+t+` H384z`);case`⏐`:return mI(`M312 0 H355 V`+t+` H312z`);case`‖`:return mI(`M257 0 H300 V`+t+` H257z`)+mI(`M478 0 H521 V`+t+` H478z`);default:return``}},TI={doubleleftarrow:`M262 157
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},wI=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=_I(t,gI);break;case`sqrtSize1`:r=vI(t,gI);break;case`sqrtSize2`:r=yI(t,gI);break;case`sqrtSize3`:r=bI(t,gI);break;case`sqrtSize4`:r=xI(t,gI);break;case`sqrtTall`:r=CI(t,gI,n)}return r},TI=function(e,t){switch(e){case`⎜`:return hI(`M291 0 H417 V`+t+` H291z`);case`∣`:return hI(`M145 0 H188 V`+t+` H145z`);case`∥`:return hI(`M145 0 H188 V`+t+` H145z`)+hI(`M367 0 H410 V`+t+` H367z`);case`⎟`:return hI(`M457 0 H583 V`+t+` H457z`);case`⎢`:return hI(`M319 0 H403 V`+t+` H319z`);case`⎥`:return hI(`M263 0 H347 V`+t+` H263z`);case`⎪`:return hI(`M384 0 H504 V`+t+` H384z`);case`⏐`:return hI(`M312 0 H355 V`+t+` H312z`);case`‖`:return hI(`M257 0 H300 V`+t+` H257z`)+hI(`M478 0 H521 V`+t+` H478z`);default:return``}},EI={doubleleftarrow:`M262 157
l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3
0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28
14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5
@@ -256,10 +256,10 @@ m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9
v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5
-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3
-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:mI(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:mI(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:mI(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:mI(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:hI(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:hI(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:hI(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:hI(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8
c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:mI(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:hI(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14
-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7
311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11
@@ -308,7 +308,7 @@ m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown
m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3
15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0
-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:mI(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:mI(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:mI(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:hI(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:hI(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:hI(`M399995 440 h-120 V150 H0 v-120 H399995z`),rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23
1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32
-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142
-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40
@@ -381,7 +381,7 @@ M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`
c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199,
-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6
c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},EI=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},DI=function(e,t){switch(e){case`lbrack`:return`M403 1759 V84 H666 V0 H319 V1759 v`+t+` v1759 v84 h347 v-84
H403z M403 1759 V0 H319 V1759 v`+t+` v1759 v84 h84z`;case`rbrack`:return`M347 1759 V0 H0 V84 H263 V1759 v`+t+` v1759 H0 v84 H347z
M347 1759 V0 H263 V1759 v`+t+` v1759 h84z`;case`vert`:return`M145 15 v585 v`+t+` v585 c2.667,10,9.667,15,21,15
c10,0,16.667,-5,20,-15 v-585 v`+-t+` v-585 c-2.667,-10,-9.667,-15,-21,-15
@@ -409,18 +409,18 @@ c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6
c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17
c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558
l0,-`+(t+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function DI(e){return`toText`in e}var OI=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(DI(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},kI={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},AI={ex:!0,em:!0,mu:!0},jI=function(e){return typeof e!=`string`&&(e=e.unit),e in kI||e in AI||e===`ex`},MI=function(e,t){var n;if(e.unit in kI)n=kI[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new I(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},R=function(e){return+e.toFixed(4)+`em`},NI=function(e){return e.filter(e=>e).join(` `)},PI=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=FF(n)+`:`+r+`;`)}return t},FI=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},II=function(e){var t=document.createElement(e);t.className=NI(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},LI=/[\s"'>/=\x00-\x1f]/,RI=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+RF(NI(this.classes))+`"`);var n=PI(this.style);n&&(t+=` style="`+RF(n)+`"`);for(var r of Object.keys(this.attributes)){if(LI.test(r))throw new I(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+RF(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},zI=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,FI.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return II.call(this,`span`)}toMarkup(){return RI.call(this,`span`)}},BI=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,FI.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return II.call(this,`a`)}toMarkup(){return RI.call(this,`a`)}},VI=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+RF(this.src)+`"`+(` alt="`+RF(this.alt)+`"`),t=PI(this.style);return t&&(e+=` style="`+RF(t)+`"`),e+=`'/>`,e}},HI={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},UI=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=dI(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=HI[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=R(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=NI(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=RF(NI(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new WI([new GI(d[v])],{width:`400em`,height:R(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=ZL([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=R(m),l.push(b)}return{span:Y([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=R(o),a>0&&(i.style.minWidth=R(a)),i},oz=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=Y([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new KI({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new KI({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=ZL([],[new WI(c,{width:`100%`,height:R(o)})],i)}return a.height=o,a.style.height=R(o),a},sz=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],cz=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],lz=new Set(sz),uz=new Set(cz);function dz(e){return lz.has(e)}function Q(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function fz(e){var t=pz(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function pz(e){return e.type===`atom`||uz.has(e.type)?e:null}function mz(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new I(t,e);return r}var hz=e=>{if(e instanceof UI)return e;if(YI(e)&&e.children.length===1)return hz(e.children[0])},gz=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=Q(e.base,`accent`),n=r.base,e.base=n,i=JI(AR(e,t)),e.base=r):(r=Q(e,`accent`),n=r.base);var a=AR(n,t.havingCrampedStyle()),o=r.isShifty&&VF(n),s=0;o&&(s=hz(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=az(r,t),u=rR({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+R(2*s)+`)`,marginLeft:R(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=cR(`vec`,t),f=sR.vec[1]):(d=qL({type:`textord`,mode:r.mode,text:r.label},t),d=qI(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=Y([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=R(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=rR({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=Y([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},_z=(e,t)=>{var n=e.isStretchy?nz(e.label):new Z(`mo`,[RR(e.label,e.mode)]),r=new Z(`mover`,[GR(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},vz=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));X({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=vR(t[0]),r=!vz.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:gz,mathmlBuilder:_z}),X({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),X({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=AR(e.base,t),r=az(e,t),i=e.label===`\\utilde`?.12:0;return Y([`mord`,`accentunder`],[rR({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=nz(e.label),r=new Z(`munder`,[GR(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var yz=e=>{var t=new Z(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};X({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrightarLine truncated
]`,uV=`\\\\[a-zA-Z@]+`,dV=`\\\\[^\ud800-\udfff]`,fV=`(`+uV+`)`+lV+`*`,pV=`\\\\(
-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw Error(`Unknown stretchy delimiter.`)}};function OI(e){return`toText`in e}var kI=class{constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),t=0;t<this.children.length;t++)e.appendChild(this.children[t].toNode());return e}toMarkup(){for(var e=``,t=0;t<this.children.length;t++)e+=this.children[t].toMarkup();return e}toText(){return this.children.map(e=>{if(OI(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},AI={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},jI={ex:!0,em:!0,mu:!0},MI=function(e){return typeof e!=`string`&&(e=e.unit),e in AI||e in jI||e===`ex`},NI=function(e,t){var n;if(e.unit in AI)n=AI[e.unit]/t.fontMetrics().ptPerEm/t.sizeMultiplier;else if(e.unit===`mu`)n=t.fontMetrics().cssEmPerMu;else{var r=t.style.isTight()?t.havingStyle(t.style.text()):t;if(e.unit===`ex`)n=r.fontMetrics().xHeight;else if(e.unit===`em`)n=r.fontMetrics().quad;else throw new I(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},R=function(e){return+e.toFixed(4)+`em`},PI=function(e){return e.filter(e=>e).join(` `)},FI=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=IF(n)+`:`+r+`;`)}return t},II=function(e,t,n){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=n||{},t){t.style.isTight()&&this.classes.push(`mtight`);var r=t.getColor();r&&(this.style.color=r)}},LI=function(e){var t=document.createElement(e);t.className=PI(this.classes),Object.assign(t.style,this.style);for(var n of Object.keys(this.attributes))t.setAttribute(n,this.attributes[n]);for(var r=0;r<this.children.length;r++)t.appendChild(this.children[r].toNode());return t},RI=/[\s"'>/=\x00-\x1f]/,zI=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+zF(PI(this.classes))+`"`);var n=FI(this.style);n&&(t+=` style="`+zF(n)+`"`);for(var r of Object.keys(this.attributes)){if(RI.test(r))throw new I(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+zF(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},BI=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,this.italic=void 0,II.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return LI.call(this,`span`)}toMarkup(){return zI.call(this,`span`)}},VI=class{constructor(e,t,n,r){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,II.call(this,t,r),this.children=n||[],this.setAttribute(`href`,e)}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return LI.call(this,`a`)}toMarkup(){return zI.call(this,`a`)}},HI=class{constructor(e,t,n){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=t,this.src=e,this.classes=[`mord`],this.height=0,this.depth=0,this.maxFontSize=0,this.style=n}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement(`img`);return e.src=this.src,e.alt=this.alt,e.className=`mord`,Object.assign(e.style,this.style),e}toMarkup(){var e=`<img src="`+zF(this.src)+`"`+(` alt="`+zF(this.alt)+`"`),t=FI(this.style);return t&&(e+=` style="`+zF(t)+`"`),e+=`'/>`,e}},UI={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},WI=class{constructor(e,t,n,r,i,a,o,s){this.text=void 0,this.height=void 0,this.depth=void 0,this.italic=void 0,this.skew=void 0,this.width=void 0,this.maxFontSize=void 0,this.classes=void 0,this.style=void 0,this.text=e,this.height=t||0,this.depth=n||0,this.italic=r||0,this.skew=i||0,this.width=a||0,this.classes=o||[],this.style=s||{},this.maxFontSize=0;var c=fI(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=UI[this.text])}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createTextNode(this.text),t=null;return this.italic>0&&(t=document.createElement(`span`),t.style.marginRight=R(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=PI(this.classes)),Object.keys(this.style).length>0&&(t||=document.createElement(`span`),Object.assign(t.style,this.style)),t?(t.appendChild(e),t):e}toMarkup(){var e=!1,t=`<span`;this.classes.length&&(e=!0,t+=` class="`,t+=zF(PI(this.classes)Line truncated
`+h+` children.`);for(var v=0;v<h;v++){var y=new GI([new KI(d[v])],{width:`400em`,height:R(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=QL([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=R(m),l.push(b)}return{span:Y([`katex-stretchy`],l,t),minWidth:f,height:m}}var r=n(),i=r.span,a=r.minWidth,o=r.height;return i.height=o,i.style.height=R(o),a>0&&(i.style.minWidth=R(a)),i},sz=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=Y([`katex-stretchy`,t],[],i),t===`fbox`){var s=i.color&&i.getColor();s&&(a.style.borderColor=s)}}else{var c=[];/^[bx]cancel$/.test(t)&&c.push(new qI({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new qI({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=QL([],[new GI(c,{width:`100%`,height:R(o)})],i)}return a.height=o,a.style.height=R(o),a},cz=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],lz=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],uz=new Set(cz),dz=new Set(lz);function fz(e){return uz.has(e)}function Q(e,t){if(!e||e.type!==t)throw Error(`Expected node of type `+t+`, but got `+(e?`node of type `+e.type:String(e)));return e}function pz(e){var t=mz(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function mz(e){return e.type===`atom`||dz.has(e.type)?e:null}function hz(e,t,n){var r=``;for(var i of e.body)if(i.type===`textord`)r+=i.text;else if(n&&i.type===`spacing`&&i.text===` `)r+=` `;else throw new I(t,e);return r}var gz=e=>{if(e instanceof WI)return e;if(XI(e)&&e.children.length===1)return gz(e.children[0])},_z=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=Q(e.base,`accent`),n=r.base,e.base=n,i=YI(jR(e,t)),e.base=r):(r=Q(e,`accent`),n=r.base);var a=jR(n,t.havingCrampedStyle()),o=r.isShifty&&HF(n),s=0;o&&(s=gz(a)?.skew??0);var c=r.label===`\\c`,l=c?a.height+a.depth:Math.min(a.height,t.fontMetrics().xHeight),u;if(r.isStretchy)u=oz(r,t),u=iR({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+R(2*s)+`)`,marginLeft:R(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=lR(`vec`,t),f=cR.vec[1]):(d=JL({type:`textord`,mode:r.mode,text:r.label},t),d=JI(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=Y([`accent-body`],[d]);var p=r.label===`\\textcircled`;p&&(u.classes.push(`accent-full`),l=a.height);var m=s;p||(m-=f/2),u.style.left=R(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=iR({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=Y([`mord`,`katex-accent`],[u],t);return i?(i.children[0]=h,i.height=Math.max(h.height,i.height),i.classes[0]=`mord`,i):h},vz=(e,t)=>{var n=e.isStretchy?rz(e.label):new Z(`mo`,[zR(e.label,e.mode)]),r=new Z(`mover`,[KR(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},yz=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));X({type:`accent`,names:[`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`,`\\widecheck`,`\\widehat`,`\\widetilde`,`\\overrightarrow`,`\\overleftarrow`,`\\Overrightarrow`,`\\overleftrightarrow`,`\\overgroup`,`\\overlinesegment`,`\\overleftharpoon`,`\\overrightharpoon`],numArgs:1,handler:(e,t)=>{var n=yR(t[0]),r=!yz.test(e.funcName),i=!r||e.funcName===`\\widehat`||e.funcName===`\\widetilde`||e.funcName===`\\widecheck`;return{type:`accent`,mode:e.parser.mode,label:e.funcName,isStretchy:r,isShifty:i,base:n}},htmlBuilder:_z,mathmlBuilder:vz}),X({type:`accent`,names:[`\\'`,"\\`",`\\^`,`\\~`,`\\=`,`\\u`,`\\.`,`\\"`,`\\c`,`\\r`,`\\H`,`\\v`,`\\textcircled`],numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:[`primitive`],handler:(e,t)=>{var n=t[0],r=e.parser.mode;return r===`math`&&(e.parser.settings.reportNonstrict(`mathVsTextAccents`,`LaTeX's accent `+e.funcName+` works only in text mode`),r=`text`),{type:`accent`,mode:r,label:e.funcName,isStretchy:!1,isShifty:!0,base:n}}}),X({type:`accentUnder`,names:[`\\underleftarrow`,`\\underrightarrow`,`\\underleftrightarrow`,`\\undergroup`,`\\underlinesegment`,`\\utilde`],numArgs:1,handler:(e,t)=>{var n=e.parser,r=e.funcName,i=t[0];return{type:`accentUnder`,mode:n.mode,label:r,base:i}},htmlBuilder:(e,t)=>{var n=jR(e.base,t),r=oz(e,t),i=e.label===`\\utilde`?.12:0;return Y([`mord`,`accentunder`],[iR({positionType:`top`,positionData:n.height,children:[{type:`elem`,elem:r,wrapperClasses:[`svg-align`]},{type:`kern`,size:i},{type:`elem`,elem:n}]})],t)},mathmlBuilder:(e,t)=>{var n=rz(e.label),r=new Z(`munder`,[KR(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var bz=e=>{var t=new Z(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};X({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrightarLine truncated
]`,dV=`\\\\[a-zA-Z@]+`,fV=`\\\\[^\ud800-\udfff]`,pV=`(`+dV+`)`+uV+`*`,mV=`\\\\(
|[ \r ]+
?)[ \r ]*`,mV=`[̀-ͯ]`,hV=RegExp(mV+`+$`),gV=`(`+lV+`+)|`+(pV+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(mV+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(mV+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+fV)+(`|`+dV+`)`),_V=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(gV,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new _B(`EOF`,new gB(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new I(`Unexpected character: '`+e[t]+`'`,new _B(e[t],new gB(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(`
`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new _B(r,new gB(this,t,this.tokenRegex.lastIndex))}},vV=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new I(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},yV=hB;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var bV={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new I("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=bV[t.text],r==null||r>=n)throw new I(`Invalid base-`+n+` digit `+t.text);for(var i;(i=bV[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var xV=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new I(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new I(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new I(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new I(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>xV(e,!1,!0,!1)),$(`\\renewcommand`,e=>xV(e,!0,!1,!1)),$(`\\providecommand`,e=>xV(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),cV[n],rL.math[n],rL.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(MV,t[0])&&!rL[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=MV[t[0]]+t.slice(1));var i=hV.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(rL[this.mode][t]){this.settings.strict&&this.mode===`math`&&TL.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=rL[this.mode][t].group,s=gB.range(e);a=dz(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&(pI(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:gB.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!jV[l])throw new I(`Unknown accent ' `+l+`'`,e);var u=jV[l][this.mode]||jV[l].text;if(!u)throw new I(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:gB.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};NV.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var PV=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new NV(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new I(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new _B(`\\df@tag`)])}]}return r},FV=function(e,t,n){t.textContent=``;var r=zV(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),FV=function(){throw new I(`KaTeX doesn't work in quirks mode.`)});var IV=function(e,t){return zV(e,t).toMarkup()},LV=function(e,t){return PV(e,new qF(t))},RV=function(e,t,n){if(n.throwOnError||!(e instanceof I))throw e;var r=Y([`katex-error`],[new UI(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},zV=function(e,t){var n=new qF(t);try{return $R(PV(e,n),e,n)}catch(t){return RV(t,e,n)}},BV={version:`0.18.10`,render:FV,renderToString:IV,ParseError:I,SETTINGS_SCHEMA:UF,__parse:LV,__renderToDomTree:zV,__renderToHTMLTree:function(e,t){var n=new qF(t);try{return ez(PV(e,n),e,n)}catch(t){return RV(t,e,n)}},__setFontMetrics:$I,__defineSymbol:z,__defineFunction:X,__defineMacro:$,__domTree:{Span:zI,Anchor:BI,SymbolNode:UI,SvgNode:WI,PathNode:GI,LineNode:KI}},VV=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{BV.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),HV=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},UV=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:HV,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{BV.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),WV=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[VV.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),UV.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function GV(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;cF({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return WV.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function KV(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=kf(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=RegELine truncated
`);return/\s/.test(n)}):!1}function JV(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 YV(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:JV(e)}function XV({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&&!qV(r)}function ZV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function QV({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function $V({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function eH({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 tH({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[Tj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(Dj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function nH(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 rH({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&&nH(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=wj(c,o,()=>{Oj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function iH({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,_=eH({editor:e,items:n}),v=tH({placLine truncated
Idea --> Draft --> Review --> Published`,mH=null;function hH(e){return mH??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),mH}var gH=0;async function _H(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await hH(r)).render(`dw-mermaid-${++gH}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var vH=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=pH)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return _H(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;cF({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void _H(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),_H(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void _H(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),_H(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}}),yH=e=>`/p/${encodeURIComponent(e)}`,bH=/^\/p\/([A-Za-z0-9_-]+)\/?(?:[?#].*)?$/;function xH(e){return bH.exec(e)?.[1]??``}function SH(e,t,n,r=`Untitled`){let i=`${n.icon?`${n.icon} `:``}${n.title||r}`;e.chain().focus().deleteRange(t).insertContent([{type:`text`,text:i,marks:[{type:`link`,attrs:{href:yH(n.id)}}]},{type:`text`,text:` `}]).run()}async function CH(e,t,n){if(!t.create)return;let{from:r,to:i,empty:a}=e.state.selection,o=a?``:e.state.doc.textBetween(r,i,` `).trim().slice(0,200),s=await t.create(o);a||!o?SH(e,{from:r,to:r},s,n):e.chain().focus().setTextSelection({from:r,to:i}).setLink({href:yH(s.id)}).run()}var wH=Tp.create({name:`pageLinks`,addOptions(){return{host:void 0,labels:null,onNavigate:void 0}},addProseMirrorPlugins(){let{host:e,onNavigate:t}=this.options,n=this.options.labels,r=[];return e&&r.push(sH({editor:this.editor,pluginKey:new D(`pageLinks`),char:`[[`,allowSpaces:!0,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:async({query:t})=>(await e.search(t).catch(()=>[])).slice(0,8),render:Ij({label:n.pageLinks,empty:n.noPages,toItem:e=>({label:`${e.icon?`${e.icon} `:``}${e.title||`…`}`,description:e.hint,icon:`page`}),pick:(e,t)=>SH(e.editor,e.range,t)})})),t&&r.push(new E({key:new D(`pageLinkClicks`),props:{handleClick:(e,n,r)=>{let i=(r.target?.closest?.(`a[href]`))?.getAttribute(`href`)??``;return!xH(i)||e.editable&&!(r.ctrlKey||r.metaKey)?!1:(r.preventDefault(),t(i),!0)}}})),r}});function TH(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 EH(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),...[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`other headings`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run())),o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`taLine truncated
?)[ \r ]*`,hV=`[̀-ͯ]`,gV=RegExp(hV+`+$`),_V=`(`+uV+`+)|`+(mV+`|`)+`([!-\\[\\]-‧‪-퟿豈-￿]`+(hV+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(hV+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+pV)+(`|`+fV+`)`),vV=class{constructor(e,t){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=t,this.tokenRegex=new RegExp(_V,`g`),this.catcodes={"%":14,"~":13}}setCatcode(e,t){this.catcodes[e]=t}lex(){var e=this.input,t=this.tokenRegex.lastIndex;if(t===e.length)return new vB(`EOF`,new _B(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new I(`Unexpected character: '`+e[t]+`'`,new vB(e[t],new _B(this,t,t+1)));var r=n[6]||n[3]||(n[2]?`\\ `:` `);if(this.catcodes[r]===14){var i=e.indexOf(`
`,this.tokenRegex.lastIndex);return i===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict(`commentAtEnd`,`% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)`)):this.tokenRegex.lastIndex=i+1,this.lex()}return new vB(r,new _B(this,t,this.tokenRegex.lastIndex))}},yV=class{constructor(e,t){e===void 0&&(e={}),t===void 0&&(t={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=t,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new I(`Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug`);var e=this.undefStack.pop();for(var t of Object.keys(e))e[t]===void 0?delete this.current[t]:this.current[t]=e[t]}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return Object.prototype.hasOwnProperty.call(this.current,e)||Object.prototype.hasOwnProperty.call(this.builtins,e)}get(e){if(Object.prototype.hasOwnProperty.call(this.current,e))return this.current[e];if(Object.prototype.hasOwnProperty.call(this.builtins,e))return this.builtins[e]}set(e,t,n){if(n===void 0&&(n=!1),n){for(var r=0;r<this.undefStack.length;r++)delete this.undefStack[r][e];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][e]=t)}else{var i=this.undefStack[this.undefStack.length-1];i&&!Object.prototype.hasOwnProperty.call(i,e)&&(i[e]=Object.prototype.hasOwnProperty.call(this.current,e)?this.current[e]:void 0)}t==null?delete this.current[e]:this.current[e]=t}},bV=gB;$(`\\noexpand`,function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}}),$(`\\expandafter`,function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}}),$(`\\@firstoftwo`,function(e){return{tokens:e.consumeArgs(2)[0],numArgs:0}}),$(`\\@secondoftwo`,function(e){return{tokens:e.consumeArgs(2)[1],numArgs:0}}),$(`\\@ifnextchar`,function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}}),$(`\\@ifstar`,`\\@ifnextchar *{\\@firstoftwo{#1}}`),$(`\\TextOrMath`,function(e){var t=e.consumeArgs(2);return e.mode===`text`?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var xV={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};$(`\\char`,function(e){var t=e.popToken(),n,r=0;if(t.text===`'`)n=8,t=e.popToken();else if(t.text===`"`)n=16,t=e.popToken();else if(t.text==="`"){if(t=e.popToken(),t.text[0]===`\\`)r=t.text.charCodeAt(1);else if(t.text===`EOF`)throw new I("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=xV[t.text],r==null||r>=n)throw new I(`Invalid base-`+n+` digit `+t.text);for(var i;(i=xV[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var SV=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new I(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new I(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new I(`\\renewcommand{`+a+`} when command `+a+` does not yet exist; use \\newcommand`);var s=0;if(i=e.consumeArg().tokens,i.length===1&&i[0].text===`[`){for(var c=``,l=e.expandNextToken();l.text!==`]`&&l.text!==`EOF`;)c+=l.text,l=e.expandNextToken();if(!c.match(/^\s*[0-9]+\s*$/))throw new I(`Invalid number of arguments: `+c);s=parseInt(c),i=e.consumeArg().tokens}return o&&r||e.macros.set(a,{tokens:i,numArgs:s}),``};$(`\\newcommand`,e=>SV(e,!1,!0,!1)),$(`\\renewcommand`,e=>SV(e,!0,!1,!1)),$(`\\providecommand`,e=>SV(e,!0,!0,!0)),$(`\\message`,e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(e=>e.text).join(``)),``}),$(`\\errmessage`,e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(e=>e.text).join(``)),``}),$(`\\show`,e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),lV[n],iL.math[n],iL.text[n]),``}),$(`\\bgroup`,`{`),$(`\\egroup`,`}`),$(`~`,`\\nobreakspace`),$(`\\lq`,"`"),$(`\\rq`,`'`),$(`\\aa`,`\\r a`),$(`\\AA`,`\\r A`),$(`\\textcopyright`,"\\html@mathml{\\textcircled{c}}{\\char`©}"),$(`\\copyright`,`\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}`),$(`\\textregistered`,"\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}"),$(`ℬ`,`\\mathscr{B}`),$(`ℰ`,`\\mathscr{E}`),$(`ℱ`,`\\mathscr{F}`),$(`ℋ`,`\\mathscr{H}`),$(`ℐ`,`\\mathscr{I}`),$(`ℒ`,`\\mathscr{L}`),$(`ℳ`,`\\mathscr{M}`),$(`ℛ`,`\\mathscr{R}`),$(`ℭ`,`\\mathfrak{C}`),$(`ℌ`,`\\mathfrak{H}`),$(`ℨ`,`\\mathfrak{Z}`),$(`\\Bbbk`,`\\Bbb{k}`),$(`\\llap`,`\\mathllap{\\textrm{#1}}`),$(`\\rlap`,`\\mathrlap{\\textrm{#1}}`),$(`\\clap`,`\\mathclap{\\textrm{#1}}`),$(`\\mathstrut`,`\\vphantom{(}`),$(`\\underbar`,`\\underline{\\text{#1}}`),$(`\\not`,`\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}`),$(`\\neq`,"\\html@mathml{\\mathreLine truncated
please report what input caused this bug`);return n=n.slice(1,-1),{type:`verb`,mode:`text`,body:n,star:r}}Object.prototype.hasOwnProperty.call(NV,t[0])&&!iL[this.mode][t[0]]&&(this.settings.strict&&this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Accented Unicode text character "`+t[0]+`" used in math mode`,e),t=NV[t[0]]+t.slice(1));var i=gV.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(iL[this.mode][t]){this.settings.strict&&this.mode===`math`&&EL.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=iL[this.mode][t].group,s=_B.range(e);a=fz(o)?{type:`atom`,mode:this.mode,family:o,loc:s,text:t}:{type:o,mode:this.mode,loc:s,text:t}}else if(t.charCodeAt(0)>=128)this.settings.strict&&(mI(t.charCodeAt(0))?this.mode===`math`&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Unicode text character "`+t[0]+`" used in math mode`,e):this.settings.reportNonstrict(`unknownSymbol`,`Unrecognized Unicode character "`+t[0]+`"`+(` (`+t.charCodeAt(0)+`)`),e)),a={type:`textord`,mode:`text`,loc:_B.range(e),text:t};else return null;if(this.consume(),i)for(var c=0;c<i[0].length;c++){var l=i[0][c];if(!MV[l])throw new I(`Unknown accent ' `+l+`'`,e);var u=MV[l][this.mode]||MV[l].text;if(!u)throw new I(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:_B.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};PV.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var FV=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new PV(e,t);delete n.gullet.macros.current[`\\df@tag`];var r=n.parse();if(delete n.gullet.macros.current[`\\current@color`],delete n.gullet.macros.current[`\\color`],n.gullet.macros.get(`\\df@tag`)){if(!t.displayMode)throw new I(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new vB(`\\df@tag`)])}]}return r},IV=function(e,t,n){t.textContent=``;var r=BV(e,n).toNode();t.appendChild(r)};typeof document<`u`&&document.compatMode!==`CSS1Compat`&&(typeof console<`u`&&console.warn(`Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype.`),IV=function(){throw new I(`KaTeX doesn't work in quirks mode.`)});var LV=function(e,t){return BV(e,t).toMarkup()},RV=function(e,t){return FV(e,new JF(t))},zV=function(e,t,n){if(n.throwOnError||!(e instanceof I))throw e;var r=Y([`katex-error`],[new WI(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},BV=function(e,t){var n=new JF(t);try{return ez(FV(e,n),e,n)}catch(t){return zV(t,e,n)}},VV={version:`0.18.10`,render:IV,renderToString:LV,ParseError:I,SETTINGS_SCHEMA:WF,__parse:RV,__renderToDomTree:BV,__renderToHTMLTree:function(e,t){var n=new JF(t);try{return tz(FV(e,n),e,n)}catch(t){return zV(t,e,n)}},__setFontMetrics:eL,__defineSymbol:z,__defineFunction:X,__defineMacro:$,__domTree:{Span:BI,Anchor:VI,SymbolNode:WI,SvgNode:GI,PathNode:KI,LineNode:qI}},HV=Jp.create({name:`blockMath`,group:`block`,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertBlockMath:e=>({commands:t,editor:n})=>{let{latex:r,pos:i}=e;return r?t.insertContentAt(i??n.state.selection.from,{type:this.name,attrs:{latex:r}}):!1},deleteBlockMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateBlockMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r??a.attrs.latex}),!0)}}},parseHTML(){return[{tag:`div[data-type="block-math"]`}]},renderHTML({HTMLAttributes:e}){return[`div`,A(e,{"data-type":`block-math`})]},parseMarkdown:e=>({type:`blockMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>[`$$`,e.attrs?.latex||``,`$$`].join(`
`),markdownTokenizer:{name:`blockMath`,level:`block`,start:e=>e.indexOf(`$$`),tokenize:e=>{let t=e.match(/^\$\$([^$]+)\$\$/);if(!t)return;let[n,r]=t;return{type:`blockMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:/^\$\$\$([^$]+)\$\$\$$/,handler:({state:e,range:t,match:n})=>{let[,r]=n,{tr:i}=e,a=e.doc.resolve(t.from),o=this.type.create({latex:r}),s=a.depth>0&&a.parent.isTextblock&&t.from===a.start()&&t.to===a.end()&&a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),this.type)?{from:a.before(),to:a.after()}:t;i.replaceWith(s.from,s.to,o)}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`div`),i=document.createElement(`div`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),i.className=`block-math-inner`,r.dataset.type=`block-math`,r.setAttribute(`data-latex`,t.attrs.latex),r.appendChild(i);function a(){try{VV.render(t.attrs.latex,i,e),r.classList.remove(`block-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`block-math-error`)}}let o=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,o),a(),{dom:r,destroy(){r.removeEventListener(`click`,o)}}}}}),UV=e=>{let t=/\$\$([^$\n]+?)\$\$(?!\$)/g,n=t.exec(e);for(;n!==null;){if(n.index===0||e[n.index-1]!==`$`)return{index:n.index,text:n[0],data:{latex:n[1]}};t.lastIndex=n.index+1,n=t.exec(e)}return null},WV=Jp.create({name:`inlineMath`,group:`inline`,inline:!0,atom:!0,addOptions(){return{onClick:void 0,katexOptions:void 0}},addAttributes(){return{latex:{default:``,parseHTML:e=>e.getAttribute(`data-latex`),renderHTML:e=>({"data-latex":e.latex})}}},addCommands(){return{insertInlineMath:e=>({editor:t,tr:n})=>{let r=e.latex,i=e?.pos??t.state.selection.from;return r?(n.replaceWith(i,i,this.type.create({latex:r})),!0):!1},deleteInlineMath:e=>({editor:t,tr:n})=>{let r=e?.pos??t.state.selection.$from.pos,i=t.state.doc.nodeAt(r);return!i||i.type.name!==this.name?!1:(n.delete(r,r+i.nodeSize),!0)},updateInlineMath:e=>({editor:t,tr:n})=>{let r=e?.latex,i=e?.pos;i===void 0&&(i=t.state.selection.$from.pos);let a=t.state.doc.nodeAt(i);return!a||a.type.name!==this.name?!1:(n.setNodeMarkup(i,this.type,{...a.attrs,latex:r}),!0)}}},parseHTML(){return[{tag:`span[data-type="inline-math"]`}]},renderHTML({HTMLAttributes:e}){return[`span`,A(e,{"data-type":`inline-math`})]},parseMarkdown:e=>({type:`inlineMath`,attrs:{latex:e.latex}}),renderMarkdown:e=>`$${e.attrs?.latex||``}$`,markdownTokenizer:{name:`inlineMath`,level:`inline`,start:e=>e.indexOf(`$`),tokenize:e=>{let t=e.match(/^\$([^$]+)\$(?!\$)/);if(!t)return;let[n,r]=t;return{type:`inlineMath`,raw:n,latex:r.trim()}}},addInputRules(){return[new lp({find:UV,handler:({state:e,range:t,match:n})=>{let r=n.data?.latex;if(typeof r!=`string`)return null;let{tr:i}=e,a=t.from,o=t.to;i.replaceWith(a,o,this.type.create({latex:r}))}})]},addNodeView(){let{katexOptions:e}=this.options;return({node:t,getPos:n})=>{let r=document.createElement(`span`);r.className=`tiptap-mathematics-render`,this.editor.isEditable&&r.classList.add(`tiptap-mathematics-render--editable`),r.dataset.type=`inline-math`,r.setAttribute(`data-latex`,t.attrs.latex);function i(){try{VV.render(t.attrs.latex,r,e),r.classList.remove(`inline-math-error`)}catch{r.textContent=t.attrs.latex,r.classList.add(`inline-math-error`)}}let a=e=>{e.preventDefault(),e.stopPropagation();let r=n();r!=null&&this.options.onClick&&this.options.onClick(t,r)};return this.options.onClick&&r.addEventListener(`click`,a),i(),{dom:r,destroy(){r.removeEventListener(`click`,a)}}}}}),GV=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[HV.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),WV.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function KV(e,t){let n=n=>(r,i)=>{let a=t();if(!a?.isEditable)return;let o=a.view.nodeDOM(i);if(!(o instanceof HTMLElement))return;let s=e.blocks;lF({anchor:o,value:String(r.attrs.latex??``),label:s.latex,multiline:n===`block`,monospace:!0,labels:{done:s.done,cancel:s.cancel,remove:s.remove},onSave:e=>{let t=a.chain().setNodeSelection(i);e.trim()?(n===`inline`?t.updateInlineMath({latex:e,pos:i}):t.updateBlockMath({latex:e,pos:i})).focus().run():(n===`inline`?t.deleteInlineMath({pos:i}):t.deleteBlockMath({pos:i})).focus().run()},onRemove:()=>{let e=a.chain();(n===`inline`?e.deleteInlineMath({pos:i}):e.deleteBlockMath({pos:i})).focus().run()}})};return GV.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function qV(e){let{char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:o}=e,s=n&&!r,c=kf(t),l=RegExp(`\\s${c}$`),u=a?`^`:``,d=r?``:c,f=RegELine truncated
`);return/\s/.test(n)}):!1}function YV(e){return()=>{let t=e.state.selection.$anchor.pos,{top:n,right:r,bottom:i,left:a}=e.view.coordsAtPos(t);try{return new DOMRect(a,n,r-a,i-n)}catch{return null}}}function XV(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:YV(e)}function ZV({match:e,dismissedRange:t,state:n,transaction:r,editor:i,shouldResetDismissed:a,effectiveAllowSpaces:o}){return a?.({editor:i,state:n,range:t,match:e,transaction:r,allowSpaces:o})?!1:o?e.range.from===t.from:e.range.from===t.from&&!JV(r)}function QV({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function $V({pluginKey:e,decorationTag:t,decorationClass:n,decorationContent:r,decorationEmptyClass:i,renderer:a,dispatchExit:o}){return{handleKeyDown(t,n){var r;let i=e.getState(t.state);if(!i.active)return!1;if(n.key===`Escape`||n.key===`Esc`){var s;return a==null||(s=a.onKeyDown)==null||s.call(a,{view:t,event:n,range:i.range}),o(t),!0}return(a==null||(r=a.onKeyDown)==null?void 0:r.call(a,{view:t,event:n,range:i.range}))||!1},decorations(a){let{active:o,range:s,decorationId:c,query:l}=e.getState(a);if(!o)return null;let u=!l?.length,d=[n];return u&&d.push(i),xs.create(a.doc,[vs.inline(s.from,s.to,{nodeName:t,class:d.join(` `),"data-decoration-id":c||void 0,"data-decoration-content":r})])}}}function eH({editor:e,char:t,effectiveAllowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,findSuggestionMatch:o,allow:s,shouldShow:c,shouldKeepDismissed:l,pluginKey:u}){return{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(d,f,p,m){let{isEditable:h}=e,{composing:g}=e.view,{selection:_}=d,{empty:v,from:y}=_,b={...f},x=d.getMeta(u);if(x&&x.exit)return b.active=!1,b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null,b.dismissedRange=f.active?{...f.range}:f.dismissedRange,b;if(b.composing=g,d.docChanged&&b.dismissedRange!==null&&(b.dismissedRange={from:d.mapping.map(b.dismissedRange.from),to:d.mapping.map(b.dismissedRange.to)}),h&&(v||e.view.composing)){(y<f.range.from||y>f.range.to)&&!g&&!f.composing&&(b.active=!1);let u=o({char:t,allowSpaces:n,allowToIncludeChar:r,allowedPrefixes:i,startOfLine:a,$position:_.$from}),p=`id_${Math.floor(Math.random()*4294967295)}`;u&&s({editor:e,state:m,range:u.range,isActive:f.active})&&(!c||c({editor:e,range:u.range,query:u.query,text:u.text,transaction:d}))?(b.dismissedRange!==null&&!l({match:u,dismissedRange:b.dismissedRange,state:m,transaction:d})&&(b.dismissedRange=null),b.dismissedRange===null?(b.active=!0,b.decorationId=f.decorationId||p,b.range=u.range,b.query=u.query,b.text=u.text):b.active=!1):(u||(b.dismissedRange=null),b.active=!1)}else b.active=!1;return b.active||(b.decorationId=null,b.range={from:0,to:0},b.query=null,b.text=null),b}}}function tH({editor:e,items:t}){let n=null,r=null,i=null,a=()=>{r!==null&&(clearTimeout(r),r=null),i?.(),i=null},o=e=>new Promise(t=>{i=t,r=setTimeout(()=>{r=null;let e=i;i=null,e?.()},e)}),s=()=>{n?.abort(),a(),n=null};return{abort:s,fetch:async(r,i)=>{s(),n=new AbortController;let a=n;if(i>0&&await o(i),n!==a||a.signal.aborted)return{status:`aborted`};try{let i=await t({editor:e,query:r,signal:a.signal});return n!==a||a.signal.aborted?{status:`aborted`}:{status:`resolved`,items:i}}catch{return n!==a||a.signal.aborted?{status:`aborted`}:{status:`error`}}}}}function nH({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[Tj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(Dj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function rH(e){if(e instanceof HTMLElement)return e;if(typeof e==`string`)try{let t=document.querySelector(e);if(t)return t}catch{return document.body}return document.body}function iH({getReferenceRect:e,contextElement:t,config:n,container:r,dismissOnOutsideClick:i,dismiss:a}){return(o,s={})=>{let c={getBoundingClientRect:()=>e()??new DOMRect,contextElement:t},l=!1,u=!o.isConnected;u&&rH(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=wj(c,o,()=>{Oj(c,o,{placement:n.placement,strategy:n.strategy,middleware:n.middleware}).then(({x:e,y:t,placement:n,strategy:r})=>{s.onPosition?s.onPosition({x:e,y:t,placement:n,strategy:r}):(Object.assign(o.style,{position:r,left:`${e}px`,top:`${t}px`}),l||(l=!0,o.style.visibility=``))})},s.autoUpdate),f;return i&&(f=e=>{let n=e.target;!(n instanceof Node)||o.contains(n)||t.contains(n)||a()},document.addEventListener(`pointerdown`,f,!0)),()=>{d(),f&&document.removeEventListener(`pointerdown`,f,!0),u&&o.remove()}}}function aH({editor:e,pluginKey:t,items:n,renderer:r,minQueryLength:i,debounce:a,initialItems:o,placement:s,offset:c,container:l,flip:u,floatingUi:d,dismissOnOutsideClick:f,command:p,clientRectFor:m,dispatchExit:h}){let g,_=tH({editor:e,items:n}),v=nH({placLine truncated
Idea --> Draft --> Review --> Published`,hH=null;function gH(e){return hH??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),hH}var _H=0;async function vH(e,t,n,r){if(e.classList.remove(`dw-mermaid__body--error`),!t.trim())e.textContent=``;else if(r)try{let{svg:n}=await(await gH(r)).render(`dw-mermaid-${++_H}`,t);e.innerHTML=n}catch(t){e.classList.add(`dw-mermaid__body--error`),e.textContent=`${n.blocks.mermaidError} ${t instanceof Error?t.message:String(t)}`}else{let n=document.createElement(`pre`);n.className=`dw-mermaid__source`,n.textContent=t,e.replaceChildren(n)}}var yH=Jp.create({name:`mermaid`,group:`block`,atom:!0,draggable:!0,addOptions(){return{labels:null,load:void 0}},addAttributes(){return{code:{default:``,parseHTML:e=>e.getAttribute(`data-code`)??e.textContent??``,renderHTML:e=>({"data-code":e.code})}}},parseHTML(){return[{tag:`div[data-type='mermaid']`},{tag:`pre.mermaid`}]},renderHTML({node:e,HTMLAttributes:t}){return[`div`,A(t,{"data-type":`mermaid`}),[`pre`,{},String(e.attrs.code)]]},addCommands(){return{insertMermaid:(e=mH)=>({commands:t})=>t.insertContent({type:this.name,attrs:{code:e}})}},addNodeView(){return({node:e,editor:t,getPos:n})=>{let r=this.options.labels,i=this.options.load,a=document.createElement(`div`);a.className=`dw-mermaid`,a.setAttribute(`data-type`,`mermaid`);let o=document.createElement(`div`);o.className=`dw-mermaid__body`,a.append(o);let s=String(e.attrs.code);return vH(o,s,r,i),a.addEventListener(`click`,()=>{if(!t.isEditable)return;let e=typeof n==`function`?n():void 0;if(e===void 0)return;let c=r.blocks;lF({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void vH(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),vH(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void vH(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),vH(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}}),bH=e=>`/p/${encodeURIComponent(e)}`,xH=/^\/p\/([A-Za-z0-9_-]+)\/?(?:[?#].*)?$/;function SH(e){return xH.exec(e)?.[1]??``}function CH(e,t,n,r=`Untitled`){let i=`${n.icon?`${n.icon} `:``}${n.title||r}`;e.chain().focus().deleteRange(t).insertContent([{type:`text`,text:i,marks:[{type:`link`,attrs:{href:bH(n.id)}}]},{type:`text`,text:` `}]).run()}async function wH(e,t,n){if(!t.create)return;let{from:r,to:i,empty:a}=e.state.selection,o=a?``:e.state.doc.textBetween(r,i,` `).trim().slice(0,200),s=await t.create(o);a||!o?CH(e,{from:r,to:r},s,n):e.chain().focus().setTextSelection({from:r,to:i}).setLink({href:bH(s.id)}).run()}var TH=Tp.create({name:`pageLinks`,addOptions(){return{host:void 0,labels:null,onNavigate:void 0}},addProseMirrorPlugins(){let{host:e,onNavigate:t}=this.options,n=this.options.labels,r=[];return e&&r.push(cH({editor:this.editor,pluginKey:new D(`pageLinks`),char:`[[`,allowSpaces:!0,allow:({state:e,range:t})=>!e.doc.resolve(t.from).parent.type.spec.code,items:async({query:t})=>(await e.search(t).catch(()=>[])).slice(0,8),render:Ij({label:n.pageLinks,empty:n.noPages,toItem:e=>({label:`${e.icon?`${e.icon} `:``}${e.title||`…`}`,description:e.hint,icon:`page`}),pick:(e,t)=>CH(e.editor,e.range,t)})})),t&&r.push(new E({key:new D(`pageLinkClicks`),props:{handleClick:(e,n,r)=>{let i=(r.target?.closest?.(`a[href]`))?.getAttribute(`href`)??``;return!SH(i)||e.editable&&!(r.ctrlKey||r.metaKey)?!1:(r.preventDefault(),t(i),!0)}}})),r}});function EH(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,n.accept=e,n.multiple=!0,n.onchange=()=>t([...n.files??[]]),n.click()})}function DH(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`]Line truncated
<style rel="stylesheet" crossorigin>/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-Line truncated
@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:"Inter Variable", "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;--font-serif:"Source Serif 4 Variable", "Source Serif 4", "Iowan Old Style", Georgia, serif;--font-mono:"JetBrains Mono Variable", "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace;--color-gray-50:oklch(98.5% .002 247.839);--color-gray-100:oklch(96.7% .003 264.542);--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--radius-xs:4px;--radius-sm:6px;--radius-md:10px;--ease-in:cubic-bezier(.4, 0, 1, 1);--ease-out:cubic-bezier(0, 0, .2, 1);--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono);--color-surface:var(--dw-surface);--color-surface-sunken:var(--dw-surface-sunken);--color-surface-raised:var(--dw-surface-raised);--color-surface-hover:var(--dw-surface-hover);--color-line:var(--dw-line);--color-line-strong:var(--dw-line-strong);--color-ink:var(--dw-ink);--color-ink-muted:var(--dw-ink-muted);--color-ink-faint:var(--dw-ink-faint);--color-primary:var(--dw-primary);--color-primary-hover:var(--dw-primary-hover);--color-on-primary:var(--dw-on-primary);--color-accent:var(--dw-accent);--color-accent-soft:var(--dw-accent-soft);--color-selection:var(--dw-selection);--color-focus-ring:var(--dw-focus-ring);--color-success:var(--dw-success);--color-success-soft:var(--dw-success-soft);--color-warning:var(--dw-warning);--color-warning-soft:var(--dw-warning-soft);--color-danger:var(--dw-danger);--color-danger-soft:var(--dw-danger-soft);--color-on-danger:var(--dw-on-danger);--color-info:var(--dw-info);--color-info-soft:var(--dw-info-soft);--color-code-bg:var(--dw-code-bg);--text-ui-xs:12px;--text-ui-xs--line-height:16px;--text-ui-xs--letter-spacing:.01em;--text-ui-xs--font-weight:500;--text-ui-sm:13px;--text-ui-sm--line-height:18px;--text-ui-md:14px;--text-ui-md--line-height:20px;--text-doc-h1:30px;--text-doc-h1--line-height:38px;--text-doc-h2:24px;--text-doc-h2--line-height:32px;--text-doc-h3:18px;--text-doc-h3--line-height:28px;--text-doc-body:16px;--text-doc-body--line-height:27px;--text-code:14px;--text-code--line-height:22px;--shadow-menu:var(--dw-shadow-menu);--container-doc:720px;--container-doc-wide:1040px;--spacing-control-sm:28px;--spacing-control-md:34px}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-Line truncated
/*$vite$:1*/</style>
</head>
<body>
+7 -10
View File
@@ -6,7 +6,7 @@ import { BubbleMenu } from "@tiptap/vue-3/menus";
import { CellSelection } from "@tiptap/pm/tables";
import { DwIcon, type IconName } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { blockHash, ensureBlockId } from "./blocklinks";
import { copyBlockLink } from "./blocklinks";
import { palette, type PaletteColor } from "./colors";
import { docwellExtensions, type CollabUser } from "./extensions";
import { findKey } from "./find";
@@ -188,13 +188,8 @@ const tools = computed<Tool[]>(() => {
active: () => false,
run: () => {
const $from = e.state.selection.$from;
const id = $from.depth >= 1 ? ensureBlockId(e.view, $from.before(1)) : null;
if (!id) return;
const url = blockLink(blockHash(id));
navigator.clipboard.writeText(url).then(
() => emit("block-link-copied", url),
() => window.prompt("", url),
);
if ($from.depth >= 1)
void copyBlockLink(e.view, $from.before(1), blockLink, (url) => emit("block-link-copied", url));
},
});
}
@@ -215,7 +210,7 @@ function setAlign(a: "left" | "center" | "right") {
// The table toolbar sits above the table the cursor is in.
type TableTool = {
id: Exclude<keyof EditorLabels["table"], "toolbar" | "dragRow">;
id: Exclude<keyof EditorLabels["table"], "toolbar" | "dragRow" | "dragColumn">;
run: (e: Editor) => boolean;
danger?: boolean;
};
@@ -226,6 +221,8 @@ const tableTools: TableTool[] = [
{ id: "addColumnAfter", run: (e) => e.chain().focus().addColumnAfter().run() },
{ id: "moveRowUp", run: (e) => e.chain().focus().moveTableRow(-1).run() },
{ id: "moveRowDown", run: (e) => e.chain().focus().moveTableRow(1).run() },
{ id: "moveColumnLeft", run: (e) => e.chain().focus().moveTableColumn(-1).run() },
{ id: "moveColumnRight", run: (e) => e.chain().focus().moveTableColumn(1).run() },
{ id: "deleteRow", run: (e) => e.chain().focus().deleteRow().run() },
{ id: "deleteColumn", run: (e) => e.chain().focus().deleteColumn().run() },
{ id: "toggleHeaderRow", run: (e) => e.chain().focus().toggleHeaderRow().run() },
@@ -533,7 +530,7 @@ defineExpose({ editor, openFind });
plugin-key="tableMenu"
:should-show="showTableMenu"
:get-referenced-virtual-element="tableElement"
:options="{ placement: 'top-start', offset: 6 }"
:options="{ placement: 'top-start', offset: 12 }"
class="flex max-w-[calc(100vw-16px)] flex-wrap items-center gap-0.5 rounded-md border border-line bg-surface-raised p-1 shadow-menu"
role="toolbar"
:aria-label="labels.table.toolbar"
+43 -10
View File
@@ -60,6 +60,28 @@ export function ensureBlockId(view: EditorView, pos: number): string | null {
return fresh;
}
/**
* Copies the full address of a link to the block at pos, giving the block an
* id first if it needs one. Returns false when the block cannot be linked.
*/
export async function copyBlockLink(
view: EditorView,
pos: number,
link: (hash: string) => string,
onCopied?: (url: string) => void,
): Promise<boolean> {
const id = ensureBlockId(view, pos);
if (!id) return false;
const url = link(blockHash(id));
try {
await navigator.clipboard.writeText(url);
onCopied?.(url);
} catch {
window.prompt("", url);
}
return true;
}
function findBlock(doc: PMNode, id: string): number {
let found = -1;
doc.descendants((node, pos) => {
@@ -130,6 +152,26 @@ export const BlockLinks = Extension.create<BlockLinkOptions>({
];
},
addKeyboardShortcuts() {
const { link, onCopied } = this.options;
return {
// Ctrl+Shift+C (as in AFFiNE): copy a link to the block the cursor is in.
// Some browsers keep the key for their developer tools; the toolbar
// and margin buttons do the same everywhere.
"Mod-Shift-c": ({ editor }) => {
if (!link) return false;
const $from = editor.state.selection.$from;
if ($from.depth < 1) return false;
const pos = $from.before(1);
const node = editor.state.doc.nodeAt(pos);
if (!node || !linkable.includes(node.type.name)) return false;
if (!node.attrs.blockId && !editor.isEditable) return false;
void copyBlockLink(editor.view, pos, link, onCopied);
return true;
},
};
},
addProseMirrorPlugins() {
const { link, onCopied } = this.options;
const labels = this.options.labels!;
@@ -284,16 +326,7 @@ class BlockHandle {
};
private async copy(at = this.pos) {
if (at < 0 || !this.link) return;
const id = ensureBlockId(this.view, at);
if (!id) return;
const url = this.link(blockHash(id));
try {
await navigator.clipboard.writeText(url);
this.onCopied?.(url);
} catch {
window.prompt("", url);
}
if (at >= 0 && this.link) await copyBlockLink(this.view, at, this.link, this.onCopied);
}
update() {
+33 -2
View File
@@ -84,10 +84,18 @@ describe("new blocks", () => {
it("offers the new blocks and date shortcuts in the slash menu", () => {
const ids = filterCommands(slashCommands(englishLabels), "").map((c) => c.id);
for (const id of ["h4", "h5", "h6", "todo", "callout", "table", "today", "tomorrow", "yesterday", "now"]) {
for (const id of ["otherHeadings", "todo", "callout", "table", "today", "tomorrow", "yesterday", "now"]) {
expect(ids).toContain(id);
}
expect(filterCommands(slashCommands(englishLabels), "other").map((c) => c.id)).toEqual(["h4", "h5", "h6"]);
// H4-H6 sit in a group, which a search looks into.
const all = slashCommands(englishLabels);
expect(all.find((c) => c.id === "otherHeadings")!.children!.map((c) => c.id)).toEqual(["h4", "h5", "h6"]);
expect(ids).not.toContain("h4");
expect(filterCommands(all, "other").map((c) => c.id)).toEqual(["otherHeadings"]);
expect(filterCommands(all, "h5").map((c) => c.id)).toEqual(["h5"]);
const headings = filterCommands(all, "heading").map((c) => c.id);
expect(headings).toEqual(expect.arrayContaining(["h1", "h4", "h5", "h6"]));
expect(headings).not.toContain("otherHeadings");
expect(ids).not.toContain("newPage");
const withPages = slashCommands(englishLabels, undefined, undefined, {
search: async () => [],
@@ -97,6 +105,29 @@ describe("new blocks", () => {
});
});
describe("Ctrl+Shift+C", () => {
it("copies a link to the block the cursor is in, giving it an id", async () => {
const written: string[] = [];
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: async (s: string) => void written.push(s) },
});
const copied: string[] = [];
const e = setup("<p>one</p><p>two</p>", {
blockLink: (hash) => `https://docwell.test/p/x${hash}`,
onBlockLinkCopied: (url) => copied.push(url),
});
e.commands.setTextSelection(e.state.doc.child(0).nodeSize + 2);
expect(e.commands.keyboardShortcut("Mod-Shift-c")).toBe(true);
await Promise.resolve();
const id = e.state.doc.child(1).attrs.blockId as string;
expect(id).toMatch(/^[a-z0-9]{8}$/);
expect(written).toEqual([`https://docwell.test/p/x#b-${id}`]);
expect(copied).toEqual(written);
expect(e.state.doc.child(0).attrs.blockId).toBeNull();
});
});
describe("blockActions", () => {
const doc = "<p>one</p><p>two</p><p>three</p>";
+20 -12
View File
@@ -1081,13 +1081,14 @@
.dw-block-menu .dw-suggest__item.is-danger :is(.dw-suggest__label, .dw-suggest__icon) {
color: var(--color-danger);
}
.dw-suggest__more,
.dw-block-menu__more {
margin-left: auto;
color: var(--color-ink-faint);
}
/* ---- Moving table rows (tablerows.ts) ---- */
.dw-row-grip {
/* ---- Moving table rows and columns (tablemove.ts) ---- */
.dw-table-grip {
position: absolute;
z-index: 5;
display: grid;
@@ -1102,36 +1103,43 @@
cursor: grab;
touch-action: none;
}
.dw-row-grip::before {
.dw-table-grip--column {
width: 22px;
height: 14px;
}
.dw-table-grip::before {
content: "";
width: 4px;
height: 10px;
background: radial-gradient(circle, currentColor 1px, transparent 1.5px) 0 0 / 4px 4px;
}
.dw-row-grip:hover,
.dw-row-grip:active {
.dw-table-grip--column::before {
width: 10px;
height: 4px;
}
.dw-table-grip:hover,
.dw-table-grip:active {
color: var(--color-ink);
border-color: var(--color-focus-ring);
}
.dw-row-grip:active {
.dw-table-grip:active {
cursor: grabbing;
}
.dw-row-grip[hidden],
.dw-row-drop[hidden] {
.dw-table-grip[hidden],
.dw-table-drop[hidden] {
display: none;
}
.dw-row-drop {
.dw-table-drop {
position: absolute;
z-index: 5;
height: 2px;
background: var(--color-focus-ring);
pointer-events: none;
}
.dw-prose tr.dw-row-dragging {
.dw-prose .dw-table-dragging {
opacity: 0.45;
}
@media (max-width: 640px), (hover: none) {
.dw-row-grip {
.dw-table-grip {
display: none;
}
}
+2 -2
View File
@@ -24,7 +24,7 @@ import { PageLinks, type PageHost } from "./pagelinks";
import type { PdfLoader } from "./pdf";
import { SlashMenu, slashCommands } from "./slash";
import type { CollabProvider } from "./provider";
import { TableRows } from "./tablerows";
import { TableMove } from "./tablemove";
import { TableOfContents } from "./toc";
import { docwellToggles } from "./toggle";
@@ -110,7 +110,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
DocwellHighlight,
...docwellTasks(),
...docwellTables(),
TableRows.configure({ labels }),
TableMove.configure({ labels }),
Callout.configure({ labels }),
FileDrop.configure({ host: opts.files, onError: opts.onError }),
docwellMention(labels, opts.mentions),
+11 -3
View File
@@ -41,8 +41,12 @@ export interface EditorLabels {
toolbar: string;
/** The grip on a row's left edge. */
dragRow: string;
/** The grip on a column's top edge. */
dragColumn: string;
moveRowUp: string;
moveRowDown: string;
moveColumnLeft: string;
moveColumnRight: string;
addRowBefore: string;
addRowAfter: string;
addColumnBefore: string;
@@ -138,9 +142,10 @@ export const englishLabels: EditorLabels = {
h1: { label: "Heading 1", description: "Big section heading" },
h2: { label: "Heading 2", description: "Medium section heading" },
h3: { label: "Heading 3", description: "Small section heading" },
h4: { label: "Heading 4", description: "Other headings: level 4" },
h5: { label: "Heading 5", description: "Other headings: level 5" },
h6: { label: "Heading 6", description: "Other headings: level 6" },
otherHeadings: { label: "Other headings", description: "Headings 4 to 6" },
h4: { label: "Heading 4", description: "A heading below level 3" },
h5: { label: "Heading 5", description: "A heading below level 4" },
h6: { label: "Heading 6", description: "The smallest heading" },
bullet: { label: "Bulleted list", description: "A simple list" },
ordered: { label: "Numbered list", description: "A list with numbers" },
todo: { label: "To-do list", description: "Tasks to tick off (or type [])" },
@@ -201,8 +206,11 @@ export const englishLabels: EditorLabels = {
table: {
toolbar: "Table",
dragRow: "Drag to move the row",
dragColumn: "Drag to move the column",
moveRowUp: "Move row up",
moveRowDown: "Move row down",
moveColumnLeft: "Move column left",
moveColumnRight: "Move column right",
addRowBefore: "Add row above",
addRowAfter: "Add row below",
addColumnBefore: "Add column left",
+22 -9
View File
@@ -20,6 +20,8 @@ export interface SlashCommand {
/** Extra words the filter matches, e.g. "h1" for Heading 1. */
keywords: string[];
run: (editor: Editor, range: Range) => void;
/** A group: picking it opens these instead of running. A search finds them directly too. */
children?: SlashCommand[];
}
/** Opens the system file picker and resolves with the chosen files. */
@@ -67,11 +69,14 @@ export function slashCommands(
block("h3", "heading", ["heading", "###"], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level: 3 }).run(),
),
...([4, 5, 6] as const).map((level) =>
block(`h${level}`, "heading", ["heading", "other headings", "#".repeat(level)], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level }).run(),
{
...block("otherHeadings", "heading", ["other", "more headings", "smaller"], () => {}),
children: ([4, 5, 6] as const).map((level) =>
block(`h${level}`, "heading", ["heading", "#".repeat(level)], (e, r) =>
e.chain().focus().deleteRange(r).setHeading({ level }).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(),
@@ -168,14 +173,21 @@ export function slashCommands(
return list;
}
/** Filters commands by what follows the "/": label, id or keywords. */
/**
* Filters commands by what follows the "/": label, id or keywords. With a
* query, the commands inside groups are matched and listed on their own.
*/
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)),
);
const matches = (c: SlashCommand) =>
c.label.toLowerCase().includes(q) || c.id.startsWith(q) || c.keywords.some((k) => k.toLowerCase().startsWith(q));
return commands.flatMap((c) => {
// A search finds the commands in a group; the group itself when none of them match.
const inside = c.children?.filter(matches) ?? [];
if (inside.length) return inside;
return matches(c) ? [c] : [];
});
}
/** Typing "/" at the start of a word opens the block menu. */
@@ -205,6 +217,7 @@ export const SlashMenu = Extension.create<{ commands: SlashCommand[]; labels: Ed
empty: this.options.labels.noMatches,
showQuery: true,
toItem: (c) => ({ label: c.label, description: c.description, icon: c.icon }),
children: (c) => c.children,
pick: (p, c) => c.run(p.editor, p.range),
}),
}),
+48 -6
View File
@@ -49,16 +49,29 @@ export function floatingList<T>(opts: {
toItem: (item: T) => ListItem;
pick: (props: SuggestionProps<T>, item: T) => void;
showQuery?: boolean;
/** An item that opens a list of its own instead of being picked ("Other headings"). */
children?: (item: T) => T[] | undefined;
}) {
return () => {
let box: HTMLDivElement | null = null;
let stop: (() => void) | null = null;
let current: SuggestionProps<T> | null = null;
let active = 0;
// The list of a group the user opened, with the group, until the query changes.
let sub: { parent: T; items: T[] } | null = null;
const items = () => sub?.items ?? current?.items ?? [];
const choose = (i: number) => {
const item = current?.items[i];
if (current && item !== undefined) opts.pick(current, item);
const item = items()[i];
if (!current || item === undefined) return;
const kids = opts.children?.(item);
if (kids?.length) {
sub = { parent: item, items: kids };
active = 0;
draw();
return;
}
opts.pick(current, item);
};
const draw = () => {
@@ -71,7 +84,15 @@ export function floatingList<T>(opts: {
q.textContent = `/${p.query}`;
box.append(q);
}
if (!p.items.length) {
if (sub) {
// The open group, which ArrowLeft or Escape leaves.
const head = document.createElement("div");
head.className = "dw-suggest__query";
head.textContent = `‹ ${opts.toItem(sub.parent).label}`;
box.append(head);
}
const list = items();
if (!list.length) {
const empty = document.createElement("div");
empty.className = "dw-suggest__empty";
empty.setAttribute("role", "status");
@@ -79,7 +100,7 @@ export function floatingList<T>(opts: {
box.append(empty);
return;
}
p.items.forEach((raw, i) => {
list.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";
@@ -106,6 +127,12 @@ export function floatingList<T>(opts: {
text.append(desc);
}
row.append(glyph, text);
if (opts.children?.(raw)?.length) {
row.setAttribute("aria-haspopup", "listbox");
const more = svgIcon("chevron-right", 14);
more.classList.add("dw-suggest__more");
row.append(more);
}
box!.append(row);
});
box.querySelector(".is-active")?.scrollIntoView({ block: "nearest" });
@@ -139,6 +166,7 @@ export function floatingList<T>(opts: {
onStart(p: SuggestionProps<T>) {
current = p;
active = 0;
sub = null;
box = document.createElement("div");
box.className = "dw-suggest";
box.setAttribute("role", "listbox");
@@ -148,13 +176,27 @@ export function floatingList<T>(opts: {
place();
},
onUpdate(p: SuggestionProps<T>) {
if (p.items !== current?.items) active = 0;
if (p.items !== current?.items) {
active = 0;
sub = null;
}
current = p;
draw();
place();
},
onKeyDown({ event }: SuggestionKeyDownProps) {
const n = current?.items.length ?? 0;
const n = items().length;
if (sub && (event.key === "Escape" || event.key === "ArrowLeft")) {
sub = null;
active = 0;
draw();
return true;
}
const at = items()[active];
if (event.key === "ArrowRight" && at !== undefined && opts.children?.(at)?.length) {
choose(active);
return true;
}
if (event.key === "Escape") {
close();
return true;
+118
View File
@@ -0,0 +1,118 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Editor } from "@tiptap/core";
import { afterEach, describe, expect, it } from "vitest";
import { docwellExtensions } from "./extensions";
import { moveInTable } from "./tablemove";
let editor: Editor | undefined;
afterEach(() => editor?.destroy());
/** A table after a paragraph; each row is its cells' text. */
const table = (rows: string[][]) =>
`<p>before</p><table>${rows.map((r) => `<tr>${r.map((c) => `<td><p>${c}</p></td>`).join("")}</tr>`).join("")}</table>`;
function setup(html: string) {
editor = new Editor({ extensions: docwellExtensions(), content: html });
return editor;
}
const grid = (e: Editor) => {
const out: string[][] = [];
e.state.doc.descendants((n) => {
if (n.type.name === "tableRow") out.push(Array.from({ length: n.childCount }, (_, i) => n.child(i).textContent));
return n.type.name !== "tableRow";
});
return out;
};
const tablePos = (e: Editor) => e.state.doc.child(0).nodeSize;
/** A position inside the cell at row, column. */
function inCell(e: Editor, row: number, column: number) {
let pos = -1;
let r = 0;
e.state.doc.descendants((n, p) => {
if (pos >= 0) return false;
if (n.type.name !== "tableRow") return true;
if (r++ === row) {
pos = p + 1;
for (let i = 0; i < column; i++) pos += n.child(i).nodeSize;
pos += 2;
}
return false;
});
return pos;
}
const abc = [
["a", "a2"],
["b", "b2"],
["c", "c2"],
];
describe("moving table rows", () => {
it("moves a row to another place and keeps the cursor in it", () => {
const e = setup(table(abc));
e.view.dispatch(moveInTable(e.state, tablePos(e), "row", 0, 2)!);
expect(grid(e).map((r) => r[0])).toEqual(["b", "c", "a"]);
expect(e.state.selection.$from.parent.textContent).toBe("a");
});
it("moves the cursor's row up and down with the commands", () => {
const e = setup(table(abc));
e.commands.setTextSelection(inCell(e, 1, 0));
expect(e.commands.moveTableRow(-1)).toBe(true);
expect(grid(e).map((r) => r[0])).toEqual(["b", "a", "c"]);
expect(e.commands.moveTableRow(-1)).toBe(false);
e.commands.moveTableRow(1);
e.commands.moveTableRow(1);
expect(grid(e).map((r) => r[0])).toEqual(["a", "c", "b"]);
expect(e.commands.moveTableRow(1)).toBe(false);
});
it("does nothing outside a table, or where a cell spans rows", () => {
const e = setup(
"<p>before</p><table><tr><td rowspan='2'><p>x</p></td><td><p>a</p></td></tr><tr><td><p>b</p></td></tr></table>",
);
expect(moveInTable(e.state, tablePos(e), "row", 0, 1)).toBeNull();
e.commands.setTextSelection(2);
expect(e.commands.moveTableRow(1)).toBe(false);
});
});
describe("moving table columns", () => {
const cols = [
["n", "r", "x"],
["ada", "lead", "1"],
];
it("moves a column in every row and keeps the cursor in its cell", () => {
const e = setup(table(cols));
e.view.dispatch(moveInTable(e.state, tablePos(e), "column", 0, 2, 1)!);
expect(grid(e)).toEqual([
["r", "x", "n"],
["lead", "1", "ada"],
]);
expect(e.state.selection.$from.parent.textContent).toBe("ada");
});
it("moves the cursor's column left and right with the commands", () => {
const e = setup(table(cols));
e.commands.setTextSelection(inCell(e, 1, 1));
expect(e.commands.moveTableColumn(1)).toBe(true);
expect(grid(e)[0]).toEqual(["n", "x", "r"]);
expect(e.state.selection.$from.parent.textContent).toBe("lead");
expect(e.commands.moveTableColumn(1)).toBe(false);
e.commands.moveTableColumn(-1);
e.commands.moveTableColumn(-1);
expect(grid(e)[1]).toEqual(["lead", "ada", "1"]);
});
it("does nothing where a cell spans columns", () => {
const e = setup(
"<p>before</p><table><tr><td colspan='2'><p>x</p></td></tr><tr><td><p>a</p></td><td><p>b</p></td></tr></table>",
);
expect(moveInTable(e.state, tablePos(e), "column", 0, 1)).toBeNull();
});
});
+344
View File
@@ -0,0 +1,344 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension } from "@tiptap/core";
import { Fragment, type Node as PMNode } from "@tiptap/pm/model";
import { Plugin, PluginKey, Selection, type EditorState, type Transaction } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import type { EditorLabels } from "./labels";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
tableMove: {
/** Moves the table row the selection is in one place up (-1) or down (1). */
moveTableRow: (direction: -1 | 1) => ReturnType;
/** Moves the table column the selection is in one place left (-1) or right (1). */
moveTableColumn: (direction: -1 | 1) => ReturnType;
};
}
}
export type Axis = "row" | "column";
/**
* Whether rows (or columns) can move: cells spanning several of them would
* be pulled apart, and columns need every row to have the same cells.
*/
export function movable(table: PMNode, axis: Axis): boolean {
let ok = true;
const width = table.firstChild?.childCount ?? 0;
table.forEach((row) => {
if (axis === "column" && row.childCount !== width) ok = false;
row.forEach((cell) => {
const span = axis === "row" ? cell.attrs.rowspan : cell.attrs.colspan;
if ((span ?? 1) > 1) ok = false;
});
});
return ok;
}
function moved<T>(list: T[], from: number, to: number): T[] {
const out = [...list];
const [item] = out.splice(from, 1);
out.splice(to, 0, item!);
return out;
}
const children = (n: PMNode) => {
const out: PMNode[] = [];
n.forEach((c) => out.push(c));
return out;
};
/**
* A transaction that moves row (or column) from of the table at tablePos to
* index to, as an index in the table as it will be, leaving the cursor in
* the moved row or column. Null when nothing would change or it cannot move.
*/
export function moveInTable(
state: EditorState,
tablePos: number,
axis: Axis,
from: number,
to: number,
/** The row the cursor goes to when a column moves. */
cursorRow = 0,
): Transaction | null {
const table = state.doc.nodeAt(tablePos);
if (!table || table.type.name !== "table" || !movable(table, axis)) return null;
const rows = children(table);
const count = axis === "row" ? rows.length : (rows[0]?.childCount ?? 0);
if (from === to || from < 0 || to < 0 || from >= count || to >= count) return null;
const newRows =
axis === "row" ? moved(rows, from, to) : rows.map((r) => r.copy(Fragment.fromArray(moved(children(r), from, to))));
const tr = state.tr.replaceWith(tablePos, tablePos + table.nodeSize, table.copy(Fragment.fromArray(newRows)));
// The cell to put the cursor in: the moved row's first, or the moved column's in cursorRow.
const [row, col] = axis === "row" ? [to, 0] : [Math.min(cursorRow, newRows.length - 1), to];
let pos = tablePos + 1;
for (let i = 0; i < row; i++) pos += newRows[i]!.nodeSize;
pos += 1;
for (let i = 0; i < col; i++) pos += newRows[row]!.child(i).nodeSize;
return tr.setSelection(Selection.near(tr.doc.resolve(pos + 1))).scrollIntoView();
}
/** The table around pos, and the row and column pos is in, or null. */
function cellAt(state: EditorState, pos: number): { tablePos: number; row: number; column: number } | null {
const $pos = state.doc.resolve(pos);
for (let d = $pos.depth; d > 0; d--) {
if ($pos.node(d).type.name === "table") {
return { tablePos: $pos.before(d), row: $pos.index(d), column: d + 1 <= $pos.depth ? $pos.index(d + 1) : 0 };
}
}
return null;
}
/**
* Moving table rows and columns: grips on the left edge of the row and the
* top edge of the column under the pointer drag them to another place, and
* the commands move them from the keyboard (Ctrl+Alt+arrows) or a toolbar.
*/
export const TableMove = Extension.create<{ labels: EditorLabels | null }>({
name: "tableMove",
addOptions() {
return { labels: null };
},
addCommands() {
const command =
(axis: Axis) =>
(direction: -1 | 1) =>
({ state, dispatch }: { state: EditorState; dispatch?: (tr: Transaction) => void }) => {
const at = cellAt(state, state.selection.from);
if (!at) return false;
const index = axis === "row" ? at.row : at.column;
const tr = moveInTable(state, at.tablePos, axis, index, index + direction, at.row);
if (!tr) return false;
dispatch?.(tr);
return true;
};
return { moveTableRow: command("row"), moveTableColumn: command("column") };
},
addKeyboardShortcuts() {
return {
"Mod-Alt-ArrowUp": () => this.editor.commands.moveTableRow(-1),
"Mod-Alt-ArrowDown": () => this.editor.commands.moveTableRow(1),
"Mod-Alt-ArrowLeft": () => this.editor.commands.moveTableColumn(-1),
"Mod-Alt-ArrowRight": () => this.editor.commands.moveTableColumn(1),
};
},
addProseMirrorPlugins() {
const t = this.options.labels?.table;
return [
new Plugin({
key: new PluginKey("tableMove"),
view: (view) =>
new TableGrips(view, {
row: t?.dragRow ?? "Drag to move the row",
column: t?.dragColumn ?? "Drag to move the column",
}),
}),
];
},
});
interface Drag {
axis: Axis;
tablePos: number;
from: number;
/** The rows, or the first row's cells, as they are on screen. */
slots: HTMLElement[];
/** The cells being moved, dimmed while dragging. */
dimmed: HTMLElement[];
to: number;
cursorRow: number;
}
/** The grips beside the row and column under the pointer, and the line showing where a dragged one will go. */
class TableGrips {
private grips: Record<Axis, HTMLButtonElement> = {
row: document.createElement("button"),
column: document.createElement("button"),
};
private line = document.createElement("div");
private cell: HTMLTableCellElement | null = null;
private drag: Drag | null = null;
constructor(
private view: EditorView,
labels: Record<Axis, string>,
) {
for (const axis of ["row", "column"] as const) {
const g = this.grips[axis];
g.type = "button";
g.className = `dw-table-grip dw-table-grip--${axis}`;
g.contentEditable = "false";
g.setAttribute("aria-label", labels[axis]);
g.title = labels[axis];
g.hidden = true;
// Keyboard and screen reader users move rows and columns with the table toolbar or Ctrl+Alt+arrows.
g.tabIndex = -1;
g.addEventListener("pointerdown", (e) => this.start(e, axis));
g.addEventListener("mouseleave", this.leave);
}
this.line.className = "dw-table-drop";
this.line.hidden = true;
view.dom.addEventListener("mousemove", this.move);
view.dom.addEventListener("mouseleave", this.leave);
}
private get host(): HTMLElement | null {
const host = this.view.dom.parentElement;
if (host && this.line.parentElement !== host) {
host.classList.add("dw-block-host");
host.append(this.grips.row, this.grips.column, this.line);
}
return host;
}
private hide = () => {
if (this.drag) return;
this.grips.row.hidden = true;
this.grips.column.hidden = true;
this.cell = null;
};
private leave = (e: MouseEvent) => {
const to = e.relatedTarget as Node | null;
if (to && (this.grips.row.contains(to) || this.grips.column.contains(to) || this.view.dom.contains(to))) return;
this.hide();
};
private move = (e: MouseEvent) => {
if (this.drag) return;
const cell = (e.target as HTMLElement | null)?.closest?.("td, th");
const host = this.host;
if (!this.view.editable || !host || !(cell instanceof HTMLTableCellElement) || !this.view.dom.contains(cell)) {
return this.hide();
}
const at = this.locate(cell);
const table = at && this.view.state.doc.nodeAt(at.tablePos);
if (!at || !table) return this.hide();
this.cell = cell;
const hostBox = host.getBoundingClientRect();
const tableBox = cell.closest("table")!.getBoundingClientRect();
const rowBox = cell.parentElement!.getBoundingClientRect();
const cellBox = cell.getBoundingClientRect();
const showRow = table.childCount > 1 && movable(table, "row");
const showColumn = (table.firstChild?.childCount ?? 0) > 1 && movable(table, "column");
Object.assign(this.grips.row.style, {
top: `${rowBox.top - hostBox.top + rowBox.height / 2 - 11}px`,
left: `${tableBox.left - hostBox.left - 7}px`,
});
Object.assign(this.grips.column.style, {
top: `${tableBox.top - hostBox.top - 7}px`,
left: `${cellBox.left - hostBox.left + cellBox.width / 2 - 11}px`,
});
this.grips.row.hidden = !showRow;
this.grips.column.hidden = !showColumn;
};
private locate(cell: HTMLTableCellElement) {
try {
return cellAt(this.view.state, this.view.posAtDOM(cell, 0));
} catch {
return null;
}
}
private start(e: PointerEvent, axis: Axis) {
const cell = this.cell;
if (!cell || e.button !== 0) return;
const at = this.locate(cell);
const tbody = cell.parentElement?.parentElement;
if (!at || !tbody) return;
e.preventDefault();
const grip = this.grips[axis];
grip.setPointerCapture(e.pointerId);
const rows = [...tbody.children].filter((r): r is HTMLTableRowElement => r instanceof HTMLTableRowElement);
const from = axis === "row" ? at.row : at.column;
const slots = axis === "row" ? rows : ([...(rows[0]?.children ?? [])] as HTMLElement[]);
const dimmed = axis === "row" ? [rows[from]!] : rows.map((r) => r.children[from] as HTMLElement).filter(Boolean);
for (const el of dimmed) el.classList.add("dw-table-dragging");
this.drag = { axis, tablePos: at.tablePos, from, slots, dimmed, to: from, cursorRow: at.row };
grip.addEventListener("pointermove", this.dragMove);
grip.addEventListener("pointerup", this.drop);
grip.addEventListener("pointercancel", this.cancel);
}
/** Shows the line at the gap nearest the pointer. */
private dragMove = (e: PointerEvent) => {
const d = this.drag;
const host = this.host;
if (!d || !host) return;
const rowAxis = d.axis === "row";
const point = rowAxis ? e.clientY : e.clientX;
let gap = d.slots.length;
for (const [i, el] of d.slots.entries()) {
const b = el.getBoundingClientRect();
if (point < (rowAxis ? b.top + b.height / 2 : b.left + b.width / 2)) {
gap = i;
break;
}
}
// A gap next to the moving one itself leaves it where it is.
d.to = gap > d.from ? gap - 1 : gap;
const hostBox = host.getBoundingClientRect();
const table = d.slots[0]!.closest("table")!.getBoundingClientRect();
const last = d.slots.at(-1)!.getBoundingClientRect();
const next = d.slots[gap]?.getBoundingClientRect();
const edge = rowAxis ? (next?.top ?? last.bottom) : (next?.left ?? last.right);
Object.assign(
this.line.style,
rowAxis
? {
top: `${edge - hostBox.top - 1}px`,
left: `${table.left - hostBox.left}px`,
width: `${table.width}px`,
height: "2px",
}
: {
top: `${table.top - hostBox.top}px`,
left: `${edge - hostBox.left - 1}px`,
width: "2px",
height: `${table.height}px`,
},
);
this.line.hidden = d.to === d.from;
};
private drop = () => {
const d = this.drag;
this.cancel();
if (!d || d.to === d.from) return;
const tr = moveInTable(this.view.state, d.tablePos, d.axis, d.from, d.to, d.cursorRow);
if (tr) this.view.dispatch(tr);
this.view.focus();
};
private cancel = () => {
const d = this.drag;
for (const el of d?.dimmed ?? []) el.classList.remove("dw-table-dragging");
this.drag = null;
this.line.hidden = true;
for (const g of Object.values(this.grips)) {
g.removeEventListener("pointermove", this.dragMove);
g.removeEventListener("pointerup", this.drop);
g.removeEventListener("pointercancel", this.cancel);
}
this.hide();
};
update() {
if (this.cell && !this.cell.isConnected) this.hide();
}
destroy() {
this.cancel();
for (const g of Object.values(this.grips)) g.remove();
this.line.remove();
this.view.dom.removeEventListener("mousemove", this.move);
this.view.dom.removeEventListener("mouseleave", this.leave);
}
}
-72
View File
@@ -1,72 +0,0 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Editor } from "@tiptap/core";
import { afterEach, describe, expect, it } from "vitest";
import { docwellExtensions } from "./extensions";
import { moveRow } from "./tablerows";
let editor: Editor | undefined;
afterEach(() => editor?.destroy());
const table = (rows: string[]) =>
`<p>before</p><table>${rows.map((r) => `<tr><td><p>${r}</p></td><td><p>${r}2</p></td></tr>`).join("")}</table>`;
function setup(html: string) {
editor = new Editor({ extensions: docwellExtensions(), content: html });
return editor;
}
const rowTexts = (e: Editor) => {
const out: string[] = [];
e.state.doc.descendants((n) => {
if (n.type.name === "tableRow") out.push(n.firstChild!.textContent);
return n.type.name !== "tableRow";
});
return out;
};
const tablePos = (e: Editor) => e.state.doc.child(0).nodeSize;
/** A position inside the first cell of row index. */
function inRow(e: Editor, index: number) {
let pos = -1;
let seen = 0;
e.state.doc.descendants((n, p) => {
if (pos >= 0) return false;
if (n.type.name === "tableRow" && seen++ === index) pos = p + 3;
return true;
});
return pos;
}
describe("moving table rows", () => {
it("moves a row to another place and keeps the cursor in it", () => {
const e = setup(table(["a", "b", "c"]));
e.view.dispatch(moveRow(e.state, tablePos(e), 0, 2)!);
expect(rowTexts(e)).toEqual(["b", "c", "a"]);
expect(e.state.selection.$from.parent.textContent).toBe("a");
e.view.dispatch(moveRow(e.state, tablePos(e), 2, 1)!);
expect(rowTexts(e)).toEqual(["b", "a", "c"]);
});
it("moves the cursor's row up and down from the keyboard command", () => {
const e = setup(table(["a", "b", "c"]));
e.commands.setTextSelection(inRow(e, 1));
expect(e.commands.moveTableRow(-1)).toBe(true);
expect(rowTexts(e)).toEqual(["b", "a", "c"]);
expect(e.commands.moveTableRow(-1)).toBe(false);
e.commands.moveTableRow(1);
e.commands.moveTableRow(1);
expect(rowTexts(e)).toEqual(["a", "c", "b"]);
expect(e.commands.moveTableRow(1)).toBe(false);
});
it("does nothing outside a table, or where a cell spans rows", () => {
const e = setup(
"<p>before</p><table><tr><td rowspan='2'><p>x</p></td><td><p>a</p></td></tr><tr><td><p>b</p></td></tr></table>",
);
expect(moveRow(e.state, tablePos(e), 0, 1)).toBeNull();
e.commands.setTextSelection(2);
expect(e.commands.moveTableRow(1)).toBe(false);
});
});
-242
View File
@@ -1,242 +0,0 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { Extension } from "@tiptap/core";
import { Fragment, type Node as PMNode } from "@tiptap/pm/model";
import { Plugin, PluginKey, Selection, type EditorState, type Transaction } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import type { EditorLabels } from "./labels";
declare module "@tiptap/core" {
interface Commands<ReturnType> {
tableRows: {
/** Moves the table row the selection is in one place up (-1) or down (1). */
moveTableRow: (direction: -1 | 1) => ReturnType;
};
}
}
/** Whether a row can move: rows joined by a cell spanning several rows cannot be pulled apart. */
export function rowsMovable(table: PMNode): boolean {
let ok = true;
table.forEach((row) => row.forEach((cell) => (ok &&= (cell.attrs.rowspan ?? 1) <= 1)));
return ok;
}
/**
* A transaction that moves row from of the table at tablePos to index to (an
* index in the table as it will be), leaving the cursor in the moved row.
* Null when nothing would change or the rows cannot move.
*/
export function moveRow(state: EditorState, tablePos: number, from: number, to: number): Transaction | null {
const table = state.doc.nodeAt(tablePos);
if (!table || table.type.name !== "table" || !rowsMovable(table)) return null;
const rows: PMNode[] = [];
table.forEach((r) => rows.push(r));
if (from === to || from < 0 || to < 0 || from >= rows.length || to >= rows.length) return null;
const [row] = rows.splice(from, 1);
rows.splice(to, 0, row!);
const tr = state.tr.replaceWith(tablePos, tablePos + table.nodeSize, table.copy(Fragment.fromArray(rows)));
let rowStart = tablePos + 1;
for (let i = 0; i < to; i++) rowStart += rows[i]!.nodeSize;
return tr.setSelection(Selection.near(tr.doc.resolve(rowStart + 1))).scrollIntoView();
}
/** The table around $pos and the index of the row $pos is in, or null. */
function rowAt(state: EditorState, pos: number): { tablePos: number; index: number } | null {
const $pos = state.doc.resolve(pos);
for (let d = $pos.depth; d > 0; d--) {
if ($pos.node(d).type.name === "table") return { tablePos: $pos.before(d), index: $pos.index(d) };
}
return null;
}
/**
* Moving table rows: a grip on the left edge of the row under the pointer
* drags the row to another place, and moveTableRow moves it from the
* keyboard or a toolbar.
*/
export const TableRows = Extension.create<{ labels: EditorLabels | null }>({
name: "tableRows",
addOptions() {
return { labels: null };
},
addCommands() {
return {
moveTableRow:
(direction) =>
({ state, dispatch }) => {
const at = rowAt(state, state.selection.from);
if (!at) return false;
const tr = moveRow(state, at.tablePos, at.index, at.index + direction);
if (!tr) return false;
dispatch?.(tr);
return true;
},
};
},
addKeyboardShortcuts() {
return {
"Mod-Alt-ArrowUp": () => this.editor.commands.moveTableRow(-1),
"Mod-Alt-ArrowDown": () => this.editor.commands.moveTableRow(1),
};
},
addProseMirrorPlugins() {
const label = this.options.labels?.table.dragRow ?? "Drag to move the row";
return [new Plugin({ key: new PluginKey("tableRows"), view: (view) => new RowGrip(view, label) })];
},
});
/** The grip beside the table row under the pointer, and the line showing where a dragged row will go. */
class RowGrip {
private grip = document.createElement("button");
private line = document.createElement("div");
private row: HTMLTableRowElement | null = null;
private drag: { tablePos: number; from: number; rows: HTMLTableRowElement[]; to: number } | null = null;
constructor(
private view: EditorView,
label: string,
) {
const g = this.grip;
g.type = "button";
g.className = "dw-row-grip";
g.contentEditable = "false";
g.setAttribute("aria-label", label);
g.title = label;
g.hidden = true;
// Keyboard and screen reader users move rows with the table toolbar or Ctrl+Alt+arrows.
g.tabIndex = -1;
g.addEventListener("pointerdown", this.start);
g.addEventListener("mouseleave", this.leave);
this.line.className = "dw-row-drop";
this.line.hidden = true;
view.dom.addEventListener("mousemove", this.move);
view.dom.addEventListener("mouseleave", this.leave);
}
private get host(): HTMLElement | null {
const host = this.view.dom.parentElement;
if (host && this.grip.parentElement !== host) {
host.classList.add("dw-block-host");
host.append(this.grip, this.line);
}
return host;
}
private hide = () => {
if (this.drag) return;
this.grip.hidden = true;
this.row = null;
};
private leave = (e: MouseEvent) => {
const to = e.relatedTarget as Node | null;
if (to && (this.grip.contains(to) || this.view.dom.contains(to))) return;
this.hide();
};
private move = (e: MouseEvent) => {
if (this.drag) return;
const tr = (e.target as HTMLElement | null)?.closest?.("tr");
const host = this.host;
if (!this.view.editable || !host || !(tr instanceof HTMLTableRowElement) || !this.view.dom.contains(tr)) {
return this.hide();
}
const at = this.locate(tr);
const table = at && this.view.state.doc.nodeAt(at.tablePos);
if (!at || !table || table.childCount < 2 || !rowsMovable(table)) return this.hide();
this.row = tr;
const box = tr.getBoundingClientRect();
const hostBox = host.getBoundingClientRect();
Object.assign(this.grip.style, {
top: `${box.top - hostBox.top + box.height / 2 - 11}px`,
left: `${box.left - hostBox.left - 7}px`,
});
this.grip.hidden = false;
};
private locate(tr: HTMLTableRowElement) {
try {
return rowAt(this.view.state, this.view.posAtDOM(tr, 0));
} catch {
return null;
}
}
private start = (e: PointerEvent) => {
if (!this.row || e.button !== 0) return;
const at = this.locate(this.row);
const tbody = this.row.parentElement;
if (!at || !tbody) return;
e.preventDefault();
this.grip.setPointerCapture(e.pointerId);
const rows = [...tbody.children].filter((r): r is HTMLTableRowElement => r instanceof HTMLTableRowElement);
this.drag = { tablePos: at.tablePos, from: at.index, rows, to: at.index };
this.row.classList.add("dw-row-dragging");
this.grip.addEventListener("pointermove", this.dragMove);
this.grip.addEventListener("pointerup", this.drop);
this.grip.addEventListener("pointercancel", this.cancel);
};
/** Shows the line at the gap between rows nearest the pointer. */
private dragMove = (e: PointerEvent) => {
const d = this.drag;
const host = this.host;
if (!d || !host) return;
let gap = d.rows.length;
for (const [i, r] of d.rows.entries()) {
const b = r.getBoundingClientRect();
if (e.clientY < b.top + b.height / 2) {
gap = i;
break;
}
}
// A gap next to the row itself leaves it where it is.
d.to = gap > d.from ? gap - 1 : gap;
const hostBox = host.getBoundingClientRect();
const first = d.rows[0]!.getBoundingClientRect();
const edge =
gap < d.rows.length ? d.rows[gap]!.getBoundingClientRect().top : d.rows.at(-1)!.getBoundingClientRect().bottom;
Object.assign(this.line.style, {
top: `${edge - hostBox.top - 1}px`,
left: `${first.left - hostBox.left}px`,
width: `${first.width}px`,
});
this.line.hidden = d.to === d.from;
};
private drop = () => {
const d = this.drag;
this.cancel();
if (!d || d.to === d.from) return;
const tr = moveRow(this.view.state, d.tablePos, d.from, d.to);
if (tr) this.view.dispatch(tr);
this.view.focus();
};
private cancel = () => {
this.row?.classList.remove("dw-row-dragging");
this.drag = null;
this.line.hidden = true;
this.grip.removeEventListener("pointermove", this.dragMove);
this.grip.removeEventListener("pointerup", this.drop);
this.grip.removeEventListener("pointercancel", this.cancel);
this.hide();
};
update() {
if (this.row && !this.row.isConnected) this.hide();
}
destroy() {
this.cancel();
this.grip.remove();
this.line.remove();
this.view.dom.removeEventListener("mousemove", this.move);
this.view.dom.removeEventListener("mouseleave", this.leave);
}
}
+3
View File
@@ -503,6 +503,7 @@ func (e CreateApiTokenJSONBodyScope) Valid() bool {
// Defines values for ExportPageParamsFormat.
const (
ExportPageParamsFormatDocx ExportPageParamsFormat = "docx"
ExportPageParamsFormatHtml ExportPageParamsFormat = "html"
ExportPageParamsFormatMarkdown ExportPageParamsFormat = "markdown"
ExportPageParamsFormatPdf ExportPageParamsFormat = "pdf"
@@ -511,6 +512,8 @@ const (
// Valid indicates whether the value is a known member of the ExportPageParamsFormat enum.
func (e ExportPageParamsFormat) Valid() bool {
switch e {
case ExportPageParamsFormatDocx:
return true
case ExportPageParamsFormatHtml:
return true
case ExportPageParamsFormatMarkdown:
+94
View File
@@ -3,7 +3,11 @@
package convert
import (
"archive/zip"
"bytes"
"encoding/xml"
"errors"
"io"
"strings"
"testing"
)
@@ -151,3 +155,93 @@ func TestNearestPalette(t *testing.T) {
}
}
}
func TestDOCXRoundTrip(t *testing.T) {
src := mustParse(t, phaseA)
data, err := DOCX("Blocks", src, DOCXOptions{})
if err != nil {
t.Fatal(err)
}
doc, _, err := FromDOCX(data)
if err != nil {
t.Fatal(err)
}
title, body := Title(doc)
if title != "Blocks" {
t.Errorf("title = %q", title)
}
if got, want := Markdown(body, Options{}), Markdown(src, Options{}); got != want {
t.Errorf("word round trip:\n%s\nwant\n%s", got, want)
}
j := asJSON(t, body)
for _, want := range []string{
`"textAlign":"right"`, `"textAlign":"center"`,
`{"type":"textColor","attrs":{"color":"red"}}`, `{"type":"highlight","attrs":{"color":"green"}}`,
`{"type":"callout","attrs":{"color":"red","emoji":"🔥"}`, `"type":"tableHeader"`,
} {
if !strings.Contains(j, want) {
t.Errorf("word import lacks %s:\n%s", want, j)
}
}
}
func TestDOCXListsCodeLinksAndImages(t *testing.T) {
src := mustParse(t, sample)
data, err := DOCX("", src, DOCXOptions{
Options: Options{FileURL: func(p string) string { return "https://api.docwell.test" + p }},
Image: func(string) ([]byte, error) { return pngOf(t, 4, 2), nil },
})
if err != nil {
t.Fatal(err)
}
doc, assets, err := FromDOCX(data)
if err != nil {
t.Fatal(err)
}
md := Markdown(doc, Options{})
for _, want := range []string{
`## Plan & \<scope\>`,
"[a link](https://docwell.test/x)",
"- one\n\n 1. nested\n- two",
"```\nx := 1 < 2\n```",
"> quoted",
"![diagram](asset:0)",
} {
if !strings.Contains(md, want) {
t.Errorf("markdown lacks %q:\n%s", want, md)
}
}
if strings.Contains(md, "javascript:") {
t.Error("unsafe link kept")
}
if len(assets) != 1 {
t.Errorf("assets = %d", len(assets))
}
}
func TestDOCXIsWellFormed(t *testing.T) {
data, err := DOCX("A & <b>", mustParse(t, phaseA), DOCXOptions{})
if err != nil {
t.Fatal(err)
}
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
for _, f := range zr.File {
if !strings.HasSuffix(f.Name, ".xml") && !strings.HasSuffix(f.Name, ".rels") {
continue
}
rc, _ := f.Open()
d := xml.NewDecoder(rc)
for {
if _, err := d.Token(); err != nil {
if !errors.Is(err, io.EOF) {
t.Errorf("%s: %v", f.Name, err)
}
break
}
}
_ = rc.Close()
}
}
+72 -1
View File
@@ -357,9 +357,11 @@ var headingStyle = regexp.MustCompile(`^heading\s*([1-9])$`)
// para is a Word paragraph after its style is known.
type para struct {
kind string // paragraph, heading, quote, code, list
kind string // paragraph, heading, quote, code, list, callout, task
level int // heading level, or list depth
align string // "center" or "right", or "" for the default
color string // a callout's palette colour
checked bool // a ticked to-do
ordered bool
inline []Node
text string // code paragraphs keep their plain text
@@ -406,6 +408,22 @@ func (d *docxReader) blocks(nodes []*xnode) []Node {
if inl := trimInline(p.inline); len(inl) > 0 {
out = append(out, withAlign(Node{Type: "heading", Attrs: map[string]any{"level": float64(min(p.level, 6))}, Content: inl}, p.align))
}
case "callout":
// Paragraphs in the Callout style with the same shading are one callout.
q := Node{Type: "paragraph", Content: trimInline(p.inline)}
if l := len(out) - 1; l >= 0 && out[l].Type == "callout" && out[l].attr("color") == p.color {
out[l].Content = append(out[l].Content, q)
} else {
emoji, body := liftEmoji([]Node{q})
out = append(out, newCallout(emoji, p.color, body))
}
case "task":
item := Node{Type: "taskItem", Attrs: map[string]any{"checked": p.checked}, Content: []Node{{Type: "paragraph", Content: trimInline(p.inline)}}}
if l := len(out) - 1; l >= 0 && out[l].Type == "taskList" {
out[l].Content = append(out[l].Content, item)
} else {
out = append(out, Node{Type: "taskList", Content: []Node{item}})
}
case "quote":
if inl := trimInline(p.inline); len(inl) > 0 {
q := Node{Type: "paragraph", Content: inl}
@@ -512,6 +530,9 @@ func (d *docxReader) paragraph(p *xnode) para {
out.kind, out.level = "heading", outline
case name == "subtitle":
out.kind, out.level = "heading", 2
case name == "callout":
out.kind = "callout"
out.color = paletteNamed(paletteBackground, ppr.child("shd").attrValue("fill"))
case strings.Contains(name, "quote"):
out.kind = "quote"
case strings.Contains(name, "code") || strings.Contains(name, "preformatted") || name == "source":
@@ -541,6 +562,12 @@ func (d *docxReader) paragraph(p *xnode) para {
if out.kind == "code" {
out.text = PlainText(Node{Content: r.inline})
}
// A paragraph starting with a ballot box is a to-do (how DOCX writes them).
if out.kind == "paragraph" || out.kind == "list" {
if checked, rest, ok := ballot(out.inline); ok {
out.kind, out.checked, out.inline = "task", checked, rest
}
}
return out
}
@@ -621,6 +648,46 @@ func (r *runReader) children(nodes []*xnode, marks []Mark) {
}
}
// paletteNamed is the palette colour whose value in table is hex ("rrggbb"), or "".
func paletteNamed(table map[string]string, hex string) string {
for name, v := range table {
if strings.EqualFold(strings.TrimPrefix(v, "#"), hex) {
return name
}
}
return ""
}
func (n *xnode) attrValue(key string) string {
if n == nil {
return ""
}
return n.attrs[key]
}
// ballot takes a leading "☐ " or "☒ " off a paragraph and tells whether it was ticked.
func ballot(inline []Node) (checked bool, rest []Node, ok bool) {
i := 0
for i < len(inline) && inline[i].Type == "text" && strings.TrimSpace(inline[i].Text) == "" {
i++
}
if i == len(inline) || inline[i].Type != "text" {
return false, inline, false
}
t := strings.TrimLeft(inline[i].Text, " ")
for box, on := range map[string]bool{"☐": false, "☒": true, "☑": true} {
if after, found := strings.CutPrefix(t, box); found {
rest = append([]Node{}, inline[i:]...)
rest[0].Text = strings.TrimLeft(after, "  ")
if rest[0].Text == "" {
rest = rest[1:]
}
return on, rest, true
}
}
return false, inline, false
}
// wordHighlight maps Word's highlight colours to the palette.
var wordHighlight = map[string]string{
"yellow": "yellow", "darkYellow": "yellow", "green": "green", "darkGreen": "green", "cyan": "teal",
@@ -679,6 +746,10 @@ func (r *runReader) run(n *xnode, marks []Mark) {
if c, ok := wordHighlight[rpr.val("highlight")]; ok {
marks = withMark(marks, Mark{Type: "highlight", Attrs: map[string]any{"color": c}})
}
// Shading in a palette colour is a highlight too (how DOCX writes them).
if c := paletteNamed(paletteBackground, rpr.child("shd").attrValue("fill")); c != "" {
marks = withMark(marks, Mark{Type: "highlight", Attrs: map[string]any{"color": c}})
}
}
if r.link != "" {
marks = withLink(marks, r.link)
+685
View File
@@ -0,0 +1,685 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
package convert
import (
"archive/zip"
"bytes"
"fmt"
"strconv"
"strings"
"time"
)
// DOCXOptions adjust a Word export.
type DOCXOptions struct {
Options
// BaseURL makes server paths (/p/<id>, attachments) absolute links.
BaseURL string
// Image loads an image by its document URL; nil, or an error, leaves a
// link to the image in its place.
Image func(src string) ([]byte, error)
}
// DOCX renders a page as a Word document with the title on top. Headings,
// lists, to-dos, quotes, callouts, code, tables, alignment, text colours and
// highlights, links and images are kept in a form FromDOCX reads back.
// Diagrams and embeds become links, formulas their LaTeX.
func DOCX(title string, doc Node, o DOCXOptions) ([]byte, error) {
w := &docxWriter{o: o}
if strings.TrimSpace(title) != "" {
w.para(paraProps{style: "Title"}, func() { w.text(title, runProps{}) })
}
w.blocks(doc.Content, blockCtx{})
return w.pack(title)
}
// ---- Package ---------------------------------------------------------------
const (
docxTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
`<Default Extension="xml" ContentType="application/xml"/>` +
`<Default Extension="png" ContentType="image/png"/>` +
`<Default Extension="jpeg" ContentType="image/jpeg"/>` +
`<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>` +
`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>` +
`<Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>` +
`<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>` +
`</Types>`
docxRootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>` +
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>` +
`</Relationships>`
relStyles = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
relNumbering = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering"
relLink = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"
relImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"
)
func (w *docxWriter) pack(title string) ([]byte, error) {
var buf bytes.Buffer
z := zip.NewWriter(&buf)
put := func(name, body string) error {
f, err := z.Create(name)
if err == nil {
_, err = f.Write([]byte(body))
}
return err
}
rels := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
`<Relationship Id="rId1" Type="` + relStyles + `" Target="styles.xml"/>` +
`<Relationship Id="rId2" Type="` + relNumbering + `" Target="numbering.xml"/>`
for _, r := range w.rels {
mode := ""
if r.external {
mode = ` TargetMode="External"`
}
rels += `<Relationship Id="` + r.id + `" Type="` + r.typ + `" Target="` + xmlText(r.target) + `"` + mode + `/>`
}
rels += `</Relationships>`
document := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` +
`xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` +
`xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` +
`xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ` +
`xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><w:body>` +
w.b.String() +
`<w:sectPr><w:pgSz w:w="11906" w:h="16838"/>` +
`<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="708" w:footer="708" w:gutter="0"/>` +
`</w:sectPr></w:body></w:document>`
core := `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" ` +
`xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" ` +
`xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">` +
`<dc:title>` + xmlText(title) + `</dc:title><dc:creator>Docwell</dc:creator>` +
`<dcterms:created xsi:type="dcterms:W3CDTF">` + time.Now().UTC().Format(time.RFC3339) + `</dcterms:created>` +
`</cp:coreProperties>`
for _, p := range []struct{ name, body string }{
{"[Content_Types].xml", docxTypes}, {"_rels/.rels", docxRootRels}, {"docProps/core.xml", core},
{"word/document.xml", document}, {"word/_rels/document.xml.rels", rels},
{"word/styles.xml", docxStyles}, {"word/numbering.xml", w.numbering()},
} {
if err := put(p.name, p.body); err != nil {
return nil, err
}
}
for _, m := range w.media {
f, err := z.Create("word/media/" + m.name)
if err != nil {
return nil, err
}
if _, err := f.Write(m.data); err != nil {
return nil, err
}
}
if err := z.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// The styles FromDOCX recognises by name: headings, Title, Quote, Code and
// Callout, plus the Hyperlink character style and a bordered table style.
var docxStyles = func() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">` +
`<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Calibri" w:cs="Calibri"/>` +
`<w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US"/></w:rPr></w:rPrDefault>` +
`<w:pPrDefault><w:pPr><w:spacing w:after="120" w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` +
`<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>` +
`<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:spacing w:after="240"/></w:pPr><w:rPr><w:b/><w:sz w:val="48"/></w:rPr></w:style>`)
sizes := []int{36, 30, 26, 24, 22, 20}
for i, sz := range sizes {
fmt.Fprintf(&b, `<w:style w:type="paragraph" w:styleId="Heading%d"><w:name w:val="heading %d"/><w:basedOn w:val="Normal"/>`+
`<w:next w:val="Normal"/><w:qFormat/><w:pPr><w:keepNext/><w:spacing w:before="240" w:after="80"/><w:outlineLvl w:val="%d"/></w:pPr>`+
`<w:rPr><w:b/><w:sz w:val="%d"/></w:rPr></w:style>`, i+1, i+1, i, sz)
}
b.WriteString(`<w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:qFormat/>` +
`<w:pPr><w:pBdr><w:left w:val="single" w:sz="18" w:space="8" w:color="C8C8C8"/></w:pBdr><w:ind w:left="284"/></w:pPr>` +
`<w:rPr><w:color w:val="5F5F5F"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Code"><w:name w:val="Code"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:shd w:val="clear" w:color="auto" w:fill="F4F4F1"/><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr>` +
`<w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/><w:sz w:val="19"/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="Callout"><w:name w:val="Callout"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:ind w:left="170" w:right="170"/></w:pPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="TableHeading"><w:name w:val="Table Heading"/><w:basedOn w:val="Normal"/>` +
`<w:rPr><w:b/></w:rPr></w:style>` +
`<w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/>` +
`<w:pPr><w:spacing w:after="40"/></w:pPr></w:style>` +
`<w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/>` +
`<w:rPr><w:color w:val="2F6FBF"/><w:u w:val="single"/></w:rPr></w:style>` +
`<w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:tblPr><w:tblBorders>` +
`<w:top w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:left w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`<w:bottom w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:right w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`<w:insideH w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/><w:insideV w:val="single" w:sz="4" w:space="0" w:color="BFBFBF"/>` +
`</w:tblBorders><w:tblCellMar><w:left w:w="100" w:type="dxa"/><w:right w:w="100" w:type="dxa"/></w:tblCellMar></w:tblPr></w:style>` +
`</w:styles>`)
return b.String()
}()
// numbering lists a bulleted and a numbered pattern, and one list instance
// per list in the document so each numbered list counts from its own start.
func (w *docxWriter) numbering() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
bullets := []string{"•", "◦", "▪"}
for abs, ordered := range []bool{false, true} {
fmt.Fprintf(&b, `<w:abstractNum w:abstractNumId="%d"><w:multiLevelType w:val="hybridMultilevel"/>`, abs+1)
for lvl := range 9 {
if ordered {
fmt.Fprintf(&b, `<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%%%d."/>`, lvl, lvl+1)
} else {
fmt.Fprintf(&b, `<w:lvl w:ilvl="%d"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="%s"/>`, lvl, bullets[lvl%3])
}
fmt.Fprintf(&b, `<w:lvlJc w:val="left"/><w:pPr><w:ind w:left="%d" w:hanging="360"/></w:pPr></w:lvl>`, 720+lvl*360)
}
b.WriteString(`</w:abstractNum>`)
}
for i, n := range w.nums {
abs := 1
if n.ordered {
abs = 2
}
fmt.Fprintf(&b, `<w:num w:numId="%d"><w:abstractNumId w:val="%d"/>`, i+1, abs)
if n.ordered && n.start != 1 {
fmt.Fprintf(&b, `<w:lvlOverride w:ilvl="%d"><w:startOverride w:val="%d"/></w:lvlOverride>`, n.level, n.start)
}
b.WriteString(`</w:num>`)
}
b.WriteString(`</w:numbering>`)
return b.String()
}
// ---- Document --------------------------------------------------------------
type docxRel struct {
id, typ, target string
external bool
}
type docxNum struct {
ordered bool
level int
start int
}
type docxWriter struct {
o DOCXOptions
b strings.Builder
rels []docxRel
media []struct {
name string
data []byte
}
nums []docxNum
images int
}
// blockCtx is what surrounds a block: a quote, a callout, list depth.
type blockCtx struct {
quote bool
callout string // the callout's colour, "" outside one
depth int // list nesting, for indentation
}
type paraProps struct {
style string
align string
numID int
ilvl int
indent int // left indent in twips
shading string // background "rrggbb"
border string // left border colour "rrggbb"
rule bool // a horizontal line under the paragraph
}
type runProps struct {
bold, italic, underline, strike, code bool
color, shade, href string
}
func (w *docxWriter) rel(typ, target string, external bool) string {
id := "rId" + strconv.Itoa(len(w.rels)+3)
w.rels = append(w.rels, docxRel{id: id, typ: typ, target: target, external: external})
return id
}
// link makes a document URL something Word can open, or "".
func (w *docxWriter) link(href string) string {
href = w.o.file(href)
if strings.HasPrefix(href, "/") && !strings.HasPrefix(href, "//") {
if w.o.BaseURL == "" {
return ""
}
href = strings.TrimRight(w.o.BaseURL, "/") + href
}
if !safeURL.MatchString(href) || strings.HasPrefix(href, "#") {
return ""
}
return href
}
func (w *docxWriter) para(p paraProps, content func()) {
w.b.WriteString("<w:p><w:pPr>")
if p.style != "" {
w.b.WriteString(`<w:pStyle w:val="` + p.style + `"/>`)
}
if p.numID > 0 {
fmt.Fprintf(&w.b, `<w:numPr><w:ilvl w:val="%d"/><w:numId w:val="%d"/></w:numPr>`, p.ilvl, p.numID)
}
if p.border != "" || p.rule {
w.b.WriteString("<w:pBdr>")
if p.border != "" {
w.b.WriteString(`<w:left w:val="single" w:sz="24" w:space="8" w:color="` + p.border + `"/>`)
}
if p.rule {
w.b.WriteString(`<w:bottom w:val="single" w:sz="6" w:space="1" w:color="D2D2D2"/>`)
}
w.b.WriteString("</w:pBdr>")
}
if p.shading != "" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + p.shading + `"/>`)
}
if p.indent > 0 {
fmt.Fprintf(&w.b, `<w:ind w:left="%d"/>`, p.indent)
}
if p.align != "" {
w.b.WriteString(`<w:jc w:val="` + p.align + `"/>`)
}
w.b.WriteString("</w:pPr>")
if content != nil {
content()
}
w.b.WriteString("</w:p>")
}
// textPara is the paragraph style a text block gets where it is.
func (w *docxWriter) textPara(ctx blockCtx) paraProps {
switch {
case ctx.callout != "":
bg := strings.TrimPrefix(paletteBackground[ctx.callout], "#")
fg := strings.TrimPrefix(paletteText[ctx.callout], "#")
return paraProps{style: "Callout", shading: bg, border: fg}
case ctx.quote:
return paraProps{style: "Quote"}
case ctx.depth > 0:
return paraProps{indent: 720 + (ctx.depth-1)*360}
}
return paraProps{}
}
func (w *docxWriter) blocks(nodes []Node, ctx blockCtx) {
for _, n := range nodes {
w.block(n, ctx)
}
}
func (w *docxWriter) block(n Node, ctx blockCtx) {
switch n.Type {
case "paragraph":
p := w.textPara(ctx)
p.align = docxAlign(n)
w.para(p, func() { w.inline(n.Content, runProps{}) })
case "heading":
level := min(max(n.intAttr("level", 1), 1), 6)
w.para(paraProps{style: "Heading" + strconv.Itoa(level), align: docxAlign(n)}, func() { w.inline(n.Content, runProps{}) })
case "bulletList", "orderedList":
w.list(n, ctx)
case "taskList":
// FromDOCX reads paragraphs starting with a ballot box back as to-dos.
for _, item := range n.Content {
box := "☐ "
if item.Attrs["checked"] == true {
box = "☒ "
}
for i, c := range item.Content {
if i == 0 && c.Type == "paragraph" {
p := paraProps{style: "ListParagraph", indent: 360 + ctx.depth*360}
w.para(p, func() {
w.text(box, runProps{})
w.inline(c.Content, runProps{})
})
continue
}
w.block(c, blockCtx{depth: ctx.depth + 1})
}
}
case "blockquote":
ctx.quote = true
w.blocks(n.Content, ctx)
case "callout":
emoji, color := calloutParts(n)
ctx.callout = color
body := n.Content
// The emoji leads the first paragraph, where FromDOCX lifts it off again.
if len(body) > 0 && body[0].Type == "paragraph" {
first := body[0]
first.Content = append([]Node{{Type: "text", Text: emoji + " "}}, first.Content...)
body = append([]Node{first}, body[1:]...)
} else {
body = append([]Node{{Type: "paragraph", Content: []Node{{Type: "text", Text: emoji}}}}, body...)
}
w.blocks(body, ctx)
case "codeBlock":
w.code(PlainText(n))
case "mermaid":
w.code(n.attr("code"))
case "blockMath":
w.para(paraProps{align: "center"}, func() { w.text(n.attr("latex"), runProps{code: true}) })
case "horizontalRule":
w.para(paraProps{rule: true}, nil)
case "image":
w.image(n.attr("src"), n.attr("alt"))
case "drawio", "excalidraw":
label := "Draw.io diagram"
if n.Type == "excalidraw" {
label = "Excalidraw drawing"
}
w.para(paraProps{}, func() { w.text(label, runProps{italic: true, href: w.link(n.attr("src"))}) })
case "fileAttachment":
w.para(paraProps{}, func() { w.text(n.attr("name"), runProps{href: w.link(n.attr("url"))}) })
case "embed", "linkCard":
title := n.attr("title")
if title == "" {
title = n.attr("url")
}
w.para(paraProps{}, func() {
w.text(title, runProps{href: w.link(n.attr("url"))})
if d := n.attr("description"); d != "" {
w.b.WriteString("<w:r><w:br/></w:r>")
w.text(d, runProps{color: "787878"})
}
})
case "tableOfContents":
// Word builds its own from the headings (References > Table of Contents).
case "details":
for _, c := range n.Content {
if c.Type == "detailsSummary" {
w.para(w.textPara(ctx), func() { w.inline(c.Content, runProps{bold: true}) })
} else {
w.blocks(c.Content, ctx)
}
}
case "table":
w.table(n)
default:
w.blocks(n.Content, ctx)
}
}
func docxAlign(n Node) string {
switch alignOf(n) {
case "center":
return "center"
case "right":
return "right"
}
return ""
}
// list writes a bulleted or numbered list as numbered paragraphs, nesting
// by level; more blocks in an item follow indented under it.
func (w *docxWriter) list(n Node, ctx blockCtx) {
w.nums = append(w.nums, docxNum{ordered: n.Type == "orderedList", level: ctx.depth, start: n.intAttr("start", 1)})
id := len(w.nums)
for _, item := range n.Content {
for i, c := range item.Content {
if i == 0 && c.Type == "paragraph" {
w.para(paraProps{style: "ListParagraph", numID: id, ilvl: min(ctx.depth, 8)}, func() { w.inline(c.Content, runProps{}) })
continue
}
w.block(c, blockCtx{depth: ctx.depth + 1})
}
}
}
func (w *docxWriter) code(text string) {
for _, line := range strings.Split(strings.ReplaceAll(text, "\t", " "), "\n") {
w.para(paraProps{style: "Code"}, func() { w.text(line, runProps{}) })
}
// A little room after the block.
w.para(paraProps{}, nil)
}
// table writes a bordered table across the page. A row of header cells
// repeats on every page, which is also how FromDOCX tells header rows.
func (w *docxWriter) table(n Node) {
cols := 0
for _, row := range n.Content {
width := 0
for _, c := range row.Content {
width += max(c.intAttr("colspan", 1), 1)
}
cols = max(cols, width)
}
if cols == 0 {
return
}
const total = 9026 // the text width of an A4 page with 1" margins, in twips
w.b.WriteString(`<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="5000" w:type="pct"/>` +
`<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr><w:tblGrid>`)
for range cols {
fmt.Fprintf(&w.b, `<w:gridCol w:w="%d"/>`, total/cols)
}
w.b.WriteString("</w:tblGrid>")
for _, row := range n.Content {
header := len(row.Content) > 0
for _, c := range row.Content {
header = header && c.Type == "tableHeader"
}
w.b.WriteString("<w:tr>")
if header {
w.b.WriteString("<w:trPr><w:tblHeader/></w:trPr>")
}
for _, c := range row.Content {
span := max(c.intAttr("colspan", 1), 1)
fmt.Fprintf(&w.b, `<w:tc><w:tcPr><w:tcW w:w="%d" w:type="dxa"/>`, total/cols*span)
if span > 1 {
fmt.Fprintf(&w.b, `<w:gridSpan w:val="%d"/>`, span)
}
if c.Type == "tableHeader" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="F4F4F1"/>`)
}
w.b.WriteString("</w:tcPr>")
start := w.b.Len()
for _, b := range c.Content {
if b.Type == "paragraph" && c.Type == "tableHeader" {
w.para(paraProps{style: "TableHeading", align: docxAlign(b)}, func() { w.inline(b.Content, runProps{}) })
continue
}
w.block(b, blockCtx{})
}
if w.b.Len() == start || !strings.HasSuffix(w.b.String(), "</w:p>") {
// A cell must end with a paragraph.
w.para(paraProps{}, nil)
}
w.b.WriteString("</w:tc>")
}
w.b.WriteString("</w:tr>")
}
w.b.WriteString("</w:tbl>")
// Word joins tables that touch; a paragraph keeps the next block apart.
w.para(paraProps{}, nil)
}
func (w *docxWriter) inline(nodes []Node, base runProps) {
for _, n := range nodes {
switch n.Type {
case "text":
p := base
for _, m := range n.Marks {
switch m.Type {
case "bold":
p.bold = true
case "italic":
p.italic = true
case "underline":
p.underline = true
case "strike":
p.strike = true
case "code":
p.code = true
case "textColor":
if c, ok := paletteText[m.attr("color")]; ok {
p.color = strings.TrimPrefix(c, "#")
}
case "highlight":
c, ok := paletteBackground[m.attr("color")]
if !ok {
c = paletteBackground["yellow"]
}
p.shade = strings.TrimPrefix(c, "#")
case "link":
p.href = w.link(m.attr("href"))
}
}
w.text(n.Text, p)
case "hardBreak":
w.b.WriteString("<w:r><w:br/></w:r>")
case "inlineMath":
w.text(n.attr("latex"), runProps{code: true})
case "mention":
w.text("@"+mentionLabel(n), runProps{bold: true})
case "dateMention":
w.text(n.attr("date"), runProps{bold: true})
default:
w.inline(n.Content, base)
}
}
}
// text writes one run, inside a hyperlink when it links somewhere.
func (w *docxWriter) text(s string, p runProps) {
if s == "" {
return
}
if p.href != "" {
w.b.WriteString(`<w:hyperlink r:id="` + w.rel(relLink, p.href, true) + `" w:history="1">`)
}
w.b.WriteString("<w:r><w:rPr>")
if p.href != "" {
w.b.WriteString(`<w:rStyle w:val="Hyperlink"/>`)
}
if p.code {
w.b.WriteString(`<w:rFonts w:ascii="Consolas" w:hAnsi="Consolas" w:cs="Consolas"/>`)
}
if p.bold {
w.b.WriteString("<w:b/>")
}
if p.italic {
w.b.WriteString("<w:i/>")
}
if p.strike {
w.b.WriteString("<w:strike/>")
}
if p.color != "" {
w.b.WriteString(`<w:color w:val="` + strings.ToUpper(p.color) + `"/>`)
}
if p.underline {
w.b.WriteString(`<w:u w:val="single"/>`)
}
if p.shade != "" {
w.b.WriteString(`<w:shd w:val="clear" w:color="auto" w:fill="` + strings.ToUpper(p.shade) + `"/>`)
}
w.b.WriteString("</w:rPr>")
for i, line := range strings.Split(s, "\n") {
if i > 0 {
w.b.WriteString("<w:br/>")
}
for j, part := range strings.Split(line, "\t") {
if j > 0 {
w.b.WriteString("<w:tab/>")
}
if part != "" {
w.b.WriteString(`<w:t xml:space="preserve">` + xmlText(part) + `</w:t>`)
}
}
}
w.b.WriteString("</w:r>")
if p.href != "" {
w.b.WriteString("</w:hyperlink>")
}
}
// image embeds a picture at its size (96 pixels to the inch), shrunk to the
// page width, or links to it when it cannot be loaded.
func (w *docxWriter) image(src, alt string) {
fallback := func() {
text := "Image"
if alt != "" {
text += ": " + alt
}
w.para(paraProps{}, func() { w.text("["+text+"]", runProps{italic: true, href: w.link(src)}) })
}
if w.o.Image == nil || src == "" {
fallback()
return
}
data, err := w.o.Image(src)
if err != nil {
fallback()
return
}
kind, body, px, py, err := pdfImage(data)
if err != nil {
fallback()
return
}
const emuPerPx, maxW = 9525, 5731510 // 6.27" in EMU
cx, cy := int64(px)*emuPerPx, int64(py)*emuPerPx
if cx > maxW {
cx, cy = maxW, cy*maxW/cx
}
w.images++
ext := "png"
if kind == "JPG" {
ext = "jpeg"
}
name := "image" + strconv.Itoa(w.images) + "." + ext
w.media = append(w.media, struct {
name string
data []byte
}{name, body})
rid := w.rel(relImage, "media/"+name, false)
id := strconv.Itoa(w.images)
w.para(paraProps{}, func() {
fmt.Fprintf(&w.b, `<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0">`+
`<wp:extent cx="%d" cy="%d"/><wp:docPr id="%s" name="Picture %s" descr="%s"/>`+
`<wp:cNvGraphicFramePr><a:graphicFrameLocks noChangeAspect="1"/></wp:cNvGraphicFramePr>`+
`<a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">`+
`<pic:pic><pic:nvPicPr><pic:cNvPr id="%s" name="%s"/><pic:cNvPicPr/></pic:nvPicPr>`+
`<pic:blipFill><a:blip r:embed="%s"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>`+
`<pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="%d" cy="%d"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr>`+
`</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`,
cx, cy, id, id, xmlText(alt), id, name, rid, cx, cy)
})
}
// xmlText escapes text for XML and leaves out the control characters XML
// cannot hold.
func xmlText(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r == '&':
b.WriteString("&amp;")
case r == '<':
b.WriteString("&lt;")
case r == '>':
b.WriteString("&gt;")
case r == '"':
b.WriteString("&quot;")
case r < 0x20 && r != '\t' && r != '\n' && r != '\r', r == 0xFFFE, r == 0xFFFF:
default:
b.WriteRune(r)
}
}
return b.String()
}
+17 -4
View File
@@ -60,8 +60,8 @@ func exportName(title, ext string) string {
return name + ext
}
// ExportPage renders a page as Markdown ("markdown"), HTML ("html") or PDF
// ("pdf") (viewer).
// ExportPage renders a page as Markdown ("markdown"), HTML ("html"), PDF
// ("pdf") or Word ("docx") (viewer).
func (s *Service) ExportPage(ctx context.Context, c access.Caller, id, format string) (Export, error) {
p, _, err := s.pageFor(ctx, c, id)
if err != nil {
@@ -96,11 +96,24 @@ func (s *Service) ExportPage(ctx context.Context, c access.Caller, id, format st
return Export{}, err
}
return Export{Filename: exportName(p.Title, ".pdf"), ContentType: "application/pdf", Body: body}, nil
case "docx":
body, err := convert.DOCX(p.Title, doc, convert.DOCXOptions{
Options: opts, BaseURL: s.publicURL,
Image: func(src string) ([]byte, error) { return s.pdfImage(ctx, c, src) },
})
if err != nil {
return Export{}, err
}
return Export{
Filename: exportName(p.Title, ".docx"),
ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
Body: body,
}, nil
}
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown, html or pdf."})
return Export{}, apperr.InvalidFields(map[string]string{"format": "Format must be markdown, html, pdf or docx."})
}
// pdfImage loads an attachment the caller can read for a PDF export. Images
// pdfImage loads an attachment the caller can read for a PDF or Word export. Images
// on other sites are not fetched: the server would make requests on a
// reader's behalf to wherever a document points.
func (s *Service) pdfImage(ctx context.Context, c access.Caller, src string) ([]byte, error) {
+11 -3
View File
@@ -283,6 +283,7 @@
"exportMarkdown": "Als Markdown exportieren",
"exportHtml": "Als HTML exportieren",
"exportPdf": "Als PDF exportieren",
"exportDocx": "Als Word exportieren",
"backlinks": "Verlinkt von {n} Seite | Verlinkt von {n} Seiten",
"find": "Suchen und ersetzen",
"fullWidth": "Volle Breite",
@@ -496,17 +497,21 @@
"label": "Linkkarte",
"description": "Ein Link mit Titel und Bild seiner Seite"
},
"otherHeadings": {
"label": "Weitere Überschriften",
"description": "Überschriften 4 bis 6"
},
"h4": {
"label": "Überschrift 4",
"description": "Weitere Überschriften: Ebene 4"
"description": "Eine Überschrift unter Ebene 3"
},
"h5": {
"label": "Überschrift 5",
"description": "Weitere Überschriften: Ebene 5"
"description": "Eine Überschrift unter Ebene 4"
},
"h6": {
"label": "Überschrift 6",
"description": "Weitere Überschriften: Ebene 6"
"description": "Die kleinste Überschrift"
},
"todo": {
"label": "Aufgabenliste",
@@ -604,8 +609,11 @@
"table": {
"toolbar": "Tabelle",
"dragRow": "Ziehen, um die Zeile zu verschieben",
"dragColumn": "Ziehen, um die Spalte zu verschieben",
"moveRowUp": "Zeile nach oben",
"moveRowDown": "Zeile nach unten",
"moveColumnLeft": "Spalte nach links",
"moveColumnRight": "Spalte nach rechts",
"addRowBefore": "Zeile darüber",
"addRowAfter": "Zeile darunter",
"addColumnBefore": "Spalte links",
+11 -3
View File
@@ -283,6 +283,7 @@
"exportMarkdown": "Export as Markdown",
"exportHtml": "Export as HTML",
"exportPdf": "Export as PDF",
"exportDocx": "Export as Word",
"backlinks": "Linked from {n} page | Linked from {n} pages",
"find": "Find and replace",
"fullWidth": "Full width",
@@ -496,17 +497,21 @@
"label": "Link card",
"description": "A link with its page's title and picture"
},
"otherHeadings": {
"label": "Other headings",
"description": "Headings 4 to 6"
},
"h4": {
"label": "Heading 4",
"description": "Other headings: level 4"
"description": "A heading below level 3"
},
"h5": {
"label": "Heading 5",
"description": "Other headings: level 5"
"description": "A heading below level 4"
},
"h6": {
"label": "Heading 6",
"description": "Other headings: level 6"
"description": "The smallest heading"
},
"todo": {
"label": "To-do list",
@@ -604,8 +609,11 @@
"table": {
"toolbar": "Table",
"dragRow": "Drag to move the row",
"dragColumn": "Drag to move the column",
"moveRowUp": "Move row up",
"moveRowDown": "Move row down",
"moveColumnLeft": "Move column left",
"moveColumnRight": "Move column right",
"addRowBefore": "Add row above",
"addRowAfter": "Add row below",
"addColumnBefore": "Add column left",
+11 -3
View File
@@ -283,6 +283,7 @@
"exportMarkdown": "Exportar como Markdown",
"exportHtml": "Exportar como HTML",
"exportPdf": "Exportar como PDF",
"exportDocx": "Exportar como Word",
"backlinks": "Enlazada desde {n} página | Enlazada desde {n} páginas",
"find": "Buscar y reemplazar",
"fullWidth": "Ancho completo",
@@ -496,17 +497,21 @@
"label": "Tarjeta de enlace",
"description": "Un enlace con el título y la imagen de su página"
},
"otherHeadings": {
"label": "Otros encabezados",
"description": "Encabezados 4 a 6"
},
"h4": {
"label": "Encabezado 4",
"description": "Otros encabezados: nivel 4"
"description": "Un encabezado bajo el nivel 3"
},
"h5": {
"label": "Encabezado 5",
"description": "Otros encabezados: nivel 5"
"description": "Un encabezado bajo el nivel 4"
},
"h6": {
"label": "Encabezado 6",
"description": "Otros encabezados: nivel 6"
"description": "El encabezado más pequeño"
},
"todo": {
"label": "Lista de tareas",
@@ -604,8 +609,11 @@
"table": {
"toolbar": "Tabla",
"dragRow": "Arrastra para mover la fila",
"dragColumn": "Arrastra para mover la columna",
"moveRowUp": "Subir fila",
"moveRowDown": "Bajar fila",
"moveColumnLeft": "Mover columna a la izquierda",
"moveColumnRight": "Mover columna a la derecha",
"addRowBefore": "Fila encima",
"addRowAfter": "Fila debajo",
"addColumnBefore": "Columna a la izquierda",
+11 -3
View File
@@ -283,6 +283,7 @@
"exportMarkdown": "Exporter en Markdown",
"exportHtml": "Exporter en HTML",
"exportPdf": "Exporter en PDF",
"exportDocx": "Exporter en Word",
"backlinks": "Liée depuis {n} page | Liée depuis {n} pages",
"find": "Rechercher et remplacer",
"fullWidth": "Pleine largeur",
@@ -496,17 +497,21 @@
"label": "Carte de lien",
"description": "Un lien avec le titre et l’image de sa page"
},
"otherHeadings": {
"label": "Autres titres",
"description": "Titres 4 à 6"
},
"h4": {
"label": "Titre 4",
"description": "Autres titres : niveau 4"
"description": "Un titre sous le niveau 3"
},
"h5": {
"label": "Titre 5",
"description": "Autres titres : niveau 5"
"description": "Un titre sous le niveau 4"
},
"h6": {
"label": "Titre 6",
"description": "Autres titres : niveau 6"
"description": "Le plus petit titre"
},
"todo": {
"label": "Liste de tâches",
@@ -604,8 +609,11 @@
"table": {
"toolbar": "Tableau",
"dragRow": "Glisser pour déplacer la ligne",
"dragColumn": "Glisser pour déplacer la colonne",
"moveRowUp": "Monter la ligne",
"moveRowDown": "Descendre la ligne",
"moveColumnLeft": "Colonne à gauche",
"moveColumnRight": "Colonne à droite",
"addRowBefore": "Ligne au-dessus",
"addRowAfter": "Ligne en dessous",
"addColumnBefore": "Colonne à gauche",
+11 -3
View File
@@ -283,6 +283,7 @@
"exportMarkdown": "Eksportuj jako Markdown",
"exportHtml": "Eksportuj jako HTML",
"exportPdf": "Eksportuj jako PDF",
"exportDocx": "Eksportuj jako Word",
"backlinks": "Linkuje tu {n} strona | Linkują tu {n} strony | Linkuje tu {n} stron",
"find": "Znajdź i zamień",
"fullWidth": "Pełna szerokość",
@@ -496,17 +497,21 @@
"label": "Karta linku",
"description": "Link z tytułem i obrazkiem strony"
},
"otherHeadings": {
"label": "Inne nagłówki",
"description": "Nagłówki od 4 do 6"
},
"h4": {
"label": "Nagłówek 4",
"description": "Inne nagłówki: poziom 4"
"description": "Nagłówek poniżej poziomu 3"
},
"h5": {
"label": "Nagłówek 5",
"description": "Inne nagłówki: poziom 5"
"description": "Nagłówek poniżej poziomu 4"
},
"h6": {
"label": "Nagłówek 6",
"description": "Inne nagłówki: poziom 6"
"description": "Najmniejszy nagłówek"
},
"todo": {
"label": "Lista zadań",
@@ -604,8 +609,11 @@
"table": {
"toolbar": "Tabela",
"dragRow": "Przeciągnij, aby przenieść wiersz",
"dragColumn": "Przeciągnij, aby przenieść kolumnę",
"moveRowUp": "Wiersz wyżej",
"moveRowDown": "Wiersz niżej",
"moveColumnLeft": "Kolumna w lewo",
"moveColumnRight": "Kolumna w prawo",
"addRowBefore": "Wiersz powyżej",
"addRowAfter": "Wiersz poniżej",
"addColumnBefore": "Kolumna z lewej",
+2 -1
View File
@@ -380,7 +380,7 @@ const toggleFavorite = () =>
if (page.value?.id === p.id) page.value = { ...page.value, favorite: !p.favorite };
});
const exportAs = (format: "markdown" | "html" | "pdf") =>
const exportAs = (format: "markdown" | "html" | "pdf" | "docx") =>
run(async () => {
// Save first, so the file has the latest title.
await saveTitle();
@@ -429,6 +429,7 @@ const menu = computed<MenuItem[]>(() => [
{ label: t("page.exportMarkdown"), icon: "download", onSelect: () => exportAs("markdown") },
{ label: t("page.exportHtml"), icon: "download", onSelect: () => exportAs("html") },
{ label: t("page.exportPdf"), icon: "download", onSelect: () => exportAs("pdf") },
{ label: t("page.exportDocx"), icon: "download", onSelect: () => exportAs("docx") },
]);
const addChild = () =>
+6 -2
View File
@@ -1794,14 +1794,16 @@ paths:
get:
operationId: exportPage
tags: [pages]
summary: Download the page as Markdown, HTML or PDF
summary: Download the page as Markdown, HTML, PDF or Word
description: >-
Attachment links point at DOCWELL_PUBLIC_URL and need a file token to open.
PDFs are A4 with a bookmark per heading; images stored on the page are drawn in,
diagrams become a link to their file and Mermaid charts show their source.
Word files (docx) embed the page's images the same way and keep headings, lists,
to-dos, callouts, tables, colours and alignment in a form Docwell imports back.
security: [{ bearer: [] }]
parameters:
- { name: format, in: query, schema: { type: string, enum: [markdown, html, pdf], default: markdown } }
- { name: format, in: query, schema: { type: string, enum: [markdown, html, pdf, docx], default: markdown } }
responses:
"200":
description: The file
@@ -1812,6 +1814,8 @@ paths:
schema: { type: string }
application/pdf:
schema: { type: string, format: binary }
application/vnd.openxmlformats-officedocument.wordprocessingml.document:
schema: { type: string, format: binary }
"400": { $ref: "#/components/responses/Error" }
"404": { $ref: "#/components/responses/Error" }
/api/v1/spaces/{id}/import: