File size: 10,829 Bytes
036913a
 
 
 
 
16da498
 
 
036913a
16da498
 
036913a
 
16da498
 
 
 
 
 
 
 
 
036913a
 
 
 
 
 
 
 
 
d4d18df
16da498
 
036913a
16da498
036913a
 
 
 
 
 
 
d4d18df
 
 
 
036913a
 
 
 
 
 
 
 
d4d18df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036913a
 
d4d18df
 
 
 
 
 
 
 
 
 
 
 
 
036913a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4d18df
036913a
 
 
d4d18df
 
 
 
 
 
 
 
 
 
036913a
d4d18df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036913a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4d18df
 
 
 
 
 
036913a
 
 
d4d18df
 
 
 
 
 
 
 
 
 
 
 
 
036913a
 
d4d18df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afdf449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1527e69
 
afdf449
1527e69
 
 
 
 
 
 
 
 
afdf449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036913a
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
// src/js/format.js
// Rich text formatting commands for the editor

/**
 * Execute a formatting command on the current selection
 * @param {string} command - execCommand name
 * @param {string} [value] - optional value
 * @param {boolean} [keepSelection] - if true, don't collapse selection
 */
function execFormat(command, value, keepSelection) {
  document.execCommand(command, false, value !== undefined ? value : null);
  const editor = getEditorElement();
  if (editor) editor.focus();
  
  // Collapse selection after formatting so text doesn't stay highlighted
  if (!keepSelection) {
    const sel = window.getSelection();
    if (sel && sel.rangeCount > 0 && !sel.isCollapsed) {
      sel.collapseToEnd();
    }
  }
  
  updateFormatState();
}

/* ── Text style ── */
function formatBold() { execFormat('bold'); }
function formatItalic() { execFormat('italic'); }
function formatUnderline() { execFormat('underline'); }
function formatStrikethrough() { execFormat('strikethrough'); }

/* ── Undo / Redo (handles both typing and formatting) ── */
function formatUndo() { execFormat('undo', undefined, true); }
function formatRedo() { execFormat('redo', undefined, true); }

/* ── Alignment (applies to paragraph containing selection/cursor) ── */
function formatAlignRight() { execFormat('justifyRight'); }
function formatAlignCenter() { execFormat('justifyCenter'); }
function formatAlignLeft() { execFormat('justifyLeft'); }

/* ── Font family ── */
function formatFont(fontName) {
  execFormat('fontName', fontName);
  // Update the dropdown label
  const label = document.getElementById('fmt-font-label');
  if (label) label.textContent = fontName;
  closeAllFmtDropdowns();
}

/* ── Font size ── */
function formatFontSize(size) {
  const sel = window.getSelection();
  if (!sel.rangeCount) return;

  const range = sel.getRangeAt(0);
  if (range.collapsed) {
    // No selection — size will apply to next typed text
    // Use a zero-width space trick
    const span = document.createElement('span');
    span.style.fontSize = size;
    span.textContent = '\u200B';
    range.insertNode(span);
    // Place cursor after the span
    const newRange = document.createRange();
    newRange.setStartAfter(span);
    newRange.collapse(true);
    sel.removeAllRanges();
    sel.addRange(newRange);
  } else {
    // Wrap selected text
    const span = document.createElement('span');
    span.style.fontSize = size;
    try {
      range.surroundContents(span);
    } catch (e) {
      // Fallback: use execCommand
      execFormat('fontSize', '4');
      const editor = getEditorElement();
      if (editor) {
        editor.querySelectorAll('font[size="4"]').forEach(f => {
          const s = document.createElement('span');
          s.style.fontSize = size;
          s.innerHTML = f.innerHTML;
          f.replaceWith(s);
        });
      }
    }
  }

  // Update label
  const label = document.getElementById('fmt-size-label');
  if (label) label.textContent = parseInt(size);
  
  // Update active item
  document.querySelectorAll('#fmt-size-menu .fmt-dropdown__item').forEach(item => {
    item.classList.toggle('fmt-dropdown__item--active', item.dataset.size === size);
  });

  closeAllFmtDropdowns();
  const editor = getEditorElement();
  if (editor) editor.focus();
  updateFormatState();
}

/**
 * Update toolbar button active states based on current selection
 */
function updateFormatState() {
  const btnMap = {
    'fmt-bold': 'bold',
    'fmt-italic': 'italic',
    'fmt-underline': 'underline',
    'fmt-strikethrough': 'strikeThrough',
  };

  Object.entries(btnMap).forEach(([id, command]) => {
    const btn = document.getElementById(id);
    if (btn) {
      btn.classList.toggle('fmt-active', document.queryCommandState(command));
    }
  });

  // Alignment — mutually exclusive
  const alignMap = {
    'fmt-align-right': 'justifyRight',
    'fmt-align-center': 'justifyCenter',
    'fmt-align-left': 'justifyLeft',
  };
  Object.entries(alignMap).forEach(([id, command]) => {
    const btn = document.getElementById(id);
    if (btn) {
      btn.classList.toggle('fmt-active', document.queryCommandState(command));
    }
  });
}

/**
 * Close all formatting dropdowns
 */
function closeAllFmtDropdowns() {
  document.querySelectorAll('.fmt-dropdown').forEach(d => d.classList.remove('open'));
}

/**
 * Toggle a specific dropdown
 */
function toggleFmtDropdown(wrapperId) {
  const wrap = document.getElementById(wrapperId);
  if (!wrap) return;
  const isOpen = wrap.classList.contains('open');
  closeAllFmtDropdowns();
  if (!isOpen) wrap.classList.add('open');
}

/**
 * Initialize formatting toolbar events
 */
function initFormatToolbar() {
  const editor = getEditorElement();
  if (!editor) return;

  // Update button states on selection change
  document.addEventListener('selectionchange', () => {
    if (editor.contains(document.activeElement) || editor === document.activeElement) {
      updateFormatState();
    }
  });

  // Font dropdown trigger
  const fontTrigger = document.getElementById('fmt-font-trigger');
  if (fontTrigger) {
    fontTrigger.addEventListener('click', (e) => {
      e.stopPropagation();
      toggleFmtDropdown('fmt-font-wrap');
    });
  }

  // Font items
  document.querySelectorAll('#fmt-font-menu .fmt-dropdown__item').forEach(item => {
    item.addEventListener('click', () => {
      formatFont(item.dataset.font);
    });
  });

  // Size dropdown trigger
  const sizeTrigger = document.getElementById('fmt-size-trigger');
  if (sizeTrigger) {
    sizeTrigger.addEventListener('click', (e) => {
      e.stopPropagation();
      toggleFmtDropdown('fmt-size-wrap');
    });
  }

  // Size items
  document.querySelectorAll('#fmt-size-menu .fmt-dropdown__item').forEach(item => {
    item.addEventListener('click', () => {
      formatFontSize(item.dataset.size);
    });
  });

  // Close dropdowns when clicking outside
  document.addEventListener('click', (e) => {
    if (!e.target.closest('.fmt-dropdown')) {
      closeAllFmtDropdowns();
    }
  });

  // Close dropdowns on Escape
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') closeAllFmtDropdowns();
  });

  // Item 8: Color pickers
  initColorPicker('fmt-textcolor', 'foreColor', 'fmt-textcolor-bar');
  initColorPicker('fmt-highlight', 'hiliteColor', 'fmt-highlight-bar');
}

/* ── Item 8: Color Picker ── */
const COLOR_PALETTE = [
  '#ECEEF2', '#E88A8A', '#E4B35A', '#6BC98A', '#6BA3E0', '#A594E8',
  '#F5F5F5', '#FF6B6B', '#FFD93D', '#51CF66', '#339AF0', '#845EF7',
  '#ADB5BD', '#C92A2A', '#F08C00', '#2B8A3E', '#1864AB', '#5F3DC4',
  '#495057', '#862E2E', '#B7791F', '#1B5E20', '#0D47A1', '#311B92',
  '#212529', '#000000', '#5D4037', '#004D40', '#1A237E', '#4A148C',
];

function initColorPicker(prefix, command, barId) {
  const trigger = document.getElementById(prefix + '-trigger');
  const wrap = document.getElementById(prefix + '-wrap');
  const grid = document.getElementById(prefix + '-grid');
  if (!trigger || !wrap || !grid) return;

  // Build swatches
  COLOR_PALETTE.forEach(color => {
    const swatch = document.createElement('button');
    swatch.type = 'button';
    swatch.className = 'fmt-color-swatch';
    swatch.style.background = color;
    swatch.title = color;
    swatch.addEventListener('click', () => {
      document.execCommand(command, false, color);
      const bar = document.getElementById(barId);
      if (bar) bar.style.background = color;
      closeAllFmtDropdowns();
      const editor = getEditorElement();
      if (editor) editor.focus();
    });
    grid.appendChild(swatch);
  });

  // Toggle
  trigger.addEventListener('click', (e) => {
    e.stopPropagation();
    toggleFmtDropdown(prefix + '-wrap');
  });
}

/* ── Item 4: Enhanced Stats ── */
function updateEnhancedStats() {
  const text = getEditorText();
  const charCount = text.length;
  
  // Count sentences: split on Arabic/Latin sentence endings + newlines
  const words = text.trim().split(/\s+/).filter(w => w.length > 0).length;
  let sentences = 0;
  if (text.trim().length > 0) {
    // Split by: . ! ? ؟ ، ؛ and newlines
    sentences = text.split(/[.!?؟\n]+/).filter(s => s.trim().length > 2).length;
    if (sentences === 0) sentences = 1; // at least 1 if there's text
  }
  
  // Reading time: ~180 words/min for Arabic, show actual minutes
  const readingTimeMinutes = words === 0 ? 0 : Math.max(1, Math.round(words / 180));

  const charEl = document.getElementById('char-count');
  const sentEl = document.getElementById('sentence-count');
  const readEl = document.getElementById('reading-time');

  if (charEl) charEl.textContent = charCount.toLocaleString('ar-EG');
  if (sentEl) sentEl.textContent = sentences.toLocaleString('ar-EG');
  if (readEl) readEl.textContent = readingTimeMinutes.toLocaleString('ar-EG');
}

/* ── Item 6: Summary Stats ── */
function updateSummaryStats(summaryText) {
  const originalText = getEditorText();
  const summaryWords = summaryText.trim().split(/\s+/).filter(w => w.length > 0).length;
  const originalWords = originalText.trim().split(/\s+/).filter(w => w.length > 0).length;
  const compression = originalWords > 0 ? Math.round((1 - summaryWords / originalWords) * 100) : 0;

  const statsEl = document.getElementById('summary-stats');
  const wordCountEl = document.getElementById('summary-word-count');
  const compressionEl = document.getElementById('summary-compression');

  if (statsEl) statsEl.style.display = 'flex';
  if (wordCountEl) wordCountEl.textContent = summaryWords;
  if (compressionEl) compressionEl.textContent = compression + '%';
}

/* ── Item 11: Summary Mode ── */
window._summaryMode = 'paragraph';

function setSummaryMode(mode) {
  window._summaryMode = mode;
  document.querySelectorAll('.summary-mode-btn').forEach(btn => {
    btn.classList.toggle('active', btn.id === 'summary-mode-' + mode);
  });
}

/* ── Item 3: Empty States ── */
function renderEmptyState(container, icon, title, desc) {
  if (!container) return;
  container.innerHTML = `
    <div class="empty-state">
      <div class="empty-state__icon">${icon}</div>
      <div class="empty-state__title">${title}</div>
      <div class="empty-state__desc">${desc}</div>
    </div>
  `;
}

/* ── Item 7: Document Search ── */
function initDocSearch() {
  const searchInput = document.getElementById('docs-search-input');
  if (!searchInput) return;

  searchInput.addEventListener('input', () => {
    const query = searchInput.value.trim().toLowerCase();
    const items = document.querySelectorAll('.doc-item');
    items.forEach(item => {
      const title = (item.textContent || '').toLowerCase();
      item.style.display = title.includes(query) || !query ? '' : 'none';
    });
  });
}