@veltdev/slate-velt-comments-staging 1.0.4 → 1.0.5

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 (62) hide show
  1. package/cjs/index.js +1 -1
  2. package/cjs/index.js.map +1 -1
  3. package/cjs/types/adapters/host/doc.d.ts +86 -0
  4. package/cjs/types/adapters/host/marks.d.ts +51 -0
  5. package/cjs/types/adapters/host/storage.d.ts +38 -0
  6. package/cjs/types/adapters/velt.d.ts +50 -0
  7. package/cjs/types/constants/common.d.ts +58 -0
  8. package/cjs/types/core/ExtensionComponent.d.ts +13 -0
  9. package/cjs/types/core/extension.d.ts +54 -0
  10. package/cjs/types/core/registry.d.ts +52 -0
  11. package/cjs/types/core/state.d.ts +80 -0
  12. package/cjs/types/features/addComment.d.ts +63 -0
  13. package/cjs/types/features/commentRenderer.d.ts +46 -0
  14. package/cjs/types/features/renderComments.d.ts +73 -0
  15. package/cjs/types/features/updateContent.d.ts +25 -0
  16. package/cjs/types/index.d.ts +14 -34
  17. package/cjs/types/types/common.d.ts +54 -0
  18. package/cjs/types/types/host.d.ts +65 -0
  19. package/cjs/types/types/state.d.ts +28 -0
  20. package/cjs/types/types/velt.d.ts +23 -0
  21. package/cjs/types/utils/common.d.ts +80 -0
  22. package/cjs/types/utils/console.d.ts +25 -0
  23. package/cjs/types/utils/serializer.d.ts +20 -0
  24. package/esm/index.js +1 -1
  25. package/esm/index.js.map +1 -1
  26. package/esm/types/adapters/host/doc.d.ts +86 -0
  27. package/esm/types/adapters/host/marks.d.ts +51 -0
  28. package/esm/types/adapters/host/storage.d.ts +38 -0
  29. package/esm/types/adapters/velt.d.ts +50 -0
  30. package/esm/types/constants/common.d.ts +58 -0
  31. package/esm/types/core/ExtensionComponent.d.ts +13 -0
  32. package/esm/types/core/extension.d.ts +54 -0
  33. package/esm/types/core/registry.d.ts +52 -0
  34. package/esm/types/core/state.d.ts +80 -0
  35. package/esm/types/features/addComment.d.ts +63 -0
  36. package/esm/types/features/commentRenderer.d.ts +46 -0
  37. package/esm/types/features/renderComments.d.ts +73 -0
  38. package/esm/types/features/updateContent.d.ts +25 -0
  39. package/esm/types/index.d.ts +14 -34
  40. package/esm/types/types/common.d.ts +54 -0
  41. package/esm/types/types/host.d.ts +65 -0
  42. package/esm/types/types/state.d.ts +28 -0
  43. package/esm/types/types/velt.d.ts +23 -0
  44. package/esm/types/utils/common.d.ts +80 -0
  45. package/esm/types/utils/console.d.ts +25 -0
  46. package/esm/types/utils/serializer.d.ts +20 -0
  47. package/index.d.ts +268 -34
  48. package/package.json +1 -1
  49. package/cjs/types/SlateVeltComment.d.ts +0 -6
  50. package/cjs/types/constants.d.ts +0 -9
  51. package/cjs/types/editor.d.ts +0 -72
  52. package/cjs/types/plugin.d.ts +0 -17
  53. package/cjs/types/store.d.ts +0 -36
  54. package/cjs/types/types.d.ts +0 -14
  55. package/cjs/types/velt.d.ts +0 -21
  56. package/esm/types/SlateVeltComment.d.ts +0 -6
  57. package/esm/types/constants.d.ts +0 -9
  58. package/esm/types/editor.d.ts +0 -72
  59. package/esm/types/plugin.d.ts +0 -17
  60. package/esm/types/store.d.ts +0 -36
  61. package/esm/types/types.d.ts +0 -14
  62. package/esm/types/velt.d.ts +0 -21
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Update Content feature module.
3
+ * Handles document changes and annotation context updates.
4
+ *
5
+ * Responsibilities:
6
+ * - Detect document changes via doc adapter
7
+ * - Process each change: contentChanged, occurrenceChanged, targetTextNodeIdChanged
8
+ * - Update annotation contexts in Velt SDK
9
+ * - Update marks/nodes via marks adapter
10
+ *
11
+ * Architectural Rules:
12
+ * - NO direct editor or Velt imports (uses adapters)
13
+ * - Orchestrates: doc adapter → velt adapter → marks adapter
14
+ * - All functions use ES6 arrow functions
15
+ * - All imports use path aliases (@/)
16
+ */
17
+ /**
18
+ * Handles content updates when document changes occur.
19
+ * Detects annotation changes and updates Velt contexts accordingly.
20
+ *
21
+ * @param editorId Unique identifier for the editor
22
+ * @param editor The editor instance
23
+ * @param transaction The transaction object
24
+ */
25
+ export declare const handleContentUpdate: (editorId: string, editor: unknown, transaction: unknown) => void;
@@ -1,36 +1,16 @@
1
- import type { CommentAnnotation } from '@veltdev/types';
2
- import type { Editor } from 'slate';
3
- export { SlateVeltComment } from './SlateVeltComment';
4
- export * from './types';
5
- export interface VeltCommentsEditor extends Editor {
6
- }
7
- export interface VeltCommentsEditorOptions {
8
- HistoryEditor?: any;
9
- }
10
- export declare const withVeltComments: <T extends Editor>(editor: T, options?: VeltCommentsEditorOptions) => T & VeltCommentsEditor;
11
- export interface VeltCommentConfig {
12
- context?: unknown;
13
- }
14
- export declare const triggerAddComment: (editor: Editor, config?: VeltCommentConfig) => Promise<void>;
15
- export interface AddCommentRequest {
16
- editorId?: string;
17
- editor: Editor;
18
- context?: unknown;
19
- }
20
1
  /**
21
- * Creates a comment annotation for the currently selected text in the editor
22
- * This function handles the entire flow from getting the selected text to creating
23
- * the actual comment through the Velt service
2
+ * Public API for Editor-Velt Comments integration.
3
+ *
4
+ * This module exports the public API for the v2 implementation.
5
+ * All internal imports use path aliases (@/) for clean dependency management.
6
+ *
7
+ * @module EditorVeltComments
24
8
  */
25
- export declare const addComment: ({ editorId, editor, context: clientContext, }: AddCommentRequest) => Promise<void>;
26
- export declare function highlightComments(editor: Editor, commentAnnotations: CommentAnnotation[], editorId?: string): void;
27
- export interface RenderCommentsRequest {
28
- editor: Editor;
29
- editorId?: string;
30
- commentAnnotations?: CommentAnnotation[];
31
- }
32
- export declare const renderComments: ({ editor, editorId, commentAnnotations }: RenderCommentsRequest) => void;
33
- export declare const onSlateValueChange: ({ editor, editorId, }: {
34
- editor: Editor;
35
- editorId?: string;
36
- }) => void;
9
+ export { withVeltComments } from '@/core/extension';
10
+ export type { VeltCommentsExtensionConfig } from '@/core/extension';
11
+ export { addComment } from '@/features/addComment';
12
+ export { renderComments } from '@/features/renderComments';
13
+ export { exportJSONWithoutComments } from '@/utils/serializer';
14
+ export { SlateVeltComment } from '@/core/ExtensionComponent';
15
+ export type { AddCommentRequest, CommentAnnotationContext, RenderCommentsRequest } from '@/types/common';
16
+ export type { VeltCommentsEditor, VeltCommentsElement } from '@/types/host';
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Common type definitions shared across the entire codebase.
3
+ * These types are SDK-agnostic and represent domain concepts.
4
+ */
5
+ import type { CommentAnnotation } from '@/types/velt';
6
+ /**
7
+ * Context object for comment annotations.
8
+ * Contains text editor configuration and any additional context data.
9
+ */
10
+ export interface CommentAnnotationContext {
11
+ textEditorConfig?: {
12
+ text: string;
13
+ occurrence: number;
14
+ editorId?: string;
15
+ targetTextNodeId?: string;
16
+ };
17
+ [key: string]: unknown;
18
+ }
19
+ /**
20
+ * Request interface for addComment function.
21
+ * Matches legacy AddCommentRequest interface.
22
+ */
23
+ export interface AddCommentRequest {
24
+ editorId?: string;
25
+ editor: unknown;
26
+ context?: unknown;
27
+ }
28
+ /**
29
+ * Request interface for renderComments function.
30
+ * Matches legacy RenderCommentsRequest interface.
31
+ */
32
+ export interface RenderCommentsRequest {
33
+ editor: unknown;
34
+ editorId?: string;
35
+ commentAnnotations?: CommentAnnotation[];
36
+ }
37
+ /**
38
+ * Extension configuration for registry.
39
+ */
40
+ export interface ExtensionConfig {
41
+ persistVeltMarks?: boolean;
42
+ editorId?: string;
43
+ HistoryEditor?: unknown;
44
+ [key: string]: unknown;
45
+ }
46
+ /**
47
+ * Editor context containing editor instance and related state.
48
+ * Note: Editor type is generic to avoid importing editor types here.
49
+ */
50
+ export interface EditorContext<TEditor = unknown> {
51
+ editorId: string;
52
+ editor: TEditor;
53
+ config: ExtensionConfig;
54
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Editor-specific type definitions.
3
+ * This is the ONLY place where editor-specific types may be defined.
4
+ */
5
+ import type { Descendant, Editor } from 'slate';
6
+ import type { AnnotationData } from '@/types/state';
7
+ /**
8
+ * Extended Editor interface with Velt comments functionality.
9
+ */
10
+ export interface VeltCommentsEditor extends Editor {
11
+ }
12
+ /**
13
+ * Velt comment element type for the editor.
14
+ * This represents a comment annotation node/element in the editor's document model.
15
+ */
16
+ export type VeltCommentsElement = {
17
+ type: 'veltComment';
18
+ children: Descendant[];
19
+ annotationId?: string;
20
+ multiThreadAnnotationId?: string;
21
+ };
22
+ /**
23
+ * Selection context extracted from editor.
24
+ */
25
+ export interface SelectionContext {
26
+ text: string;
27
+ from: number;
28
+ to: number;
29
+ occurrence: number;
30
+ targetTextNodeId?: string;
31
+ locationId?: string;
32
+ }
33
+ /**
34
+ * Occurrence match result.
35
+ */
36
+ export interface OccurrenceMatch {
37
+ index: number;
38
+ start: number;
39
+ end: number;
40
+ text: string;
41
+ }
42
+ /**
43
+ * Represents a detected change to an annotation during document editing.
44
+ */
45
+ export interface AnnotationChange {
46
+ annotationId: string;
47
+ multiThreadAnnotationId?: string;
48
+ originalText: string;
49
+ currentText: string;
50
+ originalOccurrence: number;
51
+ currentOccurrence: number;
52
+ originalTargetTextNodeId: string;
53
+ newTargetTextNodeId: string;
54
+ annotation: AnnotationData;
55
+ contentChanged: boolean;
56
+ occurrenceChanged: boolean;
57
+ targetTextNodeIdChanged: boolean;
58
+ }
59
+ /**
60
+ * Document change event data.
61
+ */
62
+ export interface DocumentChangeEvent {
63
+ editorId: string;
64
+ changes: Map<string, AnnotationChange>;
65
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * State management type definitions.
3
+ * These types represent the internal state structure for managing annotations.
4
+ */
5
+ import type { CommentAnnotationContext } from '@/types/common';
6
+ import type { CommentAnnotation } from '@/types/velt';
7
+ /**
8
+ * Represents a single annotation with its associated data and position.
9
+ */
10
+ export interface AnnotationData {
11
+ annotationId: string;
12
+ multiThreadAnnotationId?: string;
13
+ context: CommentAnnotationContext;
14
+ position?: {
15
+ from: number;
16
+ to: number;
17
+ };
18
+ }
19
+ /**
20
+ * Annotation state per editor instance.
21
+ * Stores both simplified AnnotationData[] for core logic and full CommentAnnotation[] for rendering.
22
+ */
23
+ export interface AnnotationState {
24
+ editorId: string;
25
+ annotations: Map<string, AnnotationData>;
26
+ commentAnnotations: CommentAnnotation[];
27
+ selectedAnnotations: Set<string>;
28
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Velt SDK type definitions.
3
+ * This is the ONLY place where @veltdev/types may be imported.
4
+ */
5
+ import type { CommentAnnotation, Location, Velt } from '@veltdev/types';
6
+ export type { CommentAnnotation, Location, Velt };
7
+ /**
8
+ * Comment element from Velt SDK.
9
+ */
10
+ export type CommentElement = {
11
+ addManualComment: (params: {
12
+ context: unknown;
13
+ location?: Location;
14
+ }) => Promise<CommentAnnotation | null>;
15
+ updateContext: (annotationId: string, context: unknown) => void;
16
+ getSelectedComments?: () => {
17
+ subscribe: (callback: (comments: CommentAnnotation[]) => void) => () => void;
18
+ };
19
+ };
20
+ /**
21
+ * Unsubscribe function for Velt SDK subscriptions.
22
+ */
23
+ export type UnsubscribeFn = () => void;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Pure utility functions with zero side effects.
3
+ * These functions contain algorithmic logic extracted from legacy code.
4
+ *
5
+ * IMPORTANT: This module MUST NOT import any external SDKs or have side effects.
6
+ * All functions must be pure: input → output, deterministic, no mutations.
7
+ */
8
+ /**
9
+ * Computes the KMP (Knuth-Morris-Pratt) failure function (LPS array).
10
+ * This is used for efficient pattern matching in text search.
11
+ *
12
+ * @param pattern The pattern string to compute the failure function for
13
+ * @returns Longest proper prefix array (LPS array)
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const lps = computeKMPTable("abcabc");
18
+ * // Returns: [0, 0, 0, 1, 2, 3]
19
+ * ```
20
+ */
21
+ export declare const computeKMPTable: (pattern: string) => number[];
22
+ /**
23
+ * Finds all occurrences of a pattern in text using the KMP algorithm.
24
+ *
25
+ * @param text The text to search in
26
+ * @param pattern The pattern to search for
27
+ * @param startPos Starting position offset (default: 0)
28
+ * @param maxOccurrences Maximum number of occurrences to find (optional)
29
+ * @returns Array of start positions (0-based indices in the text)
30
+ *
31
+ * @example
32
+ * ```typescript
33
+ * const positions = kmpSearch("abcabcabc", "abc", 0, 2);
34
+ * // Returns: [0, 3] (first 2 occurrences)
35
+ * ```
36
+ */
37
+ export declare const kmpSearch: (text: string, pattern: string, startPos?: number, maxOccurrences?: number) => number[];
38
+ /**
39
+ * Maps text positions in a combined string back to document positions.
40
+ * Used when searching across multiple text nodes that have been concatenated.
41
+ *
42
+ * @param textNodes Array of text nodes with their document positions
43
+ * @param textPositions Positions in the combined text (from kmpSearch)
44
+ * @param patternLength Length of the pattern being searched for
45
+ * @returns Array of { from, to } ranges in document coordinates
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const textNodes = [
50
+ * { text: "Hello ", pos: 0 },
51
+ * { text: "World", pos: 6 }
52
+ * ];
53
+ * const positions = [0]; // Found at start of combined text
54
+ * const ranges = mapTextPositionsToDocument(textNodes, positions, 5);
55
+ * // Returns: [{ from: 0, to: 5 }]
56
+ * ```
57
+ */
58
+ export declare const mapTextPositionsToDocument: (textNodes: Array<{
59
+ text: string;
60
+ pos: number;
61
+ }>, textPositions: number[], patternLength: number) => Array<{
62
+ from: number;
63
+ to: number;
64
+ }>;
65
+ /**
66
+ * Compares two maps for equality.
67
+ * Checks if both maps have the same size and identical key-value pairs.
68
+ *
69
+ * @param map1 First map to compare
70
+ * @param map2 Second map to compare
71
+ * @returns True if maps are equal, false otherwise
72
+ *
73
+ * @example
74
+ * ```typescript
75
+ * const map1 = new Map([['a', true], ['b', false]]);
76
+ * const map2 = new Map([['a', true], ['b', false]]);
77
+ * areMapsEqual(map1, map2); // Returns: true
78
+ * ```
79
+ */
80
+ export declare const areMapsEqual: <K, V>(map1: Map<K, V>, map2: Map<K, V>) => boolean;
@@ -0,0 +1,25 @@
1
+ export declare class Console {
2
+ static log: {
3
+ (...data: any[]): void;
4
+ (message?: any, ...optionalParams: any[]): void;
5
+ };
6
+ static warn: {
7
+ (...data: any[]): void;
8
+ (message?: any, ...optionalParams: any[]): void;
9
+ };
10
+ static error: {
11
+ (...data: any[]): void;
12
+ (message?: any, ...optionalParams: any[]): void;
13
+ };
14
+ static debug: {
15
+ (...data: any[]): void;
16
+ (message?: any, ...optionalParams: any[]): void;
17
+ };
18
+ static info: {
19
+ (...data: any[]): void;
20
+ (message?: any, ...optionalParams: any[]): void;
21
+ };
22
+ static logsEnabled: boolean;
23
+ static catch: (message: string, error?: unknown) => void;
24
+ static showLogs(): boolean;
25
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Serializer utilities for Slate editor content
3
+ *
4
+ * This module provides utilities for serializing Slate editor content,
5
+ * particularly for removing comment nodes from serialized JSON.
6
+ *
7
+ * Use this when persisting editor content to remove Velt comment elements
8
+ * while preserving the original text content.
9
+ */
10
+ import type { Descendant } from 'slate';
11
+ /**
12
+ * Export JSON without comment nodes.
13
+ *
14
+ * This function takes Slate editor content and removes all comment nodes,
15
+ * unwrapping their children and merging adjacent text nodes with same formatting.
16
+ *
17
+ * @param content - Slate editor content (Descendant[])
18
+ * @returns Serialized content without comment nodes
19
+ */
20
+ export declare const exportJSONWithoutComments: (content: Descendant[]) => Descendant[];
package/esm/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{Editor as t,Path as e,Node as o,Transforms as n,Text as r,Element as i,Operation as c}from"slate";import{ReactEditor as a}from"slate-react";import s from"react";function l(t,e,o,n){return new(o||(o=Promise))((function(r,i){function c(t){try{s(n.next(t))}catch(t){i(t)}}function a(t){try{s(n.throw(t))}catch(t){i(t)}}function s(t){var e;t.done?r(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(c,a)}s((n=n.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const d={EDITOR_ID:"data-editor-id",LOCATION_ID:"data-velt-location-id"},u={VELT_COMMENT:"veltComment"};var h;class f{}h=f,f.selectedCommentsMap=new Map,f.subscribers=new Map,f.isSubscribed=!1,f.getCommentElement=()=>{try{const t=window.Velt;return(null==t?void 0:t.getCommentElement)?t.getCommentElement():null}catch(t){return h.catchError("Error getting comment element:",t),null}},f.addManualComment=({context:t,location:e})=>{try{const o=h.getCommentElement();return o?o.addManualComment({context:t,location:e}):Promise.resolve(null)}catch(t){return h.catchError("Error adding manual comment:",t),Promise.resolve(null)}},f.updateContext=({annotationId:t,context:e})=>{try{const o=h.getCommentElement();return o?o.updateContext(t,e):Promise.resolve(null)}catch(t){h.catchError("Error updating context:",t)}},f.subscribeToSelectedCommentsMap=(t,e)=>{try{h.subscribeToSelectedAnnotationsMapSingleton(),h.subscribers.set(t,e)}catch(t){h.catchError("Error subscribing to selected comments map:",t)}},f.unsubscribeFromSelectedCommentsMap=t=>{try{h.subscribers.delete(t)}catch(t){h.catchError("Error unsubscribing from selected comments map:",t)}},f.catchError=(t,e)=>{var o;try{let n={};e&&"object"==typeof e&&(n=Object.assign(Object.assign({},n),e)),t&&(n.message=t),n.sdkVersion=null===(o=window.Velt)||void 0===o?void 0:o.version}catch(t){}},f.subscribeToSelectedAnnotationsMapSingleton=()=>{var t;try{if(h.isSubscribed)return;const e=h.getCommentElement();e&&"function"==typeof(null==e?void 0:e.getSelectedComments)&&(null===(t=null==e?void 0:e.getSelectedComments())||void 0===t||t.subscribe((t=>{const e=new Map;null==t||t.forEach((t=>{(null==t?void 0:t.annotationId)&&e.set(null==t?void 0:t.annotationId,!0)}));((t,e)=>{if(t.size!==e.size)return!1;for(const[o,n]of t)if(e.get(o)!==n)return!1;return!0})(e,h.selectedCommentsMap||new Map)||h.updateSelectedCommentsMap(e)})),h.isSubscribed=!0)}catch(t){return new Map}},f.updateSelectedCommentsMap=t=>{try{h.selectedCommentsMap=t,h.subscribers.forEach((t=>{"function"==typeof t&&t(h.selectedCommentsMap)}))}catch(t){h.catchError("Error updating selected comments map:",t)}};class g{constructor(r){this.getSelectedText=e=>{try{return e.selection?t.string(e,e.selection):null}catch(t){return f.catchError("Error getting selected text:",t),null}},this.findOccurrenceOfText=t=>{try{const{searchText:e,scopeElement:o,startOffset:n=0,caseSensitive:r=!0}=t;if(!e)return{total:0,position:0};const i="string"==typeof o?o:(null==o?void 0:o.textContent)||"",c=r?t=>t:t=>t.toLowerCase(),a=c(i),s=c(e),l=[];let d=0;for(;;){const t=a.indexOf(s,d);if(-1===t)break;l.push(t),d=t+s.length}const u=l.filter((t=>t<n)).length+1;return{total:l.length,position:u}}catch(t){return f.catchError("Error finding occurrence of text:",t),null}},this.findOccurrenceOfSelectedText=(t,o)=>{var n;try{const r=this.getSelectedText(t);if(!r)return 0;if(!o){let o=0;const n=this.findAllMatches(t,r),i=t.selection;if(i){const t=e.compare(i.anchor.path,i.focus.path)>0||e.equals(i.anchor.path,i.focus.path)&&i.anchor.offset>i.focus.offset,r=n.findIndex((e=>t?e.anchor.path.toString()===i.focus.path.toString()&&e.focus.path.toString()===i.anchor.path.toString()&&e.anchor.offset===i.focus.offset&&e.focus.offset===i.anchor.offset:e.anchor.path.toString()===i.anchor.path.toString()&&e.focus.path.toString()===i.focus.path.toString()&&e.anchor.offset===i.anchor.offset&&e.focus.offset===i.focus.offset));-1!==r&&(o=r+1)}return o}const i=a.toDOMNode(t,t),c=null===(n=t.selection)||void 0===n?void 0:n.anchor.offset,s=this.findOccurrenceOfText({searchText:r,scopeElement:o||i,startOffset:c});return null==s?void 0:s.position}catch(t){return f.catchError("Error finding occurrence of selected text:",t),null}},this.findAllMatches=(e,o,n={caseSensitive:!0})=>{try{const{caseSensitive:r=!0}=n,i=[];if(!o)return i;const c=t=>"object"==typeof t&&null!==t&&"text"in t?t.text:"",a=t=>"object"==typeof t&&null!==t&&"text"in t&&"string"==typeof t.text,s=(t,e)=>{if(a(t)){const n=c(t),a=r?o:o.toLowerCase(),s=r?n:n.toLowerCase();let l=0;for(;;){const t=s.indexOf(a,l);if(-1===t)break;const n={anchor:{path:e,offset:t},focus:{path:e,offset:t+o.length}};i.push(n),l=t+1}}"children"in t&&Array.isArray(t.children)&&t.children.forEach(((t,o)=>{s(t,[...e,o])}))};try{const[o]=t.nodes(e,{at:[],mode:"highest"});o&&s(o[0],o[1])}catch(t){f.catchError("Error searching in document:",t)}return i}catch(t){return f.catchError("Error finding all matches:",t),[]}},this.findParentNodeWithIdForSelection=t=>{try{const{selection:e}=t;if(!e)return null;const{anchor:n}=e,r=o.get(t,n.path);return this.findParentNodeWithId(t,{node:r,path:n.path})}catch(t){return f.catchError("Error finding parent node with ID for selection:",t),null}},this.findParentNodeWithId=(e,o)=>{var n;try{let{node:r,path:i}=o||{};if(!r)return null;i&&(r=t.node(e,i)[0]);let c=null,s=null;try{c=a.toDOMNode(e,r)}catch(t){return null}try{s=a.toDOMNode(e,e)}catch(t){return null}const l=null!==(n=null==o?void 0:o.maxIterations)&&void 0!==n?n:100,d=null==o?void 0:o.idPattern;let u=c,h=0;for(;u&&u!==document.body&&h<l;){if(!s.contains(u))return null;if(u.id&&(!d||d.test(u.id)))return u;u=u.parentElement,h++}return null}catch(t){return f.catchError("Error finding parent node with ID:",t),null}},this.removeVeltCommentFromEditor=(e,r)=>{try{if(!e||!r)throw new Error("Invalid input: editor and annotationId are required");const i=[];for(const[t,n]of o.descendants(e))g.isVeltCommentText(t)&&t.annotationId===r&&i.push(n);try{i.reverse().forEach((o=>{const r=t.node(e,o)[0],i=a.toDOMNode(e,r);if(null==i?void 0:i.isConnected){const t=()=>{n.unwrapNodes(e,{at:o,mode:"lowest"})},r=g.getHistoryEditor();r&&"function"==typeof r.withoutSaving?r.withoutSaving(e,(()=>{t()})):t()}}))}catch(t){f.catchError("Error unwrapping elements:",t)}return!0}catch(t){return f.catchError("Error removing Velt comment:",t),!1}},this.highlightTextWithVeltComment=(t,e)=>{var o;try{const{text:n,targetTextNodeId:r,occurrence:i}=(null===(o=null==e?void 0:e.context)||void 0===o?void 0:o.textEditorConfig)||{};if(!n||!i)return;this.injectTag(t,n,i,e.annotationId,r)&&e.annotationId&&this.plugin.storeService.annotationStore.set(e.annotationId,{annotation:e})}catch(t){f.catchError("Error highlighting text with velt comment:",t)}},this.getEditorTextContent=t=>{try{return t.children.map((t=>o.string(t))).join("")}catch(t){return f.catchError("Error getting editor text content:",t),""}},this.onSlateValueChange=({editor:e})=>{try{const o=this.collectDocumentAnnotations({editor:e});if(0===o.size)return;const n=new Map;for(const[r]of o){if(!this.plugin.storeService.annotationStore.get(r))continue;if(!Array.from(t.nodes(e,{at:[]})).filter((([t])=>g.isVeltCommentText(t))).filter((([t])=>t.annotationId===r)).map((([o,n])=>({node:o,pos:t.start(e,n).offset}))).length)continue;const o=this.processAnnotationChanges({editor:e,annotationId:r});o&&n.set(r,o)}n.size>0&&this.updateVeltComments({changes:n,editor:e})}catch(t){f.catchError("Error in processVeltCommentChanges:",t)}},this.injectTag=(e,o,n,r,i)=>{try{let c=null;if(i){if(c=document.getElementById(i),!c)return!1;if(!this.isElementInEditor(e,c))return!1}else c=a.toDOMNode(e,e);if(!c)return!1;const s=this.findTextOccurrence(e,o,n,c);if(!s)return!1;if(Array.from(t.nodes(e,{at:s,match:t=>g.isVeltCommentText(t)})).length>0)return!1;const l=()=>{e.wrapNodes({type:u.VELT_COMMENT,children:[],annotationId:r},{at:s,split:!0})},d=g.getHistoryEditor();return d&&"function"==typeof d.withoutSaving?d.withoutSaving(e,(()=>{l()})):l(),!0}catch(t){return f.catchError("Error injecting tag:",t),!1}},this.plugin=r}collectDocumentAnnotations({editor:e}){try{const o=new Map;return Array.from(t.nodes(e,{at:[]})).filter((([t])=>g.isVeltCommentText(t))).forEach((([t])=>{const e=t.annotationId;if(e){const t=this.plugin.storeService.annotationStore.get(e);(null==t?void 0:t.annotation)&&o.set(e,t.annotation)}})),o}catch(t){return f.catchError("Error collecting document annotations:",t),new Map}}processAnnotationChanges({editor:e,annotationId:n}){var r,i,c,s;try{let l=null,d=null,u=null;const h=null===(r=this.plugin.storeService.annotationStore.get(n))||void 0===r?void 0:r.annotation;if(!(null===(i=null==h?void 0:h.context)||void 0===i?void 0:i.textEditorConfig))return null;const{text:f,targetTextNodeId:m,occurrence:v}=(null===(c=null==h?void 0:h.context)||void 0===c?void 0:c.textEditorConfig)||{},E=Array.from(t.nodes(e,{at:[],match:t=>g.isVeltCommentText(t)&&t.annotationId===n,mode:"lowest"}));for(const[t,e]of E)l=t,u=e;if(!l)return null;try{if(d=a.toDOMNode(e,l),!d)return null}catch(t){return null}const p=E.map((([t])=>o.string(t))).join("");if(!p)return null;const x=this.findParentNodeWithId(e,{node:l,path:null!=u?u:void 0});let C,S,b;x&&(C=x.id),x&&(S=a.toSlateNode(e,x),b=a.findPath(e,S));const y=null===(s=this.findTextOccurrenceOfNode(e,l,null!=u?u:void 0,S,b))||void 0===s?void 0:s.nodeOccurrencePosition;if(!y)return null;const T=p!==f,I=y!==v,O=m!==C;return T||I||O?{contentChanged:T,currentText:p,occurrenceChanged:I,currentOccurrence:null!=y?y:0,originalOccurrence:v,annotationId:n,originalText:f,originalTargetTextNodeId:m,newTargetTextNodeId:C,annotation:h,multiThreadAnnotationId:null==h?void 0:h.multiThreadAnnotationId,targetTextNodeIdChanged:O}:null}catch(t){return f.catchError("Error processing annotation changes:",t),null}}updateVeltComments({changes:t,editor:e}){var o;try{for(const[n,r]of Array.from(t.entries()))try{if(!(null===(o=r.annotation.context)||void 0===o?void 0:o.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 i=Object.assign(Object.assign({},r.annotation.context),{textEditorConfig:t});this.plugin.storeService.annotationStore.remove(n),this.removeVeltCommentFromEditor(e,n),f.updateContext({annotationId:n,context:i})}catch(t){f.catchError("Error updating Velt comments",t)}}catch(t){f.catchError("Error updating Velt comments",t)}}isElementInEditor(t,e){try{return a.toDOMNode(t,t).contains(e)}catch(t){return f.catchError("Error checking element in editor:",t),!1}}traverseNodesForText(t,e,o,n){try{if(r.isText(t)){const r=n.length,i=(n+=t.text).length;o.push({node:t,path:e,start:r,end:i})}else if(i.isElement(t))for(let r=0;r<t.children.length;r++){const i=[...e,r];n=this.traverseNodesForText(t.children[r],i,o,n)}return n}catch(t){return f.catchError("Error traversing nodes for text:",t),""}}collectSubtreeText(t,e,o){try{const n=[];let r="";if(0===o.length)for(let e=0;e<t.children.length;e++){const o=[e];r=this.traverseNodesForText(t.children[e],o,n,r)}else r=this.traverseNodesForText(e,o,n,r);return{fullText:r,textNodePositions:n}}catch(t){return f.catchError("Error collecting subtree text:",t),{fullText:"",textNodePositions:[]}}}findTextOccurrence(t,e,o,n){try{const r=a.toSlateNode(t,n),i=a.findPath(t,r),{fullText:c,textNodePositions:s}=this.collectSubtreeText(t,r,i),l=[];let d;const u=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");for(;null!==(d=u.exec(c));)l.push({index:d.index});if(l.length<o)return null;const h=l[o-1].index,f=h+e.length;let g,m;for(const t of s)if(h>=t.start&&h<t.end&&(g=t),f>t.start&&f<=t.end&&(m=t),g&&m)return{anchor:{path:g.path,offset:h-g.start},focus:{path:m.path,offset:f-m.start}};return null}catch(t){return f.catchError("Error in findTextOccurrence:",t),null}}findAllTextOccurrences(n,i,c=!0,a,s){try{if(!i)return[];const l=[],d=c?t=>t:t=>t.toLowerCase(),u=d(i);if(a&&!s)try{for(const[e,o]of t.nodes(n))if(e===a){s=o;break}}catch(t){f.catchError("Error finding container path:",t)}const h=s||[];for(const[c,a]of t.nodes(n,{at:h,match:t=>r.isText(t)})){if(s&&!e.isDescendant(a,s)&&!e.equals(a,s))continue;const t=o.string(c),n=d(t);let r,h=0;for(;-1!==(r=n.indexOf(u,h));){const e={path:a,offset:r},o={path:a,offset:r+i.length},n={anchor:e,focus:o};l.push({node:c,path:a,range:n,startPoint:e,endPoint:o,text:t.substring(r,r+i.length)}),h=r+u.length}}return l}catch(t){return f.catchError("Error finding all text occurrences:",t),[]}}findTextOccurrenceOfNode(n,r,i,c,s){try{const l=o.string(r);if(!l.trim())return{node:r,nodePath:i,text:l,totalOccurrences:0,nodeOccurrencePosition:0,textOccurrences:[],containerNode:c,containerPath:s};if(!i)try{if("findPath"in a)try{i=a.findPath(n,r)}catch(t){f.catchError("Error finding path with ReactEditor:",t)}if(!i)for(const[e,o]of t.nodes(n))if(e===r){i=o;break}}catch(t){f.catchError("Error finding node path:",t)}const d=this.findAllTextOccurrences(n,l,!0,c,s);let u=0;if(i)for(let t=0;t<d.length;t++){const o=d[t],n=e.equals(o.path,i),r=e.isAncestor(i,o.path);if(n||r){u=t+1;break}}return{node:r,nodePath:i,text:l,totalOccurrences:d.length,nodeOccurrencePosition:u,textOccurrences:d,containerNode:c,containerPath:s}}catch(t){return f.catchError("Error finding text occurrence of node:",t),null}}}g.setHistoryEditor=t=>{g.HistoryEditor=t},g.getHistoryEditor=()=>g.HistoryEditor,g.getEditorId=t=>{var e,o;try{const n=a.toDOMNode(t,t);return n&&(null!==(o=null===(e=null==n?void 0:n.closest(`[${d.EDITOR_ID}]`))||void 0===e?void 0:e.getAttribute(d.EDITOR_ID))&&void 0!==o)?o:null}catch(t){return f.catchError("Error finding editor ID:",t),null}},g.isVeltCommentText=t=>t.type===u.VELT_COMMENT;class m{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)}},this.updateGlobalStore=t=>{var e,o,n;try{const r=(null==t?void 0:t.comments)||(null===(e=this.globalStore)||void 0===e?void 0:e.comments)||[],i=(null==t?void 0:t.selectedCommentsMap)||(null===(o=this.globalStore)||void 0===o?void 0:o.selectedCommentsMap)||new Map,c=(null===(n=this.globalStore)||void 0===n?void 0:n.filteredComments)||[],a=r.filter((t=>{var e;return"terminal"!==(null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.type)||(null==i?void 0:i.get(null==t?void 0:t.annotationId))})),s=new Set(a.map((t=>null==t?void 0:t.annotationId)));c.map((t=>null==t?void 0:t.annotationId)).filter((t=>t&&!s.has(t))).forEach((t=>{var e,o;(null===(e=this.globalStore)||void 0===e?void 0:e.editor)&&t&&this.plugin.editorService.removeVeltCommentFromEditor(null===(o=this.globalStore)||void 0===o?void 0:o.editor,t)})),this.globalStore=Object.assign(Object.assign(Object.assign({},this.globalStore),t),{filteredComments:a}),this.highlightCommentsFromGlobalStore()}catch(t){f.catchError("Error updating global store:",t)}},this.highlightCommentsFromGlobalStore=()=>{var t,e;try{const{editor:o,filteredComments:n}=this.globalStore;if(!o||!n)return;for(const r of n){(null===(e=null===(t=null==r?void 0:r.context)||void 0===t?void 0:t.textEditorConfig)||void 0===e?void 0:e.text)&&this.plugin.editorService.highlightTextWithVeltComment(o,r)}}catch(t){f.catchError("Error highlighting comments from global store:",t)}},this.plugin=t;try{f.subscribeToSelectedCommentsMap(this.plugin.editorId,(t=>{try{this.updateGlobalStore({selectedCommentsMap:t})}catch(t){f.catchError("Error updating global store:",t)}}))}catch(t){f.catchError("Error subscribing to selected comments map:",t)}}}m.storeInstanceMap=new Map;const v=new Map;class E{constructor(t,e){this.previousEditorTextContent="",this.editorId=t,this.editor=e,this.editorService=new g(this),this.storeService=new m(this),e&&this.setPreviousEditorTextContent(this.editorService.getEditorTextContent(e))}static getInstance(t){let{editorId:e,editor:o}=t||{};return e||(e="default"),v.has(e)||v.set(e,new E(e,o)),v.get(e)}getPreviousEditorTextContent(){return this.previousEditorTextContent}setPreviousEditorTextContent(t){this.previousEditorTextContent=t}}const p=t=>{const{attributes:e,children:o,element:n}=t,r=null==n?void 0:n.annotationId;return s.createElement("velt-comment-text",Object.assign({"annotation-id":r},e),o)},x=(t,e)=>{const{isInline:o,isVoid:n,onChange:r}=t;return(null==e?void 0:e.HistoryEditor)&&g.setHistoryEditor(e.HistoryEditor),t.isInline=t=>!!g.isVeltCommentText(t)||o(t),t.isVoid=t=>!g.isVeltCommentText(t)&&n(t),t.onChange=()=>{r&&r();t.operations.some((t=>c.isTextOperation(t)))&&T({editor:t})},t},C=(t,e)=>l(void 0,void 0,void 0,(function*(){try{return S({editor:t,context:null==e?void 0:e.context})}catch(t){f.catchError("Error triggering add comment",t)}})),S=t=>l(void 0,[t],void 0,(function*({editorId:t,editor:e,context:o}){var n,r;try{if(!f.getCommentElement())return;t||(t=null!==(n=g.getEditorId(e))&&void 0!==n?n:void 0);const i=E.getInstance({editorId:t,editor:e}),c=i.editorService.getSelectedText(e);if(!c)return;const a=i.editorService.findParentNodeWithIdForSelection(e);let s,l=null;a&&(s=a.id,l=null===(r=a.closest("[data-velt-location-id]"))||void 0===r?void 0:r.getAttribute("data-velt-location-id"));const d=i.editorService.findOccurrenceOfSelectedText(e,null!=a?a:void 0);if(!d)return;let u,h={};o&&"object"==typeof o&&(h=Object.assign(Object.assign({},h),o)),h.textEditorConfig={text:c,occurrence:d,targetTextNodeId:s},t&&(h.textEditorConfig.editorId=t),yield new Promise((t=>setTimeout(t,200))),l&&(u={id:l});try{f.addManualComment({context:h,location:u})}catch(t){f.catchError("Error creating comment",t)}}catch(t){f.catchError("Error adding comment",t)}}));function b(t,e,o){try{y({editor:t,editorId:o,commentAnnotations:e})}catch(t){f.catchError("Error highlighting tiptap-velt-comments",t)}}const y=({editor:t,editorId:e,commentAnnotations:o})=>{var n;try{if(t){e||(e=null!==(n=g.getEditorId(t))&&void 0!==n?n:void 0),o=null==o?void 0:o.filter((t=>{var o,n,r;return!!(null===(o=t.context)||void 0===o?void 0:o.textEditorConfig)&&(null===(r=null===(n=t.context)||void 0===n?void 0:n.textEditorConfig)||void 0===r?void 0:r.editorId)===e}));E.getInstance({editorId:e,editor:t}).storeService.updateGlobalStore({editor:t,comments:o}),f.subscribeToSelectedAnnotationsMapSingleton()}}catch(t){f.catchError("Error highlighting tiptap-velt-comments",t)}},T=({editor:t,editorId:e})=>{var o;try{e||(e=null!==(o=g.getEditorId(t))&&void 0!==o?o:void 0);const n=E.getInstance({editorId:e,editor:t}),r=n.editorService.getEditorTextContent(t);if(r===n.getPreviousEditorTextContent())return;n.setPreviousEditorTextContent(r),n.editorService.onSlateValueChange({editor:t})}catch(t){f.catchError("Error in processVeltCommentChanges:",t)}};export{p as SlateVeltComment,S as addComment,b as highlightComments,T as onSlateValueChange,y as renderComments,C as triggerAddComment,x as withVeltComments};
1
+ import{Editor as t,Path as n,Node as e,Element as o,Transforms as r,Text as c,Operation as i}from"slate";import{ReactEditor as a}from"slate-react";import s from"react";const d={EDITOR_ID:"data-editor-id",LOCATION_ID:"data-velt-location-id",ANNOTATION_ID:"annotation-id",MULTI_THREAD_ANNOTATION_ID:"multi-thread-annotation-id"},l={VELT_COMMENT:"veltComment"},u="veltComment",f="slateVeltComments",h="__default__",g="terminal",p="SlateVeltComments: ",m="debugMode",v="forceDebugMode",x=(t,n,e=0,o)=>{const r=[];if(!n||!t||n.length>t.length)return r;const c=(t=>{if(!t||0===t.length)return[];const n=new Array(t.length).fill(0);let e=0,o=1;for(;o<t.length;)t[o]===t[e]?(e++,n[o]=e,o++):0!==e?e=n[e-1]:(n[o]=0,o++);return n})(n);let i=0,a=0;for(;i<t.length;)if(n[a]===t[i]&&(i++,a++),a===n.length){if(r.push(e+i-a),a=c[a-1],o&&r.length>=o)break}else i<t.length&&n[a]!==t[i]&&(0!==a?a=c[a-1]:i++);return r};class y{static showLogs(){try{return!!sessionStorage.getItem(m)||!!sessionStorage.getItem(v)}catch(t){return y.catch("Error in showLogs: ",t),!1}}}y.log=y.showLogs()?console.log:()=>{},y.warn=y.showLogs()?console.warn:()=>{},y.error=y.showLogs()?console.error:()=>{},y.debug=y.showLogs()?console.debug:()=>{},y.info=y.showLogs()?console.info:()=>{},y.logsEnabled=!0,y.catch=(t,n)=>{try{y.logsEnabled&&(void 0!==n?console.warn(p,t,n):console.warn(p,t))}catch(t){}};const E=t=>{var n,e;try{const o=a.toDOMNode(t,t);return o&&(null!==(e=null===(n=null==o?void 0:o.closest(`[${d.EDITOR_ID}]`))||void 0===n?void 0:n.getAttribute(d.EDITOR_ID))&&void 0!==e)?e:null}catch(t){return null}},I=(t,e,o)=>{try{if(!e||!t.selection)return 0;if(o){const n=document.getElementById(o);if(n){const o=t.selection.anchor.offset;return O(n,e,o)}}const r=N(t,e),c=t.selection;if(!c||0===r.length)return 0;const i=n.compare(c.anchor.path,c.focus.path)>0||n.equals(c.anchor.path,c.focus.path)&&c.anchor.offset>c.focus.offset,a=r.findIndex((t=>i?n.equals(t.anchor.path,c.focus.path)&&n.equals(t.focus.path,c.anchor.path)&&t.anchor.offset===c.focus.offset&&t.focus.offset===c.anchor.offset:n.equals(t.anchor.path,c.anchor.path)&&n.equals(t.focus.path,c.focus.path)&&t.anchor.offset===c.anchor.offset&&t.focus.offset===c.focus.offset));return-1!==a?a+1:0}catch(t){return y.catch("[HostAdapter] Error finding occurrence index:",t),0}},w=t=>{try{const{selection:n}=t;if(!n)return null;const{anchor:o}=n,r=e.get(t,o.path);return A(t,r,o.path)}catch(t){return y.catch("[HostAdapter] Error finding parent node with ID:",t),null}},A=(t,n,e,o=100)=>{try{let e=null,r=null;try{e=a.toDOMNode(t,n)}catch(t){return null}try{r=a.toDOMNode(t,t)}catch(t){return null}let c=e,i=0;for(;c&&c!==document.body&&i<o;){if(!r.contains(c))return null;if(c.id)return c;c=c.parentElement,i++}return null}catch(t){return y.catch("[HostAdapter] Error finding parent node:",t),null}},T=(o,r,c,i,s)=>{try{if(!r)return 0;const d=e.string(c);if(!d||!d.trim())return 0;let l,u;if(s){const t=document.getElementById(s);if(t)try{l=a.toSlateNode(o,t),u=a.findPath(o,l)}catch(t){y.warn("[findOccurrenceForNode] Could not find container node:",t)}}const f=N(o,r);if(0===f.length)return 0;let h=f;if(u&&(h=f.filter((e=>{const r=t.start(o,e);return n.isAncestor(u,r.path)||n.equals(u,r.path)}))),0===h.length)return 0;for(let e=0;e<h.length;e++){const r=h[e],c=t.start(o,r).path,a=n.equals(c,i),s=n.isAncestor(i,c);if(a||s){const t=f.indexOf(r);return-1!==t?t+1:e+1}}return y.warn("[findOccurrenceForNode] No matching occurrence found for text:",r,"node path:",i),0}catch(t){return y.catch("[HostAdapter] Error finding occurrence for node:",t),0}},N=(n,e,o=!0)=>{try{const r=[];if(!e)return r;const c=t=>"object"==typeof t&&null!==t&&"text"in t?t.text:"",i=t=>"object"==typeof t&&null!==t&&"text"in t&&"string"==typeof t.text,a=(t,n)=>{if(i(t)){const i=c(t),a=o?e:e.toLowerCase(),s=o?i:i.toLowerCase(),d=x(s,a);for(const t of d){const o={anchor:{path:n,offset:t},focus:{path:n,offset:t+e.length}};r.push(o)}}"children"in t&&Array.isArray(t.children)&&t.children.forEach(((t,e)=>{a(t,[...n,e])}))};try{const[e]=t.nodes(n,{at:[],mode:"highest"});e&&a(e[0],e[1])}catch(t){y.catch("[HostAdapter] Error searching in document:",t)}return r}catch(t){return y.catch("[HostAdapter] Error finding all matches:",t),[]}},O=(t,n,e,o=!0)=>{try{if(!n)return 0;const r=t.textContent||"",c=o?r:r.toLowerCase(),i=o?n:n.toLowerCase(),a=x(c,i);if(0===a.length)return 0;if(void 0!==e){return a.filter((t=>t<e)).length+1}return 1}catch(t){return y.catch("[HostAdapter] Error finding occurrence in DOM:",t),0}},C=(t,n)=>{try{let e=t;return e||(e=E(n)||"default"),{editorId:e}}catch(n){return y.warn("[ensureEditorSetup] Error setting up editor:",n),{editorId:t||"default"}}};let b=null;const M=t=>o.isElement(t)&&t.type===l.VELT_COMMENT,$=(n,e,c,i,s,d)=>{const u="[applyAnnotationMarkByText]";try{if(!n||!i)return!1;const f=n;let h=null;if(d){if(h=document.getElementById(d),!h)return y.warn(`${u} Target element not found: ${d}`),!1;if(!V(f,h))return y.warn(`${u} Target element not in editor: ${d}`),!1}else h=a.toDOMNode(f,f);if(!h)return y.warn(`${u} No target element found`),!1;const g=k(f,e,c,h);return g?((n,e,c,i)=>{try{if(!i)return!1;if(Array.from(t.nodes(n,{at:i,match:t=>!!o.isElement(t)&&M(t)})).length>0)return!1;const a=()=>{r.wrapNodes(n,{type:l.VELT_COMMENT,children:[],annotationId:e,multiThreadAnnotationId:c},{at:i,split:!0})};return b&&"function"==typeof b.withoutSaving?b.withoutSaving(n,(()=>{a()})):a(),!0}catch(t){return y.catch("[HostAdapter] Error applying annotation mark:",t),!1}})(f,i,s,g):(y.warn(`${u} Could not find text occurrence range for "${e}" occurrence ${c}`),!1)}catch(t){return y.catch(`${u} Error applying annotation mark by text:`,t),!1}},S=(t,n)=>{try{if(!t||!n)return!1;const c=[];for(const[r,i]of e.descendants(t))o.isElement(r)&&M(r)&&r.annotationId===n&&c.push(i);try{c.reverse().forEach((n=>{const o=e.get(t,n),c=a.toDOMNode(t,o);if(null==c?void 0:c.isConnected){const e=()=>{r.unwrapNodes(t,{at:n,mode:"lowest"})};b&&"function"==typeof b.withoutSaving?b.withoutSaving(t,(()=>{e()})):e()}}))}catch(t){y.catch("[HostAdapter] Error unwrapping elements:",t)}return!0}catch(t){return y.catch("[HostAdapter] Error removing annotation mark:",t),!1}},V=(t,n)=>{try{return a.toDOMNode(t,t).contains(n)}catch(t){return y.catch("[HostAdapter] Error checking element in editor:",t),!1}},k=(t,n,e,o)=>{const r="[findTextOccurrenceRange]";try{const c=a.toSlateNode(t,o);if(!c)return y.warn(`${r} Could not convert target element to Slate node`),null;const i=a.findPath(t,c),{fullText:s,textNodePositions:d}=D(t,c,i),l=[];let u;const f=new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g");for(;null!==(u=f.exec(s));)l.push({index:u.index});if(l.length<e)return y.warn(`${r} Not enough occurrences: found ${l.length}, need ${e}`),null;const h=l[e-1].index,g=h+n.length;let p,m;for(const t of d)if(h>=t.start&&h<t.end&&!p&&(p=t),g>t.start&&g<=t.end&&!m&&(m=t),p&&m){return{anchor:{path:p.path,offset:h-p.start},focus:{path:m.path,offset:g-m.start}}}return y.warn(`${r} Could not find anchor/focus nodes for match`),null}catch(t){return y.catch(`${r} Error finding text occurrence range:`,t),null}},D=(t,n,e)=>{const r=[];let i="";const a=(t,n,e,r)=>{try{if(c.isText(t)){const o=r.length,c=(r+=t.text).length;e.push({node:t,path:n,start:o,end:c})}else if(o.isElement(t))for(let o=0;o<t.children.length;o++){const c=[...n,o];r=a(t.children[o],c,e,r)}return r}catch(t){return y.catch("[HostAdapter] Error traversing nodes for text:",t),r}};if(0===e.length)for(let n=0;n<t.children.length;n++){const e=[n];i=a(t.children[n],e,r,i)}else i=a(n,e,r,i);return{fullText:i,textNodePositions:r}},L=new Map,_=t=>{const n={annotations:new Map,commentAnnotations:[],selectedAnnotations:new Set,editorId:t};return L.set(t,n),n},H=t=>{let n=L.get(t);return n||(n=_(t)),n},j=(t,n)=>{try{const e=H(t);e.commentAnnotations=n;const o=new Map;for(const t of n){if(!(null==t?void 0:t.annotationId))continue;const n={annotationId:t.annotationId,multiThreadAnnotationId:t.multiThreadAnnotationId,context:t.context};o.set(t.annotationId,n)}e.annotations=o}catch(t){y.catch("Error updating annotations:",t)}},R=(t,n)=>{try{const e=L.get(t);return e&&e.annotations.get(n)||null}catch(t){return y.catch("Error getting annotation:",t),null}},P=new Map;function q(t,n,e,o){return new(e||(e=Promise))((function(r,c){function i(t){try{s(o.next(t))}catch(t){c(t)}}function a(t){try{s(o.throw(t))}catch(t){c(t)}}function s(t){var n;t.done?r(t.value):(n=t.value,n instanceof e?n:new e((function(t){t(n)}))).then(i,a)}s((o=o.apply(t,n||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;let B=!1,F=new Map;const J=new Map,z=()=>{try{const t=window.Velt;return(null==t?void 0:t.getCommentElement)?t.getCommentElement():null}catch(t){return y.catch("[VeltAdapter] Error getting comment element:",t),null}},K=(t,n)=>{try{const e=z();if(!e)return;e.updateContext(t,n)}catch(t){y.catch("[VeltAdapter] Error updating context:",t)}},U=()=>{const t=z();if(!(null==t?void 0:t.getSelectedComments))return!1;try{const n=t.getSelectedComments();if(!(null==n?void 0:n.subscribe))return!1;const e=n.subscribe((t=>{const n=new Map;if(null==t||t.forEach((t=>{(null==t?void 0:t.annotationId)&&n.set(t.annotationId,!0)})),!((t,n)=>{if(t.size!==n.size)return!1;for(const[e,o]of Array.from(t))if(n.get(e)!==o)return!1;return!0})(n,F)){F=n;const t=new Set;for(const[e]of n)t.add(e);J.forEach((n=>{if("function"==typeof n)try{n(t)}catch(t){y.catch("[VeltAdapter] Error in subscriber callback:",t)}}))}}));if(e&&"function"==typeof e.unsubscribe)return B=!0,!0}catch(t){y.catch("[VeltAdapter] Error setting up getSelectedComments subscription:",t)}return!1},G=(n,r,c)=>{var i;const a="[handleContentUpdate]";try{const c=t=>{var e,o,r,c,i,s;const d=R(n,t);if(!d)return y.warn(`${a} Annotation not found in state: ${t}`),null;return{annotation:d,originalText:(null===(o=null===(e=d.context)||void 0===e?void 0:e.textEditorConfig)||void 0===o?void 0:o.text)||"",originalOccurrence:(null===(c=null===(r=d.context)||void 0===r?void 0:r.textEditorConfig)||void 0===c?void 0:c.occurrence)||1,targetTextNodeId:(null===(s=null===(i=d.context)||void 0===i?void 0:i.textEditorConfig)||void 0===s?void 0:s.targetTextNodeId)||""}},s=((n,r,c=u,i)=>{const a="[detectDocumentChanges]",s=new Map;try{const r=Array.from(t.nodes(n,{at:[],match:t=>o.isElement(t)&&t.type===l.VELT_COMMENT&&"annotationId"in t,mode:"lowest"}));for(const[t,o]of r){const r=t.annotationId;if(!r){y.warn(`${a} Node missing annotationId, skipping`);continue}const c=i(r);if(!c){y.warn(`${a} No stored data found for annotationId: ${r}, skipping`);continue}const d=c.originalText,l=c.originalOccurrence,u=c.targetTextNodeId||"",f=e.string(t);if(!f){y.warn(`${a} Node has no text content, skipping`);continue}const h=A(n,t,o),g=(null==h?void 0:h.id)||"",p=T(n,f,t,o,g),m=f!==d,v=p!==l,x=u!==g;if(m||v||x){const t=c.annotation;s.set(r,{annotationId:r,multiThreadAnnotationId:t.multiThreadAnnotationId,originalText:d,currentText:f,originalOccurrence:l,currentOccurrence:p,originalTargetTextNodeId:u,newTargetTextNodeId:g,annotation:t,contentChanged:m,occurrenceChanged:v,targetTextNodeIdChanged:x})}}}catch(t){y.catch("[HostAdapter] Error detecting document changes:",t)}return s})(r,0,u,c);if(0===s.size)return;for(const[t,e]of Array.from(s.entries())){const o=`${a}[${t}]`,r=R(n,t);if(!r){y.warn(`${o} Annotation not found in state, skipping`);continue}if(!(null===(i=r.context)||void 0===i?void 0:i.textEditorConfig)){y.warn(`${o} No textEditorConfig, skipping`);continue}const c=JSON.parse(JSON.stringify(r.context.textEditorConfig));e.contentChanged&&(c.text=e.currentText),e.occurrenceChanged&&(c.occurrence=e.currentOccurrence),e.targetTextNodeIdChanged&&(c.targetTextNodeId=e.newTargetTextNodeId);const s=Object.assign(Object.assign({},r.context),{textEditorConfig:c});K(t,s)}((t,n)=>{try{for(const[e,o]of n)S(t,e)}catch(t){y.catch("[HostAdapter] Error updating marks:",t)}})(r,s)}catch(t){y.catch("Error handling content update:",t)}},Q=t=>o.isElement(t)&&t.type===l.VELT_COMMENT,W=(t,n)=>{var e;const{isInline:o,isVoid:r,onChange:c}=t;var a;(null==n?void 0:n.HistoryEditor)&&(a=n.HistoryEditor,b=a);const s=(null==n?void 0:n.editorId)||E(t)||"default";return((t,n,e)=>{const o=t||"default";_(o);const r={editorId:o,editor:n,config:e||{}};P.set(o,r)})(s,t,{persistVeltMarks:null===(e=null==n?void 0:n.persistVeltMarks)||void 0===e||e,editorId:s,HistoryEditor:null==n?void 0:n.HistoryEditor}),t.isInline=t=>!!Q(t)||o(t),t.isVoid=t=>!Q(t)&&r(t),t.onChange=()=>{c&&c();t.operations.some((t=>i.isTextOperation(t)))&&G(s,t)},t},X=(t,n=f)=>{var e;try{const n=E(t);if(!n)return!0;const o=(t=>P.get(t)||null)(n);return void 0===(null===(e=null==o?void 0:o.config)||void 0===e?void 0:e.persistVeltMarks)||o.config.persistVeltMarks}catch(t){return y.warn("[getPersistVeltMarks] Error checking persistVeltMarks, defaulting to true:",t),!0}};function Y(n){return q(this,arguments,void 0,(function*({editorId:n,editor:e,context:o}){const r="[addComment]";var c;if(e)try{if(!z())return void y.warn(`${r} Velt SDK not available, cannot add comment`);const i=(n=>{var e;try{if(!n.selection)return null;const o=t.string(n,n.selection);if(!o)return null;const r=t.start(n,n.selection).offset,c=t.end(n,n.selection).offset,i=w(n),a=null==i?void 0:i.id;let s;return i&&(s=(null===(e=i.closest(`[${d.LOCATION_ID}]`))||void 0===e?void 0:e.getAttribute(d.LOCATION_ID))||void 0),{text:o,from:r,to:c,occurrence:I(n,o,a),targetTextNodeId:a,locationId:s}}catch(t){return y.catch("[HostAdapter] Error getting selection context:",t),null}})(e);if(!i)return void y.warn(`${r} No valid selection found, exiting`);const{editorId:a}=C(n,e),s=void 0!==n||a!==h,l=Object.assign(Object.assign({},o&&"object"==typeof o?o:{}),{textEditorConfig:Object.assign(Object.assign({text:i.text,occurrence:i.occurrence},s&&{editorId:a}),{targetTextNodeId:i.targetTextNodeId})});let u;i.locationId&&(u={id:i.locationId}),yield new Promise((t=>setTimeout(t,200)));const g=yield(c={context:l,location:u},q(void 0,void 0,void 0,(function*(){try{const t=z();if(!t)return null;const n=yield t.addManualComment({context:c.context,location:c.location});return n?{annotation:n}:null}catch(t){return y.catch("[VeltAdapter] Error adding comment:",t),null}})));if(!g||!g.annotation)return void y.warn(`${r} Failed to create comment via Velt SDK`);const p=g.annotation,m=((t,n=f)=>{try{return!1===X(t,n)}catch(t){return y.warn("[shouldApplyMark] Error checking persistVeltMarks, defaulting to true:",t),!0}})(e,f);m&&p.annotationId&&$(e,i.text,i.occurrence,p.annotationId,p.multiThreadAnnotationId,i.targetTextNodeId),p.annotationId?j(a,[p]):y.warn(`${r} No annotationId, skipping state update`)}catch(t){y.catch(`${r} Error adding comment:`,t)}else y.catch(`${r} ERROR: No editor provided`)}))}const Z=new Map,tt=(t,n,e)=>{var o;try{const r=Z.get(t);r?r.editor=n:Z.set(t,{editor:n,previousFilteredAnnotations:[]});const c=(t=>{try{const n=L.get(t);return n?new Set(n.selectedAnnotations):new Set}catch(t){return y.catch("Error getting selected annotations:",t),new Set}})(t),i=((t,n)=>t.filter((t=>{var e;return(null===(e=null==t?void 0:t.status)||void 0===e?void 0:e.type)!==g||n.has(t.annotationId)})))(e,c),a=(null===(o=Z.get(t))||void 0===o?void 0:o.previousFilteredAnnotations)||[],s=new Set(i.map((t=>t.annotationId)).filter(Boolean)),d=new Set(a.map((t=>t.annotationId)).filter(Boolean)),l=Array.from(d).filter((t=>!s.has(t)));for(const t of l)t&&S(n,t);const u=Z.get(t);u&&(u.previousFilteredAnnotations=i),((t,n)=>{var e;for(const o of n){const n=null===(e=null==o?void 0:o.context)||void 0===e?void 0:e.textEditorConfig;if(!(null==n?void 0:n.text)||!o.annotationId)continue;const r=n.text,c=n.occurrence||1,i=n.targetTextNodeId;$(t,r,c,o.annotationId,o.multiThreadAnnotationId,i)}})(n,i)}catch(t){y.catch("[commentRenderer:updateComments] Error updating comments:",t)}},nt=(t,n)=>{const e="[commentRenderer:updateSelection]";try{const n=Z.get(t);if(!n||!n.editor)return void y.warn(`${e} No editor found for editorId: ${t}`);const o=(t=>{try{const n=L.get(t);return n?[...n.commentAnnotations]:[]}catch(t){return y.catch("Error getting comment annotations:",t),[]}})(t);tt(t,n.editor,o)}catch(t){y.catch(`${e} Error updating selection:`,t)}},et=new Map,ot=({editor:t,editorId:n,commentAnnotations:e})=>{const o="[renderComments]";try{if(!t)return void y.warn(`${o} No editor provided`);e&&Array.isArray(e)||(e=[]);const{editorId:r}=C(n,t),c=JSON.parse(JSON.stringify(e)).filter((t=>{var n;if(!(null===(n=null==t?void 0:t.context)||void 0===n?void 0:n.textEditorConfig))return!1;const e=t.context.textEditorConfig.editorId;return r===h?void 0===e||e===h:e===r}));if(j(r,c),!et.has(r)){const t=r,n=((t,n)=>{try{return J.set(n,t),B||U(),()=>{J.delete(n)}}catch(t){return y.catch("[VeltAdapter] Error subscribing to selected annotations:",t),()=>{}}})((n=>{((t,n)=>{try{H(t).selectedAnnotations=new Set(n)}catch(t){y.catch("Error setting selected annotations:",t)}})(t,n),nt(t)}),t);et.set(r,n)}B||U(),tt(r,t,c)}catch(t){y.catch(`${o} Error rendering comments:`,t)}},rt=l.VELT_COMMENT,ct=t=>{const n=it(t);return dt(n)},it=t=>at(t),at=t=>{const n=[];for(const e of t)if(ft(e)&&e.type===rt){const t=at(e.children);n.push(...t)}else n.push(st(e));return n},st=t=>{if(ft(t)){const n=at(t.children);return Object.assign(Object.assign({},t),{children:n})}return t},dt=t=>{const n=t.map(lt);return ut(n)},lt=t=>{if(ft(t)){const n=t.children.map(lt);return Object.assign(Object.assign({},t),{children:ut(n)})}return t},ut=t=>{var n,e;if(t.length<2)return t;const o=[];let r=0;for(;r<t.length;){const c=t[r];if(ht(c)){if(""===c.text){r++;continue}let i=null!==(n=c.text)&&void 0!==n?n:"",a=r+1;for(;a<t.length;){const n=t[a];if(ht(n)&&""===n.text)a++;else{if(!ht(n)||!gt(c,n))break;i+=null!==(e=n.text)&&void 0!==e?e:"",a++}}o.push(Object.assign(Object.assign({},c),{text:i})),r=a}else o.push(c),r++}return o.length>0?o:[{text:""}]},ft=t=>Object.prototype.hasOwnProperty.call(t,"children")&&Object.prototype.hasOwnProperty.call(t,"type"),ht=t=>Object.prototype.hasOwnProperty.call(t,"text"),gt=(t,n)=>t.bold===n.bold&&t.italic===n.italic&&t.underline===n.underline,pt=t=>{const{attributes:n,children:e,element:o}=t,r=null==o?void 0:o.annotationId;return s.createElement("velt-comment-text",Object.assign({[d.ANNOTATION_ID]:r},n),e)};export{pt as SlateVeltComment,Y as addComment,ct as exportJSONWithoutComments,ot as renderComments,W as withVeltComments};
2
2
  //# sourceMappingURL=index.js.map