Add databases: table, kanban and calendar views with rows as pages
CI / go (Server) (push) Failing after 4m1s
CI / go (Web-App) (push) Successful in 10m50s
CI / frontend (push) Failing after 6m46s
CI / desktop (ubuntu-latest) (push) Successful in 1h10m39s
CI / mobile (push) Failing after 3m2s
CI / docker (push) Successful in 35m59s
Docs / build (push) Successful in 13m26s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Server) (push) Failing after 4m1s
CI / go (Web-App) (push) Successful in 10m50s
CI / frontend (push) Failing after 6m46s
CI / desktop (ubuntu-latest) (push) Successful in 1h10m39s
CI / mobile (push) Failing after 3m2s
CI / docker (push) Successful in 35m59s
Docs / build (push) Successful in 13m26s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Phase C of docs/AFFINE.md (ADR-13).
A database is a block whose records live in the page's Y.Doc, in
ydoc.getMap("blocks") under the block's id: columns, rows (each cell its
own map entry, so concurrent edits to one row merge) and views. Order is
a fractional position per item, so moving a row keeps edits made to it at
the same time. Database edits share the page's undo history.
- Thirteen property types: title, text, number, checkbox, select,
multi-select, date, progress, link, attachment, member, created time
and created by. The column menu renames, changes type (converting the
values), sorts, filters, hides, inserts, moves, duplicates and deletes;
columns resize and drag.
- Table view: keyboard navigation, range selection, typing to edit,
copy and paste with spreadsheets (pasting adds rows as needed), row
dragging, bulk delete, grouping.
- Views in tabs, each with its own filters (all/any), sorts, grouping
and visible properties; kanban grouped by select, multi-select,
checkbox or member with cards dragged between columns; calendar by a
date property with records dragged between days.
- A record opens beside the page with its properties and a body of its
own (a Y.XmlFragment in the row, edited by a second editor).
- /database, Ctrl+G or "Group as database" turns a list into a database;
CSV export and import; a copied, pasted or duplicated database gets
its own copy of the records.
Server: yrs writes each database's records into its node as attrs.data
when it turns a document into JSON, adds them to the search text, and
writes them back on imports, restores and templates. Markdown, HTML,
PDF and Word exports show a database as a table of its first view's
columns. Notion database CSVs import as database blocks with guessed
types. Share links and history previews show databases read-only.
Strings are translated into all five languages, the user guide covers
databases, and the mobile editor bundle is rebuilt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
53dd43cc2e
commit
3102a476a6
34 files changed
+6833
-83
No files matched your search
@@ -36,6 +36,31 @@ A synced page is read-only where it is shown: open it to edit it. People who can
|
||||
title. **Account → Editor** sets, for this device, the text size, whether new pages start full width or titled with
|
||||
today's date, whether properties and the pages that link here show, and line numbers in code blocks.
|
||||
|
||||
## Databases
|
||||
|
||||
A database is a block that holds records: type `/database` to add one, or select a list and press **Ctrl+G** (or
|
||||
choose **Group as database** in the list's ⠿ menu) to turn each item into a record. Everyone with the page open edits
|
||||
it together, and Ctrl+Z undoes database changes like any other.
|
||||
|
||||
- **Properties** are the columns: title, text, number, checkbox, select, multi-select, date, progress, link,
|
||||
attachment, member, created time and created by. Click a column's name to rename it, change its type (values are
|
||||
converted), sort or filter by it, hide it, move it, or insert another next to it. Drag its edge to resize it, or its
|
||||
name to move it.
|
||||
- **Cells:** click a cell and type, or press Enter to edit it; arrow keys and Tab move between cells, Delete clears
|
||||
them and Shift+arrows select several. Copy and paste work with spreadsheets: paste a block of cells and new records
|
||||
are added as needed.
|
||||
- **Views** sit in tabs above the records, each with its own filters, sorts, grouping and visible properties: a
|
||||
**table**, a **kanban** board grouped by a select, checkbox or member property (drag cards between columns), and a
|
||||
**calendar** that places records on a date property (drag them to another day). Click the active tab to rename,
|
||||
duplicate, change or delete the view; which view you look at is yours alone.
|
||||
- **Records as pages:** **Open** on a record, or a click on a card, opens it beside the page, with its properties on
|
||||
top and room to write below.
|
||||
- **CSV:** the ⋯ menu exports the current view as a CSV file, or adds records from one; an empty database takes the
|
||||
file's columns and guesses their types.
|
||||
|
||||
Exports (Markdown, HTML, PDF, Word) show a database as a table of its first view's columns, and search finds the text
|
||||
in its records. On a public link or in **History**, databases are read-only.
|
||||
|
||||
## Comments
|
||||
|
||||
Select text and choose **Comment** to start a discussion; the text stays highlighted and the comment appears in
|
||||
@@ -89,8 +114,9 @@ account. Turning it off makes the link stop working at once. Pages in the trash
|
||||
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 tables; callouts and to-do lists are kept.
|
||||
between the pages, and stores images and files as attachments. Each database becomes a page with a database block of
|
||||
its rows, with guessed property types, and the row pages under it. Tables in pages 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
|
||||
|
||||
+53
-49
@@ -105,16 +105,16 @@ img.ProseMirror-separator {
|
||||
`,textSerializers:n={}}=e||{};return qu(this.state.doc,{blockSeparator:t,textSerializers:{...Ju(this.schema),...n}})}get isEmpty(){return fd(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit(`destroy`),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){return this.editorView?.isDestroyed??!0}$node(e,t){return this.$doc?.querySelector(e,t)||null}$nodes(e,t){return this.$doc?.querySelectorAll(e,t)||null}$pos(e){let t=this.state.doc.resolve(e),n=e>0&&t.nodeAfter&&!t.nodeAfter.isText&&t.nodeAfter.isAtom?t.nodeAfter:null;return new zp(t,this,!1,n)}get $doc(){return this.$pos(0)}};function Hp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Nu(e.getAttributes,void 0,r);if(i===!1||i===null)return null;let{tr:a}=t,o=r[r.length-1],s=r[0];if(o){let r=s.search(/\S/),c=n.from+s.indexOf(o),l=c+o.length;if(ed(n.from,n.to,t.doc).filter(t=>t.mark.type.excluded.find(n=>n===e.type&&n!==t.mark.type)).filter(e=>e.to>c).length)return null;l<n.to&&a.delete(l,n.to),c>n.from&&a.delete(n.from+r,c);let u=n.from+r+o.length;a.addMark(n.from+r,u,e.type.create(i||{})),a.removeStoredMark(e.type)}},undoable:e.undoable})}function Up(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Nu(e.getAttributes,void 0,r)||{},{tr:a}=t,o=n.from,s=n.to,c=e.type.create(i);if(r[1]){let e=o+r[0].lastIndexOf(r[1]);e>s?e=s:s=e+r[1].length;let t=r[0][r[0].length-1];a.insertText(t,o+r[0].length-1),a.replaceWith(e,s,c)}else if(r[0]){let t=e.type.isInline?o:o-1;a.insert(t,e.type.create(i)).delete(a.mapping.map(o),a.mapping.map(s))}a.scrollIntoView()},undoable:e.undoable})}function Wp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r})=>{let i=t.doc.resolve(n.from),a=Nu(e.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),e.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,e.type,a)},undoable:e.undoable})}function Gp(e){return new lp({find:e.find,handler:({state:t,range:n,match:r,chain:i})=>{let a=Nu(e.getAttributes,void 0,r)||{},o=t.tr.delete(n.from,n.to),s=o.doc.resolve(n.from).blockRange(),c=s&&It(s,e.type,a);if(!c)return null;if(o.wrap(s,c),e.keepMarks&&e.editor){let{selection:n,storedMarks:r}=t,{splittableMarks:i}=e.editor.extensionManager,a=r||n.$to.parentOffset&&n.$from.marks();if(a){let e=a.filter(e=>i.includes(e.type.name));o.ensureMarks(e)}}if(e.keepAttributes){let t=e.type.name===`bulletList`||e.type.name===`orderedList`?`listItem`:`taskList`;i().updateAttributes(t,a).run()}let l=o.doc.resolve(n.from-1).nodeBefore;l&&l.type===e.type&&Jt(o.doc,n.from-1)&&(!e.joinPredicate||e.joinPredicate(r,l))&&o.join(n.from-1)},undoable:e.undoable})}var Kp=e=>`touches`in e,qp=class{constructor(e){var t;this.directions=[`bottom-left`,`bottom-right`,`top-left`,`top-right`],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:``,wrapper:``,handle:``,resizing:``},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.clientX-this.startX,n=e.clientY-this.startY;this.handleResize(t,n)},this.handleTouchMove=e=>{if(!this.isResizing||!this.activeHandle)return;let t=e.touches[0];if(!t)return;let n=t.clientX-this.startX,r=t.clientY-this.startY;this.handleResize(n,r)},this.handleMouseUp=()=>{if(!this.isResizing)return;let e=this.element.offsetWidth,t=this.element.offsetHeight;this.onCommit(e,t),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState=`false`,this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener(`mousemove`,this.handleMouseMove),document.removeEventListener(`mouseup`,this.handleMouseUp),document.removeEventListener(`keydown`,this.handleKeyDown),document.removeEventListener(`keyup`,this.handleKeyUp)},this.handleKeyDown=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=e=>{e.key===`Shift`&&(this.isShiftKeyPressed=!1)},this.node=e.node,this.editor=e.editor,this.element=e.element,this.element.draggable=!1,this.contentElement=e.contentElement,this.getPos=e.getPos,this.onResize=e.onResize,this.onCommit=e.onCommit,this.onUpdate=e.onUpdate,e.options?.min&&(this.minSize={...this.minSize,...e.options.min}),e.options?.max&&(this.maxSize=e.options.max),e!=null&&(t=e.options)!=null&&t.directions&&(this.directions=e.options.directions),e.options?.preserveAspectRatio&&(this.preserveAspectRatio=e.options.preserveAspectRatio),e.options?.className&&(this.classNames={container:e.options.className.container||``,wrapper:e.options.className.wrapper||``,handle:e.options.className.handle||``,resizing:e.options.className.resLine truncated
|
||||
`)}},Ag=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[Lh]?Rh(e,t):cm(e)?am(e,e=>om(t,t=>Ag(e,t))):zh(e)?Gh(e,(e,n)=>Ag(e,t[n])):!1,jg=class{static _dilutes=!1;extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),Ag(t,n)}equals(e){return this.constructor===e.constructor&&Qh(this.shape,e.shape)}[Og](){return!0}[Lh](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){ah()}get nullable(){return u_(this,T_)}get optional(){return new Hg(this)}cast(e){return k_(e,this),e}expect(e){return k_(e,this),e}},Mg=class extends jg{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=e?.constructor===this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor===this.shape?`Check failed`:`Constructor match failed`),n}},Ng=(e,t=null)=>new Mg(e,t);Ng(Mg);var Pg=class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&t?.extend(null,`custom prop`,e?.constructor.name,`failed to check custom prop`),n}},Fg=e=>new Pg(e);Ng(Pg);var Ig=class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&t?.extend(null,this.shape.join(` | `),e.toString()),n}},Lg=(...e)=>new Ig(e),Rg=Ng(Ig),zg=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),Bg=e=>{if(b_.check(e))return[zg(e)];if(Rg.check(e))return e.shape.map(e=>e+``);if(y_.check(e))return[`[+-]?\\d+.?\\d*`];if(x_.check(e))return[`.*`];if(d_.check(e))return e.shape.map(Bg).flat(1);oh()};Ng(class extends jg{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(Bg).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&t?.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`),n}});var Vg=Symbol(`optional`),Hg=class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&t?.extend(null,`undefined (optional)`,`()`),n}get[Vg](){return!0}},Ug=Ng(Hg),Wg=class extends jg{check(e,t){return t?.extend(null,`never`,typeof e),!1}};new Wg,Ng(Wg);var Gg=class e extends jg{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,`object`,`null`),!1):Gh(this.shape,(n,r)=>{let i=this._isPartial&&!Kh(e,r)||n.check(e[r],t);return!i&&t?.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`),i})}},Kg=e=>new Gg(e),qg=Ng(Gg),Jg=Fg(e=>e!=null&&(e.constructor===Object||e.constructor==null)),Yg=class extends jg{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&Gh(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&t?.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`),i&&this.shape.values.check(n,t)})}},Xg=(e,t)=>new Yg(e,t),Zg=Ng(Yg),Qg=class extends jg{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&Gh(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&t?.extend(r.toString(),`Tuple`,typeof n),i})}},$g=(...e)=>new Qg(e);Ng(Qg);var e_=class extends jg{constructor(e){super(),this.shape=e.length===1?e[0]:new l_(e)}check(e,t){let n=cm(e)&&am(e,e=>this.shape.check(e));return!n&&t?.extend(null,`Array`,``),n}},t_=(...e)=>new e_(e),n_=Ng(e_),r_=Fg(e=>cm(e)),i_=class extends jg{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name),n}},a_=(e,t=null)=>new i_(e,t);Ng(i_);var o_=a_(jg),s_=Ng(class extends jg{constructor(e){super(),this.len=e.length-1,this.args=$g(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&t?.extend(null,`function`,typeof e),n}}),c_=Fg(e=>typeof e==`function`);Ng(class extends jg{constructor(e){super(),this.shape=e}check(e,t){let n=am(this.shape,n=>n.check(e,t));return!n&&t?.extend(null,`Intersectinon`,typeof e),n}},e=>e.shape.length>0);var l_=class extends jg{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let n=om(this.shape,n=>n.check(e,t));return t?.extend(null,`Union`,typeof e),n}},u_=(...e)=>e.findIndex(e=>d_.check(e))>=0?u_(...e.map(e=>O_(e)).map(e=>d_.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new l_(e),d_=Ng(l_),f_=()=>!0,p_=Fg(f_),m_=Ng(Pg,e=>e.shape===f_),h_=Fg(e=>typeof e==`bigint`),g_=Fg(e=>e===h_),__=Fg(e=>typeof e==`symbol`);Fg(e=>e===__);var v_=Fg(e=>typeof e==`number`),y_=Fg(e=>e===v_),b_=Fg(e=>typeof e==`string`),x_=Fg(e=>e===b_),S_=Fg(e=>typeof e==`boolean`),C_=Fg(e=>e===S_),w_=Lg(void 0);Ng(Ig,e=>e.shape.length===1&&e.shape[0]===void 0),Lg(void 0);var T_=Lg(null),E_=Ng(Ig,e=>e.shape.length===1&&e.shape[0]===null);Ng(Uint8Array),Ng(Mg,e=>e.shape===Uint8Array);var D_=u_(v_,b_,T_,w_,h_,S_,__);(()=>{let e=t_(p_),t=Xg(b_,p_),n=u_(v_,b_,T_,S_,e,t);return e.shape=n,t.shape.values=n,n})();var O_=e=>{if(o_.check(e))return e;ifLine truncated
|
||||
`;n.right=new Yx(N(o,xy(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Mx(i)),n.right.integrate(e,0),n.forward()}Ub(e,t,n,s)},Yb=(e,t,n,r,i)=>{let a=t,o=Xp();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Tx){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case Tx:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Wb(i,n);break}}}t=t.right}return s},Xb=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Tx){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Zb=e=>{let t=0;return Ly(e.doc,n=>{let r=e._start,i=e._start,a=Xp(),o=Zp(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Tx:Wb(o,i.content);break;default:t+=Yb(n,r,i,a,o),a=Zp(o),r=i}i=i.right}}),t},Qb=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&ky(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===Tx&&e.constructor!==hx&&t.add(e.parent)})}Ly(n,n=>{cv(e,e.deleteSet,e=>{if(e instanceof hx||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===Tx?t.add(r):Xb(n,e)});for(let e of t)Zb(e)})},$b=(e,t,n)=>{let r=n,i=Zp(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Hx:case Cx:case Mx:n<t.right.length&&Ey(e,N(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}a&&Yb(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&db(o._searchMarker,t.index,-r+n),t},ex=class extends tb{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Ly(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},Wh(o)||(e.attributes=Bh({},o))),c=0}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Hx:case Cx:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case Mx:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case Tx:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(zb(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),zb(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;zb(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(zb(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Wb(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},tx=class e extends pb{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??rb(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new ex(this,e,t);fb(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??rb();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Mx&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Ly(this.doc,n=>{let r=new Bb(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
||||
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&qb(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&$b(n,r,a.delete):Jb(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??rb();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(_y(s,e)||t!==void 0&&_y(s,t))switch(s.content.constructor){case Mx:{let r=i.get(`ychange`);e!==void 0&&!_y(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!_y(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Hx:case Cx:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Tx:_y(s,e)&&(c(),Wb(i,s.content))}s=s.right}c()};return e||t?Ly(a,n=>{e&&vy(n,e),t&&vy(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),qb(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Ly(r,r=>{let i=Hb(r,this,e,!n);qb(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Ly(n,n=>{$b(n,Hb(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!1);i.right!==null&&Jb(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Ly(this.doc,t=>{Eb(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Ly(this.doc,n=>{Db(n,this,e,t)})}getAttribute(e){return Ob(this,e)}getAttributes(){return kb(this)}_write(e){e.writeTypeRef(Lx)}},nx=e=>new tx,rx=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??rb()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===ox||t.constructor===ix)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},ix=class e extends pb{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof pb?e.clone():e)),t}get length(){return this.doc??rb(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new rx(this,e)}querySelector(e){e=e.toUpperCase();let t=new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),im(new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){fb(this,e,new cx(this,t,e))}toString(){return vb(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),_b(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Ly(this.doc,n=>{Cb(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Ly(this.doc,n=>{let r=e&&e instanceof pb?e._item:e;xb(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw ih(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Ly(this.doc,n=>{Tb(n,this,e,t)})}toArray(){return hb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return bb(this,e)}slice(e=0,t=this.length){return mb(this,e,t)}forEach(e){_b(this,e)}_write(e){e.writeTypeRef(zx)}},ax=e=>new ix,ox=class e extends ix{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return Hh(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>eLine truncated
|
||||
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&qb(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&$b(n,r,a.delete):Jb(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??rb();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(_y(s,e)||t!==void 0&&_y(s,t))switch(s.content.constructor){case Mx:{let r=i.get(`ychange`);e!==void 0&&!_y(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!_y(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Hx:case Cx:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Tx:_y(s,e)&&(c(),Wb(i,s.content))}s=s.right}c()};return e||t?Ly(a,n=>{e&&vy(n,e),t&&vy(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),qb(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Ly(r,r=>{let i=Hb(r,this,e,!n);qb(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Ly(n,n=>{$b(n,Hb(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Ly(r,r=>{let i=Hb(r,this,e,!1);i.right!==null&&Jb(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Ly(this.doc,t=>{Eb(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Ly(this.doc,n=>{Db(n,this,e,t)})}getAttribute(e){return Ob(this,e)}getAttributes(){return kb(this)}_write(e){e.writeTypeRef(Lx)}},nx=e=>new tx,rx=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??rb()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===ox||t.constructor===ix)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},ix=class e extends pb{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof pb?e.clone():e)),t}get length(){return this.doc??rb(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new rx(this,e)}querySelector(e){e=e.toUpperCase();let t=new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),im(new rx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){fb(this,e,new cx(this,t,e))}toString(){return vb(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),_b(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Ly(this.doc,n=>{Cb(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Ly(this.doc,n=>{let r=e&&e instanceof pb?e._item:e;xb(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw ih(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Ly(this.doc,n=>{Tb(n,this,e,t)})}toArray(){return hb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return bb(this,e)}slice(e=0,t=this.length){return mb(this,e,t)}forEach(e){_b(this,e)}_write(e){e.writeTypeRef(zx)}},ax=e=>new ix,ox=class e extends ix{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return Hh(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>eLine truncated
|
||||
`).map(e=>e.trim()===``?`>`:`> ${e}`);n.push(i.join(`
|
||||
`))}),n.join(`
|
||||
>
|
||||
`)},addCommands(){return{setBlockquote:()=>({commands:e})=>e.wrapIn(this.name),toggleBlockquote:()=>({commands:e})=>e.toggleWrap(this.name),unsetBlockquote:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>wT(this.editor,this.type)}},addInputRules(){return[Gp({find:TT,type:this.type})]}}),DT=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,OT=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,kT=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,AT=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,jT=_p.create({name:`bold`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`strong`},{tag:`b`,getAttrs:e=>e.style.fontWeight!==`normal`&&null},{style:`font-weight=400`,clearMark:e=>e.type.name===this.name},{style:`font-weight`,getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}]},renderHTML({HTMLAttributes:e}){return CT(`strong`,{...A(this.options.HTMLAttributes,e),children:CT(`slot`,{})})},markdownTokenName:`strong`,parseMarkdown:(e,t)=>t.applyMark(`bold`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<strong>`,close:`</strong>`}},renderMarkdown:(e,t)=>`**${t.renderChildren(e)}**`,addCommands(){return{setBold:()=>({commands:e})=>e.setMark(this.name),toggleBold:()=>({commands:e})=>e.toggleMark(this.name),unsetBold:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Hp({find:DT,type:this.type}),Hp({find:kT,type:this.type})]},addPasteRules(){return[Yp({find:OT,type:this.type}),Yp({find:AT,type:this.type})]}}),MT=e=>{let t=/`([^`]+)`(?!`)$/.exec(e);return!t||t.index>0&&e[t.index-1]==="`"?null:{index:t.index,text:t[0],replaceWith:t[1]}},NT=e=>{let t=/`([^`]+)`(?!`)/g,n=[],r;for(;(r=t.exec(e))!==null;)r.index>0&&e[r.index-1]==="`"||n.push({index:r.index,text:r[0],replaceWith:r[1]});return n};function PT(e){let t=new Set((e.match(/`+/g)||[]).map(e=>e.length)),n=1;for(;t.has(n);)n+=1;return n}var FT=_p.create({name:`code`,addOptions(){return{HTMLAttributes:{}}},excludes:`_`,code:!0,exitable:!0,parseHTML(){return[{tag:`code`}]},renderHTML({HTMLAttributes:e}){return[`code`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`codespan`,parseMarkdown:(e,t)=>t.applyMark(`code`,[{type:`text`,text:e.text||``}]),renderMarkdown:(e,t,n)=>{var r;if(!e.content)return``;let i=typeof(n==null||(r=n.meta)==null?void 0:r.markText)==`string`?n.meta.markText:``,a="`".repeat(PT(i)),o=i.startsWith("`")||i.endsWith("`")?` `:``;return`${a}${o}${t.renderChildren(e.content)}${o}${a}`},addCommands(){return{setCode:()=>({commands:e})=>e.setMark(this.name),toggleCode:()=>({commands:e})=>e.toggleMark(this.name),unsetCode:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Hp({find:MT,type:this.type})]},addPasteRules(){return[Yp({find:NT,type:this.type})]}}),IT=4,LT=/^```([a-z]+)?[\s\n]$/,RT=/^~~~([a-z]+)?[\s\n]$/,zT=Jp.create({name:`codeBlock`,addOptions(){return{languageClassPrefix:`language-`,exitOnTripleEnter:!0,exitOnArrowDown:!0,exitOnArrowUp:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:IT,HTMLAttributes:{}}},content:`text*`,marks:``,group:`block`,code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:e=>{let{languageClassPrefix:t}=this.options;return t&&[...e.firstElementChild?.classList||[]].filter(e=>e.startsWith(t)).map(e=>e.replace(t,``))[0]||null},rendered:!1}}},parseHTML(){return[{tag:`pre`,preserveWhitespace:`full`}]},renderHTML({node:e,HTMLAttributes:t}){return[`pre`,A(this.options.HTMLAttributes,t),[`code`,{class:e.attrs.language?this.options.languageClassPrefix+e.attrs.language:null},0]]},markdownTokenName:`code`,parseMarkdown:(e,t)=>e.raw?.startsWith("```")===!1&&e.raw?.startsWith(`~~~`)===!1&&e.codeBlockStyle!==`indented`?[]:t.createNode(`codeBlock`,{language:e.lang||null},e.text?[t.createTextNode(e.text)]:[]),renderMarkdown:(e,t)=>{let n=``,r=e.attrs?.language||``;return n=e.content?[`\`\`\`${r}`,t.renderChildren(e.content),"```"].join(`
|
||||
`):`\`\`\`${r}\n\n\`\`\``,n},addCommands(){return{setCodeBlock:e=>({commands:t})=>t.setNode(this.name,e),toggleCodeBlock:e=>({commands:t})=>t.toggleNode(this.name,`paragraph`,e)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{let{empty:e,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!e||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??IT,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;if(i.parent.type!==this.type)return!1;let o=` `.repeat(t);return a?e.commands.insertContent(o):e.commands.command(({tr:e})=>{let{from:t,to:i}=r,a=n.doc.textBetween(t,i,`
|
||||
`)},addCommands(){return{setBlockquote:()=>({commands:e})=>e.wrapIn(this.name),toggleBlockquote:()=>({commands:e})=>e.toggleWrap(this.name),unsetBlockquote:()=>({commands:e})=>e.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>DT(this.editor,this.type)}},addInputRules(){return[Gp({find:OT,type:this.type})]}}),AT=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,jT=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,MT=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,NT=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,PT=_p.create({name:`bold`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`strong`},{tag:`b`,getAttrs:e=>e.style.fontWeight!==`normal`&&null},{style:`font-weight=400`,clearMark:e=>e.type.name===this.name},{style:`font-weight`,getAttrs:e=>/^(bold(er)?|[5-9]\d{2,})$/.test(e)&&null}]},renderHTML({HTMLAttributes:e}){return ET(`strong`,{...A(this.options.HTMLAttributes,e),children:ET(`slot`,{})})},markdownTokenName:`strong`,parseMarkdown:(e,t)=>t.applyMark(`bold`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<strong>`,close:`</strong>`}},renderMarkdown:(e,t)=>`**${t.renderChildren(e)}**`,addCommands(){return{setBold:()=>({commands:e})=>e.setMark(this.name),toggleBold:()=>({commands:e})=>e.toggleMark(this.name),unsetBold:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[Hp({find:AT,type:this.type}),Hp({find:MT,type:this.type})]},addPasteRules(){return[Yp({find:jT,type:this.type}),Yp({find:NT,type:this.type})]}}),FT=e=>{let t=/`([^`]+)`(?!`)$/.exec(e);return!t||t.index>0&&e[t.index-1]==="`"?null:{index:t.index,text:t[0],replaceWith:t[1]}},IT=e=>{let t=/`([^`]+)`(?!`)/g,n=[],r;for(;(r=t.exec(e))!==null;)r.index>0&&e[r.index-1]==="`"||n.push({index:r.index,text:r[0],replaceWith:r[1]});return n};function LT(e){let t=new Set((e.match(/`+/g)||[]).map(e=>e.length)),n=1;for(;t.has(n);)n+=1;return n}var RT=_p.create({name:`code`,addOptions(){return{HTMLAttributes:{}}},excludes:`_`,code:!0,exitable:!0,parseHTML(){return[{tag:`code`}]},renderHTML({HTMLAttributes:e}){return[`code`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`codespan`,parseMarkdown:(e,t)=>t.applyMark(`code`,[{type:`text`,text:e.text||``}]),renderMarkdown:(e,t,n)=>{var r;if(!e.content)return``;let i=typeof(n==null||(r=n.meta)==null?void 0:r.markText)==`string`?n.meta.markText:``,a="`".repeat(LT(i)),o=i.startsWith("`")||i.endsWith("`")?` `:``;return`${a}${o}${t.renderChildren(e.content)}${o}${a}`},addCommands(){return{setCode:()=>({commands:e})=>e.setMark(this.name),toggleCode:()=>({commands:e})=>e.toggleMark(this.name),unsetCode:()=>({commands:e})=>e.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[Hp({find:FT,type:this.type})]},addPasteRules(){return[Yp({find:IT,type:this.type})]}}),zT=4,BT=/^```([a-z]+)?[\s\n]$/,VT=/^~~~([a-z]+)?[\s\n]$/,HT=Jp.create({name:`codeBlock`,addOptions(){return{languageClassPrefix:`language-`,exitOnTripleEnter:!0,exitOnArrowDown:!0,exitOnArrowUp:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:zT,HTMLAttributes:{}}},content:`text*`,marks:``,group:`block`,code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:e=>{let{languageClassPrefix:t}=this.options;return t&&[...e.firstElementChild?.classList||[]].filter(e=>e.startsWith(t)).map(e=>e.replace(t,``))[0]||null},rendered:!1}}},parseHTML(){return[{tag:`pre`,preserveWhitespace:`full`}]},renderHTML({node:e,HTMLAttributes:t}){return[`pre`,A(this.options.HTMLAttributes,t),[`code`,{class:e.attrs.language?this.options.languageClassPrefix+e.attrs.language:null},0]]},markdownTokenName:`code`,parseMarkdown:(e,t)=>e.raw?.startsWith("```")===!1&&e.raw?.startsWith(`~~~`)===!1&&e.codeBlockStyle!==`indented`?[]:t.createNode(`codeBlock`,{language:e.lang||null},e.text?[t.createTextNode(e.text)]:[]),renderMarkdown:(e,t)=>{let n=``,r=e.attrs?.language||``;return n=e.content?[`\`\`\`${r}`,t.renderChildren(e.content),"```"].join(`
|
||||
`):`\`\`\`${r}\n\n\`\`\``,n},addCommands(){return{setCodeBlock:e=>({commands:t})=>t.setNode(this.name,e),toggleCodeBlock:e=>({commands:t})=>t.toggleNode(this.name,`paragraph`,e)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{let{empty:e,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!e||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??zT,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;if(i.parent.type!==this.type)return!1;let o=` `.repeat(t);return a?e.commands.insertContent(o):e.commands.command(({tr:e})=>{let{from:t,to:i}=r,a=n.doc.textBetween(t,i,`
|
||||
`,`
|
||||
`).split(`
|
||||
`).map(e=>o+e).join(`
|
||||
`);return e.replaceWith(t,i,n.schema.text(a)),!0})},"Shift-Tab":({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??IT,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;return i.parent.type===this.type?a?e.commands.command(({tr:e})=>{let{pos:r}=i,a=i.start(),o=i.end(),s=n.doc.textBetween(a,o,`
|
||||
`);return e.replaceWith(t,i,n.schema.text(a)),!0})},"Shift-Tab":({editor:e})=>{if(!this.options.enableTabIndentation)return!1;let t=this.options.tabSize??zT,{state:n}=e,{selection:r}=n,{$from:i,empty:a}=r;return i.parent.type===this.type?a?e.commands.command(({tr:e})=>{let{pos:r}=i,a=i.start(),o=i.end(),s=n.doc.textBetween(a,o,`
|
||||
`,`
|
||||
`).split(`
|
||||
`),c=0,l=0,u=r-a;for(let e=0;e<s.length;e+=1){if(l+s[e].length>=u){c=e;break}l+=s[e].length+1}let d=s[c].match(/^ */)?.[0]||``,f=Math.min(d.length,t);if(f===0)return!0;let p=a;for(let e=0;e<c;e+=1)p+=s[e].length+1;return e.delete(p,p+f),r-p<=f&&e.setSelection(w.create(e.doc,p)),!0}):e.commands.command(({tr:e})=>{let{from:i,to:a}=r,o=n.doc.textBetween(i,a,`
|
||||
@@ -123,44 +123,48 @@ img.ProseMirror-separator {
|
||||
`).map(e=>{let n=e.match(/^ */)?.[0]||``,r=Math.min(n.length,t);return e.slice(r)}).join(`
|
||||
`);return e.replaceWith(i,a,n.schema.text(o)),!0}):!1},Enter:({editor:e})=>{if(!this.options.exitOnTripleEnter)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type)return!1;let a=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(`
|
||||
|
||||
`);return!a||!o?!1:e.chain().command(({tr:e})=>(e.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:e})=>{if(!this.options.exitOnArrowUp)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;let a=r.before();return a>0?!1:e.commands.insertDefaultBlock({pos:a})},ArrowDown:({editor:e})=>{if(!this.options.exitOnArrowDown)return!1;let{state:t}=e,{selection:n,doc:r}=t,{$from:i,empty:a}=n;if(!a||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;let o=i.after();return o===void 0?!1:r.nodeAt(o)?e.commands.command(({tr:e})=>(e.setSelection(C.near(r.resolve(o))),!0)):e.commands.exitCode()}}},addInputRules(){return[Wp({find:LT,type:this.type,getAttributes:e=>({language:e[1]})}),Wp({find:RT,type:this.type,getAttributes:e=>({language:e[1]})})]},addProseMirrorPlugins(){return[new E({key:new D(`codeBlockVSCodeHandler`),props:{handlePaste:(e,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;let n=t.clipboardData.getData(`text/plain`),r=t.clipboardData.getData(`vscode-editor-data`),i=(r?JSON.parse(r):void 0)?.mode;if(!n||!i)return!1;let{tr:a,schema:o}=e.state,s=o.text(n.replace(/\r\n?/g,`
|
||||
`));return a.replaceSelectionWith(this.type.create({language:i},s)),a.selection.$from.parent.type!==this.type&&a.setSelection(w.near(a.doc.resolve(Math.max(0,a.selection.from-2)))),a.setMeta(`paste`,!0),e.dispatch(a),!0}}})]}}),BT=zT,VT=Jp.create({name:`doc`,topNode:!0,content:`block+`,renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
|
||||
`);return!a||!o?!1:e.chain().command(({tr:e})=>(e.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:e})=>{if(!this.options.exitOnArrowUp)return!1;let{state:t}=e,{selection:n}=t,{$from:r,empty:i}=n;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;let a=r.before();return a>0?!1:e.commands.insertDefaultBlock({pos:a})},ArrowDown:({editor:e})=>{if(!this.options.exitOnArrowDown)return!1;let{state:t}=e,{selection:n,doc:r}=t,{$from:i,empty:a}=n;if(!a||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;let o=i.after();return o===void 0?!1:r.nodeAt(o)?e.commands.command(({tr:e})=>(e.setSelection(C.near(r.resolve(o))),!0)):e.commands.exitCode()}}},addInputRules(){return[Wp({find:BT,type:this.type,getAttributes:e=>({language:e[1]})}),Wp({find:VT,type:this.type,getAttributes:e=>({language:e[1]})})]},addProseMirrorPlugins(){return[new E({key:new D(`codeBlockVSCodeHandler`),props:{handlePaste:(e,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;let n=t.clipboardData.getData(`text/plain`),r=t.clipboardData.getData(`vscode-editor-data`),i=(r?JSON.parse(r):void 0)?.mode;if(!n||!i)return!1;let{tr:a,schema:o}=e.state,s=o.text(n.replace(/\r\n?/g,`
|
||||
`));return a.replaceSelectionWith(this.type.create({language:i},s)),a.selection.$from.parent.type!==this.type&&a.setSelection(w.near(a.doc.resolve(Math.max(0,a.selection.from-2)))),a.setMeta(`paste`,!0),e.dispatch(a),!0}}})]}}),UT=HT,WT=Jp.create({name:`doc`,topNode:!0,content:`block+`,renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
|
||||
|
||||
`):``}),HT=Jp.create({name:`hardBreak`,markdownTokenName:`br`,addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:`inline`,selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:`br`}]},renderHTML({HTMLAttributes:e}){return[`br`,A(this.options.HTMLAttributes,e)]},renderText(){return`
|
||||
`):``}),GT=Jp.create({name:`hardBreak`,markdownTokenName:`br`,addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:`inline`,selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:`br`}]},renderHTML({HTMLAttributes:e}){return[`br`,A(this.options.HTMLAttributes,e)]},renderText(){return`
|
||||
`},renderMarkdown:()=>`
|
||||
`,parseMarkdown:()=>({type:`hardBreak`}),addCommands(){return{setHardBreak:()=>({commands:e,chain:t,state:n,editor:r})=>e.first([()=>e.exitCode(),()=>e.command(()=>{let{selection:e,storedMarks:i}=n;if(e.$from.parent.type.spec.isolating)return!1;let{keepMarks:a}=this.options,{splittableMarks:o}=r.extensionManager,s=i||e.$to.parentOffset&&e.$from.marks();return t().insertContent({type:this.name}).command(({tr:e,dispatch:t})=>{if(t&&s&&a){let t=s.filter(e=>o.includes(e.type.name));e.ensureMarks(t)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),UT=Jp.create({name:`heading`,addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:`inline*`,group:`block`,defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(e=>({tag:`h${e}`,attrs:{level:e}}))},renderHTML({node:e,HTMLAttributes:t}){return[`h${this.options.levels.includes(e.attrs.level)?e.attrs.level:this.options.levels[0]}`,A(this.options.HTMLAttributes,t),0]},parseMarkdown(e,t){let n=e.depth||1;return this.options.levels.includes(n)?t.createNode(`heading`,{level:n},t.parseInline(e.tokens||[])):t.createNode(`paragraph`,void 0,t.parseInline(e.tokens||[]))},renderMarkdown:(e,t)=>{let n=e.attrs?.level?parseInt(e.attrs.level,10):1,r=`#`.repeat(n);return e.content?`${r} ${t.renderChildren(e.content)}`:``},addCommands(){return{setHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.setNode(this.name,e):!1,toggleHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.toggleNode(this.name,`paragraph`,e):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((e,t)=>({...e,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(e=>Wp({find:RegExp(`^(#{${Math.min(...this.options.levels)},${e}})\\s$`),type:this.type,getAttributes:{level:e}}))}}),WT=Jp.create({name:`horizontalRule`,addOptions(){return{HTMLAttributes:{},nextNodeType:`paragraph`}},group:`block`,parseHTML(){return[{tag:`hr`}]},renderHTML({HTMLAttributes:e}){return[`hr`,A(this.options.HTMLAttributes,e)]},markdownTokenName:`hr`,parseMarkdown:(e,t)=>t.createNode(`horizontalRule`),renderMarkdown:()=>`---`,addCommands(){return{setHorizontalRule:()=>({chain:e,state:t})=>{if(!Df(t,t.schema.nodes[this.name]))return!1;let{selection:n}=t,{$to:r}=n,i=e();return pd(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:e,tr:t,dispatch:n})=>{if(n){let{$to:n}=t.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?t.setSelection(w.create(t.doc,n.pos+1)):n.nodeAfter.isBlock?t.setSelection(T.create(t.doc,n.pos)):t.setSelection(w.create(t.doc,n.pos));else{let i=(e.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType)?.create();i&&(t.insert(r,i),t.setSelection(w.create(t.doc,r+1)))}t.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Up({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),GT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,KT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,qT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,JT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,YT=_p.create({name:`italic`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`em`},{tag:`i`,getAttrs:e=>e.style.fontStyle!==`normal`&&null},{style:`font-style=normal`,clearMark:e=>e.type.name===this.name},{style:`font-style=italic`}]},renderHTML({HTMLAttributes:e}){return[`em`,A(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:`em`,parseMarkdown:(e,t)=>t.applyMark(`italic`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<em>`,close:`</em>`}},renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Hp({find:GT,type:this.type}),Hp({find:qT,type:this.type})]},addPasteRules(){return[Yp({find:KT,type:this.type}),Yp({find:JT,type:this.type})]}}),XT=`aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zLine truncated
|
||||
`,CD=`️`,wD=``,TD=``,ED=null,DD=null;function OD(e=[]){let t={};dE.groups=t;let n=new dE;ED??=MD(XT),DD??=MD(ZT),F(n,`'`,UE),F(n,`{`,EE),F(n,`}`,DE),F(n,`[`,OE),F(n,`]`,kE),F(n,`(`,AE),F(n,`)`,jE),F(n,`<`,ME),F(n,`>`,NE),F(n,`(`,PE),F(n,`)`,FE),F(n,`「`,IE),F(n,`」`,LE),F(n,`『`,RE),F(n,`』`,zE),F(n,`<`,BE),F(n,`>`,VE),F(n,`&`,HE),F(n,`*`,WE),F(n,`@`,GE),F(n,"`",qE),F(n,`^`,JE),F(n,`:`,YE),F(n,`,`,XE),F(n,`$`,ZE),F(n,`.`,QE),F(n,`=`,$E),F(n,`!`,eD),F(n,`-`,tD),F(n,`%`,nD),F(n,`|`,rD),F(n,`+`,iD),F(n,`#`,aD),F(n,`?`,oD),F(n,`"`,sD),F(n,`/`,uD),F(n,`;`,lD),F(n,`~`,dD),F(n,`_`,fD),F(n,`\\`,KE),F(n,`・`,cD);let r=fE(n,yD,CE,{[QT]:!0});fE(r,yD,r);let i=fE(r,gD,gE,{[tE]:!0}),a=fE(r,_D,_E,{[nE]:!0}),o=fE(n,gD,mE,{[$T]:!0});fE(o,yD,i),fE(o,gD,o),fE(i,yD,i),fE(i,gD,i);let s=fE(n,_D,hE,{[eE]:!0});fE(s,gD),fE(s,yD,a),fE(s,_D,s),fE(a,yD,a),fE(a,gD),fE(a,_D,a);let c=F(n,SD,TE,{[sE]:!0}),l=F(n,xD,wE,{[sE]:!0}),u=fE(n,bD,wE,{[sE]:!0});F(n,TD,u),F(l,SD,c),F(l,TD,u),fE(l,bD,u),F(u,xD),F(u,SD),fE(u,bD,u),F(u,TD,u);let d=fE(n,vD,pD,{[iE]:!0});F(d,`#`),fE(d,vD,d),F(d,CD,d);let f=F(d,wD);F(f,`#`),fE(f,vD,d);let p=[[gD,o],[yD,i]],m=[[gD,null],[_D,s],[yD,a]];for(let e=0;e<ED.length;e++)jD(n,ED[e],yE,mE,p);for(let e=0;e<DD.length;e++)jD(n,DD[e],bE,hE,m);lE(yE,{tld:!0,ascii:!0},t),lE(bE,{utld:!0,alpha:!0},t),jD(n,`file`,xE,mE,p),jD(n,`mailto`,xE,mE,p),jD(n,`http`,SE,mE,p),jD(n,`https`,SE,mE,p),jD(n,`ftp`,SE,mE,p),jD(n,`ftps`,SE,mE,p),lE(xE,{scheme:!0,ascii:!0},t),lE(SE,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let r=e[t][0],i=e[t][1]?{[aE]:!0}:{[oE]:!0};r.indexOf(`-`)>=0?i[rE]=!0:gD.test(r)?yD.test(r)?i[tE]=!0:i[$T]=!0:i[QT]=!0,pE(n,r,r,i)}return pE(n,`localhost`,vE,{ascii:!0}),n.jd=new dE(mD),{start:n,tokens:Object.assign({groups:t},hD)}}function kD(e,t){let n=AD(t.replace(/[A-Z]/g,e=>e.toLowerCase())),r=n.length,i=[],a=0,o=0;for(;o<r;){let s=e,c=null,l=0,u=null,d=-1,f=-1;for(;o<r&&(c=s.go(n[o]));)s=c,s.accepts()?(d=0,f=0,u=s):d>=0&&(d+=n[o].length,f++),l+=n[o].length,a+=n[o].length,o++;a-=d,o-=f,l-=d,i.push({t:u.t,v:t.slice(a-l,a),s:a-l,e:a})}return i}function AD(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e.charCodeAt(r),a,o=i<55296||i>56319||r+1===n||(a=e.charCodeAt(r+1))<56320||a>57343?e[r]:e.slice(r,r+2);t.push(o),r+=o.length}return t}function jD(e,t,n,r,i){let a,o=t.length;for(let n=0;n<o-1;n++){let o=t[n];e.j[o]?a=e.j[o]:(a=new dE(r),a.jr=i.slice(),e.j[o]=a),e=a}return a=new dE(n),a.jr=i.slice(),e.j[t[o-1]]=a,a}function MD(e){let t=[],n=[],r=0;for(;r<e.length;){let i=0;for(;`0123456789`.indexOf(e[r+i])>=0;)i++;if(i>0){t.push(n.join(``));for(let t=parseInt(e.substring(r,r+i),10);t>0;t--)n.pop();r+=i}else n.push(e[r]),r++}return t}var ND={defaultProtocol:`http`,events:null,format:FD,formatHref:FD,nl2br:!1,tagName:`a`,target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],ignoreClasses:[],render:null};function PD(e,t=null){let n=Object.assign({},ND);e&&(n=Object.assign(n,e instanceof PD?e.o:e));let r=n.ignoreTags,i=[];for(let e=0;e<r.length;e++)i.push(r[e].toUpperCase());this.o=n,t&&(this.defaultRender=t),this.ignoreTags=i,this.ignoreClasses=n.ignoreClasses.slice()}PD.prototype={o:ND,ignoreTags:[],ignoreClasses:[],isIgnoredClass(e){if(typeof e!=`string`||this.ignoreClasses.length===0)return!1;let t=e.split(/\s+/);for(let e=0;e<t.length;e++)if(this.ignoreClasses.indexOf(t[e])>=0)return!0;return!1},defaultRender(e){return e},check(e){return this.get(`validate`,e.toString(),e)},get(e,t,n){let r=t!=null,i=this.o[e];return i&&(typeof i==`object`?(i=n.t in i?i[n.t]:ND[e],typeof i==`function`&&r&&(i=i(t,n))):typeof i==`function`&&r&&(i=i(t,n.t,n)),i)},getObj(e,t,n){let r=this.o[e];return typeof r==`function`&&t!=null&&(r=r(t,n.t,n)),r},render(e){let t=e.render(this);return(this.get(`render`,null,e)||this.defaultRender)(t,e.t,e)}};function FD(e){return e}function ID(e,t){this.t=`token`,this.v=e,this.tk=t}ID.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),n=e.get(`truncate`,t,this),r=e.get(`format`,t,this);return n&&r.length>n?r.substring(0,n)+`…`:r},toFormattedHref(e){return e.get(`formatHref`,this.toHref(e.get(`defaultProtocol`)),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=ND.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get(`validate`,this.toString(),this)},render(e){let t=this,n=this.toHref(e.get(`defaultProtocol`)),r=e.get(`formatHref`,n,this),i=e.get(`tagName`,n,t),a=this.toFormattedString(e),o={},s=e.get(`className`,n,t),c=e.get(`target`,n,t),l=e.get(`rel`,n,t),u=e.getObj(`attributes`,n,t),d=e.getObj(`events`,n,t);reLine truncated
|
||||
`,parseMarkdown:()=>({type:`hardBreak`}),addCommands(){return{setHardBreak:()=>({commands:e,chain:t,state:n,editor:r})=>e.first([()=>e.exitCode(),()=>e.command(()=>{let{selection:e,storedMarks:i}=n;if(e.$from.parent.type.spec.isolating)return!1;let{keepMarks:a}=this.options,{splittableMarks:o}=r.extensionManager,s=i||e.$to.parentOffset&&e.$from.marks();return t().insertContent({type:this.name}).command(({tr:e,dispatch:t})=>{if(t&&s&&a){let t=s.filter(e=>o.includes(e.type.name));e.ensureMarks(t)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),KT=Jp.create({name:`heading`,addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:`inline*`,group:`block`,defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(e=>({tag:`h${e}`,attrs:{level:e}}))},renderHTML({node:e,HTMLAttributes:t}){return[`h${this.options.levels.includes(e.attrs.level)?e.attrs.level:this.options.levels[0]}`,A(this.options.HTMLAttributes,t),0]},parseMarkdown(e,t){let n=e.depth||1;return this.options.levels.includes(n)?t.createNode(`heading`,{level:n},t.parseInline(e.tokens||[])):t.createNode(`paragraph`,void 0,t.parseInline(e.tokens||[]))},renderMarkdown:(e,t)=>{let n=e.attrs?.level?parseInt(e.attrs.level,10):1,r=`#`.repeat(n);return e.content?`${r} ${t.renderChildren(e.content)}`:``},addCommands(){return{setHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.setNode(this.name,e):!1,toggleHeading:e=>({commands:t})=>this.options.levels.includes(e.level)?t.toggleNode(this.name,`paragraph`,e):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((e,t)=>({...e,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(e=>Wp({find:RegExp(`^(#{${Math.min(...this.options.levels)},${e}})\\s$`),type:this.type,getAttributes:{level:e}}))}}),qT=Jp.create({name:`horizontalRule`,addOptions(){return{HTMLAttributes:{},nextNodeType:`paragraph`}},group:`block`,parseHTML(){return[{tag:`hr`}]},renderHTML({HTMLAttributes:e}){return[`hr`,A(this.options.HTMLAttributes,e)]},markdownTokenName:`hr`,parseMarkdown:(e,t)=>t.createNode(`horizontalRule`),renderMarkdown:()=>`---`,addCommands(){return{setHorizontalRule:()=>({chain:e,state:t})=>{if(!Df(t,t.schema.nodes[this.name]))return!1;let{selection:n}=t,{$to:r}=n,i=e();return pd(n)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:e,tr:t,dispatch:n})=>{if(n){let{$to:n}=t.selection,r=n.end();if(n.nodeAfter)n.nodeAfter.isTextblock?t.setSelection(w.create(t.doc,n.pos+1)):n.nodeAfter.isBlock?t.setSelection(T.create(t.doc,n.pos)):t.setSelection(w.create(t.doc,n.pos));else{let i=(e.schema.nodes[this.options.nextNodeType]||n.parent.type.contentMatch.defaultType)?.create();i&&(t.insert(r,i),t.setSelection(w.create(t.doc,r+1)))}t.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Up({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),JT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,YT=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,XT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,ZT=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,QT=_p.create({name:`italic`,addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:`em`},{tag:`i`,getAttrs:e=>e.style.fontStyle!==`normal`&&null},{style:`font-style=normal`,clearMark:e=>e.type.name===this.name},{style:`font-style=italic`}]},renderHTML({HTMLAttributes:e}){return[`em`,A(this.options.HTMLAttributes,e),0]},addCommands(){return{setItalic:()=>({commands:e})=>e.setMark(this.name),toggleItalic:()=>({commands:e})=>e.toggleMark(this.name),unsetItalic:()=>({commands:e})=>e.unsetMark(this.name)}},markdownTokenName:`em`,parseMarkdown:(e,t)=>t.applyMark(`italic`,t.parseInline(e.tokens||[])),markdownOptions:{htmlReopen:{open:`<em>`,close:`</em>`}},renderMarkdown:(e,t)=>`*${t.renderChildren(e)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[Hp({find:JT,type:this.type}),Hp({find:XT,type:this.type})]},addPasteRules(){return[Yp({find:YT,type:this.type}),Yp({find:ZT,type:this.type})]}}),$T=`aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zLine truncated
|
||||
`,ED=`️`,DD=``,OD=``,kD=null,AD=null;function jD(e=[]){let t={};mE.groups=t;let n=new mE;kD??=FD($T),AD??=FD(eE),F(n,`'`,KE),F(n,`{`,kE),F(n,`}`,AE),F(n,`[`,jE),F(n,`]`,ME),F(n,`(`,NE),F(n,`)`,PE),F(n,`<`,FE),F(n,`>`,IE),F(n,`(`,LE),F(n,`)`,RE),F(n,`「`,zE),F(n,`」`,BE),F(n,`『`,VE),F(n,`』`,HE),F(n,`<`,UE),F(n,`>`,WE),F(n,`&`,GE),F(n,`*`,qE),F(n,`@`,JE),F(n,"`",XE),F(n,`^`,ZE),F(n,`:`,QE),F(n,`,`,$E),F(n,`$`,eD),F(n,`.`,tD),F(n,`=`,nD),F(n,`!`,rD),F(n,`-`,iD),F(n,`%`,aD),F(n,`|`,oD),F(n,`+`,sD),F(n,`#`,cD),F(n,`?`,lD),F(n,`"`,uD),F(n,`/`,pD),F(n,`;`,fD),F(n,`~`,mD),F(n,`_`,hD),F(n,`\\`,YE),F(n,`・`,dD);let r=hE(n,SD,EE,{[tE]:!0});hE(r,SD,r);let i=hE(r,yD,yE,{[iE]:!0}),a=hE(r,bD,bE,{[aE]:!0}),o=hE(n,yD,_E,{[nE]:!0});hE(o,SD,i),hE(o,yD,o),hE(i,SD,i),hE(i,yD,i);let s=hE(n,bD,vE,{[rE]:!0});hE(s,yD),hE(s,SD,a),hE(s,bD,s),hE(a,SD,a),hE(a,yD),hE(a,bD,a);let c=F(n,TD,OE,{[uE]:!0}),l=F(n,wD,DE,{[uE]:!0}),u=hE(n,CD,DE,{[uE]:!0});F(n,OD,u),F(l,TD,c),F(l,OD,u),hE(l,CD,u),F(u,wD),F(u,TD),hE(u,CD,u),F(u,OD,u);let d=hE(n,xD,gD,{[sE]:!0});F(d,`#`),hE(d,xD,d),F(d,ED,d);let f=F(d,DD);F(f,`#`),hE(f,xD,d);let p=[[yD,o],[SD,i]],m=[[yD,null],[bD,s],[SD,a]];for(let e=0;e<kD.length;e++)PD(n,kD[e],SE,_E,p);for(let e=0;e<AD.length;e++)PD(n,AD[e],CE,vE,m);fE(SE,{tld:!0,ascii:!0},t),fE(CE,{utld:!0,alpha:!0},t),PD(n,`file`,wE,_E,p),PD(n,`mailto`,wE,_E,p),PD(n,`http`,TE,_E,p),PD(n,`https`,TE,_E,p),PD(n,`ftp`,TE,_E,p),PD(n,`ftps`,TE,_E,p),fE(wE,{scheme:!0,ascii:!0},t),fE(TE,{slashscheme:!0,ascii:!0},t),e=e.sort((e,t)=>e[0]>t[0]?1:-1);for(let t=0;t<e.length;t++){let r=e[t][0],i=e[t][1]?{[cE]:!0}:{[lE]:!0};r.indexOf(`-`)>=0?i[oE]=!0:yD.test(r)?SD.test(r)?i[iE]=!0:i[nE]=!0:i[tE]=!0,gE(n,r,r,i)}return gE(n,`localhost`,xE,{ascii:!0}),n.jd=new mE(_D),{start:n,tokens:Object.assign({groups:t},vD)}}function MD(e,t){let n=ND(t.replace(/[A-Z]/g,e=>e.toLowerCase())),r=n.length,i=[],a=0,o=0;for(;o<r;){let s=e,c=null,l=0,u=null,d=-1,f=-1;for(;o<r&&(c=s.go(n[o]));)s=c,s.accepts()?(d=0,f=0,u=s):d>=0&&(d+=n[o].length,f++),l+=n[o].length,a+=n[o].length,o++;a-=d,o-=f,l-=d,i.push({t:u.t,v:t.slice(a-l,a),s:a-l,e:a})}return i}function ND(e){let t=[],n=e.length,r=0;for(;r<n;){let i=e.charCodeAt(r),a,o=i<55296||i>56319||r+1===n||(a=e.charCodeAt(r+1))<56320||a>57343?e[r]:e.slice(r,r+2);t.push(o),r+=o.length}return t}function PD(e,t,n,r,i){let a,o=t.length;for(let n=0;n<o-1;n++){let o=t[n];e.j[o]?a=e.j[o]:(a=new mE(r),a.jr=i.slice(),e.j[o]=a),e=a}return a=new mE(n),a.jr=i.slice(),e.j[t[o-1]]=a,a}function FD(e){let t=[],n=[],r=0;for(;r<e.length;){let i=0;for(;`0123456789`.indexOf(e[r+i])>=0;)i++;if(i>0){t.push(n.join(``));for(let t=parseInt(e.substring(r,r+i),10);t>0;t--)n.pop();r+=i}else n.push(e[r]),r++}return t}var ID={defaultProtocol:`http`,events:null,format:RD,formatHref:RD,nl2br:!1,tagName:`a`,target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],ignoreClasses:[],render:null};function LD(e,t=null){let n=Object.assign({},ID);e&&(n=Object.assign(n,e instanceof LD?e.o:e));let r=n.ignoreTags,i=[];for(let e=0;e<r.length;e++)i.push(r[e].toUpperCase());this.o=n,t&&(this.defaultRender=t),this.ignoreTags=i,this.ignoreClasses=n.ignoreClasses.slice()}LD.prototype={o:ID,ignoreTags:[],ignoreClasses:[],isIgnoredClass(e){if(typeof e!=`string`||this.ignoreClasses.length===0)return!1;let t=e.split(/\s+/);for(let e=0;e<t.length;e++)if(this.ignoreClasses.indexOf(t[e])>=0)return!0;return!1},defaultRender(e){return e},check(e){return this.get(`validate`,e.toString(),e)},get(e,t,n){let r=t!=null,i=this.o[e];return i&&(typeof i==`object`?(i=n.t in i?i[n.t]:ID[e],typeof i==`function`&&r&&(i=i(t,n))):typeof i==`function`&&r&&(i=i(t,n.t,n)),i)},getObj(e,t,n){let r=this.o[e];return typeof r==`function`&&t!=null&&(r=r(t,n.t,n)),r},render(e){let t=e.render(this);return(this.get(`render`,null,e)||this.defaultRender)(t,e.t,e)}};function RD(e){return e}function zD(e,t){this.t=`token`,this.v=e,this.tk=t}zD.prototype={isLink:!1,toString(){return this.v},toHref(e){return this.toString()},toFormattedString(e){let t=this.toString(),n=e.get(`truncate`,t,this),r=e.get(`format`,t,this);return n&&r.length>n?r.substring(0,n)+`…`:r},toFormattedHref(e){return e.get(`formatHref`,this.toHref(e.get(`defaultProtocol`)),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(e=ID.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(e),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(e){return{type:this.t,value:this.toFormattedString(e),isLink:this.isLink,href:this.toFormattedHref(e),start:this.startIndex(),end:this.endIndex()}},validate(e){return e.get(`validate`,this.toString(),this)},render(e){let t=this,n=this.toHref(e.get(`defaultProtocol`)),r=e.get(`formatHref`,n,this),i=e.get(`tagName`,n,t),a=this.toFormattedString(e),o={},s=e.get(`className`,n,t),c=e.get(`target`,n,t),l=e.get(`rel`,n,t),u=e.getObj(`attributes`,n,t),d=e.getObj(`events`,n,t);reLine truncated
|
||||
1. Must only contain digits, lowercase ASCII letters or "-"
|
||||
2. Cannot start or end with "-"
|
||||
3. "-" cannot repeat`);JD.customSchemes.push([e,t])}function ZD(){JD.scanner=OD(JD.customSchemes);for(let e=0;e<JD.tokenQueue.length;e++)JD.tokenQueue[e][1]({scanner:JD.scanner});JD.parser=UD(JD.scanner.tokens);for(let e=0;e<JD.pluginQueue.length;e++)JD.pluginQueue[e][1]({scanner:JD.scanner,parser:JD.parser});return JD.initialized=!0,JD}function QD(e){return JD.initialized||ZD(),WD(JD.parser.start,e,kD(JD.scanner.start,e))}QD.scan=kD;function $D(e,t=null,n=null){if(t&&typeof t==`object`){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}let r=new PD(n),i=QD(e),a=[];for(let e=0;e<i.length;e++){let n=i[e];n.isLink&&(!t||n.t===t)&&r.check(n)&&a.push(n.toFormattedObject(r))}return a}var eO=`[\0- \xA0 -\u2029 ]`,tO=new RegExp(eO),nO=RegExp(`${eO}$`),rO=RegExp(`${eO}+$`),iO=new RegExp(eO,`g`);function aO(e,t,n){let r=e.doc.resolve(t.to);if(!r.nodeBefore?.isText)return;let i=e.doc.textBetween(t.from,t.to,``,``).match(rO)?.[0];if(!i)return;let a=t.to-i.length,o=ed(a,t.to,e.doc).filter(e=>e.mark.type===n);if(!o.length)return;let{nodeAfter:s}=r;if(s&&o.some(e=>e.mark.isInSet(s.marks)))return;let c=e.storedMarks;e.removeMark(a,t.to,n),e.setStoredMarks(c),e.selection.empty&&e.selection.from===t.to&&e.removeStoredMark(n)}function oO(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function sO(e){return new E({key:new D(`autolink`),appendTransaction:(t,n,r)=>{let i=t.some(e=>e.docChanged)&&!n.doc.eq(r.doc),a=t.some(e=>e.getMeta(`preventAutolink`));if(!i||a)return;let{tr:o}=r,s=hu(n.doc,[...t]);if(!t.some(Jc)){let t=[];s.steps.forEach((e,n)=>{if(!(e instanceof Dt)||!e.slice.size)return;let r=s.mapping.slice(n+1),i=r.map(e.from,1),a=r.map(e.from+e.slice.size,-1);i<a&&t.push({from:i,to:a})}),t.sort((e,t)=>t.to-e.to),t.forEach(t=>aO(o,t,e.type))}if($u(s).forEach(({newRange:t})=>{let n=_u(r.doc,t,e=>e.isTextblock),i,a;if(n.length>1)i=n[0],a=r.doc.textBetween(i.pos,i.pos+i.node.nodeSize,void 0,` `);else if(n.length){let e=r.doc.textBetween(t.from,t.to,` `,` `);if(!nO.test(e))return;i=n[0],a=r.doc.textBetween(i.pos,t.to,void 0,` `)}if(i&&a){let t=a.split(tO).filter(Boolean);if(t.length<=0)return!1;let n=t[t.length-1],s=i.pos+a.lastIndexOf(n);if(!n)return!1;let c=QD(n).map(t=>t.toObject(e.defaultProtocol));if(!oO(c))return!1;c.filter(e=>e.isLink).map(e=>({...e,from:s+e.start+1,to:s+e.end+1})).filter(e=>!r.schema.marks.code||!r.doc.rangeHasMark(e.from,e.to,r.schema.marks.code)).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{ed(t.from,t.to,r.doc).some(t=>t.mark.type===e.type)||o.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),o.steps.length)return o}})}function cO(e){return new E({key:new D(`handleClickLink`),props:{handleClick:(t,n,r)=>{if(r.button!==0||!t.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{let t=r.target;if(!t)return!1;let n=e.editor.view.dom;i=t.closest(`a`),i&&!n.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(e.enableClickSelection&&(a=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let n=Xu(t.state,e.type.name),r=i.href??n.href,o=i.target??n.target;r&&(window.open(r,o),a=!0)}return a}}})}var lO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,uO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function dO(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function fO(e,t){let n=0,r=0;for(;r<t;){if(e[r]!=="`"||n===0&&dO(e,r)){r+=1;continue}let i=0;for(;r<t&&e[r]==="`";)i+=1,r+=1;n===0?n=i:i===n&&(n=0)}return n>0}function pO(e,t,n){let[,r,i]=t;return(t.index?e[t.index-1]:void 0)===`!`||dO(e,t.index??0)||fO(e,t.index??0)?!1:!!r.trim()&&n(i)}function mO(e){let[t,n,r,,i,a,o]=e,s=i??a??o;return{index:e.index??0,text:t,replaceWith:n,data:{href:r,title:s||null,markdown:!0}}}function hO(e,t){return e.index<t.index+t.text.length&&t.index<e.index+e.text.length}function gO(e){return{href:e.data?.href,title:e.data?.title??null}}function _O(e){let t=Hp({find:t=>{let n=lO.exec(t);return!n||!pO(t,n,e.isAllowedHref)?null:mO(n)},type:e.type,getAttributes:gO});return new lp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function vO(e){let t=Yp({find:t=>{let n=[];for(let r of t.matchAll(uO))pO(t,r,e.isAllowedHref)&&n.push(mO(r));let r=(e.findPlainUrls?.call(e,t)??[]).filter(e=>!n.some(t=>hO(t,e)));return[...n,...r]},type:e.type,getAttributes:gO});return new vp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.match.data?.markdown&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function yO(e){return new E({key:new D(`handlePasteLink`),props:{handlePaste:(t,n,r)=>{let{shouldAutoLink:i}=e,{state:a}=t,{selection:o}=a,{empty:s}=o;if(s)return!1;let c=``;r.content.forEach(e=>{c+=e.textContent});let l=$D(c,Line truncated
|
||||
`):``,markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(SO,this.editor.getAttributes(CO)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let e=Gp({find:wO,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=Gp({find:wO,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(CO),editor:this.editor})),[e]}}),EO=(e,t,n)=>{let{selection:r}=e;if(!r.empty)return null;let{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let a=-1;for(let e=i.depth;e>0;--e)if(i.node(e).type.name===t){a=e;break}if(a<0)return null;let o=i.node(a),s=i.index(a);if(s+1>=o.childCount)return null;let c=o.child(s+1);if(!n.includes(c.type.name))return null;let l=e.schema.nodes[t],u=!1;if(c.forEach(e=>{e.type===l&&e.childCount>1&&(u=!0)}),!u)return null;let d=e.doc.resolve(i.after()).nodeAfter;if(!d||!n.includes(d.type.name))return null;let f=[];return d.forEach(e=>{f.push(e)}),f.length===0?null:{listItemDepth:a,nestedList:d,nestedListPos:i.after(),insertPos:i.after(a),items:f}},DO=(e,t,n,r)=>{let i=EO(e,n,r);if(!i)return!1;let{selection:a}=e,{nestedList:o,nestedListPos:c,insertPos:l,items:u}=i,d=e.tr;d.delete(c,c+o.nodeSize);let f=d.mapping.map(l);return d.insert(f,s.from(u)),d.setSelection(a.map(d.doc,d.mapping)),t&&t(d),!0},OO=(e,t,n)=>DO(e.state,e.view.dispatch,t,n),kO=(e,t)=>Tp.create({name:`${e}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let n=()=>OO(this.editor,e,t);return{Delete:n,"Mod-Delete":n}}}),AO=[[1e3,`m`],[900,`cm`],[500,`d`],[400,`cd`],[100,`c`],[90,`xc`],[50,`l`],[40,`xl`],[10,`x`],[9,`ix`],[5,`v`],[4,`iv`],[1,`i`]],jO=`abcdefghijklmnopqrstuvwxyz`,MO=String.raw`\d+|[ivxlcdmIVXLCDM]+|${`[a-zA-Z]{1,2}`}`;function NO(e){let t=e,n=``;for(let[e,r]of AO)for(;t>=e;)n+=r,t-=e;return n}function PO(e){return NO(e).toUpperCase()}function FO(e){let t=e.toLowerCase(),n=0,r=0;for(;n<t.length;){let e=!1;for(let[i,a]of AO)if(t.startsWith(a,n)){r+=i,n+=a.length,e=!0;break}if(!e)return 0}return r}function IO(e){if(!/^[ivxlcdmIVXLCDM]+$/.test(e))return!1;let t=FO(e);return t<=0?!1:(e===e.toLowerCase()?NO(t):PO(t))===e}function LO(e){let t=e.toLowerCase();if(t.length===1)return t.charCodeAt(0)-97+1;if(t.length===2){let e=t.charCodeAt(0)-97,n=t.charCodeAt(1)-97;return(e+1)*26+n+1}return 0}function RO(e){if(e<=26)return jO[e-1];let t=Math.floor((e-1)/26)-1,n=(e-1)%26;return t<0?jO[n]:jO[t]+jO[n]}function zO(e){if(e&&!/^\d+$/.test(e)){if(IO(e))return e===e.toLowerCase()?`i`:`I`;if(/^[a-z]{1,2}$/.test(e))return`a`;if(/^[A-Z]{1,2}$/.test(e))return`A`}}function BO(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=zO(e);if(t===`i`||t===`I`)return FO(e);if(t===`a`||t===`A`){let t=LO(e);return t>0?t:1}let n=parseInt(e,10);return Number.isNaN(n)?1:n}function VO(e,t){if(e===`numeric`)return String(t);switch(e){case`a`:return RO(t);case`A`:return RO(t).toUpperCase();case`i`:return NO(t);case`I`:return PO(t);default:return String(t)}}function HO(e){if(e.length===0)return!1;let t=zO(e[0])??`numeric`,n=BO(e[0]);if(n<1)return!1;for(let r=0;r<e.length;r++){let i=VO(t,n+r);if(e[r]!==i)return!1}return!0}function UO(e){return{type:zO(e),start:BO(e)}}function WO(e){let{type:t,start:n}=UO(e),r={};return t&&(r.type=t),n!==1&&(r.start=n),r}function GO(e,t,n=`. `){let r=t+1;if(!e||e===`1`)return`${r}${n}`;switch(e){case`a`:return`${RO(r)}${n}`;case`A`:return`${RO(r).toUpperCase()}${n}`;case`i`:return`${NO(r)}${n}`;case`I`:return`${PO(r)}${n}`;default:return`${r}${n}`}}function KO(e){return!e[0]||e[0].type===`paragraph`?e:[{type:`paragraph`,content:[]},...e]}function qO(e){let t=e.content?.[0];return t?.type===`paragraph`&&!t.content?.length}var JO=` `,YO=1,XO=e=>(e?.level??YO)>YO;function ZO(e){let t=e.tokens?.[0];return!!(e.text&&e.tokens?.length===1&&t?.type===`list`&&t.ordered&&t.raw===e.text)}function QO(e,t){return t.tokenizeInline?t.parseInline(t.tokenizeInline(e)):t.parseInline([{type:`text`,raw:e,text:e}])}var $O=Jp.create({name:`listItem`,addOptions(){return{HTMLAttributes:{},bulletListTypeName:`bulletList`,orderedListTypeName:`orderedList`}},content:`paragraph block*`,defining:!0,parseHTML(){return[{tag:`li`}]},renderHTML({HTMLAttributes:e}){return[`li`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`list_item`,parseMarkdown:(e,t)=>{if(e.type!==`list_item`)return[];let n=t.parseBlockChildren??t.parseChildren,r=[];if(e.tokens&&e.tokens.length>0){if(ZO(e))return{type:`listItem`,content:[{type:`paragraph`,content:QO(e.text||``,t)}]};let[i,...a]=e.tokens;if(i.type===`heading`)return{type:`listItem`,content:[{type:`paragraph`,content:t.parseInline(i.tokens??[])},...a.length>0?n(a):[]]}Line truncated
|
||||
3. "-" cannot repeat`);ZD.customSchemes.push([e,t])}function eO(){ZD.scanner=jD(ZD.customSchemes);for(let e=0;e<ZD.tokenQueue.length;e++)ZD.tokenQueue[e][1]({scanner:ZD.scanner});ZD.parser=KD(ZD.scanner.tokens);for(let e=0;e<ZD.pluginQueue.length;e++)ZD.pluginQueue[e][1]({scanner:ZD.scanner,parser:ZD.parser});return ZD.initialized=!0,ZD}function tO(e){return ZD.initialized||eO(),qD(ZD.parser.start,e,MD(ZD.scanner.start,e))}tO.scan=MD;function nO(e,t=null,n=null){if(t&&typeof t==`object`){if(n)throw Error(`linkifyjs: Invalid link type ${t}; must be a string`);n=t,t=null}let r=new LD(n),i=tO(e),a=[];for(let e=0;e<i.length;e++){let n=i[e];n.isLink&&(!t||n.t===t)&&r.check(n)&&a.push(n.toFormattedObject(r))}return a}var rO=`[\0- \xA0 -\u2029 ]`,iO=new RegExp(rO),aO=RegExp(`${rO}$`),oO=RegExp(`${rO}+$`),sO=new RegExp(rO,`g`);function cO(e,t,n){let r=e.doc.resolve(t.to);if(!r.nodeBefore?.isText)return;let i=e.doc.textBetween(t.from,t.to,``,``).match(oO)?.[0];if(!i)return;let a=t.to-i.length,o=ed(a,t.to,e.doc).filter(e=>e.mark.type===n);if(!o.length)return;let{nodeAfter:s}=r;if(s&&o.some(e=>e.mark.isInSet(s.marks)))return;let c=e.storedMarks;e.removeMark(a,t.to,n),e.setStoredMarks(c),e.selection.empty&&e.selection.from===t.to&&e.removeStoredMark(n)}function lO(e){return e.length===1?e[0].isLink:e.length===3&&e[1].isLink?[`()`,`[]`].includes(e[0].value+e[2].value):!1}function uO(e){return new E({key:new D(`autolink`),appendTransaction:(t,n,r)=>{let i=t.some(e=>e.docChanged)&&!n.doc.eq(r.doc),a=t.some(e=>e.getMeta(`preventAutolink`));if(!i||a)return;let{tr:o}=r,s=hu(n.doc,[...t]);if(!t.some(Jc)){let t=[];s.steps.forEach((e,n)=>{if(!(e instanceof Dt)||!e.slice.size)return;let r=s.mapping.slice(n+1),i=r.map(e.from,1),a=r.map(e.from+e.slice.size,-1);i<a&&t.push({from:i,to:a})}),t.sort((e,t)=>t.to-e.to),t.forEach(t=>cO(o,t,e.type))}if($u(s).forEach(({newRange:t})=>{let n=_u(r.doc,t,e=>e.isTextblock),i,a;if(n.length>1)i=n[0],a=r.doc.textBetween(i.pos,i.pos+i.node.nodeSize,void 0,` `);else if(n.length){let e=r.doc.textBetween(t.from,t.to,` `,` `);if(!aO.test(e))return;i=n[0],a=r.doc.textBetween(i.pos,t.to,void 0,` `)}if(i&&a){let t=a.split(iO).filter(Boolean);if(t.length<=0)return!1;let n=t[t.length-1],s=i.pos+a.lastIndexOf(n);if(!n)return!1;let c=tO(n).map(t=>t.toObject(e.defaultProtocol));if(!lO(c))return!1;c.filter(e=>e.isLink).map(e=>({...e,from:s+e.start+1,to:s+e.end+1})).filter(e=>!r.schema.marks.code||!r.doc.rangeHasMark(e.from,e.to,r.schema.marks.code)).filter(t=>e.validate(t.value)).filter(t=>e.shouldAutoLink(t.value)).forEach(t=>{ed(t.from,t.to,r.doc).some(t=>t.mark.type===e.type)||o.addMark(t.from,t.to,e.type.create({href:t.href}))})}}),o.steps.length)return o}})}function dO(e){return new E({key:new D(`handleClickLink`),props:{handleClick:(t,n,r)=>{if(r.button!==0||!t.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{let t=r.target;if(!t)return!1;let n=e.editor.view.dom;i=t.closest(`a`),i&&!n.contains(i)&&(i=null)}if(!i)return!1;let a=!1;if(e.enableClickSelection&&(a=e.editor.commands.extendMarkRange(e.type.name)),e.openOnClick){let n=Xu(t.state,e.type.name),r=i.href??n.href,o=i.target??n.target;r&&(window.open(r,o),a=!0)}return a}}})}var fO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,pO=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function mO(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function hO(e,t){let n=0,r=0;for(;r<t;){if(e[r]!=="`"||n===0&&mO(e,r)){r+=1;continue}let i=0;for(;r<t&&e[r]==="`";)i+=1,r+=1;n===0?n=i:i===n&&(n=0)}return n>0}function gO(e,t,n){let[,r,i]=t;return(t.index?e[t.index-1]:void 0)===`!`||mO(e,t.index??0)||hO(e,t.index??0)?!1:!!r.trim()&&n(i)}function _O(e){let[t,n,r,,i,a,o]=e,s=i??a??o;return{index:e.index??0,text:t,replaceWith:n,data:{href:r,title:s||null,markdown:!0}}}function vO(e,t){return e.index<t.index+t.text.length&&t.index<e.index+e.text.length}function yO(e){return{href:e.data?.href,title:e.data?.title??null}}function bO(e){let t=Hp({find:t=>{let n=fO.exec(t);return!n||!gO(t,n,e.isAllowedHref)?null:_O(n)},type:e.type,getAttributes:yO});return new lp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function xO(e){let t=Yp({find:t=>{let n=[];for(let r of t.matchAll(pO))gO(t,r,e.isAllowedHref)&&n.push(_O(r));let r=(e.findPlainUrls?.call(e,t)??[]).filter(e=>!n.some(t=>vO(t,e)));return[...n,...r]},type:e.type,getAttributes:yO});return new vp({find:t.find,handler:e=>{let n=t.handler(e);return n!==null&&e.state.tr.steps.length&&e.match.data?.markdown&&e.state.tr.setMeta(`preventAutolink`,!0),n}})}function SO(e){return new E({key:new D(`handlePasteLink`),props:{handlePaste:(t,n,r)=>{let{shouldAutoLink:i}=e,{state:a}=t,{selection:o}=a,{empty:s}=o;if(s)return!1;let c=``;r.content.forEach(e=>{c+=e.textContent});let l=nO(c,Line truncated
|
||||
`):``,markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(TO,this.editor.getAttributes(EO)).run():e.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let e=Gp({find:DO,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(e=Gp({find:DO,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(EO),editor:this.editor})),[e]}}),kO=(e,t,n)=>{let{selection:r}=e;if(!r.empty)return null;let{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let a=-1;for(let e=i.depth;e>0;--e)if(i.node(e).type.name===t){a=e;break}if(a<0)return null;let o=i.node(a),s=i.index(a);if(s+1>=o.childCount)return null;let c=o.child(s+1);if(!n.includes(c.type.name))return null;let l=e.schema.nodes[t],u=!1;if(c.forEach(e=>{e.type===l&&e.childCount>1&&(u=!0)}),!u)return null;let d=e.doc.resolve(i.after()).nodeAfter;if(!d||!n.includes(d.type.name))return null;let f=[];return d.forEach(e=>{f.push(e)}),f.length===0?null:{listItemDepth:a,nestedList:d,nestedListPos:i.after(),insertPos:i.after(a),items:f}},AO=(e,t,n,r)=>{let i=kO(e,n,r);if(!i)return!1;let{selection:a}=e,{nestedList:o,nestedListPos:c,insertPos:l,items:u}=i,d=e.tr;d.delete(c,c+o.nodeSize);let f=d.mapping.map(l);return d.insert(f,s.from(u)),d.setSelection(a.map(d.doc,d.mapping)),t&&t(d),!0},jO=(e,t,n)=>AO(e.state,e.view.dispatch,t,n),MO=(e,t)=>Tp.create({name:`${e}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){let n=()=>jO(this.editor,e,t);return{Delete:n,"Mod-Delete":n}}}),NO=[[1e3,`m`],[900,`cm`],[500,`d`],[400,`cd`],[100,`c`],[90,`xc`],[50,`l`],[40,`xl`],[10,`x`],[9,`ix`],[5,`v`],[4,`iv`],[1,`i`]],PO=`abcdefghijklmnopqrstuvwxyz`,FO=String.raw`\d+|[ivxlcdmIVXLCDM]+|${`[a-zA-Z]{1,2}`}`;function IO(e){let t=e,n=``;for(let[e,r]of NO)for(;t>=e;)n+=r,t-=e;return n}function LO(e){return IO(e).toUpperCase()}function RO(e){let t=e.toLowerCase(),n=0,r=0;for(;n<t.length;){let e=!1;for(let[i,a]of NO)if(t.startsWith(a,n)){r+=i,n+=a.length,e=!0;break}if(!e)return 0}return r}function zO(e){if(!/^[ivxlcdmIVXLCDM]+$/.test(e))return!1;let t=RO(e);return t<=0?!1:(e===e.toLowerCase()?IO(t):LO(t))===e}function BO(e){let t=e.toLowerCase();if(t.length===1)return t.charCodeAt(0)-97+1;if(t.length===2){let e=t.charCodeAt(0)-97,n=t.charCodeAt(1)-97;return(e+1)*26+n+1}return 0}function VO(e){if(e<=26)return PO[e-1];let t=Math.floor((e-1)/26)-1,n=(e-1)%26;return t<0?PO[n]:PO[t]+PO[n]}function HO(e){if(e&&!/^\d+$/.test(e)){if(zO(e))return e===e.toLowerCase()?`i`:`I`;if(/^[a-z]{1,2}$/.test(e))return`a`;if(/^[A-Z]{1,2}$/.test(e))return`A`}}function UO(e){if(/^\d+$/.test(e))return parseInt(e,10);let t=HO(e);if(t===`i`||t===`I`)return RO(e);if(t===`a`||t===`A`){let t=BO(e);return t>0?t:1}let n=parseInt(e,10);return Number.isNaN(n)?1:n}function WO(e,t){if(e===`numeric`)return String(t);switch(e){case`a`:return VO(t);case`A`:return VO(t).toUpperCase();case`i`:return IO(t);case`I`:return LO(t);default:return String(t)}}function GO(e){if(e.length===0)return!1;let t=HO(e[0])??`numeric`,n=UO(e[0]);if(n<1)return!1;for(let r=0;r<e.length;r++){let i=WO(t,n+r);if(e[r]!==i)return!1}return!0}function KO(e){return{type:HO(e),start:UO(e)}}function qO(e){let{type:t,start:n}=KO(e),r={};return t&&(r.type=t),n!==1&&(r.start=n),r}function JO(e,t,n=`. `){let r=t+1;if(!e||e===`1`)return`${r}${n}`;switch(e){case`a`:return`${VO(r)}${n}`;case`A`:return`${VO(r).toUpperCase()}${n}`;case`i`:return`${IO(r)}${n}`;case`I`:return`${LO(r)}${n}`;default:return`${r}${n}`}}function YO(e){return!e[0]||e[0].type===`paragraph`?e:[{type:`paragraph`,content:[]},...e]}function XO(e){let t=e.content?.[0];return t?.type===`paragraph`&&!t.content?.length}var ZO=` `,QO=1,$O=e=>(e?.level??QO)>QO;function ek(e){let t=e.tokens?.[0];return!!(e.text&&e.tokens?.length===1&&t?.type===`list`&&t.ordered&&t.raw===e.text)}function tk(e,t){return t.tokenizeInline?t.parseInline(t.tokenizeInline(e)):t.parseInline([{type:`text`,raw:e,text:e}])}var nk=Jp.create({name:`listItem`,addOptions(){return{HTMLAttributes:{},bulletListTypeName:`bulletList`,orderedListTypeName:`orderedList`}},content:`paragraph block*`,defining:!0,parseHTML(){return[{tag:`li`}]},renderHTML({HTMLAttributes:e}){return[`li`,A(this.options.HTMLAttributes,e),0]},markdownTokenName:`list_item`,parseMarkdown:(e,t)=>{if(e.type!==`list_item`)return[];let n=t.parseBlockChildren??t.parseChildren,r=[];if(e.tokens&&e.tokens.length>0){if(ek(e))return{type:`listItem`,content:[{type:`paragraph`,content:tk(e.text||``,t)}]};let[i,...a]=e.tokens;if(i.type===`heading`)return{type:`listItem`,content:[{type:`paragraph`,content:t.parseInline(i.tokens??[])},...a.length>0?n(a):[]]}Line truncated
|
||||
`).trim(),contentLines:m,raw:g.join(`
|
||||
`)}),r=h,n=h}return[t,r]}var _k=RegExp(`^(${MO})([.)])\\s+(.+)$`);function vk(e){let t=e.split(`
|
||||
`).filter(e=>e.trim().length>0);if(t.length===0)return null;let n=[];for(let e of t){let t=e.trim().match(_k);if(!t)return null;n.push({marker:t[1],content:t[3]})}return HO(n.map(e=>e.marker))?{type:`orderedList`,attrs:WO(n[0].marker),content:n.map(e=>({type:`listItem`,content:[{type:`paragraph`,content:[{type:`text`,text:e.content}]}]}))}:null}function yk(e,t,n){let r=[],i=0;for(;i<e.length;){let a=e[i];if(a.indent===t){let{paragraphLines:o,blockLines:s}=hk(a.contentLines),c=o.join(`
|
||||
`)}),r=h,n=h}return[t,r]}var bk=RegExp(`^(${FO})([.)])\\s+(.+)$`);function xk(e){let t=e.split(`
|
||||
`).filter(e=>e.trim().length>0);if(t.length===0)return null;let n=[];for(let e of t){let t=e.trim().match(bk);if(!t)return null;n.push({marker:t[1],content:t[3]})}return GO(n.map(e=>e.marker))?{type:`orderedList`,attrs:qO(n[0].marker),content:n.map(e=>({type:`listItem`,content:[{type:`paragraph`,content:[{type:`text`,text:e.content}]}]}))}:null}function Sk(e,t,n){let r=[],i=0;for(;i<e.length;){let a=e[i];if(a.indent===t){let{paragraphLines:o,blockLines:s}=vk(a.contentLines),c=o.join(`
|
||||
`).trim(),l=[];c&&l.push({type:`paragraph`,raw:c,tokens:n.inlineTokens(c)});let u=s.join(`
|
||||
`).trim();if(u){let e=n.blockTokens(u);l.push(...e)}let d=i+1,f=[];for(;d<e.length&&e[d].indent>t;)f.push(e[d]),d+=1;if(f.length>0){let e=yk(f,Math.min(...f.map(e=>e.indent)),n);l.push({type:`list`,ordered:!0,start:f[0].number,typeMarker:f[0].type,items:e,raw:f.map(e=>e.raw).join(`
|
||||
`)})}r.push({type:`list_item`,raw:a.raw,tokens:l}),i=d}else i+=1}return r}function bk(e,t){return e.map(e=>{if(e.type!==`list_item`)return t.parseChildren([e])[0];let n=[];return e.tokens&&e.tokens.length>0&&e.tokens.forEach(e=>{if(e.type===`paragraph`||e.type===`list`||e.type===`blockquote`||e.type===`code`)n.push(...t.parseChildren([e]));else if(e.type===`text`&&e.tokens){let r=t.parseChildren([e]);n.push({type:`paragraph`,content:r})}else{let r=t.parseChildren([e]);r.length>0&&n.push(...r)}}),{type:`listItem`,content:n}})}var xk=64;function Sk(e,t){let n=[],r=0;for(;n.length<t;){let t=e.indexOf(`
|
||||
`,r);if(t===-1)return n.push(e.slice(r)),n;n.push(e.slice(r,t)),r=t+1}return n}function Ck(e){let t=e.indexOf(`
|
||||
`),n=t===-1?e:e.slice(0,t);if(!lk.test(n))return[[],0,[]];let r=xk,i=Sk(e,r),a=gk(i);for(;a[1]===i.length&&i.length===r;)r*=2,i=Sk(e,r),a=gk(i);return[a[0],a[1],i]}var wk=`listItem`,Tk=`textStyle`,Ek=/^(\d+)\.\s$/;function Dk(e){let t=e.match(/list-style-type\s*:\s*([^;]+)/i);if(!t)return null;switch(t[1].trim().toLowerCase()){case`upper-roman`:return`I`;case`lower-roman`:return`i`;case`upper-alpha`:case`upper-latin`:return`A`;case`lower-alpha`:case`lower-latin`:return`a`;default:return null}}var Ok=Jp.create({name:`orderedList`,addOptions(){return{itemTypeName:`listItem`,HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:`block list`,content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute(`start`)?parseInt(e.getAttribute(`start`)||``,10):1},type:{default:null,parseHTML:e=>{let t=e.getAttribute(`type`);if(t)return t;let n=e.getAttribute(`style`);if(n){let e=Dk(n);if(e)return e}let r=e.querySelector(`li`);if(r){let e=r.getAttribute(`style`);if(e){let t=Dk(e);if(t)return t}}return null}}}},parseHTML(){return[{tag:`ol`}]},renderHTML({HTMLAttributes:e}){let{start:t,type:n,...r}=e,i=A(this.options.HTMLAttributes,r);return t!==1&&(i.start=t),n&&n!==`1`&&(i.type=n),[`ol`,i,0]},markdownTokenName:`list`,parseMarkdown:(e,t)=>{if(e.type!==`list`||!e.ordered)return[];let n=e.start||1,r=e.typeMarker,i=e.items?bk(e.items,t):[],a={};return n!==1&&(a.start=n),r&&(a.type=r),Object.keys(a).length>0?{type:`orderedList`,attrs:a,content:i}:{type:`orderedList`,content:i}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
|
||||
`):``,markdownTokenizer:{name:`orderedList`,level:`block`,start:()=>-1,tokenize:(e,t,n)=>{let[r,i,a]=Ck(e);if(r.length===0)return;let o=yk(r,r[0].indent,n);if(o.length!==0)return{type:`list`,ordered:!0,start:r[0]?.number||1,typeMarker:r[0]?.type,items:o,raw:a.slice(0,i).join(`
|
||||
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(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=` `,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
|
||||
`).trim();if(u){let e=n.blockTokens(u);l.push(...e)}let d=i+1,f=[];for(;d<e.length&&e[d].indent>t;)f.push(e[d]),d+=1;if(f.length>0){let e=Sk(f,Math.min(...f.map(e=>e.indent)),n);l.push({type:`list`,ordered:!0,start:f[0].number,typeMarker:f[0].type,items:e,raw:f.map(e=>e.raw).join(`
|
||||
`)})}r.push({type:`list_item`,raw:a.raw,tokens:l}),i=d}else i+=1}return r}function Ck(e,t){return e.map(e=>{if(e.type!==`list_item`)return t.parseChildren([e])[0];let n=[];return e.tokens&&e.tokens.length>0&&e.tokens.forEach(e=>{if(e.type===`paragraph`||e.type===`list`||e.type===`blockquote`||e.type===`code`)n.push(...t.parseChildren([e]));else if(e.type===`text`&&e.tokens){let r=t.parseChildren([e]);n.push({type:`paragraph`,content:r})}else{let r=t.parseChildren([e]);r.length>0&&n.push(...r)}}),{type:`listItem`,content:n}})}var wk=64;function Tk(e,t){let n=[],r=0;for(;n.length<t;){let t=e.indexOf(`
|
||||
`,r);if(t===-1)return n.push(e.slice(r)),n;n.push(e.slice(r,t)),r=t+1}return n}function Ek(e){let t=e.indexOf(`
|
||||
`),n=t===-1?e:e.slice(0,t);if(!fk.test(n))return[[],0,[]];let r=wk,i=Tk(e,r),a=yk(i);for(;a[1]===i.length&&i.length===r;)r*=2,i=Tk(e,r),a=yk(i);return[a[0],a[1],i]}var Dk=`listItem`,Ok=`textStyle`,kk=/^(\d+)\.\s$/;function Ak(e){let t=e.match(/list-style-type\s*:\s*([^;]+)/i);if(!t)return null;switch(t[1].trim().toLowerCase()){case`upper-roman`:return`I`;case`lower-roman`:return`i`;case`upper-alpha`:case`upper-latin`:return`A`;case`lower-alpha`:case`lower-latin`:return`a`;default:return null}}var jk=Jp.create({name:`orderedList`,addOptions(){return{itemTypeName:`listItem`,HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:`block list`,content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:e=>e.hasAttribute(`start`)?parseInt(e.getAttribute(`start`)||``,10):1},type:{default:null,parseHTML:e=>{let t=e.getAttribute(`type`);if(t)return t;let n=e.getAttribute(`style`);if(n){let e=Ak(n);if(e)return e}let r=e.querySelector(`li`);if(r){let e=r.getAttribute(`style`);if(e){let t=Ak(e);if(t)return t}}return null}}}},parseHTML(){return[{tag:`ol`}]},renderHTML({HTMLAttributes:e}){let{start:t,type:n,...r}=e,i=A(this.options.HTMLAttributes,r);return t!==1&&(i.start=t),n&&n!==`1`&&(i.type=n),[`ol`,i,0]},markdownTokenName:`list`,parseMarkdown:(e,t)=>{if(e.type!==`list`||!e.ordered)return[];let n=e.start||1,r=e.typeMarker,i=e.items?Ck(e.items,t):[],a={};return n!==1&&(a.start=n),r&&(a.type=r),Object.keys(a).length>0?{type:`orderedList`,attrs:a,content:i}:{type:`orderedList`,content:i}},renderMarkdown:(e,t)=>e.content?t.renderChildren(e.content,`
|
||||
`):``,markdownTokenizer:{name:`orderedList`,level:`block`,start:()=>-1,tokenize:(e,t,n)=>{let[r,i,a]=Ek(e);if(r.length===0)return;let o=Sk(r,r[0].indent,n);if(o.length!==0)return{type:`list`,ordered:!0,start:r[0]?.number||1,typeMarker:r[0]?.type,items:o,raw:a.slice(0,i).join(`
|
||||
`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:e,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(Dk,this.editor.getAttributes(Ok)).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=xk(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:kk,type:this.type,getAttributes:e=>({start:+e[1]}),joinPredicate:e});return(this.options.keepMarks||this.options.keepAttributes)&&(t=Gp({find:kk,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(Ok)}),joinPredicate:e,editor:this.editor})),[t]}}),Mk=/^\s*(\[([( |x])?\])\s$/,Nk=`position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0`,Pk=(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`}`},Fk=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?[MO(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=Nk;let l=e=>{let t=Pk(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:Mk,type:this.type,getAttributes:e=>({checked:e[e.length-1]===`x`})})]}}),Ik=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(OO.configure(this.options.bulletList)),this.options.listItem!==!1&&e.push(nk.configure(this.options.listItem)),this.options.listKeymap!==!1&&e.push(dk.configure(this.options.listKeymap)),this.options.orderedList!==!1&&e.push(jk.configure(this.options.orderedList)),this.options.taskItem!==!1&&e.push(Fk.configure(this.options.taskItem)),this.options.taskList!==!1&&e.push(Ik.configure(this.options.taskList)),e}});var Lk=` `,Rk=`\xA0`,zk=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===Lk||n[0].text===Lk||n[0].raw===Rk||n[0].text===Rk)&&r.length===1&&r[0].type===`text`&&(r[0].text===Lk||r[0].text===Rk)?t.createNode(`paragraph`,void 0,[]):t.createNode(`paragraph`,void 0,r)},renderMarkdown:(e,t,n)=>{if(!e)return``;let r=Array.isArray(e.content)?e.content:[];if(r.length===0){var i,a;let e=Array.isArray(n==null||(i=n.previousNode)==null?void 0:i.content)?n.previousNode.content:[];return(n==null||(a=n.previousNode)==null?void 0:a.type)===`paragraph`&&e.length===0?Lk:``}return t.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:e})=>e.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Bk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Vk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Hk=_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:Bk,type:this.type})]},addPasteRules(){return[Yp({find:Vk,type:this.type})]}}),Uk=Jp.create({name:`text`,group:`inline`,parseMarkdown:e=>({type:`text`,text:e.text||``}),renderMarkdown:e=>e.text||``}),Wk=_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: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(`
|
||||
`))};return s(n),{dom:r,contentDOM:a,update:e=>e.type===n.type&&(s(e),!0),ignoreMutation:e=>i.contains(e.target)}}}}),Pj=(e,t)=>e===`application/pdf`||typeof t==`string`&&/\.pdf$/i.test(t);function Fj(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 Ij={page:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`,`M9 12h6`,`M9 16h6`],"chevron-right":[`M10 6l6 6-6 6`],"chevron-left":[`M14 6l-6 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 4L8Line truncated
|
||||
`).map(e=>!e.includes(`|`)||!e.includes("`")?e:lP(e)).join(`
|
||||
`)}function dP(e){return(e||``).replaceAll(``,` `).replace(/\s+/g,` `).trim()}function fP(e,t){return t?e.split(t).join(`
|
||||
`):e}function pP(e){return e.replace(/\\.|\|/g,e=>e===`|`?`\\|`:e)}function mP(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=>fP(t.renderChildren(e),n.cellLineSeparator)).join(`
|
||||
`):fP(e.content?t.renderChildren(e.content):``,n.cellLineSeparator);let a=pP(dP(r.replace(/[ \t]*\r?\n[ \t]*/g,`<br>`))),o=e.type===`tableHeader`,s=HN(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 hP=new D(`preserveCellSelectionOnContextMenu`);function gP(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 _P(e,t){let n=!1;return e.forEachCell((e,r)=>{t>=r&&t<r+e.nodeSize&&(n=!0)}),n}function vP(){return new E({key:hP,props:{handleDOMEvents:{mousedown(e,t){if(t.button!==2)return!1;let{selection:n}=e.state;if(!oP(n)||n.ranges.length<2)return!1;let r=gP(e,t);return r==null||!_P(n,r)?!1:(t.preventDefault(),!0)}}}})}var yP=Jp.create({name:`table`,addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:tP,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}=nP(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=BN(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=BN(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)=>mP(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=sP(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=uP(i);if(s===i)return;let c=n.blockTokens(s)[0];if(c?.type!==`table`||!c.raw)return;let l=c.raw.split(`
|
||||
`).length,u=e.split(`
|
||||
`).slice(0,l).join(`
|
||||
`);return{...c,raw:u}}},addCommands(){return{insertTable:({rows:e=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:i,editor:a})=>{let o=nP(a.schema,e,t,n);if(i){let e=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(w.near(r.doc.resolve(e)))}return!0},addColumnBefore:()=>({state:e,dispatch:t})=>jM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>MM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return PM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>LM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>RM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return BM(e,t&&(e=>{n&&aP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>$M(e,t),mergeCells:()=>({state:e,dispatch:t})=>UM(e,t),splitCell:()=>({state:e,dispatch:t})=>WM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>YM(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>YM(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>XM(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>UM(e,t)?!0:WM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>KM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>QM(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>QM(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&DM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=yM.create(t.doc,e.anchorCell,e.headCell);t.setSelection(n)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:iP,"Mod-Backspace":iP,Delete:iP,"Mod-Delete":iP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[SN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],IN({allowTableNodeSelection:this.options.allowTableNodeSelection}),hP()]},addNodeView(){let e=this.options.View;return e?({node:t,view:n,HTMLAttributes:r})=>{let i=A(this.options.HTMLAttributes,r);return new e(t,this.options.cellMinWidth,n,i)}:null},extendNodeSchema(e){return{tableRole:Nu(k(e,`tableRole`,{name:e.name,options:e.options,storage:e.storage}))}}}),_P=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(gP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(qN.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(JN.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(YN.configure(this.options.tableRow)),e}}),vP=Tp.create({name:`textAlign`,addOptions(){return{types:[],alignments:[`left`,`center`,`right`,`justify`],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:e=>{let t=e.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:e=>!Pf(e.textAlign)||!this.options.alignments.includes(e.textAlign)?{}:{style:`text-align: ${e.textAlign}`}}}}]},addCommands(){return{setTextAlign:e=>({commands:t})=>this.options.alignments.includes(e)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:e})).some(e=>e):!1,unsetTextAlign:()=>({commands:e})=>this.options.types.map(t=>e.resetAttributes(t,`textAlign`)).some(e=>e),toggleTextAlign:e=>({editor:t,commands:n})=>this.options.alignments.includes(e)?t.isActive({textAlign:e})?n.unsetTextAlign():n.setTextAlign(e):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign(`left`),"Mod-Shift-e":()=>this.editor.commands.setTextAlign(`center`),"Mod-Shift-r":()=>this.editor.commands.setTextAlign(`right`),"Mod-Shift-j":()=>this.editor.commands.setTextAlign(`justify`)}}});function yP(){return[Nk.configure({HTMLAttributes:{class:`dw-tasks`}}),Mk.configure({nested:!0})]}function bP(){return[_P.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var xP=vP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),SP=Tp.create({name:`headingShortcuts`,addKeyboardShortcuts(){let e={"Mod-Shift-0":()=>this.editor.commands.setParagraph()};for(let t of[1,2,3,4,5,6])e[`Mod-Shift-${t}`]=()=>this.editor.commands.toggleHeading({level:t});return e}}),CP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,wP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,TP=_p.create({name:`highlight`,addOptions(){return{multicolor:!1,HTMLAttributes:{}}},addAttributes(){return this.options.multicolor?{color:{default:null,parseHTML:e=>e.getAttribute(`data-color`)||Af(e,`background-color`)||e.style.backgroundColor,renderHTML:e=>Pf(e.color)?{"data-color":e.color,style:`background-color: ${e.color}; color: inherit`}:{}}}:{}},parseHTML(){return[{tag:`mark`}]},renderHTML({HTMLAttributes:e}){retuLine truncated
|
||||
`);return/\s/.test(n)}):!1}function $P(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 eF(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:$P(e)}function tF({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&&!QP(r)}function nF({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function rF({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 iF({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 aF({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 oF({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 sF(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 cF({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&&sF(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 lF({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,_=aF({editor:e,items:n}),v=oF({placLine 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(),MF===d&&(MF=null),n||e.onCancel?.())}let d=()=>u();return MF=d,n.focus(),e.multiline||n.select(),d}var PF=[{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 FF(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of PF){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function IF(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var LF=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function RF(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;NF({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(IF(t)),onCancel:()=>e(``)})})}async function zF(e,t,n,r){let i=await RF(e,t,t.blocks.embedUrl);i&&(FF(i)?e.chain().focus().insertEmbed(i).run():await VF(e,i,n,r))}async function BF(e,t,n,r){let i=await RF(e,t,t.blocks.linkUrl);i&&await VF(e,i,n,r)}async function VF(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 HF=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=IF(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=IF(e),i=FF(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}: ${LF(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=aP(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})=>PM(e,t),addColumnAfter:()=>({state:e,dispatch:t})=>FM(e,t),deleteColumn:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return LM(e,t&&(e=>{n&&cP(e,n.pos),t(e)}))},addRowBefore:()=>({state:e,dispatch:t})=>BM(e,t),addRowAfter:()=>({state:e,dispatch:t})=>VM(e,t),deleteRow:()=>({state:e,dispatch:t})=>{let n=vu(e.selection.$from,e=>e.type.name===`table`);return UM(e,t&&(e=>{n&&cP(e,n.pos),t(e)}))},deleteTable:()=>({state:e,dispatch:t})=>nN(e,t),mergeCells:()=>({state:e,dispatch:t})=>KM(e,t),splitCell:()=>({state:e,dispatch:t})=>qM(e,t),toggleHeaderColumn:()=>({state:e,dispatch:t})=>QM(`column`)(e,t),toggleHeaderRow:()=>({state:e,dispatch:t})=>QM(`row`)(e,t),toggleHeaderCell:()=>({state:e,dispatch:t})=>$M(e,t),mergeOrSplit:()=>({state:e,dispatch:t})=>KM(e,t)?!0:qM(e,t),setCellAttribute:(e,t)=>({state:n,dispatch:r})=>YM(e,t)(n,r),goToNextCell:()=>({state:e,dispatch:t})=>tN(1)(e,t),goToPreviousCell:()=>({state:e,dispatch:t})=>tN(-1)(e,t),fixTables:()=>({state:e,dispatch:t})=>(t&&AM(e),!0),setCellSelection:e=>({tr:t,dispatch:n})=>{if(n){let n=SM.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:sP,"Mod-Backspace":sP,Delete:sP,"Mod-Delete":sP}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[TN({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],zN({allowTableNodeSelection:this.options.allowTableNodeSelection}),vP()]},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}))}}}),bP=Tp.create({name:`tableKit`,addExtensions(){let e=[];return this.options.table!==!1&&e.push(yP.configure(this.options.table)),this.options.tableCell!==!1&&e.push(XN.configure(this.options.tableCell)),this.options.tableHeader!==!1&&e.push(ZN.configure(this.options.tableHeader)),this.options.tableRow!==!1&&e.push(QN.configure(this.options.tableRow)),e}}),xP=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 SP(){return[Ik.configure({HTMLAttributes:{class:`dw-tasks`}}),Fk.configure({nested:!0})]}function CP(){return[bP.configure({table:{resizable:!0,cellMinWidth:60,HTMLAttributes:{class:`dw-table`}}})]}var wP=xP.configure({types:[`heading`,`paragraph`],alignments:[`left`,`center`,`right`]}),TP=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}}),EP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))$/,DP=/(?:^|\s)(==(?!\s+==)((?:[^=]+))==(?!\s+==))/g,OP=_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
|
||||
`||e===`\r`?(r.push(i),n.push(r),r=[],i=``,e===`\r`&&s[o+1]===`
|
||||
`&&o++):i+=e,o++}return(i!==``||r.length)&&(r.push(i),n.push(r)),n}function aI(e,t){return e.includes(t)||/["\r\n]/.test(e)||/^\s|\s$/.test(e)?`"${e.replace(/"/g,`""`)}"`:e}function oI(e,t=`,`){return e.map(e=>e.map(e=>aI(e,t)).join(t)).join(`\r
|
||||
`)}function sI(e,t,n){return oI([t.map(e=>e.name),...n.map(e=>t.map(t=>hF(e,t)))])}function cI(e){let t=e.map(e=>e.trim()).filter(Boolean);if(!t.length)return`text`;if(t.every(e=>pF(e)!==null))return`number`;if(t.every(e=>/^\d{4}-\d{2}-\d{2}/.test(e)))return`date`;if(t.every(e=>/^(true|false|yes|no)$/i.test(e)))return`checkbox`;if(t.every(e=>/^https?:\/\/\S+$/.test(e)))return`link`;let n=new Set(t.map(e=>e.toLowerCase()));return t.length>=4&&n.size<=Math.max(2,t.length/3)&&t.every(e=>e.length<=40)?`select`:`text`}function lI(e,t,n){let r=e.trim();if(!r)return null;let i=e=>{let t=n.find(t=>t.name.toLowerCase()===e.toLowerCase());return t||(t={id:tF(),name:e,color:EF(n)},n.push(t)),t.id};switch(t.type){case`number`:return pF(r);case`progress`:{let e=pF(r.replace(`%`,``));return e===null?null:Math.max(0,Math.min(100,Math.round(e)))}case`checkbox`:return/^(true|yes|1|x|✓|done)$/i.test(r);case`date`:return dF(r)||null;case`select`:return i(r);case`multiSelect`:return[...new Set(r.split(/[,;]/).map(e=>e.trim()).filter(Boolean).map(i))];case`member`:case`attachment`:case`createdBy`:case`createdTime`:return null;default:return r}}function uI(e,t=`,`){let n=iI(e,t).filter(e=>e.some(e=>e.trim())),r=n[0]??[],i=n.slice(1),a=r.map((e,t)=>({id:tF(),name:e.trim()||`${t+1}`,type:t===0?`title`:cI(i.map(e=>e[t]??``))}));for(let e of a)e.type===`select`&&(e.options=[]);return{columns:a,rows:i.map(e=>{let t={};return a.forEach((n,r)=>{let i=lI(e[r]??``,n,n.options??[]);i!==null&&(!Array.isArray(i)||i.length)&&(t[n.id]=i)}),t})}}function dI(e,t){let n=[];return{index:e.map(e=>{let r=t.find(t=>t.name.trim().toLowerCase()===e.trim().toLowerCase());return!r&&e.trim()&&n.push(e.trim()),r??null}),missing:n}}function fI(e,t,n,r){let i=I(`select`,{class:`dw-db-select`,"aria-label":n});for(let n of t){let t=I(`option`,{value:n.value},n.label);n.value===e&&(t.selected=!0),i.append(t)}return i.addEventListener(`change`,()=>r(i.value)),i.addEventListener(`keydown`,e=>e.stopPropagation()),i}var pI=e=>e.map(e=>({value:e.id,label:e.name||`…`}));function mI(e,t,n,r){let i=e.labels;if(!_F(n.op))return null;if(t.type===`select`||t.type===`multiSelect`)return fI(typeof n.value==`string`?n.value:``,[{value:``,label:`—`},...(t.options??[]).map(e=>({value:e.id,label:e.name}))],i.value,r);let a=t.type===`date`||t.type===`createdTime`?`date`:t.type===`number`||t.type===`progress`?`number`:`text`,o=I(`input`,{class:`dw-db-input dw-db-input--small`,type:a,"aria-label":i.value,placeholder:i.value});return o.value=n.value===void 0||n.value===null?``:String(n.value),o.addEventListener(`keydown`,e=>e.stopPropagation()),o.addEventListener(`change`,()=>r(a===`number`?o.value===``?null:Number(o.value):o.value)),o}function hI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.filters),s=()=>r?.updateView(n.id,{filters:o}),c=()=>{t.replaceChildren(),o.length>1&&t.append(fI(n.filterMode,[{value:`and`,label:i.matchAll},{value:`or`,label:i.matchAny}],i.filter,e=>{n.filterMode=e,r?.updateView(n.id,{filterMode:n.filterMode})})),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noFilters)),o.forEach((n,r)=>{let l=a.find(e=>e.id===n.column);if(!l)return;let u=gF(l.type),d=I(`div`,{class:`dw-db-pop__line`},fI(n.column,pI(a),i.filter,e=>{let t=a.find(t=>t.id===e);o[r]={column:e,op:gF(t.type)[0]},s(),c()}),fI(n.op,u.map(e=>({value:e,label:BP(i,e)})),i.filter,e=>{o[r]={...n,op:e},_F(e)||delete o[r].value,s(),c()}),mI(e,l,n,e=>{o[r]={...o[r],value:e},s()}),bI(i.remove,()=>{o.splice(r,1),s(),c()}));t.append(d)}),r&&t.append(xI(i.addFilter,()=>{let e=a.find(e=>e.type!==`title`)??a[0];o.push({column:e.id,op:gF(e.type)[0]}),s(),c()}))};c()}function gI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns,o=structuredClone(n.sorts),s=()=>r?.updateView(n.id,{sorts:o}),c=()=>{t.replaceChildren(),o.length||t.append(I(`p`,{class:`dw-db-pop__empty`},i.noSorts)),o.forEach((e,n)=>{t.append(I(`div`,{class:`dw-db-pop__line`},fI(e.column,pI(a),i.sort,t=>{o[n]={...e,column:t},s()}),fI(e.desc?`desc`:`asc`,[{value:`asc`,label:i.ascending},{value:`desc`,label:i.descending}],i.sort,t=>{o[n]={...e,desc:t===`desc`},s()}),bI(i.remove,()=>{o.splice(n,1),s(),c()})))}),r&&t.append(xI(i.addSort,()=>{let e=new Set(o.map(e=>e.column)),t=a.find(t=>!e.has(t.id))??a[0];o.push({column:t.id,desc:!1}),s(),c()}))};c()}function _I(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>rF.includes(e.type)),o=a.map(e=>({value:e.id,label:e.name||RP(i,e.type)}));n.type!==`kanban`&&o.unshift({value:``,label:i.noGrouping}),t.append(I(`label`,{class:`dw-db-pop__label`},i.groupBy),a.length||n.type!==`kanban`?fI(n.groupBy??``,o,i.groupBy,e=>r?.updateView(n.id,{groupBy:e||null})):I(`p`,{class:`dw-db-pop__empty`},i.noGroupColumn))}function vI(e,t,n){let r=e.store,i=e.labels,a=e.db.columns.filter(e=>e.type===`date`||e.type===`createdTime`);t.append(I(`label`,{class:`dw-db-pop__label`},i.dateColumn),a.length?fI(n.dateColumn??``,[{value:``,label:`—`},...a.map(e=>({value:e.id,label:e.name||RP(i,e.tyLine truncated
|
||||
`)},onCreate(){let{doc:e,readOnlyDoc:t,undoScope:n}=this.options;e&&!t&&n&&(NS.getState(this.editor.state)?.undoManager)?.addToScope(HF(e))},addCommands(){let e=e=>{let t=tF(),{doc:n,readOnlyDoc:r}=this.options;return!n||r?{id:t,data:e}:(rI(n,t,e,(e,t)=>MI(this.editor,e,t)),{id:t,data:null})};return{insertDatabase:t=>({commands:n})=>n.insertContent([{type:this.name,attrs:e(t??QF(DI(this.options.labels)))},{type:`paragraph`}]),groupAsDatabase:()=>({state:t,dispatch:n,commands:r})=>{let i=FI(t.selection.$from,t.selection.$to);if(!i)return!1;if(!n)return!0;let a=EI(this.options.labels),o={id:tF(),name:a.typeTitle,type:`title`},s=[o],c=i.checks?{id:tF(),name:a.done,type:`checkbox`}:null;c&&s.push(c);let l=Date.now(),u={title:``,columns:s,rows:i.items.map((e,t)=>({id:tF(),cells:{[o.id]:e.text,...c&&e.checked?{[c.id]:!0}:{}},createdAt:l+t,createdBy:this.options.me?.()??null,body:e.rest.length?e.rest:void 0})),views:[nF(`table`,a.viewTable,s)]},d=this.type.create(e(u));return r.command(({tr:e})=>(e.replaceWith(i.from,i.to,d),e.setSelection(T.create(e.doc,i.from)),!0))}}},addKeyboardShortcuts(){return{"Mod-g":()=>this.editor.commands.groupAsDatabase()}},addProseMirrorPlugins(){let{doc:e,readOnlyDoc:t}=this.options,n=e&&!t?e:null,r=this.editor;return[new E({key:new D(`databaseClipboard`),props:{transformCopied:t=>!e||!AI(t.content)?t:new p(kI(t.content,t=>{let n=HF(e).get(String(t.attrs.id));return n instanceof Lb?t.type.create({...t.attrs,data:nI(n,OI)}):t}),t.openStart,t.openEnd),transformPasted:e=>AI(e.content)?new p(kI(e.content,e=>{let t=tF();if(!n)return e.type.create({...e.attrs,id:t});let i=e.attrs.data?iF(e.attrs.data):null,a=HF(n).get(String(e.attrs.id)),o=i??(a instanceof Lb?nI(a,OI):QF(DI(this.options.labels)));return rI(n,t,PI(o),(e,t)=>MI(r,e,t)),e.type.create({id:t,data:null})}),e.openStart,e.openEnd):e},appendTransaction:(e,t,i)=>{if(!n||!e.some(e=>e.docChanged&&!e.getMeta(MS))||!e.some(e=>e.steps.some(e=>AI(e.slice?.content??s.empty))))return null;let a=new Set,o=[];if(i.doc.descendants((e,t)=>{if(e.type.name!==`database`)return;let n=String(e.attrs.id);return n&&a.has(n)&&o.push({pos:t,node:e}),a.add(n),!1}),!o.length)return null;let c=i.tr;for(let{pos:e,node:t}of o){let i=HF(n).get(String(t.attrs.id)),a=tF();i instanceof Lb&&rI(n,a,PI(nI(i,OI)),(e,t)=>MI(r,e,t)),c.setNodeMarkup(e,void 0,{...t.attrs,id:a,data:null})}return c}})]},addNodeView(){let e=this.options;return({node:t,editor:n,getPos:r})=>{let i=t,a=e.labels??UP,o=e.doc,s=()=>n.isEditable&&!!o&&!e.readOnlyDoc,c=null,l=null,u=null,d=null,f=I(`div`,{class:`dw-db-node`}),p=()=>String(i.attrs.id),m=()=>{let e=o?HF(o).get(p()):void 0;return e instanceof Lb?e:null},h=()=>{let t=m();return t?ZF(t):i.attrs.data?iF(i.attrs.data):QF(DI(e.labels))},g=()=>({labels:a.database,colorNames:a.colors,locale:a.locale,files:e.files,people:e.people,store:c}),_=(t,n)=>{let r=e.rowExtensions;if(!r)return null;let i=m(),o=null;if(i&&(o=c?c.rowBody(n.id):NI(i,n.id),!o))return t.append(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),null;let s=new Vp({element:t,editable:!!c,extensions:r(o),content:o?void 0:{type:`doc`,content:n.body??[{type:`paragraph`}]},editorProps:{attributes:{class:`dw-prose dw-db-peek__prose`}}});return!o&&!n.body?.length&&t.replaceChildren(I(`p`,{class:`dw-db-peek__note`},a.database.bodyReadOnly)),()=>s.destroy()},v=(e,t)=>{u?.close(),u=new BF({ctx:{...g()},mountBody:_},h(),e,t,()=>u=null)},y=()=>{let e=h();d?.update(e,{store:c}),u?.update(e,{store:c})},b=()=>{if(l?.(),l=null,c=null,!o)return;let t=m();if(!t&&s()){let a=i.attrs.data?iF(i.attrs.data):QF(DI(e.labels)),s=p()?p():tF();rI(o,s,a,(e,t)=>MI(n,e,t)),queueMicrotask(()=>{let e=typeof r==`function`?r():void 0;e!==void 0&&n.state.doc.nodeAt(e)?.type.name===`database`&&n.view.dispatch(n.state.tr.setNodeMarkup(e,void 0,{...i.attrs,id:s,data:null}).setMeta(`addToHistory`,!1))}),t=HF(o).get(s)}if(t){s()&&(c=new eI(o,t,()=>e.me?.()??null));let n=t,r=()=>y();n.observeDeep(r),l=()=>n.unobserveDeep(r)}else{let e=HF(o),t=e=>{e.keysChanged.has(p())&&(b(),y())};e.observe(t),l=()=>e.unobserve(t)}};b(),d=new CI({...g(),openRow:v,undo:()=>n.commands.undo?.(),redo:()=>n.commands.redo?.(),notify:e.notify},h()),f.append(d.dom);let x=s(),S=()=>{s()!==x&&(x=s(),b(),y())};return n.on(`update`,S),n.on(`transaction`,S),{dom:f,update(e){if(e.type!==i.type)return!1;let t=e.attrs.id!==i.attrs.id;return i=e,t&&b(),y(),!0},ignoreMutation:()=>!0,stopEvent:e=>e.type!==`dragstart`||e.target!==f,destroy(){l?.(),u?.close(),d?.destroy(),n.off(`update`,S),n.off(`transaction`,S)}}}}});function MI(e,t,n){try{yw(e.schema,{type:`doc`,content:t},n)}catch{}}function NI(e,t){let n=e.get(`rows`);if(!(n instanceof Pb))return null;for(let e of n.toArray())if(e.get(`id`)===t){let t=e.get(`body`);return t instanceof ix&&t.length?t:null}return null}function PI(e){return{...e,rows:e.rows.map(e=>({...e,id:tF()}))}}function FI(e,t){for(let t=e.depth;t>0;t--){let n=e.node(t);if([`bulletList`,`orderedList`,`taskList`].includes(Line truncated
|
||||
`);return/\s/.test(n)}):!1}function nL(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 rL(e,t,n,r){return n?()=>{let n=r.getState(e.state)?.decorationId;return t.dom.querySelector(`[data-decoration-id="${n}"]`)?.getBoundingClientRect()||null}:nL(e)}function iL({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&&!tL(r)}function aL({view:e,pluginKeyRef:t}){let n=e.state.tr.setMeta(t,{exit:!0});e.dispatch(n)}function oL({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 sL({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 cL({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 lL({placement:e,offset:t,flip:n,floatingUi:r}){var i;let a=[Oj({mainAxis:t.mainAxis??4,crossAxis:t.crossAxis??0})];return n&&a.push(Aj()),r!=null&&(i=r.middleware)!=null&&i.length&&a.push(...r.middleware),{placement:e,strategy:r?.strategy??`absolute`,middleware:a}}function uL(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 dL({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&&uL(r).appendChild(o),s.onPosition||(o.style.visibility=`hidden`,o.style.width=`max-content`);let d=Dj(c,o,()=>{jj(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 fL({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,_=cL({editor:e,items:n}),v=lL({placLine 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=Dj(e.anchor,t,()=>{jj(e.anchor,t,{placement:`bottom-start`,middleware:[Oj(6),Aj(),kj({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(),FL===d&&(FL=null),n||e.onCancel?.())}let d=()=>u();return FL=d,n.focus(),e.multiline||n.select(),d}var LL=[{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 RL(e){let t;try{t=new URL(e.trim())}catch{return null}for(let e of LL){let n=e.pattern.exec(t.href);if(n)return{src:e.src(n,t),ratio:e.ratio??`video`}}return null}function zL(e){try{let t=new URL(e.trim());return t.protocol===`https:`||t.protocol===`http:`?t.href:``}catch{return``}}var BL=e=>{try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}};function VL(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;IL({anchor:i,value:`https://`,label:n,labels:{done:r.done,cancel:r.cancel,remove:r.remove},onSave:t=>e(zL(t)),onCancel:()=>e(``)})})}async function HL(e,t,n,r){let i=await VL(e,t,t.blocks.embedUrl);i&&(RL(i)?e.chain().focus().insertEmbed(i).run():await WL(e,i,n,r))}async function UL(e,t,n,r){let i=await VL(e,t,t.blocks.linkUrl);i&&await WL(e,i,n,r)}async function WL(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 GL=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=zL(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=zL(e),i=RL(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}: ${BL(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
|
||||
@@ -171,7 +175,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`},HI=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`},WR=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+`
|
||||
@@ -181,7 +185,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`},UI=function(e,t){return`M983 `+(10+e+t)+`
|
||||
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},GR=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
|
||||
@@ -190,7 +194,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`},WI=function(e,t){return`M424,`+(2398+e+t)+`
|
||||
M`+(1001+e)+` `+t+`h400000v`+(40+e)+`h-400000z`},KR=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
|
||||
@@ -200,18 +204,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`},GI=function(e,t){return`M473,`+(2713+e+t)+`
|
||||
h400000v`+(40+e)+`h-400000z`},qR=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`},KI=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},qI=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`},JR=function(e){var t=e/2;return`M400000 `+e+` H0 L`+t+` 0 l65 45 L145 `+(e-80)+` H400000z`},YR=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`},JI=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=VI(t,BI);break;case`sqrtSize1`:r=HI(t,BI);break;case`sqrtSize2`:r=UI(t,BI);break;case`sqrtSize3`:r=WI(t,BI);break;case`sqrtSize4`:r=GI(t,BI);break;case`sqrtTall`:r=qI(t,BI,n)}return r},YI=function(e,t){switch(e){case`⎜`:return zI(`M291 0 H417 V`+t+` H291z`);case`∣`:return zI(`M145 0 H188 V`+t+` H145z`);case`∥`:return zI(`M145 0 H188 V`+t+` H145z`)+zI(`M367 0 H410 V`+t+` H367z`);case`⎟`:return zI(`M457 0 H583 V`+t+` H457z`);case`⎢`:return zI(`M319 0 H403 V`+t+` H319z`);case`⎥`:return zI(`M263 0 H347 V`+t+` H263z`);case`⎪`:return zI(`M384 0 H504 V`+t+` H384z`);case`⏐`:return zI(`M312 0 H355 V`+t+` H312z`);case`‖`:return zI(`M257 0 H300 V`+t+` H257z`)+zI(`M478 0 H521 V`+t+` H478z`);default:return``}},XI={doubleleftarrow:`M262 157
|
||||
219 661 l218 661zM702 `+t+`H400000v`+(40+e)+`H742z`},XR=function(e,t,n){t=1e3*t;var r=``;switch(e){case`sqrtMain`:r=UR(t,HR);break;case`sqrtSize1`:r=WR(t,HR);break;case`sqrtSize2`:r=GR(t,HR);break;case`sqrtSize3`:r=KR(t,HR);break;case`sqrtSize4`:r=qR(t,HR);break;case`sqrtTall`:r=YR(t,HR,n)}return r},ZR=function(e,t){switch(e){case`⎜`:return VR(`M291 0 H417 V`+t+` H291z`);case`∣`:return VR(`M145 0 H188 V`+t+` H145z`);case`∥`:return VR(`M145 0 H188 V`+t+` H145z`)+VR(`M367 0 H410 V`+t+` H367z`);case`⎟`:return VR(`M457 0 H583 V`+t+` H457z`);case`⎢`:return VR(`M319 0 H403 V`+t+` H319z`);case`⎥`:return VR(`M263 0 H347 V`+t+` H263z`);case`⎪`:return VR(`M384 0 H504 V`+t+` H384z`);case`⏐`:return VR(`M312 0 H355 V`+t+` H312z`);case`‖`:return VR(`M257 0 H300 V`+t+` H257z`)+VR(`M478 0 H521 V`+t+` H478z`);default:return``}},QR={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
|
||||
@@ -257,10 +261,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:zI(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:zI(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:zI(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:zI(`M40 281 V448H0V74H40V241H400000v40z`),leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23
|
||||
71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:VR(`M40 281 V428 H0 V94 H40 V241 H400000 v40z`),leftbracketunder:VR(`M0 0 h120 V290 H399995 v120 H0z`),leftbracketover:VR(`M0 440 h120 V150 H399995 v-120 H0z`),leftmapsto:VR(`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:zI(`M0 50 h400000 v40H0z m0 194h40000v40H0z`),midbrace:`M200428 334
|
||||
68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:VR(`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
|
||||
@@ -309,7 +313,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:zI(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:zI(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:zI(`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:VR(`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`),rightbracketunder:VR(`M399995 0 h-120 V290 H0 v120 H400000z`),rightbracketover:VR(`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
|
||||
@@ -382,7 +386,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`},ZI=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`},$R=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
|
||||
@@ -410,17 +414,17 @@ 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 QI(e){return`toText`in e}var $I=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(QI(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},eL={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},tL={ex:!0,em:!0,mu:!0},nL=function(e){return typeof e!=`string`&&(e=e.unit),e in eL||e in tL||e===`ex`},rL=function(e,t){var n;if(e.unit in eL)n=eL[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`},iL=function(e){return e.filter(e=>e).join(` `)},aL=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=oI(n)+`:`+r+`;`)}return t},oL=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)}},sL=function(e){var t=document.createElement(e);t.className=iL(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},cL=/[\s"'>/=\x00-\x1f]/,lL=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+lI(iL(this.classes))+`"`);var n=aL(this.style);n&&(t+=` style="`+lI(n)+`"`);for(var r of Object.keys(this.attributes)){if(cL.test(r))throw new I(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+lI(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},uL=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,oL.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return sL.call(this,`span`)}toMarkup(){return lL.call(this,`span`)}},dL=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,oL.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 sL.call(this,`a`)}toMarkup(){return lL.call(this,`a`)}},fL=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="`+lI(this.src)+`"`+(` alt="`+lI(this.alt)+`"`),t=aL(this.style);return t&&(e+=` style="`+lI(t)+`"`),e+=`'/>`,e}},pL={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},mL=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=II(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=pL[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=iL(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+=lI(iL(this.classes)Line truncated
|
||||
`+h+` children.`);for(var v=0;v<h;v++){var y=new hL([new gL(d[v])],{width:`400em`,height:R(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=SR([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},jz=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 _L({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new _L({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=SR([],[new hL(c,{width:`100%`,height:R(o)})],i)}return a.height=o,a.style.height=R(o),a},Mz=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],Nz=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],Pz=new Set(Mz),Fz=new Set(Nz);function Iz(e){return Pz.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 Lz(e){var t=Rz(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function Rz(e){return e.type===`atom`||Fz.has(e.type)?e:null}function zz(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 Bz=e=>{if(e instanceof mL)return e;if(bL(e)&&e.children.length===1)return Bz(e.children[0])},Vz=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=Q(e.base,`accent`),n=r.base,e.base=n,i=yL(tz(e,t)),e.base=r):(r=Q(e,`accent`),n=r.base);var a=tz(n,t.havingCrampedStyle()),o=r.isShifty&&fI(n),s=0;o&&(s=Bz(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=OR({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=NR(`vec`,t),f=MR.vec[1]):(d=vR({type:`textord`,mode:r.mode,text:r.label},t),d=vL(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=OR({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},Hz=(e,t)=>{var n=e.isStretchy?Dz(e.label):new Z(`mo`,[lz(e.label,e.mode)]),r=new Z(`mover`,[gz(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},Uz=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=UR(t[0]),r=!Uz.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:Vz,mathmlBuilder:Hz}),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=tz(e.base,t),r=Az(e,t),i=e.label===`\\utilde`?.12:0;return Y([`mord`,`accentunder`],[OR({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=Dz(e.label),r=new Z(`munder`,[gz(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var Wz=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
|
||||
]`,FV=`\\\\[a-zA-Z@]+`,IV=`\\\\[^\ud800-\udfff]`,LV=`(`+FV+`)`+PV+`*`,RV=`\\\\(
|
||||
-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 ez(e){return`toText`in e}var tz=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(ez(e))return e.toText();throw Error(`Expected MathDomNode with toText, got `+e.constructor.name)}).join(``)}},nz={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},rz={ex:!0,em:!0,mu:!0},iz=function(e){return typeof e!=`string`&&(e=e.unit),e in nz||e in rz||e===`ex`},az=function(e,t){var n;if(e.unit in nz)n=nz[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 L(`Invalid unit: '`+e.unit+`'`);r!==t&&(n*=r.sizeMultiplier/t.sizeMultiplier)}return Math.min(e.number*n,t.maxSize)},z=function(e){return+e.toFixed(4)+`em`},oz=function(e){return e.filter(e=>e).join(` `)},sz=function(e){var t=``;for(var n of Object.keys(e)){var r=e[n];r!==void 0&&(t+=cR(n)+`:`+r+`;`)}return t},cz=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)}},lz=function(e){var t=document.createElement(e);t.className=oz(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},uz=/[\s"'>/=\x00-\x1f]/,dz=function(e){var t=`<`+e;this.classes.length&&(t+=` class="`+dR(oz(this.classes))+`"`);var n=sz(this.style);n&&(t+=` style="`+dR(n)+`"`);for(var r of Object.keys(this.attributes)){if(uz.test(r))throw new L(`Invalid attribute name '`+r+`'`);t+=` `+r+`="`+dR(this.attributes[r])+`"`}t+=`>`;for(var i=0;i<this.children.length;i++)t+=this.children[i].toMarkup();return t+=`</`+e+`>`,t},fz=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,cz.call(this,e,n,r),this.children=t||[]}setAttribute(e,t){this.attributes[e]=t}hasClass(e){return this.classes.includes(e)}toNode(){return lz.call(this,`span`)}toMarkup(){return dz.call(this,`span`)}},pz=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,cz.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 lz.call(this,`a`)}toMarkup(){return dz.call(this,`a`)}},mz=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="`+dR(this.src)+`"`+(` alt="`+dR(this.alt)+`"`),t=sz(this.style);return t&&(e+=` style="`+dR(t)+`"`),e+=`'/>`,e}},hz={î:`ı̂`,ï:`ı̈`,í:`ı́`,ì:`ı̀`},gz=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=RR(this.text.charCodeAt(0));c&&this.classes.push(c+`_fallback`),/[îïíì]/.test(this.text)&&(this.text=hz[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=z(this.italic)),this.classes.length>0&&(t||=document.createElement(`span`),t.className=oz(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+=dR(oz(this.classes)Line truncated
|
||||
`+h+` children.`);for(var v=0;v<h;v++){var y=new _z([new vz(d[v])],{width:`400em`,height:z(m),viewBox:`0 0 `+n+` `+p,preserveAspectRatio:_[v]+` slice`}),b=wB([g[v]],[y],t);if(h===1)return{span:b,minWidth:f,height:m};b.style.height=z(m),l.push(b)}return{span:X([`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=z(o),a>0&&(i.style.minWidth=z(a)),i},NV=function(e,t,n,r,i){var a,o=e.height+e.depth+n+r;if(/fbox|color|angl/.test(t)){if(a=X([`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 yz({x1:`0`,y1:`0`,x2:`100%`,y2:`100%`,"stroke-width":`0.046em`})),/^x?cancel$/.test(t)&&c.push(new yz({x1:`0`,y1:`100%`,x2:`100%`,y2:`0`,"stroke-width":`0.046em`})),a=wB([],[new _z(c,{width:`100%`,height:z(o)})],i)}return a.height=o,a.style.height=z(o),a},PV=[`bin`,`close`,`inner`,`open`,`punct`,`rel`],FV=[`accent-token`,`mathord`,`op-token`,`spacing`,`textord`],IV=new Set(PV),LV=new Set(FV);function RV(e){return IV.has(e)}function zV(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 BV(e){var t=VV(e);if(!t)throw Error(`Expected node of symbol group type, but got `+(e?`node of type `+e.type:String(e)));return t}function VV(e){return e.type===`atom`||LV.has(e.type)?e:null}function HV(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 L(t,e);return r}var UV=e=>{if(e instanceof gz)return e;if(Sz(e)&&e.children.length===1)return UV(e.children[0])},WV=(e,t)=>{var n,r,i;e&&e.type===`supsub`?(r=zV(e.base,`accent`),n=r.base,e.base=n,i=xz(rV(e,t)),e.base=r):(r=zV(e,`accent`),n=r.base);var a=rV(n,t.havingCrampedStyle()),o=r.isShifty&&mR(n),s=0;o&&(s=UV(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=MV(r,t),u=AB({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`elem`,elem:u,wrapperClasses:[`svg-align`],wrapperStyle:s>0?{width:`calc(100% - `+z(2*s)+`)`,marginLeft:z(2*s)}:void 0}]});else{var d,f;r.label===`\\vec`?(d=FB(`vec`,t),f=PB.vec[1]):(d=bB({type:`textord`,mode:r.mode,text:r.label},t),d=bz(d),d.italic=0,f=d.width,c&&(l+=d.depth)),u=X([`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=z(m),r.label===`\\textcircled`&&(u.style.top=`.2em`),u=AB({positionType:`firstBaseline`,children:[{type:`elem`,elem:a},{type:`kern`,size:-l},{type:`elem`,elem:u}]})}var h=X([`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},GV=(e,t)=>{var n=e.isStretchy?kV(e.label):new Q(`mo`,[dV(e.label,e.mode)]),r=new Q(`mover`,[vV(e.base,t),n]);return r.setAttribute(`accent`,`true`),r},KV=new RegExp([`\\acute`,`\\grave`,`\\ddot`,`\\tilde`,`\\bar`,`\\breve`,`\\check`,`\\hat`,`\\vec`,`\\dot`,`\\mathring`].map(e=>`\\`+e).join(`|`));Z({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=GB(t[0]),r=!KV.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:WV,mathmlBuilder:GV}),Z({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}}}),Z({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=rV(e.base,t),r=MV(e,t),i=e.label===`\\utilde`?.12:0;return X([`mord`,`accentunder`],[AB({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=kV(e.label),r=new Q(`munder`,[vV(e.base,t),n]);return r.setAttribute(`accentunder`,`true`),r}});var qV=e=>{var t=new Q(`mpadded`,e?[e]:[]);return t.setAttribute(`width`,`+0.6em`),t.setAttribute(`lspace`,`0.3em`),t};Z({type:`xArrow`,names:[`\\xleftarrow`,`\\xrightarrow`,`\\xLeftarrow`,`\\xRightarrow`,`\\xleftrighLine truncated
|
||||
]`,RU=`\\\\[a-zA-Z@]+`,zU=`\\\\[^\ud800-\udfff]`,BU=`(`+RU+`)`+LU+`*`,VU=`\\\\(
|
||||
|[ \r ]+
|
||||
?)[ \r ]*`,zV=`[̀-ͯ]`,BV=RegExp(zV+`+$`),VV=`(`+PV+`+)|`+(RV+`|`)+`([!-\\[\\]-‧-豈-]`+(zV+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(zV+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+LV)+(`|`+IV+`)`),HV=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(VV,`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 HB(`EOF`,new VB(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new I(`Unexpected character: '`+e[t]+`'`,new HB(e[t],new VB(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 HB(r,new VB(this,t,this.tokenRegex.lastIndex))}},UV=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}},WV=BB;$(`\\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 GV={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=GV[t.text],r==null||r>=n)throw new I(`Invalid base-`+n+` digit `+t.text);for(var i;(i=GV[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var KV=(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=>KV(e,!1,!0,!1)),$(`\\renewcommand`,e=>KV(e,!0,!1,!1)),$(`\\providecommand`,e=>KV(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),NV[n],OL.math[n],OL.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(rH,t[0])&&!OL[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=rH[t[0]]+t.slice(1));var i=BV.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(OL[this.mode][t]){this.settings.strict&&this.mode===`math`&&XL.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=OL[this.mode][t].group,s=VB.range(e);a=Iz(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&&(RI(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:VB.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(!nH[l])throw new I(`Unknown accent ' `+l+`'`,e);var u=nH[l][this.mode]||nH[l].text;if(!u)throw new I(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:VB.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};iH.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var aH=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new iH(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 HB(`\\df@tag`)])}]}return r},oH=function(e,t,n){t.textContent=``;var r=uH(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.`),oH=function(){throw new I(`KaTeX doesn't work in quirks mode.`)});var sH=function(e,t){return uH(e,t).toMarkup()},cH=function(e,t){return aH(e,new vI(t))},lH=function(e,t,n){if(n.throwOnError||!(e instanceof I))throw e;var r=Y([`katex-error`],[new mL(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},uH=function(e,t){var n=new vI(t);try{return wz(aH(e,n),e,n)}catch(t){return lH(t,e,n)}},dH={version:`0.18.10`,render:oH,renderToString:sH,ParseError:I,SETTINGS_SCHEMA:mI,__parse:cH,__renderToDomTree:uH,__renderToHTMLTree:function(e,t){var n=new vI(t);try{return Tz(aH(e,n),e,n)}catch(t){return lH(t,e,n)}},__setFontMetrics:wL,__defineSymbol:z,__defineFunction:X,__defineMacro:$,__domTree:{Span:uL,Anchor:dL,SymbolNode:mL,SvgNode:hL,PathNode:gL,LineNode:_L}},fH=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{dH.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)}}}}}),pH=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},mH=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:pH,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{dH.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)}}}}}),hH=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[fH.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),mH.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function gH(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;NF({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 hH.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function _H({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new D,command:({editor:e,range:t,props:i})=>{var a,o;let s=Line truncated
|
||||
Idea --> Draft --> Review --> Published`,CH=null;function wH(e){return CH??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),CH}var TH=0;async function EH(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 wH(r)).render(`dw-mermaid-${++TH}`,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 DH=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=SH)=>({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 EH(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;NF({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void EH(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),EH(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void EH(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),EH(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function OH(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 kH(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().focus().deleteRange(r).run(),zF(t,e,a,n)}),o(`linkCard`,`link`,[`bookmark`,`preview`,`card`,`url`,`web`],(t,r)=>{t.chain().focus().deleteRange(r).rLine truncated
|
||||
?)[ \r ]*`,HU=`[̀-ͯ]`,UU=RegExp(HU+`+$`),WU=`(`+LU+`+)|`+(VU+`|`)+`([!-\\[\\]-‧-豈-]`+(HU+`*`)+`|[\ud800-\udbff][\udc00-\udfff]`+(HU+`*`)+`|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5`+(`|`+BU)+(`|`+zU+`)`),GU=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(WU,`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 GH(`EOF`,new WH(this,t,t));var n=this.tokenRegex.exec(e);if(n===null||n.index!==t)throw new L(`Unexpected character: '`+e[t]+`'`,new GH(e[t],new WH(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 GH(r,new WH(this,t,this.tokenRegex.lastIndex))}},KU=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 L(`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}},qU=UH;$(`\\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 JU={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 L("\\char` missing argument");else r=t.text.charCodeAt(0)}else n=10;if(n){if(r=JU[t.text],r==null||r>=n)throw new L(`Invalid base-`+n+` digit `+t.text);for(var i;(i=JU[e.future().text])!=null&&i<n;)r*=n,r+=i,e.popToken()}return`\\@char{`+r+`}`});var YU=(e,t,n,r)=>{var i=e.consumeArg().tokens;if(i.length!==1)throw new L(`\\newcommand's first argument must be a macro name`);var a=i[0].text,o=e.isDefined(a);if(o&&!t)throw new L(`\\newcommand{`+a+`} attempting to redefine `+(a+`; use \\renewcommand`));if(!o&&!n)throw new L(`\\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 L(`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=>YU(e,!1,!0,!1)),$(`\\renewcommand`,e=>YU(e,!0,!1,!1)),$(`\\providecommand`,e=>YU(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),IU[n],Az.math[n],Az.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(oW,t[0])&&!Az[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=oW[t[0]]+t.slice(1));var i=UU.exec(t);i&&(t=t.substring(0,i.index),t===`i`?t=`ı`:t===`j`&&(t=`ȷ`));var a;if(Az[this.mode][t]){this.settings.strict&&this.mode===`math`&&Qz.includes(t)&&this.settings.reportNonstrict(`unicodeTextInMathMode`,`Latin-1/Unicode text character "`+t[0]+`" used in math mode`,e);var o=Az[this.mode][t].group,s=WH.range(e);a=RV(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&&(BR(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:WH.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(!aW[l])throw new L(`Unknown accent ' `+l+`'`,e);var u=aW[l][this.mode]||aW[l].text;if(!u)throw new L(`Accent `+l+` unsupported in `+this.mode+` mode`,e);a={type:`accent`,mode:this.mode,loc:WH.range(e),label:u,isStretchy:!1,isShifty:!0,base:a}}return a}};sW.endOfExpression=new Set([`}`,`\\endgroup`,`\\end`,`\\right`,`&`]);var cW=function(e,t){if(!(typeof e==`string`||e instanceof String))throw TypeError(`KaTeX can only parse string typed expression`);var n=new sW(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 L(`\\tag works only in display equations`);r=[{type:`tag`,mode:`text`,body:r,tag:n.subparse([new GH(`\\df@tag`)])}]}return r},lW=function(e,t,n){t.textContent=``;var r=pW(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.`),lW=function(){throw new L(`KaTeX doesn't work in quirks mode.`)});var uW=function(e,t){return pW(e,t).toMarkup()},dW=function(e,t){return cW(e,new bR(t))},fW=function(e,t,n){if(n.throwOnError||!(e instanceof L))throw e;var r=X([`katex-error`],[new gz(t)]);return r.setAttribute(`title`,e.toString()),r.setAttribute(`style`,`color:`+n.errorColor),r},pW=function(e,t){var n=new bR(t);try{return EV(cW(e,n),e,n)}catch(t){return fW(t,e,n)}},mW={version:`0.18.10`,render:lW,renderToString:uW,ParseError:L,SETTINGS_SCHEMA:gR,__parse:dW,__renderToDomTree:pW,__renderToHTMLTree:function(e,t){var n=new bR(t);try{return DV(cW(e,n),e,n)}catch(t){return fW(t,e,n)}},__setFontMetrics:Ez,__defineSymbol:B,__defineFunction:Z,__defineMacro:$,__domTree:{Span:fz,Anchor:pz,SymbolNode:gz,SvgNode:_z,PathNode:vz,LineNode:yz}},hW=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{mW.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)}}}}}),gW=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},_W=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:gW,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{mW.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)}}}}}),vW=Tp.create({name:`Mathematics`,addOptions(){return{inlineOptions:void 0,blockOptions:void 0,katexOptions:void 0}},addExtensions(){return[hW.configure({...this.options.blockOptions,katexOptions:this.options.katexOptions}),_W.configure({...this.options.inlineOptions,katexOptions:this.options.katexOptions})]}});function yW(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;IL({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 vW.configure({katexOptions:{throwOnError:!1,strict:!1,trust:!1},inlineOptions:{onClick:n(`inline`)},blockOptions:{onClick:n(`block`)}})}function bW({editor:e,overrideSuggestionOptions:t,extensionName:n,char:r=`@`}){return{editor:e,char:r,pluginKey:new D,command:({editor:e,range:t,props:i})=>{var a,o;let s=Line truncated
|
||||
Idea --> Draft --> Review --> Published`,EW=null;function DW(e){return EW??=e().then(e=>(e.initialize({startOnLoad:!1,securityLevel:`strict`,theme:document.documentElement.classList.contains(`dark`)?`dark`:`neutral`,fontFamily:`inherit`}),e)),EW}var OW=0;async function kW(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 DW(r)).render(`dw-mermaid-${++OW}`,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 AW=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=TW)=>({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 kW(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;IL({anchor:a,value:s,label:c.mermaid,multiline:!0,monospace:!0,labels:{done:c.done,cancel:c.cancel,remove:c.remove},onInput:e=>void kW(o,e,r,i),onSave:n=>{t.chain().setNodeSelection(e).updateAttributes(`mermaid`,{code:n}).run(),kW(o,n,r,i)},onRemove:()=>t.chain().setNodeSelection(e).deleteSelection().focus().run(),onCancel:()=>void kW(o,s,r,i)})}),{dom:a,update:e=>e.type.name===`mermaid`&&(e.attrs.code!==s&&(s=String(e.attrs.code),kW(o,s,r,i)),!0),ignoreMutation:()=>!0,stopEvent:()=>!1}}}});function jW(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 MW(e,t,n,r,i=!1,a){let o=(t,n,r,i)=>({id:t,icon:n,keywords:r,label:e.slash[t]?.label??t,description:e.slash[t]?.description??``,run:i}),s=[o(`text`,`text`,[`paragraph`,`p`],(e,t)=>e.chain().focus().deleteRange(t).setParagraph().run()),o(`h1`,`heading`,[`heading`,`title`,`#`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:1}).run()),o(`h2`,`heading`,[`heading`,`subtitle`,`##`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:2}).run()),o(`h3`,`heading`,[`heading`,`###`],(e,t)=>e.chain().focus().deleteRange(t).setHeading({level:3}).run()),{...o(`otherHeadings`,`heading`,[`other`,`more headings`,`smaller`],()=>{}),children:[4,5,6].map(e=>o(`h${e}`,`heading`,[`heading`,`#`.repeat(e)],(t,n)=>t.chain().focus().deleteRange(n).setHeading({level:e}).run()))},o(`bullet`,`list`,[`list`,`ul`,`-`],(e,t)=>e.chain().focus().deleteRange(t).toggleBulletList().run()),o(`ordered`,`list-ordered`,[`list`,`ol`,`1.`],(e,t)=>e.chain().focus().deleteRange(t).toggleOrderedList().run()),o(`todo`,`todo`,[`task`,`checkbox`,`checklist`,`[]`],(e,t)=>e.chain().focus().deleteRange(t).toggleTaskList().run()),o(`callout`,`callout`,[`note`,`info`,`tip`,`warning`,`aside`,`box`],(e,t)=>e.chain().focus().deleteRange(t).setCallout().run()),o(`table`,`table`,[`grid`,`rows`,`columns`,`spreadsheet`],(e,t)=>e.chain().focus().deleteRange(t).insertTable({rows:3,cols:3,withHeaderRow:!0}).run()),o(`database`,`database`,[`kanban`,`board`,`calendar`,`records`,`tracker`,`notion`],(e,t)=>e.chain().focus().deleteRange(t).insertDatabase().run()),o(`quote`,`quote`,[`blockquote`,`>`],(e,t)=>e.chain().focus().deleteRange(t).toggleBlockquote().run()),o(`code`,`code`,[`codeblock`,"```",`snippet`],(e,t)=>e.chain().focus().deleteRange(t).toggleCodeBlock().run()),o(`toggle`,`chevron-right`,[`details`,`collapse`,`expand`,`fold`,`>`],(e,t)=>e.chain().focus().deleteRange(t).setDetails().run()),o(`divider`,`divider`,[`hr`,`rule`,`line`,`---`],(e,t)=>e.chain().focus().deleteRange(t).setHorizontalRule().run()),o(`toc`,`list`,[`contents`,`outline`,`headings`,`index`],(e,t)=>e.chain().focus().deleteRange(t).insertTableOfContents().run()),o(`math`,`sigma`,[`latex`,`formula`,`equation`,`katex`,`$$`],(e,t)=>e.chain().focus().deleteRange(t).insertBlockMath({latex:`E = mc^2`}).run()),o(`mathInline`,`sigma`,[`latex`,`formula`,`equation`,`$`],(e,t)=>e.chain().focus().deleteRange(t).insertInlineMath({latex:`x^2`}).run()),o(`mermaid`,`diagram`,[`diagram`,`flowchart`,`chart`,`sequence`,`graph`],(e,t)=>e.chain().focus().deleteRange(t).insertMermaid().run()),o(`embed`,`video`,[`video`,`youtube`,`vimeo`,`figma`,`loom`,`iframe`,`map`],(t,r)=>{t.chain().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);--shadow-dialog:var(--dw-shadow-dialog);--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-varLine truncated
|
||||
/*$vite$:1*/</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -273,6 +273,7 @@ function shouldShow({ editor: e, from, to }: { editor: Editor; from: number; to:
|
||||
"tableOfContents",
|
||||
"embed",
|
||||
"linkCard",
|
||||
"database",
|
||||
];
|
||||
if (from === to || blocks.some((b) => e.isActive(b)) || e.state.selection instanceof CellSelection) return false;
|
||||
return e.isEditable || props.canComment;
|
||||
|
||||
@@ -99,6 +99,21 @@ export function blockActions(editor: Editor, pos: number, labels: EditorLabels,
|
||||
})),
|
||||
});
|
||||
}
|
||||
if (["bulletList", "orderedList", "taskList"].includes(node.type.name)) {
|
||||
out.push({
|
||||
id: "groupAsDatabase",
|
||||
label: labels.database.groupAsDatabase,
|
||||
icon: "database",
|
||||
run: () => {
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.setTextSelection(pos + 2)
|
||||
.groupAsDatabase()
|
||||
.run();
|
||||
},
|
||||
});
|
||||
}
|
||||
if (node.type.name === "codeBlock") {
|
||||
const byDefault = !!editor.extensionManager.extensions.find((e) => e.name === "codeBlock")?.options.lineNumbers;
|
||||
const on = showsLineNumbers(node.attrs.lineNumbers, byDefault);
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// How each property type shows in a cell, and how it is edited: text-like
|
||||
// cells edit in place, the rest in a small panel next to the cell.
|
||||
|
||||
import type { IconName } from "@docwell/ui/icons";
|
||||
import { openBlockMenu } from "../blockmenu";
|
||||
import { palette, type PaletteColor } from "../colors";
|
||||
import type { FileHost } from "../files";
|
||||
import type { MentionHost } from "../mention";
|
||||
import { h, icon, popover, textInput } from "./dom";
|
||||
import { fill, type DatabaseLabels } from "./labels";
|
||||
import {
|
||||
asList,
|
||||
asNumber,
|
||||
cellValue,
|
||||
dateOf,
|
||||
newId,
|
||||
nextColor,
|
||||
type Attachment,
|
||||
type Column,
|
||||
type ColumnType,
|
||||
type DbData,
|
||||
type Person,
|
||||
type Row,
|
||||
type SelectOption,
|
||||
} from "./model";
|
||||
import type { DbStore } from "./store";
|
||||
|
||||
/** What cells, views and panels need from the block. */
|
||||
export interface DbContext {
|
||||
db: DbData;
|
||||
/** null when the reader cannot edit. */
|
||||
store: DbStore | null;
|
||||
labels: DatabaseLabels;
|
||||
colorNames: Record<string, string>;
|
||||
locale?: string;
|
||||
files?: FileHost;
|
||||
people?: MentionHost;
|
||||
/** Opens a row as a page. */
|
||||
openRow: (id: string) => void;
|
||||
/** Called while a cell is being edited (true) and after (false); the block holds back redraws meanwhile. */
|
||||
setEditing: (on: boolean) => void;
|
||||
}
|
||||
|
||||
export const typeIcons: Record<ColumnType, IconName> = {
|
||||
title: "text",
|
||||
text: "type",
|
||||
number: "sigma",
|
||||
checkbox: "todo",
|
||||
select: "tag",
|
||||
multiSelect: "layers",
|
||||
date: "calendar",
|
||||
progress: "sliders",
|
||||
link: "link",
|
||||
attachment: "paperclip",
|
||||
member: "users",
|
||||
createdTime: "clock",
|
||||
createdBy: "at",
|
||||
};
|
||||
|
||||
/** Types whose cells edit as a line of text in place. */
|
||||
export const inlineTypes: ColumnType[] = ["title", "text", "number", "link"];
|
||||
|
||||
/** Types that cannot be edited at all. */
|
||||
export const readOnlyTypes: ColumnType[] = ["createdTime", "createdBy"];
|
||||
|
||||
export function formatDay(iso: string, locale?: string): string {
|
||||
const [y, m, d] = iso.split("-").map(Number);
|
||||
if (!y || !m || !d) return iso;
|
||||
return new Date(y, m - 1, d).toLocaleDateString(locale, { year: "numeric", month: "short", day: "numeric" });
|
||||
}
|
||||
|
||||
export function tag(name: string, color: PaletteColor | undefined, onRemove?: () => void): HTMLElement {
|
||||
const el = h("span", { class: "dw-db-tag", dataset: { color: color ?? "gray" } }, name);
|
||||
if (onRemove) {
|
||||
const x = h("button", { type: "button", class: "dw-db-tag__x", "aria-label": "×" }, "×");
|
||||
x.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
x.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
onRemove();
|
||||
});
|
||||
el.append(x);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
function safeHref(url: string): string | null {
|
||||
try {
|
||||
const u = new URL(url.includes("://") ? url : `https://${url}`);
|
||||
return u.protocol === "http:" || u.protocol === "https:" || u.protocol === "mailto:" ? u.href : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A cell's content for display. */
|
||||
export function renderCell(ctx: DbContext, row: Row, col: Column): Node {
|
||||
const v = cellValue(row, col);
|
||||
const l = ctx.labels;
|
||||
switch (col.type) {
|
||||
case "title": {
|
||||
const text = typeof v === "string" ? v : "";
|
||||
return h("span", { class: text ? "dw-db-cell__title" : "dw-db-cell__title is-empty" }, text || l.untitledRow);
|
||||
}
|
||||
case "text":
|
||||
return h("span", { class: "dw-db-cell__text" }, typeof v === "string" ? v : "");
|
||||
case "number": {
|
||||
const n = asNumber(v);
|
||||
return h("span", { class: "dw-db-cell__number" }, n === null ? "" : n.toLocaleString(ctx.locale));
|
||||
}
|
||||
case "checkbox":
|
||||
return h(
|
||||
"span",
|
||||
{ class: v === true ? "dw-db-check is-on" : "dw-db-check", role: "img", "aria-label": v === true ? l.checked : l.unchecked },
|
||||
v === true ? icon("check", 13) : null,
|
||||
);
|
||||
case "select": {
|
||||
const o = col.options?.find((x) => x.id === v);
|
||||
return h("span", { class: "dw-db-tags" }, o ? tag(o.name, o.color) : null);
|
||||
}
|
||||
case "multiSelect":
|
||||
return h(
|
||||
"span",
|
||||
{ class: "dw-db-tags" },
|
||||
asList<string>(v).flatMap((id) => {
|
||||
const o = col.options?.find((x) => x.id === id);
|
||||
return o ? [tag(o.name, o.color)] : [];
|
||||
}),
|
||||
);
|
||||
case "date":
|
||||
case "createdTime": {
|
||||
const d = dateOf(v);
|
||||
return h("span", { class: "dw-db-cell__text" }, d ? formatDay(d, ctx.locale) : "");
|
||||
}
|
||||
case "progress": {
|
||||
const n = asNumber(v);
|
||||
if (n === null) return h("span");
|
||||
const pct = Math.max(0, Math.min(100, n));
|
||||
return h(
|
||||
"span",
|
||||
{ class: "dw-db-progress" },
|
||||
h("span", { class: "dw-db-progress__bar" }, h("span", { class: "dw-db-progress__fill", style: { width: `${pct}%` } })),
|
||||
h("span", { class: "dw-db-progress__num" }, `${pct}%`),
|
||||
);
|
||||
}
|
||||
case "link": {
|
||||
const url = typeof v === "string" ? v : "";
|
||||
const href = url ? safeHref(url) : null;
|
||||
if (!href) return h("span", { class: "dw-db-cell__text" }, url);
|
||||
const a = h("a", { class: "dw-db-cell__link", href, target: "_blank", rel: "noopener noreferrer" }, url);
|
||||
// A plain click selects the cell; Ctrl/Cmd+click follows the link.
|
||||
a.addEventListener("click", (e) => {
|
||||
if (!e.ctrlKey && !e.metaKey) e.preventDefault();
|
||||
});
|
||||
return a;
|
||||
}
|
||||
case "attachment":
|
||||
return h(
|
||||
"span",
|
||||
{ class: "dw-db-tags" },
|
||||
asList<Attachment>(v).map((f) => {
|
||||
const href = ctx.files ? ctx.files.resolve(f.src) : f.src;
|
||||
const a = h("a", { class: "dw-db-file", href, target: "_blank", rel: "noopener noreferrer" }, icon("paperclip", 12), f.name);
|
||||
a.addEventListener("click", (e) => {
|
||||
if (!e.ctrlKey && !e.metaKey) e.preventDefault();
|
||||
});
|
||||
return a;
|
||||
}),
|
||||
);
|
||||
case "member":
|
||||
case "createdBy":
|
||||
return h(
|
||||
"span",
|
||||
{ class: "dw-db-tags" },
|
||||
asList<Person>(v).map((p) => h("span", { class: "dw-db-person" }, h("span", { class: "dw-db-person__dot" }, (p?.name || "?").slice(0, 1).toUpperCase()), p?.name ?? "")),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export interface EditOptions {
|
||||
/** Called when editing ends; move is where the selection should go next (Enter/Tab). */
|
||||
onDone: (move?: "down" | "right" | "left") => void;
|
||||
/** Text typed to start editing; replaces the value. */
|
||||
initial?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts editing a cell drawn in el: text-like types get an input inside it,
|
||||
* the rest a panel next to it. Checkboxes toggle at once.
|
||||
*/
|
||||
export function editCell(ctx: DbContext, el: HTMLElement, row: Row, col: Column, opts: EditOptions) {
|
||||
const store = ctx.store;
|
||||
if (!store || readOnlyTypes.includes(col.type)) return opts.onDone();
|
||||
const v = cellValue(row, col);
|
||||
if (col.type === "checkbox") {
|
||||
store.setCell(row.id, col.id, v !== true);
|
||||
return opts.onDone();
|
||||
}
|
||||
ctx.setEditing(true);
|
||||
const finish = (move?: "down" | "right" | "left") => {
|
||||
ctx.setEditing(false);
|
||||
opts.onDone(move);
|
||||
};
|
||||
if (inlineTypes.includes(col.type)) {
|
||||
const start = opts.initial ?? (col.type === "number" ? (asNumber(v)?.toString() ?? "") : typeof v === "string" ? v : "");
|
||||
let move: "down" | "right" | "left" | undefined;
|
||||
const input = textInput(start, {
|
||||
class: "dw-db-cell__input",
|
||||
type: col.type === "number" ? "text" : "text",
|
||||
label: col.name,
|
||||
onCommit: (text) => {
|
||||
const t = text.trim();
|
||||
const value = col.type === "number" ? asNumber(t) : col.type === "title" || col.type === "text" ? text : t;
|
||||
if (value !== (v ?? null) && !(value === "" && v === undefined)) store.setCell(row.id, col.id, value);
|
||||
finish(move);
|
||||
},
|
||||
onCancel: () => finish(),
|
||||
});
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") move = "down";
|
||||
if (e.key === "Tab") {
|
||||
e.preventDefault();
|
||||
move = e.shiftKey ? "left" : "right";
|
||||
input.blur();
|
||||
}
|
||||
});
|
||||
el.replaceChildren(input);
|
||||
el.classList.add("is-editing");
|
||||
input.focus();
|
||||
if (opts.initial !== undefined) input.setSelectionRange(input.value.length, input.value.length);
|
||||
else input.select();
|
||||
return;
|
||||
}
|
||||
const panel = (fillBox: (box: HTMLDivElement, close: () => void) => void, cls = "") =>
|
||||
popover(el, fillBox, { class: cls, onClose: () => finish(), label: col.name });
|
||||
switch (col.type) {
|
||||
case "select":
|
||||
case "multiSelect":
|
||||
panel((box, close) => choicePanel(ctx, box, row, col, close, opts.initial), "dw-db-pop--choices");
|
||||
break;
|
||||
case "date":
|
||||
panel((box, close) => {
|
||||
const input = h("input", { type: "date", class: "dw-db-input", "aria-label": col.name });
|
||||
input.value = dateOf(v);
|
||||
input.addEventListener("change", () => store.setCell(row.id, col.id, input.value || null));
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") close();
|
||||
});
|
||||
const clear = h("button", { type: "button", class: "dw-db__btn" }, ctx.labels.clear);
|
||||
clear.addEventListener("click", () => {
|
||||
store.setCell(row.id, col.id, null);
|
||||
close();
|
||||
});
|
||||
const today = h("button", { type: "button", class: "dw-db__btn" }, ctx.labels.today);
|
||||
today.addEventListener("click", () => {
|
||||
const d = new Date();
|
||||
store.setCell(row.id, col.id, `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`);
|
||||
close();
|
||||
});
|
||||
box.append(input, h("div", { class: "dw-db-pop__row" }, today, clear));
|
||||
input.focus({ preventScroll: true });
|
||||
});
|
||||
break;
|
||||
case "progress":
|
||||
panel((box, close) => {
|
||||
const n = asNumber(v) ?? 0;
|
||||
const range = h("input", { type: "range", min: "0", max: "100", step: "1", class: "dw-db-range", "aria-label": col.name });
|
||||
range.value = String(n);
|
||||
const num = h("span", { class: "dw-db-progress__num" }, `${n}%`);
|
||||
range.addEventListener("input", () => (num.textContent = `${range.value}%`));
|
||||
range.addEventListener("change", () => store.setCell(row.id, col.id, Number(range.value)));
|
||||
range.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") close();
|
||||
});
|
||||
box.append(h("div", { class: "dw-db-pop__row" }, range, num));
|
||||
range.focus({ preventScroll: true });
|
||||
});
|
||||
break;
|
||||
case "member":
|
||||
panel((box, close) => memberPanel(ctx, box, row, col, close), "dw-db-pop--choices");
|
||||
break;
|
||||
case "attachment":
|
||||
panel((box) => attachmentPanel(ctx, box, row, col), "dw-db-pop--choices");
|
||||
break;
|
||||
default:
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
/** The choice list of a select cell: pick, find or create, and edit choices. */
|
||||
function choicePanel(ctx: DbContext, box: HTMLDivElement, row: Row, col: Column, close: () => void, initial?: string) {
|
||||
const store = ctx.store!;
|
||||
const l = ctx.labels;
|
||||
const multi = col.type === "multiSelect";
|
||||
let options: SelectOption[] = [...(col.options ?? [])];
|
||||
let picked: string[] = multi ? asList<string>(cellValue(row, col)) : [String(cellValue(row, col) ?? "")].filter(Boolean);
|
||||
let active = 0;
|
||||
const chosen = h("div", { class: "dw-db-tags dw-db-pop__chosen" });
|
||||
const input = h("input", { class: "dw-db-input", placeholder: l.searchOptions, "aria-label": l.searchOptions });
|
||||
input.value = initial ?? "";
|
||||
const list = h("div", { class: "dw-db-pop__list", role: "listbox" });
|
||||
box.append(chosen, input, list);
|
||||
|
||||
const save = () => store.setCell(row.id, col.id, multi ? picked : (picked[0] ?? null));
|
||||
const toggle = (id: string) => {
|
||||
if (multi) picked = picked.includes(id) ? picked.filter((x) => x !== id) : [...picked, id];
|
||||
else picked = picked[0] === id ? [] : [id];
|
||||
save();
|
||||
if (!multi) close();
|
||||
else draw();
|
||||
};
|
||||
const create = (name: string) => {
|
||||
const o: SelectOption = { id: newId(), name, color: nextColor(options) };
|
||||
options = [...options, o];
|
||||
store.tx(() => {
|
||||
store.setOptions(col.id, options);
|
||||
picked = multi ? [...picked, o.id] : [o.id];
|
||||
save();
|
||||
});
|
||||
input.value = "";
|
||||
if (!multi) close();
|
||||
else draw();
|
||||
};
|
||||
const editOption = (anchor: HTMLElement, o: SelectOption) => {
|
||||
openBlockMenu(
|
||||
anchor,
|
||||
[
|
||||
{
|
||||
id: "rename",
|
||||
label: l.renameOption,
|
||||
icon: "pencil",
|
||||
run: () => {
|
||||
const name = window.prompt(l.renameOption, o.name)?.trim();
|
||||
if (!name) return;
|
||||
options = options.map((x) => (x.id === o.id ? { ...x, name } : x));
|
||||
store.setOptions(col.id, options);
|
||||
draw();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "color",
|
||||
label: l.optionColor,
|
||||
icon: "palette",
|
||||
children: palette.map((c) => ({
|
||||
id: c,
|
||||
label: ctx.colorNames[c] ?? c,
|
||||
icon: c === o.color ? "check" : "drop",
|
||||
run: () => {
|
||||
options = options.map((x) => (x.id === o.id ? { ...x, color: c } : x));
|
||||
store.setOptions(col.id, options);
|
||||
draw();
|
||||
},
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
label: l.deleteOption,
|
||||
icon: "trash",
|
||||
danger: true,
|
||||
run: () => {
|
||||
options = options.filter((x) => x.id !== o.id);
|
||||
picked = picked.filter((x) => x !== o.id);
|
||||
store.setOptions(col.id, options);
|
||||
draw();
|
||||
},
|
||||
},
|
||||
],
|
||||
l.optionColor,
|
||||
() => input.focus(),
|
||||
);
|
||||
};
|
||||
|
||||
type Item = { kind: "option"; o: SelectOption } | { kind: "create"; name: string };
|
||||
let items: Item[] = [];
|
||||
function draw() {
|
||||
chosen.replaceChildren(
|
||||
...picked.flatMap((id) => {
|
||||
const o = options.find((x) => x.id === id);
|
||||
return o ? [tag(o.name, o.color, () => toggle(id))] : [];
|
||||
}),
|
||||
);
|
||||
const q = input.value.trim();
|
||||
const found = options.filter((o) => o.name.toLowerCase().includes(q.toLowerCase()));
|
||||
items = found.map((o) => ({ kind: "option" as const, o }));
|
||||
if (q && !options.some((o) => o.name.toLowerCase() === q.toLowerCase())) items.push({ kind: "create", name: q });
|
||||
active = Math.min(active, Math.max(0, items.length - 1));
|
||||
list.replaceChildren(
|
||||
...items.map((it, i) => {
|
||||
const rowEl = h("div", {
|
||||
class: `dw-db-pop__item${i === active ? " is-active" : ""}`,
|
||||
role: "option",
|
||||
"aria-selected": String(it.kind === "option" && picked.includes(it.o.id)),
|
||||
});
|
||||
rowEl.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
if (it.kind === "option") {
|
||||
rowEl.append(
|
||||
h("span", { class: "dw-db-pop__check" }, picked.includes(it.o.id) ? icon("check", 13) : null),
|
||||
tag(it.o.name, it.o.color),
|
||||
);
|
||||
const more = h("button", { type: "button", class: "dw-db__btn dw-db__btn--icon dw-db-pop__more", "aria-label": l.optionColor }, icon("more", 14));
|
||||
more.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
editOption(more, it.o);
|
||||
});
|
||||
rowEl.append(more);
|
||||
rowEl.addEventListener("click", () => toggle(it.o.id));
|
||||
} else {
|
||||
rowEl.append(h("span", { class: "dw-db-pop__check" }, icon("plus", 13)), h("span", {}, fill(l.createOption, it.name)));
|
||||
rowEl.addEventListener("click", () => create(it.name));
|
||||
}
|
||||
return rowEl;
|
||||
}),
|
||||
);
|
||||
}
|
||||
input.addEventListener("input", () => {
|
||||
active = 0;
|
||||
draw();
|
||||
});
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (items.length) active = (active + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length;
|
||||
draw();
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
const it = items[active];
|
||||
if (it?.kind === "option") toggle(it.o.id);
|
||||
else if (it?.kind === "create") create(it.name);
|
||||
else close();
|
||||
} else if (e.key === "Backspace" && !input.value && multi && picked.length) {
|
||||
toggle(picked[picked.length - 1]!);
|
||||
}
|
||||
});
|
||||
draw();
|
||||
// Focus at once (not on the next frame), so keys typed right away land here.
|
||||
input.focus({ preventScroll: true });
|
||||
input.setSelectionRange(input.value.length, input.value.length);
|
||||
}
|
||||
|
||||
/** People in a member cell: remove them, or find and add more. */
|
||||
function memberPanel(ctx: DbContext, box: HTMLDivElement, row: Row, col: Column, close: () => void) {
|
||||
const store = ctx.store!;
|
||||
const l = ctx.labels;
|
||||
let people = asList<Person>(cellValue(row, col)).filter((p) => p?.id);
|
||||
const chosen = h("div", { class: "dw-db-tags dw-db-pop__chosen" });
|
||||
const input = h("input", { class: "dw-db-input", placeholder: l.searchPeople, "aria-label": l.searchPeople });
|
||||
const list = h("div", { class: "dw-db-pop__list", role: "listbox" });
|
||||
box.append(chosen, input, list);
|
||||
const save = () => store.setCell(row.id, col.id, people);
|
||||
const drawChosen = () =>
|
||||
chosen.replaceChildren(
|
||||
...people.map((p) =>
|
||||
tag(p.name, "gray", () => {
|
||||
people = people.filter((x) => x.id !== p.id);
|
||||
save();
|
||||
drawChosen();
|
||||
}),
|
||||
),
|
||||
);
|
||||
let seq = 0;
|
||||
let found: Person[] = [];
|
||||
let active = 0;
|
||||
const drawList = () => {
|
||||
list.replaceChildren(
|
||||
...(found.length
|
||||
? found.map((p, i) => {
|
||||
const el = h(
|
||||
"div",
|
||||
{ class: `dw-db-pop__item${i === active ? " is-active" : ""}`, role: "option" },
|
||||
h("span", { class: "dw-db-person__dot" }, (p.name || "?").slice(0, 1).toUpperCase()),
|
||||
h("span", {}, p.name),
|
||||
);
|
||||
el.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
el.addEventListener("click", () => add(p));
|
||||
return el;
|
||||
})
|
||||
: [h("div", { class: "dw-db-pop__empty" }, input.value.trim() ? l.noPeople : "")]),
|
||||
);
|
||||
};
|
||||
const add = (p: Person) => {
|
||||
if (!people.some((x) => x.id === p.id)) people = [...people, p];
|
||||
save();
|
||||
input.value = "";
|
||||
found = [];
|
||||
drawChosen();
|
||||
drawList();
|
||||
};
|
||||
input.addEventListener("input", async () => {
|
||||
const q = input.value.trim();
|
||||
const n = ++seq;
|
||||
const res = ctx.people && q ? await ctx.people.search(q).catch(() => []) : [];
|
||||
if (n !== seq) return;
|
||||
found = res.slice(0, 8).map((p) => ({ id: p.id, name: p.label }));
|
||||
active = 0;
|
||||
drawList();
|
||||
});
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
if (found.length) active = (active + (e.key === "ArrowDown" ? 1 : -1) + found.length) % found.length;
|
||||
drawList();
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
const p = found[active];
|
||||
if (p) add(p);
|
||||
else close();
|
||||
}
|
||||
});
|
||||
drawChosen();
|
||||
drawList();
|
||||
input.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
/** Files in an attachment cell: open, remove, or upload more. */
|
||||
function attachmentPanel(ctx: DbContext, box: HTMLDivElement, row: Row, col: Column) {
|
||||
const store = ctx.store!;
|
||||
const l = ctx.labels;
|
||||
let files = asList<Attachment>(cellValue(row, col)).filter((f) => f?.src);
|
||||
const list = h("div", { class: "dw-db-pop__list" });
|
||||
const draw = () =>
|
||||
list.replaceChildren(
|
||||
...files.map((f, i) => {
|
||||
const href = ctx.files ? ctx.files.resolve(f.src) : f.src;
|
||||
const rm = h("button", { type: "button", class: "dw-db__btn dw-db__btn--icon", "aria-label": l.remove, title: l.remove }, icon("trash", 14));
|
||||
rm.addEventListener("click", () => {
|
||||
files = files.filter((_, j) => j !== i);
|
||||
store.setCell(row.id, col.id, files);
|
||||
draw();
|
||||
});
|
||||
return h(
|
||||
"div",
|
||||
{ class: "dw-db-pop__item" },
|
||||
h("a", { class: "dw-db-file", href, target: "_blank", rel: "noopener noreferrer" }, icon("paperclip", 12), f.name),
|
||||
rm,
|
||||
);
|
||||
}),
|
||||
);
|
||||
box.append(list);
|
||||
const upload = ctx.files?.upload;
|
||||
if (upload) {
|
||||
const btn = h("button", { type: "button", class: "dw-db__btn" }, icon("upload", 14), h("span", {}, l.upload));
|
||||
btn.addEventListener("click", () => {
|
||||
const input = h("input", { type: "file", multiple: true });
|
||||
input.onchange = async () => {
|
||||
for (const file of [...(input.files ?? [])]) {
|
||||
try {
|
||||
const up = await upload.call(ctx.files, file);
|
||||
files = [...files, { name: up.name, src: up.url, size: up.size, mime: up.mime }];
|
||||
store.setCell(row.id, col.id, files);
|
||||
draw();
|
||||
} catch {
|
||||
/* the host reports upload errors */
|
||||
}
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
box.append(h("div", { class: "dw-db-pop__row" }, btn));
|
||||
}
|
||||
draw();
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// CSV for import and export, and tab-separated text for copying and pasting
|
||||
// cells to and from spreadsheets.
|
||||
|
||||
import {
|
||||
asNumber,
|
||||
cellText,
|
||||
dateOf,
|
||||
newId,
|
||||
nextColor,
|
||||
type Column,
|
||||
type ColumnType,
|
||||
type DbData,
|
||||
type Row,
|
||||
type SelectOption,
|
||||
} from "./model";
|
||||
|
||||
/** Parses CSV (or TSV with sep "\t") into rows of fields; quotes may hold separators and line breaks. */
|
||||
export function parseDelimited(text: string, sep = ","): string[][] {
|
||||
const out: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = "";
|
||||
let quoted = false;
|
||||
let i = 0;
|
||||
const src = text.replace(/^\uFEFF/, "");
|
||||
while (i < src.length) {
|
||||
const ch = src[i]!;
|
||||
if (quoted) {
|
||||
if (ch === '"') {
|
||||
if (src[i + 1] === '"') {
|
||||
field += '"';
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
quoted = false;
|
||||
} else field += ch;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' && field === "") quoted = true;
|
||||
else if (ch === sep) {
|
||||
row.push(field);
|
||||
field = "";
|
||||
} else if (ch === "\n" || ch === "\r") {
|
||||
row.push(field);
|
||||
out.push(row);
|
||||
row = [];
|
||||
field = "";
|
||||
if (ch === "\r" && src[i + 1] === "\n") i++;
|
||||
} else field += ch;
|
||||
i++;
|
||||
}
|
||||
if (field !== "" || row.length) {
|
||||
row.push(field);
|
||||
out.push(row);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function quote(s: string, sep: string): string {
|
||||
return s.includes(sep) || /["\r\n]/.test(s) || /^\s|\s$/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
|
||||
}
|
||||
|
||||
export function formatDelimited(rows: string[][], sep = ","): string {
|
||||
return rows.map((r) => r.map((f) => quote(f, sep)).join(sep)).join("\r\n");
|
||||
}
|
||||
|
||||
/** A database as CSV: a header of column names, then one line per row. */
|
||||
export function toCSV(db: DbData, columns: Column[], rows: Row[]): string {
|
||||
return formatDelimited([columns.map((c) => c.name), ...rows.map((r) => columns.map((c) => cellText(r, c)))]);
|
||||
}
|
||||
|
||||
/** Guesses a column's type from its values: numbers, dates, yes/no, or a few repeated words. */
|
||||
export function guessType(values: string[]): ColumnType {
|
||||
const filled = values.map((v) => v.trim()).filter(Boolean);
|
||||
if (!filled.length) return "text";
|
||||
if (filled.every((v) => asNumber(v) !== null)) return "number";
|
||||
if (filled.every((v) => /^\d{4}-\d{2}-\d{2}/.test(v))) return "date";
|
||||
if (filled.every((v) => /^(true|false|yes|no)$/i.test(v))) return "checkbox";
|
||||
if (filled.every((v) => /^https?:\/\/\S+$/.test(v))) return "link";
|
||||
const distinct = new Set(filled.map((v) => v.toLowerCase()));
|
||||
if (filled.length >= 4 && distinct.size <= Math.max(2, filled.length / 3) && filled.every((v) => v.length <= 40)) {
|
||||
return "select";
|
||||
}
|
||||
return "text";
|
||||
}
|
||||
|
||||
/** A text value as a cell of col; choices missing from options are added to it (options is mutated). */
|
||||
export function parseCell(text: string, col: Column, options: SelectOption[]): unknown {
|
||||
const t = text.trim();
|
||||
if (!t) return null;
|
||||
const choice = (name: string) => {
|
||||
let o = options.find((x) => x.name.toLowerCase() === name.toLowerCase());
|
||||
if (!o) {
|
||||
o = { id: newId(), name, color: nextColor(options) };
|
||||
options.push(o);
|
||||
}
|
||||
return o.id;
|
||||
};
|
||||
switch (col.type) {
|
||||
case "number":
|
||||
return asNumber(t);
|
||||
case "progress": {
|
||||
const n = asNumber(t.replace("%", ""));
|
||||
return n === null ? null : Math.max(0, Math.min(100, Math.round(n)));
|
||||
}
|
||||
case "checkbox":
|
||||
return /^(true|yes|1|x|✓|done)$/i.test(t);
|
||||
case "date":
|
||||
return dateOf(t) || null;
|
||||
case "select":
|
||||
return choice(t);
|
||||
case "multiSelect":
|
||||
return [
|
||||
...new Set(
|
||||
t
|
||||
.split(/[,;]/)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean)
|
||||
.map(choice),
|
||||
),
|
||||
];
|
||||
case "member":
|
||||
case "attachment":
|
||||
case "createdBy":
|
||||
case "createdTime":
|
||||
return null;
|
||||
default:
|
||||
return t;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The columns and rows of a CSV file for a new database: the header names
|
||||
* the columns, the first column is the title, and types are guessed.
|
||||
*/
|
||||
export function fromCSV(text: string, sep = ","): { columns: Column[]; rows: Record<string, unknown>[] } {
|
||||
const lines = parseDelimited(text, sep).filter((r) => r.some((f) => f.trim()));
|
||||
const head = lines[0] ?? [];
|
||||
const body = lines.slice(1);
|
||||
const columns: Column[] = head.map((name, i) => ({
|
||||
id: newId(),
|
||||
name: name.trim() || `${i + 1}`,
|
||||
type: i === 0 ? "title" : guessType(body.map((r) => r[i] ?? "")),
|
||||
}));
|
||||
for (const c of columns) if (c.type === "select") c.options = [];
|
||||
const rows = body.map((r) => {
|
||||
const cells: Record<string, unknown> = {};
|
||||
columns.forEach((c, i) => {
|
||||
const v = parseCell(r[i] ?? "", c, c.options ?? []);
|
||||
if (v !== null && !(Array.isArray(v) && !v.length)) cells[c.id] = v;
|
||||
});
|
||||
return cells;
|
||||
});
|
||||
return { columns, rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches CSV header names to an existing database's columns (by name,
|
||||
* ignoring case). Unknown names come back in missing, to be added as text.
|
||||
*/
|
||||
export function matchHeader(head: string[], columns: Column[]): { index: (Column | null)[]; missing: string[] } {
|
||||
const missing: string[] = [];
|
||||
const index = head.map((name) => {
|
||||
const c = columns.find((x) => x.name.trim().toLowerCase() === name.trim().toLowerCase());
|
||||
if (!c && name.trim()) missing.push(name.trim());
|
||||
return c ?? null;
|
||||
});
|
||||
return { index, missing };
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as Y from "yjs";
|
||||
import { formatDelimited, fromCSV, parseDelimited, toCSV } from "./csv";
|
||||
import { convertValue, defaultView, groupRows, monthGrid, moveToGroup, normalize, viewRows, type Column, type DbData, type Row } from "./model";
|
||||
import { blocksOf, DbStore, readDb, seedDb } from "./store";
|
||||
|
||||
const title: Column = { id: "t", name: "Name", type: "title" };
|
||||
const status: Column = {
|
||||
id: "s",
|
||||
name: "Status",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "todo", name: "To do", color: "gray" },
|
||||
{ id: "done", name: "Done", color: "green" },
|
||||
],
|
||||
};
|
||||
const points: Column = { id: "p", name: "Points", type: "number" };
|
||||
const row = (id: string, cells: Record<string, unknown>): Row => ({ id, cells, createdAt: 1, createdBy: null });
|
||||
|
||||
function sample(): DbData {
|
||||
return {
|
||||
title: "Tasks",
|
||||
columns: [title, status, points],
|
||||
rows: [row("a", { t: "Write", s: "todo", p: 3 }), row("b", { t: "Read", s: "done", p: 1 }), row("c", { t: "Ship", p: 5 })],
|
||||
views: [defaultView("table", "Table", [title, status, points])],
|
||||
};
|
||||
}
|
||||
|
||||
describe("database model", () => {
|
||||
it("filters, searches and sorts rows, keeping empty cells last", () => {
|
||||
const db = sample();
|
||||
const v = db.views[0]!;
|
||||
expect(viewRows(db, { ...v, filters: [{ column: "s", op: "is", value: "todo" }] }).map((r) => r.id)).toEqual(["a"]);
|
||||
expect(viewRows(db, { ...v, filters: [{ column: "s", op: "isEmpty" }] }).map((r) => r.id)).toEqual(["c"]);
|
||||
expect(viewRows(db, { ...v, filters: [{ column: "p", op: "gt", value: 2 }] }).map((r) => r.id)).toEqual(["a", "c"]);
|
||||
expect(viewRows(db, v, "rea").map((r) => r.id)).toEqual(["b"]);
|
||||
expect(viewRows(db, { ...v, sorts: [{ column: "p", desc: true }] }).map((r) => r.id)).toEqual(["c", "a", "b"]);
|
||||
// Choices sort in their own order; the row without one goes last either way.
|
||||
expect(viewRows(db, { ...v, sorts: [{ column: "s", desc: true }] }).map((r) => r.id)).toEqual(["b", "a", "c"]);
|
||||
});
|
||||
|
||||
it("groups rows by a choice, with a group for rows without one", () => {
|
||||
const db = sample();
|
||||
const groups = groupRows(db.rows, status, "No value", "Yes", "No");
|
||||
expect(groups.map((g) => [g.key, g.rows.map((r) => r.id)])).toEqual([
|
||||
["", ["c"]],
|
||||
["todo", ["a"]],
|
||||
["done", ["b"]],
|
||||
]);
|
||||
expect(moveToGroup(db.rows[0]!, status, "todo", "done")).toBe("done");
|
||||
});
|
||||
|
||||
it("converts values when a column changes type", () => {
|
||||
const text: Column = { id: "x", name: "X", type: "text" };
|
||||
const out = convertValue("Red, Blue", text, "multiSelect", []);
|
||||
expect(out.options.map((o) => o.name)).toEqual(["Red", "Blue"]);
|
||||
expect(out.value).toEqual(out.options.map((o) => o.id));
|
||||
expect(convertValue("done", status, "text", []).value).toBe("Done");
|
||||
expect(convertValue("12,5", text, "number", []).value).toBe(12.5);
|
||||
});
|
||||
|
||||
it("normalizes untrusted data and always has a title column", () => {
|
||||
const db = normalize({ columns: [{ id: "a", type: "bogus" }], rows: [{ id: 3 }, { id: "r", cells: { a: "x" } }] });
|
||||
expect(db.columns.map((c) => c.type)).toEqual(["title", "text"]);
|
||||
expect(db.rows.map((r) => r.id)).toEqual(["r"]);
|
||||
});
|
||||
|
||||
it("lays out a month from Monday", () => {
|
||||
const days = monthGrid(2026, 10); // November 2026 starts on a Sunday
|
||||
expect(days[0]).toBe("2026-10-26");
|
||||
expect(days.length % 7).toBe(0);
|
||||
expect(days).toContain("2026-11-30");
|
||||
});
|
||||
});
|
||||
|
||||
describe("CSV", () => {
|
||||
it("reads quoted fields with separators and line breaks", () => {
|
||||
expect(parseDelimited('a,"b,c","d ""e""\nf"\r\n1,2,3')).toEqual([
|
||||
["a", "b,c", 'd "e"\nf'],
|
||||
["1", "2", "3"],
|
||||
]);
|
||||
expect(formatDelimited([["a", "b,c"], ['x"y', ""]])).toBe('a,"b,c"\r\n"x""y",');
|
||||
});
|
||||
|
||||
it("guesses column types on import and writes them back", () => {
|
||||
const { columns, rows } = fromCSV("Name,Points,Due,Done\nA,1,2026-11-01,yes\nB,2.5,2026-11-02,no\n");
|
||||
expect(columns.map((c) => c.type)).toEqual(["title", "number", "date", "checkbox"]);
|
||||
expect(rows[1]).toEqual({ [columns[0]!.id]: "B", [columns[1]!.id]: 2.5, [columns[2]!.id]: "2026-11-02", [columns[3]!.id]: false });
|
||||
const db = sample();
|
||||
expect(toCSV(db, db.columns, db.rows).split("\r\n")[1]).toBe("Write,To do,3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("database store", () => {
|
||||
it("edits a database in the Y.Doc and moves rows without recreating them", () => {
|
||||
const doc = new Y.Doc();
|
||||
seedDb(doc, "db1", sample(), () => {});
|
||||
const store = new DbStore(doc, blocksOf(doc).get("db1")!, () => ({ id: "u1", name: "Ann" }));
|
||||
store.setCell("a", "p", 8);
|
||||
const id = store.addRow({ t: "New" }, 0);
|
||||
expect(store.snapshot().rows.map((r) => r.id)).toEqual([id, "a", "b", "c"]);
|
||||
expect(store.snapshot().rows[0]!.createdBy).toEqual({ id: "u1", name: "Ann" });
|
||||
|
||||
const body = store.rowBody("a")!;
|
||||
store.moveRow("a", 3);
|
||||
expect(store.snapshot().rows.map((r) => r.id)).toEqual([id, "b", "c", "a"]);
|
||||
expect(store.rowBody("a")).toBe(body);
|
||||
expect(store.snapshot().rows.find((r) => r.id === "a")!.cells.p).toBe(8);
|
||||
|
||||
store.changeType("s", "text");
|
||||
expect(readDb(store.map).rows.find((r) => r.id === "b")!.cells.s).toBe("Done");
|
||||
store.deleteColumn("s");
|
||||
expect(store.snapshot().columns.map((c) => c.id)).toEqual(["t", "p"]);
|
||||
});
|
||||
|
||||
it("merges concurrent edits to different cells of a row", () => {
|
||||
const a = new Y.Doc();
|
||||
seedDb(a, "db", sample(), () => {});
|
||||
const b = new Y.Doc();
|
||||
Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
|
||||
new DbStore(a, blocksOf(a).get("db")!, () => null).setCell("a", "t", "Write more");
|
||||
new DbStore(b, blocksOf(b).get("db")!, () => null).setCell("a", "p", 13);
|
||||
Y.applyUpdate(a, Y.encodeStateAsUpdate(b));
|
||||
Y.applyUpdate(b, Y.encodeStateAsUpdate(a));
|
||||
for (const d of [a, b]) {
|
||||
expect(readDb(blocksOf(d).get("db")!).rows[0]!.cells).toEqual({ t: "Write more", s: "todo", p: 13 });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// Small DOM helpers for the database block, which (like the rest of the
|
||||
// editor's blocks) draws plain DOM so it also runs in the mobile bridge.
|
||||
|
||||
import { autoUpdate, computePosition, flip, offset, shift, type Placement } from "@floating-ui/dom";
|
||||
import type { IconName } from "@docwell/ui/icons";
|
||||
import { svgIcon } from "../suggestion";
|
||||
|
||||
type Child = Node | string | null | undefined | false;
|
||||
type Props = Record<string, unknown> & {
|
||||
class?: string;
|
||||
on?: Partial<{ [K in keyof HTMLElementEventMap]: (e: HTMLElementEventMap[K]) => void }>;
|
||||
dataset?: Record<string, string>;
|
||||
style?: Partial<CSSStyleDeclaration>;
|
||||
};
|
||||
|
||||
/** Makes an element: h("button", { class: "x", on: { click } }, "Text"). */
|
||||
export function h<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
props: Props = {},
|
||||
...children: (Child | Child[])[]
|
||||
): HTMLElementTagNameMap[K] {
|
||||
const el = document.createElement(tag);
|
||||
for (const [k, v] of Object.entries(props)) {
|
||||
if (v === undefined || v === null || v === false) continue;
|
||||
if (k === "class") el.className = String(v);
|
||||
else if (k === "on") {
|
||||
for (const [ev, fn] of Object.entries(v as Record<string, EventListener>)) el.addEventListener(ev, fn);
|
||||
} else if (k === "dataset") Object.assign(el.dataset, v);
|
||||
else if (k === "style") Object.assign(el.style, v);
|
||||
else if (k in el && typeof v !== "string") (el as unknown as Record<string, unknown>)[k] = v;
|
||||
else el.setAttribute(k, v === true ? "" : String(v));
|
||||
}
|
||||
for (const c of children.flat()) {
|
||||
if (c === null || c === undefined || c === false) continue;
|
||||
el.append(c);
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
export function icon(name: IconName, size = 16): SVGSVGElement {
|
||||
return svgIcon(name, size);
|
||||
}
|
||||
|
||||
/** A small button with an icon and, optionally, text; label is its accessible name. */
|
||||
export function iconButton(name: IconName, label: string, onClick: (e: MouseEvent) => void, text?: string) {
|
||||
const b = h(
|
||||
"button",
|
||||
{ type: "button", class: text ? "dw-db__btn" : "dw-db__btn dw-db__btn--icon", title: label, "aria-label": label },
|
||||
icon(name, 15),
|
||||
text ? h("span", {}, text) : null,
|
||||
);
|
||||
b.addEventListener("click", (e) => {
|
||||
e.preventDefault();
|
||||
onClick(e);
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
export interface Popover {
|
||||
box: HTMLDivElement;
|
||||
close: () => void;
|
||||
}
|
||||
|
||||
let current: Popover | null = null;
|
||||
|
||||
/**
|
||||
* A floating panel next to anchor (one at a time). Escape or a click outside
|
||||
* closes it; onClose runs once. The panel's content is up to the caller.
|
||||
*/
|
||||
export function popover(
|
||||
anchor: Element,
|
||||
fill: (box: HTMLDivElement, close: () => void) => void,
|
||||
opts: { placement?: Placement; class?: string; onClose?: () => void; label?: string } = {},
|
||||
): Popover {
|
||||
current?.close();
|
||||
const box = h("div", { class: `dw-db-pop ${opts.class ?? ""}`, role: "dialog", "aria-label": opts.label });
|
||||
let closed = false;
|
||||
const close = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
stop();
|
||||
box.remove();
|
||||
document.removeEventListener("mousedown", onDown, true);
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
if (current?.box === box) current = null;
|
||||
opts.onClose?.();
|
||||
};
|
||||
const onDown = (e: MouseEvent) => {
|
||||
const t = e.target as Node;
|
||||
// Menus opened from this panel (block menus, other popovers) are siblings in body.
|
||||
if (box.contains(t) || anchor.contains(t) || (t instanceof Element && t.closest(".dw-block-menu"))) return;
|
||||
close();
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape" && !document.querySelector(".dw-block-menu")) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
close();
|
||||
if (anchor instanceof HTMLElement) anchor.focus();
|
||||
}
|
||||
};
|
||||
document.body.append(box);
|
||||
const stop = autoUpdate(anchor, box, () => {
|
||||
void computePosition(anchor, box, {
|
||||
placement: opts.placement ?? "bottom-start",
|
||||
strategy: "fixed",
|
||||
middleware: [offset(4), flip(), shift({ padding: 8 })],
|
||||
}).then(({ x, y }) => Object.assign(box.style, { left: `${x}px`, top: `${y}px` }));
|
||||
});
|
||||
document.addEventListener("mousedown", onDown, true);
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
fill(box, close);
|
||||
current = { box, close };
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Closes the open popover, if any. */
|
||||
export function closePopover() {
|
||||
current?.close();
|
||||
}
|
||||
|
||||
/** A text input that commits on Enter or blur and cancels on Escape. */
|
||||
export function textInput(
|
||||
value: string,
|
||||
opts: { placeholder?: string; label?: string; class?: string; type?: string; onCommit: (v: string) => void; onCancel?: () => void },
|
||||
): HTMLInputElement {
|
||||
const input = h("input", {
|
||||
type: opts.type ?? "text",
|
||||
class: opts.class ?? "dw-db-input",
|
||||
placeholder: opts.placeholder,
|
||||
"aria-label": opts.label ?? opts.placeholder,
|
||||
});
|
||||
input.value = value;
|
||||
let done = false;
|
||||
const commit = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
opts.onCommit(input.value);
|
||||
};
|
||||
input.addEventListener("keydown", (e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
commit();
|
||||
} else if (e.key === "Escape") {
|
||||
done = true;
|
||||
opts.onCancel?.();
|
||||
}
|
||||
});
|
||||
input.addEventListener("blur", commit);
|
||||
return input;
|
||||
}
|
||||
|
||||
/** Offers a file for download. */
|
||||
export function download(name: string, text: string, mime: string) {
|
||||
const url = URL.createObjectURL(new Blob([text], { type: mime }));
|
||||
const a = h("a", { href: url, download: name });
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Opens the system file picker for one file. */
|
||||
export function pickFile(accept: string): Promise<File | null> {
|
||||
return new Promise((resolve) => {
|
||||
const input = h("input", { type: "file", accept });
|
||||
input.onchange = () => resolve(input.files?.[0] ?? null);
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// The database block (ADR-13). The node keeps only an id; its records live
|
||||
// in ydoc.getMap("blocks"). Editors without a live document (share links,
|
||||
// history previews) draw it read-only from the node's data attribute, which
|
||||
// the server fills in when it turns the document into JSON.
|
||||
|
||||
import { Editor, mergeAttributes, Node, type AnyExtension, type JSONContent } from "@tiptap/core";
|
||||
import { Fragment, Slice, type Node as PMNode } from "@tiptap/pm/model";
|
||||
import { NodeSelection, Plugin, PluginKey } from "@tiptap/pm/state";
|
||||
import { prosemirrorJSONToYXmlFragment, ySyncPluginKey, yUndoPluginKey, yXmlFragmentToProsemirrorJSON } from "@tiptap/y-tiptap";
|
||||
import * as Y from "yjs";
|
||||
import type { FileHost } from "../files";
|
||||
import { englishLabels, type EditorLabels } from "../labels";
|
||||
import type { MentionHost } from "../mention";
|
||||
import { h } from "./dom";
|
||||
import { cellText, defaultView, newId, normalize, titleColumn, type Column, type DbData, type Person, type Row } from "./model";
|
||||
import { RowPeek } from "./peek";
|
||||
import { blocksOf, DbStore, emptyDb, exportDb, readDb, seedDb } from "./store";
|
||||
import { DatabaseView } from "./view";
|
||||
import { typeLabel } from "./labels";
|
||||
|
||||
export interface DatabaseOptions {
|
||||
labels: EditorLabels | null;
|
||||
/** The page's live document; without it databases show read-only from their data attribute. */
|
||||
doc?: Y.Doc;
|
||||
/** The document is shown read-only (a synced page). */
|
||||
readOnlyDoc?: boolean;
|
||||
/** Adds database edits to the editor's undo history (not in row bodies, whose page has it). */
|
||||
undoScope?: boolean;
|
||||
files?: FileHost;
|
||||
people?: MentionHost;
|
||||
/** The signed-in person, recorded as the creator of new rows. */
|
||||
me?: () => Person | null;
|
||||
/**
|
||||
* The extensions of a row body's editor: bound to fragment, or (null) for
|
||||
* a read-only body from JSON.
|
||||
*/
|
||||
rowExtensions?: (fragment: Y.XmlFragment | null) => AnyExtension[];
|
||||
/** Shows a short message, e.g. "Copied 6 cells". */
|
||||
notify?: (text: string) => void;
|
||||
}
|
||||
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
database: {
|
||||
/** Inserts a database; data defaults to an empty one. */
|
||||
insertDatabase: (data?: DbData) => ReturnType;
|
||||
/** Turns the list (or paragraphs) around the selection into a database, one row per item. */
|
||||
groupAsDatabase: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const dbLabels = (l: EditorLabels | null) => (l ?? englishLabels).database;
|
||||
|
||||
function dbDefaults(l: EditorLabels | null) {
|
||||
const d = dbLabels(l);
|
||||
return { tableView: d.viewTable, columnName: (t: Column["type"]) => (t === "title" ? d.typeTitle : typeLabel(d, t)) };
|
||||
}
|
||||
|
||||
/** The ProseMirror JSON of a row body fragment, as nodes. */
|
||||
const bodyJSON = (f: Y.XmlFragment) => (yXmlFragmentToProsemirrorJSON(f).content as unknown[] | undefined) ?? [];
|
||||
|
||||
/** Copies database nodes in a fragment through fn (copy and paste). */
|
||||
function mapDatabases(fragment: Fragment, fn: (node: PMNode) => PMNode): Fragment {
|
||||
const out: PMNode[] = [];
|
||||
fragment.forEach((child) => {
|
||||
if (child.type.name === "database") out.push(fn(child));
|
||||
else if (child.content.size) out.push(child.copy(mapDatabases(child.content, fn)));
|
||||
else out.push(child);
|
||||
});
|
||||
return Fragment.from(out);
|
||||
}
|
||||
|
||||
function hasDatabase(fragment: Fragment): boolean {
|
||||
let found = false;
|
||||
fragment.descendants((n) => {
|
||||
if (n.type.name === "database") found = true;
|
||||
return !found;
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export const Database = Node.create<DatabaseOptions>({
|
||||
name: "database",
|
||||
group: "block",
|
||||
atom: true,
|
||||
draggable: true,
|
||||
selectable: true,
|
||||
|
||||
addOptions() {
|
||||
return {
|
||||
labels: null,
|
||||
doc: undefined,
|
||||
readOnlyDoc: false,
|
||||
undoScope: true,
|
||||
files: undefined,
|
||||
people: undefined,
|
||||
me: undefined,
|
||||
rowExtensions: undefined,
|
||||
notify: undefined,
|
||||
};
|
||||
},
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
id: {
|
||||
default: "",
|
||||
parseHTML: (el) => el.getAttribute("data-id") ?? "",
|
||||
renderHTML: (a) => ({ "data-id": a.id }),
|
||||
},
|
||||
// The records as JSON, only where there is no live map: read-only
|
||||
// readers, the clipboard, and documents written by the server.
|
||||
data: {
|
||||
default: null,
|
||||
parseHTML: (el) => {
|
||||
try {
|
||||
const raw = el.getAttribute("data-db");
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
renderHTML: (a) => (a.data ? { "data-db": JSON.stringify(a.data) } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [{ tag: "div[data-type='database']" }];
|
||||
},
|
||||
|
||||
// As HTML (copying to other apps), a database is a table of its records.
|
||||
renderHTML({ node, HTMLAttributes }) {
|
||||
const attrs = mergeAttributes(HTMLAttributes, { "data-type": "database" });
|
||||
if (!node.attrs.data) return ["div", attrs];
|
||||
const db = normalize(node.attrs.data);
|
||||
const view = db.views[0];
|
||||
const cols = db.columns.filter((c) => c.type === "title" || !view?.hidden.includes(c.id));
|
||||
return [
|
||||
"div",
|
||||
attrs,
|
||||
["p", {}, ["strong", {}, db.title || dbLabels(this.options.labels).untitled]],
|
||||
[
|
||||
"table",
|
||||
{},
|
||||
["tr", {}, ...cols.map((c) => ["th", {}, c.name])],
|
||||
...db.rows.map((r) => ["tr", {}, ...cols.map((c) => ["td", {}, cellText(r, c)])]),
|
||||
],
|
||||
];
|
||||
},
|
||||
|
||||
renderText({ node }) {
|
||||
const db = node.attrs.data ? normalize(node.attrs.data) : null;
|
||||
if (!db) return "";
|
||||
const title = titleColumn(db);
|
||||
return [db.title, ...db.rows.map((r) => cellText(r, title))].filter(Boolean).join("\n");
|
||||
},
|
||||
|
||||
onCreate() {
|
||||
const { doc, readOnlyDoc, undoScope } = this.options;
|
||||
if (!doc || readOnlyDoc || !undoScope) return;
|
||||
// Database edits are undone with the page's own Ctrl+Z.
|
||||
const um = yUndoPluginKey.getState(this.editor.state)?.undoManager as Y.UndoManager | undefined;
|
||||
um?.addToScope(blocksOf(doc));
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
/** A new node's attributes. With a live document the map goes in first, so peers never see a node without data. */
|
||||
const attrsFor = (db: DbData) => {
|
||||
const id = newId();
|
||||
const { doc, readOnlyDoc } = this.options;
|
||||
if (!doc || readOnlyDoc) return { id, data: db };
|
||||
seedDb(doc, id, db, (json, f) => writeBody(this.editor, json, f));
|
||||
return { id, data: null };
|
||||
};
|
||||
return {
|
||||
insertDatabase:
|
||||
(data) =>
|
||||
({ commands }) =>
|
||||
commands.insertContent([
|
||||
{ type: this.name, attrs: attrsFor(data ?? emptyDb(dbDefaults(this.options.labels))) },
|
||||
{ type: "paragraph" },
|
||||
]),
|
||||
groupAsDatabase:
|
||||
() =>
|
||||
({ state, dispatch, commands }) => {
|
||||
const found = listAt(state.selection.$from, state.selection.$to);
|
||||
if (!found) return false;
|
||||
if (!dispatch) return true;
|
||||
const l = dbLabels(this.options.labels);
|
||||
const title: Column = { id: newId(), name: l.typeTitle, type: "title" };
|
||||
const columns: Column[] = [title];
|
||||
const done: Column | null = found.checks ? { id: newId(), name: l.done, type: "checkbox" } : null;
|
||||
if (done) columns.push(done);
|
||||
const now = Date.now();
|
||||
const rows: Row[] = found.items.map((it, i) => ({
|
||||
id: newId(),
|
||||
cells: { [title.id]: it.text, ...(done && it.checked ? { [done.id]: true } : {}) },
|
||||
createdAt: now + i,
|
||||
createdBy: this.options.me?.() ?? null,
|
||||
body: it.rest.length ? it.rest : undefined,
|
||||
}));
|
||||
const db: DbData = { title: "", columns, rows, views: [defaultView("table", l.viewTable, columns)] };
|
||||
const node = this.type.create(attrsFor(db));
|
||||
return commands.command(({ tr }) => {
|
||||
// The list itself is replaced, whatever sits next to it.
|
||||
tr.replaceWith(found.from, found.to, node);
|
||||
tr.setSelection(NodeSelection.create(tr.doc, found.from));
|
||||
return true;
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
addKeyboardShortcuts() {
|
||||
return {
|
||||
"Mod-g": () => this.editor.commands.groupAsDatabase(),
|
||||
};
|
||||
},
|
||||
|
||||
addProseMirrorPlugins() {
|
||||
const { doc, readOnlyDoc } = this.options;
|
||||
const live = doc && !readOnlyDoc ? doc : null;
|
||||
const editor = this.editor;
|
||||
return [
|
||||
new Plugin({
|
||||
key: new PluginKey("databaseClipboard"),
|
||||
props: {
|
||||
// A copied database carries its records, so it pastes as its own copy.
|
||||
transformCopied: (slice) => {
|
||||
if (!doc || !hasDatabase(slice.content)) return slice;
|
||||
const content = mapDatabases(slice.content, (n) => {
|
||||
const m = blocksOf(doc).get(String(n.attrs.id));
|
||||
return m instanceof Y.Map ? n.type.create({ ...n.attrs, data: exportDb(m, bodyJSON) }) : n;
|
||||
});
|
||||
return new Slice(content, slice.openStart, slice.openEnd);
|
||||
},
|
||||
transformPasted: (slice) => {
|
||||
if (!hasDatabase(slice.content)) return slice;
|
||||
const content = mapDatabases(slice.content, (n) => {
|
||||
const id = newId();
|
||||
if (!live) return n.type.create({ ...n.attrs, id });
|
||||
const source = n.attrs.data ? normalize(n.attrs.data) : null;
|
||||
const m = blocksOf(live).get(String(n.attrs.id));
|
||||
const data = source ?? (m instanceof Y.Map ? exportDb(m, bodyJSON) : emptyDb(dbDefaults(this.options.labels)));
|
||||
seedDb(live, id, freshIds(data), (json, f) => writeBody(editor, json, f));
|
||||
return n.type.create({ id, data: null });
|
||||
});
|
||||
return new Slice(content, slice.openStart, slice.openEnd);
|
||||
},
|
||||
},
|
||||
// Two nodes never share one map: a duplicated block gets a copy of the records.
|
||||
appendTransaction: (trs, _old, state) => {
|
||||
if (!live || !trs.some((tr) => tr.docChanged && !tr.getMeta(ySyncPluginKey))) return null;
|
||||
if (!trs.some((tr) => tr.steps.some((s) => hasDatabase((s as unknown as { slice?: Slice }).slice?.content ?? Fragment.empty)))) return null;
|
||||
const seen = new Set<string>();
|
||||
const fix: { pos: number; node: PMNode }[] = [];
|
||||
state.doc.descendants((n, pos) => {
|
||||
if (n.type.name !== "database") return;
|
||||
const id = String(n.attrs.id);
|
||||
if (id && seen.has(id)) fix.push({ pos, node: n });
|
||||
seen.add(id);
|
||||
return false;
|
||||
});
|
||||
if (!fix.length) return null;
|
||||
const tr = state.tr;
|
||||
for (const { pos, node } of fix) {
|
||||
const m = blocksOf(live).get(String(node.attrs.id));
|
||||
const id = newId();
|
||||
if (m instanceof Y.Map) seedDb(live, id, freshIds(exportDb(m, bodyJSON)), (json, f) => writeBody(editor, json, f));
|
||||
tr.setNodeMarkup(pos, undefined, { ...node.attrs, id, data: null });
|
||||
}
|
||||
return tr;
|
||||
},
|
||||
}),
|
||||
];
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
const opts = this.options;
|
||||
return ({ node: initial, editor, getPos }) => {
|
||||
let node = initial;
|
||||
const labels = opts.labels ?? englishLabels;
|
||||
const doc = opts.doc;
|
||||
const canEdit = () => editor.isEditable && !!doc && !opts.readOnlyDoc;
|
||||
|
||||
let store: DbStore | null = null;
|
||||
let stop: (() => void) | null = null;
|
||||
let peek: RowPeek | null = null;
|
||||
let view: DatabaseView | null = null;
|
||||
const wrap = h("div", { class: "dw-db-node" });
|
||||
|
||||
const id = () => String(node.attrs.id);
|
||||
const mapOf = () => {
|
||||
const m = doc ? blocksOf(doc).get(id()) : undefined;
|
||||
return m instanceof Y.Map ? m : null;
|
||||
};
|
||||
const snapshot = (): DbData => {
|
||||
const m = mapOf();
|
||||
if (m) return readDb(m);
|
||||
return node.attrs.data ? normalize(node.attrs.data) : emptyDb(dbDefaults(opts.labels));
|
||||
};
|
||||
|
||||
const host = () => ({
|
||||
labels: labels.database,
|
||||
colorNames: labels.colors,
|
||||
locale: labels.locale,
|
||||
files: opts.files,
|
||||
people: opts.people,
|
||||
store,
|
||||
});
|
||||
|
||||
const mountBody = (el: HTMLElement, row: Row) => {
|
||||
const make = opts.rowExtensions;
|
||||
if (!make) return null;
|
||||
const m = mapOf();
|
||||
let fragment: Y.XmlFragment | null = null;
|
||||
if (m) {
|
||||
fragment = store ? store.rowBody(row.id) : findBody(m, row.id);
|
||||
if (!fragment) {
|
||||
el.append(h("p", { class: "dw-db-peek__note" }, labels.database.bodyReadOnly));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
const editable = !!store;
|
||||
const ed = new Editor({
|
||||
element: el,
|
||||
editable,
|
||||
extensions: make(fragment),
|
||||
content: fragment ? undefined : { type: "doc", content: (row.body as JSONContent[] | undefined) ?? [{ type: "paragraph" }] },
|
||||
editorProps: { attributes: { class: "dw-prose dw-db-peek__prose" } },
|
||||
});
|
||||
if (!fragment && !row.body?.length) el.replaceChildren(h("p", { class: "dw-db-peek__note" }, labels.database.bodyReadOnly));
|
||||
return () => ed.destroy();
|
||||
};
|
||||
|
||||
const openRow = (rowId: string, order: string[]) => {
|
||||
peek?.close();
|
||||
peek = new RowPeek({ ctx: { ...host(), }, mountBody }, snapshot(), rowId, order, () => (peek = null));
|
||||
};
|
||||
|
||||
const refresh = () => {
|
||||
const db = snapshot();
|
||||
view?.update(db, { store });
|
||||
peek?.update(db, { store });
|
||||
};
|
||||
|
||||
/** Binds to the database's map, making it when an editor finds none. */
|
||||
const bind = () => {
|
||||
stop?.();
|
||||
stop = null;
|
||||
store = null;
|
||||
if (!doc) return;
|
||||
let m = mapOf();
|
||||
if (!m && canEdit()) {
|
||||
const data = node.attrs.data ? normalize(node.attrs.data) : emptyDb(dbDefaults(opts.labels));
|
||||
const newIdNeeded = !id();
|
||||
const key = newIdNeeded ? newId() : id();
|
||||
seedDb(doc, key, data, (json, f) => writeBody(editor, json, f));
|
||||
// Keep only the id in the document from now on.
|
||||
queueMicrotask(() => {
|
||||
const pos = typeof getPos === "function" ? getPos() : undefined;
|
||||
if (pos !== undefined && editor.state.doc.nodeAt(pos)?.type.name === "database") {
|
||||
editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, id: key, data: null }).setMeta("addToHistory", false));
|
||||
}
|
||||
});
|
||||
m = blocksOf(doc).get(key) as Y.Map<unknown>;
|
||||
}
|
||||
if (m) {
|
||||
if (canEdit()) store = new DbStore(doc, m, () => opts.me?.() ?? null);
|
||||
const watched = m;
|
||||
const h1 = () => refresh();
|
||||
watched.observeDeep(h1);
|
||||
stop = () => watched.unobserveDeep(h1);
|
||||
} else {
|
||||
// A peer's map may still be on its way.
|
||||
const blocks = blocksOf(doc);
|
||||
const h2 = (e: Y.YMapEvent<Y.Map<unknown>>) => {
|
||||
if (e.keysChanged.has(id())) {
|
||||
bind();
|
||||
refresh();
|
||||
}
|
||||
};
|
||||
blocks.observe(h2);
|
||||
stop = () => blocks.unobserve(h2);
|
||||
}
|
||||
};
|
||||
bind();
|
||||
|
||||
view = new DatabaseView(
|
||||
{
|
||||
...host(),
|
||||
openRow,
|
||||
undo: () => editor.commands.undo?.(),
|
||||
redo: () => editor.commands.redo?.(),
|
||||
notify: opts.notify,
|
||||
},
|
||||
snapshot(),
|
||||
);
|
||||
wrap.append(view.dom);
|
||||
|
||||
let wasEditable = canEdit();
|
||||
const onEditable = () => {
|
||||
if (canEdit() === wasEditable) return;
|
||||
wasEditable = canEdit();
|
||||
bind();
|
||||
refresh();
|
||||
};
|
||||
editor.on("update", onEditable);
|
||||
editor.on("transaction", onEditable);
|
||||
|
||||
return {
|
||||
dom: wrap,
|
||||
update(next) {
|
||||
if (next.type !== node.type) return false;
|
||||
const changed = next.attrs.id !== node.attrs.id;
|
||||
node = next;
|
||||
if (changed) bind();
|
||||
refresh();
|
||||
return true;
|
||||
},
|
||||
ignoreMutation: () => true,
|
||||
// The block handles its own clicks, keys, drags and clipboard, except the drag of the whole block.
|
||||
stopEvent: (e) => !(e.type === "dragstart" && (e.target as HTMLElement) === wrap),
|
||||
destroy() {
|
||||
stop?.();
|
||||
peek?.close();
|
||||
view?.destroy();
|
||||
editor.off("update", onEditable);
|
||||
editor.off("transaction", onEditable);
|
||||
},
|
||||
};
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
/** Writes ProseMirror nodes into a row body fragment with the editor's schema. */
|
||||
function writeBody(editor: Editor, json: unknown[], f: Y.XmlFragment) {
|
||||
try {
|
||||
prosemirrorJSONToYXmlFragment(editor.schema, { type: "doc", content: json }, f);
|
||||
} catch {
|
||||
/* a body with nodes this editor does not know stays empty */
|
||||
}
|
||||
}
|
||||
|
||||
function findBody(m: Y.Map<unknown>, rowId: string): Y.XmlFragment | null {
|
||||
const rows = m.get("rows");
|
||||
if (!(rows instanceof Y.Array)) return null;
|
||||
for (const r of rows.toArray() as Y.Map<unknown>[]) {
|
||||
if (r.get("id") === rowId) {
|
||||
const b = r.get("body");
|
||||
return b instanceof Y.XmlFragment && b.length ? b : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A copy of a database with new row ids (column and view ids stay, they are local to it). */
|
||||
function freshIds(db: DbData): DbData {
|
||||
return { ...db, rows: db.rows.map((r) => ({ ...r, id: newId() })) };
|
||||
}
|
||||
|
||||
interface ListFound {
|
||||
from: number;
|
||||
to: number;
|
||||
checks: boolean;
|
||||
items: { text: string; checked: boolean; rest: JSONContent[] }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The list around the selection (or the top-level blocks it spans) as items:
|
||||
* each item's first line is its title, the rest its body.
|
||||
*/
|
||||
function listAt($from: import("@tiptap/pm/model").ResolvedPos, $to: import("@tiptap/pm/model").ResolvedPos): ListFound | null {
|
||||
for (let d = $from.depth; d > 0; d--) {
|
||||
const n = $from.node(d);
|
||||
if (["bulletList", "orderedList", "taskList"].includes(n.type.name)) {
|
||||
const items: ListFound["items"] = [];
|
||||
n.forEach((item) => {
|
||||
const first = item.firstChild;
|
||||
const rest: JSONContent[] = [];
|
||||
item.forEach((c, _o, i) => {
|
||||
if (i > 0) rest.push(c.toJSON() as JSONContent);
|
||||
});
|
||||
items.push({ text: first?.textContent ?? "", checked: !!item.attrs.checked, rest });
|
||||
});
|
||||
return { from: $from.before(d), to: $from.after(d), checks: n.type.name === "taskList", items };
|
||||
}
|
||||
}
|
||||
if ($from.depth < 1) return null;
|
||||
const from = $from.before(1);
|
||||
const to = $to.after(Math.min(1, $to.depth) || 1);
|
||||
const items: ListFound["items"] = [];
|
||||
$from.doc.nodesBetween(from, to, (n, pos) => {
|
||||
if (pos < from || pos >= to) return false;
|
||||
if (n.isTextblock && n.textContent.trim()) items.push({ text: n.textContent, checked: false, rest: [] });
|
||||
return !n.isTextblock;
|
||||
});
|
||||
return items.length > 1 ? { from, to, checks: false, items } : null;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import type { ColumnType, FilterOp, ViewType } from "./model";
|
||||
|
||||
/** The database block's words. "{n}" is filled in by the editor. */
|
||||
export const englishDatabaseLabels = {
|
||||
database: "Database",
|
||||
untitled: "Untitled database",
|
||||
untitledRow: "Untitled",
|
||||
newRow: "New record",
|
||||
addColumn: "Add property",
|
||||
columnName: "Property name",
|
||||
search: "Search records",
|
||||
filter: "Filter",
|
||||
sort: "Sort",
|
||||
group: "Group",
|
||||
properties: "Properties",
|
||||
more: "More",
|
||||
addView: "Add view",
|
||||
viewName: "View name",
|
||||
renameView: "Rename view",
|
||||
duplicateView: "Duplicate view",
|
||||
deleteView: "Delete view",
|
||||
layout: "Layout",
|
||||
viewTable: "Table",
|
||||
viewKanban: "Kanban",
|
||||
viewCalendar: "Calendar",
|
||||
noValue: "No value",
|
||||
checked: "Checked",
|
||||
unchecked: "Unchecked",
|
||||
noRows: "No records",
|
||||
noMatches: "No records match",
|
||||
rename: "Rename",
|
||||
type: "Type",
|
||||
hide: "Hide in view",
|
||||
show: "Show in view",
|
||||
sortAscending: "Sort ascending",
|
||||
sortDescending: "Sort descending",
|
||||
filterBy: "Filter by this property",
|
||||
insertLeft: "Insert left",
|
||||
insertRight: "Insert right",
|
||||
moveLeft: "Move left",
|
||||
moveRight: "Move right",
|
||||
duplicate: "Duplicate",
|
||||
deleteColumn: "Delete property",
|
||||
typeTitle: "Title",
|
||||
typeText: "Text",
|
||||
typeNumber: "Number",
|
||||
typeCheckbox: "Checkbox",
|
||||
typeSelect: "Select",
|
||||
typeMultiSelect: "Multi-select",
|
||||
typeDate: "Date",
|
||||
typeProgress: "Progress",
|
||||
typeLink: "Link",
|
||||
typeAttachment: "Attachment",
|
||||
typeMember: "Member",
|
||||
typeCreatedTime: "Created time",
|
||||
typeCreatedBy: "Created by",
|
||||
opContains: "contains",
|
||||
opNotContains: "does not contain",
|
||||
opIs: "is",
|
||||
opIsNot: "is not",
|
||||
opIsEmpty: "is empty",
|
||||
opIsNotEmpty: "is not empty",
|
||||
opGt: "is greater than",
|
||||
opLt: "is less than",
|
||||
opGte: "is at least",
|
||||
opLte: "is at most",
|
||||
opBefore: "is before",
|
||||
opAfter: "is after",
|
||||
opChecked: "is checked",
|
||||
opUnchecked: "is not checked",
|
||||
addFilter: "Add filter",
|
||||
matchAll: "Every filter matches",
|
||||
matchAny: "Any filter matches",
|
||||
remove: "Remove",
|
||||
value: "Value",
|
||||
noFilters: "No filters yet",
|
||||
addSort: "Add sort",
|
||||
ascending: "Ascending",
|
||||
descending: "Descending",
|
||||
noSorts: "No sorts yet",
|
||||
groupBy: "Group by",
|
||||
noGrouping: "No grouping",
|
||||
showAll: "Show all",
|
||||
hideAll: "Hide all",
|
||||
dateColumn: "Date property",
|
||||
today: "Today",
|
||||
previousMonth: "Previous month",
|
||||
nextMonth: "Next month",
|
||||
noDateColumn: "Add a date property to place records on the calendar.",
|
||||
noDate: "No date ({n})",
|
||||
noGroupColumn: "Add a select, checkbox or member property to sort cards into columns.",
|
||||
openRow: "Open",
|
||||
deleteRow: "Delete record",
|
||||
duplicateRow: "Duplicate record",
|
||||
insertAbove: "Insert above",
|
||||
insertBelow: "Insert below",
|
||||
deleteRows: "Delete",
|
||||
selected: "{n} selected",
|
||||
selectRow: "Select record",
|
||||
dragRow: "Drag to move",
|
||||
close: "Close",
|
||||
expand: "Full width",
|
||||
collapse: "Narrow",
|
||||
previousRow: "Previous record",
|
||||
nextRow: "Next record",
|
||||
bodyPlaceholder: "Write about this record…",
|
||||
bodyReadOnly: "This record has no notes.",
|
||||
searchOptions: "Find or create a choice",
|
||||
createOption: "Create “{n}”",
|
||||
optionColor: "Colour",
|
||||
deleteOption: "Delete choice",
|
||||
renameOption: "Rename choice",
|
||||
searchPeople: "Find a person",
|
||||
noPeople: "Nobody found",
|
||||
upload: "Upload a file",
|
||||
linkPlaceholder: "Paste a link",
|
||||
clear: "Clear",
|
||||
exportCsv: "Export as CSV",
|
||||
importCsv: "Import CSV",
|
||||
imported: "Added {n} records",
|
||||
copyNotice: "Copied {n} cells",
|
||||
readOnly: "Only people who can edit the page can change this database.",
|
||||
resize: "Drag to change the width",
|
||||
groupAsDatabase: "Group as database",
|
||||
done: "Done",
|
||||
};
|
||||
|
||||
export type DatabaseLabels = typeof englishDatabaseLabels;
|
||||
|
||||
const typeKeys: Record<ColumnType, keyof DatabaseLabels> = {
|
||||
title: "typeTitle",
|
||||
text: "typeText",
|
||||
number: "typeNumber",
|
||||
checkbox: "typeCheckbox",
|
||||
select: "typeSelect",
|
||||
multiSelect: "typeMultiSelect",
|
||||
date: "typeDate",
|
||||
progress: "typeProgress",
|
||||
link: "typeLink",
|
||||
attachment: "typeAttachment",
|
||||
member: "typeMember",
|
||||
createdTime: "typeCreatedTime",
|
||||
createdBy: "typeCreatedBy",
|
||||
};
|
||||
|
||||
export const typeLabel = (l: DatabaseLabels, t: ColumnType) => l[typeKeys[t]];
|
||||
|
||||
const opKeys: Record<FilterOp, keyof DatabaseLabels> = {
|
||||
contains: "opContains",
|
||||
notContains: "opNotContains",
|
||||
is: "opIs",
|
||||
isNot: "opIsNot",
|
||||
isEmpty: "opIsEmpty",
|
||||
isNotEmpty: "opIsNotEmpty",
|
||||
gt: "opGt",
|
||||
lt: "opLt",
|
||||
gte: "opGte",
|
||||
lte: "opLte",
|
||||
before: "opBefore",
|
||||
after: "opAfter",
|
||||
checked: "opChecked",
|
||||
unchecked: "opUnchecked",
|
||||
};
|
||||
|
||||
export const opLabel = (l: DatabaseLabels, op: FilterOp) => l[opKeys[op]];
|
||||
|
||||
export const viewLabel = (l: DatabaseLabels, t: ViewType) =>
|
||||
t === "kanban" ? l.viewKanban : t === "calendar" ? l.viewCalendar : l.viewTable;
|
||||
|
||||
export const fill = (s: string, n: number | string) => s.replace("{n}", String(n));
|
||||
@@ -0,0 +1,594 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// The shape of a database block (ADR-13) and the pure rules over it: how a
|
||||
// cell reads as text, filtering, sorting, grouping and changing a column's
|
||||
// type. The live data is a Y.Map (store.ts); views render a plain snapshot.
|
||||
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { isPaletteColor, palette, type PaletteColor } from "../colors";
|
||||
|
||||
export const columnTypes = [
|
||||
"title",
|
||||
"text",
|
||||
"number",
|
||||
"checkbox",
|
||||
"select",
|
||||
"multiSelect",
|
||||
"date",
|
||||
"progress",
|
||||
"link",
|
||||
"attachment",
|
||||
"member",
|
||||
"createdTime",
|
||||
"createdBy",
|
||||
] as const;
|
||||
export type ColumnType = (typeof columnTypes)[number];
|
||||
|
||||
/** Types a column can be changed to (the title column stays the title). */
|
||||
export const editableTypes = columnTypes.filter((t) => t !== "title");
|
||||
|
||||
export interface SelectOption {
|
||||
id: string;
|
||||
name: string;
|
||||
color: PaletteColor;
|
||||
}
|
||||
|
||||
export interface Column {
|
||||
id: string;
|
||||
name: string;
|
||||
type: ColumnType;
|
||||
/** The choices of a select or multi-select column. */
|
||||
options?: SelectOption[];
|
||||
}
|
||||
|
||||
export interface Person {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Attachment {
|
||||
name: string;
|
||||
src: string;
|
||||
size?: number;
|
||||
mime?: string;
|
||||
}
|
||||
|
||||
export interface Row {
|
||||
id: string;
|
||||
cells: Record<string, unknown>;
|
||||
/** Milliseconds since the epoch. */
|
||||
createdAt: number;
|
||||
createdBy: Person | null;
|
||||
/** Whether the row was opened as a page and has a body. */
|
||||
hasBody?: boolean;
|
||||
/** The body as ProseMirror nodes, in snapshots read from JSON (see ADR-13). */
|
||||
body?: JSONContent[];
|
||||
}
|
||||
|
||||
export const viewTypes = ["table", "kanban", "calendar"] as const;
|
||||
export type ViewType = (typeof viewTypes)[number];
|
||||
|
||||
export type FilterOp =
|
||||
| "contains"
|
||||
| "notContains"
|
||||
| "is"
|
||||
| "isNot"
|
||||
| "isEmpty"
|
||||
| "isNotEmpty"
|
||||
| "gt"
|
||||
| "lt"
|
||||
| "gte"
|
||||
| "lte"
|
||||
| "before"
|
||||
| "after"
|
||||
| "checked"
|
||||
| "unchecked";
|
||||
|
||||
export interface Filter {
|
||||
column: string;
|
||||
op: FilterOp;
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export interface Sort {
|
||||
column: string;
|
||||
desc: boolean;
|
||||
}
|
||||
|
||||
export interface View {
|
||||
id: string;
|
||||
name: string;
|
||||
type: ViewType;
|
||||
/** Column ids the view leaves out. */
|
||||
hidden: string[];
|
||||
filters: Filter[];
|
||||
/** Whether a row must match every filter or any. */
|
||||
filterMode: "and" | "or";
|
||||
sorts: Sort[];
|
||||
/** The column rows are grouped by (kanban always groups). */
|
||||
groupBy: string | null;
|
||||
/** The date column a calendar places rows by. */
|
||||
dateColumn: string | null;
|
||||
/** Column widths in pixels, by column id. */
|
||||
widths: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface DbData {
|
||||
title: string;
|
||||
columns: Column[];
|
||||
rows: Row[];
|
||||
views: View[];
|
||||
}
|
||||
|
||||
/** A short random id, unique enough within one document. */
|
||||
export function newId(): string {
|
||||
const bytes = new Uint8Array(6);
|
||||
crypto.getRandomValues(bytes);
|
||||
return [...bytes].map((b) => b.toString(36).padStart(2, "0")).join("").slice(0, 10);
|
||||
}
|
||||
|
||||
export function defaultView(type: ViewType, name: string, columns: Column[]): View {
|
||||
const groupable = columns.find((c) => groupableTypes.includes(c.type));
|
||||
const date = columns.find((c) => c.type === "date" || c.type === "createdTime");
|
||||
return {
|
||||
id: newId(),
|
||||
name,
|
||||
type,
|
||||
hidden: [],
|
||||
filters: [],
|
||||
filterMode: "and",
|
||||
sorts: [],
|
||||
groupBy: type === "kanban" ? (groupable?.id ?? null) : null,
|
||||
dateColumn: type === "calendar" ? (date?.id ?? null) : null,
|
||||
widths: {},
|
||||
};
|
||||
}
|
||||
|
||||
/** Columns rows can be grouped by, and kanban boards built on. */
|
||||
export const groupableTypes: ColumnType[] = ["select", "multiSelect", "checkbox", "member", "createdBy"];
|
||||
|
||||
/** Reads a database from untrusted JSON (a node's data attribute, a paste), dropping what does not fit. */
|
||||
export function normalize(raw: unknown): DbData {
|
||||
const o = isObject(raw) ? raw : {};
|
||||
const columns = (Array.isArray(o.columns) ? o.columns : []).flatMap((c): Column[] => {
|
||||
if (!isObject(c) || typeof c.id !== "string" || !c.id) return [];
|
||||
const type = (columnTypes as readonly string[]).includes(String(c.type)) ? (c.type as ColumnType) : "text";
|
||||
const col: Column = { id: c.id, name: typeof c.name === "string" ? c.name : "", type };
|
||||
if (Array.isArray(c.options)) col.options = c.options.flatMap(option);
|
||||
return [col];
|
||||
});
|
||||
if (!columns.some((c) => c.type === "title")) columns.unshift({ id: newId(), name: "", type: "title" });
|
||||
const rows = (Array.isArray(o.rows) ? o.rows : []).flatMap((r): Row[] => {
|
||||
if (!isObject(r) || typeof r.id !== "string" || !r.id) return [];
|
||||
const row: Row = {
|
||||
id: r.id,
|
||||
cells: isObject(r.cells) ? { ...r.cells } : {},
|
||||
createdAt: typeof r.createdAt === "number" ? r.createdAt : 0,
|
||||
createdBy: person(r.createdBy),
|
||||
};
|
||||
if (Array.isArray(r.body) && r.body.length) {
|
||||
row.body = r.body as JSONContent[];
|
||||
row.hasBody = true;
|
||||
}
|
||||
return [row];
|
||||
});
|
||||
const ids = new Set(columns.map((c) => c.id));
|
||||
const views = (Array.isArray(o.views) ? o.views : []).flatMap((v): View[] => {
|
||||
if (!isObject(v) || typeof v.id !== "string" || !v.id) return [];
|
||||
const type = (viewTypes as readonly string[]).includes(String(v.type)) ? (v.type as ViewType) : "table";
|
||||
return [
|
||||
{
|
||||
id: v.id,
|
||||
name: typeof v.name === "string" ? v.name : "",
|
||||
type,
|
||||
hidden: Array.isArray(v.hidden) ? v.hidden.filter((h): h is string => typeof h === "string") : [],
|
||||
filters: Array.isArray(v.filters)
|
||||
? v.filters.filter((f): f is Filter => isObject(f) && typeof f.column === "string" && typeof f.op === "string")
|
||||
: [],
|
||||
filterMode: v.filterMode === "or" ? "or" : "and",
|
||||
sorts: Array.isArray(v.sorts)
|
||||
? v.sorts.flatMap((s) => (isObject(s) && typeof s.column === "string" ? [{ column: s.column, desc: !!s.desc }] : []))
|
||||
: [],
|
||||
groupBy: typeof v.groupBy === "string" && ids.has(v.groupBy) ? v.groupBy : null,
|
||||
dateColumn: typeof v.dateColumn === "string" && ids.has(v.dateColumn) ? v.dateColumn : null,
|
||||
widths: isObject(v.widths)
|
||||
? Object.fromEntries(Object.entries(v.widths).filter((e): e is [string, number] => typeof e[1] === "number"))
|
||||
: {},
|
||||
},
|
||||
];
|
||||
});
|
||||
return { title: typeof o.title === "string" ? o.title : "", columns, rows, views };
|
||||
}
|
||||
|
||||
function option(o: unknown): SelectOption[] {
|
||||
if (!isObject(o) || typeof o.id !== "string") return [];
|
||||
return [{ id: o.id, name: typeof o.name === "string" ? o.name : "", color: isPaletteColor(o.color) ? o.color : "gray" }];
|
||||
}
|
||||
|
||||
function person(p: unknown): Person | null {
|
||||
return isObject(p) && typeof p.id === "string" ? { id: p.id, name: typeof p.name === "string" ? p.name : "" } : null;
|
||||
}
|
||||
|
||||
export function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === "object" && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
/** The title column (normalize makes sure there is one). */
|
||||
export function titleColumn(db: DbData): Column {
|
||||
return db.columns.find((c) => c.type === "title") ?? db.columns[0]!;
|
||||
}
|
||||
|
||||
/** The value a row has in a column; created time and creator come from the row itself. */
|
||||
export function cellValue(row: Row, col: Column): unknown {
|
||||
if (col.type === "createdTime") return row.createdAt || null;
|
||||
if (col.type === "createdBy") return row.createdBy ? [row.createdBy] : [];
|
||||
return row.cells[col.id];
|
||||
}
|
||||
|
||||
export function isEmptyValue(v: unknown): boolean {
|
||||
return v === undefined || v === null || v === "" || v === false || (Array.isArray(v) && v.length === 0);
|
||||
}
|
||||
|
||||
/** "YYYY-MM-DD" of a date cell, or "" when it holds none. */
|
||||
export function dateOf(v: unknown): string {
|
||||
if (typeof v === "number" && v > 0) return isoDay(new Date(v));
|
||||
if (typeof v === "string" && /^\d{4}-\d{2}-\d{2}/.test(v)) return v.slice(0, 10);
|
||||
return "";
|
||||
}
|
||||
|
||||
export function isoDay(d: Date): string {
|
||||
const p = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
||||
}
|
||||
|
||||
export function asNumber(v: unknown): number | null {
|
||||
if (typeof v === "number" && Number.isFinite(v)) return v;
|
||||
if (typeof v === "string" && v.trim() !== "") {
|
||||
const n = Number(v.trim().replace(",", "."));
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function asList<T>(v: unknown): T[] {
|
||||
return Array.isArray(v) ? (v as T[]) : [];
|
||||
}
|
||||
|
||||
/** A cell as plain text: for CSV, search, sorting text and copying. */
|
||||
export function cellText(row: Row, col: Column): string {
|
||||
const v = cellValue(row, col);
|
||||
switch (col.type) {
|
||||
case "title":
|
||||
case "text":
|
||||
case "link":
|
||||
return typeof v === "string" ? v : "";
|
||||
case "number":
|
||||
case "progress": {
|
||||
const n = asNumber(v);
|
||||
return n === null ? "" : String(n);
|
||||
}
|
||||
case "checkbox":
|
||||
return v === true ? "true" : "false";
|
||||
case "select":
|
||||
return col.options?.find((o) => o.id === v)?.name ?? "";
|
||||
case "multiSelect": {
|
||||
const names = asList<string>(v).map((id) => col.options?.find((o) => o.id === id)?.name);
|
||||
return names.filter((n): n is string => !!n).join(", ");
|
||||
}
|
||||
case "date":
|
||||
case "createdTime":
|
||||
return dateOf(v);
|
||||
case "attachment":
|
||||
return asList<Attachment>(v)
|
||||
.map((a) => a?.name ?? "")
|
||||
.join(", ");
|
||||
case "member":
|
||||
case "createdBy":
|
||||
return asList<Person>(v)
|
||||
.map((p) => p?.name ?? "")
|
||||
.join(", ");
|
||||
}
|
||||
}
|
||||
|
||||
/** The filter operators a column type offers, the first being the default. */
|
||||
export function filterOps(type: ColumnType): FilterOp[] {
|
||||
switch (type) {
|
||||
case "number":
|
||||
case "progress":
|
||||
return ["is", "isNot", "gt", "lt", "gte", "lte", "isEmpty", "isNotEmpty"];
|
||||
case "checkbox":
|
||||
return ["checked", "unchecked"];
|
||||
case "select":
|
||||
return ["is", "isNot", "isEmpty", "isNotEmpty"];
|
||||
case "multiSelect":
|
||||
case "member":
|
||||
case "createdBy":
|
||||
return ["contains", "notContains", "isEmpty", "isNotEmpty"];
|
||||
case "date":
|
||||
case "createdTime":
|
||||
return ["is", "before", "after", "isEmpty", "isNotEmpty"];
|
||||
case "attachment":
|
||||
return ["isEmpty", "isNotEmpty"];
|
||||
default:
|
||||
return ["contains", "notContains", "is", "isNot", "isEmpty", "isNotEmpty"];
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a filter operator compares against a value the user types or picks. */
|
||||
export const opTakesValue = (op: FilterOp) => !["isEmpty", "isNotEmpty", "checked", "unchecked"].includes(op);
|
||||
|
||||
export function matchesFilter(row: Row, col: Column, f: Filter): boolean {
|
||||
const v = cellValue(row, col);
|
||||
if (f.op === "isEmpty") return isEmptyValue(v) || cellText(row, col) === "";
|
||||
if (f.op === "isNotEmpty") return !(isEmptyValue(v) || cellText(row, col) === "");
|
||||
if (f.op === "checked") return v === true;
|
||||
if (f.op === "unchecked") return v !== true;
|
||||
// A filter without a value yet matches everything, as in a spreadsheet.
|
||||
if (f.value === undefined || f.value === null || f.value === "") return true;
|
||||
switch (col.type) {
|
||||
case "number":
|
||||
case "progress": {
|
||||
const n = asNumber(v);
|
||||
const want = asNumber(f.value);
|
||||
if (want === null) return true;
|
||||
if (n === null) return f.op === "isNot";
|
||||
return { is: n === want, isNot: n !== want, gt: n > want, lt: n < want, gte: n >= want, lte: n <= want }[
|
||||
f.op as "is"
|
||||
];
|
||||
}
|
||||
case "select":
|
||||
return f.op === "is" ? v === f.value : v !== f.value;
|
||||
case "multiSelect": {
|
||||
const has = asList<string>(v).includes(String(f.value));
|
||||
return f.op === "notContains" ? !has : has;
|
||||
}
|
||||
case "member":
|
||||
case "createdBy": {
|
||||
const want = String(f.value).toLowerCase();
|
||||
const has = asList<Person>(v).some((p) => p?.id === f.value || p?.name?.toLowerCase().includes(want));
|
||||
return f.op === "notContains" ? !has : has;
|
||||
}
|
||||
case "date":
|
||||
case "createdTime": {
|
||||
const d = dateOf(v);
|
||||
const want = dateOf(f.value);
|
||||
if (!d) return false;
|
||||
return f.op === "before" ? d < want : f.op === "after" ? d > want : d === want;
|
||||
}
|
||||
default: {
|
||||
const text = cellText(row, col).toLowerCase();
|
||||
const want = String(f.value).toLowerCase();
|
||||
switch (f.op) {
|
||||
case "contains":
|
||||
return text.includes(want);
|
||||
case "notContains":
|
||||
return !text.includes(want);
|
||||
case "is":
|
||||
return text === want;
|
||||
case "isNot":
|
||||
return text !== want;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Compares two rows by one column, empty cells last. */
|
||||
export function compareRows(a: Row, b: Row, col: Column): number {
|
||||
const ea = cellText(a, col) === "" && col.type !== "checkbox";
|
||||
const eb = cellText(b, col) === "" && col.type !== "checkbox";
|
||||
if (ea || eb) return ea === eb ? 0 : ea ? 1 : -1;
|
||||
switch (col.type) {
|
||||
case "number":
|
||||
case "progress":
|
||||
return (asNumber(cellValue(a, col)) ?? 0) - (asNumber(cellValue(b, col)) ?? 0);
|
||||
case "checkbox":
|
||||
return Number(cellValue(a, col) === true) - Number(cellValue(b, col) === true);
|
||||
case "createdTime":
|
||||
return a.createdAt - b.createdAt;
|
||||
case "select": {
|
||||
// Choices sort in their own order, like a status column.
|
||||
const order = (r: Row) => col.options?.findIndex((o) => o.id === cellValue(r, col)) ?? -1;
|
||||
return order(a) - order(b);
|
||||
}
|
||||
default:
|
||||
return cellText(a, col).localeCompare(cellText(b, col), undefined, { numeric: true, sensitivity: "base" });
|
||||
}
|
||||
}
|
||||
|
||||
/** The rows a view shows, filtered, searched and sorted (stable: ties keep the manual order). */
|
||||
export function viewRows(db: DbData, view: View, search = ""): Row[] {
|
||||
const byId = new Map(db.columns.map((c) => [c.id, c]));
|
||||
const filters = view.filters.flatMap((f) => {
|
||||
const col = byId.get(f.column);
|
||||
return col ? [{ f, col }] : [];
|
||||
});
|
||||
const q = search.trim().toLowerCase();
|
||||
let rows = db.rows.filter((r) => {
|
||||
if (filters.length) {
|
||||
const test = ({ f, col }: (typeof filters)[number]) => matchesFilter(r, col, f);
|
||||
if (view.filterMode === "or" ? !filters.some(test) : !filters.every(test)) return false;
|
||||
}
|
||||
return !q || db.columns.some((c) => cellText(r, c).toLowerCase().includes(q));
|
||||
});
|
||||
const sorts = view.sorts.flatMap((s) => {
|
||||
const col = byId.get(s.column);
|
||||
return col ? [{ col, desc: s.desc }] : [];
|
||||
});
|
||||
if (sorts.length) {
|
||||
rows = rows
|
||||
.map((r, i) => ({ r, i }))
|
||||
.sort((x, y) => {
|
||||
for (const s of sorts) {
|
||||
const c = compareRows(x.r, y.r, s.col);
|
||||
// Empty cells stay last in both directions.
|
||||
if (c !== 0) {
|
||||
const empty = cellText(x.r, s.col) === "" || cellText(y.r, s.col) === "";
|
||||
return s.desc && !(empty && s.col.type !== "checkbox") ? -c : c;
|
||||
}
|
||||
}
|
||||
return x.i - y.i;
|
||||
})
|
||||
.map((x) => x.r);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** The columns a view shows, in order. The title column always shows. */
|
||||
export function visibleColumns(db: DbData, view: View): Column[] {
|
||||
return db.columns.filter((c) => c.type === "title" || !view.hidden.includes(c.id));
|
||||
}
|
||||
|
||||
export interface Group {
|
||||
/** The value rows in this group have: an option id, "true"/"false", a person id; "" = none. */
|
||||
key: string;
|
||||
label: string;
|
||||
color?: PaletteColor;
|
||||
rows: Row[];
|
||||
}
|
||||
|
||||
/** Splits rows into groups by a column: one per choice (in order) plus "No value". */
|
||||
export function groupRows(rows: Row[], col: Column, noValue: string, yes: string, no: string): Group[] {
|
||||
const groups = new Map<string, Group>();
|
||||
const add = (key: string, label: string, color?: PaletteColor) => {
|
||||
if (!groups.has(key)) groups.set(key, { key, label, color, rows: [] });
|
||||
return groups.get(key)!;
|
||||
};
|
||||
if (col.type === "checkbox") {
|
||||
add("false", no);
|
||||
add("true", yes);
|
||||
} else {
|
||||
add("", noValue);
|
||||
for (const o of col.options ?? []) add(o.id, o.name, o.color);
|
||||
}
|
||||
for (const r of rows) {
|
||||
for (const key of groupKeys(r, col)) {
|
||||
const g = groups.get(key) ?? add(key, personName(r, col, key) || key);
|
||||
g.rows.push(r);
|
||||
}
|
||||
}
|
||||
return [...groups.values()];
|
||||
}
|
||||
|
||||
function personName(r: Row, col: Column, id: string): string {
|
||||
return asList<Person>(cellValue(r, col)).find((p) => p?.id === id)?.name ?? "";
|
||||
}
|
||||
|
||||
/** The groups a row belongs to in a column (several for multi-select and members). */
|
||||
export function groupKeys(r: Row, col: Column): string[] {
|
||||
const v = cellValue(r, col);
|
||||
switch (col.type) {
|
||||
case "checkbox":
|
||||
return [v === true ? "true" : "false"];
|
||||
case "select":
|
||||
return [typeof v === "string" && col.options?.some((o) => o.id === v) ? v : ""];
|
||||
case "multiSelect": {
|
||||
const ids = asList<string>(v).filter((id) => col.options?.some((o) => o.id === id));
|
||||
return ids.length ? ids : [""];
|
||||
}
|
||||
case "member":
|
||||
case "createdBy": {
|
||||
const ids = asList<Person>(v).flatMap((p) => (p?.id ? [p.id] : []));
|
||||
return ids.length ? ids : [""];
|
||||
}
|
||||
default:
|
||||
return [""];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The cell value after moving a row from one group to another (kanban drag):
|
||||
* select takes the new choice, multi-select swaps the old one for the new.
|
||||
*/
|
||||
export function moveToGroup(r: Row, col: Column, from: string, to: string, people: Person[] = []): unknown {
|
||||
const v = cellValue(r, col);
|
||||
switch (col.type) {
|
||||
case "checkbox":
|
||||
return to === "true";
|
||||
case "select":
|
||||
return to || null;
|
||||
case "multiSelect": {
|
||||
const ids = asList<string>(v).filter((id) => id !== from && id !== to);
|
||||
return to ? [...ids, to] : ids;
|
||||
}
|
||||
case "member": {
|
||||
const list = asList<Person>(v).filter((p) => p?.id !== from && p?.id !== to);
|
||||
const p = people.find((x) => x.id === to) ?? asList<Person>(v).find((x) => x?.id === to);
|
||||
return to && p ? [...list, p] : list;
|
||||
}
|
||||
default:
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
/** The next palette colour for a new choice, so neighbours differ. */
|
||||
export function nextColor(options: SelectOption[]): PaletteColor {
|
||||
const choices = palette.filter((c) => c !== "gray");
|
||||
return choices[options.length % choices.length]!;
|
||||
}
|
||||
|
||||
/**
|
||||
* A cell's value after its column changed type. Text becomes choices (new
|
||||
* options are returned to add), numbers parse, choices become their names.
|
||||
*/
|
||||
export function convertValue(
|
||||
v: unknown,
|
||||
from: Column,
|
||||
to: ColumnType,
|
||||
options: SelectOption[],
|
||||
): { value: unknown; options: SelectOption[] } {
|
||||
if (from.type === to) return { value: v, options };
|
||||
const text = cellText({ id: "", cells: { [from.id]: v }, createdAt: 0, createdBy: null }, from);
|
||||
const choice = (name: string) => {
|
||||
const n = name.trim();
|
||||
if (!n) return null;
|
||||
let o = options.find((x) => x.name.toLowerCase() === n.toLowerCase());
|
||||
if (!o) {
|
||||
o = { id: newId(), name: n, color: nextColor(options) };
|
||||
options = [...options, o];
|
||||
}
|
||||
return o.id;
|
||||
};
|
||||
switch (to) {
|
||||
case "title":
|
||||
case "text":
|
||||
case "link":
|
||||
return { value: text || null, options };
|
||||
case "number":
|
||||
return { value: asNumber(text), options };
|
||||
case "progress": {
|
||||
const n = asNumber(text);
|
||||
return { value: n === null ? null : Math.max(0, Math.min(100, Math.round(n))), options };
|
||||
}
|
||||
case "checkbox":
|
||||
return { value: ["true", "yes", "1", "x", "✓", "done"].includes(text.trim().toLowerCase()), options };
|
||||
case "select":
|
||||
return { value: choice(text.split(",")[0] ?? ""), options };
|
||||
case "multiSelect": {
|
||||
const ids = text.split(",").flatMap((t) => {
|
||||
const id = choice(t);
|
||||
return id ? [id] : [];
|
||||
});
|
||||
return { value: [...new Set(ids)], options };
|
||||
}
|
||||
case "date":
|
||||
return { value: dateOf(text) || null, options };
|
||||
case "member":
|
||||
return { value: from.type === "member" || from.type === "createdBy" ? v : [], options };
|
||||
default:
|
||||
return { value: null, options };
|
||||
}
|
||||
}
|
||||
|
||||
/** Days of the month grid around a month (Monday first): 5 or 6 weeks of "YYYY-MM-DD". */
|
||||
export function monthGrid(year: number, month: number, weekStart = 1): string[] {
|
||||
const first = new Date(year, month, 1);
|
||||
const lead = (first.getDay() - weekStart + 7) % 7;
|
||||
const start = new Date(year, month, 1 - lead);
|
||||
const days = new Date(year, month + 1, 0).getDate();
|
||||
const weeks = Math.ceil((lead + days) / 7);
|
||||
return Array.from({ length: weeks * 7 }, (_, i) =>
|
||||
isoDay(new Date(start.getFullYear(), start.getMonth(), start.getDate() + i)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// The view settings panels: filters, sorts, grouping and which properties show.
|
||||
|
||||
import type { DbContext } from "./cells";
|
||||
import { typeIcons } from "./cells";
|
||||
import { h, icon } from "./dom";
|
||||
import { opLabel, typeLabel } from "./labels";
|
||||
import {
|
||||
filterOps,
|
||||
groupableTypes,
|
||||
opTakesValue,
|
||||
type Column,
|
||||
type Filter,
|
||||
type FilterOp,
|
||||
type View,
|
||||
} from "./model";
|
||||
|
||||
function select<T extends string>(
|
||||
value: T | "",
|
||||
choices: { value: T | ""; label: string }[],
|
||||
label: string,
|
||||
onChange: (v: T) => void,
|
||||
): HTMLSelectElement {
|
||||
const s = h("select", { class: "dw-db-select", "aria-label": label });
|
||||
for (const c of choices) {
|
||||
const o = h("option", { value: c.value }, c.label);
|
||||
if (c.value === value) o.selected = true;
|
||||
s.append(o);
|
||||
}
|
||||
s.addEventListener("change", () => onChange(s.value as T));
|
||||
s.addEventListener("keydown", (e) => e.stopPropagation());
|
||||
return s;
|
||||
}
|
||||
|
||||
const columnChoices = (cols: Column[]) => cols.map((c) => ({ value: c.id, label: c.name || "…" }));
|
||||
|
||||
/** The value field of a filter, by the column's type. */
|
||||
function filterValue(ctx: DbContext, col: Column, f: Filter, set: (v: unknown) => void): HTMLElement | null {
|
||||
const l = ctx.labels;
|
||||
if (!opTakesValue(f.op)) return null;
|
||||
if (col.type === "select" || col.type === "multiSelect") {
|
||||
return select(
|
||||
typeof f.value === "string" ? f.value : "",
|
||||
[{ value: "", label: "—" }, ...(col.options ?? []).map((o) => ({ value: o.id, label: o.name }))],
|
||||
l.value,
|
||||
set,
|
||||
);
|
||||
}
|
||||
const type = col.type === "date" || col.type === "createdTime" ? "date" : col.type === "number" || col.type === "progress" ? "number" : "text";
|
||||
const input = h("input", { class: "dw-db-input dw-db-input--small", type, "aria-label": l.value, placeholder: l.value });
|
||||
input.value = f.value === undefined || f.value === null ? "" : String(f.value);
|
||||
input.addEventListener("keydown", (e) => e.stopPropagation());
|
||||
input.addEventListener("change", () => set(type === "number" ? (input.value === "" ? null : Number(input.value)) : input.value));
|
||||
return input;
|
||||
}
|
||||
|
||||
export function filterPanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
const l = ctx.labels;
|
||||
const cols = ctx.db.columns;
|
||||
const filters = structuredClone(view.filters);
|
||||
const save = () => store?.updateView(view.id, { filters });
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
if (filters.length > 1) {
|
||||
box.append(
|
||||
select(view.filterMode, [
|
||||
{ value: "and", label: l.matchAll },
|
||||
{ value: "or", label: l.matchAny },
|
||||
], l.filter, (v) => {
|
||||
view.filterMode = v as "and" | "or";
|
||||
store?.updateView(view.id, { filterMode: view.filterMode });
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!filters.length) box.append(h("p", { class: "dw-db-pop__empty" }, l.noFilters));
|
||||
filters.forEach((f, i) => {
|
||||
const col = cols.find((c) => c.id === f.column);
|
||||
if (!col) return;
|
||||
const ops = filterOps(col.type);
|
||||
const line = h(
|
||||
"div",
|
||||
{ class: "dw-db-pop__line" },
|
||||
select(f.column, columnChoices(cols), l.filter, (id) => {
|
||||
const c = cols.find((x) => x.id === id)!;
|
||||
filters[i] = { column: id, op: filterOps(c.type)[0]! };
|
||||
save();
|
||||
draw();
|
||||
}),
|
||||
select<FilterOp>(f.op, ops.map((op) => ({ value: op, label: opLabel(l, op) })), l.filter, (op) => {
|
||||
filters[i] = { ...f, op };
|
||||
if (!opTakesValue(op)) delete filters[i]!.value;
|
||||
save();
|
||||
draw();
|
||||
}),
|
||||
filterValue(ctx, col, f, (v) => {
|
||||
filters[i] = { ...filters[i]!, value: v };
|
||||
save();
|
||||
}),
|
||||
removeButton(l.remove, () => {
|
||||
filters.splice(i, 1);
|
||||
save();
|
||||
draw();
|
||||
}),
|
||||
);
|
||||
box.append(line);
|
||||
});
|
||||
if (store) {
|
||||
box.append(
|
||||
addButton(l.addFilter, () => {
|
||||
const col = cols.find((c) => c.type !== "title") ?? cols[0]!;
|
||||
filters.push({ column: col.id, op: filterOps(col.type)[0]! });
|
||||
save();
|
||||
draw();
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
draw();
|
||||
}
|
||||
|
||||
export function sortPanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
const l = ctx.labels;
|
||||
const cols = ctx.db.columns;
|
||||
const sorts = structuredClone(view.sorts);
|
||||
const save = () => store?.updateView(view.id, { sorts });
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
if (!sorts.length) box.append(h("p", { class: "dw-db-pop__empty" }, l.noSorts));
|
||||
sorts.forEach((s, i) => {
|
||||
box.append(
|
||||
h(
|
||||
"div",
|
||||
{ class: "dw-db-pop__line" },
|
||||
select(s.column, columnChoices(cols), l.sort, (id) => {
|
||||
sorts[i] = { ...s, column: id };
|
||||
save();
|
||||
}),
|
||||
select(s.desc ? "desc" : "asc", [
|
||||
{ value: "asc", label: l.ascending },
|
||||
{ value: "desc", label: l.descending },
|
||||
], l.sort, (v) => {
|
||||
sorts[i] = { ...s, desc: v === "desc" };
|
||||
save();
|
||||
}),
|
||||
removeButton(l.remove, () => {
|
||||
sorts.splice(i, 1);
|
||||
save();
|
||||
draw();
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
if (store) {
|
||||
box.append(
|
||||
addButton(l.addSort, () => {
|
||||
const used = new Set(sorts.map((s) => s.column));
|
||||
const col = cols.find((c) => !used.has(c.id)) ?? cols[0]!;
|
||||
sorts.push({ column: col.id, desc: false });
|
||||
save();
|
||||
draw();
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
draw();
|
||||
}
|
||||
|
||||
/** Grouping (table and kanban) and, for calendars, the date property. */
|
||||
export function groupPanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
const l = ctx.labels;
|
||||
const groupable = ctx.db.columns.filter((c) => groupableTypes.includes(c.type));
|
||||
const choices = groupable.map((c) => ({ value: c.id, label: c.name || typeLabel(l, c.type) }));
|
||||
if (view.type !== "kanban") choices.unshift({ value: "", label: l.noGrouping });
|
||||
box.append(
|
||||
h("label", { class: "dw-db-pop__label" }, l.groupBy),
|
||||
groupable.length || view.type !== "kanban"
|
||||
? select(view.groupBy ?? "", choices, l.groupBy, (v) => store?.updateView(view.id, { groupBy: v || null }))
|
||||
: h("p", { class: "dw-db-pop__empty" }, l.noGroupColumn),
|
||||
);
|
||||
}
|
||||
|
||||
export function datePanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
const l = ctx.labels;
|
||||
const dates = ctx.db.columns.filter((c) => c.type === "date" || c.type === "createdTime");
|
||||
box.append(
|
||||
h("label", { class: "dw-db-pop__label" }, l.dateColumn),
|
||||
dates.length
|
||||
? select(
|
||||
view.dateColumn ?? "",
|
||||
[{ value: "", label: "—" }, ...dates.map((c) => ({ value: c.id, label: c.name || typeLabel(l, c.type) }))],
|
||||
l.dateColumn,
|
||||
(v) => store?.updateView(view.id, { dateColumn: v || null }),
|
||||
)
|
||||
: h("p", { class: "dw-db-pop__empty" }, l.noDateColumn),
|
||||
);
|
||||
}
|
||||
|
||||
/** Which properties the view shows. */
|
||||
export function propertiesPanel(ctx: DbContext, box: HTMLElement, view: View) {
|
||||
const store = ctx.store;
|
||||
const l = ctx.labels;
|
||||
let hidden = [...view.hidden];
|
||||
const save = () => store?.updateView(view.id, { hidden });
|
||||
const draw = () => {
|
||||
box.replaceChildren();
|
||||
const others = ctx.db.columns.filter((c) => c.type !== "title");
|
||||
if (store && others.length) {
|
||||
const all = h("button", { type: "button", class: "dw-db__btn" }, hidden.length ? l.showAll : l.hideAll);
|
||||
all.addEventListener("click", () => {
|
||||
hidden = hidden.length ? [] : others.map((c) => c.id);
|
||||
save();
|
||||
draw();
|
||||
});
|
||||
box.append(h("div", { class: "dw-db-pop__row dw-db-pop__row--end" }, all));
|
||||
}
|
||||
for (const c of ctx.db.columns) {
|
||||
const shown = c.type === "title" || !hidden.includes(c.id);
|
||||
const toggle = h(
|
||||
"button",
|
||||
{
|
||||
type: "button",
|
||||
class: "dw-db-pop__item",
|
||||
role: "switch",
|
||||
"aria-checked": String(shown),
|
||||
disabled: c.type === "title" || !store,
|
||||
},
|
||||
h("span", { class: "dw-db-pop__check" }, icon(typeIcons[c.type], 14)),
|
||||
h("span", { class: "dw-db-pop__grow" }, c.name || typeLabel(l, c.type)),
|
||||
h("span", { class: shown ? "dw-db-switch is-on" : "dw-db-switch" }),
|
||||
);
|
||||
toggle.addEventListener("click", () => {
|
||||
hidden = shown ? [...hidden, c.id] : hidden.filter((x) => x !== c.id);
|
||||
save();
|
||||
draw();
|
||||
});
|
||||
box.append(toggle);
|
||||
}
|
||||
};
|
||||
draw();
|
||||
}
|
||||
|
||||
function removeButton(label: string, onClick: () => void) {
|
||||
const b = h("button", { type: "button", class: "dw-db__btn dw-db__btn--icon", "aria-label": label, title: label }, icon("close", 14));
|
||||
b.addEventListener("click", onClick);
|
||||
return b;
|
||||
}
|
||||
|
||||
function addButton(label: string, onClick: () => void) {
|
||||
const b = h("button", { type: "button", class: "dw-db__btn dw-db-pop__add" }, icon("plus", 14), h("span", {}, label));
|
||||
b.addEventListener("click", onClick);
|
||||
return b;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// A row opened as a page: a panel over the page with the row's title and
|
||||
// properties on top and its own body below, edited by a second editor bound
|
||||
// to the row's fragment (ADR-13).
|
||||
|
||||
import { openBlockMenu } from "../blockmenu";
|
||||
import { editCell, readOnlyTypes, renderCell, typeIcons, type DbContext } from "./cells";
|
||||
import { h, icon, iconButton } from "./dom";
|
||||
import { typeLabel } from "./labels";
|
||||
import { cellValue, editableTypes, titleColumn, type DbData, type Row } from "./model";
|
||||
|
||||
export interface PeekHost {
|
||||
ctx: Omit<DbContext, "db" | "setEditing" | "openRow">;
|
||||
/** Draws the row's body into el; returns a cleanup. */
|
||||
mountBody: (el: HTMLElement, row: Row) => (() => void) | null;
|
||||
}
|
||||
|
||||
export class RowPeek {
|
||||
private dom: HTMLDivElement;
|
||||
private panel: HTMLDivElement;
|
||||
private head = h("div", { class: "dw-db-peek__head" });
|
||||
private props = h("div", { class: "dw-db-peek__props" });
|
||||
private bodyEl = h("div", { class: "dw-db-peek__body" });
|
||||
private unmount: (() => void) | null = null;
|
||||
private editing = 0;
|
||||
private pending = false;
|
||||
private wide = false;
|
||||
private returnFocus: Element | null;
|
||||
|
||||
constructor(
|
||||
private host: PeekHost,
|
||||
private db: DbData,
|
||||
private rowId: string,
|
||||
private order: string[],
|
||||
private onClose: () => void,
|
||||
) {
|
||||
this.returnFocus = document.activeElement;
|
||||
this.panel = h("div", { class: "dw-db-peek__panel", role: "dialog", "aria-modal": "true", tabIndex: -1 }, this.head, this.props, this.bodyEl);
|
||||
this.dom = h("div", { class: "dw-db-peek" }, this.panel);
|
||||
this.dom.addEventListener("mousedown", (e) => {
|
||||
if (e.target === this.dom) this.close();
|
||||
});
|
||||
this.dom.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape" && !document.querySelector(".dw-db-pop, .dw-block-menu")) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.close();
|
||||
}
|
||||
});
|
||||
document.body.append(this.dom);
|
||||
this.draw(true);
|
||||
this.panel.focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
get row(): string {
|
||||
return this.rowId;
|
||||
}
|
||||
|
||||
private ctx(): DbContext {
|
||||
return {
|
||||
...this.host.ctx,
|
||||
db: this.db,
|
||||
openRow: (id) => this.show(id),
|
||||
setEditing: (on) => {
|
||||
this.editing = Math.max(0, this.editing + (on ? 1 : -1));
|
||||
if (!this.editing && this.pending) {
|
||||
this.pending = false;
|
||||
this.draw(false);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
update(db: DbData, host?: Partial<PeekHost["ctx"]>) {
|
||||
this.db = db;
|
||||
if (host) this.host = { ...this.host, ctx: { ...this.host.ctx, ...host } };
|
||||
if (!db.rows.some((r) => r.id === this.rowId)) return this.close();
|
||||
if (this.editing) {
|
||||
this.pending = true;
|
||||
return;
|
||||
}
|
||||
this.draw(false);
|
||||
}
|
||||
|
||||
private show(id: string) {
|
||||
if (id === this.rowId) return;
|
||||
this.rowId = id;
|
||||
this.draw(true);
|
||||
}
|
||||
|
||||
private draw(withBody: boolean) {
|
||||
const row = this.db.rows.find((r) => r.id === this.rowId);
|
||||
if (!row) return;
|
||||
const ctx = this.ctx();
|
||||
const l = ctx.labels;
|
||||
const store = ctx.store;
|
||||
this.panel.classList.toggle("is-wide", this.wide);
|
||||
const i = this.order.indexOf(this.rowId);
|
||||
const prev = iconButton("chevron-up", l.previousRow, () => this.show(this.order[i - 1]!));
|
||||
const next = iconButton("chevron-down", l.nextRow, () => this.show(this.order[i + 1]!));
|
||||
prev.disabled = i <= 0;
|
||||
next.disabled = i < 0 || i >= this.order.length - 1;
|
||||
this.head.replaceChildren(
|
||||
h("span", { class: "dw-db-peek__db" }, icon("database", 14), this.db.title || l.untitled),
|
||||
h("span", { class: "dw-db-peek__grow" }),
|
||||
prev,
|
||||
next,
|
||||
iconButton(this.wide ? "width" : "width", this.wide ? l.collapse : l.expand, () => {
|
||||
this.wide = !this.wide;
|
||||
this.panel.classList.toggle("is-wide", this.wide);
|
||||
}),
|
||||
iconButton("close", l.close, () => this.close()),
|
||||
);
|
||||
|
||||
const title = titleColumn(this.db);
|
||||
const titleText = String(cellValue(row, title) ?? "");
|
||||
const titleEl = store
|
||||
? (() => {
|
||||
const input = h("input", { class: "dw-db-peek__title", placeholder: l.untitledRow, "aria-label": title.name || l.typeTitle });
|
||||
input.value = titleText;
|
||||
input.addEventListener("focus", () => ctx.setEditing(true));
|
||||
input.addEventListener("blur", () => {
|
||||
if (input.value !== titleText) store.setCell(row.id, title.id, input.value);
|
||||
ctx.setEditing(false);
|
||||
});
|
||||
input.addEventListener("keydown", (e) => {
|
||||
e.stopPropagation();
|
||||
if (e.key === "Enter") input.blur();
|
||||
});
|
||||
return input;
|
||||
})()
|
||||
: h("h2", { class: "dw-db-peek__title" }, titleText || l.untitledRow);
|
||||
this.panel.setAttribute("aria-label", titleText || l.untitledRow);
|
||||
|
||||
const lines = this.db.columns
|
||||
.filter((c) => c.type !== "title")
|
||||
.map((c) => {
|
||||
const value = h("div", { class: `dw-db-peek__value dw-db-t__cell--${c.type}`, tabIndex: store && !readOnlyTypes.includes(c.type) ? 0 : -1 }, renderCell(ctx, row, c));
|
||||
const edit = () => {
|
||||
if (!store) return;
|
||||
editCell(ctx, value, row, c, { onDone: () => this.draw(false) });
|
||||
};
|
||||
value.addEventListener("click", (e) => {
|
||||
if ((e.target as HTMLElement).closest("a, button")) return;
|
||||
edit();
|
||||
});
|
||||
value.addEventListener("keydown", (e) => {
|
||||
if (e.target === value && (e.key === "Enter" || e.key === " ")) {
|
||||
e.preventDefault();
|
||||
edit();
|
||||
}
|
||||
});
|
||||
return h(
|
||||
"div",
|
||||
{ class: "dw-db-peek__prop" },
|
||||
h("div", { class: "dw-db-peek__label" }, icon(typeIcons[c.type], 14), h("span", {}, c.name || typeLabel(l, c.type))),
|
||||
value,
|
||||
);
|
||||
});
|
||||
const children: Node[] = [titleEl, ...lines];
|
||||
if (store) {
|
||||
const add = iconButton("plus", l.addColumn, () =>
|
||||
openBlockMenu(
|
||||
add,
|
||||
editableTypes.map((t) => ({ id: t, label: typeLabel(l, t), icon: typeIcons[t], run: () => store.addColumn(t, typeLabel(l, t)) })),
|
||||
l.addColumn,
|
||||
),
|
||||
l.addColumn);
|
||||
add.classList.add("dw-db-peek__add");
|
||||
children.push(add);
|
||||
}
|
||||
const hadFocus = this.props.contains(document.activeElement);
|
||||
this.props.replaceChildren(...children);
|
||||
if (hadFocus) this.panel.focus({ preventScroll: true });
|
||||
|
||||
if (withBody) {
|
||||
this.unmount?.();
|
||||
this.bodyEl.replaceChildren();
|
||||
this.unmount = this.host.mountBody(this.bodyEl, row);
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
this.unmount?.();
|
||||
this.unmount = null;
|
||||
this.dom.remove();
|
||||
this.onClose();
|
||||
if (this.returnFocus instanceof HTMLElement && this.returnFocus.isConnected) this.returnFocus.focus({ preventScroll: true });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// A database's live data in the page's Y.Doc (ADR-13):
|
||||
// ydoc.getMap("blocks").get(id) → Y.Map { title, columns, rows, views }.
|
||||
// Every edit runs in one transaction with DB_ORIGIN, which the page's undo
|
||||
// manager tracks, so Ctrl+Z undoes it like typing.
|
||||
|
||||
import * as Y from "yjs";
|
||||
import {
|
||||
convertValue,
|
||||
defaultView,
|
||||
isObject,
|
||||
newId,
|
||||
normalize,
|
||||
type Column,
|
||||
type ColumnType,
|
||||
type DbData,
|
||||
type Person,
|
||||
type Row,
|
||||
type SelectOption,
|
||||
type View,
|
||||
type ViewType,
|
||||
} from "./model";
|
||||
|
||||
/** The transaction origin of database edits; the Collaboration undo manager tracks it. */
|
||||
export const DB_ORIGIN = "docwell-database";
|
||||
|
||||
export const blocksOf = (doc: Y.Doc) => doc.getMap<Y.Map<unknown>>("blocks");
|
||||
|
||||
type Key = "columns" | "rows" | "views";
|
||||
type YItem = Y.Map<unknown>;
|
||||
|
||||
/** Writes a database (from JSON) as a new Y.Map, to put into the blocks map. */
|
||||
export function dbToY(data: DbData): YItem {
|
||||
const m = new Y.Map<unknown>();
|
||||
m.set("title", data.title);
|
||||
const list = <T,>(items: T[], toY: (x: T) => YItem) => {
|
||||
const a = new Y.Array<YItem>();
|
||||
a.push(items.map((x, i) => withPos(toY(x), i)));
|
||||
return a;
|
||||
};
|
||||
m.set("columns", list(data.columns, columnToY));
|
||||
m.set("rows", list(data.rows, rowToY));
|
||||
m.set("views", list(data.views, viewToY));
|
||||
return m;
|
||||
}
|
||||
|
||||
function withPos(m: YItem, pos: number): YItem {
|
||||
m.set("pos", pos);
|
||||
return m;
|
||||
}
|
||||
|
||||
function columnToY(c: Column): YItem {
|
||||
const m = new Y.Map<unknown>();
|
||||
m.set("id", c.id);
|
||||
m.set("name", c.name);
|
||||
m.set("type", c.type);
|
||||
if (c.options) m.set("options", c.options);
|
||||
return m;
|
||||
}
|
||||
|
||||
function rowToY(r: Row): YItem {
|
||||
const m = new Y.Map<unknown>();
|
||||
m.set("id", r.id);
|
||||
m.set("createdAt", r.createdAt);
|
||||
if (r.createdBy) m.set("createdBy", r.createdBy);
|
||||
const cells = new Y.Map<unknown>();
|
||||
for (const [k, v] of Object.entries(r.cells)) if (v !== undefined && v !== null) cells.set(k, v);
|
||||
m.set("cells", cells);
|
||||
return m;
|
||||
}
|
||||
|
||||
function viewToY(v: View): YItem {
|
||||
const m = new Y.Map<unknown>();
|
||||
for (const [k, val] of Object.entries(v)) m.set(k, val);
|
||||
return m;
|
||||
}
|
||||
|
||||
/**
|
||||
* Items of a list in display order. Order is a fractional "pos" on each
|
||||
* item, not the array order, so moving one only changes its pos: concurrent
|
||||
* edits to the moved item survive, and a row's open body stays bound.
|
||||
*/
|
||||
export function ordered(a: Y.Array<YItem>): YItem[] {
|
||||
return a
|
||||
.toArray()
|
||||
.filter((m): m is YItem => m instanceof Y.Map)
|
||||
.map((m, i) => ({ m, p: posOf(m, i), i }))
|
||||
.sort((x, y) => x.p - y.p || x.i - y.i)
|
||||
.map((x) => x.m);
|
||||
}
|
||||
|
||||
function posOf(m: YItem | undefined, fallback: number): number {
|
||||
const p = m?.get("pos");
|
||||
return typeof p === "number" ? p : fallback;
|
||||
}
|
||||
|
||||
/** A pos that sorts at index at of list (display order), between its neighbours. */
|
||||
function posAt(list: YItem[], at: number, skip?: YItem): number {
|
||||
const rest = skip ? list.filter((m) => m !== skip) : list;
|
||||
const i = Math.max(0, Math.min(at, rest.length));
|
||||
const before = i > 0 ? posOf(rest[i - 1], i - 1) : null;
|
||||
const after = i < rest.length ? posOf(rest[i], i) : null;
|
||||
if (before === null && after === null) return 0;
|
||||
if (before === null) return after! - 1;
|
||||
if (after === null) return before + 1;
|
||||
return (before + after) / 2;
|
||||
}
|
||||
|
||||
/** A plain snapshot of the Y.Map, for rendering. */
|
||||
export function readDb(m: YItem): DbData {
|
||||
const arr = (key: Key) => {
|
||||
const a = m.get(key);
|
||||
return a instanceof Y.Array ? ordered(a as Y.Array<YItem>) : [];
|
||||
};
|
||||
const plain = (x: YItem) => {
|
||||
const o = x.toJSON() as Record<string, unknown>;
|
||||
delete o.pos;
|
||||
return o;
|
||||
};
|
||||
const bodies = new Set<string>();
|
||||
const rows = arr("rows").map((r) => {
|
||||
const cells = r.get("cells");
|
||||
const body = r.get("body");
|
||||
const id = r.get("id");
|
||||
if (typeof id === "string" && body instanceof Y.XmlFragment && body.length > 0) bodies.add(id);
|
||||
return {
|
||||
id,
|
||||
createdAt: r.get("createdAt"),
|
||||
createdBy: r.get("createdBy"),
|
||||
cells: cells instanceof Y.Map ? cells.toJSON() : {},
|
||||
};
|
||||
});
|
||||
const db = normalize({
|
||||
title: m.get("title"),
|
||||
columns: arr("columns").map(plain),
|
||||
rows,
|
||||
views: arr("views").map(plain),
|
||||
});
|
||||
for (const r of db.rows) if (bodies.has(r.id)) r.hasBody = true;
|
||||
return db;
|
||||
}
|
||||
|
||||
export interface DbLabels {
|
||||
tableView: string;
|
||||
/** The default names of new columns, by type. */
|
||||
columnName: (type: ColumnType) => string;
|
||||
}
|
||||
|
||||
/** A new, empty database: a title column, a status column, three rows and one table view. */
|
||||
export function emptyDb(labels: DbLabels, title = ""): DbData {
|
||||
const name: Column = { id: newId(), name: labels.columnName("title"), type: "title" };
|
||||
const status: Column = { id: newId(), name: labels.columnName("select"), type: "select", options: [] };
|
||||
const columns = [name, status];
|
||||
const now = Date.now();
|
||||
return {
|
||||
title,
|
||||
columns,
|
||||
rows: [0, 1, 2].map((i) => ({ id: newId(), cells: {}, createdAt: now + i, createdBy: null })),
|
||||
views: [defaultView("table", labels.tableView, columns)],
|
||||
};
|
||||
}
|
||||
|
||||
const isEmpty = (v: unknown) => v === undefined || v === null || v === "" || (Array.isArray(v) && !v.length);
|
||||
|
||||
/** Edits one database. Methods are no-ops for ids that no longer exist (a peer deleted them). */
|
||||
export class DbStore {
|
||||
constructor(
|
||||
readonly doc: Y.Doc,
|
||||
readonly map: YItem,
|
||||
private readonly me: () => Person | null,
|
||||
) {}
|
||||
|
||||
snapshot(): DbData {
|
||||
return readDb(this.map);
|
||||
}
|
||||
|
||||
/** Calls fn after every change, local or remote; returns the unsubscribe. */
|
||||
observe(fn: () => void): () => void {
|
||||
const h = () => fn();
|
||||
this.map.observeDeep(h);
|
||||
return () => this.map.unobserveDeep(h);
|
||||
}
|
||||
|
||||
/** Runs fn as one undo step. */
|
||||
tx(fn: () => void) {
|
||||
this.doc.transact(fn, DB_ORIGIN);
|
||||
}
|
||||
|
||||
private list(key: Key): Y.Array<YItem> {
|
||||
let a = this.map.get(key);
|
||||
if (!(a instanceof Y.Array)) {
|
||||
a = new Y.Array<YItem>();
|
||||
this.map.set(key, a);
|
||||
}
|
||||
return a as Y.Array<YItem>;
|
||||
}
|
||||
|
||||
/** The item with id and its index in display order. */
|
||||
private find(key: Key, id: string): { item: YItem; index: number } | null {
|
||||
const list = ordered(this.list(key));
|
||||
const index = list.findIndex((m) => m.get("id") === id);
|
||||
return index < 0 ? null : { item: list[index]!, index };
|
||||
}
|
||||
|
||||
/** Inserts items at index at of the display order (the end by default). */
|
||||
private insertAt(key: Key, at: number | undefined, items: YItem[]) {
|
||||
const a = this.list(key);
|
||||
const list = ordered(a);
|
||||
let i = Math.max(0, Math.min(at ?? list.length, list.length));
|
||||
for (const item of items) {
|
||||
item.set("pos", posAt(list, i));
|
||||
list.splice(i++, 0, item);
|
||||
}
|
||||
a.push(items);
|
||||
}
|
||||
|
||||
private moveTo(key: Key, id: string, to: number) {
|
||||
const found = this.find(key, id);
|
||||
if (!found || found.index === to) return;
|
||||
found.item.set("pos", posAt(ordered(this.list(key)), to, found.item));
|
||||
}
|
||||
|
||||
private remove(key: Key, item: YItem) {
|
||||
const a = this.list(key);
|
||||
const i = a.toArray().indexOf(item);
|
||||
if (i >= 0) a.delete(i, 1);
|
||||
}
|
||||
|
||||
setTitle(title: string) {
|
||||
this.tx(() => this.map.set("title", title));
|
||||
}
|
||||
|
||||
// ---- columns ----
|
||||
|
||||
addColumn(type: ColumnType, name: string, at?: number): string {
|
||||
const col: Column = { id: newId(), name, type };
|
||||
if (type === "select" || type === "multiSelect") col.options = [];
|
||||
this.tx(() => this.insertAt("columns", at, [columnToY(col)]));
|
||||
return col.id;
|
||||
}
|
||||
|
||||
renameColumn(id: string, name: string) {
|
||||
this.tx(() => this.find("columns", id)?.item.set("name", name));
|
||||
}
|
||||
|
||||
setOptions(id: string, options: SelectOption[]) {
|
||||
this.tx(() => this.find("columns", id)?.item.set("options", options));
|
||||
}
|
||||
|
||||
/** Changes a column's type and converts every row's value. */
|
||||
changeType(id: string, type: ColumnType) {
|
||||
const db = this.snapshot();
|
||||
const col = db.columns.find((c) => c.id === id);
|
||||
if (!col || col.type === type || col.type === "title" || type === "title") return;
|
||||
let options = type === "select" || type === "multiSelect" ? (col.options ?? []) : [];
|
||||
const values = new Map<string, unknown>();
|
||||
for (const r of db.rows) {
|
||||
const out = convertValue(r.cells[id], col, type, options);
|
||||
options = out.options;
|
||||
values.set(r.id, out.value);
|
||||
}
|
||||
this.tx(() => {
|
||||
const found = this.find("columns", id);
|
||||
if (!found) return;
|
||||
found.item.set("type", type);
|
||||
if (type === "select" || type === "multiSelect") found.item.set("options", options);
|
||||
else found.item.delete("options");
|
||||
for (const yr of this.list("rows").toArray()) {
|
||||
const cells = yr.get("cells");
|
||||
if (!(cells instanceof Y.Map)) continue;
|
||||
const v = values.get(String(yr.get("id")));
|
||||
if (isEmpty(v) || v === false) cells.delete(id);
|
||||
else cells.set(id, v);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteColumn(id: string) {
|
||||
this.tx(() => {
|
||||
const found = this.find("columns", id);
|
||||
if (!found || found.item.get("type") === "title") return;
|
||||
this.remove("columns", found.item);
|
||||
for (const yr of this.list("rows").toArray()) {
|
||||
const cells = yr.get("cells");
|
||||
if (cells instanceof Y.Map) cells.delete(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
moveColumn(id: string, to: number) {
|
||||
this.tx(() => this.moveTo("columns", id, to));
|
||||
}
|
||||
|
||||
duplicateColumn(id: string, name: string): string | null {
|
||||
const col = this.snapshot().columns.find((c) => c.id === id);
|
||||
if (!col || col.type === "title") return null;
|
||||
const copy: Column = { ...structuredClone(col), id: newId(), name };
|
||||
this.tx(() => {
|
||||
const found = this.find("columns", id);
|
||||
if (!found) return;
|
||||
this.insertAt("columns", found.index + 1, [columnToY(copy)]);
|
||||
for (const yr of this.list("rows").toArray()) {
|
||||
const cells = yr.get("cells");
|
||||
if (cells instanceof Y.Map && cells.has(id)) cells.set(copy.id, cells.get(id));
|
||||
}
|
||||
});
|
||||
return copy.id;
|
||||
}
|
||||
|
||||
// ---- rows ----
|
||||
|
||||
/** Adds a row with these cells at index at (the end by default); returns its id. */
|
||||
addRow(cells: Record<string, unknown> = {}, at?: number): string {
|
||||
return this.addRows([cells], at)[0]!;
|
||||
}
|
||||
|
||||
/** Adds many rows in one undo step (paste, CSV import). */
|
||||
addRows(list: Record<string, unknown>[], at?: number): string[] {
|
||||
const me = this.me();
|
||||
const now = Date.now();
|
||||
const rows: Row[] = list.map((cells, i) => ({ id: newId(), cells, createdAt: now + i, createdBy: me }));
|
||||
this.tx(() => this.insertAt("rows", at, rows.map(rowToY)));
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
setCell(row: string, col: string, value: unknown) {
|
||||
this.setCells([{ row, col, value }]);
|
||||
}
|
||||
|
||||
/** Sets several cells in one undo step. Empty values are removed. */
|
||||
setCells(changes: { row: string; col: string; value: unknown }[]) {
|
||||
this.tx(() => {
|
||||
for (const { row, col, value } of changes) {
|
||||
const cells = this.find("rows", row)?.item.get("cells");
|
||||
if (!(cells instanceof Y.Map)) continue;
|
||||
if (isEmpty(value)) cells.delete(col);
|
||||
else cells.set(col, value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
deleteRows(ids: string[]) {
|
||||
this.tx(() => {
|
||||
const a = this.list("rows");
|
||||
for (let i = a.length - 1; i >= 0; i--) {
|
||||
if (ids.includes(String(a.get(i)?.get("id")))) a.delete(i, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Moves a row to index to of the full, unfiltered order. */
|
||||
moveRow(id: string, to: number) {
|
||||
this.tx(() => this.moveTo("rows", id, to));
|
||||
}
|
||||
|
||||
duplicateRow(id: string): string | null {
|
||||
const found = this.find("rows", id);
|
||||
if (!found) return null;
|
||||
const copy = cloneRow(found.item, this.me());
|
||||
this.tx(() => this.insertAt("rows", found.index + 1, [copy]));
|
||||
return String(copy.get("id"));
|
||||
}
|
||||
|
||||
/** The row's body fragment, made on first use (opening a row as a page). */
|
||||
rowBody(id: string): Y.XmlFragment | null {
|
||||
const found = this.find("rows", id);
|
||||
if (!found) return null;
|
||||
const body = found.item.get("body");
|
||||
if (body instanceof Y.XmlFragment) return body;
|
||||
const fresh = new Y.XmlFragment();
|
||||
this.tx(() => found.item.set("body", fresh));
|
||||
return fresh;
|
||||
}
|
||||
|
||||
/** The row's index in the full order, or -1. */
|
||||
rowIndex(id: string): number {
|
||||
return this.find("rows", id)?.index ?? -1;
|
||||
}
|
||||
|
||||
// ---- views ----
|
||||
|
||||
addView(type: ViewType, name: string): string {
|
||||
const view = defaultView(type, name, this.snapshot().columns);
|
||||
this.tx(() => this.insertAt("views", undefined, [viewToY(view)]));
|
||||
return view.id;
|
||||
}
|
||||
|
||||
updateView(id: string, patch: Partial<Omit<View, "id">>) {
|
||||
this.tx(() => {
|
||||
const found = this.find("views", id);
|
||||
if (!found) return;
|
||||
for (const [k, v] of Object.entries(patch)) found.item.set(k, v);
|
||||
});
|
||||
}
|
||||
|
||||
duplicateView(id: string, name: string): string | null {
|
||||
const view = this.snapshot().views.find((v) => v.id === id);
|
||||
if (!view) return null;
|
||||
const copy: View = { ...structuredClone(view), id: newId(), name };
|
||||
this.tx(() => {
|
||||
const found = this.find("views", id);
|
||||
this.insertAt("views", (found?.index ?? -1) + 1, [viewToY(copy)]);
|
||||
});
|
||||
return copy.id;
|
||||
}
|
||||
|
||||
deleteView(id: string) {
|
||||
this.tx(() => {
|
||||
const found = this.find("views", id);
|
||||
if (found && this.list("views").length > 1) this.remove("views", found.item);
|
||||
});
|
||||
}
|
||||
|
||||
moveView(id: string, to: number) {
|
||||
this.tx(() => this.moveTo("views", id, to));
|
||||
}
|
||||
}
|
||||
|
||||
/** Copies a row map with a new id, its cells and its body. */
|
||||
function cloneRow(m: YItem, me: Person | null): YItem {
|
||||
const out = new Y.Map<unknown>();
|
||||
out.set("id", newId());
|
||||
out.set("createdAt", Date.now());
|
||||
const by = me ?? m.get("createdBy");
|
||||
if (isObject(by)) out.set("createdBy", by);
|
||||
const cells = new Y.Map<unknown>();
|
||||
const old = m.get("cells");
|
||||
if (old instanceof Y.Map) for (const [k, v] of old.entries()) cells.set(k, v);
|
||||
out.set("cells", cells);
|
||||
const body = m.get("body");
|
||||
if (body instanceof Y.XmlFragment && body.length) {
|
||||
const copy = new Y.XmlFragment();
|
||||
copy.insert(
|
||||
0,
|
||||
body.toArray().map((n) => n.clone() as Y.XmlElement | Y.XmlText),
|
||||
);
|
||||
out.set("body", copy);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The database's JSON with row bodies, for copying (ADR-13: a pasted copy seeds its own map). */
|
||||
export function exportDb(m: YItem, bodyJSON: (f: Y.XmlFragment) => unknown[]): DbData {
|
||||
const db = readDb(m);
|
||||
const rows = m.get("rows");
|
||||
if (rows instanceof Y.Array) {
|
||||
const bodies = new Map<string, Y.XmlFragment>();
|
||||
for (const r of rows.toArray() as YItem[]) {
|
||||
const b = r.get("body");
|
||||
if (b instanceof Y.XmlFragment && b.length) bodies.set(String(r.get("id")), b);
|
||||
}
|
||||
for (const r of db.rows) {
|
||||
const b = bodies.get(r.id);
|
||||
if (b) r.body = bodyJSON(b) as Row["body"];
|
||||
}
|
||||
}
|
||||
return db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a database with row bodies (from exportDb or the server's JSON)
|
||||
* into the blocks map under id. Bodies are written once the map is part of
|
||||
* the document, which y-prosemirror needs.
|
||||
*/
|
||||
export function seedDb(doc: Y.Doc, id: string, data: DbData, writeBody: (json: unknown[], f: Y.XmlFragment) => void) {
|
||||
doc.transact(() => {
|
||||
const m = dbToY(data);
|
||||
blocksOf(doc).set(id, m);
|
||||
const rows = m.get("rows") as Y.Array<YItem>;
|
||||
const byId = new Map(data.rows.map((r) => [r.id, r]));
|
||||
for (const yr of rows.toArray()) {
|
||||
const body = byId.get(String(yr.get("id")))?.body;
|
||||
if (!body?.length) continue;
|
||||
const f = new Y.XmlFragment();
|
||||
yr.set("body", f);
|
||||
writeBody(body, f);
|
||||
}
|
||||
}, DB_ORIGIN);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1240,3 +1240,930 @@
|
||||
.dw-prose .dw-synced__body .dw-prose {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* ---- Databases (database/): table, kanban and calendar views ---- */
|
||||
.dw-db-node {
|
||||
margin: 1em 0;
|
||||
}
|
||||
.dw-db {
|
||||
font-family: var(--font-sans);
|
||||
font-size: 14px;
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.dw-db__head {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
.dw-db__title,
|
||||
.dw-db__title-input {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 650;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.dw-db__title .is-empty {
|
||||
color: var(--color-ink-faint);
|
||||
}
|
||||
.dw-db__title-input {
|
||||
width: 100%;
|
||||
padding: 2px 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font-family: inherit;
|
||||
}
|
||||
.dw-db__title-input:focus {
|
||||
outline: none;
|
||||
}
|
||||
.dw-db__title-input::placeholder {
|
||||
color: var(--color-ink-faint);
|
||||
}
|
||||
.dw-db__bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 4px 12px;
|
||||
padding-bottom: 4px;
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
}
|
||||
.dw-db__tabs,
|
||||
.dw-db__tools {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
.dw-db__tab,
|
||||
.dw-db__btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 28px;
|
||||
padding: 2px 8px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: none;
|
||||
color: var(--color-ink-muted);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db__tab:hover,
|
||||
.dw-db__btn:hover:not(:disabled) {
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.dw-db__tab.is-active {
|
||||
color: var(--color-ink);
|
||||
font-weight: 600;
|
||||
box-shadow: inset 0 -2px 0 var(--color-accent);
|
||||
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
|
||||
}
|
||||
.dw-db__btn--icon {
|
||||
width: 28px;
|
||||
padding: 0;
|
||||
justify-content: center;
|
||||
}
|
||||
.dw-db__btn.is-on {
|
||||
color: var(--color-accent);
|
||||
}
|
||||
.dw-db__btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
.dw-db__btn[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.dw-db__btn--primary {
|
||||
background: var(--color-primary);
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
.dw-db__btn--primary:hover:not(:disabled) {
|
||||
background: var(--color-primary-hover);
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
.dw-db__tab:focus-visible,
|
||||
.dw-db__btn:focus-visible,
|
||||
.dw-db-t__head:focus-visible,
|
||||
.dw-db-t__wrap:focus-visible,
|
||||
.dw-db-k__card:focus-visible,
|
||||
.dw-db-peek__value:focus-visible {
|
||||
outline: 2px solid var(--color-focus-ring);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
.dw-db__search {
|
||||
width: 12rem;
|
||||
max-width: 50vw;
|
||||
}
|
||||
.dw-db__search[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.dw-db__bulk {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 8px;
|
||||
margin-top: 4px;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-accent-soft);
|
||||
font-size: 13px;
|
||||
}
|
||||
.dw-db__bulk[hidden] {
|
||||
display: none;
|
||||
}
|
||||
.dw-db__empty {
|
||||
margin: 12px 0;
|
||||
color: var(--color-ink-faint);
|
||||
font-size: 13px;
|
||||
}
|
||||
.dw-db__more {
|
||||
margin-top: 4px;
|
||||
}
|
||||
.dw-db-input {
|
||||
width: 100%;
|
||||
min-height: 30px;
|
||||
padding: 4px 8px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
}
|
||||
.dw-db-input--small {
|
||||
width: 9rem;
|
||||
}
|
||||
.dw-db-input:focus,
|
||||
.dw-db-select:focus {
|
||||
outline: 2px solid var(--color-focus-ring);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
.dw-db-select {
|
||||
min-height: 30px;
|
||||
max-width: 12rem;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* Tags (select choices), people and files inside cells. */
|
||||
.dw-db-tags {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
.dw-db-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
max-width: 100%;
|
||||
padding: 0 6px;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--dw-bg, var(--dw-bg-gray));
|
||||
color: var(--color-ink);
|
||||
font-size: 12.5px;
|
||||
line-height: 20px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.dw-db-tag__x {
|
||||
padding: 0 2px;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--color-ink-muted);
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-person,
|
||||
.dw-db-file {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 13px;
|
||||
color: var(--color-ink);
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dw-db-person__dot {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-accent-soft);
|
||||
color: var(--color-accent);
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.dw-db-check {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 1.5px solid var(--color-line-strong);
|
||||
border-radius: 4px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.dw-db-check.is-on {
|
||||
border-color: var(--color-accent);
|
||||
background: var(--color-accent);
|
||||
color: var(--color-on-primary);
|
||||
}
|
||||
.dw-db-progress {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
.dw-db-progress__bar {
|
||||
flex: 1;
|
||||
height: 6px;
|
||||
border-radius: 3px;
|
||||
background: var(--color-surface-sunken);
|
||||
overflow: hidden;
|
||||
}
|
||||
.dw-db-progress__fill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--color-accent);
|
||||
}
|
||||
.dw-db-progress__num {
|
||||
min-width: 3ch;
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.dw-db-cell__title {
|
||||
font-weight: 550;
|
||||
}
|
||||
.dw-db-cell__title.is-empty {
|
||||
color: var(--color-ink-faint);
|
||||
font-weight: 400;
|
||||
}
|
||||
.dw-db-cell__number {
|
||||
display: block;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.dw-db-cell__link {
|
||||
color: var(--color-accent);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ---- Table view ---- */
|
||||
.dw-db-t__wrap {
|
||||
overflow-x: auto;
|
||||
outline: none;
|
||||
}
|
||||
.dw-prose .dw-db-t,
|
||||
.dw-db-t {
|
||||
width: max-content;
|
||||
min-width: 100%;
|
||||
margin: 0;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.dw-prose .dw-db-t th,
|
||||
.dw-prose .dw-db-t td,
|
||||
.dw-db-t th,
|
||||
.dw-db-t td {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
background: none;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.dw-prose .dw-db-t th + th,
|
||||
.dw-prose .dw-db-t td.dw-db-t__cell + td.dw-db-t__cell,
|
||||
.dw-db-t th + th,
|
||||
.dw-db-t td.dw-db-t__cell + td.dw-db-t__cell {
|
||||
border-left: 1px solid var(--color-line);
|
||||
}
|
||||
.dw-db-t__gutter-col {
|
||||
width: 48px;
|
||||
}
|
||||
.dw-db-t__add-col {
|
||||
width: 40px;
|
||||
}
|
||||
.dw-db-t__gutter {
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dw-db-t__pick,
|
||||
.dw-db-t__grip {
|
||||
opacity: 0;
|
||||
vertical-align: middle;
|
||||
}
|
||||
.dw-db-t__grip {
|
||||
display: inline-grid;
|
||||
color: var(--color-ink-faint);
|
||||
cursor: grab;
|
||||
}
|
||||
.dw-db-t tr:hover .dw-db-t__pick,
|
||||
.dw-db-t tr:hover .dw-db-t__grip,
|
||||
.dw-db-t tr.is-picked .dw-db-t__pick,
|
||||
.dw-db-t__pick:focus-visible {
|
||||
opacity: 1;
|
||||
}
|
||||
.dw-db-t tr.is-picked td {
|
||||
background: var(--color-accent-soft);
|
||||
}
|
||||
.dw-db-t__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
min-height: 34px;
|
||||
padding: 0 8px;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--color-ink-muted);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-t__head:hover {
|
||||
background: var(--color-surface-hover);
|
||||
}
|
||||
.dw-db-t__name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dw-db-t__name-input {
|
||||
width: 100%;
|
||||
min-height: 34px;
|
||||
padding: 0 8px;
|
||||
border: none;
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
outline: 2px solid var(--color-focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.dw-db-t__resize {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: -3px;
|
||||
z-index: 1;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.dw-db-t__resize:hover {
|
||||
background: var(--color-accent);
|
||||
}
|
||||
.dw-db-t th.is-drop {
|
||||
box-shadow: inset 3px 0 0 var(--color-accent);
|
||||
}
|
||||
.dw-prose .dw-db-t td.dw-db-t__cell,
|
||||
.dw-db-t__cell {
|
||||
height: 34px;
|
||||
padding: 4px 8px;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
cursor: default;
|
||||
}
|
||||
.dw-db-t__cell.is-in-range {
|
||||
background: var(--color-selection);
|
||||
}
|
||||
.dw-db-t__cell.is-selected {
|
||||
box-shadow: inset 0 0 0 2px var(--color-focus-ring);
|
||||
}
|
||||
.dw-prose .dw-db-t td.dw-db-t__cell.is-editing {
|
||||
padding: 0;
|
||||
}
|
||||
.dw-db-cell__input {
|
||||
width: 100%;
|
||||
height: 34px;
|
||||
padding: 0 8px;
|
||||
border: none;
|
||||
background: var(--color-surface);
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
outline: 2px solid var(--color-focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.dw-db-t__open {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 6px;
|
||||
display: none;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--color-surface-raised);
|
||||
color: var(--color-ink-muted);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
transform: translateY(-50%);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-t tr:hover .dw-db-t__open,
|
||||
.dw-db-t__open:focus-visible {
|
||||
display: inline-flex;
|
||||
}
|
||||
.dw-db-t tr.is-drop-above td {
|
||||
box-shadow: inset 0 2px 0 var(--color-accent);
|
||||
}
|
||||
.dw-db-t tr.is-drop-below td {
|
||||
box-shadow: inset 0 -2px 0 var(--color-accent);
|
||||
}
|
||||
.dw-db-t__new,
|
||||
.dw-db-t__group {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
min-height: 32px;
|
||||
padding: 0 8px;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--color-ink-faint);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-t__new:hover {
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.dw-db-t__group {
|
||||
color: var(--color-ink);
|
||||
font-weight: 600;
|
||||
padding-top: 8px;
|
||||
}
|
||||
.dw-db-t__count {
|
||||
color: var(--color-ink-faint);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
}
|
||||
.dw-prose .dw-db-t .dw-db-t__group-row td,
|
||||
.dw-prose .dw-db-t .dw-db-t__new-row td {
|
||||
border-bottom-color: transparent;
|
||||
}
|
||||
|
||||
/* ---- Kanban view ---- */
|
||||
.dw-db-k {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
padding: 12px 0 4px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.dw-db-k__col {
|
||||
flex: 0 0 260px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.dw-db-k__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-height: 24px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.dw-db-k__label {
|
||||
font-weight: 600;
|
||||
}
|
||||
.dw-db-k__cards {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-height: 48px;
|
||||
padding: 4px;
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface-sunken);
|
||||
}
|
||||
.dw-db-k__cards.is-drop {
|
||||
outline: 2px dashed var(--color-accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.dw-db-k__card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-surface-raised);
|
||||
box-shadow: 0 1px 2px rgb(0 0 0 / 0.04);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-k__card:hover {
|
||||
border-color: var(--color-line-strong);
|
||||
}
|
||||
.dw-db-k__card.is-dragging {
|
||||
opacity: 0.4;
|
||||
}
|
||||
.dw-db-k__prop .dw-db-cell__number {
|
||||
text-align: left;
|
||||
}
|
||||
.dw-db-k__prop {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 13px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* ---- Calendar view ---- */
|
||||
.dw-db-c {
|
||||
padding-top: 8px;
|
||||
}
|
||||
.dw-db-c__nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.dw-db-c__month {
|
||||
margin-right: auto;
|
||||
font-size: 15px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
.dw-db-c__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, minmax(0, 1fr));
|
||||
border-top: 1px solid var(--color-line);
|
||||
border-left: 1px solid var(--color-line);
|
||||
}
|
||||
.dw-db-c__wd {
|
||||
padding: 4px 6px;
|
||||
border-right: 1px solid var(--color-line);
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 12px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
.dw-db-c__day {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
min-height: 88px;
|
||||
padding: 4px;
|
||||
border-right: 1px solid var(--color-line);
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
}
|
||||
.dw-db-c__day.is-out {
|
||||
background: var(--color-surface-sunken);
|
||||
}
|
||||
.dw-db-c__day.is-out .dw-db-c__num {
|
||||
color: var(--color-ink-faint);
|
||||
}
|
||||
.dw-db-c__day.is-drop {
|
||||
background: var(--color-accent-soft);
|
||||
}
|
||||
.dw-db-c__num {
|
||||
align-self: flex-start;
|
||||
min-width: 22px;
|
||||
padding: 0 4px;
|
||||
border-radius: 11px;
|
||||
font-size: 12px;
|
||||
line-height: 22px;
|
||||
text-align: center;
|
||||
}
|
||||
.dw-db-c__day.is-today .dw-db-c__num {
|
||||
background: var(--color-accent);
|
||||
color: var(--color-on-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
.dw-db-c__chip {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 1px 6px;
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--color-accent-soft);
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-c__add {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
right: 4px;
|
||||
display: none;
|
||||
place-items: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-ink-muted);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-c__day:hover .dw-db-c__add,
|
||||
.dw-db-c__add:focus-visible {
|
||||
display: grid;
|
||||
}
|
||||
.dw-db-c__undated {
|
||||
margin-top: 8px;
|
||||
font-size: 13px;
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
.dw-db-c__chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.dw-db-c__chips .dw-db-c__chip {
|
||||
width: auto;
|
||||
max-width: 16rem;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.dw-db-c__day {
|
||||
min-height: 56px;
|
||||
}
|
||||
.dw-db-c__chip {
|
||||
padding: 0 3px;
|
||||
font-size: 11px;
|
||||
}
|
||||
.dw-db__tools .dw-db__btn span {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Panels and pickers (outside the page, in body) ---- */
|
||||
.dw-db-pop {
|
||||
position: fixed;
|
||||
z-index: 70;
|
||||
left: 0;
|
||||
top: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 14rem;
|
||||
max-width: calc(100vw - 16px);
|
||||
max-height: 24rem;
|
||||
overflow-y: auto;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--color-line);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-surface-raised);
|
||||
box-shadow: var(--shadow-menu);
|
||||
color: var(--color-ink);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 13px;
|
||||
}
|
||||
.dw-db-pop--panel {
|
||||
min-width: 20rem;
|
||||
}
|
||||
.dw-db-pop--choices {
|
||||
width: 18rem;
|
||||
}
|
||||
.dw-db-pop__row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.dw-db-pop__row--end {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.dw-db-pop__line {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.dw-db-pop__label {
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
.dw-db-pop__list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
.dw-db-pop__item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: 30px;
|
||||
padding: 2px 6px;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
background: none;
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-pop__item:hover:not(:disabled),
|
||||
.dw-db-pop__item.is-active {
|
||||
background: var(--color-surface-hover);
|
||||
}
|
||||
.dw-db-pop__item:disabled {
|
||||
cursor: default;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.dw-db-pop__check {
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
width: 16px;
|
||||
color: var(--color-ink-muted);
|
||||
}
|
||||
.dw-db-pop__grow {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dw-db-pop__more {
|
||||
margin-left: auto;
|
||||
}
|
||||
.dw-db-pop__chosen:empty {
|
||||
display: none;
|
||||
}
|
||||
.dw-db-pop__empty {
|
||||
margin: 4px 2px;
|
||||
color: var(--color-ink-faint);
|
||||
}
|
||||
.dw-db-pop__add {
|
||||
align-self: flex-start;
|
||||
}
|
||||
.dw-db-switch {
|
||||
position: relative;
|
||||
flex-shrink: 0;
|
||||
width: 28px;
|
||||
height: 16px;
|
||||
border-radius: 8px;
|
||||
background: var(--color-line-strong);
|
||||
}
|
||||
.dw-db-switch::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-surface);
|
||||
transition: transform 0.12s;
|
||||
}
|
||||
.dw-db-switch.is-on {
|
||||
background: var(--color-accent);
|
||||
}
|
||||
.dw-db-switch.is-on::after {
|
||||
transform: translateX(12px);
|
||||
}
|
||||
.dw-db-range {
|
||||
flex: 1;
|
||||
accent-color: var(--color-accent);
|
||||
}
|
||||
|
||||
/* ---- A row opened as a page ---- */
|
||||
.dw-db-peek {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 65;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
background: rgb(0 0 0 / 0.25);
|
||||
}
|
||||
.dw-db-peek__panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: min(720px, 100vw);
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
background: var(--color-surface);
|
||||
box-shadow: var(--shadow-dialog);
|
||||
outline: none;
|
||||
font-family: var(--font-sans);
|
||||
color: var(--color-ink);
|
||||
}
|
||||
.dw-db-peek__panel.is-wide {
|
||||
width: 100vw;
|
||||
}
|
||||
.dw-db-peek__head {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 8px 16px;
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
background: var(--color-surface);
|
||||
}
|
||||
.dw-db-peek__db {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.dw-db-peek__grow {
|
||||
flex: 1;
|
||||
}
|
||||
.dw-db-peek__props {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
padding: 24px 48px 12px;
|
||||
border-bottom: 1px solid var(--color-line);
|
||||
}
|
||||
.dw-db-peek__panel.is-wide .dw-db-peek__props,
|
||||
.dw-db-peek__panel.is-wide .dw-db-peek__body {
|
||||
box-sizing: border-box;
|
||||
width: min(900px, 100%);
|
||||
margin: 0 auto;
|
||||
}
|
||||
.dw-db-peek__title {
|
||||
width: 100%;
|
||||
margin: 0 0 12px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--color-ink);
|
||||
font: inherit;
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.dw-db-peek__title:focus {
|
||||
outline: none;
|
||||
}
|
||||
.dw-db-peek__prop {
|
||||
display: grid;
|
||||
grid-template-columns: 11rem minmax(0, 1fr);
|
||||
align-items: center;
|
||||
min-height: 34px;
|
||||
}
|
||||
.dw-db-peek__label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
overflow: hidden;
|
||||
color: var(--color-ink-muted);
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dw-db-peek__value {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
min-height: 30px;
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
.dw-db-peek__value:hover {
|
||||
background: var(--color-surface-hover);
|
||||
}
|
||||
.dw-db-peek__value.is-editing {
|
||||
padding: 0;
|
||||
}
|
||||
.dw-db-peek__add {
|
||||
align-self: flex-start;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.dw-db-peek__body {
|
||||
padding: 16px 48px 64px;
|
||||
}
|
||||
.dw-db-peek__note {
|
||||
color: var(--color-ink-faint);
|
||||
font-size: 14px;
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.dw-db-peek__props,
|
||||
.dw-db-peek__body {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
}
|
||||
.dw-db-peek__prop {
|
||||
grid-template-columns: 8rem minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ import StarterKit from "@tiptap/starter-kit";
|
||||
import { BlockLinks } from "./blocklinks";
|
||||
import { docwellAlign, docwellTables, docwellTasks, HeadingShortcuts } from "./blocks";
|
||||
import { Callout } from "./callout";
|
||||
import { Database } from "./database";
|
||||
import { DB_ORIGIN } from "./database/store";
|
||||
import { DocwellCodeBlock } from "./codeblock";
|
||||
import { DocwellHighlight, TextColor } from "./colors";
|
||||
import { CommentHighlights } from "./comments";
|
||||
@@ -65,6 +67,8 @@ export interface ExtensionOptions {
|
||||
* without carets, undo or synced pages of its own.
|
||||
*/
|
||||
syncedDoc?: Y.Doc;
|
||||
/** Edits a database row's body (database/peek.ts): bound to this fragment of doc, without carets. */
|
||||
rowBody?: { doc: Y.Doc; fragment: Y.XmlFragment };
|
||||
/** The Draw.io embed address (default https://embed.diagrams.net). */
|
||||
drawioUrl?: string;
|
||||
/** Loads Mermaid; without it diagrams show as their text. */
|
||||
@@ -75,6 +79,8 @@ export interface ExtensionOptions {
|
||||
loadPdf?: PdfLoader;
|
||||
/** Whether code blocks show line numbers unless one was switched on or off itself. */
|
||||
codeLineNumbers?: boolean;
|
||||
/** Shows a database row's body read-only (a row in a synced page). */
|
||||
rowFragmentReadOnly?: Y.XmlFragment;
|
||||
labels?: EditorLabels;
|
||||
/** Clicking highlighted comment text calls this with the comment id. */
|
||||
onCommentSelect?: (id: string) => void;
|
||||
@@ -109,7 +115,7 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
|
||||
codeBlock: false,
|
||||
link: { openOnClick: false, autolink: true },
|
||||
// Collaboration brings its own undo history, scoped to the local user.
|
||||
undoRedo: opts.collab || opts.syncedDoc ? false : undefined,
|
||||
undoRedo: opts.collab || opts.syncedDoc || opts.rowBody || opts.rowFragmentReadOnly ? false : undefined,
|
||||
}),
|
||||
Placeholder.configure({ placeholder: opts.placeholder ?? "Type '/' for commands…" }),
|
||||
DocwellImage.configure({ host: opts.files }),
|
||||
@@ -162,12 +168,50 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
|
||||
LinkCard.configure({ labels }),
|
||||
BlockLinks.configure({ labels, link: opts.blockLink, onCopied: opts.onBlockLinkCopied }),
|
||||
FindReplace,
|
||||
Database.configure({
|
||||
labels,
|
||||
doc: opts.collab?.provider.doc ?? opts.syncedDoc ?? opts.rowBody?.doc,
|
||||
readOnlyDoc: !!opts.syncedDoc,
|
||||
undoScope: !opts.rowBody,
|
||||
files: opts.files,
|
||||
people: opts.mentions,
|
||||
me: () => {
|
||||
const id = opts.mentions?.me;
|
||||
return id ? { id, name: opts.collab?.user.name ?? "" } : null;
|
||||
},
|
||||
// A row body is a page of its own: the same blocks, minus carets and synced pages.
|
||||
rowExtensions: (fragment) => {
|
||||
const doc = opts.collab?.provider.doc ?? opts.syncedDoc ?? opts.rowBody?.doc;
|
||||
return docwellExtensions({
|
||||
rowBody: fragment && doc && !opts.syncedDoc ? { doc, fragment } : undefined,
|
||||
files: opts.files,
|
||||
mentions: opts.mentions,
|
||||
pages: opts.pages,
|
||||
links: opts.links,
|
||||
onNavigate: opts.onNavigate,
|
||||
drawioUrl: opts.drawioUrl,
|
||||
loadMermaid: opts.loadMermaid,
|
||||
loadExcalidraw: opts.loadExcalidraw,
|
||||
loadPdf: opts.loadPdf,
|
||||
codeLineNumbers: opts.codeLineNumbers,
|
||||
labels: opts.labels,
|
||||
placeholder: labels.database.bodyPlaceholder,
|
||||
rowFragmentReadOnly: !!fragment && !!opts.syncedDoc ? fragment : undefined,
|
||||
});
|
||||
},
|
||||
}),
|
||||
];
|
||||
if (opts.syncedDoc) {
|
||||
// Database edits (DB_ORIGIN) are undone with the text they were made with.
|
||||
const yUndoOptions = { trackedOrigins: [DB_ORIGIN] };
|
||||
if (opts.rowBody) {
|
||||
list.push(Collaboration.configure({ document: opts.rowBody.doc, fragment: opts.rowBody.fragment, yUndoOptions }));
|
||||
} else if (opts.rowFragmentReadOnly) {
|
||||
list.push(Collaboration.configure({ fragment: opts.rowFragmentReadOnly }));
|
||||
} else if (opts.syncedDoc) {
|
||||
list.push(Collaboration.configure({ document: opts.syncedDoc }));
|
||||
} else if (opts.collab) {
|
||||
list.push(
|
||||
Collaboration.configure({ document: opts.collab.provider.doc }),
|
||||
Collaboration.configure({ document: opts.collab.provider.doc, yUndoOptions }),
|
||||
CollaborationCaret.configure({ provider: opts.collab.provider, user: opts.collab.user, render: renderCaret }),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { englishDatabaseLabels, type DatabaseLabels } from "./database/labels";
|
||||
|
||||
/**
|
||||
* The editor's own words (menus, buttons). The editor has no i18n of its own:
|
||||
* hosts pass translated labels, and English is the default.
|
||||
@@ -141,6 +143,8 @@ export interface EditorLabels {
|
||||
/** The button that opens the date's journal page, where the host has journals. */
|
||||
openJournal?: string;
|
||||
};
|
||||
/** The database block (database/labels.ts). */
|
||||
database: DatabaseLabels;
|
||||
}
|
||||
|
||||
export const englishLabels: EditorLabels = {
|
||||
@@ -176,6 +180,7 @@ export const englishLabels: EditorLabels = {
|
||||
embed: { label: "Embed", description: "A video, design or document from YouTube, Figma and more" },
|
||||
linkCard: { label: "Link card", description: "A link with its page's title and picture" },
|
||||
syncedPage: { label: "Synced page", description: "Show another page here, always up to date" },
|
||||
database: { label: "Database", description: "Records in a table, board or calendar" },
|
||||
newPage: { label: "New page", description: "Make a page and link it here" },
|
||||
today: { label: "Today", description: "Insert today's date" },
|
||||
tomorrow: { label: "Tomorrow", description: "Insert tomorrow's date" },
|
||||
@@ -307,4 +312,5 @@ export const englishLabels: EditorLabels = {
|
||||
edit: "Change date",
|
||||
openJournal: "Open journal",
|
||||
},
|
||||
database: englishDatabaseLabels,
|
||||
};
|
||||
@@ -90,6 +90,9 @@ export function slashCommands(
|
||||
block("table", "table", ["grid", "rows", "columns", "spreadsheet"], (e, r) =>
|
||||
e.chain().focus().deleteRange(r).insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
|
||||
),
|
||||
block("database", "database", ["kanban", "board", "calendar", "records", "tracker", "notion"], (e, r) =>
|
||||
e.chain().focus().deleteRange(r).insertDatabase().run(),
|
||||
),
|
||||
block("quote", "quote", ["blockquote", ">"], (e, r) => e.chain().focus().deleteRange(r).toggleBlockquote().run()),
|
||||
block("code", "code", ["codeblock", "```", "snippet"], (e, r) =>
|
||||
e.chain().focus().deleteRange(r).toggleCodeBlock().run(),
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
export const iconPaths = {
|
||||
page: ["M6 3h8l4 4v14H6z", "M14 3v4h4", "M9 12h6", "M9 16h6"],
|
||||
"chevron-right": ["M10 6l6 6-6 6"],
|
||||
"chevron-left": ["M14 6l-6 6 6 6"],
|
||||
"chevron-down": ["M6 10l6 6 6-6"],
|
||||
"chevron-up": ["M6 14l6-6 6 6"],
|
||||
plus: ["M12 5v14", "M5 12h14"],
|
||||
@@ -126,6 +127,8 @@ export const iconPaths = {
|
||||
layers: ["M12 4l8 4-8 4-8-4z", "M4 12l8 4 8-4", "M4 16l8 4 8-4"],
|
||||
journal: ["M6 3h11a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H6z", "M9 3v18", "M12 8h3", "M12 12h3"],
|
||||
sliders: ["M5 6h14", "M5 12h14", "M5 18h14", "M9 4v4", "M15 10v4", "M11 16v4"],
|
||||
sort: ["M7 4v16", "M4 7l3-3 3 3", "M17 20V4", "M14 17l3 3 3-3"],
|
||||
database: ["M4 5h16v14H4z", "M4 10h16", "M4 15h16", "M10 10v9"],
|
||||
} as const;
|
||||
|
||||
export type IconName = keyof typeof iconPaths;
|
||||
@@ -0,0 +1,167 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Databases (ADR-13) reach the converters as "database" nodes whose
|
||||
// attrs.data holds the records, written by yrs from the page's Y.Doc. Every
|
||||
// export draws one as its title and a table of the first view's visible
|
||||
// columns, in the rows' own order.
|
||||
|
||||
// expandDatabases replaces database nodes, at any depth, with a title and a table.
|
||||
func expandDatabases(n Node) Node {
|
||||
if len(n.Content) == 0 {
|
||||
return n
|
||||
}
|
||||
out := make([]Node, 0, len(n.Content))
|
||||
for _, c := range n.Content {
|
||||
if c.Type == "database" {
|
||||
out = append(out, databaseNodes(c)...)
|
||||
} else {
|
||||
out = append(out, expandDatabases(c))
|
||||
}
|
||||
}
|
||||
n.Content = out
|
||||
return n
|
||||
}
|
||||
|
||||
type dbColumn struct {
|
||||
id, name, typ string
|
||||
options map[string]string
|
||||
}
|
||||
|
||||
func databaseNodes(n Node) []Node {
|
||||
data, _ := n.Attrs["data"].(map[string]any)
|
||||
if data == nil {
|
||||
return nil
|
||||
}
|
||||
var cols []dbColumn
|
||||
for _, raw := range list(data["columns"]) {
|
||||
c, _ := raw.(map[string]any)
|
||||
id, _ := c["id"].(string)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
col := dbColumn{id: id, typ: str(c["type"]), name: str(c["name"]), options: map[string]string{}}
|
||||
for _, o := range list(c["options"]) {
|
||||
if om, ok := o.(map[string]any); ok {
|
||||
col.options[str(om["id"])] = str(om["name"])
|
||||
}
|
||||
}
|
||||
cols = append(cols, col)
|
||||
}
|
||||
// The first view decides which columns show.
|
||||
hidden := map[string]bool{}
|
||||
if views := list(data["views"]); len(views) > 0 {
|
||||
if v, ok := views[0].(map[string]any); ok {
|
||||
for _, h := range list(v["hidden"]) {
|
||||
hidden[str(h)] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
shown := cols[:0:0]
|
||||
for _, c := range cols {
|
||||
if c.typ == "title" || !hidden[c.id] {
|
||||
shown = append(shown, c)
|
||||
}
|
||||
}
|
||||
if len(shown) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
cell := func(typ, text string) Node {
|
||||
p := Node{Type: "paragraph"}
|
||||
if text != "" {
|
||||
p.Content = []Node{{Type: "text", Text: text}}
|
||||
}
|
||||
return Node{Type: typ, Content: []Node{p}}
|
||||
}
|
||||
head := Node{Type: "tableRow"}
|
||||
for _, c := range shown {
|
||||
head.Content = append(head.Content, cell("tableHeader", c.name))
|
||||
}
|
||||
table := Node{Type: "table", Content: []Node{head}}
|
||||
for _, raw := range list(data["rows"]) {
|
||||
r, _ := raw.(map[string]any)
|
||||
if r == nil {
|
||||
continue
|
||||
}
|
||||
row := Node{Type: "tableRow"}
|
||||
for _, c := range shown {
|
||||
row.Content = append(row.Content, cell("tableCell", cellText(c, r)))
|
||||
}
|
||||
table.Content = append(table.Content, row)
|
||||
}
|
||||
var out []Node
|
||||
if title := str(data["title"]); title != "" {
|
||||
out = append(out, Node{Type: "paragraph", Content: []Node{{Type: "text", Text: title, Marks: []Mark{{Type: "bold"}}}}})
|
||||
}
|
||||
return append(out, table)
|
||||
}
|
||||
|
||||
// cellText is a cell as text, like cellText in Packages/editor/src/database/model.ts.
|
||||
func cellText(c dbColumn, row map[string]any) string {
|
||||
cells, _ := row["cells"].(map[string]any)
|
||||
v := cells[c.id]
|
||||
switch c.typ {
|
||||
case "createdTime":
|
||||
if ms, ok := row["createdAt"].(float64); ok && ms > 0 {
|
||||
return time.UnixMilli(int64(ms)).UTC().Format("2006-01-02")
|
||||
}
|
||||
return ""
|
||||
case "createdBy":
|
||||
if p, ok := row["createdBy"].(map[string]any); ok {
|
||||
return str(p["name"])
|
||||
}
|
||||
return ""
|
||||
case "checkbox":
|
||||
if v == true {
|
||||
return "✓"
|
||||
}
|
||||
return ""
|
||||
case "select":
|
||||
return c.options[str(v)]
|
||||
case "multiSelect":
|
||||
var names []string
|
||||
for _, id := range list(v) {
|
||||
if name := c.options[str(id)]; name != "" {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
return strings.Join(names, ", ")
|
||||
case "member", "attachment":
|
||||
var names []string
|
||||
for _, x := range list(v) {
|
||||
if m, ok := x.(map[string]any); ok && str(m["name"]) != "" {
|
||||
names = append(names, str(m["name"]))
|
||||
}
|
||||
}
|
||||
return strings.Join(names, ", ")
|
||||
case "progress":
|
||||
if f, ok := v.(float64); ok {
|
||||
return formatNumber(f) + "%"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return x
|
||||
case float64:
|
||||
return formatNumber(x)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func list(v any) []any {
|
||||
l, _ := v.([]any)
|
||||
return l
|
||||
}
|
||||
|
||||
func str(v any) string {
|
||||
s, _ := v.(string)
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package convert
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDatabaseExportsAsTable(t *testing.T) {
|
||||
doc, err := Parse([]byte(`{"type":"doc","content":[{"type":"callout","content":[{"type":"database","attrs":{"id":"d","data":{
|
||||
"title":"Tasks",
|
||||
"columns":[
|
||||
{"id":"t","name":"Name","type":"title"},
|
||||
{"id":"s","name":"Status","type":"select","options":[{"id":"o","name":"Doing","color":"blue"}]},
|
||||
{"id":"m","name":"Tags","type":"multiSelect","options":[{"id":"a","name":"red"},{"id":"b","name":"blue"}]},
|
||||
{"id":"c","name":"Done","type":"checkbox"},
|
||||
{"id":"h","name":"Secret","type":"text"}
|
||||
],
|
||||
"rows":[
|
||||
{"id":"r1","createdAt":1,"cells":{"t":"Write","s":"o","m":["a","b"],"c":true,"h":"x"}},
|
||||
{"id":"r2","createdAt":2,"cells":{"t":"Ship"}}
|
||||
],
|
||||
"views":[{"id":"v","type":"table","hidden":["h"]}]
|
||||
}}}]}]}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
md := Markdown(doc, Options{})
|
||||
for _, want := range []string{"**Tasks**", "| Name | Status | Tags | Done |", "| Write | Doing | red, blue | ✓ |", "| Ship |"} {
|
||||
if !strings.Contains(md, want) {
|
||||
t.Errorf("markdown lacks %q:\n%s", want, md)
|
||||
}
|
||||
}
|
||||
if strings.Contains(md, "Secret") {
|
||||
t.Errorf("hidden column exported:\n%s", md)
|
||||
}
|
||||
h := HTML(doc, Options{})
|
||||
if !strings.Contains(h, "<th>") || !strings.Contains(h, "Doing") {
|
||||
t.Errorf("html lacks the table:\n%s", h)
|
||||
}
|
||||
if _, err := DOCX("T", doc, DOCXOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := PDF("T", doc, PDFOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ type DOCXOptions struct {
|
||||
// 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) {
|
||||
doc = expandDatabases(doc)
|
||||
w := &docxWriter{o: o}
|
||||
if strings.TrimSpace(title) != "" {
|
||||
w.para(paraProps{style: "Title"}, func() { w.text(title, runProps{}) })
|
||||
|
||||
@@ -45,6 +45,7 @@ var safeURL = regexp.MustCompile(`^(?i)(https?://|mailto:|/|#|\.{0,2}/|[^:/?#]+(
|
||||
|
||||
// HTML renders the document's body as HTML.
|
||||
func HTML(doc Node, o Options) string {
|
||||
doc = expandDatabases(doc)
|
||||
var b strings.Builder
|
||||
for _, n := range doc.Content {
|
||||
writeHTML(&b, n, o)
|
||||
@@ -256,6 +257,7 @@ func writeHTMLText(b *strings.Builder, n Node, o Options) {
|
||||
|
||||
// Markdown renders the document as CommonMark (with ~~strikethrough~~).
|
||||
func Markdown(doc Node, o Options) string {
|
||||
doc = expandDatabases(doc)
|
||||
w := &mdWriter{o: o}
|
||||
w.blocks(doc.Content, "", "")
|
||||
return strings.TrimRight(w.b.String(), "\n") + "\n"
|
||||
|
||||
@@ -5,7 +5,9 @@ package convert
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/csv"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
@@ -254,7 +256,9 @@ func (n *notionReader) resolve(dir, raw string) (string, bool) {
|
||||
return ref, true
|
||||
}
|
||||
|
||||
// notionTable turns a database's CSV into a table, its first row the header.
|
||||
// notionTable turns a database's CSV into a database block (ADR-13): the
|
||||
// header names the columns, the first column is the title, and the other
|
||||
// columns get a type guessed from their values.
|
||||
func notionTable(data []byte) (Node, error) {
|
||||
r := csv.NewReader(bytes.NewReader(bytes.TrimPrefix(data, []byte(utf8BOM))))
|
||||
r.FieldsPerRecord = -1
|
||||
@@ -263,37 +267,153 @@ func notionTable(data []byte) (Node, error) {
|
||||
if err != nil {
|
||||
return Node{}, err
|
||||
}
|
||||
cols := 0
|
||||
for _, row := range rows {
|
||||
cols = max(cols, len(row))
|
||||
}
|
||||
doc := Node{Type: "doc"}
|
||||
if cols == 0 {
|
||||
if len(rows) == 0 || len(rows[0]) == 0 {
|
||||
return doc, nil
|
||||
}
|
||||
table := Node{Type: "table"}
|
||||
for i, row := range rows {
|
||||
tr := Node{Type: "tableRow"}
|
||||
for c := range cols {
|
||||
kind := "tableCell"
|
||||
if i == 0 {
|
||||
kind = "tableHeader"
|
||||
}
|
||||
p := Node{Type: "paragraph"}
|
||||
if c < len(row) {
|
||||
if cell := strings.TrimSpace(row[c]); cell != "" {
|
||||
p.Content = []Node{{Type: "text", Text: cell}}
|
||||
}
|
||||
}
|
||||
attrs := map[string]any{"colspan": float64(1), "rowspan": float64(1), "colwidth": nil}
|
||||
tr.Content = append(tr.Content, Node{Type: kind, Attrs: attrs, Content: []Node{p}})
|
||||
head, body := rows[0], rows[1:]
|
||||
field := func(row []string, i int) string {
|
||||
if i < len(row) {
|
||||
return strings.TrimSpace(row[i])
|
||||
}
|
||||
table.Content = append(table.Content, tr)
|
||||
return ""
|
||||
}
|
||||
doc.Content = []Node{table}
|
||||
type column struct {
|
||||
id, name, typ string
|
||||
options []map[string]any
|
||||
byName map[string]string
|
||||
}
|
||||
colors := []string{"red", "orange", "yellow", "green", "teal", "blue", "purple", "pink"}
|
||||
cols := make([]*column, len(head))
|
||||
for i, name := range head {
|
||||
values := make([]string, 0, len(body))
|
||||
for _, row := range body {
|
||||
values = append(values, field(row, i))
|
||||
}
|
||||
typ := "title"
|
||||
if i > 0 {
|
||||
typ = guessColumnType(values)
|
||||
}
|
||||
if name = strings.TrimSpace(name); name == "" {
|
||||
name = strconv.Itoa(i + 1)
|
||||
}
|
||||
cols[i] = &column{id: shortID(), name: name, typ: typ, byName: map[string]string{}}
|
||||
}
|
||||
var outRows []any
|
||||
for n, row := range body {
|
||||
cells := map[string]any{}
|
||||
for i, c := range cols {
|
||||
v := field(row, i)
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
switch c.typ {
|
||||
case "number":
|
||||
f, _ := strconv.ParseFloat(strings.ReplaceAll(v, ",", "."), 64)
|
||||
cells[c.id] = f
|
||||
case "checkbox":
|
||||
if isYes(v) {
|
||||
cells[c.id] = true
|
||||
}
|
||||
case "date":
|
||||
cells[c.id] = v[:10]
|
||||
case "select":
|
||||
id, ok := c.byName[strings.ToLower(v)]
|
||||
if !ok {
|
||||
id = shortID()
|
||||
c.byName[strings.ToLower(v)] = id
|
||||
c.options = append(c.options, map[string]any{"id": id, "name": v, "color": colors[len(c.options)%len(colors)]})
|
||||
}
|
||||
cells[c.id] = id
|
||||
default:
|
||||
cells[c.id] = v
|
||||
}
|
||||
}
|
||||
outRows = append(outRows, map[string]any{"id": shortID(), "createdAt": float64(n), "cells": cells})
|
||||
}
|
||||
columns := make([]any, len(cols))
|
||||
for i, c := range cols {
|
||||
col := map[string]any{"id": c.id, "name": c.name, "type": c.typ}
|
||||
if c.typ == "select" {
|
||||
opts := make([]any, len(c.options))
|
||||
for j, o := range c.options {
|
||||
opts[j] = o
|
||||
}
|
||||
col["options"] = opts
|
||||
}
|
||||
columns[i] = col
|
||||
}
|
||||
view := map[string]any{
|
||||
"id": shortID(), "name": "Table", "type": "table", "hidden": []any{}, "filters": []any{},
|
||||
"filterMode": "and", "sorts": []any{}, "widths": map[string]any{},
|
||||
}
|
||||
db := map[string]any{"title": "", "columns": columns, "rows": outRows, "views": []any{view}}
|
||||
doc.Content = []Node{{Type: "database", Attrs: map[string]any{"id": shortID(), "data": db}}}
|
||||
return doc, nil
|
||||
}
|
||||
|
||||
var isoDate = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}`)
|
||||
|
||||
func isYes(v string) bool {
|
||||
switch strings.ToLower(v) {
|
||||
case "yes", "true", "1", "x", "✓":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// guessColumnType is the column type for these values, like guessType in
|
||||
// Packages/editor/src/database/csv.ts.
|
||||
func guessColumnType(values []string) string {
|
||||
var filled []string
|
||||
for _, v := range values {
|
||||
if v != "" {
|
||||
filled = append(filled, v)
|
||||
}
|
||||
}
|
||||
if len(filled) == 0 {
|
||||
return "text"
|
||||
}
|
||||
all := func(ok func(string) bool) bool {
|
||||
for _, v := range filled {
|
||||
if !ok(v) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case all(func(v string) bool {
|
||||
_, err := strconv.ParseFloat(strings.ReplaceAll(v, ",", "."), 64)
|
||||
return err == nil
|
||||
}):
|
||||
return "number"
|
||||
case all(isoDate.MatchString):
|
||||
return "date"
|
||||
case all(func(v string) bool {
|
||||
l := strings.ToLower(v)
|
||||
return l == "yes" || l == "no" || l == "true" || l == "false"
|
||||
}):
|
||||
return "checkbox"
|
||||
}
|
||||
distinct := map[string]bool{}
|
||||
for _, v := range filled {
|
||||
distinct[strings.ToLower(v)] = true
|
||||
}
|
||||
short := all(func(v string) bool { return len([]rune(v)) <= 40 })
|
||||
if len(filled) >= 4 && short && float64(len(distinct)) <= max(2, float64(len(filled))/3) {
|
||||
return "select"
|
||||
}
|
||||
return "text"
|
||||
}
|
||||
|
||||
// shortID is a random id for a database's columns, rows and views.
|
||||
func shortID() string {
|
||||
var b [5]byte
|
||||
_, _ = rand.Read(b[:])
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
// notionAside finds the <aside> blocks Notion writes callouts as in its
|
||||
// Markdown export. Markdown readers drop raw HTML, text and all.
|
||||
var notionAside = regexp.MustCompile(`(?ms)^[ \t]*<aside>[ \t]*\n(.*?)\n?[ \t]*</aside>[ \t]*$`)
|
||||
|
||||
@@ -42,6 +42,7 @@ const maxPDFImagePixels = 50_000_000
|
||||
// heading and page numbers. Diagrams (stored as SVG) and Mermaid charts are
|
||||
// not drawn: diagrams become a link to their file, Mermaid its source.
|
||||
func PDF(title string, doc Node, o PDFOptions) (out []byte, err error) {
|
||||
doc = expandDatabases(doc)
|
||||
defer func() {
|
||||
// fpdf panics on some input instead of failing; one bad page must
|
||||
// not take the server down.
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -111,3 +112,41 @@ func TestReplaceRejectsNonDoc(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A database node's records live in the "blocks" map (ADR-13): JSON in and
|
||||
// out carries them in attrs.data, rows in "pos" order, bodies as nodes.
|
||||
const database = `{"type":"doc","content":[
|
||||
{"type":"database","attrs":{"id":"db1","data":{
|
||||
"title":"Tasks",
|
||||
"columns":[
|
||||
{"id":"t","name":"Name","type":"title"},
|
||||
{"id":"s","name":"Status","type":"select","options":[{"id":"o1","name":"Doing","color":"blue"}]}
|
||||
],
|
||||
"rows":[
|
||||
{"id":"r1","createdAt":1,"cells":{"t":"Write the ADR","s":"o1"},
|
||||
"body":[{"type":"paragraph","content":[{"type":"text","text":"notes here"}]}]},
|
||||
{"id":"r2","createdAt":2,"cells":{"t":"Ship it"}}
|
||||
],
|
||||
"views":[{"id":"v1","name":"Table","type":"table","hidden":[],"filters":[],"filterMode":"and","sorts":[],"groupBy":null,"dateColumn":null,"widths":{}}]
|
||||
}}},
|
||||
{"type":"paragraph"}
|
||||
]}`
|
||||
|
||||
func TestDatabaseRoundTrip(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := newPool(t)
|
||||
seed, err := p.Replace(ctx, nil, []byte(database))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := p.Read(ctx, seed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Null view fields are left out, as Yjs leaves out undefined.
|
||||
want := strings.Replace(database, `"groupBy":null,"dateColumn":null,`, "", 1)
|
||||
equalJSON(t, r.JSON, want)
|
||||
if want := "Tasks\nWrite the ADR Doing notes here\nShip it\n\n\n"; r.Text != want {
|
||||
t.Fatalf("text = %q, want %q", r.Text, want)
|
||||
}
|
||||
}
|
||||
@@ -13,15 +13,18 @@ use std::cell::RefCell;
|
||||
use serde_json::{Map, Value};
|
||||
use yrs::types::text::{Diff, YChange};
|
||||
use yrs::updates::decoder::Decode;
|
||||
use yrs::types::Attrs;
|
||||
use yrs::types::{Attrs, ToJson};
|
||||
use yrs::{
|
||||
Any, Doc, GetString, Out, ReadTxn, StateVector, Text, Transact, TransactionMut, Update, Xml,
|
||||
XmlElementPrelim, XmlFragment, XmlOut, XmlTextPrelim,
|
||||
Any, Array, ArrayPrelim, Doc, GetString, In, Map as YMap, MapPrelim, MapRef, Out, ReadTxn, StateVector, Text, Transact,
|
||||
TransactionMut, Update, WriteTxn, Xml, XmlElementPrelim, XmlFragment, XmlFragmentPrelim, XmlOut, XmlTextPrelim,
|
||||
};
|
||||
|
||||
/// Tiptap's Collaboration extension stores the document in this fragment.
|
||||
const FRAGMENT: &str = "default";
|
||||
|
||||
/// Database blocks keep their records in this map, keyed by the node's id (ADR-13).
|
||||
const BLOCKS: &str = "blocks";
|
||||
|
||||
thread_local! {
|
||||
static OUT: RefCell<Vec<u8>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
@@ -216,11 +219,18 @@ fn fill<P: XmlFragment>(txn: &mut TransactionMut, parent: &P, nodes: &[Value], d
|
||||
let el = parent.insert(txn, index, XmlElementPrelim::empty(ty.as_str()));
|
||||
if let Some(Value::Object(attrs)) = nodes[i].get("attrs") {
|
||||
for (key, value) in attrs {
|
||||
// y-prosemirror leaves null attributes out.
|
||||
if !value.is_null() {
|
||||
// y-prosemirror leaves null attributes out; a database's data goes to its map.
|
||||
if !value.is_null() && !(ty == "database" && key == "data") {
|
||||
el.insert_attribute(txn, key.as_str(), json_any(value.clone())?);
|
||||
}
|
||||
}
|
||||
if ty == "database" {
|
||||
if let (Some(Value::String(id)), Some(data @ Value::Object(_))) = (attrs.get("id"), attrs.get("data")) {
|
||||
if !id.is_empty() {
|
||||
write_database(txn, id, data, depth)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(Value::Array(children)) = nodes[i].get("content") {
|
||||
fill(txn, &el, children, depth + 1)?;
|
||||
@@ -246,6 +256,12 @@ fn node_json<T: ReadTxn>(txn: &T, node: XmlOut) -> Vec<Value> {
|
||||
obj.insert("type".into(), e.tag().to_string().into());
|
||||
let attrs: Map<String, Value> =
|
||||
e.attributes(txn).map(|(k, v)| (k.to_string(), out_json(txn, v))).collect();
|
||||
let mut attrs = attrs;
|
||||
if e.tag().as_ref() == "database" {
|
||||
if let Some(data) = attrs.get("id").and_then(Value::as_str).and_then(|id| database_json(txn, id)) {
|
||||
attrs.insert("data".into(), data);
|
||||
}
|
||||
}
|
||||
if !attrs.is_empty() {
|
||||
obj.insert("attrs".into(), attrs.into());
|
||||
}
|
||||
@@ -295,6 +311,11 @@ fn node_text<T: ReadTxn>(txn: &T, node: XmlOut, buf: &mut String) {
|
||||
}
|
||||
}
|
||||
}
|
||||
XmlOut::Element(e) if e.tag().as_ref() == "database" => {
|
||||
if let Some(data) = e.get_attribute(txn, "id").and_then(|id| database_json(txn, &id.to_string(txn))) {
|
||||
buf.push_str(&database_text(&data));
|
||||
}
|
||||
}
|
||||
XmlOut::Element(e) => {
|
||||
for (i, child) in e.children(txn).enumerate() {
|
||||
if i > 0 && matches!(child, XmlOut::Element(_)) {
|
||||
@@ -327,3 +348,215 @@ fn any_json(any: &Any) -> Value {
|
||||
Any::Map(m) => Value::Object(m.iter().map(|(k, v)| (k.clone(), any_json(v))).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Databases (ADR-13) ----
|
||||
|
||||
/// A database's records as JSON: {title, columns, rows, views}, items in display
|
||||
/// order (by their "pos"), row bodies as ProseMirror nodes in rows[].body.
|
||||
fn database_json<T: ReadTxn>(txn: &T, id: &str) -> Option<Value> {
|
||||
let blocks = txn.get_map(BLOCKS)?;
|
||||
let Some(Out::YMap(db)) = blocks.get(txn, id) else {
|
||||
return None;
|
||||
};
|
||||
let mut out = Map::new();
|
||||
let title = match db.get(txn, "title") {
|
||||
Some(Out::Any(Any::String(s))) => s.to_string(),
|
||||
_ => String::new(),
|
||||
};
|
||||
out.insert("title".into(), title.into());
|
||||
for key in ["columns", "views"] {
|
||||
let items: Vec<Value> = ordered(txn, &db, key)
|
||||
.into_iter()
|
||||
.map(|m| {
|
||||
let mut v = any_json(&m.to_json(txn));
|
||||
if let Value::Object(o) = &mut v {
|
||||
o.remove("pos");
|
||||
}
|
||||
v
|
||||
})
|
||||
.collect();
|
||||
out.insert(key.into(), items.into());
|
||||
}
|
||||
let rows: Vec<Value> = ordered(txn, &db, "rows").into_iter().map(|m| row_json(txn, &m)).collect();
|
||||
out.insert("rows".into(), rows.into());
|
||||
Some(Value::Object(out))
|
||||
}
|
||||
|
||||
fn row_json<T: ReadTxn>(txn: &T, row: &MapRef) -> Value {
|
||||
let mut out = Map::new();
|
||||
for (key, value) in row.iter(txn) {
|
||||
match (key, value) {
|
||||
("pos", _) => {}
|
||||
("body", Out::YXmlFragment(f)) => {
|
||||
let body: Vec<Value> = f.children(txn).flat_map(|n| node_json(txn, n)).collect();
|
||||
if !body.is_empty() {
|
||||
out.insert("body".into(), body.into());
|
||||
}
|
||||
}
|
||||
(key, value) => {
|
||||
out.insert(key.into(), any_json(&value.to_json(txn)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
|
||||
/// The maps of a database list in display order: by "pos", then by array index.
|
||||
fn ordered<T: ReadTxn>(txn: &T, db: &MapRef, key: &str) -> Vec<MapRef> {
|
||||
let Some(Out::YArray(list)) = db.get(txn, key) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut items: Vec<(f64, usize, MapRef)> = list
|
||||
.iter(txn)
|
||||
.enumerate()
|
||||
.filter_map(|(i, item)| match item {
|
||||
Out::YMap(m) => {
|
||||
let pos = match m.get(txn, "pos") {
|
||||
Some(Out::Any(a)) => any_json(&a).as_f64().unwrap_or(i as f64),
|
||||
_ => i as f64,
|
||||
};
|
||||
Some((pos, i, m))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
items.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal).then(a.1.cmp(&b.1)));
|
||||
items.into_iter().map(|(_, _, m)| m).collect()
|
||||
}
|
||||
|
||||
/// Search text of a database: its title, then each row's cells and body, one row per line.
|
||||
fn database_text(data: &Value) -> String {
|
||||
let mut out = String::new();
|
||||
if let Some(t) = data.get("title").and_then(Value::as_str) {
|
||||
out.push_str(t);
|
||||
out.push('\n');
|
||||
}
|
||||
let columns = data.get("columns").and_then(Value::as_array).cloned().unwrap_or_default();
|
||||
for row in data.get("rows").and_then(Value::as_array).into_iter().flatten() {
|
||||
let cells = row.get("cells");
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for col in &columns {
|
||||
let Some(id) = col.get("id").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let ty = col.get("type").and_then(Value::as_str).unwrap_or("");
|
||||
let Some(v) = cells.and_then(|c| c.get(id)) else {
|
||||
continue;
|
||||
};
|
||||
let option = |oid: &Value| {
|
||||
col.get("options")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|o| o.iter().find(|x| x.get("id") == Some(oid)))
|
||||
.and_then(|o| o.get("name"))
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
};
|
||||
match (ty, v) {
|
||||
("select", v) => parts.extend(option(v)),
|
||||
("multiSelect", Value::Array(ids)) => parts.extend(ids.iter().filter_map(option)),
|
||||
("checkbox", _) => {}
|
||||
(_, Value::String(s)) => parts.push(s.clone()),
|
||||
(_, Value::Number(n)) => parts.push(n.to_string()),
|
||||
(_, Value::Array(items)) => parts.extend(
|
||||
items.iter().filter_map(|x| x.get("name").and_then(Value::as_str)).map(str::to_owned),
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(body) = row.get("body") {
|
||||
json_text(body, &mut parts);
|
||||
}
|
||||
out.push_str(&parts.join(" "));
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn json_text(v: &Value, parts: &mut Vec<String>) {
|
||||
match v {
|
||||
Value::Array(items) => items.iter().for_each(|x| json_text(x, parts)),
|
||||
Value::Object(o) => {
|
||||
if let Some(Value::String(t)) = o.get("text") {
|
||||
parts.push(t.clone());
|
||||
}
|
||||
if let Some(c) = o.get("content") {
|
||||
json_text(c, parts);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// One item of a database list (a column, row or view) as a map prelim.
|
||||
fn item_prelim(o: &Map<String, Value>, row: bool, pos: usize) -> Result<MapPrelim, String> {
|
||||
let mut fields: Vec<(String, In)> = Vec::new();
|
||||
for (k, v) in o {
|
||||
if v.is_null() || k == "pos" || k == "body" || k == "hasBody" {
|
||||
continue;
|
||||
}
|
||||
if row && k == "cells" {
|
||||
let mut cells: Vec<(String, In)> = Vec::new();
|
||||
if let Value::Object(c) = v {
|
||||
for (ck, cv) in c {
|
||||
if !cv.is_null() {
|
||||
cells.push((ck.clone(), In::Any(json_any(cv.clone())?)));
|
||||
}
|
||||
}
|
||||
}
|
||||
fields.push((k.clone(), In::Map(MapPrelim::from_iter(cells))));
|
||||
} else {
|
||||
fields.push((k.clone(), In::Any(json_any(v.clone())?)));
|
||||
}
|
||||
}
|
||||
if row && !o.contains_key("cells") {
|
||||
fields.push(("cells".into(), In::Map(MapPrelim::default())));
|
||||
}
|
||||
fields.push(("pos".into(), In::Any(Any::from(pos as f64))));
|
||||
Ok(MapPrelim::from_iter(fields))
|
||||
}
|
||||
|
||||
/// Writes a database from JSON (a node's attrs.data) into the blocks map under id,
|
||||
/// replacing what was there, the way the editor's store.ts writes it.
|
||||
fn write_database(txn: &mut TransactionMut, id: &str, data: &Value, depth: u32) -> Result<(), String> {
|
||||
let objects = |key: &str| -> Vec<Map<String, Value>> {
|
||||
data.get(key)
|
||||
.and_then(Value::as_array)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_object().cloned())
|
||||
.collect()
|
||||
};
|
||||
let list = |key: &str| -> Result<ArrayPrelim, String> {
|
||||
let mut out = Vec::new();
|
||||
for (i, o) in objects(key).iter().enumerate() {
|
||||
out.push(In::Map(item_prelim(o, key == "rows", i)?));
|
||||
}
|
||||
Ok(ArrayPrelim::from_iter(out))
|
||||
};
|
||||
let title = data.get("title").and_then(Value::as_str).unwrap_or("").to_owned();
|
||||
let prelim = MapPrelim::from_iter([
|
||||
("title".to_owned(), In::Any(Any::from(title))),
|
||||
("columns".to_owned(), In::Array(list("columns")?)),
|
||||
("rows".to_owned(), In::Array(list("rows")?)),
|
||||
("views".to_owned(), In::Array(list("views")?)),
|
||||
]);
|
||||
let blocks = txn.get_or_insert_map(BLOCKS);
|
||||
let db = blocks.insert(txn, id, prelim);
|
||||
// Bodies go in once their rows are part of the document.
|
||||
let Some(Out::YArray(rows)) = db.get(txn, "rows") else {
|
||||
return Ok(());
|
||||
};
|
||||
for (i, o) in objects("rows").iter().enumerate() {
|
||||
let Some(Value::Array(body)) = o.get("body") else {
|
||||
continue;
|
||||
};
|
||||
if body.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(Out::YMap(row)) = rows.get(txn, i as u32) {
|
||||
let fragment = row.insert(txn, "body", XmlFragmentPrelim::default());
|
||||
fill(txn, &fragment, body, depth + 1)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -38,6 +38,7 @@ export function useEditorLabels() {
|
||||
blocks: group("blocks", "block"),
|
||||
find: group("find", "find"),
|
||||
dates: group("dates", "dates"),
|
||||
database: group("database", "database"),
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
@@ -555,6 +555,10 @@
|
||||
"syncedPage": {
|
||||
"label": "Synchronisierte Seite",
|
||||
"description": "Eine andere Seite hier zeigen, immer aktuell"
|
||||
},
|
||||
"database": {
|
||||
"label": "Datenbank",
|
||||
"description": "Einträge als Tabelle, Board oder Kalender"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
@@ -655,6 +659,129 @@
|
||||
"hideLineNumbers": "Zeilennummern ausblenden",
|
||||
"showPages": "Seiten zeigen",
|
||||
"showAsFile": "Als Datei zeigen"
|
||||
},
|
||||
"database": {
|
||||
"database": "Datenbank",
|
||||
"untitled": "Unbenannte Datenbank",
|
||||
"untitledRow": "Ohne Titel",
|
||||
"newRow": "Neuer Eintrag",
|
||||
"addColumn": "Eigenschaft hinzufügen",
|
||||
"columnName": "Name der Eigenschaft",
|
||||
"search": "Einträge durchsuchen",
|
||||
"filter": "Filter",
|
||||
"sort": "Sortieren",
|
||||
"group": "Gruppieren",
|
||||
"properties": "Eigenschaften",
|
||||
"more": "Mehr",
|
||||
"addView": "Ansicht hinzufügen",
|
||||
"viewName": "Name der Ansicht",
|
||||
"renameView": "Ansicht umbenennen",
|
||||
"duplicateView": "Ansicht duplizieren",
|
||||
"deleteView": "Ansicht löschen",
|
||||
"layout": "Layout",
|
||||
"viewTable": "Tabelle",
|
||||
"viewKanban": "Kanban",
|
||||
"viewCalendar": "Kalender",
|
||||
"noValue": "Kein Wert",
|
||||
"checked": "Angehakt",
|
||||
"unchecked": "Nicht angehakt",
|
||||
"noRows": "Keine Einträge",
|
||||
"noMatches": "Keine passenden Einträge",
|
||||
"rename": "Umbenennen",
|
||||
"type": "Typ",
|
||||
"hide": "In der Ansicht ausblenden",
|
||||
"show": "In der Ansicht zeigen",
|
||||
"sortAscending": "Aufsteigend sortieren",
|
||||
"sortDescending": "Absteigend sortieren",
|
||||
"filterBy": "Nach dieser Eigenschaft filtern",
|
||||
"insertLeft": "Links einfügen",
|
||||
"insertRight": "Rechts einfügen",
|
||||
"moveLeft": "Nach links",
|
||||
"moveRight": "Nach rechts",
|
||||
"duplicate": "Duplizieren",
|
||||
"deleteColumn": "Eigenschaft löschen",
|
||||
"typeTitle": "Titel",
|
||||
"typeText": "Text",
|
||||
"typeNumber": "Zahl",
|
||||
"typeCheckbox": "Kontrollkästchen",
|
||||
"typeSelect": "Auswahl",
|
||||
"typeMultiSelect": "Mehrfachauswahl",
|
||||
"typeDate": "Datum",
|
||||
"typeProgress": "Fortschritt",
|
||||
"typeLink": "Link",
|
||||
"typeAttachment": "Anhang",
|
||||
"typeMember": "Person",
|
||||
"typeCreatedTime": "Erstellt am",
|
||||
"typeCreatedBy": "Erstellt von",
|
||||
"opContains": "enthält",
|
||||
"opNotContains": "enthält nicht",
|
||||
"opIs": "ist",
|
||||
"opIsNot": "ist nicht",
|
||||
"opIsEmpty": "ist leer",
|
||||
"opIsNotEmpty": "ist nicht leer",
|
||||
"opGt": "ist größer als",
|
||||
"opLt": "ist kleiner als",
|
||||
"opGte": "ist mindestens",
|
||||
"opLte": "ist höchstens",
|
||||
"opBefore": "ist vor",
|
||||
"opAfter": "ist nach",
|
||||
"opChecked": "ist angehakt",
|
||||
"opUnchecked": "ist nicht angehakt",
|
||||
"addFilter": "Filter hinzufügen",
|
||||
"matchAll": "Alle Filter treffen zu",
|
||||
"matchAny": "Ein Filter trifft zu",
|
||||
"remove": "Entfernen",
|
||||
"value": "Wert",
|
||||
"noFilters": "Noch keine Filter",
|
||||
"addSort": "Sortierung hinzufügen",
|
||||
"ascending": "Aufsteigend",
|
||||
"descending": "Absteigend",
|
||||
"noSorts": "Noch keine Sortierung",
|
||||
"groupBy": "Gruppieren nach",
|
||||
"noGrouping": "Keine Gruppierung",
|
||||
"showAll": "Alle zeigen",
|
||||
"hideAll": "Alle ausblenden",
|
||||
"dateColumn": "Datumseigenschaft",
|
||||
"today": "Heute",
|
||||
"previousMonth": "Voriger Monat",
|
||||
"nextMonth": "Nächster Monat",
|
||||
"noDateColumn": "Füge eine Datumseigenschaft hinzu, um Einträge in den Kalender zu setzen.",
|
||||
"noDate": "Ohne Datum ({n})",
|
||||
"noGroupColumn": "Füge eine Auswahl-, Kontrollkästchen- oder Personeneigenschaft hinzu, um Karten in Spalten zu ordnen.",
|
||||
"openRow": "Öffnen",
|
||||
"deleteRow": "Eintrag löschen",
|
||||
"duplicateRow": "Eintrag duplizieren",
|
||||
"insertAbove": "Darüber einfügen",
|
||||
"insertBelow": "Darunter einfügen",
|
||||
"deleteRows": "Löschen",
|
||||
"selected": "{n} ausgewählt",
|
||||
"selectRow": "Eintrag auswählen",
|
||||
"dragRow": "Zum Verschieben ziehen",
|
||||
"close": "Schließen",
|
||||
"expand": "Volle Breite",
|
||||
"collapse": "Schmal",
|
||||
"previousRow": "Voriger Eintrag",
|
||||
"nextRow": "Nächster Eintrag",
|
||||
"bodyPlaceholder": "Schreib etwas zu diesem Eintrag…",
|
||||
"bodyReadOnly": "Dieser Eintrag hat keine Notizen.",
|
||||
"searchOptions": "Option suchen oder anlegen",
|
||||
"createOption": "„{n}“ anlegen",
|
||||
"optionColor": "Farbe",
|
||||
"deleteOption": "Option löschen",
|
||||
"renameOption": "Option umbenennen",
|
||||
"searchPeople": "Person suchen",
|
||||
"noPeople": "Niemand gefunden",
|
||||
"upload": "Datei hochladen",
|
||||
"linkPlaceholder": "Link einfügen",
|
||||
"clear": "Leeren",
|
||||
"exportCsv": "Als CSV exportieren",
|
||||
"importCsv": "CSV importieren",
|
||||
"imported": "{n} Einträge hinzugefügt",
|
||||
"copyNotice": "{n} Zellen kopiert",
|
||||
"readOnly": "Nur wer die Seite bearbeiten darf, kann diese Datenbank ändern.",
|
||||
"resize": "Ziehen, um die Breite zu ändern",
|
||||
"groupAsDatabase": "Als Datenbank gruppieren",
|
||||
"done": "Erledigt"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
|
||||
@@ -555,6 +555,10 @@
|
||||
"syncedPage": {
|
||||
"label": "Synced page",
|
||||
"description": "Show another page here, always up to date"
|
||||
},
|
||||
"database": {
|
||||
"label": "Database",
|
||||
"description": "Records in a table, board or calendar"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
@@ -655,6 +659,129 @@
|
||||
"hideLineNumbers": "Hide line numbers",
|
||||
"showPages": "Show pages",
|
||||
"showAsFile": "Show as file"
|
||||
},
|
||||
"database": {
|
||||
"database": "Database",
|
||||
"untitled": "Untitled database",
|
||||
"untitledRow": "Untitled",
|
||||
"newRow": "New record",
|
||||
"addColumn": "Add property",
|
||||
"columnName": "Property name",
|
||||
"search": "Search records",
|
||||
"filter": "Filter",
|
||||
"sort": "Sort",
|
||||
"group": "Group",
|
||||
"properties": "Properties",
|
||||
"more": "More",
|
||||
"addView": "Add view",
|
||||
"viewName": "View name",
|
||||
"renameView": "Rename view",
|
||||
"duplicateView": "Duplicate view",
|
||||
"deleteView": "Delete view",
|
||||
"layout": "Layout",
|
||||
"viewTable": "Table",
|
||||
"viewKanban": "Kanban",
|
||||
"viewCalendar": "Calendar",
|
||||
"noValue": "No value",
|
||||
"checked": "Checked",
|
||||
"unchecked": "Unchecked",
|
||||
"noRows": "No records",
|
||||
"noMatches": "No records match",
|
||||
"rename": "Rename",
|
||||
"type": "Type",
|
||||
"hide": "Hide in view",
|
||||
"show": "Show in view",
|
||||
"sortAscending": "Sort ascending",
|
||||
"sortDescending": "Sort descending",
|
||||
"filterBy": "Filter by this property",
|
||||
"insertLeft": "Insert left",
|
||||
"insertRight": "Insert right",
|
||||
"moveLeft": "Move left",
|
||||
"moveRight": "Move right",
|
||||
"duplicate": "Duplicate",
|
||||
"deleteColumn": "Delete property",
|
||||
"typeTitle": "Title",
|
||||
"typeText": "Text",
|
||||
"typeNumber": "Number",
|
||||
"typeCheckbox": "Checkbox",
|
||||
"typeSelect": "Select",
|
||||
"typeMultiSelect": "Multi-select",
|
||||
"typeDate": "Date",
|
||||
"typeProgress": "Progress",
|
||||
"typeLink": "Link",
|
||||
"typeAttachment": "Attachment",
|
||||
"typeMember": "Member",
|
||||
"typeCreatedTime": "Created time",
|
||||
"typeCreatedBy": "Created by",
|
||||
"opContains": "contains",
|
||||
"opNotContains": "does not contain",
|
||||
"opIs": "is",
|
||||
"opIsNot": "is not",
|
||||
"opIsEmpty": "is empty",
|
||||
"opIsNotEmpty": "is not empty",
|
||||
"opGt": "is greater than",
|
||||
"opLt": "is less than",
|
||||
"opGte": "is at least",
|
||||
"opLte": "is at most",
|
||||
"opBefore": "is before",
|
||||
"opAfter": "is after",
|
||||
"opChecked": "is checked",
|
||||
"opUnchecked": "is not checked",
|
||||
"addFilter": "Add filter",
|
||||
"matchAll": "Every filter matches",
|
||||
"matchAny": "Any filter matches",
|
||||
"remove": "Remove",
|
||||
"value": "Value",
|
||||
"noFilters": "No filters yet",
|
||||
"addSort": "Add sort",
|
||||
"ascending": "Ascending",
|
||||
"descending": "Descending",
|
||||
"noSorts": "No sorts yet",
|
||||
"groupBy": "Group by",
|
||||
"noGrouping": "No grouping",
|
||||
"showAll": "Show all",
|
||||
"hideAll": "Hide all",
|
||||
"dateColumn": "Date property",
|
||||
"today": "Today",
|
||||
"previousMonth": "Previous month",
|
||||
"nextMonth": "Next month",
|
||||
"noDateColumn": "Add a date property to place records on the calendar.",
|
||||
"noDate": "No date ({n})",
|
||||
"noGroupColumn": "Add a select, checkbox or member property to sort cards into columns.",
|
||||
"openRow": "Open",
|
||||
"deleteRow": "Delete record",
|
||||
"duplicateRow": "Duplicate record",
|
||||
"insertAbove": "Insert above",
|
||||
"insertBelow": "Insert below",
|
||||
"deleteRows": "Delete",
|
||||
"selected": "{n} selected",
|
||||
"selectRow": "Select record",
|
||||
"dragRow": "Drag to move",
|
||||
"close": "Close",
|
||||
"expand": "Full width",
|
||||
"collapse": "Narrow",
|
||||
"previousRow": "Previous record",
|
||||
"nextRow": "Next record",
|
||||
"bodyPlaceholder": "Write about this record…",
|
||||
"bodyReadOnly": "This record has no notes.",
|
||||
"searchOptions": "Find or create a choice",
|
||||
"createOption": "Create “{n}”",
|
||||
"optionColor": "Colour",
|
||||
"deleteOption": "Delete choice",
|
||||
"renameOption": "Rename choice",
|
||||
"searchPeople": "Find a person",
|
||||
"noPeople": "Nobody found",
|
||||
"upload": "Upload a file",
|
||||
"linkPlaceholder": "Paste a link",
|
||||
"clear": "Clear",
|
||||
"exportCsv": "Export as CSV",
|
||||
"importCsv": "Import CSV",
|
||||
"imported": "Added {n} records",
|
||||
"copyNotice": "Copied {n} cells",
|
||||
"readOnly": "Only people who can edit the page can change this database.",
|
||||
"resize": "Drag to change the width",
|
||||
"groupAsDatabase": "Group as database",
|
||||
"done": "Done"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
|
||||
@@ -555,6 +555,10 @@
|
||||
"syncedPage": {
|
||||
"label": "Página sincronizada",
|
||||
"description": "Muestra otra página aquí, siempre al día"
|
||||
},
|
||||
"database": {
|
||||
"label": "Base de datos",
|
||||
"description": "Registros en tabla, tablero o calendario"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
@@ -655,6 +659,129 @@
|
||||
"hideLineNumbers": "Ocultar números de línea",
|
||||
"showPages": "Mostrar páginas",
|
||||
"showAsFile": "Mostrar como archivo"
|
||||
},
|
||||
"database": {
|
||||
"database": "Base de datos",
|
||||
"untitled": "Base de datos sin título",
|
||||
"untitledRow": "Sin título",
|
||||
"newRow": "Nuevo registro",
|
||||
"addColumn": "Añadir propiedad",
|
||||
"columnName": "Nombre de la propiedad",
|
||||
"search": "Buscar registros",
|
||||
"filter": "Filtrar",
|
||||
"sort": "Ordenar",
|
||||
"group": "Agrupar",
|
||||
"properties": "Propiedades",
|
||||
"more": "Más",
|
||||
"addView": "Añadir vista",
|
||||
"viewName": "Nombre de la vista",
|
||||
"renameView": "Cambiar nombre de la vista",
|
||||
"duplicateView": "Duplicar vista",
|
||||
"deleteView": "Eliminar vista",
|
||||
"layout": "Diseño",
|
||||
"viewTable": "Tabla",
|
||||
"viewKanban": "Kanban",
|
||||
"viewCalendar": "Calendario",
|
||||
"noValue": "Sin valor",
|
||||
"checked": "Marcado",
|
||||
"unchecked": "Sin marcar",
|
||||
"noRows": "No hay registros",
|
||||
"noMatches": "Ningún registro coincide",
|
||||
"rename": "Cambiar nombre",
|
||||
"type": "Tipo",
|
||||
"hide": "Ocultar en la vista",
|
||||
"show": "Mostrar en la vista",
|
||||
"sortAscending": "Orden ascendente",
|
||||
"sortDescending": "Orden descendente",
|
||||
"filterBy": "Filtrar por esta propiedad",
|
||||
"insertLeft": "Insertar a la izquierda",
|
||||
"insertRight": "Insertar a la derecha",
|
||||
"moveLeft": "Mover a la izquierda",
|
||||
"moveRight": "Mover a la derecha",
|
||||
"duplicate": "Duplicar",
|
||||
"deleteColumn": "Eliminar propiedad",
|
||||
"typeTitle": "Título",
|
||||
"typeText": "Texto",
|
||||
"typeNumber": "Número",
|
||||
"typeCheckbox": "Casilla",
|
||||
"typeSelect": "Selección",
|
||||
"typeMultiSelect": "Selección múltiple",
|
||||
"typeDate": "Fecha",
|
||||
"typeProgress": "Progreso",
|
||||
"typeLink": "Enlace",
|
||||
"typeAttachment": "Adjunto",
|
||||
"typeMember": "Miembro",
|
||||
"typeCreatedTime": "Fecha de creación",
|
||||
"typeCreatedBy": "Creado por",
|
||||
"opContains": "contiene",
|
||||
"opNotContains": "no contiene",
|
||||
"opIs": "es",
|
||||
"opIsNot": "no es",
|
||||
"opIsEmpty": "está vacío",
|
||||
"opIsNotEmpty": "no está vacío",
|
||||
"opGt": "es mayor que",
|
||||
"opLt": "es menor que",
|
||||
"opGte": "es al menos",
|
||||
"opLte": "es como mucho",
|
||||
"opBefore": "es antes de",
|
||||
"opAfter": "es después de",
|
||||
"opChecked": "está marcado",
|
||||
"opUnchecked": "no está marcado",
|
||||
"addFilter": "Añadir filtro",
|
||||
"matchAll": "Se cumplen todos los filtros",
|
||||
"matchAny": "Se cumple algún filtro",
|
||||
"remove": "Quitar",
|
||||
"value": "Valor",
|
||||
"noFilters": "Aún no hay filtros",
|
||||
"addSort": "Añadir orden",
|
||||
"ascending": "Ascendente",
|
||||
"descending": "Descendente",
|
||||
"noSorts": "Aún no hay orden",
|
||||
"groupBy": "Agrupar por",
|
||||
"noGrouping": "Sin agrupar",
|
||||
"showAll": "Mostrar todo",
|
||||
"hideAll": "Ocultar todo",
|
||||
"dateColumn": "Propiedad de fecha",
|
||||
"today": "Hoy",
|
||||
"previousMonth": "Mes anterior",
|
||||
"nextMonth": "Mes siguiente",
|
||||
"noDateColumn": "Añade una propiedad de fecha para colocar los registros en el calendario.",
|
||||
"noDate": "Sin fecha ({n})",
|
||||
"noGroupColumn": "Añade una propiedad de selección, casilla o miembro para ordenar las tarjetas en columnas.",
|
||||
"openRow": "Abrir",
|
||||
"deleteRow": "Eliminar registro",
|
||||
"duplicateRow": "Duplicar registro",
|
||||
"insertAbove": "Insertar encima",
|
||||
"insertBelow": "Insertar debajo",
|
||||
"deleteRows": "Eliminar",
|
||||
"selected": "{n} seleccionados",
|
||||
"selectRow": "Seleccionar registro",
|
||||
"dragRow": "Arrastra para mover",
|
||||
"close": "Cerrar",
|
||||
"expand": "Ancho completo",
|
||||
"collapse": "Estrecho",
|
||||
"previousRow": "Registro anterior",
|
||||
"nextRow": "Registro siguiente",
|
||||
"bodyPlaceholder": "Escribe sobre este registro…",
|
||||
"bodyReadOnly": "Este registro no tiene notas.",
|
||||
"searchOptions": "Buscar o crear una opción",
|
||||
"createOption": "Crear «{n}»",
|
||||
"optionColor": "Color",
|
||||
"deleteOption": "Eliminar opción",
|
||||
"renameOption": "Cambiar nombre de la opción",
|
||||
"searchPeople": "Buscar una persona",
|
||||
"noPeople": "No se encontró a nadie",
|
||||
"upload": "Subir un archivo",
|
||||
"linkPlaceholder": "Pega un enlace",
|
||||
"clear": "Borrar",
|
||||
"exportCsv": "Exportar como CSV",
|
||||
"importCsv": "Importar CSV",
|
||||
"imported": "{n} registros añadidos",
|
||||
"copyNotice": "{n} celdas copiadas",
|
||||
"readOnly": "Solo quien puede editar la página puede cambiar esta base de datos.",
|
||||
"resize": "Arrastra para cambiar el ancho",
|
||||
"groupAsDatabase": "Agrupar como base de datos",
|
||||
"done": "Hecho"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
|
||||
@@ -555,6 +555,10 @@
|
||||
"syncedPage": {
|
||||
"label": "Page synchronisée",
|
||||
"description": "Afficher une autre page ici, toujours à jour"
|
||||
},
|
||||
"database": {
|
||||
"label": "Base de données",
|
||||
"description": "Des éléments en tableau, kanban ou calendrier"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
@@ -655,6 +659,129 @@
|
||||
"hideLineNumbers": "Masquer les numéros de ligne",
|
||||
"showPages": "Afficher les pages",
|
||||
"showAsFile": "Afficher comme fichier"
|
||||
},
|
||||
"database": {
|
||||
"database": "Base de données",
|
||||
"untitled": "Base sans titre",
|
||||
"untitledRow": "Sans titre",
|
||||
"newRow": "Nouvel élément",
|
||||
"addColumn": "Ajouter une propriété",
|
||||
"columnName": "Nom de la propriété",
|
||||
"search": "Rechercher des éléments",
|
||||
"filter": "Filtrer",
|
||||
"sort": "Trier",
|
||||
"group": "Grouper",
|
||||
"properties": "Propriétés",
|
||||
"more": "Plus",
|
||||
"addView": "Ajouter une vue",
|
||||
"viewName": "Nom de la vue",
|
||||
"renameView": "Renommer la vue",
|
||||
"duplicateView": "Dupliquer la vue",
|
||||
"deleteView": "Supprimer la vue",
|
||||
"layout": "Disposition",
|
||||
"viewTable": "Tableau",
|
||||
"viewKanban": "Kanban",
|
||||
"viewCalendar": "Calendrier",
|
||||
"noValue": "Aucune valeur",
|
||||
"checked": "Coché",
|
||||
"unchecked": "Non coché",
|
||||
"noRows": "Aucun élément",
|
||||
"noMatches": "Aucun élément ne correspond",
|
||||
"rename": "Renommer",
|
||||
"type": "Type",
|
||||
"hide": "Masquer dans la vue",
|
||||
"show": "Afficher dans la vue",
|
||||
"sortAscending": "Trier par ordre croissant",
|
||||
"sortDescending": "Trier par ordre décroissant",
|
||||
"filterBy": "Filtrer par cette propriété",
|
||||
"insertLeft": "Insérer à gauche",
|
||||
"insertRight": "Insérer à droite",
|
||||
"moveLeft": "Déplacer à gauche",
|
||||
"moveRight": "Déplacer à droite",
|
||||
"duplicate": "Dupliquer",
|
||||
"deleteColumn": "Supprimer la propriété",
|
||||
"typeTitle": "Titre",
|
||||
"typeText": "Texte",
|
||||
"typeNumber": "Nombre",
|
||||
"typeCheckbox": "Case à cocher",
|
||||
"typeSelect": "Sélection",
|
||||
"typeMultiSelect": "Sélection multiple",
|
||||
"typeDate": "Date",
|
||||
"typeProgress": "Progression",
|
||||
"typeLink": "Lien",
|
||||
"typeAttachment": "Pièce jointe",
|
||||
"typeMember": "Membre",
|
||||
"typeCreatedTime": "Date de création",
|
||||
"typeCreatedBy": "Créé par",
|
||||
"opContains": "contient",
|
||||
"opNotContains": "ne contient pas",
|
||||
"opIs": "est",
|
||||
"opIsNot": "n’est pas",
|
||||
"opIsEmpty": "est vide",
|
||||
"opIsNotEmpty": "n’est pas vide",
|
||||
"opGt": "est supérieur à",
|
||||
"opLt": "est inférieur à",
|
||||
"opGte": "est au moins",
|
||||
"opLte": "est au plus",
|
||||
"opBefore": "est avant",
|
||||
"opAfter": "est après",
|
||||
"opChecked": "est coché",
|
||||
"opUnchecked": "n’est pas coché",
|
||||
"addFilter": "Ajouter un filtre",
|
||||
"matchAll": "Tous les filtres correspondent",
|
||||
"matchAny": "Un filtre correspond",
|
||||
"remove": "Retirer",
|
||||
"value": "Valeur",
|
||||
"noFilters": "Aucun filtre pour l’instant",
|
||||
"addSort": "Ajouter un tri",
|
||||
"ascending": "Croissant",
|
||||
"descending": "Décroissant",
|
||||
"noSorts": "Aucun tri pour l’instant",
|
||||
"groupBy": "Grouper par",
|
||||
"noGrouping": "Aucun groupement",
|
||||
"showAll": "Tout afficher",
|
||||
"hideAll": "Tout masquer",
|
||||
"dateColumn": "Propriété de date",
|
||||
"today": "Aujourd’hui",
|
||||
"previousMonth": "Mois précédent",
|
||||
"nextMonth": "Mois suivant",
|
||||
"noDateColumn": "Ajoutez une propriété de date pour placer les éléments dans le calendrier.",
|
||||
"noDate": "Sans date ({n})",
|
||||
"noGroupColumn": "Ajoutez une propriété de sélection, de case à cocher ou de membre pour ranger les cartes en colonnes.",
|
||||
"openRow": "Ouvrir",
|
||||
"deleteRow": "Supprimer l’élément",
|
||||
"duplicateRow": "Dupliquer l’élément",
|
||||
"insertAbove": "Insérer au-dessus",
|
||||
"insertBelow": "Insérer en dessous",
|
||||
"deleteRows": "Supprimer",
|
||||
"selected": "{n} sélectionnés",
|
||||
"selectRow": "Sélectionner l’élément",
|
||||
"dragRow": "Glisser pour déplacer",
|
||||
"close": "Fermer",
|
||||
"expand": "Pleine largeur",
|
||||
"collapse": "Étroit",
|
||||
"previousRow": "Élément précédent",
|
||||
"nextRow": "Élément suivant",
|
||||
"bodyPlaceholder": "Écrivez à propos de cet élément…",
|
||||
"bodyReadOnly": "Cet élément n’a pas de notes.",
|
||||
"searchOptions": "Chercher ou créer une option",
|
||||
"createOption": "Créer « {n} »",
|
||||
"optionColor": "Couleur",
|
||||
"deleteOption": "Supprimer l’option",
|
||||
"renameOption": "Renommer l’option",
|
||||
"searchPeople": "Chercher une personne",
|
||||
"noPeople": "Personne trouvée",
|
||||
"upload": "Téléverser un fichier",
|
||||
"linkPlaceholder": "Coller un lien",
|
||||
"clear": "Effacer",
|
||||
"exportCsv": "Exporter en CSV",
|
||||
"importCsv": "Importer un CSV",
|
||||
"imported": "{n} éléments ajoutés",
|
||||
"copyNotice": "{n} cellules copiées",
|
||||
"readOnly": "Seules les personnes qui peuvent modifier la page peuvent changer cette base.",
|
||||
"resize": "Glisser pour changer la largeur",
|
||||
"groupAsDatabase": "Grouper en base de données",
|
||||
"done": "Terminé"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
|
||||
@@ -555,6 +555,10 @@
|
||||
"syncedPage": {
|
||||
"label": "Strona synchronizowana",
|
||||
"description": "Pokaż tu inną stronę, zawsze aktualną"
|
||||
},
|
||||
"database": {
|
||||
"label": "Baza danych",
|
||||
"description": "Rekordy w tabeli, na tablicy lub w kalendarzu"
|
||||
}
|
||||
},
|
||||
"format": {
|
||||
@@ -655,6 +659,129 @@
|
||||
"hideLineNumbers": "Ukryj numery wierszy",
|
||||
"showPages": "Pokaż strony",
|
||||
"showAsFile": "Pokaż jako plik"
|
||||
},
|
||||
"database": {
|
||||
"database": "Baza danych",
|
||||
"untitled": "Baza danych bez tytułu",
|
||||
"untitledRow": "Bez tytułu",
|
||||
"newRow": "Nowy rekord",
|
||||
"addColumn": "Dodaj właściwość",
|
||||
"columnName": "Nazwa właściwości",
|
||||
"search": "Szukaj rekordów",
|
||||
"filter": "Filtruj",
|
||||
"sort": "Sortuj",
|
||||
"group": "Grupuj",
|
||||
"properties": "Właściwości",
|
||||
"more": "Więcej",
|
||||
"addView": "Dodaj widok",
|
||||
"viewName": "Nazwa widoku",
|
||||
"renameView": "Zmień nazwę widoku",
|
||||
"duplicateView": "Duplikuj widok",
|
||||
"deleteView": "Usuń widok",
|
||||
"layout": "Układ",
|
||||
"viewTable": "Tabela",
|
||||
"viewKanban": "Kanban",
|
||||
"viewCalendar": "Kalendarz",
|
||||
"noValue": "Brak wartości",
|
||||
"checked": "Zaznaczone",
|
||||
"unchecked": "Niezaznaczone",
|
||||
"noRows": "Brak rekordów",
|
||||
"noMatches": "Żaden rekord nie pasuje",
|
||||
"rename": "Zmień nazwę",
|
||||
"type": "Typ",
|
||||
"hide": "Ukryj w widoku",
|
||||
"show": "Pokaż w widoku",
|
||||
"sortAscending": "Sortuj rosnąco",
|
||||
"sortDescending": "Sortuj malejąco",
|
||||
"filterBy": "Filtruj po tej właściwości",
|
||||
"insertLeft": "Wstaw z lewej",
|
||||
"insertRight": "Wstaw z prawej",
|
||||
"moveLeft": "Przesuń w lewo",
|
||||
"moveRight": "Przesuń w prawo",
|
||||
"duplicate": "Duplikuj",
|
||||
"deleteColumn": "Usuń właściwość",
|
||||
"typeTitle": "Tytuł",
|
||||
"typeText": "Tekst",
|
||||
"typeNumber": "Liczba",
|
||||
"typeCheckbox": "Pole wyboru",
|
||||
"typeSelect": "Wybór",
|
||||
"typeMultiSelect": "Wielokrotny wybór",
|
||||
"typeDate": "Data",
|
||||
"typeProgress": "Postęp",
|
||||
"typeLink": "Link",
|
||||
"typeAttachment": "Załącznik",
|
||||
"typeMember": "Osoba",
|
||||
"typeCreatedTime": "Data utworzenia",
|
||||
"typeCreatedBy": "Utworzył(a)",
|
||||
"opContains": "zawiera",
|
||||
"opNotContains": "nie zawiera",
|
||||
"opIs": "jest",
|
||||
"opIsNot": "nie jest",
|
||||
"opIsEmpty": "jest puste",
|
||||
"opIsNotEmpty": "nie jest puste",
|
||||
"opGt": "jest większe niż",
|
||||
"opLt": "jest mniejsze niż",
|
||||
"opGte": "jest co najmniej",
|
||||
"opLte": "jest co najwyżej",
|
||||
"opBefore": "jest przed",
|
||||
"opAfter": "jest po",
|
||||
"opChecked": "jest zaznaczone",
|
||||
"opUnchecked": "nie jest zaznaczone",
|
||||
"addFilter": "Dodaj filtr",
|
||||
"matchAll": "Pasują wszystkie filtry",
|
||||
"matchAny": "Pasuje dowolny filtr",
|
||||
"remove": "Usuń",
|
||||
"value": "Wartość",
|
||||
"noFilters": "Brak filtrów",
|
||||
"addSort": "Dodaj sortowanie",
|
||||
"ascending": "Rosnąco",
|
||||
"descending": "Malejąco",
|
||||
"noSorts": "Brak sortowania",
|
||||
"groupBy": "Grupuj według",
|
||||
"noGrouping": "Bez grupowania",
|
||||
"showAll": "Pokaż wszystkie",
|
||||
"hideAll": "Ukryj wszystkie",
|
||||
"dateColumn": "Właściwość daty",
|
||||
"today": "Dziś",
|
||||
"previousMonth": "Poprzedni miesiąc",
|
||||
"nextMonth": "Następny miesiąc",
|
||||
"noDateColumn": "Dodaj właściwość daty, aby umieścić rekordy w kalendarzu.",
|
||||
"noDate": "Bez daty ({n})",
|
||||
"noGroupColumn": "Dodaj właściwość wyboru, pola wyboru lub osoby, aby układać karty w kolumny.",
|
||||
"openRow": "Otwórz",
|
||||
"deleteRow": "Usuń rekord",
|
||||
"duplicateRow": "Duplikuj rekord",
|
||||
"insertAbove": "Wstaw powyżej",
|
||||
"insertBelow": "Wstaw poniżej",
|
||||
"deleteRows": "Usuń",
|
||||
"selected": "Zaznaczono: {n}",
|
||||
"selectRow": "Zaznacz rekord",
|
||||
"dragRow": "Przeciągnij, aby przenieść",
|
||||
"close": "Zamknij",
|
||||
"expand": "Pełna szerokość",
|
||||
"collapse": "Wąsko",
|
||||
"previousRow": "Poprzedni rekord",
|
||||
"nextRow": "Następny rekord",
|
||||
"bodyPlaceholder": "Napisz coś o tym rekordzie…",
|
||||
"bodyReadOnly": "Ten rekord nie ma notatek.",
|
||||
"searchOptions": "Znajdź lub utwórz opcję",
|
||||
"createOption": "Utwórz „{n}”",
|
||||
"optionColor": "Kolor",
|
||||
"deleteOption": "Usuń opcję",
|
||||
"renameOption": "Zmień nazwę opcji",
|
||||
"searchPeople": "Znajdź osobę",
|
||||
"noPeople": "Nikogo nie znaleziono",
|
||||
"upload": "Prześlij plik",
|
||||
"linkPlaceholder": "Wklej link",
|
||||
"clear": "Wyczyść",
|
||||
"exportCsv": "Eksportuj jako CSV",
|
||||
"importCsv": "Importuj CSV",
|
||||
"imported": "Dodano rekordy: {n}",
|
||||
"copyNotice": "Skopiowano komórki: {n}",
|
||||
"readOnly": "Tylko osoby, które mogą edytować stronę, mogą zmieniać tę bazę danych.",
|
||||
"resize": "Przeciągnij, aby zmienić szerokość",
|
||||
"groupAsDatabase": "Grupuj jako bazę danych",
|
||||
"done": "Gotowe"
|
||||
}
|
||||
},
|
||||
"comments": {
|
||||
|
||||
Reference in new issue
Block a user