@blocknote/core 0.54.0 → 0.54.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blocknote.cjs +1 -1
- package/dist/blocknote.js +6 -6
- package/dist/{blocks-CzkqclGj.cjs → blocks-CTB_5Vyj.cjs} +4 -4
- package/dist/blocks-CTB_5Vyj.cjs.map +1 -0
- package/dist/{blocks-CzQLehlc.js → blocks-Dol85hpH.js} +337 -330
- package/dist/blocks-Dol85hpH.js.map +1 -0
- package/dist/blocks.cjs +1 -1
- package/dist/blocks.js +2 -2
- package/dist/extensions-B7Rsp_Ft.cjs +58 -0
- package/dist/extensions-B7Rsp_Ft.cjs.map +1 -0
- package/dist/{extensions-DGuhtOgB.js → extensions-D6JcJCwd.js} +389 -346
- package/dist/extensions-D6JcJCwd.js.map +1 -0
- package/dist/extensions.cjs +1 -1
- package/dist/extensions.js +3 -3
- package/dist/{src-BkfZVfaO.js → src-Buuo5l7X.js} +521 -516
- package/dist/{src-BkfZVfaO.js.map → src-Buuo5l7X.js.map} +1 -1
- package/dist/{src-DM3syMdf.cjs → src-C54Ok9E0.cjs} +10 -10
- package/dist/{src-DM3syMdf.cjs.map → src-C54Ok9E0.cjs.map} +1 -1
- package/dist/webpack-stats.json +1 -1
- package/dist/y.cjs +1 -1
- package/dist/y.cjs.map +1 -1
- package/dist/y.js +205 -205
- package/dist/y.js.map +1 -1
- package/dist/yjs.cjs +1 -1
- package/dist/yjs.js +21 -21
- package/package.json +1 -1
- package/src/api/getBlocksChangedByTransaction.test.ts +211 -0
- package/src/api/getBlocksChangedByTransaction.ts +48 -12
- package/src/api/getChangedRange.ts +54 -0
- package/src/blocks/index.ts +0 -1
- package/src/editor/performance.test.ts +45 -0
- package/src/exporter/Exporter.test.ts +148 -10
- package/src/exporter/Exporter.ts +20 -2
- package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +21 -0
- package/src/extensions/PreviousBlockType/PreviousBlockType.ts +5 -3
- package/src/extensions/TableHandles/TableHandles.browser.test.ts +305 -0
- package/src/extensions/TableHandles/TableHandles.ts +82 -41
- package/src/fonts/inter.css +9 -9
- package/src/schema/blocks/createSpec.ts +4 -5
- package/src/schema/inlineContent/createSpec.ts +4 -5
- package/src/schema/nodeViewMutations.test.ts +81 -56
- package/src/schema/nodeViewMutations.ts +30 -27
- package/src/schema/schema.test.ts +110 -0
- package/src/schema/schema.ts +13 -4
- package/src/y/extensions/AttributionExtension.test.ts +8 -9
- package/src/y/versioning/__test__/yhub.test.ts +92 -59
- package/src/y/versioning/yhub.ts +35 -29
- package/types/src/api/getChangedRange.d.ts +14 -0
- package/types/src/blocks/index.d.ts +0 -1
- package/types/src/exporter/Exporter.d.ts +9 -0
- package/types/src/extensions/TableHandles/TableHandles.browser.test.d.ts +1 -0
- package/types/src/extensions/TableHandles/TableHandles.d.ts +3 -0
- package/types/src/schema/nodeViewMutations.d.ts +2 -2
- package/types/src/schema/schema.test.d.ts +1 -0
- package/types/src/y/versioning/yhub.d.ts +3 -2
- package/dist/blocks-CzQLehlc.js.map +0 -1
- package/dist/blocks-CzkqclGj.cjs.map +0 -1
- package/dist/extensions-CSB9ZvuL.cjs +0 -58
- package/dist/extensions-CSB9ZvuL.cjs.map +0 -1
- package/dist/extensions-DGuhtOgB.js.map +0 -1
- package/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.ts +0 -20
- package/types/src/blocks/File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.d.ts +0 -6
package/dist/yjs.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./blocks-CzkqclGj.cjs"),t=require("./BlockNoteExtension-BJCLnwrE.cjs"),n=require("./ThreadStore-Bx-gSEh1.cjs");let r=require("prosemirror-model"),i=require("lib0/random"),a=require("@tiptap/pm/state"),o=require("y-prosemirror"),s=require("yjs");s=e.cr(s,1);function c(e,t){let n=e.doc;if(!n)throw Error(`type does not have a ydoc`);if(e._item===null){let r=Array.from(n.share.keys()).find(t=>n.share.get(t)===e);if(r==null)throw Error(`type does not exist in other ydoc`);return t.get(r,e.constructor)}{let n=e._item,r=t.store.clients.get(n.id.client)??[],i=r[s.findIndexSS(r,n.id.clock)];if(!i)throw Error(`type does not exist in other ydoc`);let a=i.content;if(!a)throw Error(`type does not exist in other ydoc`);return a.type}}function l(t,n){let r=t.pmSchema.nodeFromJSON(n);return e.wn(r)}function u(t,n){let r=n.map(n=>e.It(n,t.pmSchema));return t.pmSchema.topNodeType.create(null,t.pmSchema.nodes.blockGroup.create(null,r))}function d(t,n){let r=(0,o.yXmlFragmentToProseMirrorRootNode)(n,t.pmSchema);return e.wn(r)}function f(e,t,n){return(0,o.prosemirrorToYXmlFragment)(u(e,t),n)}function p(e,t,n=`prosemirror`){return d(e,t.getXmlFragment(n))}function m(e,t,n=`prosemirror`){return(0,o.prosemirrorToYDoc)(u(e,t),n)}var h=t.t(({editor:t})=>(t.on(`create`,()=>{let n=t.pmSchema,i,a=n.nodes.doc.createAndFill;n.nodes.doc.createAndFill=((...e)=>{if(i)return i;let t=a.apply(n.nodes.doc,e),o=JSON.parse(JSON.stringify(t.toJSON()));return o.content[0].content[0].attrs.id=`initialBlockId`,i=r.Node.fromJSON(n,o),i});let o=n.node;n.node=function(t,n,r,i){let a=typeof t==`string`?this.nodes[t]:t;return a&&e.Pn(this,a)&&Array.isArray(r)&&(r=r.map(e=>e?.isText&&e.marks.length?e.mark(a.allowedMarks(e.marks)):e)),o.call(this,t,n,r,i)}}),{key:`fixUpSchema`}));function g(e){let t=e.charAt(0)===`#`?e.substring(1,7):e,n=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),i=parseInt(t.substring(4,6),16),a=[n/255,r/255,i/255].map(e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4);return .2126*a[0]+.7152*a[1]+.0722*a[2]<=.179}function _(e){let t=document.createElement(`span`);t.classList.add(`bn-collaboration-cursor__base`);let n=document.createElement(`span`);n.setAttribute(`contentedEditable`,`false`),n.classList.add(`bn-collaboration-cursor__caret`),n.setAttribute(`style`,`background-color: ${e.color}; color: ${g(e.color)?`white`:`black`}`);let r=document.createElement(`span`);return r.classList.add(`bn-collaboration-cursor__label`),r.setAttribute(`style`,`background-color: ${e.color}; color: ${g(e.color)?`white`:`black`}`),r.insertBefore(document.createTextNode(e.name),null),n.insertBefore(r,null),t.insertBefore(document.createTextNode(``),null),t.insertBefore(n,null),t.insertBefore(document.createTextNode(``),null),t}var v=t.t(({options:e})=>{let t=new Map,n=e.provider&&`awareness`in e.provider&&typeof e.provider.awareness==`object`?e.provider.awareness:void 0;n&&`setLocalStateField`in n&&typeof n.setLocalStateField==`function`&&n.setLocalStateField(`user`,e.user);let r=({updated:e})=>{for(let n of e){let e=t.get(n);e&&(setTimeout(()=>{e.element.setAttribute(`data-active`,``)},10),e.hideTimeout&&clearTimeout(e.hideTimeout),t.set(n,{element:e.element,hideTimeout:setTimeout(()=>{e.element.removeAttribute(`data-active`)},2e3)}))}};return{key:`yCursor`,mount(){if(n&&e.showCursorLabels!==`always`&&`on`in n&&typeof n.on==`function`)return n.on(`change`,r),()=>{`off`in n&&typeof n.off==`function`&&n.off(`change`,r)}},prosemirrorPlugins:[n?(0,o.yCursorPlugin)(n,{selectionBuilder:o.defaultSelectionBuilder,cursorBuilder(n,r){let i=t.get(r);if(!i){let a=(e.renderCursor??_)(n);e.showCursorLabels!==`always`&&(a.addEventListener(`mouseenter`,()=>{let e=t.get(r);e.element.setAttribute(`data-active`,``),e.hideTimeout&&(clearTimeout(e.hideTimeout),t.set(r,{element:e.element,hideTimeout:void 0}))}),a.addEventListener(`mouseleave`,()=>{let e=t.get(r);t.set(r,{element:e.element,hideTimeout:setTimeout(()=>{e.element.removeAttribute(`data-active`)},2e3)})})),i={element:a,hideTimeout:void 0},t.set(r,i)}return i.element}}):void 0].filter(Boolean),dependsOn:[`ySync`],updateUser(e){n?.setLocalStateField(`user`,e)},getUser(){let e=n?.getLocalState();if(e)return e.user}}}),y=t.t(({options:e})=>({key:`ySync`,prosemirrorPlugins:[(0,o.ySyncPlugin)(e.fragment)],runsBefore:[`default`]})),b=t.t(()=>({key:`yUndo`,prosemirrorPlugins:[(0,o.yUndoPlugin)()],dependsOn:[`yCursor`,`ySync`],undoCommand:o.undoCommand,redoCommand:o.redoCommand}));function x(e,t){e.transact(e=>e.setMeta(o.ySyncPluginKey,{type:t,doc:t.doc}))}var S=t.t(({editor:e,options:n})=>{let r,i=t.n({isForked:!1});return{key:`yForkDoc`,store:i,fork({initialUpdate:t}={}){if(r)return;let a=n.fragment;if(!a)throw Error(`No fragment to fork from`);let l=new s.Doc;s.applyUpdate(l,t??s.encodeStateAsUpdate(a.doc));let u=c(a,l);r={undoStack:o.yUndoPluginKey.getState(e.prosemirrorState).undoManager.undoStack,originalFragment:a,forkedFragment:u};let d={...n,fragment:u};e.replaceExtension([`ySync`,`yCursor`,`yUndo`],[y(d),b()]),x(e,u),i.setState({isForked:!0})},merge({keepChanges:t}){if(!r)return;let{originalFragment:a,forkedFragment:c,undoStack:l}=r;if(e.replaceExtension([`ySync`,`yCursor`,`yUndo`],[y(n),v(n),b()]),x(e,a),o.yUndoPluginKey.getState(e.prosemirrorState).undoManager.undoStack=l,t){let t=s.encodeStateAsUpdate(c.doc,s.encodeStateVector(a.doc));s.applyUpdate(a.doc,t,e)}r=void 0,i.setState({isForked:!1})}}}),C=t.t(({editor:e})=>({key:`yPositionMapping`,mapPosition:(t,n=`left`)=>{let r=o.ySyncPluginKey.getState(e.prosemirrorState);if(!r)throw Error(`YSync plugin state not found`);if(t===0)return()=>0;if(r.binding.type.length===0){let r=e.getExtension(`positionMapping`);if(!r)throw Error(`positionMapping extension is not available; cannot map position before sync`);return r.mapPosition(t,n)}let i=(0,o.absolutePositionToRelativePosition)(t+(n===`right`?1:-1),r.binding.type,r.binding.mapping);return()=>{let t=o.ySyncPluginKey.getState(e.prosemirrorState),r=t.binding.type,a=(0,o.relativePositionToAbsolutePosition)(r.doc,r,i,t.binding.mapping);if(a===null)throw Error(`Position not found, cannot track positions`);return a+(n===`right`?-1:1)}}})),w=(e,t)=>{t(e),e.forEach(e=>{e instanceof s.XmlElement&&w(e,t)})},T=[(t,n)=>{let r=new Map;return t.forEach(t=>{t instanceof s.XmlElement&&w(t,t=>{if(t.nodeName===`blockContainer`&&t.hasAttribute(`id`)){let n=t.getAttribute(`textColor`),i=t.getAttribute(`backgroundColor`),a={textColor:n===e.Ct.textColor.default?void 0:n,backgroundColor:i===e.Ct.backgroundColor.default?void 0:i};(a.textColor||a.backgroundColor)&&r.set(t.getAttribute(`id`),a)}})}),r.size!==0&&(n.doc.descendants((e,t)=>{if(e.type.name===`blockContainer`&&r.has(e.attrs.id)){let i=n.doc.nodeAt(t+1);if(!i)throw Error(`No element found`);n.setNodeMarkup(t+1,void 0,{...i.attrs,...r.get(e.attrs.id)})}}),!0)}],E=t.t(({options:e})=>{let t=!1,n=new a.PluginKey(`schemaMigration`);return{key:`schemaMigration`,prosemirrorPlugins:[new a.Plugin({key:n,appendTransaction:(n,r,i)=>{if(t||!n.some(e=>e.getMeta(`y-sync$`))||n.every(e=>!e.docChanged)||!e.fragment.firstChild)return;let a=i.tr;for(let t of T)t(e.fragment,a);if(t=!0,a.docChanged)return a}})]}});function D(e,t){let{fragment:n}=t;function r(){let t=e.getExtension(S);if(!t)throw Error(`ForkYDocExtension is required for the Yjs versioning adapter. Make sure it is registered before the VersioningExtension.`);return t}return{getCurrentDocument:()=>n,serializeCurrentContent:()=>s.encodeStateAsUpdateV2(n.doc),preview:{supportsComparison:!1,enterPreview(e,t){let n=r();n.store.state.isForked&&n.merge({keepChanges:!1}),n.fork({initialUpdate:e})},exitPreview(){let e=r();e.store.state.isForked&&e.merge({keepChanges:!1})},applyRestore(e){throw Error(`Restore is not yet implemented for Yjs v13 versioning adapter.`)}}}}var O=t.t(({options:e})=>({key:`collaboration`,blockNoteExtensions:[h(),S(e),C(),E(e),v(e),y(e),b()]}));function k(e){return{...e,extensions:[...e.extensions??[],O(e.collaboration)],disableExtensions:[`history`,...e.disableExtensions??[]],initialContent:[{type:`paragraph`,id:`initialBlockId`}]}}function A(e){let t=new s.Map;if(t.set(`id`,e.id),t.set(`userId`,e.userId),t.set(`createdAt`,e.createdAt.getTime()),t.set(`updatedAt`,e.updatedAt.getTime()),e.deletedAt?(t.set(`deletedAt`,e.deletedAt.getTime()),t.set(`body`,void 0)):t.set(`body`,e.body),e.reactions.length>0)throw Error(`Reactions should be empty in commentToYMap`);return t.set(`reactionsByUser`,new s.Map),t.set(`metadata`,e.metadata),t}function j(e){let t=new s.Map;t.set(`id`,e.id),t.set(`createdAt`,e.createdAt.getTime()),t.set(`updatedAt`,e.updatedAt.getTime());let n=new s.Array;return n.push(e.comments.map(e=>A(e))),t.set(`comments`,n),t.set(`resolved`,e.resolved),t.set(`resolvedUpdatedAt`,e.resolvedUpdatedAt?.getTime()),t.set(`resolvedBy`,e.resolvedBy),t.set(`metadata`,e.metadata),t}function M(e){return{emoji:e.get(`emoji`),createdAt:new Date(e.get(`createdAt`)),userId:e.get(`userId`)}}function N(e){return[...e.values()].map(e=>M(e)).reduce((e,t)=>{let n=e.find(e=>e.emoji===t.emoji);return n?(n.userIds.push(t.userId),n.createdAt=new Date(Math.min(n.createdAt.getTime(),t.createdAt.getTime()))):e.push({emoji:t.emoji,createdAt:t.createdAt,userIds:[t.userId]}),e},[])}function P(e){return{type:`comment`,id:e.get(`id`),userId:e.get(`userId`),createdAt:new Date(e.get(`createdAt`)),updatedAt:new Date(e.get(`updatedAt`)),deletedAt:e.get(`deletedAt`)?new Date(e.get(`deletedAt`)):void 0,reactions:N(e.get(`reactionsByUser`)),metadata:e.get(`metadata`),body:e.get(`body`)}}function F(e){return{type:`thread`,id:e.get(`id`),createdAt:new Date(e.get(`createdAt`)),updatedAt:new Date(e.get(`updatedAt`)),comments:(e.get(`comments`)||[]).map(e=>P(e)),resolved:e.get(`resolved`),resolvedUpdatedAt:new Date(e.get(`resolvedUpdatedAt`)),resolvedBy:e.get(`resolvedBy`),metadata:e.get(`metadata`)}}var I=class extends n.t{threadsYMap;constructor(e,t){super(t),this.threadsYMap=e}getThread(e){let t=this.threadsYMap.get(e);if(!t)throw Error(`Thread not found`);return F(t)}getThreads(){let e=new Map;return this.threadsYMap.forEach((t,n)=>{t instanceof s.Map&&e.set(n,F(t))}),e}subscribe(e){let t=()=>{e(this.getThreads())};return this.threadsYMap.observeDeep(t),()=>{this.threadsYMap.unobserveDeep(t)}}},L=class extends I{BASE_URL;headers;constructor(e,t,n,r){super(n,r),this.BASE_URL=e,this.headers=t}doRequest=async(e,t,n)=>{let r=await fetch(`${this.BASE_URL}${e}`,{method:t,body:JSON.stringify(n),headers:{"Content-Type":`application/json`,...this.headers}});if(!r.ok)throw Error(`Failed to ${t} ${e}: ${r.statusText}`);return r.json()};addThreadToDocument=async e=>{let{threadId:t,selection:n}=e,r=o.ySyncPluginKey.getState(e.editor.prosemirrorState)?.binding,i=r?{head:(0,o.absolutePositionToRelativePosition)(n.head,r.type,r.mapping),anchor:(0,o.absolutePositionToRelativePosition)(n.anchor,r.type,r.mapping)}:void 0;return this.doRequest(`/${t}/addToDocument`,`POST`,{selection:{prosemirror:n,yjs:i}})};createThread=async e=>this.doRequest(``,`POST`,e);addComment=e=>{let{threadId:t,...n}=e;return this.doRequest(`/${t}/comments`,`POST`,n)};updateComment=e=>{let{threadId:t,commentId:n,...r}=e;return this.doRequest(`/${t}/comments/${n}`,`PUT`,r)};deleteComment=e=>{let{threadId:t,commentId:n,...r}=e;return this.doRequest(`/${t}/comments/${n}?soft=${!!r.softDelete}`,`DELETE`)};deleteThread=e=>this.doRequest(`/${e.threadId}`,`DELETE`);resolveThread=e=>this.doRequest(`/${e.threadId}/resolve`,`POST`);unresolveThread=e=>this.doRequest(`/${e.threadId}/unresolve`,`POST`);addReaction=e=>{let{threadId:t,commentId:n,...r}=e;return this.doRequest(`/${t}/comments/${n}/reactions`,`POST`,r)};deleteReaction=e=>this.doRequest(`/${e.threadId}/comments/${e.commentId}/reactions/${e.emoji}`,`DELETE`)},R=class extends I{userId;constructor(e,t,n){super(t,n),this.userId=e}transact=e=>async t=>this.threadsYMap.doc.transact(()=>e(t));createThread=this.transact(e=>{if(!this.auth.canCreateThread())throw Error(`Not authorized`);let t=new Date,n={type:`comment`,id:(0,i.uuidv4)(),userId:this.userId,createdAt:t,updatedAt:t,reactions:[],metadata:e.initialComment.metadata,body:e.initialComment.body},r={type:`thread`,id:(0,i.uuidv4)(),createdAt:t,updatedAt:t,comments:[n],resolved:!1,metadata:e.metadata};return this.threadsYMap.set(r.id,j(r)),r});addThreadToDocument=void 0;addComment=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);if(!this.auth.canAddComment(F(t)))throw Error(`Not authorized`);let n=new Date,r={type:`comment`,id:(0,i.uuidv4)(),userId:this.userId,createdAt:n,updatedAt:n,deletedAt:void 0,reactions:[],metadata:e.comment.metadata,body:e.comment.body};return t.get(`comments`).push([A(r)]),t.set(`updatedAt`,new Date().getTime()),r});updateComment=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canUpdateComment(P(r)))throw Error(`Not authorized`);r.set(`body`,e.comment.body),r.set(`updatedAt`,new Date().getTime()),r.set(`metadata`,e.comment.metadata)});deleteComment=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canDeleteComment(P(r)))throw Error(`Not authorized`);if(r.get(`deletedAt`))throw Error(`Comment already deleted`);e.softDelete?(r.set(`deletedAt`,new Date().getTime()),r.set(`body`,void 0)):t.get(`comments`).delete(n),t.get(`comments`).toArray().every(e=>e.get(`deletedAt`))&&(e.softDelete?t.set(`deletedAt`,new Date().getTime()):this.threadsYMap.delete(e.threadId)),t.set(`updatedAt`,new Date().getTime())});deleteThread=this.transact(e=>{if(!this.auth.canDeleteThread(F(this.threadsYMap.get(e.threadId))))throw Error(`Not authorized`);this.threadsYMap.delete(e.threadId)});resolveThread=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);if(!this.auth.canResolveThread(F(t)))throw Error(`Not authorized`);t.set(`resolved`,!0),t.set(`resolvedUpdatedAt`,new Date().getTime()),t.set(`resolvedBy`,this.userId)});unresolveThread=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);if(!this.auth.canUnresolveThread(F(t)))throw Error(`Not authorized`);t.set(`resolved`,!1),t.set(`resolvedUpdatedAt`,new Date().getTime())});addReaction=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canAddReaction(P(r),e.emoji))throw Error(`Not authorized`);let i=new Date,a=`${this.userId}-${e.emoji}`,o=r.get(`reactionsByUser`);if(!o.has(a)){let t=new s.Map;t.set(`emoji`,e.emoji),t.set(`createdAt`,i.getTime()),t.set(`userId`,this.userId),o.set(a,t)}});deleteReaction=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canDeleteReaction(P(r),e.emoji))throw Error(`Not authorized`);let i=`${this.userId}-${e.emoji}`;r.get(`reactionsByUser`).delete(i)})};function z(e,t){for(let n=0;n<e.length;n++)if(t(e.get(n)))return n;return-1}exports.CollaborationExtension=O,exports.ForkYDocExtension=S,exports.RESTYjsThreadStore=L,exports.RelativePositionMappingExtension=C,exports.SchemaMigration=E,exports.YCursorExtension=v,exports.YSyncExtension=y,exports.YUndoExtension=b,exports.YjsThreadStore=R,exports.YjsThreadStoreBase=I,exports._blocksToProsemirrorNode=u,exports._prosemirrorJSONToBlocks=l,exports.blocksToYDoc=m,exports.blocksToYXmlFragment=f,exports.createYjsVersioningAdapter=D,exports.findTypeInOtherYdoc=c,exports.withCollaboration=k,exports.yDocToBlocks=p,exports.yXmlFragmentToBlocks=d;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./blocks-CTB_5Vyj.cjs"),t=require("./BlockNoteExtension-BJCLnwrE.cjs"),n=require("./ThreadStore-Bx-gSEh1.cjs");let r=require("prosemirror-model"),i=require("lib0/random"),a=require("@tiptap/pm/state"),o=require("y-prosemirror"),s=require("yjs");s=e.sr(s,1);function c(e,t){let n=e.doc;if(!n)throw Error(`type does not have a ydoc`);if(e._item===null){let r=Array.from(n.share.keys()).find(t=>n.share.get(t)===e);if(r==null)throw Error(`type does not exist in other ydoc`);return t.get(r,e.constructor)}{let n=e._item,r=t.store.clients.get(n.id.client)??[],i=r[s.findIndexSS(r,n.id.clock)];if(!i)throw Error(`type does not exist in other ydoc`);let a=i.content;if(!a)throw Error(`type does not exist in other ydoc`);return a.type}}function l(t,n){let r=t.pmSchema.nodeFromJSON(n);return e.Cn(r)}function u(t,n){let r=n.map(n=>e.Ft(n,t.pmSchema));return t.pmSchema.topNodeType.create(null,t.pmSchema.nodes.blockGroup.create(null,r))}function d(t,n){let r=(0,o.yXmlFragmentToProseMirrorRootNode)(n,t.pmSchema);return e.Cn(r)}function f(e,t,n){return(0,o.prosemirrorToYXmlFragment)(u(e,t),n)}function p(e,t,n=`prosemirror`){return d(e,t.getXmlFragment(n))}function m(e,t,n=`prosemirror`){return(0,o.prosemirrorToYDoc)(u(e,t),n)}var h=t.t(({editor:t})=>(t.on(`create`,()=>{let n=t.pmSchema,i,a=n.nodes.doc.createAndFill;n.nodes.doc.createAndFill=((...e)=>{if(i)return i;let t=a.apply(n.nodes.doc,e),o=JSON.parse(JSON.stringify(t.toJSON()));return o.content[0].content[0].attrs.id=`initialBlockId`,i=r.Node.fromJSON(n,o),i});let o=n.node;n.node=function(t,n,r,i){let a=typeof t==`string`?this.nodes[t]:t;return a&&e.Nn(this,a)&&Array.isArray(r)&&(r=r.map(e=>e?.isText&&e.marks.length?e.mark(a.allowedMarks(e.marks)):e)),o.call(this,t,n,r,i)}}),{key:`fixUpSchema`}));function g(e){let t=e.charAt(0)===`#`?e.substring(1,7):e,n=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),i=parseInt(t.substring(4,6),16),a=[n/255,r/255,i/255].map(e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4);return .2126*a[0]+.7152*a[1]+.0722*a[2]<=.179}function _(e){let t=document.createElement(`span`);t.classList.add(`bn-collaboration-cursor__base`);let n=document.createElement(`span`);n.setAttribute(`contentedEditable`,`false`),n.classList.add(`bn-collaboration-cursor__caret`),n.setAttribute(`style`,`background-color: ${e.color}; color: ${g(e.color)?`white`:`black`}`);let r=document.createElement(`span`);return r.classList.add(`bn-collaboration-cursor__label`),r.setAttribute(`style`,`background-color: ${e.color}; color: ${g(e.color)?`white`:`black`}`),r.insertBefore(document.createTextNode(e.name),null),n.insertBefore(r,null),t.insertBefore(document.createTextNode(``),null),t.insertBefore(n,null),t.insertBefore(document.createTextNode(``),null),t}var v=t.t(({options:e})=>{let t=new Map,n=e.provider&&`awareness`in e.provider&&typeof e.provider.awareness==`object`?e.provider.awareness:void 0;n&&`setLocalStateField`in n&&typeof n.setLocalStateField==`function`&&n.setLocalStateField(`user`,e.user);let r=({updated:e})=>{for(let n of e){let e=t.get(n);e&&(setTimeout(()=>{e.element.setAttribute(`data-active`,``)},10),e.hideTimeout&&clearTimeout(e.hideTimeout),t.set(n,{element:e.element,hideTimeout:setTimeout(()=>{e.element.removeAttribute(`data-active`)},2e3)}))}};return{key:`yCursor`,mount(){if(n&&e.showCursorLabels!==`always`&&`on`in n&&typeof n.on==`function`)return n.on(`change`,r),()=>{`off`in n&&typeof n.off==`function`&&n.off(`change`,r)}},prosemirrorPlugins:[n?(0,o.yCursorPlugin)(n,{selectionBuilder:o.defaultSelectionBuilder,cursorBuilder(n,r){let i=t.get(r);if(!i){let a=(e.renderCursor??_)(n);e.showCursorLabels!==`always`&&(a.addEventListener(`mouseenter`,()=>{let e=t.get(r);e.element.setAttribute(`data-active`,``),e.hideTimeout&&(clearTimeout(e.hideTimeout),t.set(r,{element:e.element,hideTimeout:void 0}))}),a.addEventListener(`mouseleave`,()=>{let e=t.get(r);t.set(r,{element:e.element,hideTimeout:setTimeout(()=>{e.element.removeAttribute(`data-active`)},2e3)})})),i={element:a,hideTimeout:void 0},t.set(r,i)}return i.element}}):void 0].filter(Boolean),dependsOn:[`ySync`],updateUser(e){n?.setLocalStateField(`user`,e)},getUser(){let e=n?.getLocalState();if(e)return e.user}}}),y=t.t(({options:e})=>({key:`ySync`,prosemirrorPlugins:[(0,o.ySyncPlugin)(e.fragment)],runsBefore:[`default`]})),b=t.t(()=>({key:`yUndo`,prosemirrorPlugins:[(0,o.yUndoPlugin)()],dependsOn:[`yCursor`,`ySync`],undoCommand:o.undoCommand,redoCommand:o.redoCommand}));function x(e,t){e.transact(e=>e.setMeta(o.ySyncPluginKey,{type:t,doc:t.doc}))}var S=t.t(({editor:e,options:n})=>{let r,i=t.n({isForked:!1});return{key:`yForkDoc`,store:i,fork({initialUpdate:t}={}){if(r)return;let a=n.fragment;if(!a)throw Error(`No fragment to fork from`);let l=new s.Doc;s.applyUpdate(l,t??s.encodeStateAsUpdate(a.doc));let u=c(a,l);r={undoStack:o.yUndoPluginKey.getState(e.prosemirrorState).undoManager.undoStack,originalFragment:a,forkedFragment:u};let d={...n,fragment:u};e.replaceExtension([`ySync`,`yCursor`,`yUndo`],[y(d),b()]),x(e,u),i.setState({isForked:!0})},merge({keepChanges:t}){if(!r)return;let{originalFragment:a,forkedFragment:c,undoStack:l}=r;if(e.replaceExtension([`ySync`,`yCursor`,`yUndo`],[y(n),v(n),b()]),x(e,a),o.yUndoPluginKey.getState(e.prosemirrorState).undoManager.undoStack=l,t){let t=s.encodeStateAsUpdate(c.doc,s.encodeStateVector(a.doc));s.applyUpdate(a.doc,t,e)}r=void 0,i.setState({isForked:!1})}}}),C=t.t(({editor:e})=>({key:`yPositionMapping`,mapPosition:(t,n=`left`)=>{let r=o.ySyncPluginKey.getState(e.prosemirrorState);if(!r)throw Error(`YSync plugin state not found`);if(t===0)return()=>0;if(r.binding.type.length===0){let r=e.getExtension(`positionMapping`);if(!r)throw Error(`positionMapping extension is not available; cannot map position before sync`);return r.mapPosition(t,n)}let i=(0,o.absolutePositionToRelativePosition)(t+(n===`right`?1:-1),r.binding.type,r.binding.mapping);return()=>{let t=o.ySyncPluginKey.getState(e.prosemirrorState),r=t.binding.type,a=(0,o.relativePositionToAbsolutePosition)(r.doc,r,i,t.binding.mapping);if(a===null)throw Error(`Position not found, cannot track positions`);return a+(n===`right`?-1:1)}}})),w=(e,t)=>{t(e),e.forEach(e=>{e instanceof s.XmlElement&&w(e,t)})},T=[(t,n)=>{let r=new Map;return t.forEach(t=>{t instanceof s.XmlElement&&w(t,t=>{if(t.nodeName===`blockContainer`&&t.hasAttribute(`id`)){let n=t.getAttribute(`textColor`),i=t.getAttribute(`backgroundColor`),a={textColor:n===e.St.textColor.default?void 0:n,backgroundColor:i===e.St.backgroundColor.default?void 0:i};(a.textColor||a.backgroundColor)&&r.set(t.getAttribute(`id`),a)}})}),r.size!==0&&(n.doc.descendants((e,t)=>{if(e.type.name===`blockContainer`&&r.has(e.attrs.id)){let i=n.doc.nodeAt(t+1);if(!i)throw Error(`No element found`);n.setNodeMarkup(t+1,void 0,{...i.attrs,...r.get(e.attrs.id)})}}),!0)}],E=t.t(({options:e})=>{let t=!1,n=new a.PluginKey(`schemaMigration`);return{key:`schemaMigration`,prosemirrorPlugins:[new a.Plugin({key:n,appendTransaction:(n,r,i)=>{if(t||!n.some(e=>e.getMeta(`y-sync$`))||n.every(e=>!e.docChanged)||!e.fragment.firstChild)return;let a=i.tr;for(let t of T)t(e.fragment,a);if(t=!0,a.docChanged)return a}})]}});function D(e,t){let{fragment:n}=t;function r(){let t=e.getExtension(S);if(!t)throw Error(`ForkYDocExtension is required for the Yjs versioning adapter. Make sure it is registered before the VersioningExtension.`);return t}return{getCurrentDocument:()=>n,serializeCurrentContent:()=>s.encodeStateAsUpdateV2(n.doc),preview:{supportsComparison:!1,enterPreview(e,t){let n=r();n.store.state.isForked&&n.merge({keepChanges:!1}),n.fork({initialUpdate:e})},exitPreview(){let e=r();e.store.state.isForked&&e.merge({keepChanges:!1})},applyRestore(e){throw Error(`Restore is not yet implemented for Yjs v13 versioning adapter.`)}}}}var O=t.t(({options:e})=>({key:`collaboration`,blockNoteExtensions:[h(),S(e),C(),E(e),v(e),y(e),b()]}));function k(e){return{...e,extensions:[...e.extensions??[],O(e.collaboration)],disableExtensions:[`history`,...e.disableExtensions??[]],initialContent:[{type:`paragraph`,id:`initialBlockId`}]}}function A(e){let t=new s.Map;if(t.set(`id`,e.id),t.set(`userId`,e.userId),t.set(`createdAt`,e.createdAt.getTime()),t.set(`updatedAt`,e.updatedAt.getTime()),e.deletedAt?(t.set(`deletedAt`,e.deletedAt.getTime()),t.set(`body`,void 0)):t.set(`body`,e.body),e.reactions.length>0)throw Error(`Reactions should be empty in commentToYMap`);return t.set(`reactionsByUser`,new s.Map),t.set(`metadata`,e.metadata),t}function j(e){let t=new s.Map;t.set(`id`,e.id),t.set(`createdAt`,e.createdAt.getTime()),t.set(`updatedAt`,e.updatedAt.getTime());let n=new s.Array;return n.push(e.comments.map(e=>A(e))),t.set(`comments`,n),t.set(`resolved`,e.resolved),t.set(`resolvedUpdatedAt`,e.resolvedUpdatedAt?.getTime()),t.set(`resolvedBy`,e.resolvedBy),t.set(`metadata`,e.metadata),t}function M(e){return{emoji:e.get(`emoji`),createdAt:new Date(e.get(`createdAt`)),userId:e.get(`userId`)}}function N(e){return[...e.values()].map(e=>M(e)).reduce((e,t)=>{let n=e.find(e=>e.emoji===t.emoji);return n?(n.userIds.push(t.userId),n.createdAt=new Date(Math.min(n.createdAt.getTime(),t.createdAt.getTime()))):e.push({emoji:t.emoji,createdAt:t.createdAt,userIds:[t.userId]}),e},[])}function P(e){return{type:`comment`,id:e.get(`id`),userId:e.get(`userId`),createdAt:new Date(e.get(`createdAt`)),updatedAt:new Date(e.get(`updatedAt`)),deletedAt:e.get(`deletedAt`)?new Date(e.get(`deletedAt`)):void 0,reactions:N(e.get(`reactionsByUser`)),metadata:e.get(`metadata`),body:e.get(`body`)}}function F(e){return{type:`thread`,id:e.get(`id`),createdAt:new Date(e.get(`createdAt`)),updatedAt:new Date(e.get(`updatedAt`)),comments:(e.get(`comments`)||[]).map(e=>P(e)),resolved:e.get(`resolved`),resolvedUpdatedAt:new Date(e.get(`resolvedUpdatedAt`)),resolvedBy:e.get(`resolvedBy`),metadata:e.get(`metadata`)}}var I=class extends n.t{threadsYMap;constructor(e,t){super(t),this.threadsYMap=e}getThread(e){let t=this.threadsYMap.get(e);if(!t)throw Error(`Thread not found`);return F(t)}getThreads(){let e=new Map;return this.threadsYMap.forEach((t,n)=>{t instanceof s.Map&&e.set(n,F(t))}),e}subscribe(e){let t=()=>{e(this.getThreads())};return this.threadsYMap.observeDeep(t),()=>{this.threadsYMap.unobserveDeep(t)}}},L=class extends I{BASE_URL;headers;constructor(e,t,n,r){super(n,r),this.BASE_URL=e,this.headers=t}doRequest=async(e,t,n)=>{let r=await fetch(`${this.BASE_URL}${e}`,{method:t,body:JSON.stringify(n),headers:{"Content-Type":`application/json`,...this.headers}});if(!r.ok)throw Error(`Failed to ${t} ${e}: ${r.statusText}`);return r.json()};addThreadToDocument=async e=>{let{threadId:t,selection:n}=e,r=o.ySyncPluginKey.getState(e.editor.prosemirrorState)?.binding,i=r?{head:(0,o.absolutePositionToRelativePosition)(n.head,r.type,r.mapping),anchor:(0,o.absolutePositionToRelativePosition)(n.anchor,r.type,r.mapping)}:void 0;return this.doRequest(`/${t}/addToDocument`,`POST`,{selection:{prosemirror:n,yjs:i}})};createThread=async e=>this.doRequest(``,`POST`,e);addComment=e=>{let{threadId:t,...n}=e;return this.doRequest(`/${t}/comments`,`POST`,n)};updateComment=e=>{let{threadId:t,commentId:n,...r}=e;return this.doRequest(`/${t}/comments/${n}`,`PUT`,r)};deleteComment=e=>{let{threadId:t,commentId:n,...r}=e;return this.doRequest(`/${t}/comments/${n}?soft=${!!r.softDelete}`,`DELETE`)};deleteThread=e=>this.doRequest(`/${e.threadId}`,`DELETE`);resolveThread=e=>this.doRequest(`/${e.threadId}/resolve`,`POST`);unresolveThread=e=>this.doRequest(`/${e.threadId}/unresolve`,`POST`);addReaction=e=>{let{threadId:t,commentId:n,...r}=e;return this.doRequest(`/${t}/comments/${n}/reactions`,`POST`,r)};deleteReaction=e=>this.doRequest(`/${e.threadId}/comments/${e.commentId}/reactions/${e.emoji}`,`DELETE`)},R=class extends I{userId;constructor(e,t,n){super(t,n),this.userId=e}transact=e=>async t=>this.threadsYMap.doc.transact(()=>e(t));createThread=this.transact(e=>{if(!this.auth.canCreateThread())throw Error(`Not authorized`);let t=new Date,n={type:`comment`,id:(0,i.uuidv4)(),userId:this.userId,createdAt:t,updatedAt:t,reactions:[],metadata:e.initialComment.metadata,body:e.initialComment.body},r={type:`thread`,id:(0,i.uuidv4)(),createdAt:t,updatedAt:t,comments:[n],resolved:!1,metadata:e.metadata};return this.threadsYMap.set(r.id,j(r)),r});addThreadToDocument=void 0;addComment=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);if(!this.auth.canAddComment(F(t)))throw Error(`Not authorized`);let n=new Date,r={type:`comment`,id:(0,i.uuidv4)(),userId:this.userId,createdAt:n,updatedAt:n,deletedAt:void 0,reactions:[],metadata:e.comment.metadata,body:e.comment.body};return t.get(`comments`).push([A(r)]),t.set(`updatedAt`,new Date().getTime()),r});updateComment=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canUpdateComment(P(r)))throw Error(`Not authorized`);r.set(`body`,e.comment.body),r.set(`updatedAt`,new Date().getTime()),r.set(`metadata`,e.comment.metadata)});deleteComment=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canDeleteComment(P(r)))throw Error(`Not authorized`);if(r.get(`deletedAt`))throw Error(`Comment already deleted`);e.softDelete?(r.set(`deletedAt`,new Date().getTime()),r.set(`body`,void 0)):t.get(`comments`).delete(n),t.get(`comments`).toArray().every(e=>e.get(`deletedAt`))&&(e.softDelete?t.set(`deletedAt`,new Date().getTime()):this.threadsYMap.delete(e.threadId)),t.set(`updatedAt`,new Date().getTime())});deleteThread=this.transact(e=>{if(!this.auth.canDeleteThread(F(this.threadsYMap.get(e.threadId))))throw Error(`Not authorized`);this.threadsYMap.delete(e.threadId)});resolveThread=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);if(!this.auth.canResolveThread(F(t)))throw Error(`Not authorized`);t.set(`resolved`,!0),t.set(`resolvedUpdatedAt`,new Date().getTime()),t.set(`resolvedBy`,this.userId)});unresolveThread=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);if(!this.auth.canUnresolveThread(F(t)))throw Error(`Not authorized`);t.set(`resolved`,!1),t.set(`resolvedUpdatedAt`,new Date().getTime())});addReaction=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canAddReaction(P(r),e.emoji))throw Error(`Not authorized`);let i=new Date,a=`${this.userId}-${e.emoji}`,o=r.get(`reactionsByUser`);if(!o.has(a)){let t=new s.Map;t.set(`emoji`,e.emoji),t.set(`createdAt`,i.getTime()),t.set(`userId`,this.userId),o.set(a,t)}});deleteReaction=this.transact(e=>{let t=this.threadsYMap.get(e.threadId);if(!t)throw Error(`Thread not found`);let n=z(t.get(`comments`),t=>t.get(`id`)===e.commentId);if(n===-1)throw Error(`Comment not found`);let r=t.get(`comments`).get(n);if(!this.auth.canDeleteReaction(P(r),e.emoji))throw Error(`Not authorized`);let i=`${this.userId}-${e.emoji}`;r.get(`reactionsByUser`).delete(i)})};function z(e,t){for(let n=0;n<e.length;n++)if(t(e.get(n)))return n;return-1}exports.CollaborationExtension=O,exports.ForkYDocExtension=S,exports.RESTYjsThreadStore=L,exports.RelativePositionMappingExtension=C,exports.SchemaMigration=E,exports.YCursorExtension=v,exports.YSyncExtension=y,exports.YUndoExtension=b,exports.YjsThreadStore=R,exports.YjsThreadStoreBase=I,exports._blocksToProsemirrorNode=u,exports._prosemirrorJSONToBlocks=l,exports.blocksToYDoc=m,exports.blocksToYXmlFragment=f,exports.createYjsVersioningAdapter=D,exports.findTypeInOtherYdoc=c,exports.withCollaboration=k,exports.yDocToBlocks=p,exports.yXmlFragmentToBlocks=d;
|
|
2
2
|
//# sourceMappingURL=yjs.cjs.map
|
package/dist/yjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Cn as e, Ft as t, Nn as n, St as r } from "./blocks-Dol85hpH.js";
|
|
2
2
|
import { n as i, t as a } from "./BlockNoteExtension-CbvDA0F7.js";
|
|
3
3
|
import { t as o } from "./ThreadStore-et9wB5Xt.js";
|
|
4
4
|
import { Node as s } from "prosemirror-model";
|
|
@@ -23,17 +23,17 @@ function w(e, t) {
|
|
|
23
23
|
return a.type;
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
|
-
function T(
|
|
27
|
-
let
|
|
28
|
-
return r
|
|
26
|
+
function T(t, n) {
|
|
27
|
+
let r = t.pmSchema.nodeFromJSON(n);
|
|
28
|
+
return e(r);
|
|
29
29
|
}
|
|
30
30
|
function E(e, n) {
|
|
31
31
|
let r = n.map((n) => t(n, e.pmSchema));
|
|
32
32
|
return e.pmSchema.topNodeType.create(null, e.pmSchema.nodes.blockGroup.create(null, r));
|
|
33
33
|
}
|
|
34
|
-
function D(
|
|
35
|
-
let
|
|
36
|
-
return r
|
|
34
|
+
function D(t, n) {
|
|
35
|
+
let r = S(n, t.pmSchema);
|
|
36
|
+
return e(r);
|
|
37
37
|
}
|
|
38
38
|
function O(e, t, n) {
|
|
39
39
|
return m(E(e, t), n);
|
|
@@ -223,25 +223,25 @@ var R = a(({ editor: e, options: t }) => {
|
|
|
223
223
|
t(e), e.forEach((e) => {
|
|
224
224
|
e instanceof C.XmlElement && B(e, t);
|
|
225
225
|
});
|
|
226
|
-
}, V = [(
|
|
227
|
-
let
|
|
228
|
-
return
|
|
229
|
-
|
|
230
|
-
if (
|
|
231
|
-
let
|
|
232
|
-
textColor:
|
|
233
|
-
backgroundColor: i ===
|
|
226
|
+
}, V = [(e, t) => {
|
|
227
|
+
let n = /* @__PURE__ */ new Map();
|
|
228
|
+
return e.forEach((e) => {
|
|
229
|
+
e instanceof C.XmlElement && B(e, (e) => {
|
|
230
|
+
if (e.nodeName === "blockContainer" && e.hasAttribute("id")) {
|
|
231
|
+
let t = e.getAttribute("textColor"), i = e.getAttribute("backgroundColor"), a = {
|
|
232
|
+
textColor: t === r.textColor.default ? void 0 : t,
|
|
233
|
+
backgroundColor: i === r.backgroundColor.default ? void 0 : i
|
|
234
234
|
};
|
|
235
|
-
(a.textColor || a.backgroundColor) &&
|
|
235
|
+
(a.textColor || a.backgroundColor) && n.set(e.getAttribute("id"), a);
|
|
236
236
|
}
|
|
237
237
|
});
|
|
238
|
-
}),
|
|
239
|
-
if (e.type.name === "blockContainer" &&
|
|
240
|
-
let i =
|
|
238
|
+
}), n.size !== 0 && (t.doc.descendants((e, r) => {
|
|
239
|
+
if (e.type.name === "blockContainer" && n.has(e.attrs.id)) {
|
|
240
|
+
let i = t.doc.nodeAt(r + 1);
|
|
241
241
|
if (!i) throw Error("No element found");
|
|
242
|
-
|
|
242
|
+
t.setNodeMarkup(r + 1, void 0, {
|
|
243
243
|
...i.attrs,
|
|
244
|
-
...
|
|
244
|
+
...n.get(e.attrs.id)
|
|
245
245
|
});
|
|
246
246
|
}
|
|
247
247
|
}), !0);
|
package/package.json
CHANGED
|
@@ -2,7 +2,10 @@ import { describe, expect, it, beforeEach } from "vite-plus/test";
|
|
|
2
2
|
|
|
3
3
|
import { setupTestEnv } from "./blockManipulation/setupTestEnv.js";
|
|
4
4
|
import { getBlocksChangedByTransaction } from "./getBlocksChangedByTransaction.js";
|
|
5
|
+
import { getBlockInfo } from "./getBlockInfoFromPos.js";
|
|
6
|
+
import { getNodeById } from "./nodeUtil.js";
|
|
5
7
|
import { BlockNoteEditor } from "../editor/BlockNoteEditor.js";
|
|
8
|
+
import { PartialBlock } from "../blocks/defaultBlocks.js";
|
|
6
9
|
|
|
7
10
|
const getEditor = setupTestEnv();
|
|
8
11
|
|
|
@@ -570,3 +573,211 @@ describe("getBlocksChangedByTransaction", () => {
|
|
|
570
573
|
);
|
|
571
574
|
});
|
|
572
575
|
});
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* These exercise the ranged optimization: getBlocksChangedByTransaction only
|
|
579
|
+
* snapshots the range a transaction touched, not the whole document. In a large
|
|
580
|
+
* document the failure modes are (a) missing a real change and (b) reporting a
|
|
581
|
+
* block that didn't actually change. Each test edits a big document and asserts
|
|
582
|
+
* the exact set of reported changes.
|
|
583
|
+
*/
|
|
584
|
+
describe("getBlocksChangedByTransaction - ranged optimization", () => {
|
|
585
|
+
let editor: BlockNoteEditor;
|
|
586
|
+
|
|
587
|
+
const LARGE = 200;
|
|
588
|
+
|
|
589
|
+
function makeParagraphs(count: number): PartialBlock[] {
|
|
590
|
+
return Array.from({ length: count }, (_, i) => ({
|
|
591
|
+
id: `p-${i}`,
|
|
592
|
+
type: "paragraph",
|
|
593
|
+
content: `Paragraph ${i}`,
|
|
594
|
+
}));
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function summarize(changes: Array<{ type: string; block: { id: string } }>) {
|
|
598
|
+
return changes.map((change) => ({
|
|
599
|
+
type: change.type,
|
|
600
|
+
id: change.block.id,
|
|
601
|
+
}));
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
beforeEach(() => {
|
|
605
|
+
editor = getEditor();
|
|
606
|
+
});
|
|
607
|
+
|
|
608
|
+
it("reports only the changed block for a prop update deep in a large doc", () => {
|
|
609
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
610
|
+
|
|
611
|
+
const changes = editor.transact((tr) => {
|
|
612
|
+
editor.updateBlock("p-120", { props: { backgroundColor: "red" } });
|
|
613
|
+
return getBlocksChangedByTransaction(tr);
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
expect(summarize(changes)).toEqual([{ type: "update", id: "p-120" }]);
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
it("reports only the edited block for a content insertion in a large doc", () => {
|
|
620
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
621
|
+
|
|
622
|
+
const changes = editor.transact((tr) => {
|
|
623
|
+
editor.setTextCursorPosition("p-77", "start");
|
|
624
|
+
editor.insertInlineContent("Hello ");
|
|
625
|
+
return getBlocksChangedByTransaction(tr);
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
expect(summarize(changes)).toEqual([{ type: "update", id: "p-77" }]);
|
|
629
|
+
});
|
|
630
|
+
|
|
631
|
+
it("reports two distant prop updates without reporting the blocks between them", () => {
|
|
632
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
633
|
+
|
|
634
|
+
const changes = editor.transact((tr) => {
|
|
635
|
+
editor.updateBlock("p-10", { props: { backgroundColor: "red" } });
|
|
636
|
+
editor.updateBlock("p-190", { props: { backgroundColor: "blue" } });
|
|
637
|
+
return getBlocksChangedByTransaction(tr);
|
|
638
|
+
});
|
|
639
|
+
|
|
640
|
+
const summary = summarize(changes);
|
|
641
|
+
expect(summary).toContainEqual({ type: "update", id: "p-10" });
|
|
642
|
+
expect(summary).toContainEqual({ type: "update", id: "p-190" });
|
|
643
|
+
expect(summary).toHaveLength(2);
|
|
644
|
+
});
|
|
645
|
+
|
|
646
|
+
it("reports a mark-only change as an update (empty-map AddMarkStep)", () => {
|
|
647
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
648
|
+
|
|
649
|
+
const changes = editor.transact((tr) => {
|
|
650
|
+
const posInfo = getNodeById("p-140", tr.doc);
|
|
651
|
+
if (!posInfo) {
|
|
652
|
+
throw new Error("block not found");
|
|
653
|
+
}
|
|
654
|
+
const info = getBlockInfo(posInfo);
|
|
655
|
+
if (!info.isBlockContainer) {
|
|
656
|
+
throw new Error("expected a block container");
|
|
657
|
+
}
|
|
658
|
+
// Adding a mark produces an AddMarkStep, whose StepMap is empty — the case
|
|
659
|
+
// getChangedRange has to recover from the step's own from/to.
|
|
660
|
+
tr.addMark(
|
|
661
|
+
info.blockContent.beforePos + 1,
|
|
662
|
+
info.blockContent.afterPos - 1,
|
|
663
|
+
editor.pmSchema.marks.bold.create(),
|
|
664
|
+
);
|
|
665
|
+
return getBlocksChangedByTransaction(tr);
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
expect(summarize(changes)).toEqual([{ type: "update", id: "p-140" }]);
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
it("reports mixed insert/update/delete across a large doc in one transaction", () => {
|
|
672
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
673
|
+
|
|
674
|
+
const changes = editor.transact((tr) => {
|
|
675
|
+
editor.updateBlock("p-20", { props: { backgroundColor: "red" } });
|
|
676
|
+
editor.removeBlocks(["p-100"]);
|
|
677
|
+
editor.insertBlocks(
|
|
678
|
+
[{ id: "inserted", type: "paragraph", content: "new" }],
|
|
679
|
+
"p-180",
|
|
680
|
+
"after",
|
|
681
|
+
);
|
|
682
|
+
return getBlocksChangedByTransaction(tr);
|
|
683
|
+
});
|
|
684
|
+
|
|
685
|
+
const summary = summarize(changes);
|
|
686
|
+
expect(summary).toContainEqual({ type: "update", id: "p-20" });
|
|
687
|
+
expect(summary).toContainEqual({ type: "delete", id: "p-100" });
|
|
688
|
+
expect(summary).toContainEqual({ type: "insert", id: "inserted" });
|
|
689
|
+
expect(summary).toHaveLength(3);
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
it("reports an insert at the very start of a large doc", () => {
|
|
693
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
694
|
+
|
|
695
|
+
const changes = editor.transact((tr) => {
|
|
696
|
+
editor.insertBlocks(
|
|
697
|
+
[{ id: "new-first", type: "paragraph", content: "X" }],
|
|
698
|
+
"p-0",
|
|
699
|
+
"before",
|
|
700
|
+
);
|
|
701
|
+
return getBlocksChangedByTransaction(tr);
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
expect(summarize(changes)).toEqual([{ type: "insert", id: "new-first" }]);
|
|
705
|
+
});
|
|
706
|
+
|
|
707
|
+
it("reports an insert at the very end of a large doc", () => {
|
|
708
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
709
|
+
|
|
710
|
+
const changes = editor.transact((tr) => {
|
|
711
|
+
editor.insertBlocks(
|
|
712
|
+
[{ id: "new-last", type: "paragraph", content: "X" }],
|
|
713
|
+
`p-${LARGE - 1}`,
|
|
714
|
+
"after",
|
|
715
|
+
);
|
|
716
|
+
return getBlocksChangedByTransaction(tr);
|
|
717
|
+
});
|
|
718
|
+
|
|
719
|
+
expect(summarize(changes)).toEqual([{ type: "insert", id: "new-last" }]);
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
it("reports a delete in the middle without touching the blocks it shifts", () => {
|
|
723
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
724
|
+
|
|
725
|
+
const changes = editor.transact((tr) => {
|
|
726
|
+
editor.removeBlocks(["p-100"]);
|
|
727
|
+
return getBlocksChangedByTransaction(tr);
|
|
728
|
+
});
|
|
729
|
+
|
|
730
|
+
expect(summarize(changes)).toEqual([{ type: "delete", id: "p-100" }]);
|
|
731
|
+
});
|
|
732
|
+
|
|
733
|
+
it("reports a single move for a block moved across a large span", () => {
|
|
734
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
735
|
+
|
|
736
|
+
const changes = editor.transact((tr) => {
|
|
737
|
+
const block = editor.getBlock("p-5");
|
|
738
|
+
editor.removeBlocks(["p-5"]);
|
|
739
|
+
editor.insertBlocks([{ ...block }], "p-195", "after");
|
|
740
|
+
return getBlocksChangedByTransaction(tr);
|
|
741
|
+
});
|
|
742
|
+
|
|
743
|
+
expect(summarize(changes)).toEqual([{ type: "move", id: "p-5" }]);
|
|
744
|
+
});
|
|
745
|
+
|
|
746
|
+
it("does not report ancestor blocks when a deeply nested block changes", () => {
|
|
747
|
+
const blocks = makeParagraphs(100);
|
|
748
|
+
blocks[50] = {
|
|
749
|
+
id: "parent",
|
|
750
|
+
type: "paragraph",
|
|
751
|
+
content: "Parent",
|
|
752
|
+
children: [
|
|
753
|
+
{
|
|
754
|
+
id: "child",
|
|
755
|
+
type: "paragraph",
|
|
756
|
+
content: "Child",
|
|
757
|
+
children: [
|
|
758
|
+
{ id: "grandchild", type: "paragraph", content: "Grandchild" },
|
|
759
|
+
],
|
|
760
|
+
},
|
|
761
|
+
],
|
|
762
|
+
};
|
|
763
|
+
editor.replaceBlocks(editor.document, blocks);
|
|
764
|
+
|
|
765
|
+
const changes = editor.transact((tr) => {
|
|
766
|
+
editor.updateBlock("grandchild", { props: { backgroundColor: "red" } });
|
|
767
|
+
return getBlocksChangedByTransaction(tr);
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
expect(summarize(changes)).toEqual([{ type: "update", id: "grandchild" }]);
|
|
771
|
+
});
|
|
772
|
+
|
|
773
|
+
it("returns no changes for a selection-only transaction in a large doc", () => {
|
|
774
|
+
editor.replaceBlocks(editor.document, makeParagraphs(LARGE));
|
|
775
|
+
|
|
776
|
+
const changes = editor.transact((tr) => {
|
|
777
|
+
editor.setTextCursorPosition("p-100", "end");
|
|
778
|
+
return getBlocksChangedByTransaction(tr);
|
|
779
|
+
});
|
|
780
|
+
|
|
781
|
+
expect(changes).toEqual([]);
|
|
782
|
+
});
|
|
783
|
+
});
|
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import type { BlockSchema } from "../schema/index.js";
|
|
12
12
|
import type { InlineContentSchema } from "../schema/inlineContent/types.js";
|
|
13
13
|
import type { StyleSchema } from "../schema/styles/types.js";
|
|
14
|
+
import { getChangedRange } from "./getChangedRange.js";
|
|
14
15
|
import { getNodeId } from "./getBlockInfoFromPos.js";
|
|
15
16
|
import { nodeToBlock } from "./nodeConversions/nodeToBlock.js";
|
|
16
17
|
import { isNodeBlock } from "./nodeUtil.js";
|
|
@@ -20,14 +21,23 @@ import { isNodeBlock } from "./nodeUtil.js";
|
|
|
20
21
|
*
|
|
21
22
|
* High-level algorithm used by getBlocksChangedByTransaction:
|
|
22
23
|
* 1) Merge appended transactions into one document change.
|
|
23
|
-
* 2)
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
24
|
+
* 2) Compute the single range the transaction touched (in both the old and new
|
|
25
|
+
* doc) and only snapshot blocks within it, rather than walking the whole
|
|
26
|
+
* document. getChanges() runs per transaction, so a full-document snapshot
|
|
27
|
+
* made typing in large documents slow: every keystroke re-converted every block.
|
|
28
|
+
* 3) Snapshot blocks before and after within that range (flat map by id, and
|
|
29
|
+
* per-parent child order).
|
|
30
|
+
* 4) Emit inserts/deletes by diffing ids; for shared ids, emit a move (parent
|
|
31
|
+
* changed) or update (block changed, ignoring children).
|
|
32
|
+
* 5) Detect same-parent sibling reorders via an O(n log n) LIS in
|
|
33
|
+
* detectReorderedChildren, marking only items outside the longest ordered
|
|
34
|
+
* subsequence as moved.
|
|
35
|
+
*
|
|
36
|
+
* The range suffices because `changedRange()` spans from the first to the last
|
|
37
|
+
* changed position: any inserted/deleted/moved/updated/reordered block has its
|
|
38
|
+
* relevant positions inside it, and blocks outside are byte-for-byte identical in
|
|
39
|
+
* the same relative order. A moved block's parent contains it, so the parent
|
|
40
|
+
* overlaps the range too (and nodeToBlock converts its full subtree regardless).
|
|
31
41
|
*/
|
|
32
42
|
/**
|
|
33
43
|
* Gets the parent block of a node, if it has one.
|
|
@@ -144,14 +154,19 @@ type BlockSnapshot<
|
|
|
144
154
|
};
|
|
145
155
|
|
|
146
156
|
/**
|
|
147
|
-
*
|
|
148
|
-
*
|
|
157
|
+
* Snapshots blocks and per-parent child order for the block nodes overlapping the
|
|
158
|
+
* given range (uses "__root__" for the root level). Traversing only the range is
|
|
159
|
+
* what keeps this cheap per keystroke: nodeToBlock runs only for blocks that could
|
|
160
|
+
* have changed.
|
|
149
161
|
*/
|
|
150
162
|
function collectSnapshot<
|
|
151
163
|
BSchema extends BlockSchema,
|
|
152
164
|
ISchema extends InlineContentSchema,
|
|
153
165
|
SSchema extends StyleSchema,
|
|
154
|
-
>(
|
|
166
|
+
>(
|
|
167
|
+
doc: Node,
|
|
168
|
+
range: { from: number; to: number },
|
|
169
|
+
): BlockSnapshot<BSchema, ISchema, SSchema> {
|
|
155
170
|
const ROOT_KEY = "__root__";
|
|
156
171
|
const byId: Record<
|
|
157
172
|
string,
|
|
@@ -161,7 +176,12 @@ function collectSnapshot<
|
|
|
161
176
|
}
|
|
162
177
|
> = {};
|
|
163
178
|
const childrenByParent: Record<string, string[]> = {};
|
|
164
|
-
|
|
179
|
+
// Clamp to valid positions; nodesBetween throws on out-of-range ones.
|
|
180
|
+
const from = Math.max(0, Math.min(range.from, doc.content.size));
|
|
181
|
+
const to = Math.max(from, Math.min(range.to, doc.content.size));
|
|
182
|
+
// nodesBetween visits every node overlapping [from, to] in document order,
|
|
183
|
+
// including ancestor blocks that contain the range.
|
|
184
|
+
doc.nodesBetween(from, to, (node, pos) => {
|
|
165
185
|
if (!isNodeBlock(node)) {
|
|
166
186
|
return true;
|
|
167
187
|
}
|
|
@@ -282,11 +302,27 @@ export function getBlocksChangedByTransaction<
|
|
|
282
302
|
...appendedTransactions,
|
|
283
303
|
]);
|
|
284
304
|
|
|
305
|
+
// Changed range in the new doc; null means nothing changed.
|
|
306
|
+
const newRange = getChangedRange(combinedTransaction);
|
|
307
|
+
if (!newRange) {
|
|
308
|
+
return [];
|
|
309
|
+
}
|
|
310
|
+
// Map it back to old-doc coordinates. The -1/+1 biases expand outwards so that
|
|
311
|
+
// for pure inserts/deletes (collapsed new range) the old range still covers the
|
|
312
|
+
// affected span.
|
|
313
|
+
const invertedMapping = combinedTransaction.mapping.invert();
|
|
314
|
+
const oldRange = {
|
|
315
|
+
from: invertedMapping.map(newRange.from, -1),
|
|
316
|
+
to: invertedMapping.map(newRange.to, 1),
|
|
317
|
+
};
|
|
318
|
+
|
|
285
319
|
const prevSnap = collectSnapshot<BSchema, ISchema, SSchema>(
|
|
286
320
|
combinedTransaction.before,
|
|
321
|
+
oldRange,
|
|
287
322
|
);
|
|
288
323
|
const nextSnap = collectSnapshot<BSchema, ISchema, SSchema>(
|
|
289
324
|
combinedTransaction.doc,
|
|
325
|
+
newRange,
|
|
290
326
|
);
|
|
291
327
|
|
|
292
328
|
const changes: BlocksChanged<BSchema, ISchema, SSchema> = [];
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Transform } from "prosemirror-transform";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Like ProseMirror's `Transform.changedRange()`, but also accounts for
|
|
5
|
+
* position-preserving steps whose `StepMap` is empty — `AttrStep` (prop-only
|
|
6
|
+
* updates like a heading's `level`) and mark steps. `changedRange()` and tiptap's
|
|
7
|
+
* `getChangedRanges` both miss `AttrStep`, so anything that scopes work to the
|
|
8
|
+
* changed range would silently ignore prop-only updates.
|
|
9
|
+
*
|
|
10
|
+
* O(steps), like `changedRange()`. Returns null when nothing changed.
|
|
11
|
+
*/
|
|
12
|
+
export function getChangedRange(
|
|
13
|
+
transform: Transform,
|
|
14
|
+
): { from: number; to: number } | null {
|
|
15
|
+
const { mapping, steps } = transform;
|
|
16
|
+
let from = Number.POSITIVE_INFINITY;
|
|
17
|
+
let to = Number.NEGATIVE_INFINITY;
|
|
18
|
+
|
|
19
|
+
for (let i = 0; i < mapping.maps.length; i++) {
|
|
20
|
+
const map = mapping.maps[i];
|
|
21
|
+
// Advance the accumulated range into this step's coordinate space.
|
|
22
|
+
if (i) {
|
|
23
|
+
from = map.map(from, 1);
|
|
24
|
+
to = map.map(to, -1);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
let hadRange = false;
|
|
28
|
+
map.forEach((_oldFrom, _oldTo, newFrom, newTo) => {
|
|
29
|
+
hadRange = true;
|
|
30
|
+
from = Math.min(from, newFrom);
|
|
31
|
+
to = Math.max(to, newTo);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
if (!hadRange) {
|
|
35
|
+
// Position-preserving step: recover the affected position from the step,
|
|
36
|
+
// since its map has no ranges. (DocAttrStep has none and affects no nodes.)
|
|
37
|
+
const step = steps[i] as { pos?: number; from?: number; to?: number };
|
|
38
|
+
if (typeof step.pos === "number") {
|
|
39
|
+
// AttrStep
|
|
40
|
+
from = Math.min(from, step.pos);
|
|
41
|
+
to = Math.max(to, step.pos + 1);
|
|
42
|
+
} else if (typeof step.from === "number" && typeof step.to === "number") {
|
|
43
|
+
// AddMarkStep / RemoveMarkStep
|
|
44
|
+
from = Math.min(from, step.from);
|
|
45
|
+
to = Math.max(to, step.to);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (from === Number.POSITIVE_INFINITY) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
return { from, to };
|
|
54
|
+
}
|
package/src/blocks/index.ts
CHANGED
|
@@ -20,7 +20,6 @@ export * from "./Code/helpers/parse/parsePreCode.js";
|
|
|
20
20
|
export * from "./Code/helpers/render/createCodeBlock.js";
|
|
21
21
|
export * from "./Code/helpers/toExternalHTML/createPreCode.js";
|
|
22
22
|
export * from "./ToggleWrapper/createToggleWrapper.js";
|
|
23
|
-
export * from "./File/helpers/uploadToTmpFilesDotOrg_DEV_ONLY.js";
|
|
24
23
|
export * from "./PageBreak/getPageBreakSlashMenuItems.js";
|
|
25
24
|
|
|
26
25
|
export * from "./BlockNoteSchema.js";
|
|
@@ -144,4 +144,49 @@ describe("Performance: transaction processing scales sub-linearly (#2595)", () =
|
|
|
144
144
|
// Absolute time (~40ms) is comparable to begin (~32ms).
|
|
145
145
|
expect(ratio).toBeLessThan(250);
|
|
146
146
|
});
|
|
147
|
+
|
|
148
|
+
// getChanges() is lazy — it only diffs when a subscriber calls it, so the tests
|
|
149
|
+
// above don't cover getBlocksChangedByTransaction. This locks in that the diff
|
|
150
|
+
// scopes to the changed range, not the whole document.
|
|
151
|
+
it(
|
|
152
|
+
"getChanges() in onChange scales sub-linearly",
|
|
153
|
+
{ timeout: 30_000 },
|
|
154
|
+
() => {
|
|
155
|
+
function measureWithGetChanges(
|
|
156
|
+
editor: BlockNoteEditor<any, any, any>,
|
|
157
|
+
pos: number,
|
|
158
|
+
) {
|
|
159
|
+
// Run the diff every transaction, like an app reading changed blocks per keystroke.
|
|
160
|
+
// eslint-disable-next-line @typescript-eslint/unbound-method -- getChanges is destructured from callback parameter, not a class
|
|
161
|
+
const unsubscribe = editor.onChange((_editor, { getChanges }) => {
|
|
162
|
+
getChanges();
|
|
163
|
+
});
|
|
164
|
+
const avg = measureAvgInsertTime(editor, pos);
|
|
165
|
+
unsubscribe();
|
|
166
|
+
return avg;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const smallEditor = createEditorWithBlocks(SMALL, "paragraph");
|
|
170
|
+
const largeEditor = createEditorWithBlocks(LARGE, "paragraph");
|
|
171
|
+
|
|
172
|
+
const smallAvg = measureWithGetChanges(
|
|
173
|
+
smallEditor,
|
|
174
|
+
smallEditor._tiptapEditor.view.state.doc.content.size - 2,
|
|
175
|
+
);
|
|
176
|
+
const largeAvg = measureWithGetChanges(
|
|
177
|
+
largeEditor,
|
|
178
|
+
largeEditor._tiptapEditor.view.state.doc.content.size - 2,
|
|
179
|
+
);
|
|
180
|
+
const ratio = largeAvg / smallAvg;
|
|
181
|
+
|
|
182
|
+
// eslint-disable-next-line no-console
|
|
183
|
+
console.log(
|
|
184
|
+
`getChanges (end): ${SMALL}=${smallAvg.toFixed(3)}ms, ${LARGE}=${largeAvg.toFixed(3)}ms, ratio=${ratio.toFixed(2)}x`,
|
|
185
|
+
);
|
|
186
|
+
|
|
187
|
+
// The full-document snapshot made getChanges O(blocks) per keystroke, pushing
|
|
188
|
+
// this toward the block-count ratio (~50x); the ranged diff stays well below.
|
|
189
|
+
expect(ratio).toBeLessThan(50);
|
|
190
|
+
},
|
|
191
|
+
);
|
|
147
192
|
});
|