File size: 15,464 Bytes
7394487
 
 
 
 
 
 
 
 
 
 
 
 
0a1ff39
7394487
 
 
 
 
 
 
 
 
 
7f53fe2
7394487
 
 
 
 
 
 
 
 
 
 
 
612978c
7394487
 
 
 
 
 
 
612978c
7394487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f53fe2
 
7394487
 
 
 
 
 
 
 
 
7f53fe2
7394487
 
7f53fe2
612978c
7f53fe2
 
612978c
7f53fe2
 
7394487
 
 
 
 
 
7f53fe2
 
7394487
 
 
 
 
 
 
 
 
7f53fe2
7394487
 
 
 
 
 
 
 
 
 
 
 
 
 
612978c
 
 
 
 
 
 
 
7394487
 
 
 
 
612978c
7f53fe2
612978c
7394487
 
 
 
 
612978c
 
 
 
 
7394487
 
 
 
612978c
 
7394487
 
 
 
 
97062ad
 
 
 
 
 
 
 
 
 
612978c
 
 
 
 
 
7394487
612978c
7394487
 
612978c
7394487
 
7f53fe2
612978c
7f53fe2
612978c
7f53fe2
 
7394487
 
 
 
 
612978c
7394487
 
 
 
7f53fe2
7394487
 
 
 
 
612978c
7394487
 
 
612978c
 
7394487
 
612978c
7394487
 
 
 
 
 
 
 
612978c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7394487
 
 
7f53fe2
7394487
7f53fe2
7394487
 
7f53fe2
7394487
 
 
 
 
7f53fe2
7394487
 
 
 
 
 
 
 
 
 
612978c
7394487
 
7f53fe2
612978c
7f53fe2
7394487
 
 
 
 
 
612978c
 
7394487
 
 
 
7f53fe2
7394487
612978c
7394487
612978c
7394487
612978c
7394487
 
 
 
 
 
 
 
 
 
 
612978c
7394487
 
612978c
7394487
 
612978c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7394487
 
 
 
 
 
 
 
 
 
 
 
 
7f53fe2
7394487
 
 
7f53fe2
612978c
7394487
 
 
 
 
 
 
 
 
7f53fe2
 
7394487
 
 
 
 
612978c
 
 
7394487
612978c
 
7394487
252b187
 
 
612978c
 
 
7394487
612978c
7394487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f53fe2
 
 
612978c
7f53fe2
7394487
 
 
7f53fe2
7394487
 
612978c
7f53fe2
 
 
 
 
7394487
612978c
7f53fe2
612978c
7f53fe2
 
7394487
612978c
7f53fe2
 
 
 
 
 
 
7394487
 
 
 
 
612978c
7394487
 
 
7f53fe2
7394487
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/**
 * AutoComplete Module — Ghost Text + Dropdown for Arabic autocomplete.
 *
 * COMPLETELY INDEPENDENT from the correction pipeline.
 * It only talks to: /api/autocomplete (its own endpoint)
 */

(function () {
  'use strict';

  // ─── Configuration ───────────────────────────────────────────────
  const DEBOUNCE_MS = 400;
  const MIN_CONTEXT_LEN = 3;
  const MAX_SUGGESTIONS = 3;
  const CONTEXT_CHARS = 200;

  // ─── State ───────────────────────────────────────────────────────
  let ghostEl = null;
  let dropdownEl = null;
  let selectedIndex = -1;
  let currentSuggestions = [];
  let debounceTimer = null;
  let isComposing = false;
  let editorEl = null;
  let _lastFetchId = 0;

  // ─── Initialization ──────────────────────────────────────────────
  function init() {
    editorEl = document.getElementById('editor-container');
    if (!editorEl) {
      setTimeout(init, 500);
      return;
    }

    createGhostElement();
    createDropdownElement();
    bindEvents();
    console.log('[AutoComplete] Initialized');
  }

  // ─── Ghost Text Element ──────────────────────────────────────────
  function createGhostElement() {
    ghostEl = document.createElement('div');
    ghostEl.id = 'autocomplete-ghost';
    ghostEl.setAttribute('aria-hidden', 'true');
    var editorParent = editorEl.parentElement;
    if (editorParent) {
      editorParent.style.position = 'relative';
      editorParent.appendChild(ghostEl);
    }
  }

  // ─── Dropdown Element ────────────────────────────────────────────
  function createDropdownElement() {
    dropdownEl = document.createElement('div');
    dropdownEl.id = 'autocomplete-dropdown';
    dropdownEl.setAttribute('role', 'listbox');
    dropdownEl.setAttribute('aria-label', 'اقتراحات الإكمال التلقائي');
    dropdownEl.style.display = 'none';
    document.body.appendChild(dropdownEl);
  }

  // ─── Event Binding ───────────────────────────────────────────────
  function bindEvents() {
    editorEl.addEventListener('input', onInput);
    editorEl.addEventListener('compositionstart', function () { isComposing = true; });
    editorEl.addEventListener('compositionend', function () { isComposing = false; });
    editorEl.addEventListener('keydown', onKeyDown);

    // Click outside → dismiss
    document.addEventListener('mousedown', function (e) {
      if (dropdownEl && !dropdownEl.contains(e.target) && e.target !== editorEl) {
        dismiss();
      }
    });

    // Scroll/resize → dismiss
    editorEl.addEventListener('scroll', dismiss);
    window.addEventListener('resize', dismiss);

    // Focus lost → dismiss (with delay for dropdown clicks)
    editorEl.addEventListener('blur', function () {
      setTimeout(function () {
        if (document.activeElement !== editorEl) dismiss();
      }, 200);
    });
  }

  // ─── Input Handler ───────────────────────────────────────────────
  function onInput() {
    if (isComposing) return;
    clearTimeout(debounceTimer);
    hideGhost();
    debounceTimer = setTimeout(fetchSuggestions, DEBOUNCE_MS);
  }

  // ─── Keyboard Handler ───────────────────────────────────────────
  function onKeyDown(e) {
    if (!isVisible()) return;

    switch (e.key) {
      case 'Tab':
        e.preventDefault();
        e.stopPropagation();
        acceptSuggestion();
        break;
      case 'Escape':
        e.preventDefault();
        dismiss();
        break;
      case 'ArrowDown':
        e.preventDefault();
        navigateDropdown(1);
        break;
      case 'ArrowUp':
        e.preventDefault();
        navigateDropdown(-1);
        break;
      case 'Enter':
        // If dropdown is visible, accept on Enter too
        if (isVisible() && selectedIndex >= 0) {
          e.preventDefault();
          e.stopPropagation();
          acceptSuggestion();
        }
        break;
    }
  }

  // ─── Fetch Suggestions ───────────────────────────────────────────
  async function fetchSuggestions() {
    var fetchId = ++_lastFetchId;

    var sel = window.getSelection();
    if (!sel || !sel.isCollapsed || !sel.rangeCount) {
      dismiss();
      return;
    }

    // CRITICAL: Only show autocomplete when cursor is at END of text
    // or at the end of a word (after a space or at document end)
    var textAfterCursor = getTextAfterCursor();
    if (textAfterCursor.length > 0 && textAfterCursor[0] !== ' ' && textAfterCursor[0] !== '\n') {
      // Cursor is in the MIDDLE of a word — don't show autocomplete
      dismiss();
      return;
    }

    // Get context (text before cursor)
    var context = getTextBeforeCursor(CONTEXT_CHARS);
    if (!context || context.trim().length < MIN_CONTEXT_LEN) {
      dismiss();
      return;
    }

    // CRITICAL: Only trigger when the user just typed a SPACE
    // (meaning they finished a word). Partial words like "عا" produce garbage.
    var lastChar = context[context.length - 1];
    if (lastChar !== ' ' && lastChar !== '\u00A0') {
      // User is still typing a word — don't send partial word to backend
      dismiss();
      return;
    }

    // Trim trailing spaces for the API call (backend expects clean context)
    var trimmed = context.trimEnd();
    if (!trimmed || trimmed.length < MIN_CONTEXT_LEN) {
      dismiss();
      return;
    }

    try {
      var resp = await fetch('/api/autocomplete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ context: trimmed, n: MAX_SUGGESTIONS })
      });

      if (fetchId !== _lastFetchId) return;
      if (!resp.ok) { dismiss(); return; }

      var data = await resp.json();
      if (fetchId !== _lastFetchId) return;

      if (data.status !== 'success' || !data.suggestions || !data.suggestions.length) {
        dismiss();
        return;
      }

      console.log('[AutoComplete] Suggestions for last word:', data.suggestions);
      showSuggestions(data.suggestions);

    } catch (err) {
      console.warn('[AutoComplete] Fetch error:', err);
      if (fetchId === _lastFetchId) dismiss();
    }
  }

  // ─── Get Text Before Cursor ──────────────────────────────────────
  function getTextBeforeCursor(maxChars) {
    var sel = window.getSelection();
    if (!sel || !sel.rangeCount) return '';

    try {
      var range = sel.getRangeAt(0);
      var preRange = document.createRange();
      preRange.selectNodeContents(editorEl);
      preRange.setEnd(range.startContainer, range.startOffset);
      var text = preRange.toString();
      preRange.detach();
      if (text.length <= maxChars) return text;
      return text.slice(-maxChars);
    } catch (e) {
      return '';
    }
  }

  // ─── Get Text After Cursor ───────────────────────────────────────
  function getTextAfterCursor() {
    var sel = window.getSelection();
    if (!sel || !sel.rangeCount) return '';

    try {
      var range = sel.getRangeAt(0);
      var postRange = document.createRange();
      postRange.selectNodeContents(editorEl);
      postRange.setStart(range.endContainer, range.endOffset);
      var text = postRange.toString();
      postRange.detach();
      return text;
    } catch (e) {
      return '';
    }
  }

  // ─── Show Suggestions ────────────────────────────────────────────
  function showSuggestions(suggestions) {
    currentSuggestions = suggestions;
    selectedIndex = 0;

    // Build dropdown items
    dropdownEl.innerHTML = '';
    suggestions.forEach(function (word, idx) {
      var item = document.createElement('div');
      item.className = 'ac-dropdown-item' + (idx === 0 ? ' ac-selected' : '');
      item.setAttribute('role', 'option');
      item.textContent = word;
      item.addEventListener('mousedown', function (e) {
        e.preventDefault();
        e.stopPropagation();
        selectedIndex = idx;
        acceptSuggestion();
      });
      item.addEventListener('mouseenter', function () {
        selectedIndex = idx;
        updateDropdownSelection();
      });
      dropdownEl.appendChild(item);
    });

    // Position and show dropdown BELOW the caret, aligned to caret position
    positionDropdown();
    dropdownEl.style.display = 'block';

    // Show ghost text inline
    showGhost(suggestions[0]);
  }

  // ─── Ghost Text ──────────────────────────────────────────────────
  function showGhost(text) {
    if (!ghostEl || !text) return;

    var caretPos = getCaretCoordinates();
    if (!caretPos) { hideGhost(); return; }

    ghostEl.textContent = text;
    ghostEl.style.display = 'block';

    var parentRect = editorEl.parentElement.getBoundingClientRect();

    // Position ghost at caret — for RTL, text appears to the LEFT of caret
    ghostEl.style.top = (caretPos.top - parentRect.top) + 'px';
    // Use left positioning (place ghost just left of the caret in RTL)
    ghostEl.style.left = 'auto';
    ghostEl.style.right = (parentRect.right - caretPos.right + 2) + 'px';
  }

  function hideGhost() {
    if (ghostEl) {
      ghostEl.style.display = 'none';
      ghostEl.textContent = '';
    }
  }

  // ─── Dropdown Position ───────────────────────────────────────────
  function positionDropdown() {
    var caretPos = getCaretCoordinates();
    if (!caretPos) return;

    // Use fixed positioning relative to viewport
    dropdownEl.style.position = 'fixed';

    // Place BELOW the caret line
    var topPos = caretPos.bottom + 6;
    dropdownEl.style.top = topPos + 'px';

    // For RTL: align dropdown's RIGHT edge to the caret position
    // Use LEFT positioning to place the dropdown starting at the caret X
    var leftPos = caretPos.left - 160; // dropdown is ~160px wide, align right edge to caret
    if (leftPos < 10) leftPos = 10;
    dropdownEl.style.left = leftPos + 'px';
    dropdownEl.style.right = 'auto';

    // Check if dropdown goes off-screen bottom
    requestAnimationFrame(function () {
      var rect = dropdownEl.getBoundingClientRect();
      if (rect.bottom > window.innerHeight - 20) {
        dropdownEl.style.top = (caretPos.top - rect.height - 6) + 'px';
      }
    });
  }

  // ─── Dropdown Navigation ─────────────────────────────────────────
  function navigateDropdown(direction) {
    if (!currentSuggestions.length) return;
    selectedIndex += direction;
    if (selectedIndex < 0) selectedIndex = currentSuggestions.length - 1;
    if (selectedIndex >= currentSuggestions.length) selectedIndex = 0;
    updateDropdownSelection();
    showGhost(currentSuggestions[selectedIndex]);
  }

  function updateDropdownSelection() {
    var items = dropdownEl.querySelectorAll('.ac-dropdown-item');
    items.forEach(function (item, idx) {
      item.classList.toggle('ac-selected', idx === selectedIndex);
    });
    var selected = dropdownEl.querySelector('.ac-selected');
    if (selected) selected.scrollIntoView({ block: 'nearest' });
  }

  // ─── Accept Suggestion ───────────────────────────────────────────
  function acceptSuggestion() {
    if (selectedIndex < 0 || selectedIndex >= currentSuggestions.length) {
      dismiss();
      return;
    }

    var word = currentSuggestions[selectedIndex];
    var sel = window.getSelection();
    if (!sel || !sel.rangeCount) {
      dismiss();
      return;
    }

    // Determine if we need a space before the word
    var textBefore = getTextBeforeCursor(10);
    var needsSpaceBefore = textBefore.length > 0 && !textBefore.endsWith(' ') && !textBefore.endsWith('\n');

    // Build the text to insert: [optional space] + word + space
    var textToInsert = (needsSpaceBefore ? ' ' : '') + word + ' ';

    // Save undo state before inserting
    if (typeof pushUndoState === 'function') pushUndoState();

    // Use execCommand for reliable insertion in contenteditable
    // This preserves undo history and handles cursor position correctly
    document.execCommand('insertText', false, textToInsert);

    dismiss();
  }

  // ─── Dismiss ─────────────────────────────────────────────────────
  function dismiss() {
    hideGhost();
    currentSuggestions = [];
    selectedIndex = -1;
    if (dropdownEl) {
      dropdownEl.style.display = 'none';
      dropdownEl.innerHTML = '';
    }
  }

  // ─── Helpers ─────────────────────────────────────────────────────
  function isVisible() {
    return dropdownEl && dropdownEl.style.display !== 'none';
  }

  /**
   * Get caret coordinates using Range.getClientRects() — NO DOM mutation.
   */
  function getCaretCoordinates() {
    var sel = window.getSelection();
    if (!sel || !sel.rangeCount) return null;

    try {
      var range = sel.getRangeAt(0).cloneRange();
      range.collapse(true);

      // Try getClientRects first
      var rects = range.getClientRects();
      if (rects.length > 0) {
        var r = rects[0];
        return { top: r.top, left: r.left, bottom: r.bottom, right: r.right };
      }

      // Fallback: use getBoundingClientRect
      var bRect = range.getBoundingClientRect();
      if (bRect && (bRect.top !== 0 || bRect.left !== 0)) {
        return { top: bRect.top, left: bRect.left, bottom: bRect.bottom, right: bRect.right };
      }

      // Last resort: use editor position
      var editorRect = editorEl.getBoundingClientRect();
      return {
        top: editorRect.top + 20,
        left: editorRect.right - 20,
        bottom: editorRect.top + 44,
        right: editorRect.right
      };
    } catch (e) {
      return null;
    }
  }

  // ─── Initialize ──────────────────────────────────────────────────
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    setTimeout(init, 100);
  }

})();