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

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/cjs/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var t,e=require("lexical");class n extends e.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}class i{}t=i,i.selectedCommentsMap=new Map,i.subscribers=new Map,i.isSubscribed=!1,i.getCommentElement=()=>{try{const t=window.Velt;return t?.getCommentElement?t.getCommentElement():null}catch(e){return t.catchError("Error getting comment element:",e),null}},i.addManualComment=({context:e,location:n})=>{try{const r=t.getCommentElement();return r?r.addManualComment({context:e,location:n}):Promise.resolve(null)}catch(e){return t.catchError("Error adding manual comment:",e),Promise.resolve(null)}},i.updateContext=({annotationId:e,context:n})=>{try{const r=t.getCommentElement();return r?r.updateContext(e,n):Promise.resolve(null)}catch(e){t.catchError("Error updating context:",e)}},i.subscribeToSelectedCommentsMap=(e,n)=>{try{t.subscribeToSelectedAnnotationsMapSingleton(),t.subscribers.set(e,n)}catch(e){t.catchError("Error subscribing to selected comments map:",e)}},i.unsubscribeFromSelectedCommentsMap=e=>{try{t.subscribers.delete(e)}catch(e){t.catchError("Error unsubscribing from selected comments map:",e)}},i.catchError=(t,e)=>{try{let n={};e&&"object"==typeof e&&(n={...n,...e}),t&&(n.message=t),n.sdkVersion=window.Velt?.version}catch(t){}},i.subscribeToSelectedAnnotationsMapSingleton=()=>{try{if(t.isSubscribed)return;const e=t.getCommentElement();e&&"function"==typeof e?.getSelectedComments&&(e?.getSelectedComments()?.subscribe(e=>{const n=new Map;e?.forEach(t=>{t?.annotationId&&n.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})(n,t.selectedCommentsMap||new Map)||t.updateSelectedCommentsMap(n)}),t.isSubscribed=!0)}catch(t){return new Map}},i.updateSelectedCommentsMap=e=>{try{t.selectedCommentsMap=e,t.subscribers.forEach(e=>{"function"==typeof e&&e(t.selectedCommentsMap)})}catch(e){t.catchError("Error updating selected comments map:",e)}};class a{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){i.catchError("Error initializing transaction listener:",t)}}destroyTransactionListener(){try{this.editorUpdateListenerRemover&&(this.editorUpdateListenerRemover(),this.editorUpdateListenerRemover=void 0)}catch(t){i.catchError("Error destroying transaction listener:",t)}}hasDocumentChanged(t,n){try{return t.read(()=>{const t=e.$getRoot().getTextContent();return n.read(()=>{const n=e.$getRoot().getTextContent();return t!==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){const n=i.getCommentElement();if(!n)return;this.updateVeltComments(n,e,t)}}catch(t){i.catchError("Error in onTransaction:",t)}}getCommentNodeTextWithStructure(t){try{let n="";const r=(t,o=0)=>{if(e.$isTextNode(t))n+=t.getTextContent();else if(e.$isElementNode(t)){const i=t.getChildren(),a=t.getType();for(let t=0;t<i.length;t++)r(i[t],o+1);if("paragraph"===a&&o>=0){const r=t.getParent();if(r&&e.$isElementNode(r)){const e=r.getChildren();e.indexOf(t)<e.length-1&&(n+="\n")}}}};return r(t),n}catch(e){return t.getTextContent()}}collectDocumentAnnotations(t){try{const n=new Map,r=this;return t.getEditorState().read(()=>{const t=e.$getRoot();let i=0;const a=t=>{if(o(t)){const e=t.__annotationId;if(!e)return;const o=r.plugin.storeService.annotationStore.get(e);if(!o)return;const a=r.getCommentNodeTextWithStructure(t),c=a.length,s=n.get(e),d={node:{text:a,nodeSize:c},pos:i};s?s.nodes.push(d):n.set(e,{id:e,multiThreadAnnotationId:t.__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(e.$isTextNode(t))i+=t.getTextContent().length;else if(e.$isElementNode(t)){const e=t.getChildren();for(const t of e)a(t)}};a(t)}),n}catch(t){return i.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 i.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(t,n){const{annotationId:r,currentText:i,targetTextNodeId:a}=n;if(!a)return null;let c=null;if(t.getEditorState().read(()=>{const t=e.$getRoot();let n=0;!function t(i){if(o(i)&&i.__annotationId===r)c=n;else if(e.$isTextNode(i))n+=i.getTextContent().length;else if(e.$isElementNode(i)){const e=i.getChildren();for(const n of e)if(t(n),null!==c)return}}(t)}),null!==c){const e=t.getRootElement();if(!e)return null;if(e.querySelector(`#${a}`)){if(0===this.findTextInDomElement(t,i,a,void 0).length){const e=this.findNewContainer(t,i);if(e&&e.id!==a){const n=this.findTextInDomElement(t,i,e.id,void 0);return{changed:!0,newId:e.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,n){try{for(const[t,r]of Array.from(e.entries()))try{if(!r.annotation.context?.textEditorConfig)continue;const e=JSON.parse(JSON.stringify(r.annotation.context.textEditorConfig));r.contentChanged&&(e.text=r.currentText),r.occurrenceChanged&&(e.occurrence=r.currentOccurrence),r.targetTextNodeIdChanged&&(e.targetTextNodeId=r.newTargetTextNodeId);const o={...r.annotation.context,textEditorConfig:e};this.plugin.storeService.annotationStore.remove(t),this.removeVeltCommentFromEditor(n,t),await new Promise(t=>setTimeout(t,100)),i.updateContext({annotationId:t,context:o})}catch(t){i.catchError("Error updating individual Velt comment:",t)}}catch(t){i.catchError("Error updating Velt comments:",t)}}getSelectedText(t){return t.getEditorState().read(()=>{const t=e.$getSelection();return e.$isRangeSelection(t)?t.getTextContent():""})}findOccurrenceIndex(t,n,r){try{if(!n.trim())return 1;let o=[],i=0,a=0;t.getEditorState().read(()=>{const c=e.$getSelection();if(e.$isRangeSelection(c)){const e=this.getSelectionTextRange(t,c);i=e.start,a=e.end,o=r&&r.id?this.findTextInContainer(t,n,r.id):this.findTextInEditor(t,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 i.catchError("Error finding occurrence index:",t),1}}getSelectionTextRange(t,n){const r=e.$getRoot(),{nodeMap:o}=this.collectTextContent(r),i=n.anchor.getNode(),a=n.focus.getNode(),c=n.anchor.offset,s=n.focus.offset;let d=0,l=0;for(const t of o){if(t.isParagraphBreak||!t.node)continue;const e=t.node.getKey();e===i.getKey()&&(d=t.start+c),e===a.getKey()&&(l=t.start+s)}return{start:Math.min(d,l),end:Math.max(d,l)}}collectTextContent(t){try{const n=[];let r="",o=0;const i=(t,a=0)=>{if(e.$isTextNode(t)){const e=t.getTextContent(),i=o,a=o+e.length;n.push({node:t,start:i,end:a}),r+=e,o+=e.length}else if(e.$isElementNode(t)){const c=t.getChildren(),s=t.getType();for(let t=0;t<c.length;t++)i(c[t],a+1);if("paragraph"===s&&1===a){const i=t.getParent();if(i&&e.$isElementNode(i)){const e=i.getChildren();if(e.indexOf(t)<e.length-1){const t=o,e=o+1;n.push({node:null,start:t,end:e,isParagraphBreak:!0}),r+="\n",o+=1}}}}};return i(t),{combinedText:r,nodeMap:n}}catch(t){return i.catchError("Error collecting text content:",t),{combinedText:"",nodeMap:[]}}}findTextInEditor(t,n){try{const r=[];return t.getEditorState().read(()=>{const t=e.$getRoot(),{combinedText:o}=this.collectTextContent(t),i=this.kmpSearch(o,n);for(const t of i)r.push({start:t,end:t+n.length})}),r}catch(t){return i.catchError("Error finding text in editor:",t),[]}}findTextInContainer(t,n,r){try{const o=[],i=document.getElementById(r);return i?(t.getEditorState().read(()=>{const r=e.$getRoot(),{combinedText:a,nodeMap:c}=this.collectTextContent(r),s=this.getContainerTextContent(i,t,c,a);if(!s)return;const d=this.kmpSearch(s.text,n);for(const t of d)o.push({start:s.startOffset+t,end:s.startOffset+t+n.length})}),o):o}catch(t){return i.catchError("Error finding text in container:",t),[]}}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}}filterNodesInContainer(t,e,n){try{const r=[];for(const o of t)try{const t=o.node.getKey(),i=n.getElementByKey(t);i&&e.contains(i)&&r.push(o)}catch(t){continue}return r}catch(t){return[]}}collectTextNodes(t){try{const n=[];let r=0;const o=t=>{if(e.$isTextNode(t)){const e=t.getTextContent();n.push({node:t,text:e,textOffset:r}),r+=e.length}else if(e.$isElementNode(t)){const e=t.getChildren();for(const t of e)o(t)}};return o(t),n}catch(t){return[]}}getTextNodesInRange(t,e,n,r){try{const i=[],{combinedText:a,nodeMap:c}=this.collectTextContent(t);for(const t of c){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 i.catchError("Error getting text nodes in range:",t),[]}}isRangeAlreadyWrapped(t,n,r,i){try{let a=0,c=!1;const s=t=>{if(o(t)){if(t.__annotationId===i){const e=t.getTextContent(),o=a,i=a+e.length;if(o<=n&&i>=r)return c=!0,!0}const e=t.getTextContent();a+=e.length}else if(e.$isTextNode(t)){const e=t.getTextContent();a+=e.length}else if(e.$isElementNode(t)){const n=t.getChildren();for(const t of n)if(s(t))return!0;if("paragraph"===t.getType()){const n=t.getParent();if(n&&e.$isElementNode(n)){const e=n.getChildren();e.indexOf(t)<e.length-1&&(a+=1)}}}return!1};return s(t),c}catch(t){return!0}}collectTextNodesInRange(t,n){try{const r=[];let o=0;const i=t=>{const a=o;if(e.$isTextNode(t)){const e=t.getTextContent(),i=o+e.length;i>=n.start&&a<=n.end&&r.push({node:t,text:e,start:o,end:i}),o=i}else if(e.$isElementNode(t)){const e=t.getChildren();for(const t of e)i(t)}};return i(t),r}catch(t){return[]}}getContainerRange(t,e){try{const n=t.getRootElement();if(!n||!n.contains(e))return null;const r=e.textContent||"",o=(n.textContent||"").indexOf(r);return-1===o?null:{start:o,end:o+r.length}}catch(t){return i.catchError("Error getting container range:",t),null}}kmpSearch(t,e,n=0,r){try{const o=[];if(!e||!t||e.length>t.length)return o;const i=this.computeKMPTable(e);let a=0,c=0;for(;a<t.length;)if(e[c]===t[a]&&(a++,c++),c===e.length){if(o.push(n+a-c),c=i[c-1],r&&o.length>=r)break}else a<t.length&&e[c]!==t[a]&&(0!==c?c=i[c-1]:a++);return o}catch(t){return[]}}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[]}}findParentContainerWithId(t,e){try{const n=t.anchor.getNode(),r=e.getElementByKey(n.getKey());if(!r)return null;let o=r;for(;o&&o!==document.body;){if(o.id)return o;o=o.parentElement}return null}catch(t){return null}}highlightTextWithVeltComment(t,n,r){try{const{targetTextNodeId:o}=r,i=r?.occurrence||1;if(r.annotationId){const e=this.plugin.storeService.annotationStore.get(r.annotationId);if(e){const n=e.annotation.context?.textEditorConfig,o=r.originalAnnotation?.context?.textEditorConfig;n&&o&&(n.text!==o.text||n.occurrence!==o.occurrence||n.targetTextNodeId!==o.targetTextNodeId)&&this.removeVeltCommentFromEditor(t,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(t,n,o,i):this.findTextInDocument(t,n,i),0===a.length)return;const c=a[Math.min(i,a.length)-1];if(c&&r.annotationId){if(t.getEditorState().read(()=>{const t=e.$getRoot();return this.isRangeAlreadyWrapped(t,c.start,c.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:c.start,to:c.end}}}),this.setVeltComment(t,r.annotationId,r.multiThreadAnnotationId,c.start,c.end)}}catch(t){i.catchError("Error highlighting text with Velt comment:",t)}}findTextInDomElement(t,n,r,o){try{const i=[],a=document.getElementById(r);return a?(t.getEditorState().read(()=>{const r=e.$getRoot(),c=this.filterNodesInContainer(this.collectTextNodes(r),a,t);if(0===c.length)return;const s=c[0].textOffset,d=c.map(t=>t.text).join(""),l=this.kmpSearch(d,n,0,o);for(const t of l)i.push({start:s+t,end:s+t+n.length})}),i):i}catch(t){return[]}}findTextInDocument(t,n,r){try{const o=[];return t.getEditorState().read(()=>{const t=e.$getRoot(),{combinedText:i}=this.collectTextContent(t),a=this.kmpSearch(i,n,0,r);for(const t of a)o.push({start:t,end:t+n.length})}),o}catch(t){return i.catchError("Error finding text in document:",t),[]}}setVeltComment(t,n,o,a,c){try{t.update(()=>{const t=e.$getRoot();t.selectStart();const i=this.getTextNodesInRange(t,a,c,n);if(0===i.length)return;const s=r(n,o);if(1===i.length){const{node:t,startOffset:e,endOffset:n,isPartial:r}=i[0];r?this.wrapPartialTextNode(t,e,n,s):this.wrapEntireTextNode(t,s)}else this.wrapMultipleTextNodesWithFormatting(i,s)})}catch(t){i.catchError("Error setting Velt comment:",t)}}wrapPartialTextNode(t,n,r,o){try{const i=t.getWritable(),a=i.getTextContent(),c=a.substring(0,n),s=a.substring(n,r),d=a.substring(r),l=e.$createTextNode(s);if(l.setFormat(i.getFormat()),l.setStyle(i.getStyle()),o.append(l),c){const t=e.$createTextNode(c);t.setFormat(i.getFormat()),t.setStyle(i.getStyle()),i.insertBefore(t)}if(i.insertBefore(o),d){const t=e.$createTextNode(d);t.setFormat(i.getFormat()),t.setStyle(i.getStyle()),i.insertBefore(t)}i.remove()}catch(t){}}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){}}wrapMultipleTextNodesWithFormatting(t,e){try{const n=new Map;for(const e of t){const t=this.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?this.wrapPartialTextNode(r,o,i,n):this.wrapEntireTextNode(r,n)}else this.wrapMultipleNodesInSameParagraph(t,n);o=!1}}catch(t){i.catchError("Error in wrapMultipleTextNodesWithFormatting:",t)}}findParagraphParent(t){let n=t.getParent();for(;n;){if(e.$isElementNode(n)&&"paragraph"===n.getType())return n;n=n.getParent()}return null}wrapMultipleNodesInSameParagraph(t,n){try{const r=[...t].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 t=o.node.getTextContent().substring(0,o.startOffset),r=o.node.getTextContent().substring(o.startOffset),i=e.$createTextNode(t);i.setFormat(a.getFormat()),i.setStyle(a.getStyle());const c=e.$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 t=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=e.$createTextNode(r);a.setFormat(t.getFormat()),a.setStyle(t.getStyle());const c=e.$createTextNode(o);c.setFormat(t.getFormat()),c.setStyle(t.getStyle()),n.append(a),t.replace(c)}else n.append(t)}}catch(t){i.catchError("Error in wrapMultipleNodesInSameParagraph:",t)}}removeVeltCommentFromEditor(t,n){try{if(!t||!n)throw new Error("Invalid input: editor and annotationId are required");let r=!1;return t.update(()=>{const t=e.$getRoot(),a=[];!function t(r){if(o(r))r.__annotationId===n&&a.push(r);else if(e.$isElementNode(r)){const e=r.getChildren();for(const n of e)t(n)}}(t);for(const t of a)try{const n=t.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 t=n.getTextContent();if(t){const r=e.$createTextNode(t);n.replace(r)}else n.remove()}r=!0}catch(t){i.catchError("Error removing individual comment node:",t)}}),r&&this.plugin.storeService.annotationStore.remove(n),r}catch(t){return!1}}}a.getEditorId=t=>{try{return t&&t._config?t._config.namespace:null}catch(t){return i.catchError("Error finding editor ID:",t),null}};class c{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){i.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){i.catchError("Error highlighting comments from global store:",t)}},this.plugin=t;try{i.subscribeToSelectedCommentsMap(this.plugin.editorId,t=>{try{this.updateGlobalStore({selectedCommentsMap:t})}catch(t){i.catchError("Error updating global store:",t)}})}catch(t){i.catchError("Error subscribing to selected comments map:",t)}}}c.storeInstanceMap=new Map;const s=new Map;class d{constructor(t,e){this.editorId=t,this.editor=e,this.editorService=new a(this),e&&this.editorService.initializeTransactionListener(e),this.storeService=new c(this)}static getInstance(t){let{editorId:e,editor:n}=t||{};return e||(e="default"),s.has(e)||s.set(e,new d(e,n)),s.get(e)}}function l(t){const n=function(t){const n=t._createEditorArgs,r={namespace:`shadow-editor-${Date.now()}`,nodes:n?.nodes||[],theme:{},onError:t=>{},editable:!1};return e.createEditor(r)}(t);try{const r=t.getEditorState();n.setEditorState(r),n.update(()=>{!function(t){const n=[];function r(t){if(o(t))n.push(t);else if(e.$isElementNode(t)){t.getChildren().forEach(r)}}r(t),n.forEach(t=>{try{const e=t.getParent();if(!e)return;const n=t.getChildren(),r=t.getIndexWithinParent();t.remove(),n.length>0&&e.splice(r,0,n)}catch(t){}}),t.markDirty()}(e.$getRoot())},{discrete:!0});const i=n.getEditorState().toJSON();return JSON.stringify(i)}catch(e){return function(t){return t.getEditorState().read(()=>{const e=h(g(t.getEditorState().toJSON()));return JSON.stringify(e)})}(t)}}function g(t){if(!t||"object"!=typeof t)return t;if(Array.isArray(t)){const e=[];for(const n of t)if(n&&"comment"===n.type){if(n.children&&Array.isArray(n.children))for(const t of n.children)e.push(g(t))}else e.push(g(n));return e}const e={...t};if("comment"===e.type)return e.children&&Array.isArray(e.children)?e.children.map(t=>g(t)):null;for(const[t,n]of Object.entries(e))("children"===t&&Array.isArray(n)||"object"==typeof n&&null!==n)&&(e[t]=g(n));return e}function h(t){if(!t||"object"!=typeof t)return t;if(Array.isArray(t))return t.map(t=>h(t));const e={...t};if(e.children&&Array.isArray(e.children)){const t=e.children.map(t=>h(t));e.children=function(t){if(!Array.isArray(t)||t.length<=1)return t;const e=[];let n=0;for(;n<t.length;){const r=t[n];if(r&&"text"===r.type){let o=r.text||"",i=n+1;for(;i<t.length;){const e=t[i];if(!e||"text"!==e.type||!u(r,e))break;o+=e.text||"",i++}e.push({...r,text:o}),n=i}else e.push(r),n++}return e}(t)}for(const[t,n]of Object.entries(e))"children"!==t&&"object"==typeof n&&null!==n&&(e[t]=h(n));return e}function u(t,e){return t.format===e.format&&t.style===e.style&&t.mode===e.mode&&t.detail===e.detail}const m=async({editorId:t,editor:e,context:n})=>{try{const r=i.getCommentElement();if(!r)return;await new Promise(t=>setTimeout(t,500)),t||(t=a.getEditorId(e)??void 0);const o=d.getInstance({editorId:t,editor:e}),c=o.editorService.getSelectedText(e);if(!c)return;let s;const l=o.editorService.findOccurrenceIndex(e,c,null);if(!l)return;let g,h={};n&&"object"==typeof n&&(h={...h,...n}),h.textEditorConfig={text:c,occurrence:l,targetTextNodeId:s},t&&(h.textEditorConfig.editorId=t),r?.addManualComment({context:h,location:g})?.then(t=>{})}catch(t){i.catchError("Error adding lexical-velt-comments",t)}};const f=({editor:t,editorId:e,commentAnnotations:n})=>{try{if(t){if(e||(e=a.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)||[];d.getInstance({editorId:e,editor:t}).storeService.updateGlobalStore({editor:t,comments:r}),i.subscribeToSelectedAnnotationsMapSingleton()}}catch(t){i.catchError("Error highlighting lexical-velt-comments",t)}};exports.$createCommentNode=r,exports.$isCommentNode=o,exports.CommentNode=n,exports.addComment=m,exports.deserializeCleanState=function(t,n){try{const e=JSON.parse(n);t.setEditorState(t.parseEditorState(e))}catch(n){t.update(()=>{e.$getRoot().clear()})}},exports.exportCleanEditorContent=t=>{try{return l(t)}catch(n){return t.getEditorState().read(()=>{const t=e.$getRoot();return JSON.stringify({root:{children:[{children:[{detail:0,format:0,mode:"normal",style:"",text:t.getTextContent(),type:"text",version:1}],direction:"ltr",format:"",indent:0,type:"paragraph",version:1,textFormat:0,textStyle:""}],direction:"ltr",format:"",indent:0,type:"root",version:1}})})}},exports.highlightComments=function(t,e,n){try{f({editor:t,editorId:n,commentAnnotations:e})}catch(t){i.catchError("Error highlighting lexical-velt-comments",t)}},exports.renderComments=f,exports.triggerAddComment=async(t,e)=>{try{return m({editor:t,context:e?.context})}catch(t){i.catchError("Error triggering add comment",t)}};
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)}};
2
2
  //# sourceMappingURL=index.js.map