@veltdev/lexical-velt-comments 4.5.2-beta.2 → 4.5.2-beta.3

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.
Files changed (69) hide show
  1. package/cjs/index.js +1 -1
  2. package/cjs/index.js.map +1 -1
  3. package/cjs/types/src/adapters/host/doc.d.ts +97 -0
  4. package/cjs/types/src/adapters/host/marks.d.ts +89 -0
  5. package/cjs/types/src/adapters/host/storage.d.ts +37 -0
  6. package/cjs/types/src/adapters/velt.d.ts +55 -0
  7. package/cjs/types/src/constants/common.d.ts +67 -0
  8. package/cjs/types/src/core/extension.d.ts +40 -0
  9. package/cjs/types/src/core/registry.d.ts +71 -0
  10. package/cjs/types/src/core/state.d.ts +86 -0
  11. package/cjs/types/src/features/addComment.d.ts +63 -0
  12. package/cjs/types/src/features/commentRenderer.d.ts +46 -0
  13. package/cjs/types/src/features/renderComments.d.ts +73 -0
  14. package/cjs/types/src/features/updateContent.d.ts +32 -0
  15. package/cjs/types/src/index.d.ts +26 -0
  16. package/cjs/types/src/types/common.d.ts +72 -0
  17. package/cjs/types/src/types/host.d.ts +65 -0
  18. package/cjs/types/src/types/state.d.ts +28 -0
  19. package/cjs/types/src/types/velt.d.ts +6 -0
  20. package/cjs/types/src/utils/common.d.ts +56 -0
  21. package/cjs/types/src/utils/console.d.ts +37 -0
  22. package/cjs/types/src/utils/host.d.ts +44 -0
  23. package/cjs/types/src/utils/serializer.d.ts +19 -0
  24. package/esm/index.js +1 -1
  25. package/esm/index.js.map +1 -1
  26. package/esm/types/src/adapters/host/doc.d.ts +97 -0
  27. package/esm/types/src/adapters/host/marks.d.ts +89 -0
  28. package/esm/types/src/adapters/host/storage.d.ts +37 -0
  29. package/esm/types/src/adapters/velt.d.ts +55 -0
  30. package/esm/types/src/constants/common.d.ts +67 -0
  31. package/esm/types/src/core/extension.d.ts +40 -0
  32. package/esm/types/src/core/registry.d.ts +71 -0
  33. package/esm/types/src/core/state.d.ts +86 -0
  34. package/esm/types/src/features/addComment.d.ts +63 -0
  35. package/esm/types/src/features/commentRenderer.d.ts +46 -0
  36. package/esm/types/src/features/renderComments.d.ts +73 -0
  37. package/esm/types/src/features/updateContent.d.ts +32 -0
  38. package/esm/types/src/index.d.ts +26 -0
  39. package/esm/types/src/types/common.d.ts +72 -0
  40. package/esm/types/src/types/host.d.ts +65 -0
  41. package/esm/types/src/types/state.d.ts +28 -0
  42. package/esm/types/src/types/velt.d.ts +6 -0
  43. package/esm/types/src/utils/common.d.ts +56 -0
  44. package/esm/types/src/utils/console.d.ts +37 -0
  45. package/esm/types/src/utils/host.d.ts +44 -0
  46. package/esm/types/src/utils/serializer.d.ts +19 -0
  47. package/index.d.ts +275 -26
  48. package/package.json +1 -1
  49. package/tsconfig.tsbuildinfo +1 -0
  50. package/cjs/types/comment-node.d.ts +0 -23
  51. package/cjs/types/constants.d.ts +0 -6
  52. package/cjs/types/editor.d.ts +0 -166
  53. package/cjs/types/index.d.ts +0 -24
  54. package/cjs/types/plugin.d.ts +0 -14
  55. package/cjs/types/serializer.d.ts +0 -5
  56. package/cjs/types/store.d.ts +0 -39
  57. package/cjs/types/types.d.ts +0 -40
  58. package/cjs/types/utility.d.ts +0 -122
  59. package/cjs/types/velt.d.ts +0 -21
  60. package/esm/types/comment-node.d.ts +0 -23
  61. package/esm/types/constants.d.ts +0 -6
  62. package/esm/types/editor.d.ts +0 -166
  63. package/esm/types/index.d.ts +0 -24
  64. package/esm/types/plugin.d.ts +0 -14
  65. package/esm/types/serializer.d.ts +0 -5
  66. package/esm/types/store.d.ts +0 -39
  67. package/esm/types/types.d.ts +0 -40
  68. package/esm/types/utility.d.ts +0 -122
  69. package/esm/types/velt.d.ts +0 -21
package/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var t=require("lexical");const e={EDITOR_ID:"data-editor-id",LOCATION_ID:"data-velt-location-id"};class n extends t.ElementNode{static getType(){return"comment"}static clone(t){return new n(t.__annotationId,t.__multiThreadAnnotationId,t.__key)}constructor(t,e,n){super(n),this.__annotationId=t,this.__multiThreadAnnotationId=e}createDOM(t){const e=document.createElement("velt-comment-text");return this.__annotationId&&e.setAttribute("annotation-id",this.__annotationId),this.__multiThreadAnnotationId&&e.setAttribute("multi-thread-annotation-id",this.__multiThreadAnnotationId),e}updateDOM(t,e,n){return!1}static importJSON(t){return r(t.annotationId,t.multiThreadAnnotationId)}exportJSON(){return{...super.exportJSON(),annotationId:this.__annotationId,multiThreadAnnotationId:this.__multiThreadAnnotationId,type:"comment",version:1}}isInline(){return!0}}function r(t,e){return new n(t,e)}function o(t){return t instanceof n}var i;class a{}i=a,a.selectedCommentsMap=new Map,a.subscribers=new Map,a.isSubscribed=!1,a.getCommentElement=()=>{try{const t=window.Velt;return t?.getCommentElement?t.getCommentElement():null}catch(t){return i.catchError("Error getting comment element:",t),null}},a.addManualComment=({context:t,location:e})=>{try{const n=i.getCommentElement();return n?n.addManualComment({context:t,location:e}):Promise.resolve(null)}catch(t){return i.catchError("Error adding manual comment:",t),Promise.resolve(null)}},a.updateContext=({annotationId:t,context:e})=>{try{const n=i.getCommentElement();return n?n.updateContext(t,e):Promise.resolve(null)}catch(t){i.catchError("Error updating context:",t)}},a.subscribeToSelectedCommentsMap=(t,e)=>{try{i.subscribeToSelectedAnnotationsMapSingleton(),i.subscribers.set(t,e)}catch(t){i.catchError("Error subscribing to selected comments map:",t)}},a.unsubscribeFromSelectedCommentsMap=t=>{try{i.subscribers.delete(t)}catch(t){i.catchError("Error unsubscribing from selected comments map:",t)}},a.catchError=(t,e)=>{try{let n={};e&&"object"==typeof e&&(n={...n,...e}),t&&(n.message=t),n.sdkVersion=window.Velt?.version}catch(t){}},a.subscribeToSelectedAnnotationsMapSingleton=()=>{try{if(i.isSubscribed)return;const t=i.getCommentElement();t&&"function"==typeof t?.getSelectedComments&&(t?.getSelectedComments()?.subscribe(t=>{const e=new Map;t?.forEach(t=>{t?.annotationId&&e.set(t?.annotationId,!0)});((t,e)=>{if(t.size!==e.size)return!1;for(const[n,r]of t)if(e.get(n)!==r)return!1;return!0})(e,i.selectedCommentsMap||new Map)||i.updateSelectedCommentsMap(e)}),i.isSubscribed=!0)}catch(t){return new Map}},a.updateSelectedCommentsMap=t=>{try{i.selectedCommentsMap=t,i.subscribers.forEach(t=>{"function"==typeof t&&t(i.selectedCommentsMap)})}catch(t){i.catchError("Error updating selected comments map:",t)}};class c{static kmpSearch(t,e,n=0,r){try{const o=[];if(!e||!t||e.length>t.length)return o;const i=c.computeKMPTable(e);let a=0,s=0;for(;a<t.length;)if(e[s]===t[a]&&(a++,s++),s===e.length){if(o.push(n+a-s),s=i[s-1],r&&o.length>=r)break}else a<t.length&&e[s]!==t[a]&&(0!==s?s=i[s-1]:a++);return o}catch(t){return[]}}static computeKMPTable(t){try{const e=new Array(t.length).fill(0);let n=0,r=1;for(;r<t.length;)t[r]===t[n]?(n++,e[r]=n,r++):0!==n?n=e[n-1]:(e[r]=0,r++);return e}catch(t){return[]}}static collectTextContent(e){try{const n=[];let r="",o=0;const i=(e,a=0)=>{if(t.$isTextNode(e)){const t=e.getTextContent(),i=o,a=o+t.length;n.push({node:e,start:i,end:a}),r+=t,o+=t.length}else if(t.$isElementNode(e)){const c=e.getChildren(),s=e.getType();for(let t=0;t<c.length;t++)i(c[t],a+1);if("paragraph"===s&&1===a){const i=e.getParent();if(i&&t.$isElementNode(i)){const t=i.getChildren();if(t.indexOf(e)<t.length-1){const t=o,e=o+1;n.push({node:null,start:t,end:e,isParagraphBreak:!0}),r+="\n",o+=1}}}}};return i(e),{combinedText:r,nodeMap:n}}catch(t){return a.catchError("Error collecting text content:",t),{combinedText:"",nodeMap:[]}}}static getTextNodesInRange(t,e,n,r){try{const i=[],{combinedText:a,nodeMap:s}=c.collectTextContent(t);for(const t of s){if(t.isParagraphBreak||!t.node)continue;const a=t.node.getParent();if((!o(a)||!r||a.__annotationId!==r)&&(t.end>e&&t.start<n)){const r=Math.max(0,e-t.start),o=Math.min(t.node.getTextContent().length,n-t.start),a=r>0||o<t.node.getTextContent().length;i.push({node:t.node,startOffset:r,endOffset:o,isPartial:a})}}return i}catch(t){return a.catchError("Error getting text nodes in range:",t),[]}}static isRangeAlreadyWrapped(e,n,r,i){try{let a=0,c=!1;const s=e=>{if(o(e)){if(e.__annotationId===i){const t=e.getTextContent(),o=a,i=a+t.length;if(o<=n&&i>=r)return c=!0,!0}const t=e.getTextContent();a+=t.length}else if(t.$isTextNode(e)){const t=e.getTextContent();a+=t.length}else if(t.$isElementNode(e)){const n=e.getChildren();for(const t of n)if(s(t))return!0;if("paragraph"===e.getType()){const n=e.getParent();if(n&&t.$isElementNode(n)){const t=n.getChildren();t.indexOf(e)<t.length-1&&(a+=1)}}}return!1};return s(e),c}catch(t){return!0}}static findParagraphParent(e){let n=e.getParent();for(;n;){if(t.$isElementNode(n)&&"paragraph"===n.getType())return n;n=n.getParent()}return null}static getContainerTextContent(t,e,n,r){try{let o=-1,i=-1;for(let r=0;r<n.length;r++){const a=n[r];if(!a.isParagraphBreak&&a.node)try{const n=a.node.getKey(),r=e.getElementByKey(n);r&&t.contains(r)&&(-1===o&&(o=a.start),i=a.end)}catch(t){continue}}if(-1===o||-1===i)return null;return{text:r.substring(o,i),startOffset:o}}catch(t){return null}}static findCommonParentWithId(t,e,n){try{const r=100;let o=0;const i=[];let a=t;for(;a&&a!==document.body&&o<r&&n.contains(a);)a.id&&i.push(a),a=a.parentElement,o++;let c=e;for(o=0;c&&c!==document.body&&o<r&&n.contains(c);){if(c.id&&i.includes(c))return c;c=c.parentElement,o++}return null}catch(t){return null}}static findContainerWithId(t,e){try{const n=100;let r=0,o=t;for(;o&&o!==document.body&&r<n&&e.contains(o);){if(o.id)return o;o=o.parentElement,r++}return null}catch(t){return null}}static getSelectionTextRange(e,n){const r=t.$getRoot(),{nodeMap:o}=c.collectTextContent(r),i=n.anchor.getNode(),a=n.focus.getNode(),s=n.anchor.offset,d=n.focus.offset;let l=0,g=0;for(const t of o){if(t.isParagraphBreak||!t.node)continue;const e=t.node.getKey();e===i.getKey()&&(l=t.start+s),e===a.getKey()&&(g=t.start+d)}return{start:Math.min(l,g),end:Math.max(l,g)}}static wrapPartialTextNode(e,n,r,o){try{const i=e.getWritable(),a=i.getTextContent(),c=a.substring(0,n),s=a.substring(n,r),d=a.substring(r),l=t.$createTextNode(s);if(l.setFormat(i.getFormat()),l.setStyle(i.getStyle()),o.append(l),c){const e=t.$createTextNode(c);e.setFormat(i.getFormat()),e.setStyle(i.getStyle()),i.insertBefore(e)}if(i.insertBefore(o),d){const e=t.$createTextNode(d);e.setFormat(i.getFormat()),e.setStyle(i.getStyle()),i.insertBefore(e)}i.remove()}catch(t){}}static wrapEntireTextNode(t,e){try{const n=t.getWritable();e.append(n);const r=n.getParent();if(r){const t=r.getWritable(),o=n.getIndexWithinParent();t.splice(o,1,[e])}}catch(t){}}static wrapMultipleTextNodesWithFormatting(t,e){try{const n=new Map;for(const e of t){const t=c.findParagraphParent(e.node),r=t?t.getKey():"no-paragraph";n.has(r)||n.set(r,[]),n.get(r).push(e)}let o=!0;for(const[,t]of n.entries()){const n=o?e:r(e.__annotationId,e.__multiThreadAnnotationId);if(1===t.length){const e=t[0],{node:r,startOffset:o,endOffset:i,isPartial:a}=e;a?c.wrapPartialTextNode(r,o,i,n):c.wrapEntireTextNode(r,n)}else c.wrapMultipleNodesInSameParagraph(t,n);o=!1}}catch(t){a.catchError("Error in wrapMultipleTextNodesWithFormatting:",t)}}static wrapMultipleNodesInSameParagraph(e,n){try{const r=[...e].sort((t,e)=>t.node.getIndexWithinParent()-e.node.getIndexWithinParent()),o=r[0],i=r[r.length-1],a=o.node.getWritable(),c=a.getParent();if(!c)return;const s=c.getWritable();let d=a.getIndexWithinParent();if(o.isPartial&&o.startOffset>0){const e=o.node.getTextContent().substring(0,o.startOffset),r=o.node.getTextContent().substring(o.startOffset),i=t.$createTextNode(e);i.setFormat(a.getFormat()),i.setStyle(a.getStyle());const c=t.$createTextNode(r);c.setFormat(a.getFormat()),c.setStyle(a.getStyle()),n.append(c),s.splice(d,1,[i,n])}else n.append(a),s.splice(d,1,[n]);for(let t=1;t<r.length-1;t++){const e=r[t].node.getWritable();n.append(e)}if(r.length>1){const e=i.node.getWritable();if(i.isPartial&&i.endOffset<i.node.getTextContent().length){const r=i.node.getTextContent().substring(0,i.endOffset),o=i.node.getTextContent().substring(i.endOffset),a=t.$createTextNode(r);a.setFormat(e.getFormat()),a.setStyle(e.getStyle());const c=t.$createTextNode(o);c.setFormat(e.getFormat()),c.setStyle(e.getStyle()),n.append(a),e.replace(c)}else n.append(e)}}catch(t){a.catchError("Error in wrapMultipleNodesInSameParagraph:",t)}}}class s{constructor(t){this.plugin=t}initializeTransactionListener(t){try{this.editorUpdateListenerRemover&&this.editorUpdateListenerRemover(),this.editorUpdateListenerRemover=t.registerUpdateListener(({editorState:e,prevEditorState:n})=>{try{if(e===n||!this.hasDocumentChanged(e,n))return;this.onTransaction(t)}catch(t){}})}catch(t){a.catchError("Error initializing transaction listener:",t)}}destroyTransactionListener(){try{this.editorUpdateListenerRemover&&(this.editorUpdateListenerRemover(),this.editorUpdateListenerRemover=void 0)}catch(t){a.catchError("Error destroying transaction listener:",t)}}hasDocumentChanged(e,n){try{return e.read(()=>{const e=t.$getRoot().getTextContent();return n.read(()=>{const n=t.$getRoot().getTextContent();return e!==n})})}catch(t){return!0}}onTransaction(t){try{const e=new Map,n=this.collectDocumentAnnotations(t);for(const[r,o]of Array.from(n.entries())){const n=this.processAnnotationChanges(t,o);n&&e.set(r,n)}if(e.size>0){if(!a.getCommentElement())return;this.updateVeltComments(e,t)}}catch(t){a.catchError("Error in onTransaction:",t)}}getCommentNodeTextWithStructure(e){try{let n="";const r=(e,o=0)=>{if(t.$isTextNode(e))n+=e.getTextContent();else if(t.$isElementNode(e)){const i=e.getChildren(),a=e.getType();for(let t=0;t<i.length;t++)r(i[t],o+1);if("paragraph"===a&&o>=0){const r=e.getParent();if(r&&t.$isElementNode(r)){const t=r.getChildren();t.indexOf(e)<t.length-1&&(n+="\n")}}}};return r(e),n}catch(t){return e.getTextContent()}}collectDocumentAnnotations(e){try{const n=new Map,r=this;return e.getEditorState().read(()=>{const e=t.$getRoot();let i=0;const a=e=>{if(o(e)){const t=e.__annotationId;if(!t)return;const o=r.plugin.storeService.annotationStore.get(t);if(!o)return;const a=r.getCommentNodeTextWithStructure(e),c=a.length,s=n.get(t),d={node:{text:a,nodeSize:c},pos:i};s?s.nodes.push(d):n.set(t,{id:t,multiThreadAnnotationId:e.__multiThreadAnnotationId,annotation:o.annotation,nodes:[d],originalText:o.annotation.context?.textEditorConfig?.text||"",originalOccurrence:o.annotation.context?.textEditorConfig?.occurrence||1,targetTextNodeId:o.annotation.context?.textEditorConfig?.targetTextNodeId||""}),i+=c}else if(t.$isTextNode(e))i+=e.getTextContent().length;else if(t.$isElementNode(e)){const t=e.getChildren();for(const e of t)a(e)}};a(e)}),n}catch(t){return a.catchError("Error collecting document annotations:",t),new Map}}processAnnotationChanges(t,e){try{if(!t||!e)throw new Error("Invalid input: editor and data are required");if(!e.originalText||!e.annotation)return null;if(!Array.isArray(e.nodes)||0===e.nodes.length)return null;const{currentText:n,contentChanged:r}=this.detectContentChanges(e.nodes,e.originalText),{targetTextNodeIdChanged:o,newTargetTextNodeId:i,searchResults:a}=this.detectContainerChanges(t,{annotationId:e.id,currentText:n,targetTextNodeId:e.targetTextNodeId,nodes:e.nodes}),c=this.calculateNewOccurrence(t,{searchResults:a,nodes:e.nodes,contentChanged:r,currentText:n,targetTextNodeId:o?i:e.targetTextNodeId,originalOccurrence:e.originalOccurrence}),s=c!==e.originalOccurrence;return r||s||o?this.createAnnotationChange(e,{currentText:n,contentChanged:r,currentOccurrence:c,occurrenceChanged:s,targetTextNodeIdChanged:o,newTargetTextNodeId:i}):null}catch(t){return a.catchError("Error processing annotation changes:",t),null}}detectContentChanges(t,e){const n=[...t].sort((t,e)=>t.pos-e.pos),r=n.length>1&&e.includes("\n")?n.map(t=>t.node.text||"").join("\n"):n.map(t=>t.node.text||"").join("");return{currentText:r,contentChanged:r!==e}}detectContainerChanges(t,e){const{annotationId:n,currentText:r,targetTextNodeId:o,nodes:i}=e;let a=!1,c=o,s=[];const d=this.processContainerChanges(t,{annotationId:n,currentText:r,targetTextNodeId:o,nodes:i});return d?(a=d.changed,c=d.newId,s=d.searchResults):s=o?this.findTextInDomElement(t,r,o,void 0):this.findTextInDocument(t,r,void 0),{targetTextNodeIdChanged:a,newTargetTextNodeId:c,searchResults:s}}processContainerChanges(e,n){const{annotationId:r,currentText:i,targetTextNodeId:a}=n;if(!a)return null;let c=null;if(e.getEditorState().read(()=>{const e=t.$getRoot();let n=0;!function e(i){if(o(i)&&i.__annotationId===r)c=n;else if(t.$isTextNode(i))n+=i.getTextContent().length;else if(t.$isElementNode(i)){const t=i.getChildren();for(const n of t)if(e(n),null!==c)return}}(e)}),null!==c){const t=e.getRootElement();if(!t)return null;if(t.querySelector(`#${a}`)){if(0===this.findTextInDomElement(e,i,a,void 0).length){const t=this.findNewContainer(e,i);if(t&&t.id!==a){const n=this.findTextInDomElement(e,i,t.id,void 0);return{changed:!0,newId:t.id,searchResults:n}}}}}return null}findNewContainer(t,e){const n=t.getRootElement();if(!n)return null;const r=n.querySelectorAll("[id]");for(const t of Array.from(r))if(t.textContent?.includes(e))return t;return null}calculateNewOccurrence(t,e){if(0===e.searchResults.length)return e.originalOccurrence;const n=e.nodes[0],r=e.nodes[e.nodes.length-1],o=n.pos,i=r.pos+(r.node.nodeSize||0);for(let t=0;t<e.searchResults.length;t++){const n=e.searchResults[t];if(n.start<=o&&n.end>=o||n.start<=i&&n.end>=i||o<=n.start&&i>=n.end)return t+1}return e.originalOccurrence}createAnnotationChange(t,e){const{currentText:n,contentChanged:r,currentOccurrence:o,occurrenceChanged:i,targetTextNodeIdChanged:a,newTargetTextNodeId:c}=e;return{annotationId:t.id,multiThreadAnnotationId:t.multiThreadAnnotationId,originalText:t.originalText,currentText:r?n:t.originalText,originalOccurrence:t.originalOccurrence,currentOccurrence:o,originalTargetTextNodeId:t.targetTextNodeId,newTargetTextNodeId:a?c:t.targetTextNodeId,annotation:t.annotation,contentChanged:r,occurrenceChanged:i,targetTextNodeIdChanged:a}}async updateVeltComments(t,e){try{for(const[n,r]of Array.from(t.entries()))try{if(!r.annotation.context?.textEditorConfig)continue;const t=JSON.parse(JSON.stringify(r.annotation.context.textEditorConfig));r.contentChanged&&(t.text=r.currentText),r.occurrenceChanged&&(t.occurrence=r.currentOccurrence),r.targetTextNodeIdChanged&&(t.targetTextNodeId=r.newTargetTextNodeId);const o={...r.annotation.context,textEditorConfig:t};this.plugin.storeService.annotationStore.remove(n),this.removeVeltCommentFromEditor(e,n),await new Promise(t=>setTimeout(t,100)),a.updateContext({annotationId:n,context:o})}catch(t){a.catchError("Error updating individual Velt comment:",t)}}catch(t){a.catchError("Error updating Velt comments:",t)}}getSelectedText(e){return e.getEditorState().read(()=>{const e=t.$getSelection();return t.$isRangeSelection(e)?e.getTextContent():""})}findOccurrenceIndex(e,n,r){try{if(!n.trim())return 1;let o=[],i=0,a=0;e.getEditorState().read(()=>{const s=t.$getSelection();if(t.$isRangeSelection(s)){const t=c.getSelectionTextRange(e,s);i=t.start,a=t.end,o=r&&r.id?this.findTextInContainer(e,n,r.id):this.findTextInEditor(e,n)}});for(let t=0;t<o.length;t++)if(o[t].start===i&&o[t].end===a)return t+1;return 1}catch(t){return a.catchError("Error finding occurrence index:",t),1}}findTextInEditor(e,n){try{const r=[];return e.getEditorState().read(()=>{const e=t.$getRoot(),{combinedText:o}=c.collectTextContent(e),i=c.kmpSearch(o,n);for(const t of i)r.push({start:t,end:t+n.length})}),r}catch(t){return a.catchError("Error finding text in editor:",t),[]}}findTextInContainer(e,n,r){try{const o=[],i=document.getElementById(r);return i?(e.getEditorState().read(()=>{const r=t.$getRoot(),{combinedText:a,nodeMap:s}=c.collectTextContent(r),d=c.getContainerTextContent(i,e,s,a);if(!d)return;const l=c.kmpSearch(d.text,n);for(const t of l)o.push({start:d.startOffset+t,end:d.startOffset+t+n.length})}),o):o}catch(t){return a.catchError("Error finding text in container:",t),[]}}findParentNodeWithId(e){try{return e.getEditorState().read(()=>{const n=t.$getSelection();if(!t.$isRangeSelection(n))return null;const r=n.anchor.getNode(),o=n.focus.getNode(),i=e.getRootElement();if(!i)return null;let a=null,s=null;try{const t=r.getKey();if(a=e.getElementByKey(t),!a){const t=r.getParent()?.getKey();t&&(a=e.getElementByKey(t))}}catch(t){}try{const t=o.getKey();if(s=e.getElementByKey(t),!s){const t=o.getParent()?.getKey();t&&(s=e.getElementByKey(t))}}catch(t){}if(!a&&!s){const t=i.querySelector("p");return c.findContainerWithId(t,i)}const d=a||s,l=s||a;if(!d||!l)return null;if(d===l)return c.findContainerWithId(d,i);let g=c.findCommonParentWithId(d,l,i);if(g){const t=n.getTextContent();if(t.includes("\n")){if("p"===g.tagName.toLowerCase())return null;const e=g.textContent||"",n=t.replace(/\s+/g," ").trim();return e.replace(/\s+/g," ").trim().includes(n)?g:null}return(g.textContent||"").includes(t)?g:null}return null})}catch(t){return a.catchError("Error finding parent node with ID:",t),null}}highlightTextWithVeltComment(e,n,r){try{const{targetTextNodeId:o}=r,i=r?.occurrence||1;if(r.annotationId){const t=this.plugin.storeService.annotationStore.get(r.annotationId);if(t){const n=t.annotation.context?.textEditorConfig,o=r.originalAnnotation?.context?.textEditorConfig;n&&o&&(n.text!==o.text||n.occurrence!==o.occurrence||n.targetTextNodeId!==o.targetTextNodeId)&&this.removeVeltCommentFromEditor(e,r.annotationId)}}if(!n||0===n.length)return;if(o){const t=document.getElementById(o);if(t){const e=t.closest("[data-velt-location-id]")?.getAttribute("data-velt-location-id");if(e!==r.originalAnnotation?.location?.id)return}}let a=[];if(a=o?this.findTextInDomElement(e,n,o,i):this.findTextInDocument(e,n,i),0===a.length)return;const s=a[Math.min(i,a.length)-1];if(s&&r.annotationId){if(e.getEditorState().read(()=>{const e=t.$getRoot();return c.isRangeAlreadyWrapped(e,s.start,s.end,r.annotationId)}))return;this.plugin.storeService.annotationStore.set(r.annotationId,{annotation:r.originalAnnotation||{annotationId:r.annotationId,multiThreadAnnotationId:r.multiThreadAnnotationId,text:n},pluginReference:{node:document.createElement("velt-comment-text"),position:{from:s.start,to:s.end}}}),this.setVeltComment(e,r.annotationId,r.multiThreadAnnotationId,s.start,s.end)}}catch(t){a.catchError("Error highlighting text with Velt comment:",t)}}findTextInDomElement(e,n,r,o){try{const i=[],a=document.getElementById(r);return a?(e.getEditorState().read(()=>{const r=t.$getRoot(),{combinedText:s,nodeMap:d}=c.collectTextContent(r),l=c.getContainerTextContent(a,e,d,s);if(!l)return;const g=c.kmpSearch(l.text,n,0,o);for(const t of g)i.push({start:l.startOffset+t,end:l.startOffset+t+n.length})}),i):i}catch(t){return[]}}findTextInDocument(e,n,r){try{const o=[];return e.getEditorState().read(()=>{const e=t.$getRoot(),{combinedText:i}=c.collectTextContent(e),a=c.kmpSearch(i,n,0,r);for(const t of a)o.push({start:t,end:t+n.length})}),o}catch(t){return a.catchError("Error finding text in document:",t),[]}}setVeltComment(e,n,o,i,s){try{e.update(()=>{const e=t.$getRoot(),a=c.getTextNodesInRange(e,i,s,n);if(0===a.length)return;const d=r(n,o);if(1===a.length){const{node:t,startOffset:e,endOffset:n,isPartial:r}=a[0];r?c.wrapPartialTextNode(t,e,n,d):c.wrapEntireTextNode(t,d)}else c.wrapMultipleTextNodesWithFormatting(a,d)})}catch(t){a.catchError("Error setting Velt comment:",t)}}removeVeltCommentFromEditor(e,n){try{if(!e||!n)throw new Error("Invalid input: editor and annotationId are required");let r=!1;return e.update(()=>{const e=t.$getRoot(),i=[];!function e(r){if(o(r))r.__annotationId===n&&i.push(r);else if(t.$isElementNode(r)){const t=r.getChildren();for(const n of t)e(n)}}(e);for(const e of i)try{const n=e.getWritable(),o=n.getChildren();if(o.length>0){const t=o[0];n.replace(t);let e=t;for(let t=1;t<o.length;t++)e.insertAfter(o[t]),e=o[t]}else{const e=n.getTextContent();if(e){const r=t.$createTextNode(e);n.replace(r)}else n.remove()}r=!0}catch(t){a.catchError("Error removing individual comment node:",t)}}),r&&this.plugin.storeService.annotationStore.remove(n),r}catch(t){return!1}}}s.getEditorId=t=>{try{return t&&t._config?t._config.namespace:null}catch(t){return a.catchError("Error finding editor ID:",t),null}};class d{constructor(t){this.isSubscribed=!1,this.globalStore={editor:null,comments:[],filteredComments:[],selectedCommentsMap:new Map},this.globalAnnotationStore=new Map,this.annotationStore={get:t=>this.globalAnnotationStore.get(t),set:(t,e)=>{this.globalAnnotationStore.set(t,e)},getAll:()=>new Map(this.globalAnnotationStore),clear:()=>{this.globalAnnotationStore.clear()},remove:t=>{this.globalAnnotationStore.delete(t)},hasAnnotationTextChanged:(t,e)=>{try{const n=this.globalAnnotationStore.get(t);if(!n||!e)return!1;const r=n.annotation.text,o=e.context?.textEditorConfig?.text;return r!==o}catch(t){return!1}}},this.updateGlobalStore=t=>{try{const e=t?.comments||this.globalStore?.comments||[],n=t?.selectedCommentsMap||this.globalStore?.selectedCommentsMap||new Map,r=this.globalStore?.filteredComments||[],o=e.filter(t=>"terminal"!==t?.status?.type||n?.get(t?.annotationId)),i=new Set(o.map(t=>t?.annotationId));r.map(t=>t?.annotationId).filter(t=>t&&!i.has(t)).forEach(t=>{this.globalStore?.editor&&t&&this.plugin.editorService.removeVeltCommentFromEditor(this.globalStore?.editor,t)}),this.globalStore={...this.globalStore,...t,filteredComments:o},this.highlightCommentsFromGlobalStore()}catch(t){a.catchError("Error updating global store:",t)}},this.highlightCommentsFromGlobalStore=()=>{try{const{editor:t,filteredComments:e}=this.globalStore;if(!t||!e)return;for(const n of e){const e=n?.context?.textEditorConfig?.text,r=n?.context?.textEditorConfig?.occurrence;e&&this.plugin.editorService.highlightTextWithVeltComment(t,e,{annotationId:n?.annotationId,multiThreadAnnotationId:n?.multiThreadAnnotationId,occurrence:r,targetTextNodeId:n?.context?.textEditorConfig?.targetTextNodeId,originalAnnotation:n})}}catch(t){a.catchError("Error highlighting comments from global store:",t)}},this.plugin=t;try{a.subscribeToSelectedCommentsMap(this.plugin.editorId,t=>{try{this.updateGlobalStore({selectedCommentsMap:t})}catch(t){a.catchError("Error updating global store:",t)}})}catch(t){a.catchError("Error subscribing to selected comments map:",t)}}}d.storeInstanceMap=new Map;const l=new Map;class g{constructor(t,e){this.editorId=t,this.editor=e,this.editorService=new s(this),e&&this.editorService.initializeTransactionListener(e),this.storeService=new d(this)}static getInstance(t){let{editorId:e,editor:n}=t||{};return e||(e="default"),l.has(e)||l.set(e,new g(e,n)),l.get(e)}}const u=n.getType();function h(t){const e=[];for(const n of t)if(n.type!==u)e.push(m(n));else if(p(n)){const t=h(n.children);e.push(...t)}return e}function m(t){if(p(t)){const e=h(t.children);return{...t,children:e}}return t}function f(t){if(p(t)){const e=t.children.map(f);return{...t,children:x(e)}}return t}function x(t){if(t.length<2)return t;const e=[];let n=0;for(;n<t.length;){const r=t[n];if(T(r)){let o=r.text??"",i=n+1;for(;i<t.length;){const e=t[i];if(!T(e)||!C(r,e))break;o+=e.text??"",i++}e.push({...r,text:o}),n=i}else e.push(r),n++}return e}function p(t){return Object.prototype.hasOwnProperty.call(t,"children")}function T(t){return"text"===t.type}function C(t,e){return t.format===e.format&&t.style===e.style&&t.mode===e.mode&&t.detail===e.detail}const E=async({editorId:t,editor:n,context:r})=>{try{const o=a.getCommentElement();if(!o)return;await new Promise(t=>setTimeout(t,500)),t||(t=s.getEditorId(n)??void 0);const i=g.getInstance({editorId:t,editor:n}),c=i.editorService.getSelectedText(n);if(!c)return;const d=i.editorService.findParentNodeWithId(n);let l,u;d&&(l=d.id,u=d.closest(`[${e.LOCATION_ID}]`)?.getAttribute(e.LOCATION_ID));const h=i.editorService.findOccurrenceIndex(n,c,d);if(!h)return;let m,f={};r&&"object"==typeof r&&(f={...f,...r}),f.textEditorConfig={text:c,occurrence:h,targetTextNodeId:l},t&&(f.textEditorConfig.editorId=t),u&&(m={id:u}),o?.addManualComment({context:f,location:m})?.then(t=>{})}catch(t){a.catchError("Error adding lexical-velt-comments",t)}};const I=({editor:t,editorId:e,commentAnnotations:n})=>{try{if(t){if(e||(e=s.getEditorId(t)??void 0),!Array.isArray(n))return;n=JSON.parse(JSON.stringify(n));const r=n?.filter(t=>!!t.context?.textEditorConfig&&t.context?.textEditorConfig?.editorId===e)||[];g.getInstance({editorId:e,editor:t}).storeService.updateGlobalStore({editor:t,comments:r}),a.subscribeToSelectedAnnotationsMapSingleton()}}catch(t){a.catchError("Error highlighting lexical-velt-comments",t)}};exports.$createCommentNode=r,exports.$isCommentNode=o,exports.CommentNode=n,exports.addComment=E,exports.exportJSONWithoutComments=function(t){const e=t.getEditorState();return e.read(()=>({root:function(t){const e=t.children.map(f);return{...t,children:x(e)}}(function(t){const e=h(t.children);return{...t,children:e}}(e.toJSON().root))}))},exports.highlightComments=function(t,e,n){try{I({editor:t,editorId:n,commentAnnotations:e})}catch(t){a.catchError("Error highlighting lexical-velt-comments",t)}},exports.renderComments=I,exports.triggerAddComment=async(t,e)=>{try{return E({editor:t,context:e?.context})}catch(t){a.catchError("Error triggering add comment",t)}};
1
+ "use strict";var t=require("lexical");const e={ATTRIBUTES:{EDITOR_ID:"data-editor-id",LOCATION_ID:"data-velt-location-id",ANNOTATION_ID:"annotation-id",MULTI_THREAD_ANNOTATION_ID:"multi-thread-annotation-id"},MARK_NAME:"lexicalVeltComments",STORAGE_KEY:"lexicalVeltComments",TAG_NAME:"velt-comment-text",DEFAULT_EXTENSION_NAME:"VeltComments",NODE_TYPE:"comment",DEFAULT_EDITOR_ID:"__default__",STATUS_TERMINAL:"terminal",LOG_PREFIX:"LexicalVeltComments: ",DEBUG_MODE_KEY:"debugMode",FORCE_DEBUG_MODE_KEY:"forceDebugMode",BLOCK_TYPES:["paragraph","heading","listitem","quote","code"]};class n{static showLogs(){try{return!!sessionStorage.getItem(e.DEBUG_MODE_KEY)||!!sessionStorage.getItem(e.FORCE_DEBUG_MODE_KEY)}catch(t){return n.catch("Error in showLogs: ",t),!1}}}n.log=n.showLogs()?console.log:()=>{},n.warn=n.showLogs()?console.warn:()=>{},n.error=n.showLogs()?console.error:()=>{},n.debug=n.showLogs()?console.debug:()=>{},n.info=n.showLogs()?console.info:()=>{},n.logsEnabled=!0,n.catch=(t,o)=>{try{n.logsEnabled&&(void 0!==o?console.warn(e.LOG_PREFIX,t,o):console.warn(e.LOG_PREFIX,t))}catch(t){}};const o=(t,e,n=0,o)=>{try{const a=[];if(!e||!t||e.length>t.length)return a;const c=r(e);let i=0,s=0;for(;i<t.length;)if(e[s]===t[i]&&(i++,s++),s===e.length){if(a.push(n+i-s),s=c[s-1],o&&a.length>=o)break}else i<t.length&&e[s]!==t[i]&&(0!==s?s=c[s-1]:i++);return a}catch(t){return[]}},r=t=>{try{const e=new Array(t.length).fill(0);let n=0,o=1;for(;o<t.length;)t[o]===t[n]?(n++,e[o]=n,o++):0!==n?n=e[n-1]:(e[o]=0,o++);return e}catch(t){return[]}},a=o=>{try{const n=[];let r="",a=0;const c=(o,i=0)=>{if(t.$isTextNode(o)){const t=o.getTextContent(),e=a,c=a+t.length;n.push({node:o,start:e,end:c}),r+=t,a+=t.length}else if(t.$isElementNode(o)){const s=o.getChildren(),d=o.getType();for(let t=0;t<s.length;t++)c(s[t],i+1);if(e.BLOCK_TYPES.includes(d)&&1===i){const e=o.getParent();if(e&&t.$isElementNode(e)){const t=e.getChildren();if(t.indexOf(o)<t.length-1){const t=a,e=a+1;n.push({node:null,start:t,end:e,isParagraphBreak:!0}),r+="\n",a+=1}}}}};return c(o),{combinedText:r,nodeMap:n}}catch(t){return n.catch("Error collecting text content",t),{combinedText:"",nodeMap:[]}}},c=(t,e,n,o)=>{try{let r=-1,a=-1;for(let o=0;o<n.length;o++){const c=n[o];if(!c.isParagraphBreak&&c.node)try{const n=c.node.getKey(),o=e.getElementByKey(n);o&&t.contains(o)&&(-1===r&&(r=c.start),a=c.end)}catch(t){continue}}if(-1===r||-1===a)return null;return{text:o.substring(r,a),startOffset:r}}catch(t){return null}};class i extends t.ElementNode{static getType(){return e.NODE_TYPE}static clone(t){return new i(t.__annotationId,t.__multiThreadAnnotationId,t.__key)}constructor(t,e,n){super(n),this.__annotationId=t,this.__multiThreadAnnotationId=e}createDOM(t){const n=document.createElement(e.TAG_NAME);return this.__annotationId&&n.setAttribute(e.ATTRIBUTES.ANNOTATION_ID,this.__annotationId),this.__multiThreadAnnotationId&&n.setAttribute(e.ATTRIBUTES.MULTI_THREAD_ANNOTATION_ID,this.__multiThreadAnnotationId),n}updateDOM(t,e,n){return!1}static importJSON(t){return s(t.annotationId,t.multiThreadAnnotationId)}exportJSON(){return{...super.exportJSON(),annotationId:this.__annotationId,multiThreadAnnotationId:this.__multiThreadAnnotationId,type:e.NODE_TYPE,version:1}}isInline(){return!0}}const s=(t,e)=>new i(t,e),d=t=>t instanceof i,l=(e,n,o,r)=>{try{let a=0,c=!1;const i=e=>{if(d(e)){if(e.__annotationId===r){const t=e.getTextContent(),r=a,i=a+t.length;if(r<=n&&i>=o)return c=!0,!0}const t=e.getTextContent();a+=t.length}else if(t.$isTextNode(e)){const t=e.getTextContent();a+=t.length}else if(t.$isElementNode(e)){const n=e.getChildren();for(const t of n)if(i(t))return!0;if("paragraph"===e.getType()){const n=e.getParent();if(n&&t.$isElementNode(n)){const t=n.getChildren();t.indexOf(e)<t.length-1&&(a+=1)}}}return!1};return i(e),c}catch(t){return!0}},g=(t,e,o,r)=>{try{const n=[],{combinedText:c,nodeMap:i}=a(t);for(const t of i){if(t.isParagraphBreak||!t.node)continue;const a=t.node.getParent();if((!d(a)||!r||a.__annotationId!==r)&&(t.end>e&&t.start<o)){const r=Math.max(0,e-t.start),a=Math.min(t.node.getTextContent().length,o-t.start),c=r>0||a<t.node.getTextContent().length;n.push({node:t.node,startOffset:r,endOffset:a,isPartial:c})}}return n}catch(t){return n.catch("Error getting text nodes in range",t),[]}},u=e=>{const n=["paragraph","heading","listitem","quote","code"];let o=e.getParent();for(;o;){if(t.$isElementNode(o)){const t=o.getType();if(n.includes(t))return o;const e=o.getParent();if(e&&"root"===e.getType())return o}o=o.getParent()}return null},h=(e,o,r,a)=>{try{const n=e.getTextContent(),c=e.getFormat(),i=e.getStyle(),s=e.getParent(),d=e.getIndexWithinParent();if(!s)return;const l=n.substring(0,o),g=n.substring(o,r),u=n.substring(r),h=t.$createTextNode(g);h.setFormat(c),h.setStyle(i),a.append(h);const f=[];if(l){const e=t.$createTextNode(l);e.setFormat(c),e.setStyle(i),f.push(e)}if(f.push(a),u){const e=t.$createTextNode(u);e.setFormat(c),e.setStyle(i),f.push(e)}s.getWritable().splice(d,1,f)}catch(t){n.catch("Error in wrapPartialTextNode",t)}},f=(t,e)=>{try{const o=t.getParent(),r=t.getIndexWithinParent();if(!o)return void n.warn("[wrapEntireTextNode] No parent found for text node");o.getWritable().splice(r,1,[e]);const a=t.getWritable();e.append(a)}catch(t){n.catch("[wrapEntireTextNode] Error",t)}},m=(t,e)=>{const o=`[wrapMultipleTextNodesWithFormatting][${e.__annotationId}]`;try{const n=new Map;for(const e of t){const t=u(e.node),o=t?t.getKey():"no-paragraph";n.has(o)||n.set(o,[]),n.get(o).push(e)}let o=!0,r=0;for(const[t,a]of n.entries()){const t=o?e:s(e.__annotationId,e.__multiThreadAnnotationId);if(1===a.length){const e=a[0],{node:n,startOffset:o,endOffset:r,isPartial:c}=e;c?h(n,o,r,t):f(n,t)}else p(a,t);o=!1,r++}}catch(t){n.catch(`${o} Error in wrapMultipleTextNodesWithFormatting`,t)}},p=(e,o)=>{const r=`[wrapMultipleNodesInSameParagraph][${o.__annotationId}]`;try{const a=[...e].sort((t,e)=>t.node.getIndexWithinParent()-e.node.getIndexWithinParent()),c=a[0],i=a[a.length-1],s=c.node.getParent(),d=c.node.getIndexWithinParent();if(!s)return;const l=s.getChildrenSize();if(d<0||d>=l)return void n.warn(`${r} Invalid index ${d} for parent with ${l} children`);const g=c.node.getWritable(),u=s.getWritable(),h=d;if(c.isPartial&&c.startOffset>0){const e=c.node.getTextContent().substring(0,c.startOffset),a=c.node.getTextContent().substring(c.startOffset),i=t.$createTextNode(e);i.setFormat(g.getFormat()),i.setStyle(g.getStyle());const s=t.$createTextNode(a);s.setFormat(g.getFormat()),s.setStyle(g.getStyle()),o.append(s);const d=u.getChildrenSize();if(h+1>d)return void n.warn(`${r} Cannot splice: index ${h} + 1 > size ${d}`);u.splice(h,1,[i,o])}else{const t=u.getChildrenSize();if(h+1>t)return void n.warn(`${r} Cannot splice: index ${h} + 1 > size ${t}`);u.splice(h,1,[o]),o.append(g)}for(let t=1;t<a.length-1;t++){const e=a[t].node.getWritable();o.append(e)}if(a.length>1){const e=i.node.getWritable();if(i.isPartial&&i.endOffset<i.node.getTextContent().length){const n=i.node.getTextContent().substring(0,i.endOffset),r=i.node.getTextContent().substring(i.endOffset),a=t.$createTextNode(n);a.setFormat(e.getFormat()),a.setStyle(e.getStyle());const c=t.$createTextNode(r);c.setFormat(e.getFormat()),c.setStyle(e.getStyle()),o.append(a),e.replace(c)}else o.append(e)}}catch(t){n.catch("Error in wrapMultipleNodesInSameParagraph",t)}},T=(e,r)=>{try{const n=[],c=r.context?.textEditorConfig?.text;return c?(e.getEditorState().read(()=>{const e=t.$getRoot(),{combinedText:r}=a(e),i=o(r,c);for(const t of i)n.push({start:t,end:t+c.length})}),n):n}catch(t){return n.catch("Error finding text matches",t),[]}},x=(e,r)=>{try{for(const i of r){const r=`[applyAnnotationMarks][${i.annotationId}]`,d=i.context?.textEditorConfig?.text;if(!d||0===d.length)continue;const u=i.context?.textEditorConfig?.occurrence||1,p=i.context?.textEditorConfig?.targetTextNodeId;let x=[];if(p){const n=document.getElementById(p);n&&e.getEditorState().read(()=>{const r=t.$getRoot(),{combinedText:i,nodeMap:s}=a(r),l=c(n,e,s,i);if(l){const t=o(l.text,d,0,u);x=t.map(t=>({start:l.startOffset+t,end:l.startOffset+t+d.length}))}})}else x=T(e,i);if(0===x.length)continue;const I=Math.min(u,x.length),E=x[I-1];if(!E)continue;if(!e.getEditorState().read(()=>{const e=t.$getRoot();return l(e,E.start,E.end,i.annotationId)}))try{e.update(()=>{const e=t.$getRoot();t.$getSelection()&&t.$setSelection(null);const n=g(e,E.start,E.end,i.annotationId);if(0===n.length)return;const o=s(i.annotationId,i.multiThreadAnnotationId);if(1===n.length){const{node:t,startOffset:e,endOffset:r,isPartial:a}=n[0];a?h(t,e,r,o):f(t,o)}else m(n,o)},{discrete:!0})}catch(t){throw n.catch(`${r} Error in editor.update`,t),t}}}catch(t){n.catch("Error applying annotation marks",t)}},I=o=>{const r="[getCurrentSelectionContext]";try{return o.getEditorState().read(()=>{const c=t.$getSelection();if(!t.$isRangeSelection(c))return null;const i=c.getTextContent();if(!i.trim())return null;const s=((e,n)=>{const o=t.$getRoot(),{nodeMap:r}=a(o),c=n.anchor.getNode(),i=n.focus.getNode(),s=n.anchor.offset,d=n.focus.offset;let l=0,g=0;for(const t of r){if(t.isParagraphBreak||!t.node)continue;const e=t.node.getKey();e===c.getKey()&&(l=t.start+s),e===i.getKey()&&(g=t.start+d)}return{start:Math.min(l,g),end:Math.max(l,g)}})(0,c);c.anchor.getNode(),c.focus.getNode();let d,l;try{const t=o.getRootElement();if(t){const n=c.anchor.key,r=o.getElementByKey(n);if(r){let n=r;const o=100;let a=0;for(;n&&n!==document.body&&a<o&&t.contains(n);){if(n.id){d=n.id;break}n=n.parentElement,a++}if(d){const t=r.closest(`[${e.ATTRIBUTES.LOCATION_ID}]`);l=t?.getAttribute(e.ATTRIBUTES.LOCATION_ID)||void 0}}}}catch(t){n.catch(`${r} Error finding targetTextNodeId or locationId`,t)}let g=1;try{const t=E(o,i);for(const e of t)if(e.start===s.start&&e.end===s.end){g=e.occurrence;break}if(1===g&&t.length>0)for(const e of t)if(s.start>=e.start&&s.end<=e.end){g=e.occurrence;break}}catch(t){n.catch(`${r} Error calculating occurrence`,t)}return{text:i,from:s.start,to:s.end,occurrence:g,targetTextNodeId:d,locationId:l}})}catch(t){return n.catch(`${r} Error getting selection context`,t),null}},E=(e,r)=>{try{const n=[];return e.getEditorState().read(()=>{const e=t.$getRoot(),{combinedText:c}=a(e),i=o(c,r);for(let t=0;t<i.length;t++){const e=i[t];n.push({start:e,end:e+r.length,occurrence:t+1})}}),n}catch(t){return n.catch("Error finding occurrences by text",t),[]}},y=(e,o)=>{const r="[subscribeToDocumentChanges]";try{let a="";e.getEditorState().read(()=>{a=t.$getRoot().getTextContent()});return e.registerUpdateListener(({editorState:e,prevEditorState:c})=>{const i=`${r}[updateListener]`;try{if(e===c)return;const r=((e,o)=>{try{return e.read(()=>{const e=t.$getRoot().getTextContent();return o.read(()=>{const n=t.$getRoot().getTextContent();return e!==n})})}catch(t){return n.catch("[hasDocumentChanged] Error comparing editor states",t),!0}})(e,c);if(!r)return;e.read(()=>{const e=t.$getRoot().getTextContent(),n={type:"replace",from:0,to:a.length,insertedText:e,deletedText:a};o(n),a=e})}catch(t){n.catch(`${i} Error in document change listener`,t)}})}catch(t){return n.catch(`${r} Error subscribing to document changes`,t),()=>{}}},_=(e,n)=>{const{annotationId:r,currentText:i,targetTextNodeId:s}=n;let d=!1,l=s,g=[];if(s){const n=document.getElementById(s);if(n&&(e.getEditorState().read(()=>{const r=t.$getRoot(),{combinedText:s,nodeMap:d}=a(r),l=c(n,e,d,s);if(l){const t=o(l.text,i);for(const e of t)g.push({start:l.startOffset+e,end:l.startOffset+e+i.length})}}),0===g.length)){const n=N(e,i);n&&n.id!==s&&(d=!0,l=n.id,e.getEditorState().read(()=>{const r=t.$getRoot(),{combinedText:s,nodeMap:d}=a(r),l=c(n,e,d,s);if(l){const t=o(l.text,i);for(const e of t)g.push({start:l.startOffset+e,end:l.startOffset+e+i.length})}}))}}return 0===g.length&&e.getEditorState().read(()=>{const e=t.$getRoot(),{combinedText:n}=a(e),r=o(n,i);for(const t of r)g.push({start:t,end:t+i.length})}),{targetTextNodeIdChanged:d,newTargetTextNodeId:l,searchResults:g}},N=(t,e)=>{const n=t.getRootElement();if(!n)return null;const o=n.querySelectorAll("[id]");for(const t of Array.from(o))if(t.textContent?.includes(e))return t;return null},$=(t,e)=>{if(0===e.searchResults.length)return e.originalOccurrence;const n=e.nodes[0],o=e.nodes[e.nodes.length-1],r=n.pos,a=o.pos+(o.node.nodeSize||0);for(let t=0;t<e.searchResults.length;t++){const n=e.searchResults[t];if(n.start<=r&&n.end>=r||n.start<=a&&n.end>=a||r<=n.start&&a>=n.end)return t+1}return e.originalOccurrence};let A=!1,C=new Map;const O=new Map,S=()=>{try{const t=window.Velt;return t?.getCommentElement?t.getCommentElement():null}catch(t){return n.catch("Error getting Velt comment element",t),null}},w=(t,e)=>{try{const o=S();if(!o)return void n.warn("Velt SDK not available, cannot update annotation context");o.updateContext(t,e)}catch(t){n.catch("Error updating annotation context",t)}},b=new Map,D=t=>{const e={annotations:new Map,commentAnnotations:[],selectedAnnotations:new Set,editorId:t};return b.set(t,e),e},R=t=>{let e=b.get(t);return e||(e=D(t)),e},M=(t,e)=>{try{const n=R(t);n.commentAnnotations=e,n.annotations.clear();for(const t of e){if(!t?.annotationId)continue;const e={annotationId:t.annotationId,multiThreadAnnotationId:t.multiThreadAnnotationId,context:t.context};n.annotations.set(t.annotationId,e)}}catch(t){n.catch("[updateAnnotations] Error updating annotations",t)}},v=(t,e)=>{try{const n=b.get(t);if(!n)return null;return n.annotations.get(e)||null}catch(t){return n.catch("[getAnnotation] Error getting annotation",t),null}},P=new Map,F=(t,o,r)=>{let a=t;a||(a=(t=>{try{if(!t)return null;if(t._config?.namespace)return t._config.namespace;const n=t.getRootElement();if(n){const t=n.closest(`[${e.ATTRIBUTES.EDITOR_ID}]`)?.getAttribute(e.ATTRIBUTES.EDITOR_ID);if(t)return t}return null}catch(t){return n.catch("Error finding editor ID",t),null}})(o)||e.DEFAULT_EDITOR_ID);const c=(t=>P.get(t)||null)(a);return c||((t,n,o)=>{const r=t||e.DEFAULT_EDITOR_ID;D(r);const a={editorId:r,editor:n,config:o||{}};return P.set(r,a),a})(a,o,r)},L=(e,o,r)=>{const a="[handleContentUpdate]";try{const r=((e,o)=>{const r="[detectDocumentChanges]",a=new Map;try{const c=new Map;let i=0;e.getEditorState().read(()=>{const e=t.$getRoot();let o=0;const a=e=>{if(d(e)){i++;const t=e.__annotationId;if(!t)return void n.warn(`${r}[traverse] CommentNode found but no annotationId`);const a=e.getTextContent(),s=a.length,d={node:{text:a,nodeSize:s},pos:o},l=c.get(t);l?l.nodes.push(d):c.set(t,{id:t,multiThreadAnnotationId:e.__multiThreadAnnotationId,nodes:[d]}),o+=s}else if(t.$isTextNode(e))o+=e.getTextContent().length;else if(t.$isElementNode(e)){const t=e.getChildren();for(const e of t)a(e)}};a(e)});for(const[t,i]of Array.from(c.entries())){const c=`${r}[${t}]`,s=o(t);if(!s){n.warn(`${c} No stored data found, skipping`);continue}const d=[...i.nodes].sort((t,e)=>t.pos-e.pos).map(t=>t.node.text||"").join(""),l=d!==s.originalText,g=_(e,{annotationId:i.id,currentText:d,targetTextNodeId:s.targetTextNodeId,nodes:i.nodes}),u=g.targetTextNodeIdChanged,h=g.newTargetTextNodeId,f=g.searchResults,m=$(e,{searchResults:f,nodes:i.nodes,contentChanged:l,currentText:d,targetTextNodeId:u?h:s.targetTextNodeId,originalOccurrence:s.originalOccurrence}),p=m!==s.originalOccurrence;if(l||p||u){const e={annotationId:i.id,multiThreadAnnotationId:i.multiThreadAnnotationId,originalText:s.originalText,currentText:l?d:s.originalText,originalOccurrence:s.originalOccurrence,currentOccurrence:m,originalTargetTextNodeId:s.targetTextNodeId,newTargetTextNodeId:u?h:s.targetTextNodeId,annotation:s.annotation,contentChanged:l,occurrenceChanged:p,targetTextNodeIdChanged:u};a.set(t,e)}}}catch(t){n.catch(`${r} Error detecting document changes`,t)}return a})(o,t=>{const o=v(e,t);if(!o)return n.warn(`${a} Annotation not found in state: ${t}`),null;const r=o.context?.textEditorConfig;return{annotation:o,originalText:r?.text||"",originalOccurrence:r?.occurrence||1,targetTextNodeId:r?.targetTextNodeId||""}});if(0===r.size)return;for(const[t,o]of Array.from(r.entries())){const r=`${a}[${t}]`,c=v(e,t);if(!c){n.warn(`${r} Annotation not found in state, skipping`);continue}if(!c.context?.textEditorConfig){n.warn(`${r} No textEditorConfig, skipping`);continue}const i=JSON.parse(JSON.stringify(c.context.textEditorConfig));o.contentChanged&&(i.text=o.currentText),o.occurrenceChanged&&(i.occurrence=o.currentOccurrence),o.targetTextNodeIdChanged&&(i.targetTextNodeId=o.newTargetTextNodeId);const s={...c.context,textEditorConfig:i};w(t,s)}}catch(t){n.catch("Error handling content update",t)}},k=new Map,U=(t,o)=>{try{const e=F(t,o).editorId;return((t,e)=>{if(k.has(t))return!0;try{const n=y(e,()=>{L(t,e)});return k.set(t,n),!0}catch(t){return n.catch("[ensureDocumentChangeListeners] Error setting up document change listeners",t),!1}})(e,o),{editorId:e}}catch(o){return n.catch("[ensureEditorSetup] Error setting up editor",o),{editorId:t||e.DEFAULT_EDITOR_ID}}};const B=new Map,K=(t,e)=>{const o=(t=>{try{const e=b.get(t);return e?new Map(e.annotations):new Map}catch(t){return n.catch("Error getting all annotations",t),new Map}})(t),r=new Map;for(const[t,e]of o)r.set(t,e);const a=[];for(const t of e){if(!t.annotationId)continue;const e=r.get(t.annotationId);e?a.push(e):a.push({annotationId:t.annotationId,multiThreadAnnotationId:t.multiThreadAnnotationId,context:t.context})}return a},W=(o,r,a)=>{try{const c=B.get(o);c?c.editor=r:B.set(o,{editor:r,previousFilteredAnnotations:[]});const i=(t=>{try{const e=b.get(t);return e?new Set(e.selectedAnnotations):new Set}catch(t){return n.catch("Error getting selected annotations",t),new Set}})(o),s=((t,n)=>t.filter(t=>t?.status?.type!==e.STATUS_TERMINAL||n.has(t.annotationId)))(a,i),l=B.get(o)?.previousFilteredAnnotations||[],g=new Set(s.map(t=>t.annotationId).filter(Boolean)),u=new Set(l.map(t=>t.annotationId).filter(Boolean)),h=Array.from(u).filter(t=>!g.has(t));h.length>0&&((e,o)=>{try{e.update(()=>{const e=t.$getRoot();t.$getSelection()&&t.$setSelection(null);const r=[];!function e(n){if(d(n))n.__annotationId&&o.includes(n.__annotationId)&&r.push(n);else if(t.$isElementNode(n)){const t=n.getChildren();for(const n of t)e(n)}}(e);for(const e of r)try{const n=e.getWritable(),o=n.getChildren();if(o.length>0){const t=o[0];n.replace(t);let e=t;for(let t=1;t<o.length;t++)e.insertAfter(o[t]),e=o[t]}else{const e=n.getTextContent();if(e){const o=t.$createTextNode(e);n.replace(o)}else n.remove()}}catch(t){n.catch("Error removing individual comment mark",t)}},{discrete:!0})}catch(t){n.catch("Error removing annotation marks",t)}})(r,h);const f=B.get(o);f&&(f.previousFilteredAnnotations=s);const m=K(o,s);m.length>0&&x(r,m)}catch(t){n.catch("[commentRenderer:updateComments] Error updating comments",t)}},V=(t,e)=>{const o="[commentRenderer:updateSelection]";try{const e=B.get(t);if(!e||!e.editor)return void n.warn(`${o} No editor found for editorId: ${t}`);const r=(t=>{try{const e=b.get(t);return e?.commentAnnotations||[]}catch(t){return n.catch("Error getting comment annotations",t),[]}})(t);W(t,e.editor,r)}catch(t){n.catch(`${o} Error updating selection`,t)}},Y=new Map,G=e.NODE_TYPE,z=t=>{const e=J(t.children);return{...t,children:e}},J=t=>{const e=[];for(const n of t)if(n.type!==G)e.push(q(n));else if(Q(n)){const t=J(n.children);e.push(...t)}return e},q=t=>{if(Q(t)){const e=J(t.children);return{...t,children:e}}return t},X=t=>{const e=t.children.map(j);return{...t,children:H(e)}},j=t=>{if(Q(t)){const e=t.children.map(j);return{...t,children:H(e)}}return t},H=t=>{if(t.length<2)return t;const e=[];let n=0;for(;n<t.length;){const o=t[n];if(Z(o)){let r=o.text??"",a=n+1;for(;a<t.length;){const e=t[a];if(!Z(e)||!tt(o,e))break;r+=e.text??"",a++}e.push({...o,text:r}),n=a}else e.push(o),n++}return e},Q=t=>Object.prototype.hasOwnProperty.call(t,"children"),Z=t=>"text"===t.type,tt=(t,e)=>t.format===e.format&&t.style===e.style&&t.mode===e.mode&&t.detail===e.detail;exports.CommentNode=i,exports.addComment=async function({editorId:o,editor:r,context:c}){const i="[addComment]";if(r)try{if(!S())return void n.warn(`${i} Velt SDK not available, cannot add comment`);const s=I(r);if(!s)return void n.warn(`${i} No valid selection found, exiting`);const{editorId:d}=U(o,r),l=void 0!==o||d!==e.DEFAULT_EDITOR_ID,g={...c,textEditorConfig:{text:s.text,occurrence:s.occurrence,...l&&{editorId:d},targetTextNodeId:s.targetTextNodeId}};let u;s.locationId&&(u={id:s.locationId});const h=await(t=>{const e="[addVeltComment]";try{const o=S();return o?o.addManualComment({context:t.context,location:t.location}).then(t=>t?.annotation?{annotation:t.annotation,result:t}:(n.warn(`${e} No annotation in result`),{annotation:null,result:t})).catch(t=>(n.catch(`${e} Error adding Velt comment`,t),{annotation:null,result:null})):(n.warn(`${e} Velt SDK not available, cannot add comment`),Promise.resolve({annotation:null,result:null}))}catch(t){return n.catch(`${e} Exception adding Velt comment`,t),Promise.resolve({annotation:null,result:null})}})({context:g,location:u}),f=h.annotation;if(!f)return void n.warn(`${i} Failed to create comment via Velt SDK`);(()=>{try{return!0}catch(t){return n.catch("[shouldApplyMark] Error checking persistVeltMarks, defaulting to true",t),!0}})(0,e.STORAGE_KEY)&&f.annotationId&&((e,o,r,c,i,s=1)=>{const d="[applyAnnotationMark]";try{if(!e||!o)return!1;if(c>=i)return n.warn(`${d} Invalid position range: from must be less than to`),!1;const l=e;let g="";try{l.getEditorState().read(()=>{const e=t.$getRoot(),{combinedText:n}=a(e);g=n.substring(c,i)})}catch(t){return n.catch(`${d} Could not extract text from positions, mark may not apply correctly`,t),!1}return g&&0!==g.trim().length?(x(l,[{annotationId:o,multiThreadAnnotationId:r,context:{textEditorConfig:{text:g,occurrence:s,editorId:""}},position:{from:c,to:i}}]),!0):(n.warn(`${d} No text found at positions ${c}-${i}`),!1)}catch(t){return n.catch(`${d} Error applying annotation mark`,t),!1}})(r,f.annotationId,f.multiThreadAnnotationId,s.from,s.to,s.occurrence),f.annotationId?M(d,[f]):n.warn(`${i} No annotationId, skipping state update`),(t=>{const e="[resetEditorSelection]";try{const o=t;o?.focus?o.focus():n.warn(`${e} Editor focus API not available`)}catch(t){n.catch(`${e} Error resetting selection`,t)}})(r)}catch(t){n.catch(`${i} Error adding comment`,t)}else n.catch(`${i} ERROR: No editor provided`)},exports.exportJSONWithoutComments=t=>{const e=t.getEditorState();return e.read(()=>{const t=e.toJSON(),n=z(t.root);return{root:X(n)}})},exports.renderComments=({editor:t,editorId:o,commentAnnotations:r})=>{const a="[renderComments]";try{if(!t)return void n.warn(`${a} No editor provided`);r&&Array.isArray(r)||(r=[]);const{editorId:c}=U(o,t),i=JSON.parse(JSON.stringify(r)).filter(t=>{if(!t?.context?.textEditorConfig)return!1;const n=t.context.textEditorConfig.editorId;return c===e.DEFAULT_EDITOR_ID?void 0===n||n===e.DEFAULT_EDITOR_ID:n===c});if(M(c,i),!Y.has(c)){const t=c,e=((t,e)=>{try{const o=e||`subscriber-${Date.now()}-${Math.random()}`;if(!A){const t=S();t&&"function"==typeof t.getSelectedComments&&(t.getSelectedComments().subscribe(t=>{const e=new Map;if(t?.forEach(t=>{t?.annotationId&&e.set(t.annotationId,!0)}),!((t,e)=>{if(t.size!==e.size)return!1;for(const[n,o]of Array.from(t))if(e.get(n)!==o)return!1;return!0})(e,C)){C=e;const t=new Set;for(const[e]of Array.from(C))t.add(e);O.forEach(e=>{if("function"==typeof e)try{e(t)}catch(t){n.catch("Error in selected annotations subscriber",t)}})}}),A=!0)}return O.set(o,t),()=>{O.delete(o)}}catch(t){return n.catch("Error subscribing to selected annotations",t),()=>{}}})(e=>{((t,e)=>{try{R(t).selectedAnnotations=new Set(e)}catch(t){n.catch("Error setting selected annotations",t)}})(t,e),V(t)},t);Y.set(c,e)}W(c,t,i)}catch(t){n.catch(`${a} Error rendering comments`,t)}};
2
2
  //# sourceMappingURL=index.js.map