File size: 11,634 Bytes
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9630ec
 
41e1749
 
 
 
 
 
 
 
 
 
a9630ec
 
41e1749
a9630ec
41e1749
 
 
 
 
a9630ec
41e1749
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036913a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80d7d85
 
036913a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad7b1d2
036913a
 
 
ad7b1d2
 
 
 
 
036913a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9630ec
 
036913a
 
 
 
 
 
 
 
 
 
 
 
d061c20
036913a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41e1749
 
 
 
 
 
 
 
036913a
 
 
41e1749
 
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
// src/js/renderer.js
// Offset-based renderer for highlighted text with suggestions

/**
 * Escapes HTML special characters to prevent XSS
 * @param {string} text - Text to escape
 * @returns {string} - Escaped text
 */
function escapeHtml(text) {
  const map = {
    '&': '&',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#039;'
  };
  return text.replace(/[&<>"']/g, (c) => map[c]);
}

/**
 * Sorts suggestions by start offset
 * @param {Array} suggestions - Array of suggestions with start/end offsets
 * @returns {Array} - Sorted suggestions
 */
function sortSuggestions(suggestions) {
  return [...suggestions].sort((a, b) => a.start - b.start);
}

/**
 * Creates a segment tree of text ranges with their suggestions
 * Handles overlapping ranges by merging them
 * @param {string} text - Original text
 * @param {Array} suggestions - Array of suggestions with start/end offsets
 * @returns {Array} - Array of segments with position and suggestion info
 */
function createSegments(text, suggestions) {
  const sorted = sortSuggestions(suggestions);
  const segments = [];
  let currentPos = 0;

  // Build event timeline
  const events = [];
  sorted.forEach((suggestion, idx) => {
    events.push({
      pos: suggestion.start,
      type: 'start',
      suggestionIdx: idx
    });
    events.push({
      pos: suggestion.end,
      type: 'end',
      suggestionIdx: idx
    });
  });

  // Sort events by position
  events.sort((a, b) => a.pos - b.pos || (a.type === 'end' ? 1 : -1));

  const activeSuggestions = [];

  events.forEach((event) => {
    const pos = event.pos;

    // Add unsuggestioned text segment up to this position
    if (currentPos < pos) {
      segments.push({
        type: 'text',
        text: text.slice(currentPos, pos),
        suggestions: []
      });
    }

    // Track active suggestions
    if (event.type === 'start') {
      activeSuggestions.push(sorted[event.suggestionIdx]);
    } else {
      activeSuggestions.splice(
        activeSuggestions.findIndex((s) => s === sorted[event.suggestionIdx]),
        1
      );
    }

    currentPos = pos;
  });

  // Add remaining text
  if (currentPos < text.length) {
    segments.push({
      type: 'text',
      text: text.slice(currentPos),
      suggestions: []
    });
  }

  // Now rebuild segments with suggestion ranges
  const finalSegments = [];
  let segStart = 0;

  sorted.forEach((suggestion, idx) => {
    const { start, end } = suggestion;

    // Add text before suggestion
    if (segStart < start) {
      finalSegments.push({
        type: 'text',
        text: text.slice(segStart, start),
        suggestions: []
      });
    }

    // Add suggested text
    finalSegments.push({
      type: 'suggestion',
      text: text.slice(start, end),
      suggestion: suggestion
    });

    segStart = end;
  });

  // Add remaining text
  if (segStart < text.length) {
    finalSegments.push({
      type: 'text',
      text: text.slice(segStart),
      suggestions: []
    });
  }

  return finalSegments;
}

/**
 * Gets CSS class for suggestion type
 * @param {string} type - Suggestion type (spelling, grammar, punctuation)
 * @returns {string} - CSS class name
 */
function getErrorClass(type) {
  const classes = {
    'spelling': 'spelling-error',
    'grammar': 'grammar-error',
    'punctuation': 'punctuation-suggestion'
  };
  return classes[type] || 'spelling-error';
}

/**
 * Renders text with highlighted suggestions
 * @param {string} text - Original text
 * @param {Array} suggestions - Array of suggestions with start/end offsets
 * @returns {string} - Safe HTML string with highlights
 */
function renderHighlightedText(text, suggestions) {
  if (!text || text.length === 0) {
    return '';
  }

  if (!suggestions || suggestions.length === 0) {
    // No suggestions, return escaped text only
    return escapeHtml(text);
  }

  const segments = createSegments(text, suggestions);
  let html = '';
  // Pipeline Hardening v3.3: Track which suggestion we're rendering for UUID lookup
  let suggestionIdx = 0;

  segments.forEach((segment) => {
    if (segment.type === 'text') {
      // Regular text segment - just escape it
      html += escapeHtml(segment.text);
    } else if (segment.type === 'suggestion') {
      // Highlighted suggestion segment
      const { suggestion } = segment;
      const errorClass = getErrorClass(suggestion.type);
      const escapedText = escapeHtml(segment.text);
      // Pipeline Hardening v3.3: Use suggestion.id (UUID) if available, fallback to index
      const sid = suggestion.id || suggestionIdx;

      html += `<span class="${errorClass}" data-suggestion-id="${sid}" data-original="${escapeHtml(
        suggestion.original
      )}" data-correction="${escapeHtml(
        suggestion.correction
      )}" data-type="${suggestion.type}" title="${suggestion.type}: ${escapeHtml(suggestion.correction)}">${escapedText}</span>`;

      suggestionIdx++;
    }
  });

  return html;
}

/**
 * Main renderer function
 * Accepts text and suggestions array, returns highlighted HTML
 * @param {Object} input - Object with text and suggestions
 * @param {string} input.text - Original text
 * @param {Array} input.suggestions - Array of suggestions with { start, end, original, correction, type }
 * @returns {string} - Safe HTML with highlights
 */
function render(input) {
  const { text = '', suggestions = [] } = input;
  return renderHighlightedText(text, suggestions);
}

/**
 * Walk all text nodes in a DOM subtree in document order
 */
function walkTextNodes(root, callback) {
  const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);
  let node;
  while ((node = walker.nextNode())) {
    callback(node);
  }
}

/**
 * Remove existing error highlight spans without destroying content
 * Unwraps the spans back to plain text nodes
 */
function clearOverlays(editor) {
  const errorSpans = editor.querySelectorAll('.spelling-error, .grammar-error, .punctuation-suggestion');
  errorSpans.forEach(span => {
    // Skip spans inside quran-applied (they shouldn't be there, but safety)
    if (span.closest('.quran-applied')) return;
    const parent = span.parentNode;
    while (span.firstChild) {
      parent.insertBefore(span.firstChild, span);
    }
    parent.removeChild(span);
  });
  editor.normalize(); // merge adjacent text nodes
}

/**
 * Overlay suggestion highlights on the editor DOM without replacing innerHTML.
 * This preserves all formatting (bold, italic, underline, font, etc.)
 *
 * @param {HTMLElement} editor - The editor element
 * @param {Array} suggestions - Sorted array of suggestions with { start, end, original, correction, type }
 */
function overlaySuggestions(editor, suggestions) {
  // 1. Clear old overlays
  clearOverlays(editor);

  if (!suggestions || suggestions.length === 0) return;

  // 2. Collect text nodes with their character offsets (skip quran-applied)
  const textNodes = [];
  let offset = 0;
  walkTextNodes(editor, (node) => {
    // Skip text inside quran-applied spans (protected from analysis)
    if (node.parentElement && node.parentElement.closest('.quran-applied')) {
      offset += node.length; // still count offset to keep positions correct
      return;
    }
    textNodes.push({ node, start: offset, end: offset + node.length });
    offset += node.length;
  });

  if (textNodes.length === 0) return;

  // 3. Process suggestions in REVERSE order to avoid offset shifts
  const sorted = [...suggestions].sort((a, b) => b.start - a.start);

  sorted.forEach((suggestion, reverseIdx) => {
    const { start, end } = suggestion;
    const errorClass = getErrorClass(suggestion.type);

    // Find text nodes that overlap with this suggestion range
    const overlapping = textNodes.filter(tn => tn.start < end && tn.end > start);
    if (overlapping.length === 0) return;

    // Create the wrapper span
    const wrapper = document.createElement('span');
    wrapper.className = errorClass;
    // Pipeline Hardening v3.3: Use suggestion.id (UUID) instead of array index
    wrapper.dataset.suggestionId = suggestion.id || String(reverseIdx);
    wrapper.dataset.original = suggestion.original || '';
    wrapper.dataset.correction = suggestion.correction || '';
    wrapper.dataset.type = suggestion.type || 'spelling';
    wrapper.title = `${suggestion.type}: ${suggestion.correction}`;

    if (overlapping.length === 1) {
      // Simple case: suggestion falls within a single text node
      const tn = overlapping[0];
      const localStart = Math.max(0, start - tn.start);
      const localEnd = Math.min(tn.node.length, end - tn.start);

      // Split the text node
      if (!tn.node || !tn.node.textContent) return;
      const textContent = tn.node.textContent;
      const beforeText = textContent.slice(0, localStart);
      const errorText = textContent.slice(localStart, localEnd);
      const afterText = textContent.slice(localEnd);

      const parent = tn.node.parentNode;
      const errorTextNode = document.createTextNode(errorText);
      wrapper.appendChild(errorTextNode);

      // Replace the original text node
      if (afterText) {
        parent.insertBefore(document.createTextNode(afterText), tn.node.nextSibling);
      }
      parent.insertBefore(wrapper, tn.node.nextSibling || null);
      if (beforeText) {
        parent.insertBefore(document.createTextNode(beforeText), wrapper);
      }
      parent.removeChild(tn.node);

    } else {
      // Complex case: suggestion spans multiple text nodes
      // We use a Range to extract and wrap the content
      try {
        const range = document.createRange();

        const firstTN = overlapping[0];
        const lastTN = overlapping[overlapping.length - 1];
        const rangeStart = Math.max(0, start - firstTN.start);
        const rangeEnd = Math.min(lastTN.node.length, end - lastTN.start);

        range.setStart(firstTN.node, rangeStart);
        range.setEnd(lastTN.node, rangeEnd);

        range.surroundContents(wrapper);
      } catch (e) {
        // surroundContents can fail if the range crosses element boundaries
        // In that case, just wrap the text of the first overlapping node
        const tn = overlapping[0];
        const localStart = Math.max(0, start - tn.start);
        const localEnd = Math.min(tn.node.length, end - tn.start);

        if (localEnd > localStart) {
          const textContent = tn.node.textContent;
          const beforeText = textContent.slice(0, localStart);
          const errorText = textContent.slice(localStart, localEnd);
          const afterText = textContent.slice(localEnd);

          const parent = tn.node.parentNode;
          wrapper.appendChild(document.createTextNode(errorText));
          if (afterText) parent.insertBefore(document.createTextNode(afterText), tn.node.nextSibling);
          parent.insertBefore(wrapper, tn.node.nextSibling || null);
          if (beforeText) parent.insertBefore(document.createTextNode(beforeText), wrapper);
          parent.removeChild(tn.node);
        }
      }
    }

    // Rebuild textNodes array after modification (for next iteration)
    textNodes.length = 0;
    offset = 0;
    walkTextNodes(editor, (node) => {
      textNodes.push({ node, start: offset, end: offset + node.length });
      offset += node.length;
    });
  });
}

// Export for use in modules (if using ES6 modules)
if (typeof module !== 'undefined' && module.exports) {
  module.exports = {
    render,
    renderHighlightedText,
    escapeHtml,
    createSegments,
    sortSuggestions,
    getErrorClass,
    overlaySuggestions,
    clearOverlays
  };
}