@alpaca-editor/core 1.0.3832 → 1.0.3835

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 (74) hide show
  1. package/dist/config/config.js +17 -0
  2. package/dist/config/config.js.map +1 -1
  3. package/dist/editor/ContentTree.js +0 -1
  4. package/dist/editor/ContentTree.js.map +1 -1
  5. package/dist/editor/ai/AiResponseMessage.d.ts +4 -5
  6. package/dist/editor/ai/AiResponseMessage.js +8 -6
  7. package/dist/editor/ai/AiResponseMessage.js.map +1 -1
  8. package/dist/editor/ai/AiTerminal.d.ts +13 -3
  9. package/dist/editor/ai/AiTerminal.js +107 -71
  10. package/dist/editor/ai/AiTerminal.js.map +1 -1
  11. package/dist/editor/ai/AiToolCall.d.ts +3 -7
  12. package/dist/editor/ai/AiToolCall.js +15 -3
  13. package/dist/editor/ai/AiToolCall.js.map +1 -1
  14. package/dist/editor/ai/GhostWriter.d.ts +1 -0
  15. package/dist/editor/ai/GhostWriter.js +307 -0
  16. package/dist/editor/ai/GhostWriter.js.map +1 -0
  17. package/dist/editor/client/EditorClient.js +3 -0
  18. package/dist/editor/client/EditorClient.js.map +1 -1
  19. package/dist/editor/client/editContext.d.ts +2 -0
  20. package/dist/editor/client/editContext.js.map +1 -1
  21. package/dist/editor/media-selector/AiImageSearch.js +2 -2
  22. package/dist/editor/media-selector/AiImageSearch.js.map +1 -1
  23. package/dist/editor/media-selector/AiImageSearchPrompt.js +2 -2
  24. package/dist/editor/media-selector/AiImageSearchPrompt.js.map +1 -1
  25. package/dist/editor/page-editor-chrome/FrameMenu.js +1 -1
  26. package/dist/editor/page-editor-chrome/FrameMenu.js.map +1 -1
  27. package/dist/editor/page-editor-chrome/InlineEditor.js +124 -11
  28. package/dist/editor/page-editor-chrome/InlineEditor.js.map +1 -1
  29. package/dist/editor/page-editor-chrome/useInlineAICompletion.d.ts +7 -0
  30. package/dist/editor/page-editor-chrome/useInlineAICompletion.js +600 -0
  31. package/dist/editor/page-editor-chrome/useInlineAICompletion.js.map +1 -0
  32. package/dist/editor/page-viewer/PageViewer.js +6 -1
  33. package/dist/editor/page-viewer/PageViewer.js.map +1 -1
  34. package/dist/editor/page-viewer/PageViewerFrame.js +0 -1
  35. package/dist/editor/page-viewer/PageViewerFrame.js.map +1 -1
  36. package/dist/editor/services/aiService.d.ts +6 -1
  37. package/dist/editor/services/aiService.js +2 -3
  38. package/dist/editor/services/aiService.js.map +1 -1
  39. package/dist/editor/ui/PerfectTree.js +3 -3
  40. package/dist/editor/ui/PerfectTree.js.map +1 -1
  41. package/dist/page-wizard/steps/CreatePage.js +5 -2
  42. package/dist/page-wizard/steps/CreatePage.js.map +1 -1
  43. package/dist/page-wizard/steps/CreatePageAndLayoutStep.js +2 -1
  44. package/dist/page-wizard/steps/CreatePageAndLayoutStep.js.map +1 -1
  45. package/dist/page-wizard/steps/ImagesStep.js +1 -3
  46. package/dist/page-wizard/steps/ImagesStep.js.map +1 -1
  47. package/dist/page-wizard/steps/LayoutStep.js +5 -5
  48. package/dist/page-wizard/steps/LayoutStep.js.map +1 -1
  49. package/dist/page-wizard/steps/SelectStep.js +5 -5
  50. package/dist/page-wizard/steps/SelectStep.js.map +1 -1
  51. package/dist/styles.css +17 -8
  52. package/package.json +1 -1
  53. package/src/config/config.tsx +20 -2
  54. package/src/editor/ContentTree.tsx +0 -2
  55. package/src/editor/ai/AiResponseMessage.tsx +43 -19
  56. package/src/editor/ai/AiTerminal.tsx +153 -105
  57. package/src/editor/ai/AiToolCall.tsx +37 -21
  58. package/src/editor/ai/GhostWriter.tsx +432 -0
  59. package/src/editor/client/EditorClient.tsx +4 -0
  60. package/src/editor/client/editContext.ts +3 -0
  61. package/src/editor/media-selector/AiImageSearch.tsx +8 -9
  62. package/src/editor/media-selector/AiImageSearchPrompt.tsx +4 -5
  63. package/src/editor/page-editor-chrome/FrameMenu.tsx +1 -0
  64. package/src/editor/page-editor-chrome/InlineEditor.tsx +177 -18
  65. package/src/editor/page-editor-chrome/useInlineAICompletion.tsx +734 -0
  66. package/src/editor/page-viewer/PageViewer.tsx +21 -6
  67. package/src/editor/page-viewer/PageViewerFrame.tsx +0 -1
  68. package/src/editor/services/aiService.ts +10 -6
  69. package/src/editor/ui/PerfectTree.tsx +5 -5
  70. package/src/page-wizard/steps/CreatePage.tsx +21 -26
  71. package/src/page-wizard/steps/CreatePageAndLayoutStep.tsx +2 -2
  72. package/src/page-wizard/steps/ImagesStep.tsx +2 -5
  73. package/src/page-wizard/steps/LayoutStep.tsx +12 -13
  74. package/src/page-wizard/steps/SelectStep.tsx +12 -13
@@ -0,0 +1,734 @@
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 (element: HTMLElement) => {
287
+ const contentUpToCursor = getContentUpToCursor(element);
288
+ if (!contentUpToCursor?.trim()) return null;
289
+
290
+ // Abort any in-flight request
291
+ if (abortControllerRef.current) {
292
+ abortControllerRef.current.abort();
293
+ }
294
+
295
+ // Create a new abort controller for this request
296
+ abortControllerRef.current = new AbortController();
297
+ const signal = abortControllerRef.current.signal;
298
+
299
+ // Get field attributes
300
+ const fieldId = element.getAttribute("data-fieldid");
301
+ const fieldName = element.getAttribute("data-fieldname");
302
+ const itemId = element.getAttribute("data-itemid");
303
+ const language = element.getAttribute("data-language");
304
+ const version = element.getAttribute("data-version");
305
+ if (!fieldId || !itemId || !language || !version) return null;
306
+
307
+ // Only trigger completion after a space to ensure clean separation between
308
+ // user text and completion suggestion
309
+ const lastChar = contentUpToCursor.slice(-1);
310
+ if (lastChar !== " " && lastChar !== "\u00A0") {
311
+ return null;
312
+ }
313
+
314
+ const messages = [
315
+ {
316
+ name: "system",
317
+ role: "system",
318
+ content:
319
+ "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.",
320
+ },
321
+ {
322
+ name: "user",
323
+ role: "user",
324
+ content: `Complete this sentence. ONLY provide the completion (do not repeat my text): ${contentUpToCursor}`,
325
+ },
326
+ ];
327
+
328
+ if (!editContext) return null;
329
+
330
+ // Show loading indicator
331
+ setIsLoading(true);
332
+ startLoadingAnimation();
333
+
334
+ try {
335
+ const result = await executePrompt(
336
+ messages,
337
+ editContext,
338
+ () => ({
339
+ endpoint: "/alpaca/editor/ai/complete",
340
+ promptData: {
341
+ itemid: itemId,
342
+ language,
343
+ version,
344
+ fieldid: fieldId,
345
+ fieldname: fieldName,
346
+ content: contentUpToCursor,
347
+ },
348
+ }),
349
+ {},
350
+ { signal },
351
+ "gpt-4.1-nano",
352
+ );
353
+
354
+ return result;
355
+ } catch (error: unknown) {
356
+ // Ignore AbortError as it's expected when cancelling
357
+ if (error instanceof Error && error.name !== "AbortError") {
358
+ console.error("Error getting completion:", error);
359
+ }
360
+ return null;
361
+ } finally {
362
+ // Hide loading indicator
363
+ setIsLoading(false);
364
+ stopLoadingAnimation();
365
+ }
366
+ };
367
+
368
+ // Debounced AI call: recompute the sentence, call getCompletion, and extract only the "tail" for the ghost text
369
+ const getCompletionDebounced = useDebouncedCallback(async () => {
370
+ const el = editContext?.inlineEditingFieldElement;
371
+ if (!el) return;
372
+
373
+ // 1) Recompute the exact sentence at this moment
374
+ const full = getContentUpToCursor(el) || "";
375
+ const sentence = full.split(/[.?!]\s*/).pop() || "";
376
+
377
+ // 2) Ask AI for a completion
378
+ const result = await getCompletion(el);
379
+ const rawSuggestion = result?.messages?.[0]?.content;
380
+ if (!rawSuggestion) {
381
+ setCurrentCompletion(null);
382
+ clearCursorSpan();
383
+ return;
384
+ }
385
+
386
+ // 3) Strip off the already-typed sentence to leave just the "completion tail"
387
+ const suggestion = rawSuggestion.startsWith(sentence)
388
+ ? rawSuggestion
389
+ : sentence + rawSuggestion;
390
+
391
+ setCurrentCompletion(suggestion);
392
+
393
+ updateCursorSpan(suggestion.substring(sentence.length));
394
+ }, 250);
395
+
396
+ // Inserts or clears the ghost text inside the cursor span
397
+ const updateCursorSpan = (text: string) => {
398
+ const doc =
399
+ pageViewContext.editorIframeRef.current?.contentWindow?.document;
400
+ const span = doc?.getElementById(cursorSpanId);
401
+ if (!doc || !span) return;
402
+
403
+ // Update the completion text
404
+ if (text) {
405
+ // // Create a temporary span to measure the text width
406
+ // const measureSpan = doc.createElement("span");
407
+ // measureSpan.style.visibility = "hidden";
408
+ // measureSpan.style.position = "absolute";
409
+ // measureSpan.style.whiteSpace = "pre"; // Preserve whitespace
410
+ // measureSpan.style.font = window.getComputedStyle(span).font; // Match the font
411
+ // measureSpan.textContent = text;
412
+ // doc.body.appendChild(measureSpan);
413
+ // const textWidth = measureSpan.getBoundingClientRect().width;
414
+ // measureSpan.remove();
415
+
416
+ span.textContent = text;
417
+ span.style.color = "#888";
418
+ span.style.fontStyle = "italic";
419
+ //span.innerHTML = "hello";
420
+
421
+ // Create or update hint element in the main document
422
+ let hintElement = document.getElementById(`${cursorSpanId}-hint`);
423
+ if (!hintElement) {
424
+ hintElement = document.createElement("div");
425
+ hintElement.id = `${cursorSpanId}-hint`;
426
+ document.body.appendChild(hintElement);
427
+ }
428
+
429
+ hintElement.textContent = "Press Tab to accept ⇥";
430
+
431
+ // Apply styles that match Tailwind's utility classes
432
+ Object.assign(hintElement.style, {
433
+ position: "fixed",
434
+ fontSize: "12px",
435
+ fontWeight: "normal",
436
+ color: "rgb(75, 85, 99)",
437
+ backgroundColor: "white",
438
+ padding: "0.5rem",
439
+ marginLeft: "0.25rem",
440
+ marginRight: "0.25rem",
441
+ borderRadius: "0.25rem",
442
+ border: "1px solid rgb(229, 231, 235)",
443
+ fontStyle: "normal",
444
+ display: "block",
445
+ lineHeight: "1.4",
446
+ zIndex: "9999",
447
+ pointerEvents: "none",
448
+ boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
449
+ });
450
+
451
+ // Position the hint element relative to the iframe and cursor span
452
+ const iframeRect =
453
+ pageViewContext.editorIframeRef.current?.getBoundingClientRect();
454
+ const spanRect = span.getBoundingClientRect();
455
+
456
+ if (iframeRect) {
457
+ // Create a range for the last character to get proper position
458
+ const textLength = span.textContent?.length || 0;
459
+ if (textLength > 0 && span.firstChild) {
460
+ const range = doc.createRange();
461
+ range.setStart(span.firstChild, Math.max(0, textLength - 1));
462
+ range.setEnd(span.firstChild, textLength);
463
+
464
+ const rangeRect = range.getBoundingClientRect();
465
+
466
+ // Position at the end of the actual text
467
+ const absoluteLeft = iframeRect.left + rangeRect.right;
468
+ const absoluteTop = iframeRect.top + rangeRect.top;
469
+
470
+ hintElement.style.left = `${absoluteLeft}px`;
471
+ hintElement.style.top = `${absoluteTop}px`;
472
+ } else {
473
+ // Fallback to the old positioning if there's no text
474
+ const absoluteLeft = iframeRect.left + spanRect.right;
475
+ const absoluteTop = iframeRect.top + spanRect.top;
476
+
477
+ hintElement.style.left = `${absoluteLeft}px`;
478
+ hintElement.style.top = `${absoluteTop}px`;
479
+ }
480
+ }
481
+ } else {
482
+ span.textContent = "";
483
+ // Remove hint element if it exists
484
+ const hintElement = document.getElementById(`${cursorSpanId}-hint`);
485
+ if (hintElement) {
486
+ hintElement.remove();
487
+ }
488
+ }
489
+ };
490
+
491
+ const clearCursorSpan = () => {
492
+ const doc =
493
+ pageViewContext.editorIframeRef.current?.contentWindow?.document;
494
+ if (!doc) return;
495
+
496
+ // Clear the completion text
497
+ updateCursorSpan("");
498
+ };
499
+
500
+ // On every input: either reuse the existing suggestion or fire a new one
501
+ const handleInput = useCallback(
502
+ (e: KeyboardEvent) => {
503
+ const el = editContext?.inlineEditingFieldElement;
504
+ if (!el) return;
505
+
506
+ // Clear completion when Escape is pressed
507
+ if (e.key === "Escape") {
508
+ e.preventDefault();
509
+ e.stopPropagation();
510
+ setCurrentCompletion(null);
511
+ clearCursorSpan();
512
+ return;
513
+ }
514
+
515
+ // Request new completion when Ctrl+Space is pressed
516
+ if (e.key === " " && (e.ctrlKey || e.metaKey)) {
517
+ e.preventDefault();
518
+ e.stopPropagation();
519
+ setCurrentCompletion(null);
520
+ clearCursorSpan();
521
+ getCompletionDebounced();
522
+ return;
523
+ }
524
+
525
+ // Apply completion when Tab is pressed
526
+ if (e.key === "Tab") {
527
+ // Check if there's an actual completion in the cursor span
528
+ const cursorSpan =
529
+ pageViewContext.editorIframeRef.current?.contentWindow?.document.getElementById(
530
+ cursorSpanId,
531
+ );
532
+ if (
533
+ cursorSpan &&
534
+ cursorSpan.textContent &&
535
+ cursorSpan.textContent.trim() !== ""
536
+ ) {
537
+ e.preventDefault();
538
+ e.stopPropagation();
539
+ applyCompletion();
540
+ return;
541
+ }
542
+ }
543
+
544
+ const full = getContentUpToCursor(el) || "";
545
+ const sentence = full.split(/[.?!]\s*/).pop() || "";
546
+
547
+ // If we already have a suggestion, check if the user is still typing along it
548
+ // Normalize spaces to handle both regular and non-breaking spaces
549
+ const normalizedSentence = sentence.replace(/\s/g, " ");
550
+ const normalizedCompletion = currentCompletion?.replace(/\s/g, " ");
551
+
552
+ if (
553
+ normalizedCompletion &&
554
+ normalizedCompletion.startsWith(normalizedSentence)
555
+ ) {
556
+ // user is still matching the suggestion → update the remaining tail
557
+ const remaining = normalizedCompletion.slice(normalizedSentence.length);
558
+
559
+ updateCursorSpan(remaining);
560
+ return;
561
+ }
562
+ // else: user diverged → drop it
563
+ setCurrentCompletion(null);
564
+ clearCursorSpan();
565
+
566
+ // No active suggestion → fire new request once they've typed 2+ words
567
+ const words = sentence.trim().split(/\s+/).filter(Boolean);
568
+ if (words.length >= 2) {
569
+ getCompletionDebounced();
570
+ } else {
571
+ setCurrentCompletion(null);
572
+ clearCursorSpan();
573
+ }
574
+ },
575
+ [
576
+ editContext?.inlineEditingFieldElement,
577
+ currentCompletion,
578
+ getCompletionDebounced,
579
+ ],
580
+ );
581
+
582
+ // Wire up the input listener
583
+ useEffect(() => {
584
+ if (!editContext?.enableCompletions) return;
585
+ const el = editContext?.inlineEditingFieldElement;
586
+ if (!el) return;
587
+ el.addEventListener("keydown", handleInput);
588
+ return () => el.removeEventListener("keydown", handleInput);
589
+ }, [
590
+ editContext?.inlineEditingFieldElement,
591
+ handleInput,
592
+ editContext?.enableCompletions,
593
+ ]);
594
+
595
+ // Clean up abort controller on unmount
596
+ useEffect(() => {
597
+ return () => {
598
+ if (abortControllerRef.current) {
599
+ abortControllerRef.current.abort();
600
+ abortControllerRef.current = null;
601
+ }
602
+
603
+ if (loadingAnimationRef.current) {
604
+ cancelAnimationFrame(loadingAnimationRef.current);
605
+ loadingAnimationRef.current = null;
606
+ }
607
+ };
608
+ }, []);
609
+
610
+ // Function to apply the completion
611
+ const applyCompletion = () => {
612
+ // Get the cursor span to read the most up-to-date completion
613
+ const iframeWindow = pageViewContext.editorIframeRef.current?.contentWindow;
614
+ const iframeDocument = iframeWindow?.document;
615
+ if (
616
+ !iframeWindow ||
617
+ !iframeDocument ||
618
+ !editContext?.inlineEditingFieldElement
619
+ )
620
+ return;
621
+
622
+ const cursorSpan = iframeDocument.getElementById(cursorSpanId);
623
+ if (!cursorSpan) return;
624
+
625
+ // Get the completion text directly from the cursor span, which should be the most current
626
+ const completionToApply = cursorSpan.textContent || "";
627
+ if (!completionToApply) return;
628
+
629
+ const element = editContext?.inlineEditingFieldElement;
630
+
631
+ // Get the current selection position
632
+ const selection = iframeWindow.getSelection();
633
+ if (!selection || selection.rangeCount === 0) return;
634
+
635
+ // Get the text up to the cursor to analyze current word
636
+ const range = selection.getRangeAt(0);
637
+ const tempRange = document.createRange();
638
+ tempRange.selectNodeContents(element);
639
+ tempRange.setEnd(range.startContainer, range.startOffset);
640
+ const textUpToCursor = tempRange.toString();
641
+
642
+ // Get the current partial word by finding text from the last word boundary to cursor
643
+ // Look for last word boundary (space, punctuation, etc.)
644
+ const wordBoundaryRegex =
645
+ /[\s.,;:!?"'()[\]{}<>\/\\|=+\-*&^%$#@~`](?=[^\s.,;:!?"'()[\]{}<>\/\\|=+\-*&^%$#@~`]*$)/;
646
+ const match = textUpToCursor.match(wordBoundaryRegex);
647
+ const lastWordBoundaryIndex =
648
+ match && match.index !== undefined ? match.index + 1 : 0;
649
+
650
+ const currentPartialWord = textUpToCursor
651
+ .substring(lastWordBoundaryIndex)
652
+ .trim();
653
+
654
+ // Check if completion overlaps with current partial word
655
+ // (e.g., if user typed "int" and completion is "integer")
656
+ const isOverlapping =
657
+ currentPartialWord.length > 0 &&
658
+ completionToApply
659
+ .toLowerCase()
660
+ .startsWith(currentPartialWord.toLowerCase());
661
+
662
+ console.log("Is overlapping:", isOverlapping);
663
+
664
+ // If there's overlap, we need to delete the current partial word
665
+ if (isOverlapping) {
666
+ // Create a range to select the current partial word
667
+ const wordRange = document.createRange();
668
+
669
+ // Position where the current word starts
670
+ let startContainer = range.startContainer;
671
+ let startOffset = range.startOffset - currentPartialWord.length;
672
+
673
+ // We need to handle the case where the word spans multiple text nodes
674
+ // For simplicity, we'll try to handle the common case first
675
+ if (startOffset >= 0 && startContainer.nodeType === Node.TEXT_NODE) {
676
+ // Simple case: word is in the same text node as cursor
677
+ wordRange.setStart(startContainer, startOffset);
678
+ wordRange.setEnd(range.startContainer, range.startOffset);
679
+ wordRange.deleteContents(); // Delete the partial word
680
+ } else {
681
+ // Complex case: use a simpler approach - just insert, user can delete manually if needed
682
+ // This is a fallback for complex DOM structures
683
+ // Add a space if we're in the middle of a sentence
684
+ if (textUpToCursor.length > 0 && !textUpToCursor.endsWith(" ")) {
685
+ const spaceNode = document.createTextNode(" ");
686
+ range.insertNode(spaceNode);
687
+ range.setStartAfter(spaceNode);
688
+ range.setEndAfter(spaceNode);
689
+ }
690
+ }
691
+ } else {
692
+ // Not overlapping, add a space if we're in the middle of text
693
+ // and not already at the beginning of text or after a space
694
+ if (
695
+ textUpToCursor.length > 0 &&
696
+ !textUpToCursor.endsWith(" ") &&
697
+ // Don't add space at the start of a line or after punctuation that shouldn't have a space
698
+ !textUpToCursor.endsWith("\n") &&
699
+ !/[.!?\-—:;({[\s]$/.test(textUpToCursor)
700
+ ) {
701
+ const spaceNode = document.createTextNode(" ");
702
+ range.insertNode(spaceNode);
703
+ range.setStartAfter(spaceNode);
704
+ range.setEndAfter(spaceNode);
705
+ }
706
+ }
707
+
708
+ // Now insert the completion text
709
+ const textNode = document.createTextNode(
710
+ isOverlapping
711
+ ? completionToApply // If overlapping, use the full completion
712
+ : completionToApply, // If not overlapping, use as is
713
+ );
714
+ range.insertNode(textNode);
715
+
716
+ // Move the cursor after the inserted text
717
+ range.setStartAfter(textNode);
718
+ range.setEndAfter(textNode);
719
+ selection.removeAllRanges();
720
+ selection.addRange(range);
721
+ setCurrentCompletion(null);
722
+ clearCursorSpan();
723
+ };
724
+
725
+ // Exposed manual trigger (if needed)
726
+ return useMemo(
727
+ () => () => {
728
+ setCurrentCompletion(null);
729
+ clearCursorSpan();
730
+ getCompletionDebounced();
731
+ },
732
+ [getCompletionDebounced],
733
+ );
734
+ }