@alpaca-editor/core 1.0.3942 → 1.0.3943

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 (308) hide show
  1. package/.prettierrc +3 -0
  2. package/build.css +3 -0
  3. package/components.json +21 -0
  4. package/dist/editor/ContentTree.d.ts +2 -1
  5. package/dist/editor/ContentTree.js +23 -21
  6. package/dist/editor/ContentTree.js.map +1 -1
  7. package/dist/editor/FieldActionsOverlay.js +0 -2
  8. package/dist/editor/FieldActionsOverlay.js.map +1 -1
  9. package/dist/editor/ScrollingContentTree.js +1 -1
  10. package/dist/editor/ScrollingContentTree.js.map +1 -1
  11. package/dist/editor/Titlebar.js +1 -1
  12. package/dist/editor/Titlebar.js.map +1 -1
  13. package/dist/editor/ai/GhostWriter.js +24 -3
  14. package/dist/editor/ai/GhostWriter.js.map +1 -1
  15. package/dist/editor/client/EditorClient.js +7 -7
  16. package/dist/editor/client/EditorClient.js.map +1 -1
  17. package/dist/editor/field-types/InternalLinkFieldEditor.js +60 -10
  18. package/dist/editor/field-types/InternalLinkFieldEditor.js.map +1 -1
  19. package/dist/editor/media-selector/MediaFolderBrowser.js +48 -1
  20. package/dist/editor/media-selector/MediaFolderBrowser.js.map +1 -1
  21. package/dist/editor/menubar/PageSelector.js +116 -65
  22. package/dist/editor/menubar/PageSelector.js.map +1 -1
  23. package/dist/editor/page-viewer/EditorForm.js +5 -2
  24. package/dist/editor/page-viewer/EditorForm.js.map +1 -1
  25. package/dist/editor/ui/ItemSearch.js +14 -8
  26. package/dist/editor/ui/ItemSearch.js.map +1 -1
  27. package/dist/editor/ui/PerfectTree.d.ts +4 -2
  28. package/dist/editor/ui/PerfectTree.js +78 -4
  29. package/dist/editor/ui/PerfectTree.js.map +1 -1
  30. package/dist/editor/ui/Splitter.js +1 -1
  31. package/dist/revision.d.ts +2 -2
  32. package/dist/revision.js +2 -2
  33. package/dist/styles.css +8 -2
  34. package/eslint.config.mjs +4 -0
  35. package/images/bg-shape-black.webp +0 -0
  36. package/images/wizard-bg.png +0 -0
  37. package/images/wizard-tour.png +0 -0
  38. package/images/wizard.png +0 -0
  39. package/package.json +2 -8
  40. package/src/client-components/api.ts +6 -0
  41. package/src/client-components/index.ts +19 -0
  42. package/src/components/ActionButton.tsx +50 -0
  43. package/src/components/Error.tsx +57 -0
  44. package/src/components/ui/CardConnector.tsx +56 -0
  45. package/src/components/ui/button.tsx +62 -0
  46. package/src/components/ui/card.tsx +372 -0
  47. package/src/components/ui/context-menu.tsx +250 -0
  48. package/src/config/config.tsx +917 -0
  49. package/src/config/types.ts +286 -0
  50. package/src/editor/ComponentInfo.tsx +90 -0
  51. package/src/editor/ConfirmationDialog.tsx +103 -0
  52. package/src/editor/ContentTree.tsx +733 -0
  53. package/src/editor/ContextMenu.tsx +230 -0
  54. package/src/editor/Editor.tsx +90 -0
  55. package/src/editor/EditorWarning.tsx +34 -0
  56. package/src/editor/EditorWarnings.tsx +33 -0
  57. package/src/editor/FieldActionsOverlay.tsx +296 -0
  58. package/src/editor/FieldEditorPopup.tsx +65 -0
  59. package/src/editor/FieldHistory.tsx +75 -0
  60. package/src/editor/FieldList.tsx +190 -0
  61. package/src/editor/FieldListField.tsx +391 -0
  62. package/src/editor/FieldListFieldWithFallbacks.tsx +217 -0
  63. package/src/editor/FloatingToolbar.tsx +163 -0
  64. package/src/editor/ImageEditor.tsx +128 -0
  65. package/src/editor/ItemInfo.tsx +90 -0
  66. package/src/editor/LinkEditorDialog.tsx +196 -0
  67. package/src/editor/MainLayout.tsx +95 -0
  68. package/src/editor/MobileLayout.tsx +68 -0
  69. package/src/editor/NewEditorClient.tsx +11 -0
  70. package/src/editor/PictureCropper.tsx +568 -0
  71. package/src/editor/PictureEditor.tsx +301 -0
  72. package/src/editor/PictureEditorDialog.tsx +381 -0
  73. package/src/editor/PublishDialog.ignore +74 -0
  74. package/src/editor/ScrollingContentTree.tsx +68 -0
  75. package/src/editor/Terminal.tsx +227 -0
  76. package/src/editor/Titlebar.tsx +104 -0
  77. package/src/editor/ai/AiPopup.tsx +59 -0
  78. package/src/editor/ai/AiResponseMessage.tsx +106 -0
  79. package/src/editor/ai/AiTerminal.tsx +503 -0
  80. package/src/editor/ai/AiToolCall.tsx +61 -0
  81. package/src/editor/ai/EditorAiTerminal.tsx +20 -0
  82. package/src/editor/ai/GhostWriter.tsx +480 -0
  83. package/src/editor/ai/aiPageModel.ts +108 -0
  84. package/src/editor/ai/editorAiContext.ts +18 -0
  85. package/src/editor/client/AboutDialog.tsx +44 -0
  86. package/src/editor/client/EditorClient.tsx +2241 -0
  87. package/src/editor/client/GenericDialog.tsx +50 -0
  88. package/src/editor/client/editContext.ts +416 -0
  89. package/src/editor/client/helpers.ts +44 -0
  90. package/src/editor/client/itemsRepository.ts +574 -0
  91. package/src/editor/client/operations.ts +768 -0
  92. package/src/editor/client/pageModelBuilder.ts +219 -0
  93. package/src/editor/commands/commands.ts +22 -0
  94. package/src/editor/commands/componentCommands.tsx +431 -0
  95. package/src/editor/commands/createVersionCommand.ts +33 -0
  96. package/src/editor/commands/deleteVersionCommand.ts +71 -0
  97. package/src/editor/commands/itemCommands.tsx +351 -0
  98. package/src/editor/commands/localizeItem/LocalizeItemDialog.tsx +201 -0
  99. package/src/editor/commands/localizeItem/LocalizeItemUtils.ts +27 -0
  100. package/src/editor/commands/undo.ts +39 -0
  101. package/src/editor/component-designer/ComponentDesigner.tsx +70 -0
  102. package/src/editor/component-designer/ComponentDesignerAiTerminal.tsx +11 -0
  103. package/src/editor/component-designer/ComponentDesignerMenu.tsx +91 -0
  104. package/src/editor/component-designer/ComponentEditor.tsx +97 -0
  105. package/src/editor/component-designer/ComponentRenderingCodeEditor.tsx +31 -0
  106. package/src/editor/component-designer/ComponentRenderingEditor.tsx +104 -0
  107. package/src/editor/component-designer/ComponentsDropdown.tsx +39 -0
  108. package/src/editor/component-designer/PlaceholdersEditor.tsx +179 -0
  109. package/src/editor/component-designer/RenderingsDropdown.tsx +36 -0
  110. package/src/editor/component-designer/TemplateEditor.tsx +236 -0
  111. package/src/editor/component-designer/aiContext.ts +23 -0
  112. package/src/editor/componentTreeHelper.tsx +116 -0
  113. package/src/editor/context-menu/CopyMoveMenu.tsx +103 -0
  114. package/src/editor/context-menu/InsertMenu.tsx +347 -0
  115. package/src/editor/control-center/About.tsx +342 -0
  116. package/src/editor/control-center/ControlCenterMenu.tsx +76 -0
  117. package/src/editor/control-center/IndexOverview.tsx +50 -0
  118. package/src/editor/control-center/IndexSettings.tsx +266 -0
  119. package/src/editor/control-center/Info.tsx +104 -0
  120. package/src/editor/control-center/QuotaInfo.tsx +301 -0
  121. package/src/editor/control-center/Status.tsx +113 -0
  122. package/src/editor/control-center/WebSocketMessages.tsx +155 -0
  123. package/src/editor/editor-warnings/ItemLocked.tsx +63 -0
  124. package/src/editor/editor-warnings/NoLanguageWriteAccess.tsx +22 -0
  125. package/src/editor/editor-warnings/NoWorkflowWriteAccess.tsx +23 -0
  126. package/src/editor/editor-warnings/NoWriteAccess.tsx +16 -0
  127. package/src/editor/editor-warnings/ValidationErrors.tsx +54 -0
  128. package/src/editor/field-types/AttachmentEditor.tsx +9 -0
  129. package/src/editor/field-types/CheckboxEditor.tsx +47 -0
  130. package/src/editor/field-types/DropLinkEditor.tsx +80 -0
  131. package/src/editor/field-types/DropListEditor.tsx +84 -0
  132. package/src/editor/field-types/ImageFieldEditor.tsx +65 -0
  133. package/src/editor/field-types/InternalLinkFieldEditor.tsx +188 -0
  134. package/src/editor/field-types/LinkFieldEditor.tsx +85 -0
  135. package/src/editor/field-types/MultiLineText.tsx +82 -0
  136. package/src/editor/field-types/PictureFieldEditor.tsx +121 -0
  137. package/src/editor/field-types/RawEditor.tsx +53 -0
  138. package/src/editor/field-types/ReactQuill.tsx +580 -0
  139. package/src/editor/field-types/RichTextEditor.tsx +22 -0
  140. package/src/editor/field-types/RichTextEditorComponent.tsx +127 -0
  141. package/src/editor/field-types/SingleLineText.tsx +174 -0
  142. package/src/editor/field-types/TreeListEditor.tsx +261 -0
  143. package/src/editor/fieldTypes.ts +140 -0
  144. package/src/editor/media-selector/AiImageSearch.tsx +185 -0
  145. package/src/editor/media-selector/AiImageSearchPrompt.tsx +94 -0
  146. package/src/editor/media-selector/MediaFolderBrowser.tsx +321 -0
  147. package/src/editor/media-selector/MediaSelector.tsx +42 -0
  148. package/src/editor/media-selector/Preview.tsx +14 -0
  149. package/src/editor/media-selector/Thumbnails.tsx +48 -0
  150. package/src/editor/media-selector/TreeSelector.tsx +292 -0
  151. package/src/editor/media-selector/UploadZone.tsx +137 -0
  152. package/src/editor/media-selector/index.ts +8 -0
  153. package/src/editor/menubar/ActionsMenu.tsx +94 -0
  154. package/src/editor/menubar/ActiveUsers.tsx +17 -0
  155. package/src/editor/menubar/ApproveAndPublish.tsx +18 -0
  156. package/src/editor/menubar/BrowseHistory.tsx +28 -0
  157. package/src/editor/menubar/ItemLanguageVersion.tsx +76 -0
  158. package/src/editor/menubar/LanguageSelector.tsx +226 -0
  159. package/src/editor/menubar/Menu.tsx +83 -0
  160. package/src/editor/menubar/NavButtons.tsx +74 -0
  161. package/src/editor/menubar/PageSelector.tsx +278 -0
  162. package/src/editor/menubar/PageViewerControls.tsx +120 -0
  163. package/src/editor/menubar/PreviewSecondaryControls.tsx +18 -0
  164. package/src/editor/menubar/SecondaryControls.tsx +45 -0
  165. package/src/editor/menubar/Separator.tsx +12 -0
  166. package/src/editor/menubar/SiteInfo.tsx +53 -0
  167. package/src/editor/menubar/User.tsx +27 -0
  168. package/src/editor/menubar/VersionSelector.tsx +142 -0
  169. package/src/editor/page-editor-chrome/CommentHighlighting.tsx +307 -0
  170. package/src/editor/page-editor-chrome/CommentHighlightings.tsx +35 -0
  171. package/src/editor/page-editor-chrome/FieldActionIndicator.tsx +59 -0
  172. package/src/editor/page-editor-chrome/FieldActionIndicators.tsx +23 -0
  173. package/src/editor/page-editor-chrome/FieldEditedIndicator.tsx +64 -0
  174. package/src/editor/page-editor-chrome/FieldEditedIndicators.tsx +35 -0
  175. package/src/editor/page-editor-chrome/FrameMenu.tsx +338 -0
  176. package/src/editor/page-editor-chrome/FrameMenus.tsx +48 -0
  177. package/src/editor/page-editor-chrome/InlineEditor.tsx +765 -0
  178. package/src/editor/page-editor-chrome/LockedFieldIndicator.tsx +61 -0
  179. package/src/editor/page-editor-chrome/NoLayout.tsx +36 -0
  180. package/src/editor/page-editor-chrome/PageEditorChrome.tsx +122 -0
  181. package/src/editor/page-editor-chrome/PictureEditorOverlay.tsx +161 -0
  182. package/src/editor/page-editor-chrome/PlaceholderDropZone.tsx +169 -0
  183. package/src/editor/page-editor-chrome/PlaceholderDropZones.tsx +315 -0
  184. package/src/editor/page-editor-chrome/SuggestionHighlighting.tsx +300 -0
  185. package/src/editor/page-editor-chrome/SuggestionHighlightings.tsx +40 -0
  186. package/src/editor/page-editor-chrome/useInlineAICompletion.tsx +828 -0
  187. package/src/editor/page-viewer/DeviceToolbar.tsx +70 -0
  188. package/src/editor/page-viewer/EditorForm.tsx +262 -0
  189. package/src/editor/page-viewer/MiniMap.tsx +362 -0
  190. package/src/editor/page-viewer/PageViewer.tsx +169 -0
  191. package/src/editor/page-viewer/PageViewerFrame.tsx +1022 -0
  192. package/src/editor/page-viewer/pageModelSkeletonBuilder.ts +412 -0
  193. package/src/editor/page-viewer/pageViewContext.ts +186 -0
  194. package/src/editor/pageModel.ts +220 -0
  195. package/src/editor/picture-shared.tsx +53 -0
  196. package/src/editor/reviews/Comment.tsx +308 -0
  197. package/src/editor/reviews/Comments.tsx +125 -0
  198. package/src/editor/reviews/DiffView.tsx +109 -0
  199. package/src/editor/reviews/PreviewInfo.tsx +35 -0
  200. package/src/editor/reviews/Reviews.tsx +280 -0
  201. package/src/editor/reviews/SuggestedEdit.tsx +316 -0
  202. package/src/editor/reviews/reviewCommands.tsx +47 -0
  203. package/src/editor/reviews/useReviews.tsx +70 -0
  204. package/src/editor/services/aiService.ts +173 -0
  205. package/src/editor/services/componentDesignerService.ts +151 -0
  206. package/src/editor/services/contentService.ts +180 -0
  207. package/src/editor/services/editService.ts +488 -0
  208. package/src/editor/services/indexService.ts +24 -0
  209. package/src/editor/services/reviewsService.ts +53 -0
  210. package/src/editor/services/serviceHelper.ts +95 -0
  211. package/src/editor/services/suggestedEditsService.ts +39 -0
  212. package/src/editor/services/systemService.ts +5 -0
  213. package/src/editor/services/translationService.ts +21 -0
  214. package/src/editor/services-server/api.ts +150 -0
  215. package/src/editor/services-server/graphQL.ts +106 -0
  216. package/src/editor/sidebar/ComponentPalette.tsx +161 -0
  217. package/src/editor/sidebar/ComponentTree.tsx +549 -0
  218. package/src/editor/sidebar/Debug.tsx +111 -0
  219. package/src/editor/sidebar/DictionaryEditor.tsx +261 -0
  220. package/src/editor/sidebar/EditHistory.tsx +134 -0
  221. package/src/editor/sidebar/GraphQL.tsx +164 -0
  222. package/src/editor/sidebar/Insert.tsx +35 -0
  223. package/src/editor/sidebar/MainContentTree.tsx +102 -0
  224. package/src/editor/sidebar/Performance.tsx +53 -0
  225. package/src/editor/sidebar/Sessions.tsx +35 -0
  226. package/src/editor/sidebar/Sidebar.tsx +20 -0
  227. package/src/editor/sidebar/SidebarView.tsx +152 -0
  228. package/src/editor/sidebar/Translations.tsx +295 -0
  229. package/src/editor/sidebar/Validation.tsx +102 -0
  230. package/src/editor/sidebar/ViewSelector.tsx +60 -0
  231. package/src/editor/sidebar/Workbox.tsx +209 -0
  232. package/src/editor/ui/CenteredMessage.tsx +7 -0
  233. package/src/editor/ui/CopyMoveTargetSelectorDialog.tsx +81 -0
  234. package/src/editor/ui/CopyToClipboardButton.tsx +24 -0
  235. package/src/editor/ui/DialogButtons.tsx +11 -0
  236. package/src/editor/ui/Icons.tsx +709 -0
  237. package/src/editor/ui/ItemList.tsx +76 -0
  238. package/src/editor/ui/ItemNameDialogNew.tsx +118 -0
  239. package/src/editor/ui/ItemSearch.tsx +159 -0
  240. package/src/editor/ui/PerfectTree.tsx +676 -0
  241. package/src/editor/ui/Section.tsx +35 -0
  242. package/src/editor/ui/SimpleIconButton.tsx +54 -0
  243. package/src/editor/ui/SimpleMenu.tsx +40 -0
  244. package/src/editor/ui/SimpleTable.tsx +60 -0
  245. package/src/editor/ui/SimpleTabs.tsx +60 -0
  246. package/src/editor/ui/SimpleToolbar.tsx +7 -0
  247. package/src/editor/ui/Spinner.tsx +9 -0
  248. package/src/editor/ui/Splitter.tsx +420 -0
  249. package/src/editor/ui/StackedPanels.tsx +134 -0
  250. package/src/editor/ui/Toolbar.tsx +7 -0
  251. package/src/editor/utils/id-helper.ts +3 -0
  252. package/src/editor/utils/insertOptions.ts +69 -0
  253. package/src/editor/utils/itemutils.ts +29 -0
  254. package/src/editor/utils/useMemoDebug.ts +28 -0
  255. package/src/editor/utils.ts +486 -0
  256. package/src/editor/views/CompareView.tsx +245 -0
  257. package/src/editor/views/EditView.tsx +27 -0
  258. package/src/editor/views/ItemEditor.tsx +58 -0
  259. package/src/editor/views/MediaFolderEditView.tsx +66 -0
  260. package/src/editor/views/SingleEditView.tsx +57 -0
  261. package/src/fonts/Geist-Black.woff2 +0 -0
  262. package/src/fonts/Geist-Bold.woff2 +0 -0
  263. package/src/fonts/Geist-ExtraBold.woff2 +0 -0
  264. package/src/fonts/Geist-ExtraLight.woff2 +0 -0
  265. package/src/fonts/Geist-Light.woff2 +0 -0
  266. package/src/fonts/Geist-Medium.woff2 +0 -0
  267. package/src/fonts/Geist-Regular.woff2 +0 -0
  268. package/src/fonts/Geist-SemiBold.woff2 +0 -0
  269. package/src/fonts/Geist-Thin.woff2 +0 -0
  270. package/src/fonts/Geist[wght].woff2 +0 -0
  271. package/src/fonts/index.ts +10 -0
  272. package/src/index.ts +23 -0
  273. package/src/lib/safelist.tsx +16 -0
  274. package/src/lib/utils.ts +6 -0
  275. package/src/page-wizard/PageWizard.tsx +139 -0
  276. package/src/page-wizard/WizardBox.tsx +4 -0
  277. package/src/page-wizard/WizardBoxConnector.tsx +56 -0
  278. package/src/page-wizard/WizardSteps.tsx +458 -0
  279. package/src/page-wizard/service.ts +35 -0
  280. package/src/page-wizard/startPageWizardCommand.ts +26 -0
  281. package/src/page-wizard/steps/BuildPageStep.tsx +259 -0
  282. package/src/page-wizard/steps/CollectStep.tsx +296 -0
  283. package/src/page-wizard/steps/ComponentTypesSelector.tsx +454 -0
  284. package/src/page-wizard/steps/Components.tsx +193 -0
  285. package/src/page-wizard/steps/ContentStep.tsx +890 -0
  286. package/src/page-wizard/steps/EditButton.tsx +34 -0
  287. package/src/page-wizard/steps/FieldEditor.tsx +102 -0
  288. package/src/page-wizard/steps/Generate.tsx +60 -0
  289. package/src/page-wizard/steps/ImagesStep.tsx +382 -0
  290. package/src/page-wizard/steps/LayoutStep.tsx +227 -0
  291. package/src/page-wizard/steps/MetaDataStep.tsx +173 -0
  292. package/src/page-wizard/steps/SelectStep.tsx +281 -0
  293. package/src/page-wizard/steps/schema.ts +180 -0
  294. package/src/page-wizard/steps/usePageCreator.ts +325 -0
  295. package/src/page-wizard/usePageWizard.ts +79 -0
  296. package/src/revision.ts +2 -0
  297. package/src/splash-screen/NewPage.tsx +294 -0
  298. package/src/splash-screen/OpenPage.tsx +113 -0
  299. package/src/splash-screen/RecentPages.tsx +123 -0
  300. package/src/splash-screen/SectionHeadline.tsx +21 -0
  301. package/src/splash-screen/SplashScreen.tsx +195 -0
  302. package/src/tour/Tour.tsx +566 -0
  303. package/src/tour/default-tour.tsx +301 -0
  304. package/src/tour/preview-tour.tsx +128 -0
  305. package/src/types.ts +335 -0
  306. package/styles.css +765 -0
  307. package/tsconfig.build.json +31 -0
  308. package/tsconfig.json +14 -0
@@ -0,0 +1,828 @@
1
+ import {
2
+ useEffect,
3
+ useCallback,
4
+ useState,
5
+ useMemo,
6
+ useRef,
7
+ MutableRefObject,
8
+ } from "react";
9
+ import { useDebouncedCallback } from "use-debounce";
10
+ import { PageViewContext } from "../page-viewer/pageViewContext";
11
+ import { useEditContext } from "../client/editContext";
12
+ import { executePrompt } from "../services/aiService";
13
+
14
+ export function useInlineAiCompletion({
15
+ pageViewContext,
16
+ cursorSpanId,
17
+ isUpdatingRef,
18
+ }: {
19
+ pageViewContext: PageViewContext;
20
+ cursorSpanId: string;
21
+ isUpdatingRef: MutableRefObject<boolean>;
22
+ }) {
23
+ const editContext = useEditContext();
24
+ const [currentCompletion, setCurrentCompletion] = useState<string | null>(
25
+ null,
26
+ );
27
+ const [isLoading, setIsLoading] = useState(false);
28
+ const abortControllerRef = useRef<AbortController | null>(null);
29
+ const loadingAnimationRef = useRef<number | null>(null);
30
+
31
+ // Clean up hint element on unmount
32
+ useEffect(() => {
33
+ return () => {
34
+ const hintElement = document.getElementById(`${cursorSpanId}-hint`);
35
+ if (hintElement) {
36
+ hintElement.remove();
37
+ }
38
+
39
+ if (loadingAnimationRef.current) {
40
+ cancelAnimationFrame(loadingAnimationRef.current);
41
+ }
42
+ };
43
+ }, [cursorSpanId]);
44
+
45
+ const lastCaretPosRef = useRef<{
46
+ node: Node | null;
47
+ offset: number;
48
+ textLength?: number;
49
+ } | null>(null);
50
+
51
+ // Simple function to track caret position without inserting spans
52
+ const positionCursorSpan = () => {
53
+ if (isUpdatingRef.current) return;
54
+ isUpdatingRef.current = true;
55
+
56
+ try {
57
+ const iframeWindow =
58
+ pageViewContext.editorIframeRef.current?.contentWindow;
59
+ const iframeDocument = iframeWindow?.document;
60
+ const editableElement = editContext?.inlineEditingFieldElement;
61
+
62
+ if (!iframeWindow || !iframeDocument || !editableElement) return;
63
+
64
+ // Get current selection
65
+ const selection = iframeWindow.getSelection();
66
+ if (!selection || selection.rangeCount === 0) return;
67
+
68
+ const range = selection.getRangeAt(0);
69
+
70
+ // Only proceed if selection is within our editing element
71
+ if (!editableElement.contains(range.commonAncestorContainer)) return;
72
+
73
+ // Save detailed information about the cursor position
74
+ const currentNode = range.startContainer;
75
+ const currentOffset = range.startOffset;
76
+
77
+ // Create a temporary range to get text up to cursor
78
+ const tempRange = document.createRange();
79
+ tempRange.selectNodeContents(editableElement);
80
+ tempRange.setEnd(currentNode, currentOffset);
81
+ const textUpToCursor = tempRange.toString();
82
+
83
+ // Check if cursor position has changed
84
+ const cursorMoved =
85
+ !lastCaretPosRef.current ||
86
+ lastCaretPosRef.current.node !== currentNode ||
87
+ lastCaretPosRef.current.offset !== currentOffset ||
88
+ textUpToCursor.length !== (lastCaretPosRef.current.textLength || 0);
89
+
90
+ if (cursorMoved) {
91
+ // Reset completion if cursor position changed
92
+
93
+ lastCaretPosRef.current = {
94
+ node: currentNode,
95
+ offset: currentOffset,
96
+ textLength: textUpToCursor.length,
97
+ };
98
+ }
99
+
100
+ // Save a copy of the current range
101
+ const originalRange = range.cloneRange();
102
+
103
+ // Remove any existing cursor spans
104
+ const existingSpan = iframeDocument.getElementById(cursorSpanId);
105
+ if (existingSpan) {
106
+ existingSpan.parentNode?.removeChild(existingSpan);
107
+ }
108
+
109
+ // Create our cursor span
110
+ const cursorSpan = existingSpan ?? iframeDocument.createElement("span");
111
+ cursorSpan.id = cursorSpanId;
112
+
113
+ cursorSpan.style.fontWeight = "bold";
114
+ cursorSpan.style.display = "inline";
115
+ cursorSpan.style.pointerEvents = "none";
116
+ cursorSpan.contentEditable = "false";
117
+ cursorSpan.setAttribute("data-cursor-indicator", "true");
118
+
119
+ // Get a working range for insertion
120
+ const workingRange = range.cloneRange();
121
+ workingRange.collapse(true);
122
+
123
+ // Insert the span at cursor position
124
+ workingRange.insertNode(cursorSpan);
125
+
126
+ // Restore original selection
127
+ selection.removeAllRanges();
128
+ selection.addRange(originalRange);
129
+
130
+ // setTimeout(() => {
131
+ // getCompletionDebounced();
132
+ // }, 100);
133
+ } catch (error) {
134
+ console.error("Error updating cursor:", error);
135
+ } finally {
136
+ setTimeout(() => {
137
+ isUpdatingRef.current = false;
138
+ }, 10);
139
+ }
140
+ };
141
+
142
+ useEffect(() => {
143
+ // Handle keydown events - especially for cursor movement
144
+ const keyHandler = (e: KeyboardEvent) => {
145
+ if (
146
+ e.key === "ArrowLeft" ||
147
+ e.key === "ArrowRight" ||
148
+ e.key === "ArrowUp" ||
149
+ e.key === "ArrowDown" ||
150
+ e.key === " " ||
151
+ e.key === "Tab" ||
152
+ e.key === "End" ||
153
+ e.key === "Backspace" ||
154
+ e.key === "Delete" // Add Delete key handling
155
+ ) {
156
+ // Clear the completion when arrow keys are used
157
+ setCurrentCompletion(null);
158
+ clearCursorSpan();
159
+
160
+ // Let the browser handle the cursor movement/deletion
161
+ // Then update our cursor span after a small delay
162
+ setTimeout(() => {
163
+ if (!isUpdatingRef.current) {
164
+ positionCursorSpan();
165
+ }
166
+ }, 10);
167
+
168
+ // Special handling for right arrow and delete which seems to have issues
169
+ if (e.key === "ArrowRight" || e.key === "Delete") {
170
+ // Make sure the cursor span doesn't block the movement/deletion
171
+ const cursorSpan =
172
+ pageViewContext.editorIframeRef.current?.contentWindow?.document.getElementById(
173
+ cursorSpanId,
174
+ );
175
+ if (cursorSpan) {
176
+ // Temporarily make it display none so it doesn't interfere with selection
177
+ const originalDisplay = cursorSpan.style.display;
178
+ cursorSpan.style.display = "none";
179
+
180
+ // Restore after the browser has processed the movement/deletion
181
+ setTimeout(() => {
182
+ if (cursorSpan.parentNode) {
183
+ cursorSpan.style.display = originalDisplay;
184
+ }
185
+ }, 0);
186
+ }
187
+ }
188
+ }
189
+ };
190
+
191
+ pageViewContext.editorIframeRef.current?.contentWindow?.document.addEventListener(
192
+ "keydown",
193
+ keyHandler,
194
+ );
195
+ return () => {
196
+ pageViewContext.editorIframeRef.current?.contentWindow?.document.removeEventListener(
197
+ "keydown",
198
+ keyHandler,
199
+ );
200
+ };
201
+ }, [currentCompletion, pageViewContext.page]);
202
+
203
+ // Extracts the text up to the cursor position in the editable element
204
+ const getContentUpToCursor = (element: HTMLElement) => {
205
+ const iframeWindow = pageViewContext.editorIframeRef.current?.contentWindow;
206
+ const selection = iframeWindow?.getSelection();
207
+ if (!element || !selection || selection.rangeCount === 0) return null;
208
+ const range = selection.getRangeAt(0);
209
+ const cursorPosition = range.startOffset;
210
+ let contentUpToCursor = "";
211
+ if (element.childNodes.length === 0) {
212
+ contentUpToCursor = "";
213
+ } else if (
214
+ element.childNodes.length === 1 &&
215
+ element.firstChild?.nodeType === Node.TEXT_NODE
216
+ ) {
217
+ const full = element.innerText || "";
218
+ contentUpToCursor = full.substring(
219
+ 0,
220
+ Math.min(cursorPosition, full.length),
221
+ );
222
+ } else {
223
+ const tempRange = document.createRange();
224
+ tempRange.selectNodeContents(element);
225
+ tempRange.setEnd(range.startContainer, range.startOffset);
226
+ contentUpToCursor = tempRange.toString();
227
+ }
228
+ return contentUpToCursor;
229
+ };
230
+
231
+ // Loading animation with three dots changing color
232
+ const startLoadingAnimation = () => {
233
+ const doc =
234
+ pageViewContext.editorIframeRef.current?.contentWindow?.document;
235
+ const span = doc?.getElementById(cursorSpanId);
236
+ if (!doc || !span) return;
237
+
238
+ // Create dots container
239
+ span.innerHTML = "";
240
+ span.style.display = "inline-flex";
241
+ span.style.gap = "4px";
242
+ span.style.alignItems = "center";
243
+
244
+ // Create three dots
245
+ for (let i = 0; i < 3; i++) {
246
+ const dot = doc.createElement("span");
247
+ dot.textContent = "•";
248
+ dot.style.transition = "color 0.3s ease";
249
+ dot.style.color = "#ccc";
250
+ dot.style.fontSize = "16px";
251
+ span.appendChild(dot);
252
+ }
253
+
254
+ // Animate dots
255
+ let step = 0;
256
+ const animate = () => {
257
+ const dots = span.querySelectorAll("span");
258
+ dots.forEach((dot, index) => {
259
+ if (index === step % 3) {
260
+ (dot as HTMLElement).style.color = "#666";
261
+ } else {
262
+ (dot as HTMLElement).style.color = "#ccc";
263
+ }
264
+ });
265
+ step++;
266
+ loadingAnimationRef.current = requestAnimationFrame(() => {
267
+ // Slow down animation by only updating every 15 frames (~250ms at 60fps)
268
+ if (step % 15 === 0) {
269
+ animate();
270
+ } else {
271
+ loadingAnimationRef.current = requestAnimationFrame(animate);
272
+ }
273
+ });
274
+ };
275
+
276
+ animate();
277
+ };
278
+
279
+ const stopLoadingAnimation = () => {
280
+ if (loadingAnimationRef.current) {
281
+ cancelAnimationFrame(loadingAnimationRef.current);
282
+ loadingAnimationRef.current = null;
283
+ }
284
+ };
285
+
286
+ const getCompletion = async (
287
+ element: HTMLElement,
288
+ isManualTrigger = false,
289
+ ) => {
290
+ const contentUpToCursor = getContentUpToCursor(element);
291
+ if (!contentUpToCursor?.trim()) return null;
292
+
293
+ // Abort any in-flight request
294
+ if (abortControllerRef.current) {
295
+ abortControllerRef.current.abort();
296
+ }
297
+
298
+ // Create a new abort controller for this request
299
+ abortControllerRef.current = new AbortController();
300
+ const signal = abortControllerRef.current.signal;
301
+
302
+ // Get field attributes
303
+ const fieldId = element.getAttribute("data-fieldid");
304
+ const fieldName = element.getAttribute("data-fieldname");
305
+ const itemId = element.getAttribute("data-itemid");
306
+ const language = element.getAttribute("data-language");
307
+ const version = element.getAttribute("data-version");
308
+ if (!fieldId || !itemId || !language || !version) return null;
309
+
310
+ // Only trigger completion after a space for automatic completions
311
+ // Manual triggers (Ctrl+Space) can work anywhere
312
+ if (!isManualTrigger) {
313
+ const lastChar = contentUpToCursor.slice(-1);
314
+ if (lastChar !== " " && lastChar !== "\u00A0") {
315
+ return null;
316
+ }
317
+ }
318
+
319
+ const messages = [
320
+ {
321
+ name: "system",
322
+ role: "system",
323
+ content:
324
+ "You are a sentence completion tool. ONLY provide the completion text (what comes after the user's text), never repeat any part of what the user wrote. Your completion should flow naturally from the user's text.",
325
+ },
326
+ {
327
+ name: "user",
328
+ role: "user",
329
+ content: `Complete this sentence. ONLY provide the completion (do not repeat my text): ${contentUpToCursor}`,
330
+ },
331
+ ];
332
+
333
+ if (!editContext) return null;
334
+
335
+ // Show loading indicator
336
+ setIsLoading(true);
337
+ startLoadingAnimation();
338
+
339
+ try {
340
+ const result = await executePrompt(
341
+ messages,
342
+ editContext,
343
+ () => ({
344
+ endpoint: "/alpaca/editor/ai/complete",
345
+ promptData: {
346
+ itemid: itemId,
347
+ language,
348
+ version,
349
+ fieldid: fieldId,
350
+ fieldname: fieldName,
351
+ content: contentUpToCursor,
352
+ },
353
+ }),
354
+ {},
355
+ { signal },
356
+ "gpt-4.1-nano",
357
+ );
358
+
359
+ return result;
360
+ } catch (error: unknown) {
361
+ // Ignore AbortError as it's expected when cancelling
362
+ if (error instanceof Error && error.name !== "AbortError") {
363
+ console.error("Error getting completion:", error);
364
+ }
365
+ return null;
366
+ } finally {
367
+ // Hide loading indicator
368
+ setIsLoading(false);
369
+ stopLoadingAnimation();
370
+ }
371
+ };
372
+
373
+ // Debounced AI call: recompute the sentence, call getCompletion, and extract only the "tail" for the ghost text
374
+ const getCompletionDebounced = useDebouncedCallback(
375
+ async (isManualTrigger = false) => {
376
+ const el = editContext?.inlineEditingFieldElement;
377
+ if (!el) return;
378
+
379
+ // 1) Recompute the exact sentence at this moment
380
+ const full = getContentUpToCursor(el) || "";
381
+ const sentence = full.split(/[.?!]\s*/).pop() || "";
382
+
383
+ // 2) Ask AI for a completion
384
+ const result = await getCompletion(el, isManualTrigger);
385
+ const rawSuggestion = result?.messages?.[0]?.content;
386
+ if (!rawSuggestion) {
387
+ setCurrentCompletion(null);
388
+ clearCursorSpan();
389
+ return;
390
+ }
391
+
392
+ // 3) Strip off the already-typed sentence to leave just the "completion tail"
393
+ const suggestion = rawSuggestion.startsWith(sentence)
394
+ ? rawSuggestion
395
+ : sentence + rawSuggestion;
396
+
397
+ setCurrentCompletion(suggestion);
398
+
399
+ updateCursorSpan(suggestion.substring(sentence.length));
400
+ },
401
+ 250,
402
+ );
403
+
404
+ // Manual completion trigger (non-debounced for immediate response)
405
+ const getCompletionManual = async () => {
406
+ const el = editContext?.inlineEditingFieldElement;
407
+ if (!el) return;
408
+
409
+ // 1) Recompute the exact sentence at this moment
410
+ const full = getContentUpToCursor(el) || "";
411
+ const sentence = full.split(/[.?!]\s*/).pop() || "";
412
+
413
+ // 2) Ask AI for a completion
414
+ const result = await getCompletion(el, true);
415
+ const rawSuggestion = result?.messages?.[0]?.content;
416
+ if (!rawSuggestion) {
417
+ setCurrentCompletion(null);
418
+ clearCursorSpan();
419
+ return;
420
+ }
421
+
422
+ // 3) Strip off the already-typed sentence to leave just the "completion tail"
423
+ const suggestion = rawSuggestion.startsWith(sentence)
424
+ ? rawSuggestion
425
+ : sentence + rawSuggestion;
426
+
427
+ setCurrentCompletion(suggestion);
428
+
429
+ updateCursorSpan(suggestion.substring(sentence.length));
430
+ };
431
+
432
+ // Inserts or clears the ghost text inside the cursor span
433
+ const updateCursorSpan = (text: string) => {
434
+ const doc =
435
+ pageViewContext.editorIframeRef.current?.contentWindow?.document;
436
+ const span = doc?.getElementById(cursorSpanId);
437
+ if (!doc || !span) return;
438
+
439
+ // Update the completion text
440
+ if (text) {
441
+ // // Create a temporary span to measure the text width
442
+ // const measureSpan = doc.createElement("span");
443
+ // measureSpan.style.visibility = "hidden";
444
+ // measureSpan.style.position = "absolute";
445
+ // measureSpan.style.whiteSpace = "pre"; // Preserve whitespace
446
+ // measureSpan.style.font = window.getComputedStyle(span).font; // Match the font
447
+ // measureSpan.textContent = text;
448
+ // doc.body.appendChild(measureSpan);
449
+ // const textWidth = measureSpan.getBoundingClientRect().width;
450
+ // measureSpan.remove();
451
+
452
+ span.textContent = text;
453
+ span.style.color = "#888";
454
+ span.style.fontStyle = "italic";
455
+ //span.innerHTML = "hello";
456
+
457
+ // Create or update hint element in the main document
458
+ let hintElement = document.getElementById(`${cursorSpanId}-hint`);
459
+ if (!hintElement) {
460
+ hintElement = document.createElement("div");
461
+ hintElement.id = `${cursorSpanId}-hint`;
462
+ document.body.appendChild(hintElement);
463
+ }
464
+
465
+ hintElement.textContent = "Press Tab to accept ⇥";
466
+
467
+ // Apply styles that match Tailwind's utility classes
468
+ Object.assign(hintElement.style, {
469
+ position: "fixed",
470
+ fontSize: "12px",
471
+ fontWeight: "normal",
472
+ color: "rgb(75, 85, 99)",
473
+ backgroundColor: "white",
474
+ padding: "0.5rem",
475
+ marginLeft: "0.25rem",
476
+ marginRight: "0.25rem",
477
+ borderRadius: "0.25rem",
478
+ border: "1px solid rgb(229, 231, 235)",
479
+ fontStyle: "normal",
480
+ display: "block",
481
+ lineHeight: "1.4",
482
+ zIndex: "9999",
483
+ pointerEvents: "none",
484
+ boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
485
+ });
486
+
487
+ // Position the hint element relative to the iframe and cursor span
488
+ const iframeRect =
489
+ pageViewContext.editorIframeRef.current?.getBoundingClientRect();
490
+ const spanRect = span.getBoundingClientRect();
491
+
492
+ if (iframeRect) {
493
+ // Create a range for the last character to get proper position
494
+ const textLength = span.textContent?.length || 0;
495
+ if (textLength > 0 && span.firstChild) {
496
+ const range = doc.createRange();
497
+ range.setStart(span.firstChild, Math.max(0, textLength - 1));
498
+ range.setEnd(span.firstChild, textLength);
499
+
500
+ const rangeRect = range.getBoundingClientRect();
501
+
502
+ // Position at the end of the actual text
503
+ const absoluteLeft = iframeRect.left + rangeRect.right;
504
+ const absoluteTop = iframeRect.top + rangeRect.top;
505
+
506
+ hintElement.style.left = `${absoluteLeft}px`;
507
+ hintElement.style.top = `${absoluteTop}px`;
508
+ } else {
509
+ // Fallback to the old positioning if there's no text
510
+ const absoluteLeft = iframeRect.left + spanRect.right;
511
+ const absoluteTop = iframeRect.top + spanRect.top;
512
+
513
+ hintElement.style.left = `${absoluteLeft}px`;
514
+ hintElement.style.top = `${absoluteTop}px`;
515
+ }
516
+ }
517
+ } else {
518
+ span.textContent = "";
519
+ // Remove hint element if it exists
520
+ const hintElement = document.getElementById(`${cursorSpanId}-hint`);
521
+ if (hintElement) {
522
+ hintElement.remove();
523
+ }
524
+ }
525
+ };
526
+
527
+ const clearCursorSpan = () => {
528
+ const doc =
529
+ pageViewContext.editorIframeRef.current?.contentWindow?.document;
530
+ if (!doc) return;
531
+
532
+ // Clear the completion text
533
+ updateCursorSpan("");
534
+ };
535
+
536
+ // On every input: either reuse the existing suggestion or fire a new one
537
+ const handleInput = useCallback(
538
+ (e: KeyboardEvent) => {
539
+ const el = editContext?.inlineEditingFieldElement;
540
+ if (!el) return;
541
+
542
+ // Clear completion when Escape is pressed
543
+ if (e.key === "Escape") {
544
+ e.preventDefault();
545
+ e.stopPropagation();
546
+ setCurrentCompletion(null);
547
+ clearCursorSpan();
548
+ return;
549
+ }
550
+
551
+ // Request new completion when Ctrl+Space is pressed
552
+ if (e.key === " " && (e.ctrlKey || e.metaKey)) {
553
+ e.preventDefault();
554
+ e.stopPropagation();
555
+ setCurrentCompletion(null);
556
+ clearCursorSpan();
557
+ getCompletionManual();
558
+ return;
559
+ }
560
+
561
+ // Apply completion when Tab is pressed
562
+ if (e.key === "Tab") {
563
+ // Check if there's an actual completion in the cursor span
564
+ const cursorSpan =
565
+ pageViewContext.editorIframeRef.current?.contentWindow?.document.getElementById(
566
+ cursorSpanId,
567
+ );
568
+ if (
569
+ cursorSpan &&
570
+ cursorSpan.textContent &&
571
+ cursorSpan.textContent.trim() !== ""
572
+ ) {
573
+ e.preventDefault();
574
+ e.stopPropagation();
575
+ applyCompletion();
576
+ return;
577
+ }
578
+ }
579
+
580
+ const full = getContentUpToCursor(el) || "";
581
+ const sentence = full.split(/[.?!]\s*/).pop() || "";
582
+
583
+ // If we already have a suggestion, check if the user is still typing along it
584
+ // Normalize spaces to handle both regular and non-breaking spaces
585
+ const normalizedSentence = sentence.replace(/\s/g, " ");
586
+ const normalizedCompletion = currentCompletion?.replace(/\s/g, " ");
587
+
588
+ if (
589
+ normalizedCompletion &&
590
+ normalizedCompletion.startsWith(normalizedSentence)
591
+ ) {
592
+ // user is still matching the suggestion → update the remaining tail
593
+ const remaining = normalizedCompletion.slice(normalizedSentence.length);
594
+
595
+ updateCursorSpan(remaining);
596
+ return;
597
+ }
598
+ // else: user diverged → drop it
599
+ setCurrentCompletion(null);
600
+ clearCursorSpan();
601
+
602
+ // No active suggestion → fire new request once they've typed 2+ words
603
+ const words = sentence.trim().split(/\s+/).filter(Boolean);
604
+
605
+ // Check if cursor is at the end of the text
606
+ const isAtEnd = () => {
607
+ const el = editContext?.inlineEditingFieldElement;
608
+ if (!el) return false;
609
+
610
+ const iframeWindow =
611
+ pageViewContext.editorIframeRef.current?.contentWindow;
612
+ const selection = iframeWindow?.getSelection();
613
+ if (!selection || selection.rangeCount === 0) return false;
614
+
615
+ const range = selection.getRangeAt(0);
616
+
617
+ // Create a range for the whole editable element
618
+ const fullRange = document.createRange();
619
+ fullRange.selectNodeContents(el);
620
+
621
+ // Get the full text content
622
+ const fullText = el.textContent || "";
623
+
624
+ // Get text up to cursor
625
+ const tempRange = document.createRange();
626
+ tempRange.selectNodeContents(el);
627
+ tempRange.setEnd(range.startContainer, range.startOffset);
628
+ const textUpToCursor = tempRange.toString();
629
+
630
+ // Cursor is at the end if the text up to cursor equals the full text
631
+ // (accounting for whitespace differences)
632
+ return (
633
+ textUpToCursor.trim() === fullText.trim() ||
634
+ (fullText.trim().startsWith(textUpToCursor.trim()) &&
635
+ fullText.trim().length === textUpToCursor.trim().length)
636
+ );
637
+ };
638
+
639
+ if (words.length >= 2 && isAtEnd()) {
640
+ getCompletionDebounced();
641
+ } else {
642
+ setCurrentCompletion(null);
643
+ clearCursorSpan();
644
+ }
645
+ },
646
+ [
647
+ editContext?.inlineEditingFieldElement,
648
+ currentCompletion,
649
+ getCompletionDebounced,
650
+ getCompletionManual,
651
+ ],
652
+ );
653
+
654
+ // Wire up the input listener
655
+ useEffect(() => {
656
+ if (!editContext?.enableCompletions) return;
657
+ const el = editContext?.inlineEditingFieldElement;
658
+ if (!el) return;
659
+ el.addEventListener("keydown", handleInput);
660
+ return () => el.removeEventListener("keydown", handleInput);
661
+ }, [
662
+ editContext?.inlineEditingFieldElement,
663
+ handleInput,
664
+ editContext?.enableCompletions,
665
+ ]);
666
+
667
+ // Add mouse click handler to update cursor span position
668
+ useEffect(() => {
669
+ if (!editContext?.enableCompletions) return;
670
+ const el = editContext?.inlineEditingFieldElement;
671
+ if (!el) return;
672
+
673
+ const handleMouseUp = () => {
674
+ setTimeout(() => {
675
+ if (!isUpdatingRef.current) {
676
+ positionCursorSpan();
677
+
678
+ // Clear existing completion when cursor position changes via mouse
679
+ setCurrentCompletion(null);
680
+ clearCursorSpan();
681
+ }
682
+ }, 10);
683
+ };
684
+
685
+ el.addEventListener("mouseup", handleMouseUp);
686
+ return () => el.removeEventListener("mouseup", handleMouseUp);
687
+ }, [editContext?.inlineEditingFieldElement, editContext?.enableCompletions]);
688
+
689
+ // Clean up abort controller on unmount
690
+ useEffect(() => {
691
+ return () => {
692
+ if (abortControllerRef.current) {
693
+ abortControllerRef.current.abort();
694
+ abortControllerRef.current = null;
695
+ }
696
+
697
+ if (loadingAnimationRef.current) {
698
+ cancelAnimationFrame(loadingAnimationRef.current);
699
+ loadingAnimationRef.current = null;
700
+ }
701
+ };
702
+ }, []);
703
+
704
+ // Function to apply the completion
705
+ const applyCompletion = () => {
706
+ // Get the cursor span to read the most up-to-date completion
707
+ const iframeWindow = pageViewContext.editorIframeRef.current?.contentWindow;
708
+ const iframeDocument = iframeWindow?.document;
709
+ if (
710
+ !iframeWindow ||
711
+ !iframeDocument ||
712
+ !editContext?.inlineEditingFieldElement
713
+ )
714
+ return;
715
+
716
+ const cursorSpan = iframeDocument.getElementById(cursorSpanId);
717
+ if (!cursorSpan) return;
718
+
719
+ // Get the completion text directly from the cursor span, which should be the most current
720
+ const completionToApply = cursorSpan.textContent || "";
721
+ if (!completionToApply) return;
722
+
723
+ const element = editContext?.inlineEditingFieldElement;
724
+
725
+ // Get the current selection position
726
+ const selection = iframeWindow.getSelection();
727
+ if (!selection || selection.rangeCount === 0) return;
728
+
729
+ // Get the text up to the cursor to analyze current word
730
+ const range = selection.getRangeAt(0);
731
+ const tempRange = document.createRange();
732
+ tempRange.selectNodeContents(element);
733
+ tempRange.setEnd(range.startContainer, range.startOffset);
734
+ const textUpToCursor = tempRange.toString();
735
+
736
+ // Get the current partial word by finding text from the last word boundary to cursor
737
+ // Look for last word boundary (space, punctuation, etc.)
738
+ const wordBoundaryRegex =
739
+ /[\s.,;:!?"'()[\]{}<>\/\\|=+\-*&^%$#@~`](?=[^\s.,;:!?"'()[\]{}<>\/\\|=+\-*&^%$#@~`]*$)/;
740
+ const match = textUpToCursor.match(wordBoundaryRegex);
741
+ const lastWordBoundaryIndex =
742
+ match && match.index !== undefined ? match.index + 1 : 0;
743
+
744
+ const currentPartialWord = textUpToCursor
745
+ .substring(lastWordBoundaryIndex)
746
+ .trim();
747
+
748
+ // Check if completion overlaps with current partial word
749
+ // (e.g., if user typed "int" and completion is "integer")
750
+ const isOverlapping =
751
+ currentPartialWord.length > 0 &&
752
+ completionToApply
753
+ .toLowerCase()
754
+ .startsWith(currentPartialWord.toLowerCase());
755
+
756
+ console.log("Is overlapping:", isOverlapping);
757
+
758
+ // If there's overlap, we need to delete the current partial word
759
+ if (isOverlapping) {
760
+ // Create a range to select the current partial word
761
+ const wordRange = document.createRange();
762
+
763
+ // Position where the current word starts
764
+ let startContainer = range.startContainer;
765
+ let startOffset = range.startOffset - currentPartialWord.length;
766
+
767
+ // We need to handle the case where the word spans multiple text nodes
768
+ // For simplicity, we'll try to handle the common case first
769
+ if (startOffset >= 0 && startContainer.nodeType === Node.TEXT_NODE) {
770
+ // Simple case: word is in the same text node as cursor
771
+ wordRange.setStart(startContainer, startOffset);
772
+ wordRange.setEnd(range.startContainer, range.startOffset);
773
+ wordRange.deleteContents(); // Delete the partial word
774
+ } else {
775
+ // Complex case: use a simpler approach - just insert, user can delete manually if needed
776
+ // This is a fallback for complex DOM structures
777
+ // Add a space if we're in the middle of a sentence
778
+ if (textUpToCursor.length > 0 && !textUpToCursor.endsWith(" ")) {
779
+ const spaceNode = document.createTextNode(" ");
780
+ range.insertNode(spaceNode);
781
+ range.setStartAfter(spaceNode);
782
+ range.setEndAfter(spaceNode);
783
+ }
784
+ }
785
+ } else {
786
+ // Not overlapping, add a space if we're in the middle of text
787
+ // and not already at the beginning of text or after a space
788
+ if (
789
+ textUpToCursor.length > 0 &&
790
+ !textUpToCursor.endsWith(" ") &&
791
+ // Don't add space at the start of a line or after punctuation that shouldn't have a space
792
+ !textUpToCursor.endsWith("\n") &&
793
+ !/[.!?\-—:;({[\s]$/.test(textUpToCursor)
794
+ ) {
795
+ const spaceNode = document.createTextNode(" ");
796
+ range.insertNode(spaceNode);
797
+ range.setStartAfter(spaceNode);
798
+ range.setEndAfter(spaceNode);
799
+ }
800
+ }
801
+
802
+ // Now insert the completion text
803
+ const textNode = document.createTextNode(
804
+ isOverlapping
805
+ ? completionToApply // If overlapping, use the full completion
806
+ : completionToApply, // If not overlapping, use as is
807
+ );
808
+ range.insertNode(textNode);
809
+
810
+ // Move the cursor after the inserted text
811
+ range.setStartAfter(textNode);
812
+ range.setEndAfter(textNode);
813
+ selection.removeAllRanges();
814
+ selection.addRange(range);
815
+ setCurrentCompletion(null);
816
+ clearCursorSpan();
817
+ };
818
+
819
+ // Exposed manual trigger (if needed)
820
+ return useMemo(
821
+ () => () => {
822
+ setCurrentCompletion(null);
823
+ clearCursorSpan();
824
+ getCompletionManual();
825
+ },
826
+ [getCompletionManual],
827
+ );
828
+ }