diff --git a/CHANGELOG.md b/CHANGELOG.md index ee22521..dddd355 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 2.30.1 — 2026-11-18 + +- Fix decorative image classification inside `
` and add client-side Google Translate adapter (#201): + - Remove `figure` and `[role='figure']` from blocking decorative image hiding in `isFunctionalOrMeaningfulImage()`, prioritize explicit decorative markers (`data-decorative`, `.decorative`, `.deco`, `role="presentation"|"none"`, `aria-hidden="true"`), expand `hideVideos` selectors to cover `[data-video]` / `.video-placeholder`, and apply active contrast palette tokens to `targetRoot`. + - Add and export `createGoogleTranslateAdapter()` (querying Google Translate after explicit consent with in-memory caching and clean offline fallback) and set it as the default provider in `TranslationController`. + - Update `TRANSLATION.md`, `API.md`, `CSP.md`, and `examples/next-app/next.config.mjs` to document optional `connect-src 'self' https://translate.googleapis.com`. + ## 2.30.0 — 2026-11-16 - UI, accessibility, modal, typography, and bug-fix improvements (#182, #183, #184, #185, #186, #187, #188, #189, #190, #191, #192, #193, #194, #195, #196, #197, #199): diff --git a/docs/API.md b/docs/API.md index e3f3d8d..b28a61e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -295,6 +295,7 @@ Opt-in research prototype controller enabling host application content translati - `extractTranslatableNodes(root: Element, maxNodes?: number): TranslatableNode[]`: Traverses DOM tree starting from root and collects translatable text nodes, strictly skipping sensitive elements. - `sanitizeTranslationOutput(raw: string): string`: Sanitizes translated strings, stripping control characters and null bytes. - `applyTranslations(nodes: TranslatableNode[], translations: string[]): () => void`: Safely assigns translated strings to text nodes via `textContent` and returns an idempotent restore callback. +- `createGoogleTranslateAdapter(options?: GoogleTranslateAdapterOptions): TranslationAdapter`: Default adapter for `` querying Google Translate (`translate.googleapis.com/translate_a/single`) after explicit consent, with caching and automatic offline fallback. - `createOfflineMockTranslationAdapter(options?): TranslationAdapter`: Creates a local offline mock translation adapter operating with zero network requests. - `translateHostContent(options): Promise`: Coordinates end-to-end translation, enforcing consent, provider language support, sensitive element exclusion, and DOM restoration. - `TRANSLATION_DISCLAIMER`: Constant string disclaimer emphasizing prototype status and zero official WCAG compliance claims. diff --git a/docs/CSP.md b/docs/CSP.md index df7fdc2..5527066 100644 --- a/docs/CSP.md +++ b/docs/CSP.md @@ -64,6 +64,7 @@ const cspHeader = ` style-src-attr 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; + connect-src 'self' https://translate.googleapis.com; object-src 'none'; base-uri 'self'; form-action 'self'; @@ -116,6 +117,7 @@ export function middleware(request: NextRequest) { style-src-attr 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; + connect-src 'self' https://translate.googleapis.com; base-uri 'self'; form-action 'self'; ` @@ -169,6 +171,7 @@ For Vite applications, configure CSP headers either through your production web style-src-attr 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; + connect-src 'self' https://translate.googleapis.com; " /> @@ -185,10 +188,10 @@ For Vite applications, configure CSP headers either through your production web ## 4. Verification Checklist -| Requirement | Directive | Why It Is Needed | -| :---------------------------- | :-------------------------------------------------- | :------------------------------------------------------------------------------------------------------- | -| **Widget UI Styles** | `style-src 'self'` (with static `style.css` import) | Renders the Clean light widget panel, trigger, and control cards | -| **Dynamic Host Effects** | `style-src-attr 'unsafe-inline'` | Applies runtime font-size, line-height, and filter adjustments to host elements | -| **Big High-Contrast Cursor** | `img-src 'self' data:` | Allows SVG data URI pointer rendering | -| **No External Font Requests** | `font-src 'self'` | The plugin does not load external web fonts; all font-legibility features use local and system fallbacks | -| **No Network Calls** | No special `connect-src` | All preferences, state persistence, and effects operate 100% locally on the client | +| Requirement | Directive | Why It Is Needed | +| :---------------------------- | :-------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Widget UI Styles** | `style-src 'self'` (with static `style.css` import) | Renders the Clean light widget panel, trigger, and control cards | +| **Dynamic Host Effects** | `style-src-attr 'unsafe-inline'` | Applies runtime font-size, line-height, and filter adjustments to host elements | +| **Big High-Contrast Cursor** | `img-src 'self' data:` | Allows SVG data URI pointer rendering | +| **No External Font Requests** | `font-src 'self'` | The plugin does not load external web fonts; all font-legibility features use local and system fallbacks | +| **No Network Calls** | No special `connect-src` (unless using `TranslationController`) | Core preferences, state persistence, and effects operate 100% locally; opt-in `TranslationController` (`createGoogleTranslateAdapter()`) connects to `https://translate.googleapis.com` only after explicit user consent (`connect-src 'self' https://translate.googleapis.com`), with automatic offline fallback if blocked | diff --git a/docs/TRANSLATION.md b/docs/TRANSLATION.md index b2642b5..902599a 100644 --- a/docs/TRANSLATION.md +++ b/docs/TRANSLATION.md @@ -8,12 +8,12 @@ The host-content translation adapter (**A11Y-409**) provides a decoupled, privac ### Strict Distinction from Widget Localization -| Dimension | Widget UI Localization (`docs/LOCALES.md`) | Host-Content Translation (`docs/TRANSLATION.md`) | -| :------------------- | :---------------------------------------------- | :----------------------------------------------------- | -| **Target Scope** | Widget buttons, labels, and dialog strings only | Arbitrary host document content (articles, headings) | -| **Network Requests** | **Zero** — 100% static bundled locale packs | **Zero by default** — opt-in custom adapter only | -| **Privacy Risk** | None (no host content read) | High (host text transmitted to provider if configured) | -| **User Consent** | Not required (local interface strings) | **Mandatory explicit consent** prior to transmission | +| Dimension | Widget UI Localization (`docs/LOCALES.md`) | Host-Content Translation (`docs/TRANSLATION.md`) | +| :------------------- | :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------- | +| **Target Scope** | Widget buttons, labels, and dialog strings only | Arbitrary host document content (articles, headings) | +| **Network Requests** | **Zero** — 100% static bundled locale packs | **Opt-in after consent** — `createGoogleTranslateAdapter()` (default on ``) or custom/offline adapter | +| **Privacy Risk** | None (no host content read) | High (host text transmitted to provider if configured) | +| **User Consent** | Not required (local interface strings) | **Mandatory explicit consent** prior to transmission | --- @@ -94,11 +94,11 @@ The engine automatically scans element tags, attributes, and ancestor trees (`is ### 3. Content Security Policy (CSP) -If a host application uses a remote translation API (e.g. Google Cloud, DeepL, LibreTranslate): +If a host application uses the default Google Translate adapter or a custom remote translation API (e.g. Google Cloud, DeepL, LibreTranslate): - The host's `connect-src` CSP directive must explicitly permit the provider endpoint: ```http - Content-Security-Policy: default-src 'self'; connect-src 'self' https://api.deepl.com; + Content-Security-Policy: default-src 'self'; connect-src 'self' https://translate.googleapis.com; ``` - If an on-device local model (e.g., Transformers.js via WebAssembly or browser native Translation API `ai.translator`) is used, no external `connect-src` is required, though `wasm-unsafe-eval` may be needed for WebAssembly execution. @@ -139,14 +139,22 @@ session.restore(); ## Example Custom Providers -### 1. Local Offline Mock (Default) +### 1. Google Translate Adapter (Default on ``) & Offline Fallback -Included for zero-network development and testing: +`` defaults to `createGoogleTranslateAdapter()`, which performs client-side Google Translate requests only after explicit user consent and automatically falls back to local offline lexicons if offline or blocked: ```typescript -import { createOfflineMockTranslationAdapter } from "accessibility-plugin-react"; +import { + createGoogleTranslateAdapter, + createOfflineMockTranslationAdapter, +} from "accessibility-plugin-react"; + +const googleAdapter = createGoogleTranslateAdapter({ + fallbackToOffline: true, +}); -const adapter = createOfflineMockTranslationAdapter({ +// Zero-network alternative for air-gapped development and testing: +const offlineAdapter = createOfflineMockTranslationAdapter({ prefix: "[ES]", supportedLanguages: ["es", "fr", "de", "si", "ta"], }); diff --git a/examples/next-app/next.config.mjs b/examples/next-app/next.config.mjs index 93946de..021a9de 100644 --- a/examples/next-app/next.config.mjs +++ b/examples/next-app/next.config.mjs @@ -6,6 +6,7 @@ const cspHeader = ` style-src-attr 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; + connect-src 'self' https://translate.googleapis.com; object-src 'none'; base-uri 'self'; form-action 'self'; diff --git a/package-lock.json b/package-lock.json index 2bc85cd..114f29c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "accessibility-plugin-react", - "version": "2.30.0", + "version": "2.30.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "accessibility-plugin-react", - "version": "2.30.0", + "version": "2.30.1", "license": "ISC", "devDependencies": { "@axe-core/playwright": "^4.13.0", diff --git a/package.json b/package.json index 82924a4..5a06f52 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "accessibility-plugin-react", - "version": "2.30.0", + "version": "2.30.1", "description": "A composable React display-preference widget with a clean light design, persistent settings and movable accessible controls.", "main": "dist/index.js", "module": "dist/index.mjs", diff --git a/src/core/effects.ts b/src/core/effects.ts index e77c74c..c4b6545 100644 --- a/src/core/effects.ts +++ b/src/core/effects.ts @@ -599,10 +599,10 @@ export function isFunctionalOrMeaningfulImage(el: Element): boolean { return true; } - // 3. Charts, graphs, diagrams, and figures + // 3. Charts, graphs, and diagrams if ( el.closest( - "[role='graphics-document'], [role='graphics-symbol'], [role='figure'], figure, [class*='chart' i], [id*='chart' i], [class*='graph' i], [id*='graph' i], [class*='diagram' i], [id*='diagram' i]", + "[role='graphics-document'], [role='graphics-symbol'], [class*='chart' i], [id*='chart' i], [class*='graph' i], [id*='graph' i], [class*='diagram' i], [id*='diagram' i]", ) || el.matches( "[role='graphics-document'], [role='graphics-symbol'], [aria-roledescription*='chart' i]", @@ -640,6 +640,35 @@ export function isFunctionalOrMeaningfulImage(el: Element): boolean { return true; } + // Explicit decorative markers override alt/aria-label/title attributes + const hasExplicitDecorativeMarker = (node: Element) => { + if ( + node.hasAttribute("data-decorative") && + node.getAttribute("data-decorative") !== "false" + ) { + return true; + } + if ( + node.classList.contains("decorative") || + node.classList.contains("deco") + ) { + return true; + } + const nodeRole = node.getAttribute("role"); + if (nodeRole === "presentation" || nodeRole === "none") { + return true; + } + return node.getAttribute("aria-hidden") === "true"; + }; + + if ( + hasExplicitDecorativeMarker(el) || + (el.parentElement?.matches("picture") && + hasExplicitDecorativeMarker(el.parentElement)) + ) { + return false; + } + // 7. Meaningful accessible names or semantic roles if (el.hasAttribute("alt")) { const alt = el.getAttribute("alt")?.trim(); @@ -711,7 +740,8 @@ export function isEligibleDecorativeImage(el: Element): boolean { // 4. Explicit decorative marker if ( - el.hasAttribute("data-decorative") || + (el.hasAttribute("data-decorative") && + el.getAttribute("data-decorative") !== "false") || el.classList.contains("decorative") || el.classList.contains("deco") ) { @@ -779,6 +809,35 @@ export function resolveEffectScope( return document.body ?? null; } +function resolveActiveContrastPalette(values: Record): { + activePalette: ContrastPalette | null; + fallbackColors: [string, string] | null; +} { + if (isForcedColorsActive()) { + return { activePalette: null, fallbackColors: null }; + } + const activeContrastKey = + values.contrastMode && + values.contrastMode !== "off" && + values.contrastMode !== "original" + ? String(values.contrastMode) + : values.contrast !== undefined && + values.contrast !== 0 && + values.contrast !== "0" && + values.contrast !== "off" && + values.contrast !== "original" + ? String(values.contrast) + : null; + + const activePalette = activeContrastKey + ? (CONTRAST_PALETTES[activeContrastKey] ?? null) + : null; + const fallbackColors = !activePalette + ? (palette[String(values.contrast)] ?? null) + : null; + return { activePalette, fallbackColors }; +} + function applyToElements( elements: HTMLElement[], values: Record, @@ -1035,23 +1094,8 @@ function applyToElements( } // Active contrast mode / palette - const activeContrastKey = - values.contrastMode && - values.contrastMode !== "off" && - values.contrastMode !== "original" - ? String(values.contrastMode) - : values.contrast !== undefined && - values.contrast !== 0 && - values.contrast !== "0" && - values.contrast !== "off" && - values.contrast !== "original" - ? String(values.contrast) - : null; - - const activePalette = - activeContrastKey && !isForcedColorsActive() - ? CONTRAST_PALETTES[activeContrastKey] - : null; + const { activePalette, fallbackColors } = + resolveActiveContrastPalette(values); if (activePalette) { for (const el of targetElements) { @@ -1114,14 +1158,13 @@ function applyToElements( if ( values.hideVideos && el.matches( - 'video, iframe[src*="youtube.com/embed/"], iframe[src*="youtube-nocookie.com/embed/"], iframe[src*="youtu.be/"], iframe[src*="player.vimeo.com/video/"], iframe[src*="player.twitch.tv/"], iframe[src*="dailymotion.com/embed/"], iframe[src*="loom.com/embed/"], iframe[src*="wistia."], iframe[data-src*="youtube"], iframe[data-src*="vimeo"], iframe[data-src*="twitch.tv"], iframe[data-src*="dailymotion"], iframe[data-src*="loom.com"]', + 'video, [data-video], .video-placeholder, iframe[src*="youtube.com/embed/"], iframe[src*="youtube-nocookie.com/embed/"], iframe[src*="youtu.be/"], iframe[src*="player.vimeo.com/video/"], iframe[src*="player.twitch.tv/"], iframe[src*="dailymotion.com/embed/"], iframe[src*="loom.com/embed/"], iframe[src*="wistia."], iframe[data-src*="youtube"], iframe[data-src*="vimeo"], iframe[data-src*="twitch.tv"], iframe[data-src*="dailymotion"], iframe[data-src*="loom.com"]', ) ) set(el, "visibility", "hidden"); - const colors = palette[String(values.contrast)]; - if (colors && !activePalette && !isForcedColorsActive()) { - set(el, "color", colors[0]); - set(el, "background-color", colors[1]); + if (fallbackColors) { + set(el, "color", fallbackColors[0]); + set(el, "background-color", fallbackColors[1]); } if ( values.linkHighlight && @@ -1242,6 +1285,21 @@ export function applyPageSession( } } + const rootContrast = resolveActiveContrastPalette(values); + if (targetRoot && !targetRoot.matches(EXCLUDED)) { + if (rootContrast.activePalette) { + set(targetRoot, "color", rootContrast.activePalette.text); + set( + targetRoot, + "background-color", + rootContrast.activePalette.background, + ); + } else if (rootContrast.fallbackColors) { + set(targetRoot, "color", rootContrast.fallbackColors[0]); + set(targetRoot, "background-color", rootContrast.fallbackColors[1]); + } + } + // Smart contrast research prototype: measured relative luminance assistance const smartContrastVal = values.smartContrast; if ( @@ -1773,7 +1831,9 @@ export function useBuiltinEffects( !record.target.closest( "[data-arap-ui], [data-arap-diagnostics], .arap-root", ) && - record.target.matches("img, picture, video, iframe") + record.target.matches( + "img, picture, video, [data-video], .video-placeholder, iframe", + ) ) { added.push(record.target); } diff --git a/src/core/translationAdapter.ts b/src/core/translationAdapter.ts index 78df45b..e290af7 100644 --- a/src/core/translationAdapter.ts +++ b/src/core/translationAdapter.ts @@ -780,6 +780,221 @@ export function createOfflineMockTranslationAdapter(options?: { }; } +export interface GoogleTranslateAdapterOptions { + endpoint?: string; + concurrency?: number; + fallbackToOffline?: boolean; + fetchImpl?: typeof fetch; +} + +const GOOGLE_TRANSLATE_DEFAULT_ENDPOINT = + "https://translate.googleapis.com/translate_a/single"; + +const GOOGLE_TRANSLATE_SUPPORTED_LANGUAGES = [ + "es", + "fr", + "de", + "si", + "ta", + "ja", + "zh", + "ar", + "hi", + "pt", + "ru", + "ko", + "it", + "nl", +]; + +const LETTER_OR_SCRIPT_PATTERN = /\p{L}/u; + +function parseGoogleTranslateResponse(data: unknown): string { + if (!Array.isArray(data) || !Array.isArray(data[0])) { + return ""; + } + const parts: string[] = []; + for (const segment of data[0]) { + if (Array.isArray(segment) && typeof segment[0] === "string") { + parts.push(segment[0]); + } + } + return parts.join(""); +} + +/** + * Creates a client-side Google Translate adapter using the CORS-enabled + * translate_a/single endpoint, with optional in-memory caching and offline fallback. + */ +export function createGoogleTranslateAdapter( + options?: GoogleTranslateAdapterOptions, +): TranslationAdapter { + const endpoint = options?.endpoint ?? GOOGLE_TRANSLATE_DEFAULT_ENDPOINT; + const concurrency = Math.max(1, options?.concurrency ?? 6); + const fallbackToOffline = options?.fallbackToOffline ?? true; + const resolvedFetch = + options?.fetchImpl ?? + (typeof fetch !== "undefined" ? fetch.bind(globalThis) : undefined); + const cache = new Map(); + + return { + id: "google-translate-adapter", + name: "Google Translate", + description: + "Client-side machine translation powered by Google Translate with automatic offline fallback.", + privacyPolicyUrl: "https://policies.google.com/privacy", + dataRetention: "transient", + dataResidency: "global", + supportedTargetLanguages: GOOGLE_TRANSLATE_SUPPORTED_LANGUAGES, + translate: async ( + request: TranslationRequest, + ): Promise => { + if (request.signal?.aborted) { + throw new TranslationError( + TRANSLATION_ERROR_CODES.ABORTED, + "Translation request was aborted.", + ); + } + + const sourceLang = (request.sourceLanguage || "auto") + .trim() + .toLowerCase(); + const baseTarget = request.targetLanguage + .trim() + .toLowerCase() + .split("-")[0]; + + const pendingKeys: string[] = []; + const seenKeys = new Set(); + + for (const raw of request.texts) { + const trimmed = raw.trim(); + if (!trimmed || !LETTER_OR_SCRIPT_PATTERN.test(trimmed)) { + continue; + } + const cacheKey = `${sourceLang}:${baseTarget}:${trimmed}`; + if (!cache.has(cacheKey) && !seenKeys.has(trimmed)) { + seenKeys.add(trimmed); + pendingKeys.push(trimmed); + } + } + + let cursor = 0; + const translateSingle = async (textKey: string): Promise => { + if (request.signal?.aborted) { + throw new TranslationError( + TRANSLATION_ERROR_CODES.ABORTED, + "Translation request was aborted.", + ); + } + + const cacheKey = `${sourceLang}:${baseTarget}:${textKey}`; + if (!resolvedFetch) { + if (!fallbackToOffline) { + throw new TranslationError( + TRANSLATION_ERROR_CODES.NETWORK_ERROR, + "Fetch API is not available for Google Translate requests.", + ); + } + cache.set( + cacheKey, + translateOfflineText(textKey, request.targetLanguage), + ); + return; + } + + const url = `${endpoint}?client=gtx&sl=${encodeURIComponent( + sourceLang, + )}&tl=${encodeURIComponent(baseTarget)}&dt=t&q=${encodeURIComponent( + textKey, + )}`; + + try { + const response = await resolvedFetch(url, { + method: "GET", + signal: request.signal, + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + const json: unknown = await response.json(); + const parsed = sanitizeTranslationOutput( + parseGoogleTranslateResponse(json), + ); + cache.set(cacheKey, parsed || textKey); + } catch (err: unknown) { + const isAbort = + request.signal?.aborted || + (err instanceof Error && err.name === "AbortError") || + (err instanceof TranslationError && + err.code === TRANSLATION_ERROR_CODES.ABORTED); + if (isAbort) { + throw new TranslationError( + TRANSLATION_ERROR_CODES.ABORTED, + "Translation request was aborted.", + err, + ); + } + if (!fallbackToOffline) { + const msg = err instanceof Error ? err.message : String(err); + throw new TranslationError( + TRANSLATION_ERROR_CODES.NETWORK_ERROR, + `Google Translate request failed: ${msg}`, + err, + ); + } + cache.set( + cacheKey, + translateOfflineText(textKey, request.targetLanguage), + ); + } + }; + + const workerCount = Math.min(concurrency, pendingKeys.length); + if (workerCount > 0) { + const workers = Array.from({ length: workerCount }, async () => { + while (cursor < pendingKeys.length) { + const nextIndex = cursor; + cursor += 1; + const key = pendingKeys[nextIndex]; + if (key !== undefined) { + await translateSingle(key); + } + } + }); + await Promise.all(workers); + } + + const translations: TranslatedItem[] = request.texts.map((raw) => { + const trimmed = raw.trim(); + if (!trimmed || !LETTER_OR_SCRIPT_PATTERN.test(trimmed)) { + return { + original: raw, + translated: raw, + detectedSourceLanguage: request.sourceLanguage || "en", + }; + } + const leading = raw.match(/^\s*/)?.[0] ?? ""; + const trailing = raw.match(/\s*$/)?.[0] ?? ""; + const cacheKey = `${sourceLang}:${baseTarget}:${trimmed}`; + const translatedCore = cache.get(cacheKey) ?? trimmed; + return { + original: raw, + translated: `${leading}${translatedCore}${trailing}`, + detectedSourceLanguage: request.sourceLanguage || "en", + }; + }); + + return { + translations, + providerId: "google-translate-adapter", + timestamp: Date.now(), + attribution: "Powered by Google Translate", + }; + }, + }; +} + /** * Coordinates end-to-end host content translation: * 1. Verifies user consent status (throws if unprompted, denied, or revoked). diff --git a/src/features/TranslationController.tsx b/src/features/TranslationController.tsx index fb9d8f3..0fad2fb 100644 --- a/src/features/TranslationController.tsx +++ b/src/features/TranslationController.tsx @@ -6,7 +6,7 @@ import { type TranslationConsentRecord, type TranslationSession, TRANSLATION_DISCLAIMER, - createOfflineMockTranslationAdapter, + createGoogleTranslateAdapter, translateHostContent, } from "../core/translationAdapter"; @@ -26,6 +26,13 @@ const DEFAULT_TARGET_LANGUAGES = [ { code: "ta", label: "Tamil (தமிழ்)" }, { code: "ja", label: "Japanese (日本語)" }, { code: "zh", label: "Chinese (中文)" }, + { code: "ar", label: "Arabic (العربية)" }, + { code: "hi", label: "Hindi (हिन्दी)" }, + { code: "pt", label: "Portuguese (Português)" }, + { code: "ru", label: "Russian (Русский)" }, + { code: "ko", label: "Korean (한국어)" }, + { code: "it", label: "Italian (Italiano)" }, + { code: "nl", label: "Dutch (Nederlands)" }, ]; export const TranslationController: React.FC = ({ @@ -38,7 +45,7 @@ export const TranslationController: React.FC = ({ const { value: isTranslationEnabled, setValue: setIsTranslationEnabled } = useAccessibility("translation", false); const [provider] = useState(() => { - return customProvider || createOfflineMockTranslationAdapter(); + return customProvider || createGoogleTranslateAdapter(); }); const [targetLang, setTargetLang] = useState(defaultTargetLanguage); diff --git a/src/index.ts b/src/index.ts index d96d950..6c00eba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -439,8 +439,10 @@ export { sanitizeTranslationOutput, applyTranslations, createOfflineMockTranslationAdapter, + createGoogleTranslateAdapter, translateHostContent, TranslationError, + type GoogleTranslateAdapterOptions, type TranslationAdapter, type TranslationRequest, type TranslationResponse, diff --git a/tests/browser/widget.spec.ts b/tests/browser/widget.spec.ts index 2902ff5..89f6eb7 100644 --- a/tests/browser/widget.spec.ts +++ b/tests/browser/widget.spec.ts @@ -1877,6 +1877,22 @@ test("voice navigation research prototype renders with prototype badge, commands test("host-content translation adapter architecture renders with consent prompt, translation, and restoration (A11Y-409)", async ({ page, }) => { + await page.route( + "https://translate.googleapis.com/translate_a/single*", + async (route) => { + const url = new URL(route.request().url()); + const q = url.searchParams.get("q") ?? ""; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify([ + [[`Traducido: ${q}`, q, null, null, 3]], + null, + "en", + ]), + }); + }, + ); await page.goto("http://127.0.0.1:7311/"); // Open widget @@ -1914,17 +1930,18 @@ test("host-content translation adapter architecture renders with consent prompt, // Trigger translation await translateBtn.click(); - // Sample paragraph should contain translated text from local mock adapter + // Sample paragraph should contain translated text without [TR] prefix const sample = page.locator("#sample"); - await expect(sample).toContainText("[TR]"); + await expect(sample).toContainText("Traducido:"); + await expect(sample).not.toContainText("[TR]"); // Restore original const restoreBtn = ctrl.getByRole("button", { name: "Restore Original" }); await expect(restoreBtn).toBeVisible(); await restoreBtn.click(); - // Sample paragraph should no longer contain [TR] - await expect(sample).not.toContainText("[TR]"); + // Sample paragraph should no longer contain translated text + await expect(sample).not.toContainText("Traducido:"); }); test("A11Y-501: full supported matrix verification - zoom reflow, forced-colors, and 44px touch targets", async ({ @@ -2105,6 +2122,22 @@ test("reading aid isolation against aggressive host CSS and higher modal z-index test("dictionary looks up 'voice' and Sinhala host translation skips widget UI (#187, #188)", async ({ page, }) => { + await page.route( + "https://translate.googleapis.com/translate_a/single*", + async (route) => { + const url = new URL(route.request().url()); + const q = url.searchParams.get("q") ?? ""; + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify([ + [[`පරිවර්තනය: ${q}`, q, null, null, 3]], + null, + "en", + ]), + }); + }, + ); await page.goto("/"); await page.getByLabel("Accessibility", { exact: true }).click(); @@ -2140,15 +2173,25 @@ test("dictionary looks up 'voice' and Sinhala host translation skips widget UI ( .getByRole("button", { name: "Grant Consent", exact: true }) .click(); await translationGroup.getByLabel(/Target Language/i).selectOption("si"); + const hostSample = page.locator("main p, #host p").first(); + const originalText = (await hostSample.textContent()) ?? ""; await translationGroup .getByRole("button", { name: "Translate Page" }) .click(); - const hostSample = page.locator("main p, #host p").first(); - await expect(hostSample).toContainText("[TR]"); + await expect(hostSample).toContainText(/[\u0D80-\u0DFF]/); + await expect(hostSample).not.toContainText("[TR]"); await expect( translationGroup.getByRole("button", { name: "Restore Original" }), ).toBeVisible(); + await expect( + page.getByRole("button", { name: "Reset All", exact: true }), + ).toBeVisible(); + + await translationGroup + .getByRole("button", { name: "Restore Original" }) + .click(); + await expect(hostSample).toHaveText(originalText); }); test("read-aloud mini-player 44px targets, form field id/name compliance, and 320x200 zoom layout (#185, #191, #192)", async ({ diff --git a/tests/decorativeImages.test.tsx b/tests/decorativeImages.test.tsx index cac9f81..b6d0319 100644 --- a/tests/decorativeImages.test.tsx +++ b/tests/decorativeImages.test.tsx @@ -417,4 +417,38 @@ describe("HideImagesController & HideDecorativeImagesController integration", () expect(ytEmbed.style.visibility).toBe("hidden"); expect(mapEmbed.style.visibility).toBe(""); }); + + it("hides empty-alt and data-decorative images wrapped inside
and restores on toggle off (#201)", () => { + const { host } = renderFixture(); + + const figure = document.createElement("figure"); + const emptyAltInFigure = document.createElement("img"); + emptyAltInFigure.setAttribute("alt", ""); + emptyAltInFigure.src = "banner.png"; + + const markedWithAltInFigure = document.createElement("img"); + markedWithAltInFigure.setAttribute("alt", "Calm shoreline"); + markedWithAltInFigure.setAttribute("data-decorative", "true"); + markedWithAltInFigure.src = "shoreline.png"; + + const meaningfulInFigure = document.createElement("img"); + meaningfulInFigure.setAttribute("alt", "Editorial figure"); + meaningfulInFigure.src = "editorial.png"; + + figure.append(emptyAltInFigure, markedWithAltInFigure, meaningfulInFigure); + host.appendChild(figure); + + const toggle = screen.getByRole("button", { name: "Hide Images" }); + fireEvent.click(toggle); + + expect(emptyAltInFigure.style.visibility).toBe("hidden"); + expect(markedWithAltInFigure.style.visibility).toBe("hidden"); + expect(meaningfulInFigure.style.visibility).toBe(""); + + fireEvent.click(toggle); + + expect(emptyAltInFigure.style.visibility).toBe(""); + expect(markedWithAltInFigure.style.visibility).toBe(""); + expect(meaningfulInFigure.style.visibility).toBe(""); + }); }); diff --git a/tests/translationAdapter.test.ts b/tests/translationAdapter.test.ts index e303958..bd93253 100644 --- a/tests/translationAdapter.test.ts +++ b/tests/translationAdapter.test.ts @@ -1,10 +1,11 @@ -import { describe, it, expect, beforeEach } from "vitest"; +import { describe, it, expect, beforeEach, vi } from "vitest"; import { isSensitiveElement, extractTranslatableNodes, sanitizeTranslationOutput, applyTranslations, createOfflineMockTranslationAdapter, + createGoogleTranslateAdapter, translateHostContent, TRANSLATION_ERROR_CODES, TranslationError, @@ -344,4 +345,93 @@ describe("A11Y-409: Host-Content Translation Adapter Architecture", () => { expect(hostHeading.textContent).toBe("Accessibility Plugin React"); }); }); + + describe("createGoogleTranslateAdapter", () => { + it("joins multi-segment Google Translate arrays without [TR] prefix and caches results", async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL) => { + const url = new URL(String(input)); + const q = url.searchParams.get("q") ?? ""; + const payload = [ + [ + [`Hola `, q, null, null, 3], + [`mundo`, q, null, null, 3], + ], + null, + "en", + ]; + return new Response(JSON.stringify(payload), { status: 200 }); + }); + + const adapter = createGoogleTranslateAdapter({ + fetchImpl: fetchMock as unknown as typeof fetch, + }); + + expect(adapter.id).toBe("google-translate-adapter"); + expect(adapter.name).toBe("Google Translate"); + + const first = await adapter.translate({ + texts: [" Hello world ", "Hello world"], + targetLanguage: "es", + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(first.translations[0].translated).toBe(" Hola mundo "); + expect(first.translations[1].translated).toBe("Hola mundo"); + expect(first.translations[0].translated).not.toContain("[TR]"); + + await adapter.translate({ + texts: ["Hello world"], + targetLanguage: "es", + }); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it("falls back to clean offline translation without [TR] when fetch fails and throws when fallback disabled", async () => { + const failingFetch = vi.fn(async () => { + throw new Error("Network down"); + }); + + const fallbackAdapter = createGoogleTranslateAdapter({ + fetchImpl: failingFetch as unknown as typeof fetch, + }); + + const res = await fallbackAdapter.translate({ + texts: ["Accessibility"], + targetLanguage: "si", + }); + expect(res.translations[0].translated).not.toContain("[TR]"); + expect(res.translations[0].translated).toMatch(/[\u0D80-\u0DFF]/); + + const strictAdapter = createGoogleTranslateAdapter({ + fetchImpl: failingFetch as unknown as typeof fetch, + fallbackToOffline: false, + }); + await expect( + strictAdapter.translate({ + texts: ["Accessibility"], + targetLanguage: "si", + }), + ).rejects.toThrow(TranslationError); + }); + + it("throws ABORTED when AbortSignal is already cancelled", async () => { + const adapter = createGoogleTranslateAdapter({ + fetchImpl: vi.fn() as unknown as typeof fetch, + }); + const controller = new AbortController(); + controller.abort(); + + try { + await adapter.translate({ + texts: ["Hello world"], + targetLanguage: "es", + signal: controller.signal, + }); + expect.unreachable("Expected abort error"); + } catch (err) { + expect((err as TranslationError).code).toBe( + TRANSLATION_ERROR_CODES.ABORTED, + ); + } + }); + }); }); diff --git a/tests/translationWidget.test.tsx b/tests/translationWidget.test.tsx index 42f0938..f3aad5d 100644 --- a/tests/translationWidget.test.tsx +++ b/tests/translationWidget.test.tsx @@ -191,4 +191,12 @@ describe("A11Y-409: TranslationController Widget Integration", () => { .querySelector(".arap-translation-status-banner"); expect(statusBanner?.textContent).toContain("Sinhala"); }); + + it("defaults to Google Translate adapter metadata in consent and provider details (#201)", () => { + renderWidget(); + const title = screen + .getByTestId("translation-controller") + .querySelector(".arap-provider-title"); + expect(title?.textContent).toContain("Adapter: Google Translate"); + }); });