Mohamed Atef commited on
Commit ·
74411f9
1
Parent(s): 9784112
add the new version of the extention
Browse filesFiles changed (31)
- extension/IMPLEMENTATION_CHANGELOG.mdAdded+151
- extension/_locales/ar/messages.jsonAdded+18
- extension/_locales/en/messages.jsonAdded+18
- extension/background.jsAdded+234
- extension/content-inline.cssAdded+280
- extension/content-inline.jsAdded+685
- extension/content.jsAdded+11
- extension/manifest.jsonAdded+56
- extension/popup.cssAdded+769
- extension/popup.htmlAdded+308
- extension/popup.jsAdded+682
- extension/shared/analysis-controller.jsAdded+146
- extension/shared/bayan-api.jsAdded+133
- extension/shared/bayan-patches.jsAdded+152
- extension/shared/bayan-renderer.jsAdded+149
- extension/shared/bayan-state.jsAdded+127
- extension/shared/bayan-ui.jsAdded+99
- extension/shared/config.jsAdded+17
- extension/shared/constants.jsAdded+46
- extension/shared/hash.jsAdded+17
- extension/sidepanel/sidepanel.cssAdded+637
- extension/sidepanel/sidepanel.htmlAdded+303
- extension/sidepanel/sidepanel.jsAdded+709
- extension/tests/api_response_tc2.jsonAdded+41
- extension/tests/debug_offsets.ps1Added+14
- extension/tests/test_api_real.ps1Added+80
- extension/tests/test_e2e_real.htmlAdded+319
- extension/tests/test_inline.htmlAdded+78
- extension/tests/test_patches.htmlAdded+282
- extension/tests/test_patches.jsAdded+253
- extension/tests/test_patches.ps1Added+172
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151# BAYAN Extension — Implementation Changelog
> **Session date:** 2026-06-27> **Scope:** Chrome extension only (`extension/`). No backend, website, or Supabase changes.> **Source of work:** Implementation of the extension-facing items from `BAYAN_COMPLETE_AUDIT.md`.
---
## ⚠️ Important context
While this work was in progress, **a second process was editing the same extension files in parallel**, implementing the same audit plan. To avoid corrupting files, this session was scoped to the **untouched gaps**. As a result, the changes below fall into two groups:
- **Authored in this session** — Phase 5 (TXT export), Phase 6 (English locale, `all_frames`, bug fixes B4/U1), and the **completion of the broken Phase 4** (inline ghost-text autocomplete).- **Verified only** — Phases 1–3 (API client functions, popup/side-panel feature tabs) were written by the concurrent process; this session confirmed they are correct against the real backend (`src/app.py`) but did not author them.
This changelog documents **what was authored in this session**.
---
## Files changed
| File | Type | What changed ||------|------|--------------|| `extension/content-inline.js` | **Edited** | Implemented the missing inline ghost-text autocomplete engine (Phase 4); overlay reposition on resize (B4); tooltip viewport clamping (U1) || `extension/content-inline.css` | **Edited** | Styles for the ghost-text mirror + muted suffix || `extension/popup.js` | **Edited** | "Download as TXT" buttons for corrected text + summary (Phase 5 / H3) || `extension/sidepanel/sidepanel.js` | **Edited** | "Download as TXT" buttons for corrected text + summary (Phase 5 / H3) || `extension/manifest.json` | **Edited** | `all_frames: true` for iframe editor support (M2) || `extension/_locales/en/messages.json` | **Created** | English locale (L1) |
> `extension/shared/bayan-api.js`, `extension/popup.html`, `extension/sidepanel/sidepanel.html`, and the dialect/quran/autocomplete handlers in `popup.js` / `sidepanel.js` were authored by the **concurrent process**, not this session. They are listed in the "Verified only" section at the end.
---
## 1. Phase 4 — Inline ghost-text autocomplete (audit item H2)
**File:** `extension/content-inline.js`, `extension/content-inline.css`
### The bug this fixed (regression)
The concurrent process had added ghost-text **state variables** and a **call** to `scheduleGhost()` on every keystroke (in `onFieldInput`), but **never defined `scheduleGhost` or any ghost logic**. The content script therefore threw:
```ReferenceError: scheduleGhost is not defined```
…on **every keystroke in any editable field**, which silently broke inline analysis on every website. This was an active regression, not just a missing feature.
### What was implemented
A Tab-to-accept ghost-text engine for 3rd-party `<textarea>` / `<input>` fields, ported from the website's `src/js/autocomplete.js` behavior:
| Function | Role ||----------|------|| `ghostEligible()` | Only fires when the caret is collapsed **at the end** of the field, ≥3 chars, Arabic present || `scheduleGhost()` | 450 ms debounce; clears any stale ghost first || `fetchGhost(ctx)` | `POST {BAYAN.API_BASE}/api/autocomplete` with `{ context, n: 1 }`; staleness-guarded || `showGhost(base, suffix)` | Transparent-mirror overlay (same technique as the error overlay) painting the completion in muted grey at the caret || `acceptGhost()` | **Tab** appends the suggestion (+leading space if needed), moves caret to end, dispatches `input` to re-trigger analysis + next-word ghost || `clearGhost()` | Teardown — cancels timer, removes overlay, resets state || `syncGhostScroll()` | Keeps the ghost aligned with field scroll || `onFieldKeydown(e)` | **Tab** = accept, **Escape** = dismiss |
### Wiring added- `keydown` → `onFieldKeydown` registered in `attachField()`, removed in `detachField()`.- `clearGhost()` added to `detachField()` teardown.- `syncOverlay()` now also calls `syncGhostScroll()`.- The window `scroll` handler now repositions the ghost overlay (alongside the error overlay).
### Why a direct `fetch` (not `bayanAutocomplete`)The content script only loads `shared/constants.js`, `shared/analysis-controller.js`, and `content-inline.js` — **not** `bayan-api.js`/`config.js`. So `bayanAutocomplete()`/`CONFIG` are out of scope. `BAYAN.API_BASE` (from `constants.js`) **is** in scope, and `host_permissions` already covers that host, so the call is made directly.
### Safety properties- Overlay-only: never mutates the field while typing — only on explicit **Tab**.- Best-effort: network/render errors are swallowed; the analysis path is never affected.- Respects protected sites and is gated to `textarea`/`input` only.
### CSS added (`content-inline.css`)```css.bayan-il-ghost { background: transparent !important; pointer-events: none !important; }.bayan-il-ghost-suffix { color: rgba(120,120,130,0.75) !important; opacity: 0.9; }```(The suffix needs an explicit color because the mirror parent is `color: transparent`.)
---
## 2. Phase 5 — Download corrected text / summary as TXT (audit item H3)
**Files:** `extension/popup.js`, `extension/sidepanel/sidepanel.js`
- Added a self-contained `downloadTxt(text, filename)` helper (Blob + object URL + cleanup).- Download buttons are **injected programmatically** next to the existing copy buttons — no HTML edits, to minimize conflict with the concurrent writer.- Popup: downloads `bayan-corrected.txt` and `bayan-summary.txt`.- Side panel: same, anchored to the existing copy buttons' parent containers.
---
## 3. Phase 6 — Polish & bug fixes
### B4 — Overlay reposition on resize (`content-inline.js`)The window `resize` handler previously repositioned only the floating button. It now also **re-renders the error overlay** when suggestions are present, so highlights stay aligned after a viewport resize.
### U1 — Tooltip viewport clamping (`content-inline.js`)The error tooltip previously clamped only the right edge. It now also:- clamps the **left** edge if it overflows,- **flips above** the highlighted mark when it would overflow the **bottom** of the viewport (falling back to pinning at the top edge if there's no room above).
### M2 — iframe editor support (`manifest.json`)Added `"all_frames": true` to the content-script registration so editors inside `<iframe>` (TinyMCE, Gutenberg, etc.) are reachable.
### L1 — English locale (`_locales/en/messages.json`, new file)Created an English `messages.json` mirroring the Arabic keys (`extName`, `extDescription`, `contextMenuCorrect`, `contextMenuSummarize`) so the extension is publishable for non-Arabic users.
---
## Verification performed
- `node --check` passed on all edited JS files: `content-inline.js`, `popup.js`, `sidepanel/sidepanel.js`, `shared/bayan-api.js`.- JSON validated: `manifest.json`, `_locales/en/messages.json`, `_locales/ar/messages.json`.- Confirmed all eight ghost-text functions are defined, so the previously-orphaned `scheduleGhost()` call now resolves.
### NOT verified (no runtime/browser test in this session)- The extension was **not** loaded in Chrome. Caret-position rendering of ghost text across real sites, the new tabs, downloads, and iframe behavior are unverified by execution. See the testing guide below.
---
## How to test (manual, in Chrome)
The backend (`bayan10-bayan-api.hf.space`) is already live, so no local server is needed.
1. **Load:** `chrome://extensions` → enable **Developer mode** → **Load unpacked** → select `extension/`. Confirm no errors on the card; open the **service worker** console and confirm it's clean.2. **Popup tabs:** open the popup → expect 5 tabs (تصحيح · تلخيص · لهجة · قرآن · إكمال). Exercise each.3. **Export:** analyze text → click the download (↓) icon in the result header → `bayan-corrected.txt` downloads.4. **Ghost text (H2):** in a plain `<textarea>` (e.g. `extension/tests/test_inline.html`), type a few Arabic words ending in a space → grey ghost text appears after ~0.5 s → **Tab** inserts, **Esc** dismisses. Confirm **no** `scheduleGhost is not defined` error in the page console.5. **Regression checks:** resize the window with errors highlighted (B4 — stays aligned); click an error near the bottom (U1 — tooltip flips up); try a textarea inside an iframe (M2).
---
## Authored by the concurrent process (verified, not authored here)
For completeness — these extension changes exist but were **not** written in this session:
- `extension/shared/bayan-api.js` — `bayanDialect()`, `bayanQuran()`, `bayanAutocomplete()` (audit B3).- `extension/popup.html` + `extension/popup.js` — dialect / quran / autocomplete tabs + handlers (U3).- `extension/sidepanel/sidepanel.html` + `extension/sidepanel/sidepanel.js` — same three feature tabs + handlers.
---
## Out of scope (NOT done — still open from the 52-item audit)
This session covered extension items only. The following remain **open**: all Critical/Security backend items (C1–C3, S1–S7), extension auth (H1), the `002_documents.sql` migration (H4), the `app.py` split (H5), and the bulk of the Medium/Low backend, website, and performance items. See `BAYAN_COMPLETE_AUDIT.md` for the full list.123456789101112131415161718{ "extName": { "message": "بيان — مساعد الكتابة العربية", "description": "Extension name shown in Chrome" }, "extDescription": { "message": "تصحيح إملائي ونحوي وترقيمي للنصوص العربية مع تلخيص ذكي", "description": "Extension description shown in Chrome Web Store" }, "contextMenuCorrect": { "message": "تصحيح مع بيان", "description": "Context menu item for correcting selected text" }, "contextMenuSummarize": { "message": "تلخيص مع بيان", "description": "Context menu item for summarizing selected text" }}123456789101112131415161718{ "extName": { "message": "Bayan — Arabic Writing Assistant", "description": "Extension name shown in Chrome" }, "extDescription": { "message": "Spelling, grammar, and punctuation correction for Arabic text, with smart summarization.", "description": "Extension description shown in Chrome Web Store" }, "contextMenuCorrect": { "message": "Correct with Bayan", "description": "Context menu item for correcting selected text" }, "contextMenuSummarize": { "message": "Summarize with Bayan", "description": "Context menu item for summarizing selected text" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234/** * Bayan — Background Service Worker (Phase 7.1 Simplified) * * Single network boundary. Owns: * 1. Context menu → side panel (Phase 5) * 2. API calls with cache + timeout + retry (Phase 7) * * Uses: BAYAN (shared/constants.js), bayanHash (shared/hash.js) * loaded via importScripts(). */
importScripts('shared/constants.js', 'shared/hash.js');
// ── Context constants ──const ACTIONS = { CORRECT: 'correct', SUMMARIZE: 'summarize' };const CONTEXT_KEYS = ['contextAction', 'contextText', 'contextTimestamp'];const SIDE_PANEL_PATH = 'sidepanel/sidepanel.html';
// ── Deduplication cache ──const _cache = new Map();
function cacheGet(text) { const key = bayanHash(text); const entry = _cache.get(key); if (!entry) return null; if (Date.now() - entry.ts > BAYAN.CACHE_TTL_MS) { _cache.delete(key); return null; } if (entry.text !== text) return null; // FIX-19: LRU — move to end on access (Map maintains insertion order) _cache.delete(key); _cache.set(key, entry); return entry.data;}
function cacheSet(text, data) { const key = bayanHash(text); if (_cache.size >= BAYAN.CACHE_MAX_ENTRIES) { _cache.delete(_cache.keys().next().value); } _cache.set(key, { text, data, ts: Date.now() });}
// ── Storage helper ──function getStorage() { return chrome.storage?.session || chrome.storage?.local;}
// ══════════════════════════════════════════════════════════// Context Menu// ══════════════════════════════════════════════════════════
chrome.runtime.onInstalled.addListener(() => { chrome.contextMenus.create({ id: 'bayan-correct', title: chrome.i18n.getMessage('contextMenuCorrect') || 'تصحيح مع بيان', contexts: ['selection'], }); chrome.contextMenus.create({ id: 'bayan-summarize', title: chrome.i18n.getMessage('contextMenuSummarize') || 'تلخيص مع بيان', contexts: ['selection'], });});
chrome.contextMenus.onClicked.addListener((info, tab) => { const selectedText = info.selectionText?.trim(); if (!selectedText) return;
let action = null; if (info.menuItemId === 'bayan-correct') action = ACTIONS.CORRECT; if (info.menuItemId === 'bayan-summarize') action = ACTIONS.SUMMARIZE; if (!action) return;
// Open side panel IMMEDIATELY (preserve user gesture) if (chrome.sidePanel) { chrome.sidePanel.open({ windowId: tab.windowId }).catch(() => { chrome.tabs.create({ url: chrome.runtime.getURL(SIDE_PANEL_PATH) }); }); } else { chrome.tabs.create({ url: chrome.runtime.getURL(SIDE_PANEL_PATH) }); }
// Store context (async) const storage = getStorage(); storage.set({ contextAction: action, contextText: selectedText, contextTimestamp: Date.now(), }); setTimeout(() => storage.remove(CONTEXT_KEYS), 15000);});
// ══════════════════════════════════════════════════════════// Message Handler// ══════════════════════════════════════════════════════════
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === 'HEALTH_CHECK') { sendResponse({ status: 'ok', version: chrome.runtime.getManifest().version, cache: _cache.size, }); return true; }
if (message.type === 'CLEAR_CONTEXT') { getStorage().remove(CONTEXT_KEYS); sendResponse({ status: 'cleared' }); return true; }
if (message.type === 'INLINE_ANALYZE') { const text = message.text; if (!text || text.length < BAYAN.MIN_TEXT_LENGTH) { sendResponse({ error: 'Text too short' }); return true; } if (text.length > BAYAN.MAX_TEXT_LENGTH) { sendResponse({ error: 'Text too long' }); return true; }
// Cache hit → zero network const cached = cacheGet(text); if (cached) { sendResponse({ data: cached, cached: true }); return true; }
// Network call with retry analyzeWithRetry(text) .then((data) => { if (data) cacheSet(text, data); sendResponse({ data: data || null }); }) .catch((err) => { console.warn('[Bayan BG] Analysis error:', err.message); sendResponse({ error: err.message }); });
return true; }
if (message.type === 'INLINE_AUTOCOMPLETE') { const context = message.text || ''; if (!context || context.trim().length < 3) { sendResponse({ suggestions: [] }); return true; }
fetchAutocomplete(context) .then((data) => sendResponse({ suggestions: (data && data.suggestions) || [] })) .catch((err) => { console.warn('[Bayan BG] Autocomplete error:', err.message); sendResponse({ suggestions: [] }); });
return true; }
if (message.type === 'OPEN_SIDEPANEL') { const storage = getStorage(); storage.set({ contextAction: ACTIONS.CORRECT, contextText: message.text || '', contextTimestamp: Date.now(), }); if (chrome.sidePanel && sender.tab) { chrome.sidePanel.open({ windowId: sender.tab.windowId }).catch(() => { chrome.tabs.create({ url: chrome.runtime.getURL(SIDE_PANEL_PATH) }); }); } sendResponse({ status: 'ok' }); return true; }
return false;});
// ══════════════════════════════════════════════════════════// Network: fetch with timeout + 1 retry// ══════════════════════════════════════════════════════════
async function analyzeWithRetry(text, attempt = 0) { try { return await fetchWithTimeout(text); } catch (err) { if (attempt < BAYAN.MAX_RETRIES) { return analyzeWithRetry(text, attempt + 1); } throw err; }}
async function fetchWithTimeout(text) { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), BAYAN.API_TIMEOUT_MS);
try { const res = await fetch(`${BAYAN.API_BASE}/api/analyze`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }), signal: controller.signal, }); if (!res.ok) throw new Error(`API ${res.status}`); return await res.json(); } finally { clearTimeout(timeout); }}
// ══════════════════════════════════════════════════════════// Network: autocomplete (no retry — best-effort, short timeout)// ══════════════════════════════════════════════════════════
async function fetchAutocomplete(context) { const controller = new AbortController(); // Autocomplete must feel instant — cap well below the analyze timeout. const timeout = setTimeout(() => controller.abort(), 8000);
try { const res = await fetch(`${BAYAN.API_BASE}/api/autocomplete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ context, n: 1 }), signal: controller.signal, }); if (!res.ok) throw new Error(`API ${res.status}`); return await res.json(); } finally { clearTimeout(timeout); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280/* ══════════════════════════════════════════════ Bayan Inline Layer — Phase 6 All classes prefixed with bayan-il- to avoid conflicts. Uses !important sparingly to override page styles. ══════════════════════════════════════════════ */
/* ── Error highlights (contenteditable + overlay) ── */
.bayan-il-spelling { background: rgba(239, 68, 68, 0.12) !important; border-bottom: 2px solid #ef4444 !important; border-radius: 2px !important; cursor: pointer !important; transition: background 150ms ease !important;}.bayan-il-spelling:hover { background: rgba(239, 68, 68, 0.25) !important;}
.bayan-il-grammar { background: rgba(245, 158, 11, 0.12) !important; border-bottom: 2px solid #f59e0b !important; border-radius: 2px !important; cursor: pointer !important; transition: background 150ms ease !important;}.bayan-il-grammar:hover { background: rgba(245, 158, 11, 0.25) !important;}
.bayan-il-punctuation { background: rgba(59, 130, 246, 0.12) !important; border-bottom: 2px solid #3b82f6 !important; border-radius: 2px !important; cursor: pointer !important; transition: background 150ms ease !important;}.bayan-il-punctuation:hover { background: rgba(59, 130, 246, 0.25) !important;}
/* ── Floating Action Button (FAB) ── */
.bayan-il-fab { position: absolute; z-index: 2147483646 !important; width: 34px; height: 34px; display: flex; align-items: center; justify-content: center; background: #1a1a24 !important; border: 1px solid #3a3a4d !important; border-radius: 50% !important; cursor: pointer !important; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3) !important; opacity: 0; transform: scale(0.7); transition: opacity 200ms ease, transform 200ms cubic-bezier(0.34, 1.56, 0.64, 1) !important; pointer-events: none; user-select: none !important;}
.bayan-il-fab--visible { opacity: 1 !important; transform: scale(1) !important; pointer-events: auto !important;}
.bayan-il-fab:hover { border-color: #6366f1 !important; box-shadow: 0 2px 14px rgba(99, 102, 241, 0.3) !important;}
/* ── Badge (on FAB) ── */
.bayan-il-badge { position: absolute !important; top: -4px; right: -4px; min-width: 16px; height: 16px; display: flex; align-items: center; justify-content: center; font-size: 9px !important; font-weight: 700 !important; font-family: -apple-system, 'Segoe UI', sans-serif !important; border-radius: 8px !important; padding: 0 4px !important; line-height: 1 !important; border: 1.5px solid #1a1a24 !important; color: white !important; background: #6b6b80 !important;}
.bayan-il-badge--clean { background: #22c55e !important;}
.bayan-il-badge--errors { background: #ef4444 !important; animation: bayan-il-pulse 600ms ease-out !important;}
.bayan-il-badge--analyzing { background: #6366f1 !important; animation: bayan-il-spin 1s linear infinite !important;}
.bayan-il-badge--paused { background: #6b6b80 !important; opacity: 0.7 !important;}
@keyframes bayan-il-pulse { 0% { transform: scale(1); } 50% { transform: scale(1.3); } 100% { transform: scale(1); }}
@keyframes bayan-il-spin { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; }}
/* ── Tooltip (suggestion popup) ── */
.bayan-il-tooltip { position: absolute; z-index: 2147483647 !important; min-width: 200px; max-width: 320px; background: #1a1a24 !important; border: 1px solid #3a3a4d !important; border-radius: 10px !important; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(99, 102, 241, 0.1) !important; overflow: hidden; font-family: 'Segoe UI', Tahoma, Arial, sans-serif !important; font-size: 13px !important; color: #f0f0f5 !important; opacity: 0; transform: translateY(4px); transition: opacity 150ms ease, transform 150ms ease !important;}
.bayan-il-tooltip--visible { opacity: 1 !important; transform: translateY(0) !important;}
.bayan-il-tooltip-header { display: flex !important; align-items: center !important; justify-content: space-between !important; padding: 8px 12px !important; background: #22222e !important; border-bottom: 1px solid #2d2d3d !important;}
.bayan-il-tooltip-badge { display: inline-block !important; padding: 2px 8px !important; border-radius: 4px !important; font-size: 10px !important; font-weight: 700 !important;}
.bayan-il-badge-spelling { background: rgba(239, 68, 68, 0.15) !important; color: #ef4444 !important;}.bayan-il-badge-grammar { background: rgba(245, 158, 11, 0.15) !important; color: #f59e0b !important;}.bayan-il-badge-punctuation { background: rgba(59, 130, 246, 0.15) !important; color: #3b82f6 !important;}
.bayan-il-tooltip-close { background: none !important; border: none !important; color: #6b6b80 !important; cursor: pointer !important; font-size: 14px !important; padding: 2px !important; line-height: 1 !important;}.bayan-il-tooltip-close:hover { color: #f0f0f5 !important;}
.bayan-il-tooltip-body { display: flex !important; align-items: center !important; gap: 8px !important; padding: 10px 12px !important; font-size: 14px !important; line-height: 1.6 !important;}
.bayan-il-tooltip-original { color: #ef4444 !important; text-decoration: line-through !important; text-decoration-color: rgba(239, 68, 68, 0.4) !important;}
.bayan-il-tooltip-arrow { color: #6b6b80 !important; font-size: 12px !important;}
.bayan-il-tooltip-correction { color: #22c55e !important; font-weight: 600 !important;}
.bayan-il-tooltip-actions { display: flex !important; gap: 6px !important; padding: 8px 12px !important; border-top: 1px solid #2d2d3d !important; background: #22222e !important;}
.bayan-il-tooltip-apply { flex: 1; padding: 5px 12px !important; border: none !important; border-radius: 6px !important; background: linear-gradient(135deg, #6366f1, #4f46e5) !important; color: white !important; font-family: 'Segoe UI', Tahoma, sans-serif !important; font-size: 12px !important; font-weight: 600 !important; cursor: pointer !important; transition: transform 150ms ease, box-shadow 150ms ease !important;}.bayan-il-tooltip-apply:hover { transform: translateY(-1px) !important; box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3) !important;}
.bayan-il-tooltip-ignore { padding: 5px 12px !important; border: 1px solid #3a3a4d !important; border-radius: 6px !important; background: transparent !important; color: #9898ad !important; font-family: 'Segoe UI', Tahoma, sans-serif !important; font-size: 12px !important; cursor: pointer !important; transition: background 150ms ease !important;}.bayan-il-tooltip-ignore:hover { background: #2a2a38 !important; color: #f0f0f5 !important;}
/* ── Textarea overlay (transparent mirror) ── */
.bayan-il-overlay { background: transparent !important; pointer-events: none !important;}
/* ── Ghost-text autocomplete (transparent mirror + muted suffix) ── */
.bayan-il-ghost { background: transparent !important; pointer-events: none !important;}
.bayan-il-ghost-suffix { color: rgba(120, 120, 130, 0.75) !important; opacity: 0.9;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685/** * Bayan — Inline Analysis Engine (Phase 7.1 Simplified) * * Dependencies: BayanController (analysis-controller.js) * State: local variables only (no external state manager) * * Architecture: * 1. DETECTION — find editable fields * 2. ANALYSIS — debounced via BayanController → background.js * 3. OVERLAY — highlights, tooltip, FAB (never modifies user DOM content) * * Safety: * - Overlay-only rendering for ALL field types (never replaces innerHTML of user content) * - Trusted Types for Gmail/Google Sites * - Error boundary with graceful pause * - Protected sites: disable contenteditable on Gmail/Docs/Notion */
(function () { 'use strict';
if (window.location.protocol === 'chrome-extension:') return;
if (typeof BayanController === 'undefined') { console.error('[Bayan] BayanController not loaded.'); return; }
// ══════════════════════════════════════════════════════════ // Trusted Types // ══════════════════════════════════════════════════════════ let ttPolicy = null; try { if (window.trustedTypes?.createPolicy) { ttPolicy = window.trustedTypes.createPolicy('bayan-inline-policy', { createHTML: (input) => input, }); } } catch {}
function safeHTML(el, html) { try { el.innerHTML = ttPolicy ? ttPolicy.createHTML(html) : html; } catch { el.textContent = ''; const t = document.createElement('template'); t.innerHTML = html; el.appendChild(t.content.cloneNode(true)); } }
// ══════════════════════════════════════════════════════════ // Local state (replaces BayanState — simpler, no extra file) // ══════════════════════════════════════════════════════════ const IS_PROTECTED = BayanController.isProtectedSite();
let activeField = null; let lastAnalyzedText = ''; let suggestions = []; let paused = false; let floatingBtn = null; let tooltip = null; let overlayContainer = null; let badgeCount = null; let observer = null;
// ── Ghost-text autocomplete state ── let ghostEl = null; // the ghost overlay element let ghostSuggestion = ''; // pending completion string (suffix to insert) let ghostBaseText = ''; // field text the ghost was computed against let acDebounceTimer = null; const AC_DEBOUNCE_MS = 450; const AC_MIN_CONTEXT = 3;
// ══════════════════════════════════════════════════════════ // 1. DETECTION // ══════════════════════════════════════════════════════════
function isEditableField(el) { if (!el?.tagName) return false; const tag = el.tagName.toLowerCase(); if (tag === 'textarea') return true; if (tag === 'input') { const type = (el.type || '').toLowerCase(); return ['text', 'search', 'url', ''].includes(type); } // Contenteditable: allow on non-protected sites if (el.isContentEditable && !IS_PROTECTED) return true; return false; }
function getFieldText(field) { if (!field) return ''; const tag = field.tagName.toLowerCase(); if (tag === 'textarea' || tag === 'input') return field.value || ''; return field.innerText || field.textContent || ''; }
// ══════════════════════════════════════════════════════════ // 2. ANALYSIS (delegates to BayanController) // ══════════════════════════════════════════════════════════
function onFieldInput() { if (paused || !activeField) return;
const text = getFieldText(activeField);
// Ghost-text autocomplete (textarea/input only) runs independently of analysis. scheduleGhost();
if (!BayanController.hasArabic(text)) { clearHighlights(); updateBadge(0); return; }
updateBadge(-1);
BayanController.scheduleAnalysis( text, (result) => { try { onAnalysisResult(result); } catch (err) { console.warn('[Bayan] Callback error:', err.message); handleFailure('callback_error'); } }, () => getFieldText(activeField) ); }
function onAnalysisResult(data) { if (!activeField) return;
if (!data) { updateBadge(0); return; }
suggestions = data.suggestions || []; lastAnalyzedText = data.original || getFieldText(activeField); updateBadge(suggestions.length);
if (suggestions.length > 0) { renderOverlay(activeField, lastAnalyzedText, suggestions); } else { clearHighlights(); } }
// ══════════════════════════════════════════════════════════ // 2b. GHOST-TEXT AUTOCOMPLETE (textarea / input only) // // Mirrors the field (transparent text) and paints the predicted // completion in muted grey right at the caret (end of text). Tab // accepts, Escape dismisses. Best-effort and fully isolated: it // never throws into the analysis path, and only ever appends to // the field value on explicit accept (never mutates while typing). // ══════════════════════════════════════════════════════════
function ghostEligible() { if (!activeField || paused) return false; const tag = activeField.tagName.toLowerCase(); if (tag !== 'textarea' && tag !== 'input') return false; const val = activeField.value || ''; // Only when the caret is collapsed at the very end of the text. if (activeField.selectionStart !== val.length) return false; if (activeField.selectionEnd !== val.length) return false; if (val.trim().length < AC_MIN_CONTEXT) return false; return /[-ۿ]/.test(val); }
function scheduleGhost() { // Any keystroke invalidates a previously shown ghost. clearGhost(); if (!ghostEligible()) return;
const ctx = activeField.value; acDebounceTimer = setTimeout(() => { acDebounceTimer = null; fetchGhost(ctx); }, AC_DEBOUNCE_MS); }
async function fetchGhost(ctx) { let data; try { const res = await fetch(`${BAYAN.API_BASE}/api/autocomplete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ context: ctx, n: 1 }), }); if (!res.ok) return; data = await res.json(); } catch { return; // network error — silent (autocomplete is best-effort) }
// Staleness: field changed or caret moved during the fetch. if (!activeField || activeField.value !== ctx || !ghostEligible()) return;
const list = (data && data.suggestions) || []; const word = list.find((s) => s && s.trim()); if (!word) return;
// Insertion suffix: prepend a space when the context does not already end // with whitespace — mirrors the website's accept behaviour. const needsSpace = ctx.length > 0 && !/\s$/.test(ctx); ghostSuggestion = (needsSpace ? ' ' : '') + word.trim(); ghostBaseText = ctx; showGhost(ctx, ghostSuggestion); }
function showGhost(baseText, suffix) { if (ghostEl) { ghostEl.remove(); ghostEl = null; } if (!activeField || !suffix) return;
try { const rect = activeField.getBoundingClientRect(); const cs = window.getComputedStyle(activeField);
ghostEl = document.createElement('div'); ghostEl.className = 'bayan-il-ghost'; ghostEl.style.cssText = `position:absolute;top:${rect.top + window.scrollY}px;` + `left:${rect.left + window.scrollX}px;width:${rect.width}px;height:${rect.height}px;` + `font-family:${cs.fontFamily};font-size:${cs.fontSize};line-height:${cs.lineHeight};` + `padding:${cs.padding};border:${cs.border};border-color:transparent;` + `direction:${cs.direction};text-align:${cs.textAlign};overflow:hidden;` + `pointer-events:none;z-index:2147483645;box-sizing:border-box;` + `white-space:pre-wrap;word-wrap:break-word;color:transparent;`;
const html = esc(baseText) + `<span class="bayan-il-ghost-suffix">${esc(suffix)}</span>`; safeHTML(ghostEl, html); ghostEl.scrollTop = activeField.scrollTop; ghostEl.scrollLeft = activeField.scrollLeft; document.body.appendChild(ghostEl); } catch (err) { console.warn('[Bayan] Ghost render error:', err.message); clearGhost(); } }
function acceptGhost() { if (!ghostSuggestion || !activeField) return false; const tag = activeField.tagName.toLowerCase(); if (tag !== 'textarea' && tag !== 'input') return false; // Only accept if the field still matches what the ghost was computed for. if (activeField.value !== ghostBaseText) { clearGhost(); return false; }
const suffix = ghostSuggestion; activeField.value = ghostBaseText + suffix; const end = activeField.value.length; try { activeField.setSelectionRange(end, end); } catch {} clearGhost(); // Notify the page + our own pipeline (re-analysis + next-word ghost). activeField.dispatchEvent(new Event('input', { bubbles: true })); return true; }
function clearGhost() { if (acDebounceTimer) { clearTimeout(acDebounceTimer); acDebounceTimer = null; } if (ghostEl) { ghostEl.remove(); ghostEl = null; } ghostSuggestion = ''; ghostBaseText = ''; }
function syncGhostScroll() { if (ghostEl && activeField) { ghostEl.scrollTop = activeField.scrollTop; ghostEl.scrollLeft = activeField.scrollLeft; } }
function onFieldKeydown(e) { if (!ghostSuggestion) return; if (e.key === 'Tab') { e.preventDefault(); e.stopPropagation(); acceptGhost(); } else if (e.key === 'Escape') { clearGhost(); } }
// ══════════════════════════════════════════════════════════ // Error boundary // ══════════════════════════════════════════════════════════
function handleFailure(reason) { paused = true; clearHighlights(); BayanController.cancelAll(); if (badgeCount) { badgeCount.textContent = '⏸'; badgeCount.className = 'bayan-il-badge bayan-il-badge--paused'; } console.warn(`[Bayan] Inline paused: ${reason}. Side Panel still works.`); }
// ══════════════════════════════════════════════════════════ // 3. OVERLAY — always overlay, never modify user content // // Task 10: ALL field types use overlay rendering. // This prevents formatting destruction on Medium, Slack, // WordPress, Ghost, Discourse, etc. // ══════════════════════════════════════════════════════════
function renderOverlay(field, originalText, suggs) { clearHighlights(); if (!field || !suggs?.length) return;
try { const rect = field.getBoundingClientRect(); const cs = window.getComputedStyle(field);
overlayContainer = document.createElement('div'); overlayContainer.className = 'bayan-il-overlay'; overlayContainer.style.cssText = `position:absolute;top:${rect.top + window.scrollY}px;` + `left:${rect.left + window.scrollX}px;width:${rect.width}px;height:${rect.height}px;` + `font-family:${cs.fontFamily};font-size:${cs.fontSize};line-height:${cs.lineHeight};` + `padding:${cs.padding};border:${cs.border};border-color:transparent;` + `direction:${cs.direction};text-align:${cs.textAlign};overflow:hidden;` + `pointer-events:none;z-index:2147483645;box-sizing:border-box;` + `white-space:pre-wrap;word-wrap:break-word;color:transparent;`;
const sorted = [...suggs].sort((a, b) => a.start - b.start); let html = ''; let pos = 0;
sorted.forEach((s) => { if (pos < s.start) html += esc(originalText.slice(pos, s.start)); html += `<span class="${errCls(s.type)} bayan-il-error bayan-il-overlay-mark" ` + `data-bayan-sid="${s.id || ''}" data-bayan-original="${esc(s.original)}" ` + `data-bayan-correction="${esc(s.correction)}" data-bayan-type="${s.type}" ` + `data-bayan-start="${s.start}" data-bayan-end="${s.end}" ` + `style="pointer-events:auto;cursor:pointer;">` + `${esc(originalText.slice(s.start, s.end))}</span>`; pos = s.end; }); if (pos < originalText.length) html += esc(originalText.slice(pos));
safeHTML(overlayContainer, html); overlayContainer.scrollTop = field.scrollTop; overlayContainer.scrollLeft = field.scrollLeft; document.body.appendChild(overlayContainer);
overlayContainer.addEventListener('mousedown', (e) => e.preventDefault());
field.addEventListener('scroll', syncOverlay);
overlayContainer.querySelectorAll('.bayan-il-overlay-mark').forEach((mark) => { mark.addEventListener('click', (e) => { e.stopPropagation(); showTooltip(mark, activeField); }); }); } catch (err) { console.warn('[Bayan] Overlay error:', err.message); handleFailure('render_error'); } }
function syncOverlay() { if (overlayContainer && activeField) { overlayContainer.scrollTop = activeField.scrollTop; overlayContainer.scrollLeft = activeField.scrollLeft; } syncGhostScroll(); }
function clearHighlights() { if (overlayContainer) { overlayContainer.remove(); overlayContainer = null; } hideTooltip(); }
// ══════════════════════════════════════════════════════════ // Tooltip // ══════════════════════════════════════════════════════════
function showTooltip(el, field) { hideTooltip();
const original = el.dataset.bayanOriginal; const correction = el.dataset.bayanCorrection; const type = el.dataset.bayanType; const start = parseInt(el.dataset.bayanStart, 10); const end = parseInt(el.dataset.bayanEnd, 10); const sid = el.dataset.bayanSid;
if (!original || !correction) return;
const suggestion = { id: sid, original, correction, type, start, end }; const typeLabels = { spelling: 'إملائي', grammar: 'نحوي', punctuation: 'ترقيم' };
tooltip = document.createElement('div'); tooltip.className = 'bayan-il-tooltip'; tooltip.dir = 'rtl';
safeHTML(tooltip, ` <div class="bayan-il-tooltip-header"> <span class="bayan-il-tooltip-badge bayan-il-badge-${type}">${typeLabels[type] || type}</span> <button class="bayan-il-tooltip-close" title="إغلاق">✕</button> </div> <div class="bayan-il-tooltip-body"> <span class="bayan-il-tooltip-original">${esc(original)}</span> <span class="bayan-il-tooltip-arrow">←</span> <span class="bayan-il-tooltip-correction">${correction ? esc(correction) : '<s style="opacity:0.5">حذف</s>'}</span> </div> <div class="bayan-il-tooltip-actions"> <button class="bayan-il-tooltip-apply" data-action="apply">تطبيق</button> <button class="bayan-il-tooltip-ignore" data-action="ignore">تجاهل</button> </div> `);
document.body.appendChild(tooltip);
const r = el.getBoundingClientRect(); tooltip.style.top = `${r.bottom + window.scrollY + 6}px`; tooltip.style.left = `${r.left + window.scrollX}px`;
requestAnimationFrame(() => { if (!tooltip) return; const tr = tooltip.getBoundingClientRect(); // U1: clamp horizontally (right edge) and to the left edge if it overflows. if (tr.right > window.innerWidth) tooltip.style.left = `${window.innerWidth - tr.width - 8}px`; if (tr.left < 0) tooltip.style.left = `${window.scrollX + 8}px`; // U1: clamp vertically — if the tooltip overflows the bottom of the // viewport, flip it above the highlighted mark instead of below. if (tr.bottom > window.innerHeight) { const flippedTop = r.top + window.scrollY - tr.height - 6; // Only flip if there's room above; otherwise pin to the top edge. tooltip.style.top = flippedTop > window.scrollY ? `${flippedTop}px` : `${window.scrollY + 8}px`; } tooltip.classList.add('bayan-il-tooltip--visible'); });
tooltip.querySelector('[data-action="apply"]').addEventListener('click', () => { applyFix(field, suggestion); hideTooltip(); });
tooltip.querySelector('[data-action="ignore"]').addEventListener('click', () => { dismissSuggestion(suggestion); hideTooltip(); });
tooltip.querySelector('.bayan-il-tooltip-close').addEventListener('click', () => hideTooltip());
setTimeout(() => document.addEventListener('click', outsideClick, { once: true }), 100); }
function outsideClick(e) { if (tooltip && !tooltip.contains(e.target)) hideTooltip(); }
function hideTooltip() { if (tooltip) { tooltip.remove(); tooltip = null; } }
// ══════════════════════════════════════════════════════════ // Fix application (overlay-only: modify field value, re-render overlay) // ══════════════════════════════════════════════════════════
function applyFix(field, suggestion) { if (!field) return;
const isInput = field.tagName.toLowerCase() === 'textarea' || field.tagName.toLowerCase() === 'input'; const text = isInput ? field.value : getFieldText(field); const before = text.substring(0, suggestion.start); const after = text.substring(suggestion.end); const newText = before + suggestion.correction + after;
const delta = suggestion.correction.length - (suggestion.end - suggestion.start); suggestions = suggestions .filter((s) => s.id !== suggestion.id) .map((s) => s.start >= suggestion.end ? { ...s, start: s.start + delta, end: s.end + delta } : s);
lastAnalyzedText = newText;
if (isInput) { field.value = newText; field.dispatchEvent(new Event('input', { bubbles: true })); } else { // FIX-17: Use textContent instead of innerText for better compatibility // This preserves the DOM structure better than innerText assignment field.textContent = newText; }
if (suggestions.length > 0) { renderOverlay(field, newText, suggestions); } else { clearHighlights(); // FIX-21: Trigger re-analysis after applying last fix // This catches any remaining errors that were masked by the fixed one setTimeout(() => onFieldInput(), 500); } updateBadge(suggestions.length); }
function dismissSuggestion(suggestion) { suggestions = suggestions.filter((s) => s.id !== suggestion.id); if (suggestions.length > 0) { renderOverlay(activeField, lastAnalyzedText, suggestions); } else { clearHighlights(); } updateBadge(suggestions.length); }
// ══════════════════════════════════════════════════════════ // UI: FAB + Badge // ══════════════════════════════════════════════════════════
function createFloatingBtn() { if (floatingBtn) return;
floatingBtn = document.createElement('div'); floatingBtn.className = 'bayan-il-fab'; safeHTML(floatingBtn, ` <svg width="18" height="18" viewBox="0 0 100 100" fill="none"> <circle cx="50" cy="50" r="46" fill="url(#blGrad)" /> <path d="M30 55 Q35 35, 50 30 Q65 35, 70 55 Q65 65, 50 70 Q35 65, 30 55Z" fill="rgba(255,255,255,0.9)" /> <circle cx="50" cy="42" r="4" fill="url(#blGrad)" /> <defs> <linearGradient id="blGrad" x1="0" y1="0" x2="100" y2="100"> <stop offset="0%" stop-color="#6366f1"/> <stop offset="100%" stop-color="#8b5cf6"/> </linearGradient> </defs> </svg> <span class="bayan-il-badge">0</span> `); floatingBtn.title = 'Bayan — بيان'; document.body.appendChild(floatingBtn); badgeCount = floatingBtn.querySelector('.bayan-il-badge');
floatingBtn.addEventListener('click', (e) => { e.stopPropagation(); if (paused) { paused = false; updateBadge(0); onFieldInput(); return; } if (suggestions.length > 0) { try { chrome.runtime.sendMessage({ type: 'OPEN_SIDEPANEL', text: lastAnalyzedText }); } catch {} } }); }
function positionFab(field) { if (!floatingBtn || !field) return; const rect = field.getBoundingClientRect(); floatingBtn.style.top = `${Math.max(4, rect.top + window.scrollY + 6)}px`; floatingBtn.style.left = `${Math.max(4, rect.left + window.scrollX + 6)}px`; floatingBtn.classList.add('bayan-il-fab--visible'); }
function updateBadge(count) { if (!badgeCount) return; if (count === -1) { badgeCount.textContent = '…'; badgeCount.className = 'bayan-il-badge bayan-il-badge--analyzing'; } else if (count === 0) { badgeCount.textContent = '✓'; badgeCount.className = 'bayan-il-badge bayan-il-badge--clean'; } else { badgeCount.textContent = String(count); badgeCount.className = 'bayan-il-badge bayan-il-badge--errors'; } }
// ══════════════════════════════════════════════════════════ // Utilities // ══════════════════════════════════════════════════════════
function esc(text) { const m = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return String(text).replace(/[&<>"']/g, (c) => m[c]); }
function errCls(type) { return { spelling: 'bayan-il-spelling', grammar: 'bayan-il-grammar', punctuation: 'bayan-il-punctuation' }[type] || 'bayan-il-spelling'; }
// ══════════════════════════════════════════════════════════ // Field lifecycle (Task 7: no listener tracking leak) // // Per-field listeners use direct add/remove (NOT _trackedListeners). // Global listeners use addEventListener directly (cleaned on unload). // ══════════════════════════════════════════════════════════
function attachField(field) { if (activeField === field) return; detachField();
activeField = field; suggestions = []; if (paused) paused = false;
createFloatingBtn(); positionFab(field);
field.addEventListener('input', onFieldInput); field.addEventListener('keydown', onFieldKeydown); // FIX-20: Removed redundant 'keyup' listener (input event already fires on every change)
if (BayanController.hasArabic(getFieldText(field))) { onFieldInput(); } }
function detachField() { if (activeField) { activeField.removeEventListener('input', onFieldInput); activeField.removeEventListener('keydown', onFieldKeydown); // FIX-20: keyup listener no longer attached activeField.removeEventListener('scroll', syncOverlay); } clearHighlights(); clearGhost(); BayanController.cancelAll(); activeField = null; suggestions = []; if (floatingBtn) floatingBtn.classList.remove('bayan-il-fab--visible'); }
// ══════════════════════════════════════════════════════════ // Global listeners // ══════════════════════════════════════════════════════════
document.addEventListener('focusin', (e) => { if (isEditableField(e.target)) attachField(e.target); }, true);
document.addEventListener('focusout', () => { setTimeout(() => { if (!activeField) return; if (document.activeElement === activeField) return; const a = document.activeElement; if (tooltip?.contains(a)) return; if (floatingBtn?.contains(a)) return; if (overlayContainer?.contains(a)) return; if (document.querySelector('.bayan-il-tooltip')) return; detachField(); }, 300); }, true);
window.addEventListener('scroll', () => { if (activeField && floatingBtn) positionFab(activeField); if (overlayContainer && activeField) { const rect = activeField.getBoundingClientRect(); overlayContainer.style.top = `${rect.top + window.scrollY}px`; overlayContainer.style.left = `${rect.left + window.scrollX}px`; } if (ghostEl && activeField) { const rect = activeField.getBoundingClientRect(); ghostEl.style.top = `${rect.top + window.scrollY}px`; ghostEl.style.left = `${rect.left + window.scrollX}px`; } }, { passive: true });
window.addEventListener('resize', () => { if (activeField && floatingBtn) positionFab(activeField); // B4: a viewport resize can change the field's width/position, leaving the // overlay marks misaligned. Re-render the overlay (not just the FAB) so // highlights track the field. Guarded by suggestions to avoid needless work. if (overlayContainer && activeField && suggestions.length > 0) { renderOverlay(activeField, lastAnalyzedText, suggestions); } }, { passive: true });
// ── MutationObserver ── observer = new MutationObserver(() => { if (activeField && !document.body.contains(activeField)) detachField(); }); observer.observe(document.body, { childList: true, subtree: true });
// ── Log ── const mode = IS_PROTECTED ? 'protected' : 'full'; console.log(`[Bayan] Inline engine v7.1 (mode: ${mode}, TT: ${ttPolicy ? 'yes' : 'no'})`);})();1234567891011/** * Bayan Chrome Extension — Content Script * * Phase 1: Minimal stub — no DOM injection yet. * Phase 5: Will detect textarea/contenteditable and show floating icon. * Phase 6: Will apply suggestion patches to external page fields. * Phase 7: Will add live analysis with debounce. */
// Content script loaded — confirm injectionconsole.log('[Bayan] Content script loaded on:', window.location.hostname);1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556{ "manifest_version": 3, "name": "__MSG_extName__", "description": "__MSG_extDescription__", "version": "2.1.0", "minimum_chrome_version": "114", "default_locale": "ar",
"icons": { "16": "assets/icons/icon16.png", "48": "assets/icons/icon48.png", "128": "assets/icons/icon128.png" },
"action": { "default_popup": "popup.html", "default_icon": { "16": "assets/icons/icon16.png", "48": "assets/icons/icon48.png" }, "default_title": "__MSG_extName__" },
"side_panel": { "default_path": "sidepanel/sidepanel.html" },
"background": { "service_worker": "background.js" },
"permissions": [ "contextMenus", "activeTab", "storage", "sidePanel" ],
"host_permissions": [ "https://bayan10-bayan-api.hf.space/*" ],
"content_scripts": [ { "matches": ["https://*/*", "http://*/*"], "js": [ "shared/constants.js", "shared/analysis-controller.js", "content-inline.js" ], "css": ["content-inline.css"], "run_at": "document_idle", "all_frames": true } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769/* ══════════════════════════════════════════════ Bayan Chrome Extension — Popup Styles Arabic-first RTL | Dark mode | Premium feel ══════════════════════════════════════════════ */
/* ── Design Tokens ── */:root { --bayan-primary: #6366f1; --bayan-primary-light: #818cf8; --bayan-primary-dark: #4f46e5; --bayan-primary-glow: rgba(99, 102, 241, 0.25);
--bayan-bg: #0f0f14; --bayan-surface: #1a1a24; --bayan-surface-hover: #22222e; --bayan-surface-active: #2a2a38; --bayan-border: #2d2d3d; --bayan-border-light: #3a3a4d;
--bayan-text: #f0f0f5; --bayan-text-secondary: #9898ad; --bayan-text-muted: #6b6b80;
--bayan-success: #22c55e; --bayan-warning: #f59e0b; --bayan-error: #ef4444;
--bayan-spelling: #ef4444; --bayan-grammar: #f59e0b; --bayan-punctuation: #3b82f6;
--bayan-radius: 10px; --bayan-radius-sm: 6px; --bayan-radius-lg: 14px;
--bayan-font: 'Segoe UI', 'SF Pro', Tahoma, Arial, sans-serif; --bayan-font-arabic: 'Noto Sans Arabic', 'Segoe UI', Tahoma, sans-serif;
--bayan-transition: 200ms cubic-bezier(0.4, 0, 0.2, 1); --bayan-spring: 300ms cubic-bezier(0.34, 1.56, 0.64, 1);}
/* ── Reset ── */*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0;}
body { width: 400px; min-height: 300px; max-height: 600px; overflow-y: auto; overflow-x: hidden; font-family: var(--bayan-font-arabic); font-size: 14px; line-height: 1.6; color: var(--bayan-text); background: var(--bayan-bg); direction: rtl; -webkit-font-smoothing: antialiased;}
/* Custom scrollbar */body::-webkit-scrollbar { width: 4px;}body::-webkit-scrollbar-track { background: transparent;}body::-webkit-scrollbar-thumb { background: var(--bayan-border); border-radius: 4px;}
/* ══════════════════════════════════════════════ Header ══════════════════════════════════════════════ */.bayan-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: linear-gradient(135deg, var(--bayan-surface) 0%, var(--bayan-bg) 100%); border-bottom: 1px solid var(--bayan-border);}
.bayan-header-brand { display: flex; align-items: center; gap: 8px;}
.bayan-logo { filter: drop-shadow(0 0 8px var(--bayan-primary-glow));}
.bayan-header-title { font-size: 18px; font-weight: 700; background: linear-gradient(135deg, var(--bayan-primary-light), var(--bayan-primary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; letter-spacing: -0.3px;}
.bayan-header-status { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--bayan-text-muted);}
.bayan-status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--bayan-text-muted); transition: background var(--bayan-transition);}.bayan-status-dot.online { background: var(--bayan-success); box-shadow: 0 0 6px rgba(34, 197, 94, 0.5);}.bayan-status-dot.offline { background: var(--bayan-error); box-shadow: 0 0 6px rgba(239, 68, 68, 0.4);}
/* ══════════════════════════════════════════════ Tabs ══════════════════════════════════════════════ */.bayan-tabs { display: flex; gap: 0; border-bottom: 1px solid var(--bayan-border); background: var(--bayan-surface);}
.bayan-tab { flex: 1; display: flex; align-items: center; justify-content: center; gap: 4px; padding: 10px 4px; border: none; background: transparent; color: var(--bayan-text-muted); font-family: var(--bayan-font-arabic); font-size: 12px; font-weight: 500; cursor: pointer; transition: all var(--bayan-transition); position: relative; white-space: nowrap;}
.bayan-tab::after { content: ''; position: absolute; bottom: 0; left: 20%; right: 20%; height: 2px; background: var(--bayan-primary); border-radius: 2px 2px 0 0; opacity: 0; transform: scaleX(0); transition: all var(--bayan-spring);}
.bayan-tab:hover { color: var(--bayan-text); background: var(--bayan-surface-hover);}
.bayan-tab.active { color: var(--bayan-primary-light);}.bayan-tab.active::after { opacity: 1; transform: scaleX(1);}
/* ══════════════════════════════════════════════ Panels ══════════════════════════════════════════════ */.bayan-panel { display: none; padding: 16px; animation: fadeSlideIn 250ms ease-out;}.bayan-panel.active { display: block;}
@keyframes fadeSlideIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); }}
/* ══════════════════════════════════════════════ Input Group ══════════════════════════════════════════════ */.bayan-input-group { margin-bottom: 12px;}
.bayan-label { display: block; font-size: 12px; font-weight: 600; color: var(--bayan-text-secondary); margin-bottom: 6px;}
.bayan-textarea { width: 100%; min-height: 100px; padding: 12px 14px; border: 1px solid var(--bayan-border); border-radius: var(--bayan-radius); background: var(--bayan-surface); color: var(--bayan-text); font-family: var(--bayan-font-arabic); font-size: 14px; line-height: 1.8; resize: vertical; transition: border-color var(--bayan-transition), box-shadow var(--bayan-transition); direction: rtl;}
.bayan-textarea:focus { outline: none; border-color: var(--bayan-primary); box-shadow: 0 0 0 3px var(--bayan-primary-glow);}
.bayan-textarea::placeholder { color: var(--bayan-text-muted);}
.bayan-input-meta { display: flex; gap: 4px; margin-top: 6px; font-size: 11px; color: var(--bayan-text-muted);}
.bayan-separator { margin: 0 4px; opacity: 0.4;}
/* ══════════════════════════════════════════════ Buttons ══════════════════════════════════════════════ */.bayan-actions { display: flex; gap: 8px; margin-bottom: 14px;}
.bayan-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 9px 18px; border: none; border-radius: var(--bayan-radius-sm); font-family: var(--bayan-font-arabic); font-size: 13px; font-weight: 600; cursor: pointer; transition: all var(--bayan-transition);}
.bayan-btn-primary { flex: 1; background: linear-gradient(135deg, var(--bayan-primary), var(--bayan-primary-dark)); color: white; box-shadow: 0 2px 8px rgba(99, 102, 241, 0.3);}.bayan-btn-primary:hover { box-shadow: 0 4px 16px rgba(99, 102, 241, 0.45); transform: translateY(-1px);}.bayan-btn-primary:active { transform: translateY(0); box-shadow: 0 1px 4px rgba(99, 102, 241, 0.2);}
.bayan-btn-ghost { background: transparent; color: var(--bayan-text-secondary); border: 1px solid var(--bayan-border);}.bayan-btn-ghost:hover { background: var(--bayan-surface-hover); color: var(--bayan-text);}
.bayan-btn-sm { padding: 5px 12px; font-size: 11px; background: var(--bayan-primary); color: white; border-radius: var(--bayan-radius-sm);}.bayan-btn-sm:hover { background: var(--bayan-primary-dark);}
.bayan-btn-icon { display: flex; align-items: center; justify-content: center; width: 28px; height: 28px; padding: 0; border: none; border-radius: var(--bayan-radius-sm); background: transparent; color: var(--bayan-text-muted); cursor: pointer; transition: all var(--bayan-transition);}.bayan-btn-icon:hover { background: var(--bayan-surface-hover); color: var(--bayan-text);}
/* ══════════════════════════════════════════════ Score Ring ══════════════════════════════════════════════ */.bayan-score-section { display: flex; align-items: center; gap: 14px; padding: 12px; margin-bottom: 14px; background: var(--bayan-surface); border: 1px solid var(--bayan-border); border-radius: var(--bayan-radius); animation: fadeSlideIn 300ms ease-out;}
.bayan-score-ring { position: relative; width: 80px; height: 80px; flex-shrink: 0;}
.bayan-score-ring svg { display: block;}
.bayan-score-ring circle:last-child { transition: stroke-dashoffset 600ms cubic-bezier(0.34, 1.56, 0.64, 1);}
.bayan-score-value { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 700; color: var(--bayan-primary-light);}
.bayan-score-meta { flex: 1;}
.bayan-score-hint { display: block; font-size: 12px; color: var(--bayan-text-secondary); margin-bottom: 8px;}
.bayan-counts { display: flex; gap: 10px; flex-wrap: wrap;}
.bayan-count { font-size: 11px; color: var(--bayan-text-muted); display: flex; align-items: center; gap: 3px;}.bayan-count span { font-weight: 700;}.bayan-count-spelling span { color: var(--bayan-spelling); }.bayan-count-grammar span { color: var(--bayan-grammar); }.bayan-count-punctuation span { color: var(--bayan-punctuation); }
/* ══════════════════════════════════════════════ Result ══════════════════════════════════════════════ */.bayan-result { margin-bottom: 14px; animation: fadeSlideIn 300ms ease-out;}
.bayan-result-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px;}
.bayan-result-title { font-size: 12px; font-weight: 600; color: var(--bayan-text-secondary);}
.bayan-result-text { padding: 12px 14px; background: var(--bayan-surface); border: 1px solid var(--bayan-border); border-radius: var(--bayan-radius); font-size: 14px; line-height: 2; color: var(--bayan-text); min-height: 60px; word-wrap: break-word;}
/* Error highlights in result */.bayan-spelling-error { background: rgba(239, 68, 68, 0.15); border-bottom: 2px solid var(--bayan-spelling); border-radius: 2px; padding: 0 2px; cursor: pointer; transition: background var(--bayan-transition);}.bayan-spelling-error:hover { background: rgba(239, 68, 68, 0.25);}
.bayan-grammar-error { background: rgba(245, 158, 11, 0.15); border-bottom: 2px solid var(--bayan-grammar); border-radius: 2px; padding: 0 2px; cursor: pointer; transition: background var(--bayan-transition);}.bayan-grammar-error:hover { background: rgba(245, 158, 11, 0.25);}
.bayan-punctuation-suggestion { background: rgba(59, 130, 246, 0.15); border-bottom: 2px solid var(--bayan-punctuation); border-radius: 2px; padding: 0 2px; cursor: pointer; transition: background var(--bayan-transition);}.bayan-punctuation-suggestion:hover { background: rgba(59, 130, 246, 0.25);}
/* ══════════════════════════════════════════════ Suggestions List ══════════════════════════════════════════════ */.bayan-suggestions { animation: fadeSlideIn 300ms ease-out;}
.bayan-suggestions-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;}
.bayan-suggestions-title { font-size: 12px; font-weight: 600; color: var(--bayan-text-secondary);}
.bayan-suggestions-list { display: flex; flex-direction: column; gap: 8px;}
/* Autocomplete suggestion chips (إكمال tab) — horizontal wrap */#autocomplete-list { flex-direction: row; flex-wrap: wrap;}.bayan-ac-chip { cursor: pointer;}.bayan-ac-empty { color: var(--bayan-text-muted, #94a3b8); font-size: 13px; padding: 4px 2px;}
.bayan-suggestion-card { padding: 10px 12px; background: var(--bayan-surface); border: 1px solid var(--bayan-border); border-radius: var(--bayan-radius); cursor: pointer; transition: all var(--bayan-transition);}.bayan-suggestion-card:hover { border-color: var(--bayan-primary); background: var(--bayan-surface-hover); box-shadow: 0 0 0 1px var(--bayan-primary-glow);}
.bayan-suggestion-badge { display: inline-block; padding: 2px 8px; border-radius: 20px; font-size: 10px; font-weight: 700; margin-bottom: 6px;}
.bayan-badge-spelling { background: rgba(239, 68, 68, 0.15); color: var(--bayan-spelling);}.bayan-badge-grammar { background: rgba(245, 158, 11, 0.15); color: var(--bayan-grammar);}.bayan-badge-punctuation { background: rgba(59, 130, 246, 0.15); color: var(--bayan-punctuation);}
.bayan-suggestion-change { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; font-size: 13px;}
.bayan-suggestion-original { text-decoration: line-through; opacity: 0.55; color: var(--bayan-error);}
.bayan-suggestion-arrow { color: var(--bayan-text-muted); font-size: 12px;}
.bayan-suggestion-correction { font-weight: 600; color: var(--bayan-success);}
.bayan-suggestion-alts { display: flex; flex-wrap: wrap; gap: 6px;}
.bayan-alt-chip { padding: 4px 10px; border: 1px solid var(--bayan-border); border-radius: 20px; background: transparent; color: var(--bayan-text-secondary); font-family: var(--bayan-font-arabic); font-size: 11px; cursor: pointer; transition: all var(--bayan-transition);}.bayan-alt-chip:hover { border-color: var(--bayan-primary); color: var(--bayan-text); background: var(--bayan-surface-active);}
.bayan-alt-chip--main { background: var(--bayan-primary); border-color: var(--bayan-primary); color: white;}.bayan-alt-chip--main:hover { background: var(--bayan-primary-dark); color: white;}
.bayan-alt-chip--keep { opacity: 0.65;}.bayan-alt-chip--keep:hover { opacity: 1;}
/* ══════════════════════════════════════════════ Timing ══════════════════════════════════════════════ */.bayan-timing { padding: 8px 0; margin-top: 8px; border-top: 1px solid var(--bayan-border); font-size: 10px; color: var(--bayan-text-muted); text-align: center;}
/* ══════════════════════════════════════════════ Summary Meta ══════════════════════════════════════════════ */.bayan-summary-meta { margin-top: 10px; padding: 8px 12px; background: var(--bayan-surface-hover); border-radius: var(--bayan-radius-sm); font-size: 11px; color: var(--bayan-text-muted);}
/* ══════════════════════════════════════════════ Length Selector ══════════════════════════════════════════════ */.bayan-length-selector { margin-bottom: 12px;}
.bayan-radio-group { display: flex; gap: 12px;}
.bayan-radio { display: flex; align-items: center; gap: 4px; font-size: 12px; color: var(--bayan-text-secondary); cursor: pointer;}
.bayan-radio input[type="radio"] { accent-color: var(--bayan-primary); width: 14px; height: 14px; cursor: pointer;}
/* ══════════════════════════════════════════════ Loading Overlay ══════════════════════════════════════════════ */.bayan-loading { position: fixed; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px; background: rgba(15, 15, 20, 0.85); backdrop-filter: blur(4px); z-index: 100;}
.bayan-spinner { width: 36px; height: 36px; border: 3px solid var(--bayan-border); border-top-color: var(--bayan-primary); border-radius: 50%; animation: spin 0.8s linear infinite;}
@keyframes spin { to { transform: rotate(360deg); }}
.bayan-loading-text { font-size: 13px; color: var(--bayan-text-secondary);}
/* ══════════════════════════════════════════════ Toast ══════════════════════════════════════════════ */.bayan-toast { position: fixed; bottom: -50px; left: 50%; transform: translateX(-50%); padding: 8px 18px; background: var(--bayan-surface); border: 1px solid var(--bayan-border); border-radius: 20px; color: var(--bayan-text); font-size: 12px; font-family: var(--bayan-font-arabic); box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3); transition: bottom var(--bayan-spring); z-index: 200; white-space: nowrap;}.bayan-toast.is-visible { bottom: 16px;}
/* ══════════════════════════════════════════════ MED-2: Stale analysis indicator ══════════════════════════════════════════════ */.bayan-stale { opacity: 0.45; pointer-events: none; position: relative; filter: grayscale(30%); transition: opacity var(--bayan-transition), filter var(--bayan-transition);}.bayan-stale::after { content: '⚠ أعد التحليل'; position: absolute; top: 8px; left: 50%; transform: translateX(-50%); padding: 4px 12px; background: var(--bayan-warning); color: #000; font-size: 10px; font-weight: 700; border-radius: 12px; z-index: 10; pointer-events: none; white-space: nowrap;}
/* ══════════════════════════════════════════════ Utilities ══════════════════════════════════════════════ */.is-hidden { display: none !important;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308<!DOCTYPE html><html lang="ar" dir="rtl"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=400"> <title>بيان</title> <link rel="stylesheet" href="popup.css"></head><body> <!-- ══════════════════════════════════════════════ --> <!-- Header --> <!-- ══════════════════════════════════════════════ --> <header class="bayan-header"> <div class="bayan-header-brand"> <svg class="bayan-logo" width="28" height="28" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="46" fill="url(#logoGrad)" /> <path d="M30 55 Q35 35, 50 30 Q65 35, 70 55 Q65 65, 50 70 Q35 65, 30 55Z" fill="rgba(255,255,255,0.9)" /> <circle cx="50" cy="42" r="4" fill="url(#logoGrad)" /> <defs> <linearGradient id="logoGrad" x1="0" y1="0" x2="100" y2="100"> <stop offset="0%" stop-color="#6366f1"/> <stop offset="100%" stop-color="#8b5cf6"/> </linearGradient> </defs> </svg> <span class="bayan-header-title">بيان</span> </div> <div class="bayan-header-status" id="status-indicator"> <span class="bayan-status-dot"></span> <span class="bayan-status-text" id="status-text">جاهز</span> </div> </header>
<!-- ══════════════════════════════════════════════ --> <!-- Tab Navigation --> <!-- ══════════════════════════════════════════════ --> <nav class="bayan-tabs" role="tablist"> <button class="bayan-tab active" role="tab" aria-selected="true" data-tab="correct" id="tab-correct"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> تصحيح </button> <button class="bayan-tab" role="tab" aria-selected="false" data-tab="summarize" id="tab-summarize"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h10M4 18h14"/></svg> تلخيص </button> <button class="bayan-tab" role="tab" aria-selected="false" data-tab="dialect" id="tab-dialect"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"/></svg> لهجة </button> <button class="bayan-tab" role="tab" aria-selected="false" data-tab="quran" id="tab-quran"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg> قرآن </button> <button class="bayan-tab" role="tab" aria-selected="false" data-tab="autocomplete" id="tab-autocomplete"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg> إكمال </button> </nav>
<!-- ══════════════════════════════════════════════ --> <!-- Correct Panel --> <!-- ══════════════════════════════════════════════ --> <section class="bayan-panel active" id="panel-correct" role="tabpanel"> <!-- Input area --> <div class="bayan-input-group"> <label class="bayan-label" for="input-text">أدخل النص العربي</label> <textarea id="input-text" class="bayan-textarea" dir="rtl" placeholder="الصق أو اكتب النص هنا..." rows="5" maxlength="5000" ></textarea> <div class="bayan-input-meta"> <span id="char-count">٠</span> حرف <span class="bayan-separator">|</span> <span id="word-count">٠</span> كلمة </div> </div>
<!-- Action buttons --> <div class="bayan-actions"> <button class="bayan-btn bayan-btn-primary" id="btn-correct" type="button"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4"/></svg> تحليل وتصحيح </button> <button class="bayan-btn bayan-btn-ghost" id="btn-clear" type="button">مسح</button> </div>
<!-- Score ring --> <div class="bayan-score-section is-hidden" id="score-section"> <div class="bayan-score-ring"> <svg viewBox="0 0 160 160" width="80" height="80"> <circle cx="80" cy="80" r="70" fill="none" stroke="var(--bayan-border)" stroke-width="8"/> <circle cx="80" cy="80" r="70" fill="none" stroke="var(--bayan-primary)" stroke-width="8" stroke-dasharray="440" stroke-dashoffset="440" stroke-linecap="round" transform="rotate(-90 80 80)" id="score-circle"/> </svg> <span class="bayan-score-value" id="score-value">--</span> </div> <div class="bayan-score-meta"> <span class="bayan-score-hint" id="score-hint">ابدأ الكتابة لرؤية تقييمك</span> <div class="bayan-counts" id="error-counts"> <span class="bayan-count bayan-count-spelling"><span id="count-spelling">٠</span> إملائي</span> <span class="bayan-count bayan-count-grammar"><span id="count-grammar">٠</span> نحوي</span> <span class="bayan-count bayan-count-punctuation"><span id="count-punctuation">٠</span> ترقيم</span> </div> </div> </div>
<!-- Corrected text result --> <div class="bayan-result is-hidden" id="result-section"> <div class="bayan-result-header"> <span class="bayan-result-title">النص المصحّح</span> <button class="bayan-btn-icon" id="btn-copy-result" type="button" title="نسخ"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" stroke-width="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke-width="2"/></svg> </button> </div> <div class="bayan-result-text" id="result-text" dir="rtl"></div> </div>
<!-- Suggestions list --> <div class="bayan-suggestions is-hidden" id="suggestions-section"> <div class="bayan-suggestions-header"> <span class="bayan-suggestions-title">الاقتراحات</span> <button class="bayan-btn bayan-btn-sm" id="btn-apply-all" type="button">تطبيق الكل</button> </div> <div class="bayan-suggestions-list" id="suggestions-list" role="list"></div> </div>
<!-- Timing info --> <div class="bayan-timing is-hidden" id="timing-section"> <span id="timing-text"></span> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Summarize Panel --> <!-- ══════════════════════════════════════════════ --> <section class="bayan-panel" id="panel-summarize" role="tabpanel"> <!-- Input area --> <div class="bayan-input-group"> <label class="bayan-label" for="summary-input-text">أدخل النص للتلخيص</label> <textarea id="summary-input-text" class="bayan-textarea" dir="rtl" placeholder="الصق النص المراد تلخيصه..." rows="5" maxlength="5000" ></textarea> <div class="bayan-input-meta"> <span id="summary-char-count">٠</span> حرف </div> </div>
<!-- Length selector --> <div class="bayan-length-selector"> <label class="bayan-label">طول الملخص</label> <div class="bayan-radio-group"> <label class="bayan-radio"><input type="radio" name="summary-length" value="1"> قصير</label> <label class="bayan-radio"><input type="radio" name="summary-length" value="2" checked> متوسط</label> <label class="bayan-radio"><input type="radio" name="summary-length" value="3"> طويل</label> </div> </div>
<!-- Action --> <div class="bayan-actions"> <button class="bayan-btn bayan-btn-primary" id="btn-summarize" type="button"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h10M4 18h14"/></svg> تلخيص </button> </div>
<!-- Summary result --> <div class="bayan-result is-hidden" id="summary-result-section"> <div class="bayan-result-header"> <span class="bayan-result-title">الملخص</span> <button class="bayan-btn-icon" id="btn-copy-summary" type="button" title="نسخ"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" stroke-width="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke-width="2"/></svg> </button> </div> <div class="bayan-result-text" id="summary-text" dir="rtl"></div> <div class="bayan-summary-meta" id="summary-meta"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Dialect Panel (لهجة → فصحى) --> <!-- ══════════════════════════════════════════════ --> <section class="bayan-panel" id="panel-dialect" role="tabpanel"> <div class="bayan-input-group"> <label class="bayan-label" for="dialect-input-text">حوّل العامية إلى الفصحى</label> <textarea id="dialect-input-text" class="bayan-textarea" dir="rtl" placeholder="أدخل نصاً بالعامية..." rows="5" maxlength="5000" ></textarea> <div class="bayan-input-meta"><span id="dialect-char-count">٠</span> حرف</div> </div> <div class="bayan-actions"> <button class="bayan-btn bayan-btn-primary" id="btn-dialect" type="button"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg> تحويل إلى الفصحى </button> </div> <div class="bayan-result is-hidden" id="dialect-result-section"> <div class="bayan-result-header"> <span class="bayan-result-title">النص بالفصحى</span> <button class="bayan-btn-icon" id="btn-copy-dialect" type="button" title="نسخ"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" stroke-width="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke-width="2"/></svg> </button> </div> <div class="bayan-result-text" id="dialect-text" dir="rtl"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Quran Panel (تدقيق الآيات) --> <!-- ══════════════════════════════════════════════ --> <section class="bayan-panel" id="panel-quran" role="tabpanel"> <div class="bayan-input-group"> <label class="bayan-label" for="quran-input-text">تدقيق الآيات القرآنية</label> <textarea id="quran-input-text" class="bayan-textarea" dir="rtl" placeholder="أدخل آية أو جزءاً منها..." rows="5" maxlength="2000" ></textarea> <div class="bayan-input-meta"><span id="quran-char-count">٠</span> حرف</div> </div> <div class="bayan-actions"> <button class="bayan-btn bayan-btn-primary" id="btn-quran" type="button"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg> تدقيق الآية </button> </div> <div class="bayan-result is-hidden" id="quran-result-section"> <div class="bayan-result-header"> <span class="bayan-result-title">نتيجة التدقيق</span> <button class="bayan-btn-icon" id="btn-copy-quran" type="button" title="نسخ"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" stroke-width="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke-width="2"/></svg> </button> </div> <div class="bayan-result-text" id="quran-text" dir="rtl"></div> <div class="bayan-summary-meta" id="quran-meta"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Autocomplete Panel (إكمال) --> <!-- ══════════════════════════════════════════════ --> <section class="bayan-panel" id="panel-autocomplete" role="tabpanel"> <div class="bayan-input-group"> <label class="bayan-label" for="autocomplete-input-text">اقتراحات إكمال الجملة</label> <textarea id="autocomplete-input-text" class="bayan-textarea" dir="rtl" placeholder="اكتب بداية الجملة..." rows="5" maxlength="5000" ></textarea> <div class="bayan-input-meta"><span id="autocomplete-char-count">٠</span> حرف</div> </div> <div class="bayan-actions"> <button class="bayan-btn bayan-btn-primary" id="btn-autocomplete" type="button"> <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg> اقترح إكمالاً </button> </div> <div class="bayan-suggestions is-hidden" id="autocomplete-result-section"> <div class="bayan-suggestions-header"> <span class="bayan-suggestions-title">اقتراحات الإكمال</span> </div> <div class="bayan-suggestions-list" id="autocomplete-list" role="list"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Loading overlay --> <!-- ══════════════════════════════════════════════ --> <div class="bayan-loading is-hidden" id="loading-overlay"> <div class="bayan-spinner"></div> <span class="bayan-loading-text" id="loading-text">جارٍ التحليل...</span> </div>
<!-- ══════════════════════════════════════════════ --> <!-- Toast --> <!-- ══════════════════════════════════════════════ --> <div class="bayan-toast" id="toast" role="status" aria-live="polite"></div>
<!-- Scripts: constants first, then config, then shared modules, then popup logic --> <script src="shared/constants.js"></script> <script src="shared/config.js"></script> <script src="shared/bayan-renderer.js"></script> <script src="shared/bayan-ui.js"></script> <script src="shared/bayan-patches.js"></script> <script src="shared/bayan-api.js"></script> <script src="popup.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682/** * Bayan Chrome Extension — Popup Logic * * Fixes applied: * HIGH-1: Offset rebasing via applyAndRebase() after each individual apply * MED-1: Clipboard .catch() on all writeText() calls * MED-2: Staleness detection — locks corrections when user edits after analysis */
document.addEventListener('DOMContentLoaded', () => { // ── Element references ── const inputText = document.getElementById('input-text'); const charCount = document.getElementById('char-count'); const wordCount = document.getElementById('word-count'); const btnCorrect = document.getElementById('btn-correct'); const btnClear = document.getElementById('btn-clear'); const btnApplyAll = document.getElementById('btn-apply-all'); const btnCopyResult = document.getElementById('btn-copy-result'); const scoreSection = document.getElementById('score-section'); const resultSection = document.getElementById('result-section'); const resultText = document.getElementById('result-text'); const suggestionsSection = document.getElementById('suggestions-section'); const suggestionsList = document.getElementById('suggestions-list'); const timingSection = document.getElementById('timing-section'); const timingText = document.getElementById('timing-text'); const loadingOverlay = document.getElementById('loading-overlay'); const loadingTextEl = document.getElementById('loading-text');
// Summary tab elements const summaryInputText = document.getElementById('summary-input-text'); const summaryCharCount = document.getElementById('summary-char-count'); const btnSummarize = document.getElementById('btn-summarize'); const summaryResultSection = document.getElementById('summary-result-section'); const summaryText = document.getElementById('summary-text'); const summaryMeta = document.getElementById('summary-meta'); const btnCopySummary = document.getElementById('btn-copy-summary');
// Score elements const scoreValue = document.getElementById('score-value'); const scoreCircle = document.getElementById('score-circle'); const scoreHint = document.getElementById('score-hint'); const countSpelling = document.getElementById('count-spelling'); const countGrammar = document.getElementById('count-grammar'); const countPunctuation = document.getElementById('count-punctuation');
// ══════════════════════════════════════════════════════════ // State // ══════════════════════════════════════════════════════════ let currentSuggestions = [];
/** * MED-2: Snapshot of the text that was last analyzed. * All suggestion offsets are relative to THIS text. * applyAndRebase() mutates this alongside suggestions. */ let analyzedText = '';
/** * MED-2: Whether the analysis results are stale. * Set to true when the user edits the textarea after analysis. * When stale, suggestion actions are blocked. */ let isStale = false;
const SCORE_CIRCUMFERENCE = 440;
// ══════════════════════════════════════════════════════════ // Tab switching // ══════════════════════════════════════════════════════════ document.querySelectorAll('.bayan-tab').forEach((tab) => { tab.addEventListener('click', () => { const targetTab = tab.dataset.tab; document.querySelectorAll('.bayan-tab').forEach((t) => { t.classList.toggle('active', t.dataset.tab === targetTab); t.setAttribute('aria-selected', t.dataset.tab === targetTab ? 'true' : 'false'); }); document.querySelectorAll('.bayan-panel').forEach((p) => { p.classList.toggle('active', p.id === `panel-${targetTab}`); }); }); });
// ══════════════════════════════════════════════════════════ // Character & word counter // ══════════════════════════════════════════════════════════ function updateCounts(textarea, charEl, wordEl) { const text = textarea.value; const chars = text.length; const words = text.trim() ? text.trim().split(/\s+/).length : 0; if (charEl) charEl.textContent = chars.toLocaleString('ar-EG'); if (wordEl) wordEl.textContent = words.toLocaleString('ar-EG'); }
inputText.addEventListener('input', () => { updateCounts(inputText, charCount, wordCount);
// MED-2: Detect user edit after analysis → mark stale if (currentSuggestions.length > 0 && inputText.value !== analyzedText) { markStale(); } });
summaryInputText.addEventListener('input', () => updateCounts(summaryInputText, summaryCharCount, null));
// ══════════════════════════════════════════════════════════ // MED-2: Staleness management // ══════════════════════════════════════════════════════════
/** * Mark analysis results as stale (user edited textarea). * Disables suggestion actions and shows a re-analysis prompt. */ function markStale() { if (isStale) return; // already stale isStale = true;
// Visual indicator: dim the results area if (resultSection) resultSection.classList.add('bayan-stale'); if (suggestionsSection) suggestionsSection.classList.add('bayan-stale');
// Show re-analysis toast showToast('⚠ النص تغيّر — أعد التحليل لتحديث الاقتراحات', 4000);
// Update button text to indicate re-analysis needed btnCorrect.innerHTML = ` <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h5M20 20v-5h-5M4 9a8 8 0 0114-3M20 15a8 8 0 01-14 3"/></svg> إعادة التحليل`; }
/** * Clear staleness (after re-analysis or clear). */ function clearStale() { isStale = false; if (resultSection) resultSection.classList.remove('bayan-stale'); if (suggestionsSection) suggestionsSection.classList.remove('bayan-stale');
// Restore button text btnCorrect.innerHTML = ` <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4"/></svg> تحليل وتصحيح`; }
// ══════════════════════════════════════════════════════════ // Loading state // ══════════════════════════════════════════════════════════ function setLoading(show, text = 'جارٍ التحليل...') { loadingOverlay.classList.toggle('is-hidden', !show); loadingTextEl.textContent = text; }
// ══════════════════════════════════════════════════════════ // Toast // ══════════════════════════════════════════════════════════ function showToast(message, duration = 2500) { const toast = document.getElementById('toast'); toast.textContent = message; toast.classList.add('is-visible'); clearTimeout(toast._timer); toast._timer = setTimeout(() => toast.classList.remove('is-visible'), duration); }
// ══════════════════════════════════════════════════════════ // Score ring // ══════════════════════════════════════════════════════════ function updateScore(spelling, grammar, punctuation) { const score = calculateWritingScore(spelling, grammar, punctuation); const total = spelling + grammar + punctuation;
scoreSection.classList.remove('is-hidden');
if (scoreValue) { scoreValue.textContent = score > 0 || total > 0 ? score.toLocaleString('ar-EG') : '--'; } if (scoreCircle) { const offset = SCORE_CIRCUMFERENCE - (score / 100) * SCORE_CIRCUMFERENCE; scoreCircle.style.strokeDashoffset = String(offset); } if (scoreHint) { scoreHint.textContent = getScoreHint(score, total); } if (countSpelling) countSpelling.textContent = spelling.toLocaleString('ar-EG'); if (countGrammar) countGrammar.textContent = grammar.toLocaleString('ar-EG'); if (countPunctuation) countPunctuation.textContent = punctuation.toLocaleString('ar-EG'); }
// ══════════════════════════════════════════════════════════ // Render suggestions list // ══════════════════════════════════════════════════════════ function renderSuggestions(suggestions) { currentSuggestions = suggestions;
if (!suggestions || suggestions.length === 0) { suggestionsSection.classList.add('is-hidden'); return; }
suggestionsSection.classList.remove('is-hidden'); const html = suggestions.map((s, i) => buildSuggestionCardHTML(s, i)).join(''); suggestionsList.innerHTML = html;
// Bind suggestion card events suggestionsList.querySelectorAll('.bayan-alt-chip').forEach((chip) => { chip.addEventListener('click', (e) => { e.stopPropagation();
// MED-2: Block if stale if (isStale) { showToast('⚠ أعد التحليل أولاً — النص تغيّر'); return; }
const suggestionId = chip.dataset.cardId; const altText = chip.dataset.cardAlt; const suggestion = currentSuggestions.find((s) => String(s.id || '') === String(suggestionId)); if (!suggestion) return;
if (altText === suggestion.original) { // Dismiss — remove from list, no text change, no rebase needed currentSuggestions = removeSuggestion(currentSuggestions, suggestion.id); } else { // ═══════════════════════════════════════════════════ // HIGH-1 FIX: Apply + Rebase via atomic function // ═══════════════════════════════════════════════════ const result = applyAndRebase(analyzedText, suggestion, altText, currentSuggestions); analyzedText = result.text; currentSuggestions = result.suggestions;
// Sync textarea with the rebased text inputText.value = analyzedText; updateCounts(inputText, charCount, wordCount); }
// Re-render score and suggestions const counts = countByType(currentSuggestions); updateScore(counts.spelling, counts.grammar, counts.punctuation); renderSuggestions(currentSuggestions);
// Re-render highlighted text with updated offsets resultText.innerHTML = renderHighlightedText(analyzedText, currentSuggestions);
showToast('✓ تم التصحيح'); }); });
// Show apply-all only when >= 2 btnApplyAll.classList.toggle('is-hidden', suggestions.length < 2); }
// ══════════════════════════════════════════════════════════ // Clear button // ══════════════════════════════════════════════════════════ btnClear.addEventListener('click', () => { inputText.value = ''; analyzedText = ''; updateCounts(inputText, charCount, wordCount); scoreSection.classList.add('is-hidden'); resultSection.classList.add('is-hidden'); suggestionsSection.classList.add('is-hidden'); timingSection.classList.add('is-hidden'); currentSuggestions = []; clearStale(); });
// ══════════════════════════════════════════════════════════ // Correct button // ══════════════════════════════════════════════════════════ btnCorrect.addEventListener('click', async () => { const text = inputText.value.trim(); if (!text) { showToast('أدخل نصاً للتحليل'); return; } if (text.length < CONFIG.MIN_ANALYZE_LENGTH) { showToast('النص قصير جداً (الحد الأدنى ١٥ حرفاً)'); return; } if (text.length > CONFIG.MAX_ANALYZE_LENGTH) { showToast('النص طويل جداً (الحد الأقصى ٥٠٠٠ حرف)'); return; }
setLoading(true, 'جارٍ التحليل...'); clearStale(); // MED-2: Clear stale on re-analysis
try { const data = await bayanAnalyze(text);
if (data.status === 'success' || data.status === 'partial') { const suggestions = sortSuggestions(data.suggestions || []); currentSuggestions = suggestions;
// MED-2: Snapshot the analyzed text — all offsets reference THIS string analyzedText = data.original; // Sync textarea to the exact text the backend analyzed inputText.value = analyzedText; updateCounts(inputText, charCount, wordCount);
// Show corrected text with highlights resultSection.classList.remove('is-hidden'); resultText.innerHTML = renderHighlightedText(analyzedText, suggestions);
// Update score const counts = countByType(suggestions); updateScore(counts.spelling, counts.grammar, counts.punctuation);
// Render suggestion cards renderSuggestions(suggestions);
// Show timing if (data.timing_ms) { timingSection.classList.remove('is-hidden'); timingText.textContent = `التحليل: ${data.timing_ms.total_ms || 0}ms (إملائي: ${data.timing_ms.spelling_ms || 0}ms، نحوي: ${data.timing_ms.grammar_ms || 0}ms، ترقيم: ${data.timing_ms.punctuation_ms || 0}ms)`; }
if (suggestions.length === 0) { showToast('نصك ممتاز! لم نجد أي أخطاء ✨'); } } else { showToast('تعذّر التحليل — حاول مرة أخرى'); } } catch (error) { console.error('[Bayan] Analysis error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
// ══════════════════════════════════════════════════════════ // Apply all button // ══════════════════════════════════════════════════════════ btnApplyAll.addEventListener('click', () => { if (currentSuggestions.length === 0) return;
// MED-2: Block if stale if (isStale) { showToast('⚠ أعد التحليل أولاً — النص تغيّر'); return; }
// Apply all patches using reverse-order (no rebase needed — all applied at once) analyzedText = applyAllPatches(analyzedText, currentSuggestions); inputText.value = analyzedText; updateCounts(inputText, charCount, wordCount); currentSuggestions = []; resultText.innerHTML = escapeHtml(analyzedText); updateScore(0, 0, 0); renderSuggestions([]); showToast('✓ تم تطبيق جميع التصحيحات'); });
// ══════════════════════════════════════════════════════════ // Copy result (MED-1: .catch() for clipboard errors) // ══════════════════════════════════════════════════════════ btnCopyResult.addEventListener('click', () => { const text = resultText.textContent || ''; navigator.clipboard.writeText(text) .then(() => showToast('✓ تم نسخ النص')) .catch(() => showToast('تعذّر النسخ')); });
// ══════════════════════════════════════════════════════════ // Summarize button // ══════════════════════════════════════════════════════════ btnSummarize.addEventListener('click', async () => { const text = summaryInputText.value.trim(); if (!text) { showToast('أدخل نصاً للتلخيص'); return; } if (text.length < CONFIG.MIN_SUMMARIZE_LENGTH) { showToast('النص قصير جداً للتلخيص'); return; }
const lengthValue = parseInt(document.querySelector('input[name="summary-length"]:checked')?.value || '2', 10);
setLoading(true, 'جارٍ التلخيص...');
try { const data = await bayanSummarize(text, lengthValue);
if (data.status === 'success' && data.summary) { summaryResultSection.classList.remove('is-hidden'); summaryText.textContent = data.summary; summaryMeta.textContent = `النص الأصلي: ${(data.original_length || 0).toLocaleString('ar-EG')} حرف → الملخص: ${(data.summary_length || 0).toLocaleString('ar-EG')} حرف`; showToast('✓ تم التلخيص'); } else { showToast('تعذّر التلخيص — حاول مرة أخرى'); } } catch (error) { console.error('[Bayan] Summarization error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
// ══════════════════════════════════════════════════════════ // Copy summary (MED-1: .catch() for clipboard errors) // ══════════════════════════════════════════════════════════ btnCopySummary.addEventListener('click', () => { const text = summaryText.textContent || ''; navigator.clipboard.writeText(text) .then(() => showToast('✓ تم نسخ الملخص')) .catch(() => showToast('تعذّر النسخ')); });
// ══════════════════════════��═══════════════════════════════ // Dialect → MSA conversion // ══════════════════════════════════════════════════════════ const dialectInput = document.getElementById('dialect-input-text'); const dialectCharCount = document.getElementById('dialect-char-count'); const btnDialect = document.getElementById('btn-dialect'); const dialectResultSection = document.getElementById('dialect-result-section'); const dialectText = document.getElementById('dialect-text'); const btnCopyDialect = document.getElementById('btn-copy-dialect');
if (dialectInput) { dialectInput.addEventListener('input', () => updateCounts(dialectInput, dialectCharCount, null));
btnDialect.addEventListener('click', async () => { const text = dialectInput.value.trim(); if (!text) { showToast('أدخل نصاً للتحويل'); return; }
setLoading(true, 'جارٍ التحويل...'); try { const data = await bayanDialect(text); if (data.status === 'success' && data.converted_text) { dialectResultSection.classList.remove('is-hidden'); dialectText.textContent = data.converted_text; showToast('✓ تم التحويل'); } else { showToast(data.error || 'تعذّر التحويل — حاول مرة أخرى'); } } catch (error) { console.error('[Bayan] Dialect error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
btnCopyDialect.addEventListener('click', () => { navigator.clipboard.writeText(dialectText.textContent || '') .then(() => showToast('✓ تم نسخ النص')) .catch(() => showToast('تعذّر النسخ')); }); }
// ══════════════════════════════════════════════════════════ // Quran verification // ══════════════════════════════════════════════════════════ const quranInput = document.getElementById('quran-input-text'); const quranCharCount = document.getElementById('quran-char-count'); const btnQuran = document.getElementById('btn-quran'); const quranResultSection = document.getElementById('quran-result-section'); const quranText = document.getElementById('quran-text'); const quranMeta = document.getElementById('quran-meta'); const btnCopyQuran = document.getElementById('btn-copy-quran');
if (quranInput) { quranInput.addEventListener('input', () => updateCounts(quranInput, quranCharCount, null));
btnQuran.addEventListener('click', async () => { const text = quranInput.value.trim(); if (!text) { showToast('أدخل آية للتدقيق'); return; }
setLoading(true, 'جارٍ التدقيق...'); try { const data = await bayanQuran(text); quranResultSection.classList.remove('is-hidden'); if (data.error) { quranText.textContent = data.error; quranMeta.textContent = ''; } else { quranText.textContent = data.full_verse || data.matched_segment || JSON.stringify(data); quranMeta.textContent = data.matched_segment && data.full_verse ? `المقطع المطابق: ${data.matched_segment}` : ''; showToast('✓ تم التدقيق'); } } catch (error) { console.error('[Bayan] Quran error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
btnCopyQuran.addEventListener('click', () => { navigator.clipboard.writeText(quranText.textContent || '') .then(() => showToast('✓ تم النسخ')) .catch(() => showToast('تعذّر النسخ')); }); }
// ══════════════════════════════════════════════════════════ // Autocomplete suggestions // ══════════════════════════════════════════════════════════ const acInput = document.getElementById('autocomplete-input-text'); const acCharCount = document.getElementById('autocomplete-char-count'); const btnAutocomplete = document.getElementById('btn-autocomplete'); const acResultSection = document.getElementById('autocomplete-result-section'); const acList = document.getElementById('autocomplete-list');
if (acInput) { acInput.addEventListener('input', () => updateCounts(acInput, acCharCount, null));
btnAutocomplete.addEventListener('click', async () => { const text = acInput.value; if (!text.trim() || text.trim().length < 3) { showToast('اكتب ٣ أحرف على الأقل'); return; }
setLoading(true, 'جارٍ الاقتراح...'); try { const data = await bayanAutocomplete(text, 5); const suggestions = data.suggestions || []; acResultSection.classList.remove('is-hidden');
if (suggestions.length === 0) { acList.innerHTML = '<div class="bayan-ac-empty">لا توجد اقتراحات</div>'; return; }
acList.innerHTML = suggestions .map((s) => `<button class="bayan-alt-chip bayan-alt-chip--main bayan-ac-chip" type="button">${escapeHtml(s)}</button>`) .join('');
acList.querySelectorAll('.bayan-ac-chip').forEach((chip) => { chip.addEventListener('click', () => { const needsSpace = acInput.value.length > 0 && !/\s$/.test(acInput.value); acInput.value += (needsSpace ? ' ' : '') + chip.textContent; updateCounts(acInput, acCharCount, null); acInput.focus(); showToast('✓ تمت الإضافة'); }); }); } catch (error) { console.error('[Bayan] Autocomplete error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } }); }
// ══════════════════════════════════════════════════════════ // Phase 5: Download corrected text / summary as .txt // Buttons are injected programmatically to avoid touching popup.html. // ══════════════════════════════════════════════════════════ function downloadTxt(text, filename) { if (!text) { showToast('لا يوجد نص للتنزيل'); return; } try { const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); showToast('✓ تم تنزيل الملف'); } catch (e) { console.error('[Bayan] Download error:', e); showToast('تعذّر التنزيل'); } }
const DOWNLOAD_ICON = '<svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1M12 4v12m0 0l-4-4m4 4l4-4"/></svg>';
function addDownloadButton(headerEl, getText, filename) { if (!headerEl) return; const btn = document.createElement('button'); btn.className = 'bayan-btn-icon'; btn.type = 'button'; btn.title = 'تنزيل كملف نصي'; btn.innerHTML = DOWNLOAD_ICON; btn.addEventListener('click', () => downloadTxt((getText() || '').trim(), filename)); headerEl.appendChild(btn); }
addDownloadButton( btnCopyResult ? btnCopyResult.parentElement : null, () => resultText.textContent, 'bayan-corrected.txt' ); addDownloadButton( btnCopySummary ? btnCopySummary.parentElement : null, () => summaryText.textContent, 'bayan-summary.txt' );
// ══════════════════════════════════════════════════════════ // Status check on load // ══════════════════════════════════════════════════════════ (async function checkStatus() { const statusDot = document.querySelector('.bayan-status-dot'); const statusText = document.getElementById('status-text'); try { await bayanHealthCheck(); if (statusDot) statusDot.classList.add('online'); if (statusText) statusText.textContent = 'متصل'; } catch { if (statusDot) statusDot.classList.add('offline'); if (statusText) statusText.textContent = 'غير متصل'; } })();
// ══════════════════════════════════════════════════════════ // Phase 4: Context Menu Pickup // ══════════════════════════════════════════════════════════ // Fix #2: Guard against double execution // Fix #4: Tab name constants // Fix #5: Storage fallback (session → local) // ═══════════════════��══════════════════════════════════════
const TAB_ACTIONS = { correct: 'correct', summarize: 'summarize' }; let contextConsumed = false; // Fix #2
(async function checkContextAction() { // Only available in extension context (not in test pages) if (typeof chrome === 'undefined' || !chrome.storage) return;
// Fix #2: Prevent double-trigger if (contextConsumed) return;
// Fix #5: Storage fallback const storage = chrome.storage?.session || chrome.storage?.local; if (!storage) return;
try { const data = await storage.get(['contextAction', 'contextText', 'contextTimestamp']); if (!data.contextAction || !data.contextText) return;
// Ignore stale actions (older than 15 seconds — matches background cleanup) const age = Date.now() - (data.contextTimestamp || 0); if (age > 15000) { chrome.runtime.sendMessage({ type: 'CLEAR_CONTEXT' }); return; }
// Fix #2: Mark as consumed BEFORE processing contextConsumed = true;
console.log(`[Bayan] Context action: ${data.contextAction}, text length: ${data.contextText.length}`);
if (data.contextAction === TAB_ACTIONS.correct) { // Fill the correction tab and auto-trigger analysis inputText.value = data.contextText; updateCounts(inputText, charCount, wordCount);
// Switch to correction tab const correctTab = document.querySelector(`[data-tab="${TAB_ACTIONS.correct}"]`); if (correctTab) correctTab.click();
// Auto-click the correct button after a brief delay for UI paint setTimeout(() => btnCorrect.click(), 150);
} else if (data.contextAction === TAB_ACTIONS.summarize) { // Fill the summary tab and auto-trigger summarization summaryInputText.value = data.contextText; updateCounts(summaryInputText, summaryCharCount, null);
// Switch to summarize tab const summarizeTab = document.querySelector(`[data-tab="${TAB_ACTIONS.summarize}"]`); if (summarizeTab) summarizeTab.click();
// Auto-click the summarize button setTimeout(() => btnSummarize.click(), 150); }
// Clear the context action so it doesn't re-trigger on next popup open chrome.runtime.sendMessage({ type: 'CLEAR_CONTEXT' });
} catch (err) { console.warn('[Bayan] Context action check failed:', err); } })();});
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146/** * Bayan — Analysis Controller (Phase 7.1 Simplified) * * Responsibilities (ONLY): * - Adaptive debounce (2-tier: normal / large text) * - Stale request cancellation * - Text validation * - Message passing to background.js * * Does NOT own: * - Caching (background.js) * - Retry logic (background.js) * - Timeout (background.js) * - Network (background.js) * * Requires: BAYAN (shared/constants.js) */
// eslint-disable-next-line no-unused-varsconst BayanController = (() => { 'use strict';
// ── Debounce config ── const DEBOUNCE_NORMAL = 500; const DEBOUNCE_LARGE = 1000; const LARGE_TEXT_THRESHOLD = 2000;
// ── State ── let _debounceTimer = null; let _inflight = false;
// ── Protected site check ── const _isProtected = BAYAN.PROTECTED_HOSTS.includes(window.location.hostname);
// ══════════════════════════════════════════════════════════ // Text validation // ══════════════════════════════════════════════════════════
function hasArabic(text) { if (!text || text.length < BAYAN.MIN_TEXT_LENGTH) return false; const arabicChars = (text.match(/[\u0600-\u06FF]/g) || []).length; return arabicChars >= BAYAN.MIN_ARABIC_CHARS; }
function validateText(text) { if (!text) return { valid: false, reason: 'empty' }; if (text.length < BAYAN.MIN_TEXT_LENGTH) return { valid: false, reason: 'too_short' }; if (text.length > BAYAN.MAX_TEXT_LENGTH) return { valid: false, reason: 'too_long' }; if (!hasArabic(text)) return { valid: false, reason: 'no_arabic' }; return { valid: true }; }
// ══════════════════════════════════════════════════════════ // Core: debounced analysis via background bridge // ══════════════════════════════════════════════════════════
/** * Schedule a debounced analysis. * Background.js owns caching, retry, and timeout. * * @param {string} text * @param {function(Object|null): void} onResult * @param {function(): string} getCurrentText — staleness checker */ function scheduleAnalysis(text, onResult, getCurrentText) { if (_debounceTimer) { clearTimeout(_debounceTimer); _debounceTimer = null; }
if (!validateText(text).valid) { onResult(null); return; }
const delay = text.length > LARGE_TEXT_THRESHOLD ? DEBOUNCE_LARGE : DEBOUNCE_NORMAL;
_debounceTimer = setTimeout(() => { _debounceTimer = null;
// Staleness check: text changed during debounce if (getCurrentText() !== text) return;
executeAnalysis(text, onResult, getCurrentText); }, delay); }
/** * Send analysis request to background.js. * No timeout, no retry, no cache — background handles all of that. */ function executeAnalysis(text, onResult, getCurrentText) { _inflight = true;
chrome.runtime.sendMessage({ type: 'INLINE_ANALYZE', text }, (response) => { _inflight = false;
// Extension context invalidated (e.g., extension reloaded) if (chrome.runtime.lastError) { console.warn('[Bayan Controller]', chrome.runtime.lastError.message); onResult(null); return; }
// Staleness check: text changed during fetch if (getCurrentText() !== text) return;
if (!response || response.error) { onResult(null); return; }
onResult(response.data); }); }
// ══════════════════════════════════════════════════════════ // Cancellation // ══════════════════════════════════════════════════════════
function cancelAll() { if (_debounceTimer) { clearTimeout(_debounceTimer); _debounceTimer = null; } _inflight = false; }
function destroy() { cancelAll(); }
// ══════════════════════════════════════════════════════════ // Public API // ══════════════════════════════════════════════════════════
return { scheduleAnalysis, cancelAll, destroy, validateText, hasArabic, isProtectedSite() { return _isProtected; }, isInFlight() { return _inflight; }, };})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133/** * Bayan Chrome Extension — API Client * * Reused from: src/js/api.js (L2-20) * Adaptation: Relative paths replaced with CONFIG.API_BASE. * * Endpoints: analyze, summarize, dialect, quran, autocomplete, health. */
/** * Send text to the unified analysis pipeline. * Backend: /api/analyze (Spelling → Grammar → Punctuation) * * @param {string} text - Arabic text to analyze * @param {AbortSignal} [signal] - Optional abort signal * @returns {Promise<Object>} { original, corrected, suggestions[], timing_ms, status } */async function bayanAnalyze(text, signal) { const response = await fetch(`${CONFIG.API_BASE}/api/analyze`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }), signal, }); if (!response.ok) { throw new Error(`Analyze API error: ${response.status}`); } return await response.json();}
/** * Summarize Arabic text. * Backend: /api/summarize * * @param {string} text - Arabic text to summarize * @param {number} [length=2] - Summary length (1=short, 2=medium, 3=long) * @param {boolean} [fullText=true] - Summarize full text or first paragraph * @returns {Promise<Object>} { summary, status, original_length, summary_length } */async function bayanSummarize(text, length = 2, fullText = true) { const response = await fetch(`${CONFIG.API_BASE}/api/summarize`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, length, full_text: fullText }), }); if (!response.ok) { throw new Error(`Summarize API error: ${response.status}`); } return await response.json();}
/** * Convert dialectal Arabic to Modern Standard Arabic (MSA). * Backend: /api/dialect * * @param {string} text - Dialectal Arabic text * @param {AbortSignal} [signal] - Optional abort signal * @returns {Promise<Object>} { original_text, converted_text, status } */async function bayanDialect(text, signal) { const response = await fetch(`${CONFIG.API_BASE}/api/dialect`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }), signal, }); if (!response.ok) { throw new Error(`Dialect API error: ${response.status}`); } return await response.json();}
/** * Verify / search Quranic text. * Backend: /api/quran * * @param {string} text - Text to verify against the Quran * @param {string} [language='تدقيق الايات'] - Target operation type * @param {AbortSignal} [signal] - Optional abort signal * @returns {Promise<Object>} { matched_segment, full_verse, ... } or { error } */async function bayanQuran(text, language = 'تدقيق الايات', signal) { const response = await fetch(`${CONFIG.API_BASE}/api/quran`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text, language }), signal, }); // Quran endpoint returns 404 with a JSON {error} body on "no match" — // treat that as a normal (non-throwing) result so the UI can show it. if (!response.ok && response.status !== 404) { throw new Error(`Quran API error: ${response.status}`); } return await response.json();}
/** * Get autocomplete suggestions for Arabic text. * Backend: /api/autocomplete * * @param {string} context - Text before the cursor * @param {number} [n=3] - Number of suggestions to return * @param {AbortSignal} [signal] - Optional abort signal * @returns {Promise<Object>} { suggestions: string[], status } */async function bayanAutocomplete(context, n = 3, signal) { const response = await fetch(`${CONFIG.API_BASE}/api/autocomplete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ context, n }), signal, }); if (!response.ok) { throw new Error(`Autocomplete API error: ${response.status}`); } return await response.json();}
/** * Check backend health. * Backend: /api/health * * @returns {Promise<Object>} { status, mode, models } */async function bayanHealthCheck() { const response = await fetch(`${CONFIG.API_BASE}/api/health`, { method: 'GET', }); if (!response.ok) { throw new Error(`Health check error: ${response.status}`); } return await response.json();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152/** * Bayan Chrome Extension — Patch Application Engine * * Algorithms reused from: src/js/editor.js * Core logic: reverse-order offset replacement (editor.js L674-710) * * This module applies suggestion corrections to plain text * without requiring DOM manipulation. * * ═══════════════════════════════════════════════════════════ * HIGH-1 FIX — Offset Rebasing Strategy * ═══════════════════════════════════════════════════════════ * * When applying a single correction, the text length may change. * All remaining suggestions whose offsets come AFTER the applied * patch must be shifted by the length difference (delta). * * Strategy: LINEAR SHIFT * delta = replacementText.length - (suggestion.end - suggestion.start) * For every remaining suggestion S where S.start >= applied.end: * S.start += delta * S.end += delta * * Edge cases: * - Shorter replacement (delta < 0): offsets shift left * - Longer replacement (delta > 0): offsets shift right * - Same-length (delta = 0): offsets unchanged * - Overlapping suggestions: handled by PatchSet.resolve_overlaps() * on the backend — we never receive overlapping suggestions * * This is O(n) per apply, which is fine for ≤50 suggestions. * ═══════════════════════════════════════════════════════════ */
/** * Apply a single suggestion patch to text. * Source: src/js/editor.js L506-510 (offset-based replacement) * * @param {string} text - Original text * @param {Object} suggestion - { start, end, correction } * @returns {string} Text with correction applied */function applyPatch(text, suggestion) { const before = text.substring(0, suggestion.start); const after = text.substring(suggestion.end); return before + suggestion.correction + after;}
/** * Apply all suggestion patches to text. * CRITICAL: Sort in REVERSE order (highest start offset first) * to prevent offset shifts from invalidating subsequent patches. * Source: src/js/editor.js L674-710 (reverse-order algorithm) * * @param {string} text - Original text * @param {Array} suggestions - Array of { start, end, correction } * @returns {string} Fully corrected text */function applyAllPatches(text, suggestions) { if (!suggestions || suggestions.length === 0) return text;
// CRITICAL: Sort in REVERSE order (highest start offset first). // This is the exact same algorithm from editor.js L676. const sorted = [...suggestions].sort((a, b) => b.start - a.start);
let result = text; sorted.forEach((s) => { result = result.substring(0, s.start) + s.correction + result.substring(s.end); });
return result;}
/** * Apply a specific alternative correction to text. * Source: src/js/editor.js L547-600 (alternative correction pattern) * * @param {string} text - Original text * @param {Object} suggestion - The suggestion being corrected * @param {string} alternativeText - The alternative correction to apply * @returns {string} Text with alternative correction applied */function applyAlternativePatch(text, suggestion, alternativeText) { const before = text.substring(0, suggestion.start); const after = text.substring(suggestion.end); return before + alternativeText + after;}
/** * Apply ONE correction and rebase ALL remaining suggestions. * This is the primary function for individual suggestion applies. * * HIGH-1 FIX: Atomic apply + rebase in a single call. * * @param {string} text - Current text (must match suggestion offsets) * @param {Object} appliedSuggestion - The suggestion being applied * @param {string} replacementText - The text to insert (correction or alternative) * @param {Array} allSuggestions - All current suggestions (including the one being applied) * @returns {{ text: string, suggestions: Array }} Updated text and rebased suggestions */function applyAndRebase(text, appliedSuggestion, replacementText, allSuggestions) { // 1. Apply the patch to text const newText = text.substring(0, appliedSuggestion.start) + replacementText + text.substring(appliedSuggestion.end);
// 2. Calculate delta: how much the text length changed const originalSpanLength = appliedSuggestion.end - appliedSuggestion.start; const delta = replacementText.length - originalSpanLength;
// 3. Remove the applied suggestion and rebase remaining offsets const rebased = allSuggestions .filter((s) => s.id !== appliedSuggestion.id) .map((s) => { // Only shift suggestions that start AT or AFTER the applied patch's end. // Suggestions entirely before the patch are unaffected. // (Backend guarantees no overlapping suggestions via PatchSet.resolve_overlaps()) if (s.start >= appliedSuggestion.end) { return { ...s, start: s.start + delta, end: s.end + delta }; } return s; });
return { text: newText, suggestions: rebased };}
/** * Remove a suggestion from the list (after applying or dismissing). * Source: src/js/editor.js L520-523 (UUID-based filter) * * @param {Array} suggestions - Current suggestions array * @param {string} suggestionId - ID of suggestion to remove * @returns {Array} Filtered suggestions */function removeSuggestion(suggestions, suggestionId) { return suggestions.filter((s) => s.id !== suggestionId);}
/** * Count suggestions by type. * Source: src/js/editor.js L525-527 (type counting) * * @param {Array} suggestions * @returns {{ spelling: number, grammar: number, punctuation: number }} */function countByType(suggestions) { return { spelling: suggestions.filter((s) => s.type === 'spelling').length, grammar: suggestions.filter((s) => s.type === 'grammar').length, punctuation: suggestions.filter((s) => s.type === 'punctuation').length, };}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149/** * Bayan Chrome Extension — Renderer * * Functions reused from: src/js/renderer.js * All functions preserve original behavior exactly. * Source line references documented per Phase 0 audit. */
/** * Escapes HTML special characters to prevent XSS. * Source: src/js/renderer.js L9-18 (direct copy) * * @param {string} text - Text to escape * @returns {string} Escaped text */function escapeHtml(text) { const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }; return text.replace(/[&<>"']/g, (c) => map[c]);}
/** * Sorts suggestions by start offset. * Source: src/js/renderer.js L25-27 (direct copy) * * @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);}
/** * Gets CSS class for suggestion type. * Source: src/js/renderer.js L138-145 (direct copy) * * @param {string} type - Suggestion type (spelling, grammar, punctuation) * @returns {string} CSS class name */function getErrorClass(type) { const classes = { spelling: 'bayan-spelling-error', grammar: 'bayan-grammar-error', punctuation: 'bayan-punctuation-suggestion', }; return classes[type] || 'bayan-spelling-error';}
/** * Creates a segment tree of text ranges with their suggestions. * Handles overlapping ranges by merging them. * Source: src/js/renderer.js L36-131 (direct copy) * * @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 finalSegments = []; let segStart = 0;
sorted.forEach((suggestion) => { 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;}
/** * Renders text with highlighted suggestions as HTML string. * Source: src/js/renderer.js L153-191 (adapted for extension CSS classes) * * @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) return escapeHtml(text);
const segments = createSegments(text, suggestions); let html = '';
segments.forEach((segment) => { if (segment.type === 'text') { html += escapeHtml(segment.text); } else if (segment.type === 'suggestion') { const { suggestion } = segment; const errorClass = getErrorClass(suggestion.type); const escapedText = escapeHtml(segment.text); const sid = suggestion.id || '';
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>`; } });
return html;}
/** * Main renderer function. * Source: src/js/renderer.js L201-204 (direct copy) * * @param {Object} input - { text, suggestions } * @returns {string} Safe HTML with highlights */function bayanRender(input) { const { text = '', suggestions = [] } = input; return renderHighlightedText(text, suggestions);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127/** * Bayan Chrome Extension — Unified State Manager * * Phase 7: Production Hardening * * Single source of truth for runtime state across the inline engine. * Loaded as a content script BEFORE content-inline.js. * * Responsibilities: * - Track active field reference (WeakRef for GC safety) * - Store last analyzed text + response * - Track active mode * - Provide clean teardown */
// eslint-disable-next-line no-unused-varsconst BayanState = (() => { 'use strict';
/** @type {WeakRef<HTMLElement>|null} */ let _fieldRef = null; let _lastText = ''; let _lastHash = ''; let _lastResponse = null; /** @type {Array} */ let _suggestions = []; let _mode = 'idle'; // idle | inline | sidepanel | contextmenu let _paused = false; let _pauseReason = '';
/** * Simple FNV-1a hash for text deduplication. * 32-bit, fast, zero dependencies. * @param {string} str * @returns {string} */ function hash(str) { let h = 0x811c9dc5; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(36); }
return { // ── Field management ── /** @param {HTMLElement} field */ setField(field) { _fieldRef = field ? new WeakRef(field) : null; },
/** @returns {HTMLElement|null} */ getField() { return _fieldRef?.deref() ?? null; },
hasField() { return !!(_fieldRef?.deref()); },
// ── Text + hash ── setLastText(text) { _lastText = text; _lastHash = hash(text); }, getLastText() { return _lastText; }, getLastHash() { return _lastHash; },
/** * Check if given text is identical to last analyzed text. * Uses hash comparison (O(1)) instead of string equality (O(n)). */ isDuplicate(text) { return hash(text) === _lastHash && text === _lastText; },
// ── Response cache ── setLastResponse(data) { _lastResponse = data; }, getLastResponse() { return _lastResponse; },
// ── Suggestions ── setSuggestions(suggestions) { _suggestions = suggestions || []; }, getSuggestions() { return _suggestions; },
// ── Mode ── setMode(mode) { _mode = mode; }, getMode() { return _mode; },
// ── Pause state ── pause(reason) { _paused = true; _pauseReason = reason || 'unknown'; }, resume() { _paused = false; _pauseReason = ''; }, isPaused() { return _paused; }, getPauseReason() { return _pauseReason; },
// ── Clean teardown ── reset() { _fieldRef = null; _lastText = ''; _lastHash = ''; _lastResponse = null; _suggestions = []; _mode = 'idle'; _paused = false; _pauseReason = ''; },
// ── Debug ── toJSON() { return { hasField: !!(_fieldRef?.deref()), textLength: _lastText.length, hash: _lastHash, suggestions: _suggestions.length, mode: _mode, paused: _paused, pauseReason: _pauseReason, }; }, };})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899/** * Bayan Chrome Extension — UI Helpers * * Functions reused from: src/js/ui.js * All functions preserve original behavior exactly. * Source line references documented per Phase 0 audit. */
/** * Arabic labels for suggestion types. * Source: src/js/ui.js L3-7 (direct copy) */const TYPE_LABELS = { spelling: 'إملائي', grammar: 'نحوي', punctuation: 'ترقيم',};
/** * Resolve alternatives for a suggestion, falling back to [correction, original]. * Source: src/js/ui.js L67-71 (direct copy) * * @param {Object} suggestion * @returns {Array<string>} */function resolveAlternatives(suggestion) { return suggestion.alternatives && suggestion.alternatives.length > 0 ? suggestion.alternatives : [suggestion.correction, suggestion.original];}
/** * Calculate writing score from suggestion counts. * Source: src/js/ui.js L14-17 (direct copy) * * @param {number} spelling * @param {number} grammar * @param {number} punctuation * @returns {number} Score 0-100 */function calculateWritingScore(spelling, grammar, punctuation) { const score = 100 - spelling * 8 - grammar * 6 - punctuation * 3; return Math.max(0, Math.min(100, score));}
/** * Build HTML for a single suggestion card. * Source: src/js/ui.js L73-100 (adapted for extension CSS classes) * * @param {Object} suggestion * @param {number} index * @returns {string} HTML string */function buildSuggestionCardHTML(suggestion, index) { const badgeClass = `bayan-badge-${suggestion.type}`; const label = TYPE_LABELS[suggestion.type] || suggestion.type; const alts = resolveAlternatives(suggestion); const suggestionId = suggestion.id || index;
let altsHTML = ''; alts.forEach((alt, i) => { const isKeep = alt === suggestion.original; const isMain = i === 0; const cls = isKeep ? 'bayan-alt-chip bayan-alt-chip--keep' : isMain ? 'bayan-alt-chip bayan-alt-chip--main' : 'bayan-alt-chip'; const chipLabel = isKeep ? `${escapeHtml(alt)} ✓` : escapeHtml(alt); altsHTML += `<button class="${cls}" data-card-alt="${escapeHtml(alt)}" data-card-id="${suggestionId}" type="button">${chipLabel}</button>`; });
return ` <div class="bayan-suggestion-card" role="listitem" tabindex="0" data-suggestion-id="${suggestionId}" aria-label="${label}: ${escapeHtml(suggestion.original)} إلى ${escapeHtml(suggestion.correction)}"> <span class="bayan-suggestion-badge ${badgeClass}">${label}</span> <div class="bayan-suggestion-change"> <span class="bayan-suggestion-original">${escapeHtml(suggestion.original)}</span> <span class="bayan-suggestion-arrow">←</span> <span class="bayan-suggestion-correction">${escapeHtml(suggestion.correction)}</span> </div> <div class="bayan-suggestion-alts">${altsHTML}</div> </div>`;}
/** * Generate score hint text. * * @param {number} score * @param {number} total - total suggestion count * @returns {string} */function getScoreHint(score, total) { if (total === 0) return 'ابدأ الكتابة لرؤية تقييمك'; if (score >= 90) return 'كتابة ممتازة! استمر.'; if (score >= 70) return 'جيد — راجع الاقتراحات لتحسين النص.'; return 'يحتاج النص إلى بعض التحسينات.';}1234567891011121314151617/** * Bayan — Legacy Config (popup.js / sidepanel.js compatibility) * * This file provides the CONFIG object expected by popup.js and sidepanel.js. * All values are derived from BAYAN constants (shared/constants.js) where available, * or defined here for popup/sidepanel-specific settings. * * NOTE: popup.html and sidepanel.html load constants.js BEFORE this file, * so BAYAN is available here. */const CONFIG = { API_BASE: typeof BAYAN !== 'undefined' ? BAYAN.API_BASE : 'https://bayan10-bayan-api.hf.space', MAX_ANALYZE_LENGTH: typeof BAYAN !== 'undefined' ? BAYAN.MAX_TEXT_LENGTH : 5000, MIN_ANALYZE_LENGTH: typeof BAYAN !== 'undefined' ? BAYAN.MIN_TEXT_LENGTH : 15, ANALYZE_DEBOUNCE_MS: 3000, MIN_SUMMARIZE_LENGTH: typeof BAYAN !== 'undefined' ? BAYAN.MIN_SUMMARIZE_LENGTH : 10,};12345678910111213141516171819202122232425262728293031323334353637383940414243444546/** * Bayan — Shared Constants (Single Source of Truth) * * ALL shared configuration lives here. * No hardcoded API URLs, timeouts, or limits elsewhere. * * Used by: background.js, analysis-controller.js, config.js (legacy alias) */const BAYAN = { /** Backend API base URL (HuggingFace Spaces) */ API_BASE: 'https://bayan10-bayan-api.hf.space',
/** Network timeout for API calls (ms) */ API_TIMEOUT_MS: 60000, // FIX-09: Increased from 20s to 60s for cold-start tolerance
/** Max retries on network failure */ MAX_RETRIES: 1,
/** Cache TTL (ms) — 5 minutes */ CACHE_TTL_MS: 300000,
/** Max cache entries */ CACHE_MAX_ENTRIES: 20,
/** Max text length for analysis */ MAX_TEXT_LENGTH: 5000,
/** Min text length to trigger analysis */ MIN_TEXT_LENGTH: 15,
/** Min Arabic characters required */ MIN_ARABIC_CHARS: 5,
/** Min text length for summarization */ MIN_SUMMARIZE_LENGTH: 10,
/** Protected hosts — disable contenteditable injection */ PROTECTED_HOSTS: [ 'mail.google.com', 'docs.google.com', 'sheets.google.com', 'slides.google.com', 'notion.so', 'www.notion.so', ],};1234567891011121314151617/** * Bayan — FNV-1a Hash (Single Implementation) * * 32-bit FNV-1a hash. Fast, zero dependencies. * Used for text deduplication in cache layers. * * @param {string} str * @returns {string} Base-36 hash string */function bayanHash(str) { let h = 0x811c9dc5; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 0x01000193); } return (h >>> 0).toString(36);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637/* ══════════════════════════════════════════════ Bayan Side Panel — Styles Persistent workspace | RTL | Dark premium ══════════════════════════════════════════════ */
/* ── Design Tokens (shared with popup) ── */:root { --sp-primary: #6366f1; --sp-primary-light: #818cf8; --sp-primary-dark: #4f46e5; --sp-primary-glow: rgba(99, 102, 241, 0.25);
--sp-bg: #0f0f14; --sp-surface: #1a1a24; --sp-surface-hover: #22222e; --sp-surface-active: #2a2a38; --sp-border: #2d2d3d; --sp-border-light: #3a3a4d;
--sp-text: #f0f0f5; --sp-text-secondary: #9898ad; --sp-text-muted: #6b6b80;
--sp-success: #22c55e; --sp-warning: #f59e0b; --sp-error: #ef4444;
--sp-spelling: #ef4444; --sp-grammar: #f59e0b; --sp-punctuation: #3b82f6;
--sp-radius: 10px; --sp-radius-sm: 6px; --sp-radius-lg: 14px;
--sp-font: 'Segoe UI', 'SF Pro', Tahoma, Arial, sans-serif; --sp-font-arabic: 'Noto Sans Arabic', 'Segoe UI', Tahoma, sans-serif;
--sp-transition: 200ms cubic-bezier(0.4, 0, 0.2, 1); --sp-spring: 300ms cubic-bezier(0.34, 1.56, 0.64, 1);}
/* ── Reset ── */*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0;}
body { width: 100%; min-height: 100vh; overflow-y: auto; overflow-x: hidden; font-family: var(--sp-font-arabic); font-size: 13px; line-height: 1.6; color: var(--sp-text); background: var(--sp-bg); direction: rtl; -webkit-font-smoothing: antialiased;}
/* Custom scrollbar */::-webkit-scrollbar { width: 4px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: var(--sp-border); border-radius: 4px; }
/* ══════════════════════════════════════════════ Header ══════════════════════════════════════════════ */.sp-header { display: flex; align-items: center; justify-content: space-between; padding: 10px 14px; background: linear-gradient(135deg, var(--sp-surface) 0%, rgba(99, 102, 241, 0.08) 100%); border-bottom: 1px solid var(--sp-border); position: sticky; top: 0; z-index: 100; backdrop-filter: blur(12px);}
.sp-header-brand { display: flex; align-items: center; gap: 8px;}
.sp-header-title { font-size: 16px; font-weight: 700; background: linear-gradient(135deg, var(--sp-primary-light), #a78bfa); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: -0.5px;}
.sp-header-status { display: flex; align-items: center; gap: 5px; font-size: 11px; color: var(--sp-text-muted);}
.sp-status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--sp-text-muted); transition: background var(--sp-transition);}.sp-status-dot.online { background: var(--sp-success); box-shadow: 0 0 6px var(--sp-success); }.sp-status-dot.offline { background: var(--sp-error); }.sp-status-text { font-size: 10px; }
/* ══════════════════════════════════════════════ Tabs ══════════════════════════════════════════════ */.sp-tabs { display: flex; gap: 0; padding: 0 14px; background: var(--sp-surface); border-bottom: 1px solid var(--sp-border);}
.sp-tab { flex: 1; display: flex; align-items: center; justify-content: center; gap: 5px; padding: 8px 0; border: none; background: transparent; color: var(--sp-text-muted); font-family: var(--sp-font-arabic); font-size: 12px; font-weight: 600; cursor: pointer; border-bottom: 2px solid transparent; transition: all var(--sp-transition);}.sp-tab:hover { color: var(--sp-text-secondary); }.sp-tab.active { color: var(--sp-primary-light); border-bottom-color: var(--sp-primary);}
/* ══════════════════════════════════════════════ Panels ══════════════════════════════════════════════ */.sp-panel { display: none; padding: 12px 14px; animation: spFadeIn 200ms ease;}.sp-panel.active { display: block; }
@keyframes spFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); }}
/* ══════════════════════════════════════════════ Input ═════════��════════════════════════════════════ */.sp-input-group { margin-bottom: 10px;}
.sp-textarea { width: 100%; padding: 10px 12px; border: 1px solid var(--sp-border); border-radius: var(--sp-radius); background: var(--sp-surface); color: var(--sp-text); font-family: var(--sp-font-arabic); font-size: 14px; line-height: 1.7; resize: vertical; min-height: 80px; transition: border-color var(--sp-transition), box-shadow var(--sp-transition);}.sp-textarea:focus { outline: none; border-color: var(--sp-primary); box-shadow: 0 0 0 3px var(--sp-primary-glow);}.sp-textarea::placeholder { color: var(--sp-text-muted); font-size: 13px;}
.sp-meta-row { display: flex; gap: 12px; margin-top: 4px; padding: 0 2px;}.sp-char-count,.sp-word-count { font-size: 10px; color: var(--sp-text-muted);}
/* ══════════════════════════════════════════════ Buttons ══════════════════════════════════════════════ */.sp-actions { display: flex; gap: 8px; margin-bottom: 12px;}
.sp-btn { display: inline-flex; align-items: center; justify-content: center; gap: 5px; padding: 7px 14px; border: none; border-radius: var(--sp-radius-sm); font-family: var(--sp-font-arabic); font-size: 12px; font-weight: 600; cursor: pointer; transition: all var(--sp-transition);}
.sp-btn-primary { flex: 1; background: linear-gradient(135deg, var(--sp-primary), var(--sp-primary-dark)); color: white; box-shadow: 0 2px 8px var(--sp-primary-glow);}.sp-btn-primary:hover { transform: translateY(-1px); box-shadow: 0 4px 14px var(--sp-primary-glow);}.sp-btn-primary:active { transform: translateY(0);}
.sp-btn-ghost { background: var(--sp-surface); color: var(--sp-text-secondary); border: 1px solid var(--sp-border);}.sp-btn-ghost:hover { background: var(--sp-surface-hover); color: var(--sp-text);}
.sp-btn-icon { display: inline-flex; align-items: center; justify-content: center; width: 28px; height: 28px; border: none; border-radius: var(--sp-radius-sm); background: var(--sp-surface); color: var(--sp-text-secondary); cursor: pointer; transition: all var(--sp-transition);}.sp-btn-icon:hover { background: var(--sp-surface-hover); color: var(--sp-primary-light);}
/* ══════════════════════════════════════════════ Score ══════════════════════════════════════════════ */.sp-score { display: flex; align-items: center; gap: 12px; padding: 12px; margin-bottom: 12px; background: var(--sp-surface); border: 1px solid var(--sp-border); border-radius: var(--sp-radius);}
.sp-score-ring { position: relative; width: 64px; height: 64px; flex-shrink: 0;}.sp-score-ring svg { width: 100%; height: 100%;}.sp-score-ring circle:last-of-type { transition: stroke-dashoffset 800ms cubic-bezier(0.4, 0, 0.2, 1);}
.sp-score-value { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 18px; font-weight: 800; color: var(--sp-primary-light);}
.sp-score-details { flex: 1; min-width: 0;}
.sp-score-hint { display: block; font-size: 11px; color: var(--sp-text-secondary); margin-bottom: 6px;}
.sp-score-counts { display: flex; gap: 10px; flex-wrap: wrap; font-size: 10px; color: var(--sp-text-muted);}.sp-count-spelling strong { color: var(--sp-spelling); }.sp-count-grammar strong { color: var(--sp-grammar); }.sp-count-punctuation strong { color: var(--sp-punctuation); }
/* ══════════════════════════════════════════════ Results ══════════════════════════════════════════════ */.sp-result { margin-bottom: 12px; border: 1px solid var(--sp-border); border-radius: var(--sp-radius); background: var(--sp-surface); overflow: hidden;}
.sp-result-header { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; font-size: 11px; font-weight: 700; color: var(--sp-text-secondary); background: var(--sp-surface-hover); border-bottom: 1px solid var(--sp-border);}
.sp-result-actions { display: flex; gap: 4px;}
.sp-result-text { padding: 10px 12px; font-size: 14px; line-height: 1.8; color: var(--sp-text); word-break: break-word;}
.sp-summary-meta { padding: 6px 12px 10px; font-size: 10px; color: var(--sp-text-muted);}
/* ══════════════════════════════════════════════ Highlighted text (from bayan-renderer.js) ══════════════════════════════════════════════ */.bayan-spelling-error { background: rgba(239, 68, 68, 0.15); border-bottom: 2px solid var(--sp-spelling); padding: 0 2px; border-radius: 2px; cursor: pointer;}.bayan-grammar-error { background: rgba(245, 158, 11, 0.15); border-bottom: 2px solid var(--sp-grammar); padding: 0 2px; border-radius: 2px; cursor: pointer;}.bayan-punctuation-suggestion { background: rgba(59, 130, 246, 0.15); border-bottom: 2px solid var(--sp-punctuation); padding: 0 2px; border-radius: 2px; cursor: pointer;}
/* ══════════════════════════════════════════════ Suggestions ══════════════════════════════════════════════ */.sp-suggestions { margin-bottom: 12px;}
.sp-suggestions-header { font-size: 11px; font-weight: 700; color: var(--sp-text-secondary); margin-bottom: 6px; padding: 0 2px;}
.sp-suggestions-list { display: flex; flex-direction: column; gap: 6px;}
/* Autocomplete suggestion chips (إكمال tab) — horizontal wrap */#autocomplete-list { flex-direction: row; flex-wrap: wrap;}.sp-ac-chip { cursor: pointer;}.sp-ac-empty { color: var(--sp-text-muted, #94a3b8); font-size: 13px; padding: 4px 2px;}
/* Suggestion card — reuses bayan-ui.js HTML classes */.bayan-suggestion-card { padding: 8px 10px; background: var(--sp-surface); border: 1px solid var(--sp-border); border-radius: var(--sp-radius-sm); transition: border-color var(--sp-transition), background var(--sp-transition);}.bayan-suggestion-card:hover { border-color: var(--sp-border-light); background: var(--sp-surface-hover);}
.bayan-suggestion-badge { display: inline-block; padding: 1px 6px; border-radius: 4px; font-size: 9px; font-weight: 700; margin-bottom: 4px;}.bayan-badge-spelling { background: rgba(239, 68, 68, 0.15); color: var(--sp-spelling); }.bayan-badge-grammar { background: rgba(245, 158, 11, 0.15); color: var(--sp-grammar); }.bayan-badge-punctuation { background: rgba(59, 130, 246, 0.15); color: var(--sp-punctuation); }
.bayan-suggestion-change { display: flex; align-items: center; gap: 6px; margin-bottom: 6px; font-size: 13px;}
.bayan-suggestion-original { color: var(--sp-error); text-decoration: line-through; text-decoration-color: rgba(239, 68, 68, 0.4);}
.bayan-suggestion-arrow { color: var(--sp-text-muted); font-size: 11px;}
.bayan-suggestion-correction { color: var(--sp-success); font-weight: 600;}
.bayan-suggestion-alts { display: flex; flex-wrap: wrap; gap: 4px;}
.bayan-alt-chip { padding: 3px 8px; border: 1px solid var(--sp-border); border-radius: 12px; background: var(--sp-surface-hover); color: var(--sp-text); font-family: var(--sp-font-arabic); font-size: 11px; cursor: pointer; transition: all var(--sp-transition);}.bayan-alt-chip:hover { border-color: var(--sp-primary); background: var(--sp-primary-glow);}.bayan-alt-chip--main { border-color: var(--sp-primary); background: rgba(99, 102, 241, 0.1); color: var(--sp-primary-light);}.bayan-alt-chip--keep { border-color: var(--sp-border); color: var(--sp-text-muted); font-size: 10px;}.bayan-alt-chip--keep:hover { border-color: var(--sp-text-muted); background: var(--sp-surface-active);}
/* ══════════════════════════════════════════════ Radio group (summary length) ══════════════════════════════════════════════ */.sp-radio-group { display: flex; gap: 12px; margin-bottom: 10px; padding: 0 2px;}
.sp-radio { display: flex; align-items: center; gap: 4px; font-size: 11px; color: var(--sp-text-secondary); cursor: pointer;}.sp-radio input[type="radio"] { accent-color: var(--sp-primary); width: 13px; height: 13px;}
/* ══════════════════════════════════════════════ Timing ══════════════════════════════════════════════ */.sp-timing { padding: 6px 10px; margin-bottom: 8px; background: var(--sp-surface); border-radius: var(--sp-radius-sm); font-size: 10px; color: var(--sp-text-muted); text-align: center;}
/* ══════════════════════════════════════════════ Loading overlay ══════════════════════════════════════════════ */.sp-loading { position: fixed; inset: 0; z-index: 200; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: rgba(15, 15, 20, 0.85); backdrop-filter: blur(6px); color: var(--sp-text); font-size: 13px;}
.sp-spinner { width: 32px; height: 32px; border: 3px solid var(--sp-border); border-top-color: var(--sp-primary); border-radius: 50%; animation: spSpin 800ms linear infinite;}
@keyframes spSpin { to { transform: rotate(360deg); }}
/* ══════════════════════════════════════════════ Toast ══════════════════════════════════════════════ */.sp-toast { position: fixed; bottom: 16px; left: 50%; transform: translateX(-50%) translateY(60px); padding: 8px 16px; background: var(--sp-surface); border: 1px solid var(--sp-border); border-radius: 20px; color: var(--sp-text); font-size: 12px; font-weight: 600; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4); opacity: 0; pointer-events: none; transition: all var(--sp-spring); z-index: 300; white-space: nowrap;}.sp-toast.is-visible { opacity: 1; transform: translateX(-50%) translateY(0);}
/* ══════════════════════════════════════════════ Stale indicator ══════════════════════════════════════════════ */.sp-stale { opacity: 0.45; pointer-events: none; position: relative; filter: grayscale(30%); transition: opacity var(--sp-transition), filter var(--sp-transition);}
/* ══════════════════════════════════════════════ Utilities ══════════════════════════════════════════════ */.is-hidden { display: none !important;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303<!DOCTYPE html><html lang="ar" dir="rtl"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>بيان — لوحة التحليل</title> <link rel="stylesheet" href="sidepanel.css"></head><body> <!-- ══════════════════════════════════════════════ --> <!-- Header --> <!-- ══════════════════════════════════════════════ --> <header class="sp-header"> <div class="sp-header-brand"> <svg class="sp-logo" width="24" height="24" viewBox="0 0 100 100" fill="none"> <circle cx="50" cy="50" r="46" fill="url(#spGrad)" /> <path d="M30 55 Q35 35, 50 30 Q65 35, 70 55 Q65 65, 50 70 Q35 65, 30 55Z" fill="rgba(255,255,255,0.9)" /> <circle cx="50" cy="42" r="4" fill="url(#spGrad)" /> <defs> <linearGradient id="spGrad" x1="0" y1="0" x2="100" y2="100"> <stop offset="0%" stop-color="#6366f1"/> <stop offset="100%" stop-color="#8b5cf6"/> </linearGradient> </defs> </svg> <span class="sp-header-title">بيان</span> </div> <div class="sp-header-status" id="status-indicator"> <span class="sp-status-dot"></span> <span class="sp-status-text" id="status-text">جاري الاتصال...</span> </div> </header>
<!-- ══════════════════════════════════════════════ --> <!-- Tab Navigation --> <!-- ══════════════════════════════════════════════ --> <nav class="sp-tabs" role="tablist"> <button class="sp-tab active" role="tab" aria-selected="true" data-tab="correct" id="tab-correct"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> تصحيح </button> <button class="sp-tab" role="tab" aria-selected="false" data-tab="summarize" id="tab-summarize"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h10M4 18h14"/></svg> تلخيص </button> <button class="sp-tab" role="tab" aria-selected="false" data-tab="dialect" id="tab-dialect"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"/></svg> لهجة </button> <button class="sp-tab" role="tab" aria-selected="false" data-tab="quran" id="tab-quran"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/></svg> قرآن </button> <button class="sp-tab" role="tab" aria-selected="false" data-tab="autocomplete" id="tab-autocomplete"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg> إكمال </button> </nav>
<!-- ══════════════════════════════════════════════ --> <!-- Correct Panel --> <!-- ══════════════════════════════════════════════ --> <section class="sp-panel active" id="panel-correct" role="tabpanel"> <!-- Input area --> <div class="sp-input-group"> <textarea id="input-text" class="sp-textarea" dir="rtl" placeholder="أدخل النص العربي أو اختر نصاً من أي صفحة..." rows="4" maxlength="5000" ></textarea> <div class="sp-meta-row"> <span class="sp-char-count"><span id="char-count">٠</span> حرف</span> <span class="sp-word-count"><span id="word-count">٠</span> كلمة</span> </div> </div>
<!-- Action buttons --> <div class="sp-actions"> <button class="sp-btn sp-btn-primary" id="btn-correct"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4"/></svg> تحليل وتصحيح </button> <button class="sp-btn sp-btn-ghost" id="btn-clear">مسح</button> </div>
<!-- Score ring --> <div class="sp-score is-hidden" id="score-section"> <div class="sp-score-ring"> <svg viewBox="0 0 160 160"> <circle cx="80" cy="80" r="70" fill="none" stroke="var(--sp-border)" stroke-width="8" /> <circle cx="80" cy="80" r="70" fill="none" stroke="var(--sp-primary)" stroke-width="8" stroke-dasharray="440" stroke-dashoffset="440" stroke-linecap="round" id="score-circle" transform="rotate(-90 80 80)" /> </svg> <span class="sp-score-value" id="score-value">--</span> </div> <div class="sp-score-details"> <span class="sp-score-hint" id="score-hint"></span> <div class="sp-score-counts"> <span class="sp-count-spelling">إملائي: <strong id="count-spelling">٠</strong></span> <span class="sp-count-grammar">نحوي: <strong id="count-grammar">٠</strong></span> <span class="sp-count-punctuation">ترقيم: <strong id="count-punctuation">٠</strong></span> </div> </div> </div>
<!-- Corrected text result --> <div class="sp-result is-hidden" id="result-section"> <div class="sp-result-header"> <span>النص المصحح</span> <div class="sp-result-actions"> <button class="sp-btn-icon" id="btn-apply-all" title="تطبيق الكل"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg> </button> <button class="sp-btn-icon" id="btn-copy-result" title="نسخ"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg> </button> </div> </div> <div class="sp-result-text" id="result-text" dir="rtl"></div> </div>
<!-- Suggestions list --> <div class="sp-suggestions is-hidden" id="suggestions-section"> <div class="sp-suggestions-header">الاقتراحات</div> <div class="sp-suggestions-list" id="suggestions-list" role="list"></div> </div>
<!-- Timing info --> <div class="sp-timing is-hidden" id="timing-section"> <span id="timing-text"></span> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Summarize Panel --> <!-- ══════════════════════════════════════════════ --> <section class="sp-panel" id="panel-summarize" role="tabpanel"> <div class="sp-input-group"> <textarea id="summary-input-text" class="sp-textarea" dir="rtl" placeholder="الصق النص المراد تلخيصه..." rows="4" maxlength="5000" ></textarea> <div class="sp-meta-row"> <span class="sp-char-count"><span id="summary-char-count">٠</span> حرف</span> </div> </div>
<!-- Summary length options --> <div class="sp-radio-group"> <label class="sp-radio"><input type="radio" name="summary-length" value="1"> قصير</label> <label class="sp-radio"><input type="radio" name="summary-length" value="2" checked> متوسط</label> <label class="sp-radio"><input type="radio" name="summary-length" value="3"> طويل</label> </div>
<div class="sp-actions"> <button class="sp-btn sp-btn-primary" id="btn-summarize"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h10M4 18h14"/></svg> تلخيص </button> </div>
<!-- Summary result --> <div class="sp-result is-hidden" id="summary-result-section"> <div class="sp-result-header"> <span>الملخص</span> <button class="sp-btn-icon" id="btn-copy-summary" title="نسخ"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg> </button> </div> <div class="sp-result-text" id="summary-text" dir="rtl"></div> <div class="sp-summary-meta" id="summary-meta"></div> </div> </section>
<!-- ════════════════════════════════════════════���═ --> <!-- Dialect Panel (لهجة → فصحى) --> <!-- ══════════════════════════════════════════════ --> <section class="sp-panel" id="panel-dialect" role="tabpanel"> <div class="sp-input-group"> <textarea id="dialect-input-text" class="sp-textarea" dir="rtl" placeholder="أدخل نصاً بالعامية لتحويله إلى الفصحى..." rows="4" maxlength="5000" ></textarea> <div class="sp-meta-row"> <span class="sp-char-count"><span id="dialect-char-count">٠</span> حرف</span> </div> </div> <div class="sp-actions"> <button class="sp-btn sp-btn-primary" id="btn-dialect"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg> تحويل إلى الفصحى </button> </div> <div class="sp-result is-hidden" id="dialect-result-section"> <div class="sp-result-header"> <span>النص بالفصحى</span> <button class="sp-btn-icon" id="btn-copy-dialect" title="نسخ"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg> </button> </div> <div class="sp-result-text" id="dialect-text" dir="rtl"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Quran Panel (تدقيق الآيات) --> <!-- ══════════════════════════════════════════════ --> <section class="sp-panel" id="panel-quran" role="tabpanel"> <div class="sp-input-group"> <textarea id="quran-input-text" class="sp-textarea" dir="rtl" placeholder="أدخل آية أو جزءاً منها للتحقق منها..." rows="4" maxlength="2000" ></textarea> <div class="sp-meta-row"> <span class="sp-char-count"><span id="quran-char-count">٠</span> حرف</span> </div> </div> <div class="sp-actions"> <button class="sp-btn sp-btn-primary" id="btn-quran"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg> تدقيق الآية </button> </div> <div class="sp-result is-hidden" id="quran-result-section"> <div class="sp-result-header"> <span>نتيجة التدقيق</span> <button class="sp-btn-icon" id="btn-copy-quran" title="نسخ"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/></svg> </button> </div> <div class="sp-result-text" id="quran-text" dir="rtl"></div> <div class="sp-summary-meta" id="quran-meta"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Autocomplete Panel (إكمال) --> <!-- ══════════════════════════════════════════════ --> <section class="sp-panel" id="panel-autocomplete" role="tabpanel"> <div class="sp-input-group"> <textarea id="autocomplete-input-text" class="sp-textarea" dir="rtl" placeholder="اكتب بداية الجملة واحصل على اقتراحات لإكمالها..." rows="4" maxlength="5000" ></textarea> <div class="sp-meta-row"> <span class="sp-char-count"><span id="autocomplete-char-count">٠</span> حرف</span> </div> </div> <div class="sp-actions"> <button class="sp-btn sp-btn-primary" id="btn-autocomplete"> <svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/></svg> اقترح إكمالاً </button> </div> <div class="sp-suggestions is-hidden" id="autocomplete-result-section"> <div class="sp-suggestions-header">اقتراحات الإكمال</div> <div class="sp-suggestions-list" id="autocomplete-list" role="list"></div> </div> </section>
<!-- ══════════════════════════════════════════════ --> <!-- Loading Overlay --> <!-- ══════════════════════════════════════════════ --> <div class="sp-loading is-hidden" id="loading-overlay"> <div class="sp-spinner"></div> <span id="loading-text">جارٍ التحليل...</span> </div>
<!-- Toast --> <div class="sp-toast" id="toast"></div>
<!-- ══════════════════════════════════════════════ --> <!-- Scripts — reuse ALL shared modules --> <!-- ══════════════════════════════════════════════ --> <script src="../shared/constants.js"></script> <script src="../shared/config.js"></script> <script src="../shared/bayan-renderer.js"></script> <script src="../shared/bayan-ui.js"></script> <script src="../shared/bayan-patches.js"></script> <script src="../shared/bayan-api.js"></script> <script src="sidepanel.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709/** * Bayan Chrome Extension — Side Panel Logic * * Phase 5: Persistent workspace panel * * Reuses: * - bayanAnalyze(), bayanSummarize(), bayanHealthCheck() from bayan-api.js * - renderHighlightedText(), escapeHtml() from bayan-renderer.js * - buildSuggestionCardHTML(), calculateWritingScore(), getScoreHint() from bayan-ui.js * - applyAndRebase(), applyAllPatches(), sortSuggestions(), countByType(), removeSuggestion() from bayan-patches.js * * Key differences from popup.js: * - Persistent: panel stays open across page navigations * - Auto-analysis: text injected from context menu auto-analyzes * - Debounced live updates: re-analyzes on user edits (500ms debounce) * - State persistence: last analysis saved to chrome.storage.session */
document.addEventListener('DOMContentLoaded', () => { // ── Tab constants ── const TAB = { CORRECT: 'correct', SUMMARIZE: 'summarize' };
// ── Element references ── const inputText = document.getElementById('input-text'); const charCount = document.getElementById('char-count'); const wordCount = document.getElementById('word-count'); const btnCorrect = document.getElementById('btn-correct'); const btnClear = document.getElementById('btn-clear'); const btnApplyAll = document.getElementById('btn-apply-all'); const btnCopyResult = document.getElementById('btn-copy-result'); const scoreSection = document.getElementById('score-section'); const resultSection = document.getElementById('result-section'); const resultText = document.getElementById('result-text'); const suggestionsSection = document.getElementById('suggestions-section'); const suggestionsList = document.getElementById('suggestions-list'); const timingSection = document.getElementById('timing-section'); const timingText = document.getElementById('timing-text'); const loadingOverlay = document.getElementById('loading-overlay'); const loadingTextEl = document.getElementById('loading-text');
// Summary tab const summaryInputText = document.getElementById('summary-input-text'); const summaryCharCount = document.getElementById('summary-char-count'); const btnSummarize = document.getElementById('btn-summarize'); const summaryResultSection = document.getElementById('summary-result-section'); const summaryText = document.getElementById('summary-text'); const summaryMeta = document.getElementById('summary-meta'); const btnCopySummary = document.getElementById('btn-copy-summary');
// Score const scoreValue = document.getElementById('score-value'); const scoreCircle = document.getElementById('score-circle'); const scoreHint = document.getElementById('score-hint'); const countSpelling = document.getElementById('count-spelling'); const countGrammar = document.getElementById('count-grammar'); const countPunctuation = document.getElementById('count-punctuation');
// ══════════════════════════════════════════════════════════ // State // ══════════════════════════════════════════════════════════ let currentSuggestions = []; let analyzedText = ''; let isStale = false; let isAnalyzing = false; let contextConsumed = false; let debounceTimer = null;
const SCORE_CIRCUMFERENCE = 440; const DEBOUNCE_MS = 500;
// ══════════════════════════════════════════════════════════ // Tab switching // ══════════════════════════════════════════════════════════ document.querySelectorAll('.sp-tab').forEach((tab) => { tab.addEventListener('click', () => { const targetTab = tab.dataset.tab; document.querySelectorAll('.sp-tab').forEach((t) => { t.classList.toggle('active', t.dataset.tab === targetTab); t.setAttribute('aria-selected', t.dataset.tab === targetTab ? 'true' : 'false'); }); document.querySelectorAll('.sp-panel').forEach((p) => { p.classList.toggle('active', p.id === `panel-${targetTab}`); }); }); });
// ══════════════════════════════════════════════════════════ // Character & word counter // ══════════════════════════════════════════════════════════ function updateCounts(textarea, charEl, wordEl) { const text = textarea.value; const chars = text.length; const words = text.trim() ? text.trim().split(/\s+/).length : 0; if (charEl) charEl.textContent = chars.toLocaleString('ar-EG'); if (wordEl) wordEl.textContent = words.toLocaleString('ar-EG'); }
inputText.addEventListener('input', () => { updateCounts(inputText, charCount, wordCount);
// Staleness detection if (currentSuggestions.length > 0 && inputText.value !== analyzedText) { markStale(); }
// Debounced live re-analysis if (debounceTimer) clearTimeout(debounceTimer); debounceTimer = setTimeout(() => { const text = inputText.value.trim(); if (text.length >= CONFIG.MIN_ANALYZE_LENGTH && !isAnalyzing) { runAnalysis(text); } }, DEBOUNCE_MS); });
summaryInputText.addEventListener('input', () => { updateCounts(summaryInputText, summaryCharCount, null); });
// ══════════════════════════════════════════════════════════ // Staleness management // ══════════════════════════════════════════════════════════ function markStale() { if (isStale) return; isStale = true; if (resultSection) resultSection.classList.add('sp-stale'); if (suggestionsSection) suggestionsSection.classList.add('sp-stale'); }
function clearStale() { isStale = false; if (resultSection) resultSection.classList.remove('sp-stale'); if (suggestionsSection) suggestionsSection.classList.remove('sp-stale'); }
// ══════════════════════════════════════════════════════════ // Loading & Toast // ══════════════════════════════════════════════════════════ function setLoading(show, text = 'جارٍ التحليل...') { loadingOverlay.classList.toggle('is-hidden', !show); loadingTextEl.textContent = text; }
function showToast(message, duration = 2500) { const toast = document.getElementById('toast'); toast.textContent = message; toast.classList.add('is-visible'); clearTimeout(toast._timer); toast._timer = setTimeout(() => toast.classList.remove('is-visible'), duration); }
// ══════════════════════════════════════════════════════════ // Score ring // ══════════════════════════════════════════════════════════ function updateScore(spelling, grammar, punctuation) { const score = calculateWritingScore(spelling, grammar, punctuation); const total = spelling + grammar + punctuation;
scoreSection.classList.remove('is-hidden');
if (scoreValue) scoreValue.textContent = score > 0 || total > 0 ? score.toLocaleString('ar-EG') : '--'; if (scoreCircle) { const offset = SCORE_CIRCUMFERENCE - (score / 100) * SCORE_CIRCUMFERENCE; scoreCircle.style.strokeDashoffset = String(offset); } if (scoreHint) scoreHint.textContent = getScoreHint(score, total); if (countSpelling) countSpelling.textContent = spelling.toLocaleString('ar-EG'); if (countGrammar) countGrammar.textContent = grammar.toLocaleString('ar-EG'); if (countPunctuation) countPunctuation.textContent = punctuation.toLocaleString('ar-EG'); }
// ══════════════════════════════════════════════════════════ // Render suggestions list // ══════════════════════════════════════════════════════════ function renderSuggestions(suggestions) { currentSuggestions = suggestions;
if (!suggestions || suggestions.length === 0) { suggestionsSection.classList.add('is-hidden'); btnApplyAll.classList.add('is-hidden'); return; }
suggestionsSection.classList.remove('is-hidden'); suggestionsList.innerHTML = suggestions.map((s, i) => buildSuggestionCardHTML(s, i)).join('');
// Bind alt-chip click events suggestionsList.querySelectorAll('.bayan-alt-chip').forEach((chip) => { chip.addEventListener('click', (e) => { e.stopPropagation();
if (isStale) { showToast('⚠ أعد التحليل أولاً — النص تغيّر'); return; }
const suggestionId = chip.dataset.cardId; const altText = chip.dataset.cardAlt; const suggestion = currentSuggestions.find((s) => String(s.id || '') === String(suggestionId)); if (!suggestion) return;
if (altText === suggestion.original) { currentSuggestions = removeSuggestion(currentSuggestions, suggestion.id); } else { const result = applyAndRebase(analyzedText, suggestion, altText, currentSuggestions); analyzedText = result.text; currentSuggestions = result.suggestions; inputText.value = analyzedText; updateCounts(inputText, charCount, wordCount); }
const counts = countByType(currentSuggestions); updateScore(counts.spelling, counts.grammar, counts.punctuation); renderSuggestions(currentSuggestions); resultText.innerHTML = renderHighlightedText(analyzedText, currentSuggestions); saveState(); showToast('✓ تم التصحيح'); }); });
btnApplyAll.classList.toggle('is-hidden', suggestions.length < 2); }
// ══════════════════════════════════════════════════════════ // Core analysis function // ══════════════════════════════════════════════════════════ async function runAnalysis(text) { if (!text || text.length < CONFIG.MIN_ANALYZE_LENGTH) { showToast('النص قصير جداً (الحد الأدنى ١٥ حرفاً)'); return; } if (text.length > CONFIG.MAX_ANALYZE_LENGTH) { showToast('النص طويل جداً (الحد الأقصى ٥٠٠٠ حرف)'); return; }
isAnalyzing = true; setLoading(true, 'جارٍ التحليل...'); clearStale();
try { const data = await bayanAnalyze(text);
if (data.status === 'success' || data.status === 'partial') { const suggestions = sortSuggestions(data.suggestions || []); currentSuggestions = suggestions; analyzedText = data.original;
inputText.value = analyzedText; updateCounts(inputText, charCount, wordCount);
resultSection.classList.remove('is-hidden'); resultText.innerHTML = renderHighlightedText(analyzedText, suggestions);
const counts = countByType(suggestions); updateScore(counts.spelling, counts.grammar, counts.punctuation); renderSuggestions(suggestions);
if (data.timing_ms) { timingSection.classList.remove('is-hidden'); timingText.textContent = `التحليل: ${data.timing_ms.total_ms || 0}ms`; }
saveState();
if (suggestions.length === 0) { showToast('نصك ممتاز! لم نجد أي أخطاء ✨'); } } else { showToast('تعذّر التحليل — حاول مرة أخرى'); } } catch (error) { console.error('[Bayan SP] Analysis error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { isAnalyzing = false; setLoading(false); } }
// ══════════════════════════════════════════════════════════ // State persistence (side panel survives navigation) // ══════════════════════════════════════════════════════════ function getStorage() { return chrome.storage?.session || chrome.storage?.local; }
function saveState() { const storage = getStorage(); if (!storage) return; storage.set({ spLastText: analyzedText, spLastSuggestions: currentSuggestions, spLastInput: inputText.value, }).catch(() => {}); }
async function restoreState() { const storage = getStorage(); if (!storage) return false;
try { const data = await storage.get(['spLastText', 'spLastSuggestions', 'spLastInput']); if (!data.spLastText || !data.spLastSuggestions) return false;
analyzedText = data.spLastText; currentSuggestions = data.spLastSuggestions; inputText.value = data.spLastInput || analyzedText; updateCounts(inputText, charCount, wordCount);
resultSection.classList.remove('is-hidden'); resultText.innerHTML = renderHighlightedText(analyzedText, currentSuggestions);
const counts = countByType(currentSuggestions); updateScore(counts.spelling, counts.grammar, counts.punctuation); renderSuggestions(currentSuggestions);
return true; } catch { return false; } }
// ══════════════════════════════════════════════════════════ // Button handlers // ═══════════════════════════════════════════════════════���══ btnCorrect.addEventListener('click', () => { const text = inputText.value.trim(); runAnalysis(text); });
btnClear.addEventListener('click', () => { inputText.value = ''; analyzedText = ''; updateCounts(inputText, charCount, wordCount); scoreSection.classList.add('is-hidden'); resultSection.classList.add('is-hidden'); suggestionsSection.classList.add('is-hidden'); timingSection.classList.add('is-hidden'); currentSuggestions = []; clearStale(); const storage = getStorage(); if (storage) storage.remove(['spLastText', 'spLastSuggestions', 'spLastInput']).catch(() => {}); });
btnApplyAll.addEventListener('click', () => { if (currentSuggestions.length === 0) return; if (isStale) { showToast('⚠ أعد التحليل أولاً — النص تغيّر'); return; }
analyzedText = applyAllPatches(analyzedText, currentSuggestions); inputText.value = analyzedText; updateCounts(inputText, charCount, wordCount); currentSuggestions = []; resultText.innerHTML = escapeHtml(analyzedText); updateScore(0, 0, 0); renderSuggestions([]); saveState(); showToast('✓ تم تطبيق جميع التصحيحات'); });
btnCopyResult.addEventListener('click', () => { const text = resultText.textContent || ''; navigator.clipboard.writeText(text) .then(() => showToast('✓ تم نسخ النص')) .catch(() => showToast('تعذّر النسخ')); });
// ══════════════════════════════════════════════════════════ // Summarize // ══════════════════════════════════════════════════════════ btnSummarize.addEventListener('click', async () => { const text = summaryInputText.value.trim(); if (!text) { showToast('أدخل نصاً للتلخيص'); return; } if (text.length < CONFIG.MIN_SUMMARIZE_LENGTH) { showToast('النص قصير جداً للتلخيص'); return; }
const lengthValue = parseInt(document.querySelector('input[name="summary-length"]:checked')?.value || '2', 10); setLoading(true, 'جارٍ التلخيص...');
try { const data = await bayanSummarize(text, lengthValue); if (data.status === 'success' && data.summary) { summaryResultSection.classList.remove('is-hidden'); summaryText.textContent = data.summary; summaryMeta.textContent = `النص الأصلي: ${(data.original_length || 0).toLocaleString('ar-EG')} حرف → الملخص: ${(data.summary_length || 0).toLocaleString('ar-EG')} حرف`; showToast('✓ تم التلخيص'); } else { showToast('تعذّر التلخيص — حاول مرة أخرى'); } } catch (error) { console.error('[Bayan SP] Summarization error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
btnCopySummary.addEventListener('click', () => { const text = summaryText.textContent || ''; navigator.clipboard.writeText(text) .then(() => showToast('✓ تم نسخ الملخص')) .catch(() => showToast('تعذّر النسخ')); });
// ══════════════════════════════════════════════════════════ // Dialect → MSA conversion // ══════════════════════════════════════════════════════════ const dialectInput = document.getElementById('dialect-input-text'); const dialectCharCount = document.getElementById('dialect-char-count'); const btnDialect = document.getElementById('btn-dialect'); const dialectResultSection = document.getElementById('dialect-result-section'); const dialectText = document.getElementById('dialect-text'); const btnCopyDialect = document.getElementById('btn-copy-dialect');
if (dialectInput) { dialectInput.addEventListener('input', () => updateCounts(dialectInput, dialectCharCount, null));
btnDialect.addEventListener('click', async () => { const text = dialectInput.value.trim(); if (!text) { showToast('أدخل نصاً للتحويل'); return; }
setLoading(true, 'جارٍ التحويل...'); try { const data = await bayanDialect(text); if (data.status === 'success' && data.converted_text) { dialectResultSection.classList.remove('is-hidden'); dialectText.textContent = data.converted_text; showToast('✓ تم التحويل'); } else { showToast(data.error || 'تعذّر التحويل — حاول مرة أخرى'); } } catch (error) { console.error('[Bayan SP] Dialect error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
btnCopyDialect.addEventListener('click', () => { navigator.clipboard.writeText(dialectText.textContent || '') .then(() => showToast('✓ تم نسخ النص')) .catch(() => showToast('تعذّر النسخ')); }); }
// ══════════════════════════════════════════════════════════ // Quran verification // ══════════════════════════════════════════════════════════ const quranInput = document.getElementById('quran-input-text'); const quranCharCount = document.getElementById('quran-char-count'); const btnQuran = document.getElementById('btn-quran'); const quranResultSection = document.getElementById('quran-result-section'); const quranText = document.getElementById('quran-text'); const quranMeta = document.getElementById('quran-meta'); const btnCopyQuran = document.getElementById('btn-copy-quran');
if (quranInput) { quranInput.addEventListener('input', () => updateCounts(quranInput, quranCharCount, null));
btnQuran.addEventListener('click', async () => { const text = quranInput.value.trim(); if (!text) { showToast('أدخل آية للتدقيق'); return; }
setLoading(true, 'جارٍ التدقيق...'); try { const data = await bayanQuran(text); quranResultSection.classList.remove('is-hidden'); if (data.error) { quranText.textContent = data.error; quranMeta.textContent = ''; } else { quranText.textContent = data.full_verse || data.matched_segment || JSON.stringify(data); quranMeta.textContent = data.matched_segment && data.full_verse ? `المقطع المطابق: ${data.matched_segment}` : ''; showToast('✓ تم التدقيق'); } } catch (error) { console.error('[Bayan SP] Quran error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } });
btnCopyQuran.addEventListener('click', () => { navigator.clipboard.writeText(quranText.textContent || '') .then(() => showToast('✓ تم النسخ')) .catch(() => showToast('تعذّر النسخ')); }); }
// ══════════════════════════════════════════════════════════ // Autocomplete suggestions // ══════════════════════════════════════════════════════════ const acInput = document.getElementById('autocomplete-input-text'); const acCharCount = document.getElementById('autocomplete-char-count'); const btnAutocomplete = document.getElementById('btn-autocomplete'); const acResultSection = document.getElementById('autocomplete-result-section'); const acList = document.getElementById('autocomplete-list');
if (acInput) { acInput.addEventListener('input', () => updateCounts(acInput, acCharCount, null));
btnAutocomplete.addEventListener('click', async () => { const text = acInput.value; if (!text.trim() || text.trim().length < 3) { showToast('اكتب ٣ أحرف على الأقل'); return; }
setLoading(true, 'جارٍ الاقتراح...'); try { const data = await bayanAutocomplete(text, 5); const suggestions = data.suggestions || []; acResultSection.classList.remove('is-hidden');
if (suggestions.length === 0) { acList.innerHTML = '<div class="sp-ac-empty">لا توجد اقتراحات</div>'; return; }
acList.innerHTML = suggestions .map((s) => `<button class="bayan-alt-chip bayan-alt-chip--main sp-ac-chip" type="button">${escapeHtml(s)}</button>`) .join('');
acList.querySelectorAll('.sp-ac-chip').forEach((chip) => { chip.addEventListener('click', () => { const needsSpace = acInput.value.length > 0 && !/\s$/.test(acInput.value); acInput.value += (needsSpace ? ' ' : '') + chip.textContent; updateCounts(acInput, acCharCount, null); acInput.focus(); showToast('✓ تمت الإضافة'); }); }); } catch (error) { console.error('[Bayan SP] Autocomplete error:', error); showToast('خطأ في الاتصال — تحقق من الإنترنت'); } finally { setLoading(false); } }); }
// ═══��══════════════════════════════════════════════════════ // Phase 5: Download corrected text / summary as .txt // Buttons injected programmatically to avoid touching sidepanel.html. // ══════════════════════════════════════════════════════════ function downloadTxt(text, filename) { if (!text) { showToast('لا يوجد نص للتنزيل'); return; } try { const blob = new Blob([text], { type: 'text/plain;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); showToast('✓ تم تنزيل الملف'); } catch (e) { console.error('[Bayan SP] Download error:', e); showToast('تعذّر التنزيل'); } }
const SP_DOWNLOAD_ICON = '<svg width="14" height="14" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1M12 4v12m0 0l-4-4m4 4l4-4"/></svg>';
function addDownloadButton(anchorBtn, getText, filename) { if (!anchorBtn || !anchorBtn.parentElement) return; const btn = document.createElement('button'); btn.className = 'sp-btn-icon'; btn.type = 'button'; btn.title = 'تنزيل كملف نصي'; btn.innerHTML = SP_DOWNLOAD_ICON; btn.addEventListener('click', () => downloadTxt((getText() || '').trim(), filename)); anchorBtn.parentElement.appendChild(btn); }
addDownloadButton(btnCopyResult, () => resultText.textContent, 'bayan-corrected.txt'); addDownloadButton(btnCopySummary, () => summaryText.textContent, 'bayan-summary.txt');
// ══════════════════════════════════════════════════════════ // Status check // ══════════════════════════════════════════════════════════ (async function checkStatus() { const statusDot = document.querySelector('.sp-status-dot'); const statusText = document.getElementById('status-text'); try { await bayanHealthCheck(); if (statusDot) statusDot.classList.add('online'); if (statusText) statusText.textContent = 'متصل'; } catch { if (statusDot) statusDot.classList.add('offline'); if (statusText) statusText.textContent = 'غير متصل'; } })();
// ══════════════════════════════════════════════════════════ // Context menu pickup (from background.js → storage) // NOTE: background.js calls sidePanel.open() BEFORE storage.set() // to preserve the user gesture token. This means on first open, // storage may not be ready yet. We retry once after 300ms. // If the panel is ALREADY open, the storage.onChanged listener // below catches new actions in real-time. // ══════════════════════════════════════════════════════════ async function tryPickupContext(retryCount = 0) { if (typeof chrome === 'undefined' || !chrome.storage) return; if (contextConsumed) return;
const storage = getStorage(); if (!storage) return;
try { const data = await storage.get(['contextAction', 'contextText', 'contextTimestamp']);
// Storage not ready yet — retry once after 300ms if ((!data.contextAction || !data.contextText) && retryCount < 2) { setTimeout(() => tryPickupContext(retryCount + 1), 300); return; }
if (!data.contextAction || !data.contextText) { // No context action after retries — restore previous state await restoreState(); return; }
const age = Date.now() - (data.contextTimestamp || 0); if (age > 15000) { chrome.runtime.sendMessage({ type: 'CLEAR_CONTEXT' }); await restoreState(); return; }
contextConsumed = true;
console.log(`[Bayan SP] Context action: ${data.contextAction}, text: ${data.contextText.length} chars`);
if (data.contextAction === TAB.CORRECT) { inputText.value = data.contextText; updateCounts(inputText, charCount, wordCount);
const correctTab = document.querySelector(`[data-tab="${TAB.CORRECT}"]`); if (correctTab) correctTab.click();
// Auto-analyze immediately setTimeout(() => runAnalysis(data.contextText), 100);
} else if (data.contextAction === TAB.SUMMARIZE) { summaryInputText.value = data.contextText; updateCounts(summaryInputText, summaryCharCount, null);
const summarizeTab = document.querySelector(`[data-tab="${TAB.SUMMARIZE}"]`); if (summarizeTab) summarizeTab.click();
setTimeout(() => btnSummarize.click(), 100); }
chrome.runtime.sendMessage({ type: 'CLEAR_CONTEXT' });
} catch (err) { console.warn('[Bayan SP] Context action check failed:', err); await restoreState(); } }
// Start context pickup with retry tryPickupContext(0);
// ══════════════════════════════════════════════════════════ // Listen for NEW context actions while panel is already open // ══════════════════════════════════════════════════════════ if (chrome.storage?.session?.onChanged || chrome.storage?.onChanged) { const storageApi = chrome.storage; storageApi.onChanged.addListener((changes, area) => { if (area !== 'session' && area !== 'local') return; if (!changes.contextAction || !changes.contextText) return;
const action = changes.contextAction.newValue; const text = changes.contextText.newValue; if (!action || !text) return;
console.log(`[Bayan SP] Storage changed — new context: ${action}, ${text.length} chars`);
if (action === TAB.CORRECT) { inputText.value = text; updateCounts(inputText, charCount, wordCount);
const correctTab = document.querySelector(`[data-tab="${TAB.CORRECT}"]`); if (correctTab) correctTab.click();
runAnalysis(text);
} else if (action === TAB.SUMMARIZE) { summaryInputText.value = text; updateCounts(summaryInputText, summaryCharCount, null);
const summarizeTab = document.querySelector(`[data-tab="${TAB.SUMMARIZE}"]`); if (summarizeTab) summarizeTab.click();
setTimeout(() => btnSummarize.click(), 100); }
chrome.runtime.sendMessage({ type: 'CLEAR_CONTEXT' }); }); }});1234567891011121314151617181920212223242526272829303132333435363738394041{ "corrected": "أنا ذاهب الي البت.", "original": "انا ذاهب الي البت", "status": "success", "suggestions": [ { "alternatives": [
], "confidence": 0.8, "correction": "البت.", "end": 17, "id": "bad18f97-041d-4487-a780-17fc4082447d", "locked": true, "original": "البت", "priority": 2, "start": 13, "type": "punctuation" }, { "alternatives": [
], "confidence": 1.0, "correction": "أنا", "end": 3, "id": "1c3d902b-11a9-4350-86e2-a74e66bb0639", "locked": true, "original": "انا", "priority": 1, "start": 0, "type": "spelling" } ], "timing_ms": { "grammar_ms": 585, "punctuation_ms": 368, "spelling_ms": 2585, "total_ms": 3540 }}1234567891011121314$t = 'أنا ذاهب الى البت والمدرسه'Write-Host "Length: $($t.Length)"Write-Host "Chars 10-13: '$($t.Substring(10, 3))'"Write-Host "Chars 14-17: '$($t.Substring(14, 3))'"Write-Host "Chars 19-26: '$($t.Substring(19, 7))'"
# Direct test: substring replacement$before = $t.Substring(0, 10)$after = $t.Substring(13)$result = $before + 'إلى' + $afterWrite-Host "`nReplace [10:13] 'الى' with 'إلى':"Write-Host "Result: '$result'"Write-Host "Expected: 'أنا ذاهب إلى البت والمدرسه'"Write-Host "Match: $($result -eq 'أنا ذاهب إلى البت والمدرسه')"1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980$ErrorActionPreference = 'Stop'
# Test Case 1: Basic Correction FlowWrite-Host "═══════════════════════════════════════════════════" -ForegroundColor CyanWrite-Host "TEST CASE 1: Basic Correction Flow" -ForegroundColor CyanWrite-Host "═══════════════════════════════════════════════════" -ForegroundColor Cyan
$inputText = 'انا ذهبت الي المدرسه اليوم'Write-Host "`nInput: `"$inputText`""
$body = @{ text = $inputText } | ConvertTo-Json -Compress$response = Invoke-RestMethod -Uri 'https://bayan10-bayan-api.hf.space/api/analyze' -Method POST -Body ([System.Text.Encoding]::UTF8.GetBytes($body)) -ContentType 'application/json; charset=utf-8'
Write-Host "`n── API Response ──" -ForegroundColor YellowWrite-Host "Status: $($response.status)"Write-Host "Original: `"$($response.original)`""Write-Host "Corrected: `"$($response.corrected)`""Write-Host "Suggestions count: $($response.suggestions.Count)"
Write-Host "`n── Timing ──" -ForegroundColor YellowWrite-Host "Total: $($response.timing_ms.total_ms)ms"Write-Host "Spelling: $($response.timing_ms.spelling_ms)ms"Write-Host "Grammar: $($response.timing_ms.grammar_ms)ms"Write-Host "Punctuation: $($response.timing_ms.punctuation_ms)ms"
Write-Host "`n── Suggestions ──" -ForegroundColor Yellowforeach ($s in $response.suggestions) { Write-Host " [$($s.type)] `"$($s.original)`" → `"$($s.correction)`" (start:$($s.start), end:$($s.end), id:$($s.id.Substring(0,8))...)" if ($s.alternatives) { Write-Host " Alternatives: $($s.alternatives -join ', ')" }}
# Schema validationWrite-Host "`n── Schema Validation ──" -ForegroundColor Yellow$fields = @('status', 'original', 'corrected', 'suggestions', 'timing_ms')foreach ($f in $fields) { $exists = $null -ne $response.$f $icon = if ($exists) { "✅" } else { "❌" } Write-Host " $icon Field '$f' present"}
# Suggestion schemaif ($response.suggestions.Count -gt 0) { $s = $response.suggestions[0] $sFields = @('id', 'start', 'end', 'original', 'correction', 'type', 'alternatives') foreach ($f in $sFields) { $exists = $null -ne $s.$f $icon = if ($exists) { "✅" } else { "❌" } Write-Host " $icon Suggestion field '$f' present" }}
Write-Host "`n═══════════════════════════════════════════════════" -ForegroundColor CyanWrite-Host "TEST CASE 2: Sequential Apply Input" -ForegroundColor CyanWrite-Host "═══════════════════════════════════════════════════" -ForegroundColor Cyan
$inputText2 = 'انا ذاهب الي البت'Write-Host "`nInput: `"$inputText2`""
$body2 = @{ text = $inputText2 } | ConvertTo-Json -Compress$response2 = Invoke-RestMethod -Uri 'https://bayan10-bayan-api.hf.space/api/analyze' -Method POST -Body ([System.Text.Encoding]::UTF8.GetBytes($body2)) -ContentType 'application/json; charset=utf-8'
Write-Host "`n── API Response ──" -ForegroundColor YellowWrite-Host "Status: $($response2.status)"Write-Host "Original: `"$($response2.original)`""Write-Host "Corrected: `"$($response2.corrected)`""Write-Host "Suggestions count: $($response2.suggestions.Count)"
Write-Host "`n── Suggestions ──" -ForegroundColor Yellowforeach ($s in $response2.suggestions) { Write-Host " [$($s.type)] `"$($s.original)`" → `"$($s.correction)`" (start:$($s.start), end:$($s.end))" if ($s.alternatives) { Write-Host " Alternatives: $($s.alternatives -join ', ')" }}
# Save response for browser test$response2 | ConvertTo-Json -Depth 5 | Out-File -FilePath 'e:\Atef''s Shit\extension\tests\api_response_tc2.json' -Encoding UTF8Write-Host "`n✅ Response saved to api_response_tc2.json"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319<!DOCTYPE html><html lang="ar" dir="rtl"><head> <meta charset="UTF-8"> <title>Bayan — E2E Verification</title> <style> body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0f0f14; color: #f0f0f5; padding: 24px; max-width: 800px; margin: 0 auto; } h1 { color: #818cf8; font-size: 20px; margin-bottom: 20px; } h2 { color: #9898ad; font-size: 16px; margin: 20px 0 10px; border-bottom: 1px solid #2d2d3d; padding-bottom: 6px; } .test-group { margin-bottom: 16px; padding: 12px; background: #1a1a24; border-radius: 8px; border: 1px solid #2d2d3d; } .pass { color: #22c55e; } .fail { color: #ef4444; font-weight: bold; } .result-line { font-size: 13px; margin: 4px 0; font-family: monospace; direction: ltr; text-align: left; } .detail { color: #6b6b80; font-size: 12px; margin-left: 24px; direction: ltr; text-align: left; } .summary { margin-top: 24px; padding: 16px; background: #1a1a24; border-radius: 8px; border: 2px solid #818cf8; font-size: 16px; font-weight: bold; direction: ltr; text-align: center; } #log { white-space: pre-wrap; font-family: monospace; font-size: 12px; color: #9898ad; background: #111118; padding: 12px; border-radius: 8px; margin-top: 12px; direction: ltr; text-align: left; max-height: 300px; overflow-y: auto; } .arabic-text { direction: rtl; text-align: right; font-size: 16px; padding: 8px; background: #22222e; border-radius: 6px; margin: 6px 0; } </style></head><body> <h1>🔬 Bayan — Real E2E Verification</h1> <div id="output"></div> <h2>Execution Log</h2> <div id="log"></div>
<!-- Load extension modules --> <script src="../shared/config.js"></script> <script src="../shared/bayan-renderer.js"></script> <script src="../shared/bayan-ui.js"></script> <script src="../shared/bayan-patches.js"></script> <script src="../shared/bayan-api.js"></script>
<script> const outputEl = document.getElementById('output'); const logEl = document.getElementById('log'); let passed = 0; let failed = 0; let currentGroup = null;
function log(msg) { logEl.textContent += msg + '\n'; console.log(msg); }
function group(name) { currentGroup = document.createElement('div'); currentGroup.className = 'test-group'; currentGroup.innerHTML = `<h2 style="margin:0 0 8px;font-size:14px;color:#818cf8">${name}</h2>`; outputEl.appendChild(currentGroup); }
function assert(condition, message) { const el = document.createElement('div'); el.className = 'result-line'; if (condition) { passed++; el.innerHTML = `<span class="pass">✅</span> ${message}`; } else { failed++; el.innerHTML = `<span class="fail">❌</span> ${message}`; } currentGroup.appendChild(el); }
function assertEqual(actual, expected, message) { if (actual === expected) { assert(true, message); } else { assert(false, message); const detail = document.createElement('div'); detail.className = 'detail'; detail.textContent = `Expected: "${expected}" | Actual: "${actual}"`; currentGroup.appendChild(detail); } }
function showArabic(text) { const el = document.createElement('div'); el.className = 'arabic-text'; el.textContent = text; currentGroup.appendChild(el); }
// ══════════════════════════════════════════════ // MAIN TEST RUNNER // ══════════════════════════════════════════════ (async function runTests() {
// ═══════════════════════════════════════════ // TEST CASE 1: Basic Correction Flow // ═══════════════════════════════════════════ group('TEST CASE 1: API Verification'); const INPUT_1 = 'انا ذهبت الي المدرسه اليوم'; log(`[TC1] Input: "${INPUT_1}"`);
let data1; try { data1 = await bayanAnalyze(INPUT_1); log(`[TC1] API response received: status=${data1.status}, suggestions=${data1.suggestions?.length}`); assert(true, 'API call succeeded (no network error)'); } catch (err) { assert(false, `API call failed: ${err.message}`); log(`[TC1] ERROR: ${err.message}`); return; }
// Schema validation assertEqual(data1.status, 'success', 'Response status = "success"'); assert(typeof data1.original === 'string', 'Response has "original" (string)'); assert(typeof data1.corrected === 'string', 'Response has "corrected" (string)'); assert(Array.isArray(data1.suggestions), 'Response has "suggestions" (array)'); assert(typeof data1.timing_ms === 'object', 'Response has "timing_ms" (object)'); assert(data1.suggestions.length > 0, `Suggestions returned: ${data1.suggestions.length}`);
// Verify suggestion schema if (data1.suggestions.length > 0) { const s = data1.suggestions[0]; assert(typeof s.id === 'string', 'Suggestion has "id"'); assert(typeof s.start === 'number', 'Suggestion has "start"'); assert(typeof s.end === 'number', 'Suggestion has "end"'); assert(typeof s.original === 'string', 'Suggestion has "original"'); assert(typeof s.correction === 'string', 'Suggestion has "correction"'); assert(typeof s.type === 'string', 'Suggestion has "type"'); }
// Verify offsets match original text group('TEST CASE 1: Offset Correctness'); const sorted1 = sortSuggestions(data1.suggestions); sorted1.forEach((s, i) => { const extracted = data1.original.slice(s.start, s.end); assertEqual(extracted, s.original, `Suggestion ${i} offset [${s.start}:${s.end}] extracts "${s.original}"`); log(`[TC1] Suggestion ${i}: [${s.type}] "${s.original}" → "${s.correction}" offset=[${s.start}:${s.end}]`); });
// Apply All test group('TEST CASE 1: Apply All'); const correctedText1 = applyAllPatches(data1.original, data1.suggestions); showArabic(correctedText1); assertEqual(correctedText1, data1.corrected, 'applyAllPatches() === API corrected text'); log(`[TC1] applyAllPatches result: "${correctedText1}"`); log(`[TC1] API corrected field: "${data1.corrected}"`);
// Highlighted text test group('TEST CASE 1: Rendering'); const html1 = renderHighlightedText(data1.original, sorted1); assert(html1.length > 0, 'renderHighlightedText produces non-empty HTML'); assert(html1.includes('bayan-spelling-error') || html1.includes('bayan-punctuation-suggestion'), 'HTML contains error highlight classes'); log(`[TC1] Highlighted HTML length: ${html1.length} chars`);
// Score test group('TEST CASE 1: Score Calculation'); const counts1 = countByType(data1.suggestions); const score1 = calculateWritingScore(counts1.spelling, counts1.grammar, counts1.punctuation); assert(score1 >= 0 && score1 <= 100, `Score in valid range: ${score1}`); log(`[TC1] Counts: spelling=${counts1.spelling}, grammar=${counts1.grammar}, punctuation=${counts1.punctuation}`); log(`[TC1] Score: ${score1}/100`);
// ═══════════════════════════════════════════ // TEST CASE 2: Sequential Apply // ═══════════════════════════════════════════ group('TEST CASE 2: API Call'); const INPUT_2 = 'انا ذاهب الي البت'; log(`\n[TC2] Input: "${INPUT_2}"`);
let data2; try { data2 = await bayanAnalyze(INPUT_2); log(`[TC2] API response: status=${data2.status}, suggestions=${data2.suggestions?.length}`); assert(true, 'API call succeeded'); assertEqual(data2.status, 'success', 'Status = success'); } catch (err) { assert(false, `API call failed: ${err.message}`); return; }
// Show what the API actually detected group('TEST CASE 2: API-Detected Corrections'); data2.suggestions.forEach((s, i) => { assert(true, `[${s.type}] "${s.original}" → "${s.correction}" (${s.start}:${s.end})`); }); showArabic(`API corrected: ${data2.corrected}`);
// Sequential apply using ACTUAL API response group('TEST CASE 2: Sequential Apply (Actual API suggestions)'); let text2 = data2.original; let sugs2 = sortSuggestions([...data2.suggestions]); log(`[TC2] Starting sequential apply with ${sugs2.length} suggestions`); log(`[TC2] Initial text: "${text2}"`);
const applyOrder = [...sugs2]; // Apply in sorted order for (let i = 0; i < applyOrder.length; i++) { const sug = sugs2.find(s => s.id === applyOrder[i].id); if (!sug) { log(`[TC2] Suggestion ${i} already removed, skipping`); continue; }
// Verify offset before apply const beforeExtract = text2.slice(sug.start, sug.end); assertEqual(beforeExtract, sug.original, `Step ${i+1}: Offset [${sug.start}:${sug.end}] extracts "${sug.original}" BEFORE apply`);
// Apply and rebase const result = applyAndRebase(text2, sug, sug.correction, sugs2); text2 = result.text; sugs2 = result.suggestions;
log(`[TC2] Step ${i+1}: Applied "${sug.original}" → "${sug.correction}"`); log(`[TC2] Step ${i+1}: Text now: "${text2}"`); log(`[TC2] Step ${i+1}: Remaining suggestions: ${sugs2.length}`); showArabic(`Step ${i+1}: ${text2}`);
// Verify ALL remaining suggestion offsets still extract correct text sugs2.forEach((rs, j) => { const extracted = text2.slice(rs.start, rs.end); assertEqual(extracted, rs.original, `Step ${i+1}: Remaining[${j}] offset [${rs.start}:${rs.end}] extracts "${rs.original}"`); }); }
assert(sugs2.length === 0, 'All suggestions applied (0 remaining)'); assertEqual(text2, data2.corrected, 'Sequential result === API corrected text');
// ═══════════════════════════════════════════ // TEST CASE 2b: Synthetic test with user's exact scenario // ═══════════════════════════════════════════ group('TEST CASE 2b: Synthetic Sequential (User Scenario)'); // Simulate the exact scenario the user described, // using manually-constructed suggestions const SYNTH_TEXT = 'انا ذاهب الى البت'; const synthIdx_ana = SYNTH_TEXT.indexOf('انا'); const synthIdx_ala = SYNTH_TEXT.indexOf('الى'); const synthIdx_bet = SYNTH_TEXT.indexOf('البت');
log(`[TC2b] Synthetic text: "${SYNTH_TEXT}" (length: ${SYNTH_TEXT.length})`); log(`[TC2b] indexOf('انا')=${synthIdx_ana}, indexOf('الى')=${synthIdx_ala}, indexOf('البت')=${synthIdx_bet}`);
const synthSugs = [ { id: 's1', start: synthIdx_ala, end: synthIdx_ala + 3, original: 'الى', correction: 'إلى', type: 'grammar' }, { id: 's2', start: synthIdx_bet, end: synthIdx_bet + 4, original: 'البت', correction: 'البيت', type: 'spelling' }, { id: 's3', start: synthIdx_ana, end: synthIdx_ana + 3, original: 'انا', correction: 'أنا', type: 'spelling' }, ];
// Verify offsets synthSugs.forEach(s => { assertEqual(SYNTH_TEXT.slice(s.start, s.end), s.original, `Offset check: [${s.start}:${s.end}] = "${s.original}"`); });
// Step 1: Apply "الى" → "إلى" let sText = SYNTH_TEXT; let sSugs = [...synthSugs]; let r1 = applyAndRebase(sText, sSugs[0], 'إلى', sSugs); sText = r1.text; sSugs = r1.suggestions; showArabic(`Step 1 (الى→إلى): ${sText}`); assertEqual(sText, 'انا ذاهب إلى البت', 'Step 1 result correct'); assert(sSugs.length === 2, 'Step 1: 2 remaining'); // Verify remaining offsets sSugs.forEach(s => { assertEqual(sText.slice(s.start, s.end), s.original, `Step 1: Remaining "${s.original}" offset valid`); });
// Step 2: Apply "البت" → "البيت" (should be at shifted offset) const sugBet = sSugs.find(s => s.original === 'البت'); assert(!!sugBet, 'Found "البت" suggestion in remaining'); let r2 = applyAndRebase(sText, sugBet, 'البيت', sSugs); sText = r2.text; sSugs = r2.suggestions; showArabic(`Step 2 (البت→البيت): ${sText}`); assertEqual(sText, 'انا ذاهب إلى البيت', 'Step 2 result correct'); assert(sSugs.length === 1, 'Step 2: 1 remaining'); sSugs.forEach(s => { assertEqual(sText.slice(s.start, s.end), s.original, `Step 2: Remaining "${s.original}" offset valid`); });
// Step 3: Apply "انا" → "أنا" const sugAna = sSugs.find(s => s.original === 'انا'); assert(!!sugAna, 'Found "انا" suggestion in remaining'); let r3 = applyAndRebase(sText, sugAna, 'أنا', sSugs); sText = r3.text; sSugs = r3.suggestions; showArabic(`Step 3 (انا→أنا): ${sText}`);
// FINAL VERIFICATION assertEqual(sText, 'أنا ذاهب إلى البيت', '🏁 FINAL RESULT matches expected'); assert(sSugs.length === 0, 'All suggestions consumed');
// Verify sequential === applyAllPatches const bulkResult = applyAllPatches(SYNTH_TEXT, synthSugs); assertEqual(sText, bulkResult, 'Sequential === applyAllPatches');
// ═══════════════════════════════════════════ // SUMMARY // ═══════════════════════════════════════════ const summary = document.createElement('div'); summary.className = 'summary'; summary.style.color = failed > 0 ? '#ef4444' : '#22c55e'; summary.textContent = `Results: ${passed} passed, ${failed} failed`; outputEl.appendChild(summary);
const verdict = document.createElement('div'); verdict.className = 'summary'; verdict.style.marginTop = '12px'; if (failed === 0) { verdict.style.color = '#22c55e'; verdict.style.borderColor = '#22c55e'; verdict.textContent = 'HIGH-1 = COMPLETE (REAL VERIFIED) ✅'; } else { verdict.style.color = '#ef4444'; verdict.style.borderColor = '#ef4444'; verdict.textContent = `HIGH-1 = INCOMPLETE (${failed} failures)`; } outputEl.appendChild(verdict);
log(`\n${'═'.repeat(50)}`); log(`Results: ${passed} passed, ${failed} failed`); log(`${'═'.repeat(50)}`); })(); </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778<!DOCTYPE html><html lang="ar" dir="rtl"><head> <meta charset="UTF-8"> <title>Bayan Inline Engine — Test</title> <style> body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #1a1a2e; color: #f0f0f5; padding: 40px; } h1 { color: #818cf8; margin-bottom: 20px; } textarea { width: 100%; height: 150px; font-size: 16px; padding: 12px; border-radius: 8px; border: 1px solid #3a3a4d; background: #22222e; color: #f0f0f5; direction: rtl; } .field-group { margin-bottom: 30px; } label { display: block; margin-bottom: 8px; color: #9898ad; } [contenteditable] { width: 100%; min-height: 100px; font-size: 16px; padding: 12px; border-radius: 8px; border: 1px solid #3a3a4d; background: #22222e; color: #f0f0f5; direction: rtl; outline: none; } [contenteditable]:focus { border-color: #6366f1; } .instructions { background: #22222e; padding: 16px; border-radius: 8px; margin-bottom: 30px; font-size: 13px; color: #9898ad; } .instructions code { background: #2a2a38; padding: 2px 6px; border-radius: 4px; color: #818cf8; } </style></head><body> <h1>🧪 اختبار محرك بيان المضمّن (Phase 6)</h1>
<div class="instructions"> <p><strong>كيفية الاختبار:</strong></p> <ol> <li>اكتب أو الصق نصاً عربياً يحتوي على أخطاء في أي حقل أدناه</li> <li>انتظر ثانية واحدة — ستظهر أيقونة بيان الصغيرة</li> <li>ستظهر الأخطاء بخطوط حمراء/برتقالية/زرقاء</li> <li>انقر على كلمة مُعلّمة لرؤية الاقتراح</li> </ol> <p>نص اختباري: <code>انا ذهبت الي المدرسه اليوم وكان الجو جميل جدا</code></p> </div>
<div class="field-group"> <label>📝 حقل نصي (textarea)</label> <textarea id="test-textarea" placeholder="اكتب نصاً عربياً هنا..."></textarea> </div>
<div class="field-group"> <label>✏️ حقل قابل للتحرير (contenteditable)</label> <div contenteditable="true" id="test-contenteditable"></div> </div>
<div class="field-group"> <label>🔤 حقل إدخال (input)</label> <input type="text" id="test-input" style="width:100%;font-size:16px;padding:10px;border-radius:8px;border:1px solid #3a3a4d;background:#22222e;color:#f0f0f5;direction:rtl;" placeholder="اكتب هنا..."> </div>
<div id="console-log" style="margin-top: 30px; padding: 12px; background: #0f0f14; border-radius: 8px; font-family: monospace; font-size: 11px; color: #6b6b80; max-height: 200px; overflow-y: auto;"> <div>Bayan Inline Test Page Ready</div> </div>
<script> // Capture console.log/warn to show on page const logDiv = document.getElementById('console-log'); const origLog = console.log; const origWarn = console.warn; console.log = (...args) => { origLog(...args); if (args[0]?.includes?.('[Bayan')) { const el = document.createElement('div'); el.textContent = args.join(' '); el.style.color = '#22c55e'; logDiv.appendChild(el); logDiv.scrollTop = logDiv.scrollHeight; } }; console.warn = (...args) => { origWarn(...args); const el = document.createElement('div'); el.textContent = args.join(' '); el.style.color = '#f59e0b'; logDiv.appendChild(el); logDiv.scrollTop = logDiv.scrollHeight; }; </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Bayan Patch Engine — Tests</title> <style> body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0f0f14; color: #f0f0f5; padding: 24px; } h1 { color: #818cf8; font-size: 20px; margin-bottom: 20px; } .test-group { margin-bottom: 16px; padding: 12px; background: #1a1a24; border-radius: 8px; border: 1px solid #2d2d3d; } .test-group h2 { font-size: 14px; color: #9898ad; margin-bottom: 8px; } .pass { color: #22c55e; } .fail { color: #ef4444; font-weight: bold; } .result-line { font-size: 13px; margin: 4px 0; font-family: monospace; } .detail { color: #6b6b80; font-size: 12px; margin-left: 24px; } .summary { margin-top: 24px; padding: 16px; background: #1a1a24; border-radius: 8px; border: 2px solid #818cf8; font-size: 16px; font-weight: bold; } </style></head><body> <h1>🧪 Bayan Patch Engine — Test Suite</h1> <div id="output"></div>
<!-- Load modules in dependency order --> <script src="../shared/config.js"></script> <script src="../shared/bayan-renderer.js"></script> <script src="../shared/bayan-ui.js"></script> <script src="../shared/bayan-patches.js"></script>
<script> const output = document.getElementById('output'); let passed = 0; let failed = 0; let currentGroup = null;
function group(name) { currentGroup = document.createElement('div'); currentGroup.className = 'test-group'; currentGroup.innerHTML = `<h2>${name}</h2>`; output.appendChild(currentGroup); }
function assert(condition, message) { const el = document.createElement('div'); el.className = 'result-line'; if (condition) { passed++; el.innerHTML = `<span class="pass">✅</span> ${message}`; } else { failed++; el.innerHTML = `<span class="fail">❌</span> ${message}`; } currentGroup.appendChild(el); }
function assertEqual(actual, expected, message) { if (actual === expected) { assert(true, message); } else { assert(false, message); const detail = document.createElement('div'); detail.className = 'detail'; detail.textContent = `Expected: "${expected}" | Actual: "${actual}"`; currentGroup.appendChild(detail); } }
// ══════════════════════════════════════════════════════ // Test data — offsets verified via JavaScript indexOf() // ══════════════════════════════════════════════════════ // // TEXT = 'أنا ذاهب الى البت والمدرسه' (length: 26) // // indexOf('الى') = 9 → slice(9, 12) = 'الى' (3 chars) // indexOf('البت') = 13 → slice(13, 17) = 'البت' (4 chars) // indexOf('المدرسه') = 19 → slice(19, 26) = 'المدرسه' (7 chars) //
const TEXT = 'أنا ذاهب الى البت والمدرسه';
function makeSuggestions() { return [ { id: 'a', start: 9, end: 12, original: 'الى', correction: 'إلى', type: 'grammar' }, { id: 'b', start: 13, end: 17, original: 'البت', correction: 'البيت', type: 'spelling' }, { id: 'c', start: 19, end: 26, original: 'المدرسه', correction: 'المدرسة', type: 'spelling' }, ]; }
// ── Prerequisite: verify test data offsets ── group('PREREQ: Verify test data offsets'); assertEqual(TEXT.length, 26, 'Text length = 26'); assertEqual(TEXT.slice(9, 12), 'الى', 'slice(9,12) = "الى"'); assertEqual(TEXT.slice(13, 17), 'البت', 'slice(13,17) = "البت"'); assertEqual(TEXT.slice(19, 26), 'المدرسه', 'slice(19,26) = "المدرسه"');
// ══════════════════════════════════════════════════════ // TEST 1: Same-length replacement (delta = 0) // "الى" (3) → "إلى" (3), delta = 0 // ══════════════════════════════════════════════════════ group('TEST 1: Same-length replacement (delta = 0)'); { const suggestions = makeSuggestions(); const result = applyAndRebase(TEXT, suggestions[0], 'إلى', suggestions);
assertEqual(result.text, 'أنا ذاهب إلى البت والمدرسه', 'Text: "الى" → "إلى"'); assert(result.suggestions.length === 2, 'Removed applied (2 remaining)'); assertEqual(result.suggestions[0].start, 13, 'B.start unchanged (13)'); assertEqual(result.suggestions[0].end, 17, 'B.end unchanged (17)'); assertEqual(result.suggestions[1].start, 19, 'C.start unchanged (19)'); assertEqual(result.suggestions[1].end, 26, 'C.end unchanged (26)'); // Verify offsets extract correct text from modified string assertEqual(result.text.slice(result.suggestions[0].start, result.suggestions[0].end), 'البت', 'Rebased B extracts "البت"'); assertEqual(result.text.slice(result.suggestions[1].start, result.suggestions[1].end), 'المدرسه', 'Rebased C extracts "المدرسه"'); }
// ══════════════════════════════════════════════════════ // TEST 2: Longer replacement (delta > 0) // "البت" (4) → "البيت" (5), delta = +1 // ══════════════════════════════════════════════════════ group('TEST 2: Longer replacement (delta > 0)'); { const suggestions = makeSuggestions(); const result = applyAndRebase(TEXT, suggestions[1], 'البيت', suggestions);
assertEqual(result.text, 'أنا ذاهب الى البيت والمدرسه', 'Text: "البت" → "البيت"'); assert(result.suggestions.length === 2, 'Removed applied (2 remaining)');
// A is BEFORE B — no shift assertEqual(result.suggestions[0].start, 9, 'A.start unchanged (9)'); assertEqual(result.suggestions[0].end, 12, 'A.end unchanged (12)');
// C is AFTER B — shift by +1 assertEqual(result.suggestions[1].start, 20, 'C.start shifted 19→20 (+1)'); assertEqual(result.suggestions[1].end, 27, 'C.end shifted 26→27 (+1)');
// Verify rebased offsets assertEqual(result.text.slice(result.suggestions[0].start, result.suggestions[0].end), 'الى', 'Rebased A extracts "الى"'); assertEqual(result.text.slice(result.suggestions[1].start, result.suggestions[1].end), 'المدرسه', 'Rebased C extracts "المدرسه"'); }
// ══════════════════════════════════════════════════════ // TEST 3: Shorter replacement (delta < 0) // ══════════════════════════════════════════════════════ group('TEST 3: Shorter replacement (delta < 0)'); { const text = 'هذا النصص خاطئ والكلمه'; // Verify offsets const idx1 = text.indexOf('النصص'); const idx2 = text.indexOf('والكلمه'); const suggestions = [ { id: 'x', start: idx1, end: idx1 + 5, original: 'النصص', correction: 'النص', type: 'spelling' }, { id: 'y', start: idx2, end: idx2 + 7, original: 'والكلمه', correction: 'والكلمة', type: 'spelling' }, ];
// "النصص" (5) → "النص" (4), delta = -1 const result = applyAndRebase(text, suggestions[0], 'النص', suggestions);
assertEqual(result.text, 'هذا النص خاطئ والكلمه', 'Text: "النصص" → "النص"'); assert(result.suggestions.length === 1, '1 remaining'); assertEqual(result.suggestions[0].start, idx2 - 1, 'Y.start shifted by -1'); assertEqual(result.suggestions[0].end, idx2 + 7 - 1, 'Y.end shifted by -1'); assertEqual( result.text.slice(result.suggestions[0].start, result.suggestions[0].end), 'والكلمه', 'Rebased Y extracts "والكلمه"' ); }
// ══════════════════════════════════════════════════════ // TEST 4: Multiple sequential applies // ══════════════════════════════════════════════════════ group('TEST 4: Multiple sequential applies'); { let text = TEXT; let suggestions = makeSuggestions();
// Apply A first (same-length, delta=0) let r1 = applyAndRebase(text, suggestions[0], 'إلى', suggestions); text = r1.text; suggestions = r1.suggestions; assertEqual(text, 'أنا ذاهب إلى البت والمدرسه', 'After apply A'); assert(suggestions.length === 2, '2 remaining after A');
// Apply B (longer, delta=+1) let r2 = applyAndRebase(text, suggestions[0], 'البيت', suggestions); text = r2.text; suggestions = r2.suggestions; assertEqual(text, 'أنا ذاهب إلى البيت والمدرسه', 'After apply B'); assert(suggestions.length === 1, '1 remaining after B');
// Apply C (same-length, delta=0) let r3 = applyAndRebase(text, suggestions[0], 'المدرسة', suggestions); text = r3.text; suggestions = r3.suggestions; assertEqual(text, 'أنا ذاهب إلى البيت والمدرسة', 'After apply C — fully corrected'); assert(suggestions.length === 0, '0 remaining — all applied');
// Verify equals applyAllPatches const expectedFull = applyAllPatches(TEXT, makeSuggestions()); assertEqual(text, expectedFull, 'Sequential === applyAllPatches'); }
// ══════════════════════════════════════════════════════ // TEST 5: Apply last suggestion (no rebase needed) // ══════════════════════════════════════════════════════ group('TEST 5: Apply last suggestion'); { const suggestions = makeSuggestions(); const result = applyAndRebase(TEXT, suggestions[2], 'المدرسة', suggestions);
assertEqual(result.text, 'أنا ذاهب الى البت والمدرسة', 'Last suggestion applied'); assert(result.suggestions.length === 2, '2 remaining'); assertEqual(result.suggestions[0].start, 9, 'A unchanged'); assertEqual(result.suggestions[1].start, 13, 'B unchanged'); // Verify offsets still work assertEqual(result.text.slice(result.suggestions[0].start, result.suggestions[0].end), 'الى', 'A extracts correctly'); assertEqual(result.text.slice(result.suggestions[1].start, result.suggestions[1].end), 'البت', 'B extracts correctly'); }
// ══════════════════════════════════════════════════════ // TEST 6: Dismiss (removeSuggestion — no rebase) // ══════════════════════════════════════════════════════ group('TEST 6: Dismiss (removeSuggestion)'); { const suggestions = makeSuggestions(); const remaining = removeSuggestion(suggestions, 'b'); assert(remaining.length === 2, '2 remaining after dismiss'); assert(remaining.every(s => s.id !== 'b'), 'Dismissed suggestion removed'); assertEqual(remaining[0].start, 9, 'A offset unchanged'); assertEqual(remaining[1].start, 19, 'C offset unchanged'); }
// ══════════════════════════════════════════════════════ // TEST 7: applyAllPatches (reverse-order) // ══════════════════════════════════════════════════════ group('TEST 7: applyAllPatches'); { const result = applyAllPatches(TEXT, makeSuggestions()); assertEqual(result, 'أنا ذاهب إلى البيت والمدرسة', 'All patches applied correctly'); }
// ══════════════════════════════════════════════════════ // TEST 8: countByType // ══════════════════════════════════════════════════════ group('TEST 8: countByType'); { const counts = countByType(makeSuggestions()); assertEqual(counts.spelling, 2, '2 spelling'); assertEqual(counts.grammar, 1, '1 grammar'); assertEqual(counts.punctuation, 0, '0 punctuation'); }
// ══════════════════════════════════════════════════════ // TEST 9: Apply first suggestion at start=0 // ══════════════════════════════════════════════════════ group('TEST 9: Apply first suggestion (start=0)'); { const text = 'الخطاء في البداية'; const i1 = text.indexOf('الخطاء'); const suggestions = [ { id: 'f', start: i1, end: i1 + 6, original: 'الخطاء', correction: 'الخطأ', type: 'spelling' }, { id: 'g', start: 10, end: 17, original: 'البداية', correction: 'البدايه', type: 'grammar' }, ];
// "الخطاء" (6) → "الخطأ" (5), delta = -1 const result = applyAndRebase(text, suggestions[0], 'الخطأ', suggestions); assertEqual(result.text.slice(0, 5), 'الخطأ', 'First word replaced'); assertEqual(result.suggestions[0].start, 9, 'G.start shifted 10→9 (-1)'); assertEqual(result.suggestions[0].end, 16, 'G.end shifted 17→16 (-1)'); }
// ══════════════════════════════════════════════════════ // Summary // ═══════════════════════���══════════════════════════════ const summary = document.createElement('div'); summary.className = 'summary'; summary.style.color = failed > 0 ? '#ef4444' : '#22c55e'; summary.textContent = `Results: ${passed} passed, ${failed} failed`; output.appendChild(summary);
// Also log to console for easy capture console.log(`[TEST RESULTS] ${passed} passed, ${failed} failed`); </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253/** * Bayan Chrome Extension — Patch Engine Tests * * Tests for HIGH-1 fix: applyAndRebase() * Run with: node extension/tests/test_patches.js * * Test scenarios: * 1. Shorter replacement (delta < 0) * 2. Longer replacement (delta > 0) * 3. Same-length replacement (delta = 0) * 4. Multiple sequential applies * 5. Apply first suggestion (edge case) * 6. Apply last suggestion (edge case) * 7. Dismiss (no rebase needed) * 8. Apply all patches */
// ── Load modules (Node.js — no DOM required) ──// These are global-scope scripts, so we eval themconst fs = require('fs');const path = require('path');
function loadModule(filename) { const code = fs.readFileSync(path.join(__dirname, '..', 'shared', filename), 'utf-8'); eval(code);}
// Load in dependency orderloadModule('config.js');loadModule('bayan-renderer.js');loadModule('bayan-ui.js');loadModule('bayan-patches.js');
// ── Test utilities ──let passed = 0;let failed = 0;
function assert(condition, message) { if (condition) { passed++; console.log(` ✅ ${message}`); } else { failed++; console.error(` ❌ ${message}`); }}
function assertEqual(actual, expected, message) { if (actual === expected) { passed++; console.log(` ✅ ${message}`); } else { failed++; console.error(` ❌ ${message}`); console.error(` Expected: "${expected}"`); console.error(` Actual: "${actual}"`); }}
// ══════════════════════════════════════════════════════════// Test data: Arabic text with 3 suggestions// ══════════════════════════════════════════════════════════//// Text: "أنا ذاهب الى البت والمدرسه"// 0123456789012345678901234567//// Suggestion A: "الى" → "إلى" (start:10, end:13) — same length (3→3, delta=0)// Suggestion B: "البت" → "البيت" (start:14, end:17) — longer (+1, delta=+1)// Suggestion C: "المدرسه" → "المدرسة" (start:19, end:26) — same length (7→7, delta=0)//
const TEXT = 'أنا ذاهب الى البت والمدرسه';
function makeSuggestions() { return [ { id: 'a', start: 10, end: 13, original: 'الى', correction: 'إلى', type: 'grammar' }, { id: 'b', start: 14, end: 17, original: 'البت', correction: 'البيت', type: 'spelling' }, { id: 'c', start: 19, end: 26, original: 'المدرسه', correction: 'المدرسة', type: 'spelling' }, ];}
// ══════════════════════════════════════════════════════════// TEST 1: Same-length replacement (delta = 0)// ══════════════════════════════════════════════════════════console.log('\n── TEST 1: Same-length replacement (delta = 0) ──');{ const suggestions = makeSuggestions(); const result = applyAndRebase(TEXT, suggestions[0], 'إلى', suggestions);
assertEqual(result.text, 'أنا ذاهب إلى البت والمدرسه', 'Text: "الى" → "إلى"'); assert(result.suggestions.length === 2, 'Removed applied suggestion (2 remaining)'); assertEqual(result.suggestions[0].start, 14, 'Suggestion B start unchanged (14)'); assertEqual(result.suggestions[0].end, 17, 'Suggestion B end unchanged (17)'); assertEqual(result.suggestions[1].start, 19, 'Suggestion C start unchanged (19)'); assertEqual(result.suggestions[1].end, 26, 'Suggestion C end unchanged (26)');}
// ══════════════════════════════════════════════════════════// TEST 2: Longer replacement (delta > 0)// ══════════════════════════════════════════════════════════console.log('\n── TEST 2: Longer replacement (delta > 0) ──');{ const suggestions = makeSuggestions(); // Apply B: "البت" (3 chars) → "البيت" (5 chars), delta = +2 const result = applyAndRebase(TEXT, suggestions[1], 'البيت', suggestions);
assertEqual(result.text, 'أنا ذاهب الى البيت والمدرسه', 'Text: "البت" → "البيت"'); assert(result.suggestions.length === 2, 'Removed applied suggestion (2 remaining)');
// A is BEFORE B — should NOT shift assertEqual(result.suggestions[0].start, 10, 'Suggestion A start unchanged (10)'); assertEqual(result.suggestions[0].end, 13, 'Suggestion A end unchanged (13)');
// C is AFTER B — should shift by +2 assertEqual(result.suggestions[1].start, 21, 'Suggestion C start shifted 19→21 (+2)'); assertEqual(result.suggestions[1].end, 28, 'Suggestion C end shifted 26→28 (+2)');
// Verify the shifted offsets are correct assertEqual(result.text.substring(result.suggestions[1].start, result.suggestions[1].end), 'المدرسه', 'Rebased offset C extracts correct text');}
// ══════════════════════════════════════════════════════════// TEST 3: Shorter replacement (delta < 0)// ══════════════════════════════════════════════════════════console.log('\n── TEST 3: Shorter replacement (delta < 0) ──');{ // Custom text for this test const text = 'هذا النصص خاطئ والكلمه خطأ'; // "النصص" (5) → "النص" (4), delta = -1 const suggestions = [ { id: 'x', start: 4, end: 9, original: 'النصص', correction: 'النص', type: 'spelling' }, { id: 'y', start: 17, end: 23, original: 'والكلمه', correction: 'والكلمة', type: 'spelling' }, ];
const result = applyAndRebase(text, suggestions[0], 'النص', suggestions);
assertEqual(result.text, 'هذا النص خاطئ والكلمه خطأ', 'Text: "النصص" → "النص"'); assert(result.suggestions.length === 1, '1 remaining'); assertEqual(result.suggestions[0].start, 16, 'Suggestion Y start shifted 17→16 (-1)'); assertEqual(result.suggestions[0].end, 22, 'Suggestion Y end shifted 23→22 (-1)'); assertEqual(result.text.substring(result.suggestions[0].start, result.suggestions[0].end), 'والكلمه', 'Rebased offset Y extracts correct text');}
// ══════════════════════════════════════════════════════════// TEST 4: Multiple sequential applies// ══════════════════════════════════════════════════════════console.log('\n── TEST 4: Multiple sequential applies ──');{ let text = TEXT; let suggestions = makeSuggestions();
// Apply A first (same-length) let r1 = applyAndRebase(text, suggestions[0], 'إلى', suggestions); text = r1.text; suggestions = r1.suggestions; assertEqual(text, 'أنا ذاهب إلى البت والمدرسه', 'After apply A'); assert(suggestions.length === 2, '2 remaining after A');
// Apply B (longer, +2) let r2 = applyAndRebase(text, suggestions[0], 'البيت', suggestions); text = r2.text; suggestions = r2.suggestions; assertEqual(text, 'أنا ذاهب إلى البيت والمدرسه', 'After apply B'); assert(suggestions.length === 1, '1 remaining after B');
// Apply C (same-length) — offsets should be correctly rebased let r3 = applyAndRebase(text, suggestions[0], 'المدرسة', suggestions); text = r3.text; suggestions = r3.suggestions; assertEqual(text, 'أنا ذاهب إلى البيت والمدرسة', 'After apply C — fully corrected'); assert(suggestions.length === 0, '0 remaining — all applied');
// Verify final text matches applyAllPatches const expectedFull = applyAllPatches(TEXT, makeSuggestions()); assertEqual(text, expectedFull, 'Sequential applies produce same result as applyAllPatches');}
// ══════════════════════════════════════════════════════════// TEST 5: Apply first suggestion (edge case)// ══════════════════════════════════════════════════════════console.log('\n── TEST 5: Apply first suggestion ──');{ const text = 'الخطاء في البداية ثم نص صحيح'; const suggestions = [ { id: 'f', start: 0, end: 6, original: 'الخطاء', correction: 'الخطأ', type: 'spelling' }, { id: 'g', start: 20, end: 23, original: 'ثم ', correction: 'ثمّ ', type: 'grammar' }, ];
const result = applyAndRebase(text, suggestions[0], 'الخطأ', suggestions); assertEqual(result.text.substring(0, 5), 'الخطأ', 'First word replaced correctly'); // delta = 5 - 6 = -1 assertEqual(result.suggestions[0].start, 19, 'Second suggestion shifted by -1'); assertEqual(result.suggestions[0].end, 22, 'Second suggestion end shifted by -1');}
// ══════════════════════════════════════════════════════════// TEST 6: Apply last suggestion (edge case)// ══════════════════════════════════════════���═══════════════console.log('\n── TEST 6: Apply last suggestion ──');{ const suggestions = makeSuggestions(); // Apply C (last one) — no suggestions after it to rebase const result = applyAndRebase(TEXT, suggestions[2], 'المدرسة', suggestions);
assertEqual(result.text, 'أنا ذاهب الى البت والمدرسة', 'Last suggestion applied'); assert(result.suggestions.length === 2, '2 remaining'); assertEqual(result.suggestions[0].start, 10, 'A unchanged (before C)'); assertEqual(result.suggestions[1].start, 14, 'B unchanged (before C)');}
// ══════════════════════════════════════════════════════════// TEST 7: Dismiss (keep original)// ══════════════════════════════════════════════════════════console.log('\n── TEST 7: Dismiss (removeSuggestion) ──');{ const suggestions = makeSuggestions(); const remaining = removeSuggestion(suggestions, 'b'); assert(remaining.length === 2, '2 remaining after dismiss'); assert(remaining.every(s => s.id !== 'b'), 'Dismissed suggestion removed'); // Offsets of remaining should be unchanged (no rebase on dismiss) assertEqual(remaining[0].start, 10, 'A unchanged'); assertEqual(remaining[1].start, 19, 'C unchanged');}
// ══════════════════════════════════════════════════════════// TEST 8: applyAllPatches// ══════════════════════════════════════════════════════════console.log('\n── TEST 8: applyAllPatches ──');{ const result = applyAllPatches(TEXT, makeSuggestions()); assertEqual(result, 'أنا ذاهب إلى البيت والمدرسة', 'All patches applied correctly');}
// ══════════════════════════════════════════════════════════// TEST 9: countByType// ══════════════════════════════════════════════════════════console.log('\n── TEST 9: countByType ──');{ const counts = countByType(makeSuggestions()); assertEqual(counts.spelling, 2, '2 spelling'); assertEqual(counts.grammar, 1, '1 grammar'); assertEqual(counts.punctuation, 0, '0 punctuation');}
// ══════════════════════════════════════════════════════════// Summary// ══════════════════════════════════════════════════════════console.log(`\n${'═'.repeat(50)}`);console.log(`Results: ${passed} passed, ${failed} failed`);console.log(`${'═'.repeat(50)}`);process.exit(failed > 0 ? 1 : 0);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172# Bayan Patch Engine Tests — PowerShell Runner# Evaluates the JavaScript test logic without Node.js
$passed = 0$failed = 0
function Assert-Equal($actual, $expected, $message) { if ($actual -eq $expected) { $script:passed++ Write-Host " ✅ $message" -ForegroundColor Green } else { $script:failed++ Write-Host " ❌ $message" -ForegroundColor Red Write-Host " Expected: `"$expected`"" -ForegroundColor DarkGray Write-Host " Actual: `"$actual`"" -ForegroundColor DarkGray }}
function Assert-True($condition, $message) { if ($condition) { $script:passed++ Write-Host " ✅ $message" -ForegroundColor Green } else { $script:failed++ Write-Host " ❌ $message" -ForegroundColor Red }}
# ── Simulate applyAndRebase in PowerShell ──function ApplyAndRebase($text, $applied, $replacement, $suggestions) { # Apply patch $newText = $text.Substring(0, $applied.start) + $replacement + $text.Substring($applied.end)
# Calculate delta $originalSpanLength = $applied.end - $applied.start $delta = $replacement.Length - $originalSpanLength
# Remove applied and rebase $rebased = @() foreach ($s in $suggestions) { if ($s.id -eq $applied.id) { continue } if ($s.start -ge $applied.end) { $rebased += @{ id = $s.id; start = $s.start + $delta; end = $s.end + $delta original = $s.original; correction = $s.correction; type = $s.type } } else { $rebased += $s } }
return @{ text = $newText; suggestions = $rebased }}
function ApplyAllPatches($text, $suggestions) { $sorted = $suggestions | Sort-Object { $_.start } -Descending $result = $text foreach ($s in $sorted) { $result = $result.Substring(0, $s.start) + $s.correction + $result.Substring($s.end) } return $result}
# ── Test Data ──$TEXT = 'أنا ذاهب الى البت والمدرسه'
function MakeSuggestions { return @( @{ id='a'; start=10; end=13; original='الى'; correction='إلى'; type='grammar' }, @{ id='b'; start=14; end=17; original='البت'; correction='البيت'; type='spelling' }, @{ id='c'; start=19; end=26; original='المدرسه'; correction='المدرسة'; type='spelling' } )}
# ══════════════════════════════════════════════════════════# TEST 1: Same-length replacement (delta = 0)# ══════════════════════════════════════════════════════════Write-Host "`n── TEST 1: Same-length replacement (delta = 0) ──" -ForegroundColor Cyan$suggestions = MakeSuggestions$result = ApplyAndRebase $TEXT $suggestions[0] 'إلى' $suggestionsAssert-Equal $result.text 'أنا ذاهب إلى البت والمدرسه' 'Text: الى → إلى'Assert-True ($result.suggestions.Count -eq 2) 'Removed applied suggestion (2 remaining)'Assert-Equal $result.suggestions[0].start 14 'Suggestion B start unchanged (14)'Assert-Equal $result.suggestions[0].end 17 'Suggestion B end unchanged (17)'Assert-Equal $result.suggestions[1].start 19 'Suggestion C start unchanged (19)'Assert-Equal $result.suggestions[1].end 26 'Suggestion C end unchanged (26)'
# ══════════════════════════════════════════════════════════# TEST 2: Longer replacement (delta > 0)# ══════════════════════════════════════════════════════════Write-Host "`n── TEST 2: Longer replacement (delta > 0) ──" -ForegroundColor Cyan$suggestions = MakeSuggestions$result = ApplyAndRebase $TEXT $suggestions[1] 'البيت' $suggestionsAssert-Equal $result.text 'أنا ذاهب الى البيت والمدرسه' 'Text: البت → البيت'Assert-True ($result.suggestions.Count -eq 2) 'Removed applied suggestion (2 remaining)'Assert-Equal $result.suggestions[0].start 10 'Suggestion A start unchanged (10)'Assert-Equal $result.suggestions[0].end 13 'Suggestion A end unchanged (13)'Assert-Equal $result.suggestions[1].start 21 'Suggestion C start shifted 19→21 (+2)'Assert-Equal $result.suggestions[1].end 28 'Suggestion C end shifted 26→28 (+2)'$extracted = $result.text.Substring($result.suggestions[1].start, $result.suggestions[1].end - $result.suggestions[1].start)Assert-Equal $extracted 'المدرسه' 'Rebased offset C extracts correct text'
# ══════════════════════════════════════════════════════════# TEST 3: Shorter replacement (delta < 0)# ══════════════════════════════════════════════════════════Write-Host "`n── TEST 3: Shorter replacement (delta < 0) ──" -ForegroundColor Cyan$text3 = 'هذا النصص خاطئ والكلمه خطأ'$sugs3 = @( @{ id='x'; start=4; end=9; original='النصص'; correction='النص'; type='spelling' }, @{ id='y'; start=17; end=23; original='والكلمه'; correction='والكلمة'; type='spelling' })$result = ApplyAndRebase $text3 $sugs3[0] 'النص' $sugs3Assert-Equal $result.text 'هذا النص خاطئ والكلمه خطأ' 'Text: النصص → النص'Assert-True ($result.suggestions.Count -eq 1) '1 remaining'Assert-Equal $result.suggestions[0].start 16 'Suggestion Y start shifted 17→16 (-1)'Assert-Equal $result.suggestions[0].end 22 'Suggestion Y end shifted 23→22 (-1)'$extracted = $result.text.Substring($result.suggestions[0].start, $result.suggestions[0].end - $result.suggestions[0].start)Assert-Equal $extracted 'والكلمه' 'Rebased offset Y extracts correct text'
# ══════════════════════════════════════════════════════════# TEST 4: Multiple sequential applies# ══════════════════════════════════════════════════════════Write-Host "`n── TEST 4: Multiple sequential applies ──" -ForegroundColor Cyan$text4 = $TEXT$sugs4 = MakeSuggestions$r1 = ApplyAndRebase $text4 $sugs4[0] 'إلى' $sugs4$text4 = $r1.text; $sugs4 = $r1.suggestionsAssert-Equal $text4 'أنا ذاهب إلى البت والمدرسه' 'After apply A'Assert-True ($sugs4.Count -eq 2) '2 remaining after A'
$r2 = ApplyAndRebase $text4 $sugs4[0] 'البيت' $sugs4$text4 = $r2.text; $sugs4 = $r2.suggestionsAssert-Equal $text4 'أنا ذاهب إلى البيت والمدرسه' 'After apply B'Assert-True ($sugs4.Count -eq 1) '1 remaining after B'
$r3 = ApplyAndRebase $text4 $sugs4[0] 'المدرسة' $sugs4$text4 = $r3.text; $sugs4 = $r3.suggestionsAssert-Equal $text4 'أنا ذاهب إلى البيت والمدرسة' 'After apply C — fully corrected'Assert-True ($sugs4.Count -eq 0) '0 remaining — all applied'
$expectedFull = ApplyAllPatches $TEXT (MakeSuggestions)Assert-Equal $text4 $expectedFull 'Sequential === applyAllPatches'
# ══════════════════════════════════════════════════════════# TEST 5: Apply last suggestion# ══════════════════════════════════════════════════════════Write-Host "`n── TEST 5: Apply last suggestion ──" -ForegroundColor Cyan$sugs5 = MakeSuggestions$result = ApplyAndRebase $TEXT $sugs5[2] 'المدرسة' $sugs5Assert-Equal $result.text 'أنا ذاهب الى البت والمدرسة' 'Last suggestion applied'Assert-True ($result.suggestions.Count -eq 2) '2 remaining'Assert-Equal $result.suggestions[0].start 10 'A unchanged (before C)'Assert-Equal $result.suggestions[1].start 14 'B unchanged (before C)'
# ══════════════════════════════════════════════════════════# TEST 6: applyAllPatches# ══════════════════════════════════════════════════════════Write-Host "`n── TEST 6: applyAllPatches ──" -ForegroundColor Cyan$resultAll = ApplyAllPatches $TEXT (MakeSuggestions)Assert-Equal $resultAll 'أنا ذاهب إلى البيت والمدرسة' 'All patches applied correctly'
# ══════════════════════════════════════════════════════════# Summary# ══════════════════════════════════════════════════════════Write-Host "`n$('═' * 50)"if ($failed -gt 0) { Write-Host "Results: $passed passed, $failed FAILED" -ForegroundColor Red exit 1} else { Write-Host "Results: $passed passed, $failed failed" -ForegroundColor Green exit 0}extension/IMPLEMENTATION_CHANGELOG.mdAdded+151
extension/_locales/ar/messages.jsonAdded+18
extension/_locales/en/messages.jsonAdded+18
extension/background.jsAdded+234
extension/content-inline.cssAdded+280
extension/content-inline.jsAdded+685
extension/content.jsAdded+11
extension/manifest.jsonAdded+56
extension/popup.cssAdded+769
extension/popup.htmlAdded+308
extension/popup.jsAdded+682
extension/shared/analysis-controller.jsAdded+146
extension/shared/bayan-api.jsAdded+133
extension/shared/bayan-patches.jsAdded+152
extension/shared/bayan-renderer.jsAdded+149
extension/shared/bayan-state.jsAdded+127
extension/shared/bayan-ui.jsAdded+99
extension/shared/config.jsAdded+17
extension/shared/constants.jsAdded+46
extension/shared/hash.jsAdded+17
extension/sidepanel/sidepanel.cssAdded+637
extension/sidepanel/sidepanel.htmlAdded+303
extension/sidepanel/sidepanel.jsAdded+709
extension/tests/api_response_tc2.jsonAdded+41
extension/tests/debug_offsets.ps1Added+14
extension/tests/test_api_real.ps1Added+80
extension/tests/test_e2e_real.htmlAdded+319
extension/tests/test_inline.htmlAdded+78
extension/tests/test_patches.htmlAdded+282
extension/tests/test_patches.jsAdded+253
extension/tests/test_patches.ps1Added+172